fuels_core/codec/
abi_decoder.rs

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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
mod bounded_decoder;
mod decode_as_debug_str;

use crate::{
    codec::abi_decoder::{
        bounded_decoder::BoundedDecoder, decode_as_debug_str::decode_as_debug_str,
    },
    types::{errors::Result, param_types::ParamType, Token},
};

#[derive(Debug, Clone, Copy)]
pub struct DecoderConfig {
    /// Entering a struct, array, tuple, enum or vector increases the depth. Decoding will fail if
    /// the current depth becomes greater than `max_depth` configured here.
    pub max_depth: usize,
    /// Every decoded Token will increase the token count. Decoding will fail if the current
    /// token count becomes greater than `max_tokens` configured here.
    pub max_tokens: usize,
}

// ANCHOR: default_decoder_config
impl Default for DecoderConfig {
    fn default() -> Self {
        Self {
            max_depth: 45,
            max_tokens: 10_000,
        }
    }
}
// ANCHOR_END: default_decoder_config

#[derive(Default)]
pub struct ABIDecoder {
    pub config: DecoderConfig,
}

impl ABIDecoder {
    pub fn new(config: DecoderConfig) -> Self {
        Self { config }
    }

    /// Decodes `bytes` following the schema described in `param_type` into its respective `Token`.
    ///
    /// # Arguments
    ///
    /// * `param_type`: The `ParamType` of the type we expect is encoded
    ///                  inside `bytes`.
    /// * `bytes`:       The bytes to be used in the decoding process.
    /// # Examples
    ///
    /// ```
    /// use fuels_core::codec::ABIDecoder;
    /// use fuels_core::traits::Tokenizable;
    /// use fuels_core::types::param_types::ParamType;
    ///
    /// let decoder = ABIDecoder::default();
    ///
    /// let token = decoder.decode(&ParamType::U64,  &[0, 0, 0, 0, 0, 0, 0, 7]).unwrap();
    ///
    /// assert_eq!(u64::from_token(token).unwrap(), 7u64);
    /// ```
    pub fn decode(&self, param_type: &ParamType, bytes: &[u8]) -> Result<Token> {
        BoundedDecoder::new(self.config).decode(param_type, bytes)
    }

    /// Same as `decode` but decodes multiple `ParamType`s in one go.
    /// # Examples
    /// ```
    /// use fuels_core::codec::ABIDecoder;
    /// use fuels_core::types::param_types::ParamType;
    /// use fuels_core::types::Token;
    ///
    /// let decoder = ABIDecoder::default();
    /// let data: &[u8] = &[7, 8];
    ///
    /// let tokens = decoder.decode_multiple(&[ParamType::U8, ParamType::U8], &data).unwrap();
    ///
    /// assert_eq!(tokens, vec![Token::U8(7), Token::U8(8)]);
    /// ```
    pub fn decode_multiple(&self, param_types: &[ParamType], bytes: &[u8]) -> Result<Vec<Token>> {
        BoundedDecoder::new(self.config).decode_multiple(param_types, bytes)
    }

