1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
use std::{convert::TryInto, str};

use fuel_types::bytes::padded_len_usize;
use fuels_types::{
    constants::WORD_SIZE,
    core::{unzip_param_types, StringToken, Token},
    enum_variants::EnumVariants,
    errors::CodecError,
    param_types::ParamType,
};

#[derive(Debug, Clone)]
struct DecodeResult {
    token: Token,
    bytes_read: usize,
}

pub struct ABIDecoder;

impl ABIDecoder {
    /// Decodes types described by `param_types` into their respective `Token`s
    /// using the data in `bytes` and `receipts`.
    ///
    /// # Arguments
    ///
    /// * `param_types`: The ParamType's of the types we expect are encoded
    ///                  inside `bytes` and `receipts`.
    /// * `bytes`:       The bytes to be used in the decoding process.
    /// # Examples
    ///
    /// ```
    /// use fuels_core::abi_decoder::ABIDecoder;
    /// use fuels_types::{core::Token, param_types::ParamType};
    ///
    /// let tokens = ABIDecoder::decode(&[ParamType::U8, ParamType::U8], &[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,2]).unwrap();
    ///
    /// assert_eq!(tokens, vec![Token::U8(1), Token::U8(2)])
    /// ```
    pub fn decode(param_types: &[ParamType], bytes: &[u8]) -> Result<Vec<Token>, CodecError> {
        let (tokens, _) = Self::decode_multiple(param_types, bytes)?;

        Ok(tokens)
    }

    /// The same as `decode` just for a single type. Used in most cases since
    /// contract functions can only return one type.
    pub fn decode_single(param_type: &ParamType, bytes: &[u8]) -> Result<Token, CodecError> {
        Ok(Self::decode_param(param_type, bytes)?.token)
    }

    fn decode_param(param_type: &ParamType, bytes: &[u8]) -> Result<DecodeResult, CodecError> {
        match param_type {
            ParamType::Unit => Self::decode_unit(bytes),
            ParamType::U8 => Self::decode_u8(bytes),
            ParamType::U16 => Self::decode_u16(bytes),
            ParamType::U32 => Self::decode_u32(bytes),
            ParamType::U64 => Self::decode_u64(bytes),
            ParamType::Bool => Self::decode_bool(bytes),
            ParamType::Byte => Self::decode_byte(bytes),
            ParamType::B256 => Self::decode_b256(bytes),
            ParamType::String(length) => Self::decode_string(bytes, *length),
            ParamType::Array(ref t, length) => Self::decode_array(t, bytes, *length),
            ParamType::Struct { fields, .. } => Self::decode_struct(fields, bytes),
            ParamType::Enum { variants, .. } => Self::decode_enum(bytes, variants),
            ParamType::Tuple(types) => Self::decode_tuple(types, bytes),
            ParamType::Vector(param_type) => Self::decode_vector(param_type, bytes),
        }
    }

    fn decode_vector(_param_type: &ParamType, _bytes: &[u8]) -> Result<DecodeResult, CodecError> {
        unimplemented!("Cannot decode Vectors until we get support from the compiler.")
    }

    fn decode_tuple(param_types: &[ParamType], bytes: &[u8]) -> Result<DecodeResult, CodecError> {
        let (tokens, bytes_read) = Self::decode_multiple(param_types, bytes)?;

        Ok(DecodeResult {
            token: Token::Tuple(tokens),
            bytes_read,
        })
    }

    fn decode_struct(
        param_types: &[(String, ParamType)],
        bytes: &[u8],
    ) -> Result<DecodeResult, CodecError> {
        let param_types = unzip_param_types(param_types);
        let (tokens, bytes_read) = Self::decode_multiple(&param_types, bytes)?;

        Ok(DecodeResult {
            token: Token::Struct(tokens),
            bytes_read,
        })
    }