    /// Decodes `bytes` following the schema described in `param_type` into its respective debug
    /// string.
    ///
    /// # Arguments
    ///
    /// * `param_type`: The `ParamType` of the type we expect is encoded
    ///                  inside `bytes`.
    /// * `bytes`:       The bytes to be used in the decoding process.
    /// # Examples
    ///
    /// ```
    /// use fuels_core::codec::ABIDecoder;
    /// use fuels_core::types::param_types::ParamType;
    ///
    /// let decoder = ABIDecoder::default();
    ///
    /// let debug_string = decoder.decode_as_debug_str(&ParamType::U64,  &[0, 0, 0, 0, 0, 0, 0, 7]).unwrap();
    /// let expected_value = 7u64;
    ///
    /// assert_eq!(debug_string, format!("{expected_value}"));
    /// ```
    pub fn decode_as_debug_str(&self, param_type: &ParamType, bytes: &[u8]) -> Result<String> {
        let token = BoundedDecoder::new(self.config).decode(param_type, bytes)?;
        decode_as_debug_str(param_type, &token)
    }
}

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

    use ParamType::*;

    use super::*;
    use crate::{
        constants::WORD_SIZE,
        to_named,
        traits::Parameterize,
        types::{errors::Error, param_types::EnumVariants, StaticStringToken, U256},
    };

    #[test]
    fn decode_multiple_uint() -> Result<()> {
        let types = vec![
            ParamType::U8,
            ParamType::U16,
            ParamType::U32,
            ParamType::U64,
            ParamType::U128,
            ParamType::U256,
        ];

        let data = [
            255, // u8
            255, 255, // u16
            255, 255, 255, 255, // u32
            255, 255, 255, 255, 255, 255, 255, 255, // u64
            255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
            255, // u128
            255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
            255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // u256
        ];

        let decoded = ABIDecoder::default().decode_multiple(&types, &data)?;

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

        Ok(())
    }

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

        let decoded = ABIDecoder::default().decode_multiple(&types, &data)?;

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

        assert_eq!(decoded, expected);

        Ok(())
    }

    #[test]
    fn decode_b256() -> Result<()> {
        let data = [
            213, 87, 156, 70, 223, 204, 127, 24, 32, 112, 19, 230, 91, 68, 228, 203, 78, 44, 34,
            152, 244, 172, 69, 123, 168, 248, 39, 67, 243, 30, 147, 11,
        ];

        let decoded = ABIDecoder::default().decode(&ParamType::B256, &data)?;

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

        Ok(())
    }

    #[test]
    fn decode_string_array() -> Result<()> {
        let types = vec![ParamType::StringArray(23), ParamType::StringArray(5)];
        let data = [
            84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 102, 117, 108, 108, 32, 115, 101, 110,
            116, 101, 110, 99, 101, //This is a full sentence
            72, 101, 108, 108, 111, // Hello
        ];

        let decoded = ABIDecoder::default().decode_multiple(&types, &data)?;

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

        assert_eq!(decoded, expected);

        Ok(())
    }

    #[test]
    fn decode_string_slice() -> Result<()> {
        let data = [
            0, 0, 0, 0, 0, 0, 0, 23, // [length]
            84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 102, 117, 108, 108, 32, 115, 101, 110,
            116, 101, 110, 99, 101, //This is a full sentence
        ];

        let decoded = ABIDecoder::default().decode(&ParamType::StringSlice, &data)?;

        let expected = Token::StringSlice(StaticStringToken::new(
            "This is a full sentence".into(),
            None,
        ));

        assert_eq!(decoded, expected);

        Ok(())
    }

    #[test]
    fn decode_string() -> Result<()> {
        let data = [
            0, 0, 0, 0, 0, 0, 0, 23, // [length]
            84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 102, 117, 108, 108, 32, 115, 101, 110,
            116, 101, 110, 99, 101, //This is a full sentence
        ];

        let decoded = ABIDecoder::default().decode(&ParamType::String, &data)?;

        let expected = Token::String("This is a full sentence".to_string());

        assert_eq!(decoded, expected);

        Ok(())
    }

    #[test]
    fn decode_tuple() -> Result<()> {
        let param_type = ParamType::Tuple(vec![ParamType::U32, ParamType::Bool]);
        let data = [
            0, 0, 0, 255, //u32
            1,   //bool
        ];

        let result = ABIDecoder::default().decode(&param_type, &data)?;

        let expected = Token::Tuple(vec![Token::U32(255), Token::Bool(true)]);

        assert_eq!(result, expected);

        Ok(())
    }

    #[test]
    fn decode_array() -> Result<()> {
        let types = vec![ParamType::Array(Box::new(ParamType::U8), 2)];
        let data = [255, 42];

        let decoded = ABIDecoder::default().decode_multiple(&types, &data)?;

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

        Ok(())
    }

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

        let data = [1, 1];

        let param_type = ParamType::Struct {
            name: "".to_string(),
            fields: to_named(&[ParamType::U8, ParamType::Bool]),
            generics: vec![],
        };

        let decoded = ABIDecoder::default().decode(&param_type, &data)?;

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

        assert_eq!(decoded, expected);

        Ok(())
    }

    #[test]
    fn decode_bytes() -> Result<()> {
        let data = [0, 0, 0, 0, 0, 0, 0, 7, 255, 0, 1, 2, 3, 4, 5];

        let decoded = ABIDecoder::default().decode(&ParamType::Bytes, &data)?;

        let expected = Token::Bytes([255, 0, 1, 2, 3, 4, 5].to_vec());

        assert_eq!(decoded, expected);

        Ok(())
    }

    #[test]
    fn decode_raw_slice() -> Result<()> {
        let data = [0, 0, 0, 0, 0, 0, 0, 7, 255, 0, 1, 2, 3, 4, 5];

        let decoded = ABIDecoder::default().decode(&ParamType::RawSlice, &data)?;

        let expected = Token::RawSlice([255, 0, 1, 2, 3, 4, 5].to_vec());

        assert_eq!(decoded, expected);

        Ok(())
    }

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

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

        let data = [
            0, 0, 0, 0, 0, 0, 0, 0, // discriminant
            0, 0, 0, 42, // u32
        ];

        let decoded = ABIDecoder::default().decode_multiple(&types, &data)?;

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

        Ok(())
    }

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

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

        let data = [0, 10, 1, 1, 2];

        let decoded = ABIDecoder::default().decode(&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<()> {
        // struct Foo {
        //     x: u16,
        //     y: Bar,
        // }
        //
        // struct Bar {
        //     a: bool,
        //     b: u8[2],
        // }

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

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

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

        let types = [nested_struct, u8_arr, b256];

        let bytes = [
            0, 10, // u16
            1,  // bool
            1, 2, // array[u8;2]
            1, 2, // array[u8;2]
            213, 87, 156, 70, 223, 204, 127, 24, 32, 112, 19, 230, 91, 68, 228, 203, 78, 44, 34,
            152, 244, 172, 69, 123, 168, 248, 39, 67, 243, 30, 147, 11, // b256
        ];

        let decoded = ABIDecoder::default().decode_multiple(&types, &bytes)?;

        // 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([
            213, 87, 156, 70, 223, 204, 127, 24, 32, 112, 19, 230, 91, 68, 228, 203, 78, 44, 34,
            152, 244, 172, 69, 123, 168, 248, 39, 67, 243, 30, 147, 11,
        ]);

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

        assert_eq!(decoded, expected);

        Ok(())
    }

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

        let result = ABIDecoder::default().decode(&enum_w_only_units, &data)?;

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

        Ok(())
    }

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

        let result = ABIDecoder::default().decode(&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, Error::Other(str) if str.starts_with(expected_msg)));

        Ok(())
    }

    #[test]
    pub fn division_by_zero() {
        let param_type = Vec::<[u16; 0]>::param_type();
        let result = ABIDecoder::default().decode(&param_type, &[]);
        assert!(matches!(result, Err(Error::Codec(_))));
    }

    #[test]
    pub fn multiply_overflow_enum() {
        let result = ABIDecoder::default().decode(
            &Enum {
                name: "".to_string(),
                enum_variants: EnumVariants::new(to_named(&[
                    Array(Box::new(Array(Box::new(RawSlice), 8)), usize::MAX),
                    B256,
                    B256,
                    B256,
                    B256,
                    B256,
                    B256,
                    B256,
                    B256,
                    B256,
                    B256,
                ]))
                .unwrap(),
                generics: vec![U16],
            },
            &[],
        );

        assert!(matches!(result, Err(Error::Codec(_))));
    }

    #[test]
    pub fn multiply_overflow_arith() {
        let mut param_type: ParamType = U16;
        for _ in 0..50 {
            param_type = Array(Box::new(param_type), 8);
        }
        let result = ABIDecoder::default().decode(
            &Enum {
                name: "".to_string(),
                enum_variants: EnumVariants::new(to_named(&[param_type])).unwrap(),
                generics: vec![U16],
            },
            &[],
        );
        assert!(matches!(result, Err(Error::Codec(_))));
    }

    #[test]
    pub fn capacity_overflow() {
        let result = ABIDecoder::default().decode(
            &Array(Box::new(Array(Box::new(Tuple(vec![])), usize::MAX)), 1),
            &[],
        );
        assert!(matches!(result, Err(Error::Codec(_))));
    }

    #[test]
    pub fn stack_overflow() {
        let mut param_type: ParamType = U16;
        for _ in 0..13500 {
            param_type = Vector(Box::new(param_type));
        }
        let result = ABIDecoder::default().decode(&param_type, &[]);
        assert!(matches!(result, Err(Error::Codec(_))));
    }

    #[test]
    pub fn capacity_malloc() {
        let param_type = Array(Box::new(U8), usize::MAX);
        let result = ABIDecoder::default().decode(&param_type, &[]);
        assert!(matches!(result, Err(Error::Codec(_))));
    }

    #[test]
    fn max_depth_surpassed() {
        const MAX_DEPTH: usize = 2;
        let config = DecoderConfig {
            max_depth: MAX_DEPTH,
            ..Default::default()
        };
        let msg = format!("depth limit `{MAX_DEPTH}` reached while decoding. Try increasing it");
        // for each nested enum so that it may read the discriminant
        let data = [0; MAX_DEPTH * WORD_SIZE];

        [nested_struct, nested_enum, nested_tuple, nested_array]
            .iter()
            .map(|fun| fun(MAX_DEPTH + 1))
            .for_each(|param_type| {
                assert_decoding_failed_w_data(config, &param_type, &msg, &data);
            })
    }

    #[test]
    fn depth_is_not_reached() {
        const MAX_DEPTH: usize = 3;
        const ACTUAL_DEPTH: usize = MAX_DEPTH - 1;

        // enough data to decode 2*ACTUAL_DEPTH enums (discriminant + u8 = 2*WORD_SIZE)
        let data = [0; 2 * ACTUAL_DEPTH * (WORD_SIZE * 2)];
        let config = DecoderConfig {
            max_depth: MAX_DEPTH,
            ..Default::default()
        };

        [nested_struct, nested_enum, nested_tuple, nested_array]
            .into_iter()
            .map(|fun| fun(ACTUAL_DEPTH))
            .map(|param_type| {
                // Wrapping everything in a structure so that we may check whether the depth is
                // decremented after finishing every struct field.
                ParamType::Struct {
                    name: "".to_string(),
                    fields: to_named(&[param_type.clone(), param_type]),
                    generics: vec![],
                }
            })
            .for_each(|param_type| {
                ABIDecoder::new(config).decode(&param_type, &data).unwrap();
            })
    }

    #[test]
    fn too_many_tokens() {
        let config = DecoderConfig {
            max_tokens: 3,
            ..Default::default()
        };
        {
            let data = [0; 3 * WORD_SIZE];
            let inner_param_types = vec![ParamType::U64; 3];
            for param_type in [
                ParamType::Struct {
                    name: "".to_string(),
                    fields: to_named(&inner_param_types),
                    generics: vec![],
                },
                ParamType::Tuple(inner_param_types.clone()),
                ParamType::Array(Box::new(ParamType::U64), 3),
            ] {
                assert_decoding_failed_w_data(
                    config,
                    &param_type,
                    "token limit `3` reached while decoding. Try increasing it",
                    &data,
                );
            }
        }
        {
            let data = [0, 0, 0, 0, 0, 0, 0, 3, 1, 2, 3];

            assert_decoding_failed_w_data(
                config,
                &ParamType::Vector(Box::new(ParamType::U8)),
                "token limit `3` reached while decoding. Try increasing it",
                &data,
            );
        }
    }

    #[test]
    fn token_count_is_being_reset_between_decodings() {
        // given
        let config = DecoderConfig {
            max_tokens: 3,
            ..Default::default()
        };

        let param_type = ParamType::Array(Box::new(ParamType::StringArray(0)), 2);

        let decoder = ABIDecoder::new(config);
        decoder.decode(&param_type, &[]).unwrap();

        // when
        let result = decoder.decode(&param_type, &[]);

        // then
        result.expect("element count to be reset");
    }

    fn assert_decoding_failed_w_data(
        config: DecoderConfig,
        param_type: &ParamType,
        msg: &str,
        data: &[u8],
    ) {
        let decoder = ABIDecoder::new(config);

        let err = decoder.decode(param_type, data);

        let Err(Error::Codec(actual_msg)) = err else {
            panic!("expected a `Codec` error. Got: `{err:?}`");
        };

        assert_eq!(actual_msg, msg);
    }

    fn nested_struct(depth: usize) -> ParamType {
        let fields = if depth == 1 {
            vec![]
        } else {
            to_named(&[nested_struct(depth - 1)])
        };

        ParamType::Struct {
            name: "".to_string(),
            fields,
            generics: vec![],
        }
    }

    fn nested_enum(depth: usize) -> ParamType {
        let fields = if depth == 1 {
            to_named(&[ParamType::U8])
        } else {
            to_named(&[nested_enum(depth - 1)])
        };

        ParamType::Enum {
            name: "".to_string(),
            enum_variants: EnumVariants::new(fields).unwrap(),
            generics: vec![],
        }
    }

    fn nested_array(depth: usize) -> ParamType {
        let field = if depth == 1 {
            ParamType::U8
        } else {
            nested_array(depth - 1)
        };

        ParamType::Array(Box::new(field), 1)
    }

    fn nested_tuple(depth: usize) -> ParamType {
        let fields = if depth == 1 {
            vec![ParamType::U8]
        } else {
            vec![nested_tuple(depth - 1)]
        };

        ParamType::Tuple(fields)
    }
}