    fn decode_multiple(
        param_types: &[ParamType],
        bytes: &[u8],
    ) -> Result<(Vec<Token>, usize), CodecError> {
        let mut results = vec![];

        let mut bytes_read = 0;

        for param_type in param_types {
            let res = Self::decode_param(param_type, skip(bytes, bytes_read)?)?;
            bytes_read += res.bytes_read;
            results.push(res.token);
        }

        Ok((results, bytes_read))
    }

    fn decode_array(
        param_type: &ParamType,
        bytes: &[u8],
        length: usize,
    ) -> Result<DecodeResult, CodecError> {
        let (tokens, bytes_read) = Self::decode_multiple(&vec![param_type.clone(); length], bytes)?;

        Ok(DecodeResult {
            token: Token::Array(tokens),
            bytes_read,
        })
    }

    fn decode_string(bytes: &[u8], length: usize) -> Result<DecodeResult, CodecError> {
        let encoded_len = padded_len_usize(length);
        let encoded_str = peek(bytes, encoded_len)?;

        let decoded = str::from_utf8(&encoded_str[..length])?;

        let result = DecodeResult {
            token: Token::String(StringToken::new(decoded.into(), length)),
            bytes_read: encoded_len,
        };

        Ok(result)
    }

    fn decode_b256(bytes: &[u8]) -> Result<DecodeResult, CodecError> {
        Ok(DecodeResult {
            token: Token::B256(*peek_fixed::<32>(bytes)?),
            bytes_read: 32,
        })
    }

    fn decode_byte(bytes: &[u8]) -> Result<DecodeResult, CodecError> {
        Ok(DecodeResult {
            token: Token::Byte(peek_u8(bytes)?),
            bytes_read: 8,
        })
    }

    fn decode_bool(bytes: &[u8]) -> Result<DecodeResult, CodecError> {
        // Grab last byte of the word and compare it to 0x00
        let b = peek_u8(bytes)? != 0u8;

        let result = DecodeResult {
            token: Token::Bool(b),
            bytes_read: 8,
        };

        Ok(result)
    }

    fn decode_u64(bytes: &[u8]) -> Result<DecodeResult, CodecError> {
        Ok(DecodeResult {
            token: Token::U64(peek_u64(bytes)?),
            bytes_read: 8,
        })
    }

    fn decode_u32(bytes: &[u8]) -> Result<DecodeResult, CodecError> {
        Ok(DecodeResult {
            token: Token::U32(peek_u32(bytes)?),
            bytes_read: 8,
        })
    }

    fn decode_u16(bytes: &[u8]) -> Result<DecodeResult, CodecError> {
        Ok(DecodeResult {
            token: Token::U16(peek_u16(bytes)?),
            bytes_read: 8,
        })
    }

    fn decode_u8(bytes: &[u8]) -> Result<DecodeResult, CodecError> {
        Ok(DecodeResult {
            token: Token::U8(peek_u8(bytes)?),
            bytes_read: 8,
        })
    }

    fn decode_unit(bytes: &[u8]) -> Result<DecodeResult, CodecError> {
        // We don't need the data, we're doing this purely as a bounds
        // check.
        peek_fixed::<WORD_SIZE>(bytes)?;
        Ok(DecodeResult {
            token: Token::Unit,
            bytes_read: WORD_SIZE,
        })
    }

    /// The encoding follows the ABI specs defined
    /// [here](https://github.com/FuelLabs/fuel-specs/blob/1be31f70c757d8390f74b9e1b3beb096620553eb/specs/protocol/abi.md)
    ///
    /// # Arguments
    ///
    /// * `data`: slice of encoded data on whose beginning we're expecting an encoded enum
    /// * `variants`: all types that this particular enum type could hold
    fn decode_enum(bytes: &[u8], variants: &EnumVariants) -> Result<DecodeResult, CodecError> {
        let enum_width = variants.compute_encoding_width_of_enum();

        let discriminant = peek_u32(bytes)? as u8;
        let (_, selected_variant) = variants.select_variant(discriminant)?;

        let words_to_skip = enum_width - selected_variant.compute_encoding_width();
        let enum_content_bytes = skip(bytes, words_to_skip * WORD_SIZE)?;
        let result = Self::decode_token_in_enum(enum_content_bytes, variants, selected_variant)?;

        let selector = Box::new((discriminant as u8, result.token, variants.clone()));
        Ok(DecodeResult {
            token: Token::Enum(selector),
            bytes_read: enum_width * WORD_SIZE,
        })
    }

    fn decode_token_in_enum(
        bytes: &[u8],
        variants: &EnumVariants,
        selected_variant: &ParamType,
    ) -> Result<DecodeResult, CodecError> {
        // Enums that contain only Units as variants have only their discriminant encoded.
        // Because of this we construct the Token::Unit rather than calling `decode_param`
        if variants.only_units_inside() {
            Ok(DecodeResult {
                token: Token::Unit,
                bytes_read: 0,
            })
        } else {
            Self::decode_param(selected_variant, bytes)
        }
    }
}

fn peek_u64(bytes: &[u8]) -> Result<u64, CodecError> {
    let slice = peek_fixed::<WORD_SIZE>(bytes)?;
    Ok(u64::from_be_bytes(*slice))
}

fn peek_u32(bytes: &[u8]) -> Result<u32, CodecError> {
    const BYTES: usize = std::mem::size_of::<u32>();

    let slice = peek_fixed::<WORD_SIZE>(bytes)?;
    let bytes = slice[WORD_SIZE - BYTES..]
        .try_into()
        .expect("peek_u32: You must use a slice containing exactly 4B.");
    Ok(u32::from_be_bytes(bytes))
}

fn peek_u16(bytes: &[u8]) -> Result<u16, CodecError> {
    const BYTES: usize = std::mem::size_of::<u16>();

    let slice = peek_fixed::<WORD_SIZE>(bytes)?;
    let bytes = slice[WORD_SIZE - BYTES..]
        .try_into()
        .expect("peek_u16: You must use a slice containing exactly 2B.");
    Ok(u16::from_be_bytes(bytes))
}

fn peek_u8(bytes: &[u8]) -> Result<u8, CodecError> {
    const BYTES: usize = std::mem::size_of::<u8>();

    let slice = peek_fixed::<WORD_SIZE>(bytes)?;
    let bytes = slice[WORD_SIZE - BYTES..]
        .try_into()
        .expect("peek_u8: You must use a slice containing exactly 1B.");
    Ok(u8::from_be_bytes(bytes))
}

fn peek_fixed<const LEN: usize>(data: &[u8]) -> Result<&[u8; LEN], CodecError> {
    let slice_w_correct_length = peek(data, LEN)?;
    Ok(<&[u8; LEN]>::try_from(slice_w_correct_length)
        .expect("peek(data,len) must return a slice of length `len` or error out"))
}

fn peek(data: &[u8], len: usize) -> Result<&[u8], CodecError> {
    if len > data.len() {
        Err(CodecError::InvalidData(format!(
            "tried to read {len} bytes from response but only had {} remaining!",
            data.len()
        )))
    } else {
        Ok(&data[..len])
    }
}

fn skip(slice: &[u8], num_bytes: usize) -> Result<&[u8], CodecError> {
    if num_bytes > slice.len() {
        Err(CodecError::InvalidData(format!(
            "tried to consume {num_bytes} bytes from response but only had {} remaining!",
            slice.len()
        )))
    } else {
        Ok(&slice[num_bytes..])
    }
}

#[cfg(test)]
mod tests {
    use std::vec;

    use fuels_test_helpers::generate_unused_field_names;
    use fuels_types::{enum_variants::EnumVariants, errors::Error};

    use super::*;

    #[test]
    fn decode_int() -> Result<(), Error> {
        let data = [0x0, 0x0, 0x0, 0x0, 0xff, 0xff, 0xff, 0xff];

        let decoded = ABIDecoder::decode_single(&ParamType::U32, &data)?;

        assert_eq!(decoded, Token::U32(u32::MAX));
        Ok(())
    }

    #[test]
    fn decode_multiple_int() -> Result<(), Error> {
        let types = vec![
            ParamType::U32,
            ParamType::U8,
            ParamType::U16,
            ParamType::U64,
        ];
        let data = [
            0x0, 0x0, 0x0, 0x0, 0xff, 0xff, 0xff, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xff,
            0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff,
        ];

        let decoded = ABIDecoder::decode(&types, &data)?;

        let expected = vec![
            Token::U32(u32::MAX),
            Token::U8(u8::MAX),
            Token::U16(u16::MAX),
            Token::U64(u64::MAX),
        ];
        assert_eq!(decoded, expected);
        Ok(())
    }

    #[test]
    fn decode_bool() -> Result<(), Error> {
        let types = vec![ParamType::Bool, ParamType::Bool];
        let data = [
            0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x01, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x00,
        ];

        let decoded = ABIDecoder::decode(&types, &data)?;

        let expected = vec![Token::Bool(true), Token::Bool(false)];

        assert_eq!(decoded, expected);
        Ok(())
    }

    #[test]
    fn decode_b256() -> Result<(), Error> {
        let data = [
            0xd5, 0x57, 0x9c, 0x46, 0xdf, 0xcc, 0x7f, 0x18, 0x20, 0x70, 0x13, 0xe6, 0x5b, 0x44,
            0xe4, 0xcb, 0x4e, 0x2c, 0x22, 0x98, 0xf4, 0xac, 0x45, 0x7b, 0xa8, 0xf8, 0x27, 0x43,
            0xf3, 0x1e, 0x93, 0xb,
        ];

        let decoded = ABIDecoder::decode_single(&ParamType::B256, &data)?;

        assert_eq!(decoded, Token::B256(data));
        Ok(())
    }

    #[test]
    fn decode_string() -> Result<(), Error> {
        let types = vec![ParamType::String(23), ParamType::String(5)];
        let data = [
            0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x66, 0x75, 0x6c, 0x6c,
            0x20, 0x73, 0x65, 0x6e, 0x74, 0x65, 0x6e, 0x63, 0x65, 0x00, 0x48, 0x65, 0x6c, 0x6c,
            0x6f, 0x0, 0x0, 0x0,
        ];

        let decoded = ABIDecoder::decode(&types, &data)?;

        let expected = vec![
            Token::String(StringToken::new("This is a full sentence".into(), 23)),
            Token::String(StringToken::new("Hello".into(), 5)),
        ];

        assert_eq!(decoded, expected);
        Ok(())
    }

    #[test]
    fn decode_array() -> Result<(), Error> {
        // Create a parameter type for u8[2].
        let types = vec![ParamType::Array(Box::new(ParamType::U8), 2)];
        let data = [
            0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2a,
        ];

        let decoded = ABIDecoder::decode(&types, &data)?;

        let expected = vec![Token::Array(vec![Token::U8(255), Token::U8(42)])];
        assert_eq!(decoded, expected);
        Ok(())
    }

    #[test]
    fn decode_struct() -> Result<(), Error> {
        // struct MyStruct {
        //     foo: u8,
        //     bar: bool,
        // }

        let data = [
            0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1,
        ];
        let param_type = ParamType::Struct {
            name: "".to_string(),
            fields: generate_unused_field_names(vec![ParamType::U8, ParamType::Bool]),
            generics: vec![],
        };

        let decoded = ABIDecoder::decode_single(&param_type, &data)?;

        let expected = Token::Struct(vec![Token::U8(1), Token::Bool(true)]);

        assert_eq!(decoded, expected);
        Ok(())
    }

    #[test]
    fn decode_enum() -> Result<(), Error> {
        // enum MyEnum {
        //     x: u32,
        //     y: bool,
        // }

        let inner_enum_types = EnumVariants::new(generate_unused_field_names(vec![
            ParamType::U32,
            ParamType::Bool,
        ]))?;
        let types = vec![ParamType::Enum {
            name: "".to_string(),
            variants: inner_enum_types.clone(),
            generics: vec![],
        }];

        // "0" discriminant and 42 enum value
        let data = [
            0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2a,
        ];

        let decoded = ABIDecoder::decode(&types, &data)?;

        let expected = vec![Token::Enum(Box::new((0, Token::U32(42), inner_enum_types)))];
        assert_eq!(decoded, expected);
        Ok(())
    }

    #[test]
    fn decoder_will_skip_enum_padding_and_decode_next_arg() -> Result<(), Error> {
        // struct MyStruct {
        //     par1: MyEnum,
        //     par2: u32
        // }

        // enum MyEnum {
        //     x: b256,
        //     y: u32,
        // }

        let inner_enum_types = EnumVariants::new(generate_unused_field_names(vec![
            ParamType::B256,
            ParamType::U32,
        ]))?;

        let struct_type = ParamType::Struct {
            name: "".to_string(),
            fields: generate_unused_field_names(vec![
                ParamType::Enum {
                    name: "".to_string(),
                    variants: inner_enum_types.clone(),
                    generics: vec![],
                },
                ParamType::U32,
            ]),
            generics: vec![],
        };

        let enum_discriminant_enc = vec![0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1];
        let enum_data_enc = vec![0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x30, 0x39];
        // this padding is due to the biggest variant of MyEnum being 3 WORDs bigger than the chosen variant
        let enum_padding_enc = vec![0x0; 3 * WORD_SIZE];
        let struct_par2_enc = vec![0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xD4, 0x31];
        let bytes: Vec<u8> = vec![
            enum_discriminant_enc,
            enum_padding_enc,
            enum_data_enc,
            struct_par2_enc,
        ]
        .into_iter()
        .flatten()
        .collect();

        let decoded = ABIDecoder::decode_single(&struct_type, &bytes)?;

        let expected = Token::Struct(vec![
            Token::Enum(Box::new((1, Token::U32(12345), inner_enum_types))),
            Token::U32(54321),
        ]);
        assert_eq!(decoded, expected);
        Ok(())
    }

    #[test]
    fn decode_nested_struct() -> Result<(), Error> {
        // struct Foo {
        //     x: u16,
        //     y: Bar,
        // }
        //
        // struct Bar {
        //     a: bool,
        //     b: u8[2],
        // }

        let nested_struct = ParamType::Struct {
            name: "".to_string(),
            fields: generate_unused_field_names(vec![
                ParamType::U16,
                ParamType::Struct {
                    name: "".to_string(),
                    fields: generate_unused_field_names(vec![
                        ParamType::Bool,
                        ParamType::Array(Box::new(ParamType::U8), 2),
                    ]),
                    generics: vec![],
                },
            ]),
            generics: vec![],
        };

        let data = [
            0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0,
            0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2,
        ];

        let decoded = ABIDecoder::decode_single(&nested_struct, &data)?;

        let my_nested_struct = vec![
            Token::U16(10),
            Token::Struct(vec![
                Token::Bool(true),
                Token::Array(vec![Token::U8(1), Token::U8(2)]),
            ]),
        ];

        assert_eq!(decoded, Token::Struct(my_nested_struct));
        Ok(())
    }

    #[test]
    fn decode_comprehensive() -> Result<(), Error> {
        // struct Foo {
        //     x: u16,
        //     y: Bar,
        // }
        //
        // struct Bar {
        //     a: bool,
        //     b: u8[2],
        // }

        // fn: long_function(Foo,u8[2],b256,str[23])

        // Parameters
        let nested_struct = ParamType::Struct {
            name: "".to_string(),
            fields: generate_unused_field_names(vec![
                ParamType::U16,
                ParamType::Struct {
                    name: "".to_string(),
                    fields: generate_unused_field_names(vec![
                        ParamType::Bool,
                        ParamType::Array(Box::new(ParamType::U8), 2),
                    ]),
                    generics: vec![],
                },
            ]),
            generics: vec![],
        };

        let u8_arr = ParamType::Array(Box::new(ParamType::U8), 2);
        let b256 = ParamType::B256;
        let s = ParamType::String(23);

        let types = [nested_struct, u8_arr, b256, s];

        let data = [
            0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xa, // foo.x == 10u16
            0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, // foo.y.a == true
            0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, // foo.b.0 == 1u8
            0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, // foo.b.1 == 2u8
            0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, // u8[2].0 == 1u8
            0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, // u8[2].0 == 2u8
            0xd5, 0x57, 0x9c, 0x46, 0xdf, 0xcc, 0x7f, 0x18, // b256
            0x20, 0x70, 0x13, 0xe6, 0x5b, 0x44, 0xe4, 0xcb, // b256
            0x4e, 0x2c, 0x22, 0x98, 0xf4, 0xac, 0x45, 0x7b, // b256
            0xa8, 0xf8, 0x27, 0x43, 0xf3, 0x1e, 0x93, 0xb, // b256
            0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, // str[23]
            0x61, 0x20, 0x66, 0x75, 0x6c, 0x6c, 0x20, 0x73, // str[23]
            0x65, 0x6e, 0x74, 0x65, 0x6e, 0x63, 0x65, 0x0, // str[23]
        ];

        let decoded = ABIDecoder::decode(&types, &data)?;

        // Expected tokens
        let foo = Token::Struct(vec![
            Token::U16(10),
            Token::Struct(vec![
                Token::Bool(true),
                Token::Array(vec![Token::U8(1), Token::U8(2)]),
            ]),
        ]);

        let u8_arr = Token::Array(vec![Token::U8(1), Token::U8(2)]);

        let b256 = Token::B256([
            0xd5, 0x57, 0x9c, 0x46, 0xdf, 0xcc, 0x7f, 0x18, 0x20, 0x70, 0x13, 0xe6, 0x5b, 0x44,
            0xe4, 0xcb, 0x4e, 0x2c, 0x22, 0x98, 0xf4, 0xac, 0x45, 0x7b, 0xa8, 0xf8, 0x27, 0x43,
            0xf3, 0x1e, 0x93, 0xb,
        ]);

        let s = Token::String(StringToken::new("This is a full sentence".into(), 23));

        let expected: Vec<Token> = vec![foo, u8_arr, b256, s];

        assert_eq!(decoded, expected);
        Ok(())
    }

    #[test]
    fn units_in_structs_are_decoded_as_one_word() -> Result<(), Error> {
        let data = [
            0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
        ];
        let struct_type = ParamType::Struct {
            name: "".to_string(),
            fields: generate_unused_field_names(vec![ParamType::Unit, ParamType::U64]),
            generics: vec![],
        };

        let actual = ABIDecoder::decode_single(&struct_type, &data)?;

        let expected = Token::Struct(vec![Token::Unit, Token::U64(u64::MAX)]);
        assert_eq!(actual, expected);
        Ok(())
    }

    #[test]
    fn enums_with_all_unit_variants_are_decoded_from_one_word() -> Result<(), Error> {
        let data = [0, 0, 0, 0, 0, 0, 0, 1];
        let variants = EnumVariants::new(generate_unused_field_names(vec![
            ParamType::Unit,
            ParamType::Unit,
        ]))?;
        let enum_w_only_units = ParamType::Enum {
            name: "".to_string(),
            variants: variants.clone(),
            generics: vec![],
        };

        let result = ABIDecoder::decode_single(&enum_w_only_units, &data)?;

        let expected_enum = Token::Enum(Box::new((1, Token::Unit, variants)));
        assert_eq!(result, expected_enum);
        Ok(())
    }

    #[test]
    fn out_of_bounds_discriminant_is_detected() -> Result<(), Error> {
        let data = [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2];
        let variants = EnumVariants::new(generate_unused_field_names(vec![ParamType::U32]))?;
        let enum_type = ParamType::Enum {
            name: "".to_string(),
            variants,
            generics: vec![],
        };

        let result = ABIDecoder::decode_single(&enum_type, &data);

        let error = result.expect_err("Should have resulted in an error");

        let expected_msg = "Discriminant '1' doesn't point to any variant: ";
        assert!(matches!(error, CodecError::InvalidData(str) if str.starts_with(expected_msg)));
        Ok(())
    }
}