serde-generate 0.34.1

Library to generate (de)serialization code in multiple languages
Documentation
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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
use crate::solidity_generation::{get_bytecode, get_registry_from_type};
use alloy_sol_types::sol;
use alloy_sol_types::SolCall as _;
use revm::{
    context::result::{ExecutionResult, Output},
    database::{CacheDB, EmptyDB},
    primitives::{Address, Bytes, TxKind, U256},
    Context, ExecuteCommitEvm, MainBuilder, MainContext,
};
use serde::{
    de::DeserializeOwned,
    {Deserialize, Serialize},
};
use serde_generate::{solidity, CodeGeneratorConfig};
use std::{fmt::Display, fs::File, io::Write};
use tempfile::tempdir;

fn nonce(database: &CacheDB<EmptyDB>, addr: &Address) -> u64 {
    database
        .cache
        .accounts
        .get(addr)
        .map_or(0, |info| info.info.nonce)
}

fn test_contract(bytecode: Bytes, encoded_args: Bytes) {
    let mut database = CacheDB::new(EmptyDB::default());
    let deployer = Address::ZERO;
    let contract_address = {
        let deploy_nonce = nonce(&database, &deployer);
        let result = Context::mainnet()
            .with_db(&mut database)
            .modify_cfg_chained(|cfg| {
                cfg.limit_contract_code_size = Some(usize::MAX);
            })
            .modify_tx_chained(|tx| {
                tx.caller = deployer;
                tx.nonce = deploy_nonce;
                tx.kind = TxKind::Create;
                tx.data = bytecode;
                tx.gas_limit = u64::MAX;
                tx.value = U256::ZERO;
            })
            .build_mainnet()
            .replay_commit()
            .unwrap();

        let ExecutionResult::Success { output, .. } = result else {
            panic!("The TxKind::Create execution failed");
        };
        let Output::Create(_, Some(contract_address)) = output else {
            panic!("Failure to create the contract");
        };
        contract_address
    };

    let call_nonce = nonce(&database, &deployer);
    let result = Context::mainnet()
        .with_db(&mut database)
        .modify_cfg_chained(|cfg| {
            cfg.limit_contract_code_size = Some(usize::MAX);
        })
        .modify_tx_chained(|tx| {
            tx.caller = deployer;
            tx.nonce = call_nonce;
            tx.kind = TxKind::Call(contract_address);
            tx.data = encoded_args;
            tx.gas_limit = u64::MAX;
            tx.value = U256::ZERO;
        })
        .build_mainnet()
        .replay_commit()
        .unwrap();

    let ExecutionResult::Success { .. } = result else {
        panic!("The TxKind::Call execution failed");
    };
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct TestVec<T> {
    pub vec: Vec<T>,
}

fn test_vector_serialization<T: Serialize + DeserializeOwned + Display>(
    t: TestVec<T>,
) -> anyhow::Result<()> {
    let registry = get_registry_from_type::<TestVec<T>>();
    let dir = tempdir().unwrap();
    let path = dir.path();

    // The generated code
    let test_library_path = path.join("Library.sol");
    {
        let mut test_library_file = File::create(&test_library_path)?;
        let name = "Library".to_string();
        let config = CodeGeneratorConfig::new(name);
        let generator = solidity::CodeGenerator::new(&config);
        generator.output(&mut test_library_file, &registry).unwrap();
    }

    // The test code
    let test_code_path = path.join("test_code.sol");
    {
        let mut test_code_file = File::create(&test_code_path)?;

        let len = t.vec.len();
        let first_val = &t.vec[0];
        writeln!(
            test_code_file,
            r#"/// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import "./Library.sol";

contract ExampleCode {{

    function test_deserialization(bytes calldata input) external {{
      Library.TestVec memory t = Library.bcs_deserialize_TestVec(input);
      require(t.vec.length == {len}, "The length is incorrect");
      require(t.vec[0] == {first_val}, "incorrect value");

      bytes memory input_rev = Library.bcs_serialize_TestVec(t);
      require(input.length == input_rev.length);
      for (uint256 i=0; i<input.length; i++) {{
        require(input[i] == input_rev[i]);
      }}
    }}

}}
"#
        )?;
    }

    // Compiling the code and reading it.
    let bytecode = get_bytecode(path, "test_code.sol", "ExampleCode")?;

    // Building the test entry
    let expected_input = bcs::to_bytes(&t).unwrap();

    // Building the input to the smart contract
    sol! {
      function test_deserialization(bytes calldata input);
    }
    let input = Bytes::copy_from_slice(&expected_input);
    let fct_args = test_deserializationCall { input };
    let fct_args = fct_args.abi_encode().into();

    test_contract(bytecode, fct_args);
    Ok(())
}

#[test]
fn test_vector_serialization_types() {
    let mut vec = vec![0_u16; 3];
    vec[0] = 42;
    vec[1] = 5;
    vec[2] = 360;
    let t = TestVec { vec };
    test_vector_serialization(t).unwrap();

    let mut vec = vec![0_u8; 2];
    vec[0] = 42;
    vec[1] = 5;
    let t = TestVec { vec };
    test_vector_serialization(t).unwrap();

    let mut vec = vec![0_u32; 2];
    vec[0] = 42;
    vec[1] = 5;
    let t = TestVec { vec };
    test_vector_serialization(t).unwrap();

    let mut vec = vec![0_i8; 2];
    vec[0] = -42;
    vec[1] = 76;
    let t = TestVec { vec };
    test_vector_serialization(t).unwrap();

    let mut vec = vec![0_i16; 2];
    vec[0] = -4200;
    vec[1] = 7600;
    let t = TestVec { vec };
    test_vector_serialization(t).unwrap();

    let mut vec = vec![0_i32; 2];
    vec[0] = -4200;
    vec[1] = 7600;
    let t = TestVec { vec };
    test_vector_serialization(t).unwrap();

    let mut vec = vec![0_i64; 140];
    vec[0] = -4200;
    vec[1] = 7600;
    let t = TestVec { vec };
    test_vector_serialization(t).unwrap();
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum SimpleEnumTestType {
    ChoiceA,
    ChoiceB,
    ChoiceC,
}

#[test]
fn test_simple_enum_serialization() -> anyhow::Result<()> {
    let registry = get_registry_from_type::<SimpleEnumTestType>();
    let dir = tempdir().unwrap();
    let path = dir.path();

    // The generated code
    let test_library_path = path.join("Library.sol");
    {
        let mut test_library_file = File::create(&test_library_path)?;
        let name = "Library".to_string();
        let config = CodeGeneratorConfig::new(name);
        let generator = solidity::CodeGenerator::new(&config);
        generator.output(&mut test_library_file, &registry).unwrap();
    }

    // The test code
    let test_code_path = path.join("test_code.sol");
    {
        let mut test_code_file = File::create(&test_code_path)?;

        writeln!(
            test_code_file,
            r#"/// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import "./Library.sol";

contract ExampleCode {{

    function test_deserialization(bytes calldata input) external {{
      require(input.length == 1);
      Library.SimpleEnumTestType t = Library.bcs_deserialize_SimpleEnumTestType(input);
      require(t == Library.SimpleEnumTestType.ChoiceB);

      bytes memory input_rev = Library.bcs_serialize_SimpleEnumTestType(t);
      require(input_rev.length == 1);
      require(input[0] == input_rev[0]);
    }}

}}
"#
        )?;
    }

    // Compiling the code and reading it.
    let bytecode = get_bytecode(path, "test_code.sol", "ExampleCode")?;

    // Building the test entry
    let t = SimpleEnumTestType::ChoiceB;
    let expected_input = bcs::to_bytes(&t).unwrap();

    // Building the input to the smart contract
    sol! {
      function test_deserialization(bytes calldata input);
    }
    let input = Bytes::copy_from_slice(&expected_input);
    let fct_args = test_deserializationCall { input };
    let fct_args = fct_args.abi_encode().into();

    test_contract(bytecode, fct_args);
    Ok(())
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct StructBoolString {
    a: bool,
    b: String,
}

#[test]
fn test_struct_bool_string() -> anyhow::Result<()> {
    let registry = get_registry_from_type::<StructBoolString>();
    let dir = tempdir().unwrap();
    let path = dir.path();

    // The generated code
    let test_library_path = path.join("Library.sol");
    {
        let mut test_library_file = File::create(&test_library_path)?;
        let name = "Library".to_string();
        let config = CodeGeneratorConfig::new(name);
        let generator = solidity::CodeGenerator::new(&config);
        generator.output(&mut test_library_file, &registry).unwrap();
    }

    // The test code
    let test_code_path = path.join("test_code.sol");
    {
        let mut test_code_file = File::create(&test_code_path)?;

        writeln!(
            test_code_file,
            r#"/// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import "./Library.sol";

contract ExampleCode {{

    function test_deserialization(bytes calldata input) external {{
      Library.StructBoolString memory t = Library.bcs_deserialize_StructBoolString(input);

      bytes memory input_rev = Library.bcs_serialize_StructBoolString(t);
      require(input.length == input_rev.length);
      for (uint256 i=0; i<input.length; i++) {{
        require(input[i] == input_rev[i]);
      }}
    }}

}}
"#
        )?;
    }

    // Compiling the code and reading it.
    let bytecode = get_bytecode(path, "test_code.sol", "ExampleCode")?;

    // Building the test entry
    let t = StructBoolString {
        a: false,
        b: "abc".to_string(),
    };
    let expected_input = bcs::to_bytes(&t).unwrap();

    // Building the input to the smart contract
    sol! {
      function test_deserialization(bytes calldata input);
    }
    let input = Bytes::copy_from_slice(&expected_input);
    let fct_args = test_deserializationCall { input };
    let fct_args = fct_args.abi_encode().into();

    test_contract(bytecode, fct_args);
    Ok(())
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum ComplexEnumTestType {
    ChoiceA,
    Name(String),
    Age(i32),
}

#[test]
fn test_complex_enum() -> anyhow::Result<()> {
    let registry = get_registry_from_type::<ComplexEnumTestType>();
    let dir = tempdir().unwrap();
    let path = dir.path();

    // The generated code
    let test_library_path = path.join("Library.sol");
    {
        let mut test_library_file = File::create(&test_library_path)?;
        let name = "Library".to_string();
        let config = CodeGeneratorConfig::new(name);
        let generator = solidity::CodeGenerator::new(&config);
        generator.output(&mut test_library_file, &registry).unwrap();
    }

    // The test code
    let test_code_path = path.join("test_code.sol");
    {
        let mut test_code_file = File::create(&test_code_path)?;

        writeln!(
            test_code_file,
            r#"/// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import "./Library.sol";

contract ExampleCode {{

    function test_deserialization(bytes calldata input) external {{
      Library.ComplexEnumTestType memory t = Library.bcs_deserialize_ComplexEnumTestType(input);

      bytes memory input_rev = Library.bcs_serialize_ComplexEnumTestType(t);
      require(input.length == input_rev.length);
      for (uint256 i=0; i<input.length; i++) {{
        require(input[i] == input_rev[i]);
      }}
    }}

}}
"#
        )?;
    }

    // Compiling the code and reading it.
    let bytecode = get_bytecode(path, "test_code.sol", "ExampleCode")?;

    // Building the test entry
    let t1 = ComplexEnumTestType::ChoiceA;
    let t2 = ComplexEnumTestType::Name("joe".to_string());
    let t3 = ComplexEnumTestType::Age(43);
    for t in [t1, t2, t3] {
        let expected_input = bcs::to_bytes(&t).unwrap();

        // Building the input to the smart contract
        sol! {
            function test_deserialization(bytes calldata input);
        }
        let input = Bytes::copy_from_slice(&expected_input);
        let fct_args = test_deserializationCall { input };
        let fct_args = fct_args.abi_encode().into();

        test_contract(bytecode.clone(), fct_args);
    }
    Ok(())
}

/// Regression test for ULEB128-encoded variant indices: an enum with >= 128
/// variants forces the discriminant to use more than one byte, exercising the
/// fix that made `choice` a `uint64` encoded/decoded via `bcs_serialize_len` /
/// `bcs_deserialize_offset_len` instead of a single `uint8` byte.
#[test]
fn test_enum_uleb128_variant_index() -> anyhow::Result<()> {
    use serde_reflection::{ContainerFormat, Format, Named, Registry, VariantFormat};
    use std::collections::BTreeMap;

    // 199 Unit variants + 1 NewType(u32) variant at index 199. The non-trivial
    // tail forces the complex (struct-backed) Enum codepath in the generator.
    let mut variants: BTreeMap<u32, Named<VariantFormat>> = BTreeMap::new();
    for i in 0..199u32 {
        variants.insert(
            i,
            Named {
                name: format!("V{i}"),
                value: VariantFormat::Unit,
            },
        );
    }
    variants.insert(
        199,
        Named {
            name: "WithPayload".into(),
            value: VariantFormat::NewType(Box::new(Format::U32)),
        },
    );

    let mut registry = Registry::new();
    registry.insert("BigEnum".into(), ContainerFormat::Enum(variants));

    let dir = tempdir().unwrap();
    let path = dir.path();

    let test_library_path = path.join("Library.sol");
    {
        let mut test_library_file = File::create(&test_library_path)?;
        let config = CodeGeneratorConfig::new("Library".to_string());
        let generator = solidity::CodeGenerator::new(&config);
        generator.output(&mut test_library_file, &registry).unwrap();
    }

    let test_code_path = path.join("test_code.sol");
    {
        let mut test_code_file = File::create(&test_code_path)?;
        writeln!(
            test_code_file,
            r#"/// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import "./Library.sol";

contract ExampleCode {{

    function test_round_trip(bytes calldata input, uint64 expected_choice) external {{
        Library.BigEnum memory t = Library.bcs_deserialize_BigEnum(input);
        require(t.choice == expected_choice, "wrong choice");
        bytes memory input_rev = Library.bcs_serialize_BigEnum(t);
        require(input.length == input_rev.length, "length mismatch");
        for (uint256 i=0; i<input.length; i++) {{
            require(input[i] == input_rev[i], "byte mismatch");
        }}
    }}

}}
"#
        )?;
    }

    let bytecode = get_bytecode(path, "test_code.sol", "ExampleCode")?;

    sol! {
        function test_round_trip(bytes calldata input, uint64 expected_choice);
    }

    // (encoded BCS bytes, expected variant index).
    // - 0:   single-byte ULEB128
    // - 127: largest single-byte ULEB128
    // - 128: smallest two-byte ULEB128 (exercises continuation)
    // - 199: two-byte ULEB128 + u32 payload (the NewType variant)
    let cases: Vec<(Vec<u8>, u64)> = vec![
        (vec![0x00], 0),
        (vec![0x7f], 127),
        (vec![0x80, 0x01], 128),
        (
            {
                let mut v = vec![0xc7, 0x01];
                v.extend_from_slice(&0xdead_beef_u32.to_le_bytes());
                v
            },
            199,
        ),
    ];

    for (input_bytes, expected_choice) in cases {
        let input = Bytes::copy_from_slice(&input_bytes);
        let fct_args = test_round_tripCall {
            input,
            expected_choice,
        };
        let fct_args = fct_args.abi_encode().into();
        test_contract(bytecode.clone(), fct_args);
    }

    Ok(())
}

/// Regression test for sparse Serde variant indices.
///
/// `ContainerFormat::Enum` is a `BTreeMap<u32, ...>`, so the variant indices
/// are not required to be contiguous `0..N-1`. The generator must preserve
/// each variant's original index in the BCS encoding (rather than re-numbering
/// them by position). This test checks dispatch, validation, and the
/// precomputed multi-byte ULEB128 discriminant for a NewType variant at a
/// sparse, multi-byte index.
#[test]
fn test_enum_sparse_variant_indices() -> anyhow::Result<()> {
    use serde_reflection::{ContainerFormat, Format, Named, Registry, VariantFormat};
    use std::collections::BTreeMap;

    let mut variants: BTreeMap<u32, Named<VariantFormat>> = BTreeMap::new();
    variants.insert(
        0,
        Named {
            name: "Zero".into(),
            value: VariantFormat::Unit,
        },
    );
    variants.insert(
        5,
        Named {
            name: "Five".into(),
            value: VariantFormat::Unit,
        },
    );
    variants.insert(
        128,
        Named {
            name: "OneTwentyEight".into(),
            value: VariantFormat::Unit,
        },
    );
    variants.insert(
        300,
        Named {
            name: "WithPayload".into(),
            value: VariantFormat::NewType(Box::new(Format::U32)),
        },
    );

    let mut registry = Registry::new();
    registry.insert("Sparse".into(), ContainerFormat::Enum(variants));

    let dir = tempdir().unwrap();
    let path = dir.path();

    let test_library_path = path.join("Library.sol");
    {
        let mut test_library_file = File::create(&test_library_path)?;
        let config = CodeGeneratorConfig::new("Library".to_string());
        let generator = solidity::CodeGenerator::new(&config);
        generator.output(&mut test_library_file, &registry).unwrap();
    }

    // Spot-check the generated source: discriminant 300 = ULEB128 0xac 0x02.
    let generated = std::fs::read_to_string(&test_library_path)?;
    assert!(
        generated.contains(r#"hex"ac02""#),
        "generator should embed the precomputed ULEB128 for index 300 (0xac 0x02):\n{generated}"
    );
    // Index 5 collapses to a single byte 0x05.
    assert!(
        generated.contains(r#"hex"05""#),
        "generator should embed the precomputed ULEB128 for index 5 (0x05):\n{generated}"
    );
    // The deserializer must validate against the actual sparse index set,
    // not `choice < N`.
    assert!(
        generated.contains("choice == 0 || choice == 5 || choice == 128 || choice == 300"),
        "deserializer should validate against the sparse index set:\n{generated}"
    );

    let test_code_path = path.join("test_code.sol");
    {
        let mut test_code_file = File::create(&test_code_path)?;
        writeln!(
            test_code_file,
            r#"/// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import "./Library.sol";

contract ExampleCode {{

    function test_round_trip(bytes calldata input, uint64 expected_choice) external {{
        Library.Sparse memory t = Library.bcs_deserialize_Sparse(input);
        require(t.choice == expected_choice, "wrong choice");
        bytes memory input_rev = Library.bcs_serialize_Sparse(t);
        require(input.length == input_rev.length, "length mismatch");
        for (uint256 i=0; i<input.length; i++) {{
            require(input[i] == input_rev[i], "byte mismatch");
        }}
    }}

}}
"#
        )?;
    }

    let bytecode = get_bytecode(path, "test_code.sol", "ExampleCode")?;

    sol! {
        function test_round_trip(bytes calldata input, uint64 expected_choice);
    }

    // (encoded BCS bytes, expected variant index).
    let cases: Vec<(Vec<u8>, u64)> = vec![
        // index 0   — single-byte ULEB128
        (vec![0x00], 0),
        // index 5   — single-byte ULEB128, sparse
        (vec![0x05], 5),
        // index 128 — first two-byte ULEB128, sparse
        (vec![0x80, 0x01], 128),
        // index 300 — two-byte ULEB128 + u32 payload
        (
            {
                let mut v = vec![0xac, 0x02];
                v.extend_from_slice(&0xdead_beef_u32.to_le_bytes());
                v
            },
            300,
        ),
    ];

    for (input_bytes, expected_choice) in cases {
        let input = Bytes::copy_from_slice(&input_bytes);
        let fct_args = test_round_tripCall {
            input,
            expected_choice,
        };
        let fct_args = fct_args.abi_encode().into();
        test_contract(bytecode.clone(), fct_args);
    }

    Ok(())
}

/// Regression test for the trailing-comma bug in the complex-Enum codegen.
///
/// When an enum reaches the struct-backed `Enum` path with *no* payload-bearing
/// variants, the generated struct has only the `choice` field. The case
/// constructors and the deserializer return statement used to hardcode a comma
/// after `choice`, producing invalid Solidity like `Foo(uint64(0), )`.
///
/// Two shapes hit this path:
///   - sparse all-Unit enums (sparse indices disqualify SimpleEnum);
///   - contiguous all-Unit enums with >256 variants (over the Solidity-enum cap).
///
/// This test exercises the sparse case; the fix covers both.
#[test]
fn test_enum_sparse_all_unit() -> anyhow::Result<()> {
    use serde_reflection::{ContainerFormat, Named, Registry, VariantFormat};
    use std::collections::BTreeMap;

    let mut variants: BTreeMap<u32, Named<VariantFormat>> = BTreeMap::new();
    for &(idx, name) in &[(0u32, "Zero"), (5, "Five"), (128, "OneTwentyEight")] {
        variants.insert(
            idx,
            Named {
                name: name.into(),
                value: VariantFormat::Unit,
            },
        );
    }

    let mut registry = Registry::new();
    registry.insert("AllUnitSparse".into(), ContainerFormat::Enum(variants));

    let dir = tempdir().unwrap();
    let path = dir.path();

    let test_library_path = path.join("Library.sol");
    {
        let mut test_library_file = File::create(&test_library_path)?;
        let config = CodeGeneratorConfig::new("Library".to_string());
        let generator = solidity::CodeGenerator::new(&config);
        generator.output(&mut test_library_file, &registry).unwrap();
    }

    // The bug manifests as `Foo(..., )` in the generated source; assert it
    // never appears so a future regression fails at the unit-test layer
    // before we even invoke solc.
    let generated = std::fs::read_to_string(&test_library_path)?;
    assert!(
        !generated.contains(", )"),
        "generator emitted a trailing comma in a struct constructor:\n{generated}"
    );

    let test_code_path = path.join("test_code.sol");
    {
        let mut test_code_file = File::create(&test_code_path)?;
        writeln!(
            test_code_file,
            r#"/// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import "./Library.sol";

contract ExampleCode {{

    function test_round_trip(bytes calldata input, uint64 expected_choice) external {{
        Library.AllUnitSparse memory t = Library.bcs_deserialize_AllUnitSparse(input);
        require(t.choice == expected_choice, "wrong choice");
        bytes memory input_rev = Library.bcs_serialize_AllUnitSparse(t);
        require(input.length == input_rev.length, "length mismatch");
        for (uint256 i=0; i<input.length; i++) {{
            require(input[i] == input_rev[i], "byte mismatch");
        }}
    }}

}}
"#
        )?;
    }

    let bytecode = get_bytecode(path, "test_code.sol", "ExampleCode")?;

    sol! {
        function test_round_trip(bytes calldata input, uint64 expected_choice);
    }

    let cases: Vec<(Vec<u8>, u64)> =
        vec![(vec![0x00], 0), (vec![0x05], 5), (vec![0x80, 0x01], 128)];

    for (input_bytes, expected_choice) in cases {
        let input = Bytes::copy_from_slice(&input_bytes);
        let fct_args = test_round_tripCall {
            input,
            expected_choice,
        };
        let fct_args = fct_args.abi_encode().into();
        test_contract(bytecode.clone(), fct_args);
    }

    Ok(())
}

/// Regression test for the SimpleEnum (native Solidity `enum`) path with
/// variant indices >= 128, which require multi-byte ULEB128.
///
/// The previous SimpleEnum codec encoded the choice as a single byte
/// (`abi.encodePacked(input)` / `uint8(input[pos])`), which silently produced
/// wrong BCS for indices >= 128. The fix routes SimpleEnum through the same
/// ULEB128 helper as the complex Enum path; this test pins that down.
#[test]
fn test_simple_enum_uleb128_variant_index() -> anyhow::Result<()> {
    use serde_reflection::{ContainerFormat, Named, Registry, VariantFormat};
    use std::collections::BTreeMap;

    // 200 contiguous Unit variants → routes through SimpleEnum (is_trivial &&
    // is_contiguous && len <= 256).
    let mut variants: BTreeMap<u32, Named<VariantFormat>> = BTreeMap::new();
    for i in 0..200u32 {
        variants.insert(
            i,
            Named {
                name: format!("V{i}"),
                value: VariantFormat::Unit,
            },
        );
    }

    let mut registry = Registry::new();
    registry.insert("BigSimple".into(), ContainerFormat::Enum(variants));

    let dir = tempdir().unwrap();
    let path = dir.path();

    let test_library_path = path.join("Library.sol");
    {
        let mut test_library_file = File::create(&test_library_path)?;
        let config = CodeGeneratorConfig::new("Library".to_string());
        let generator = solidity::CodeGenerator::new(&config);
        generator.output(&mut test_library_file, &registry).unwrap();
    }

    // Confirm the SimpleEnum (native `enum`) path was selected and that the
    // codec goes through ULEB128 rather than a single byte.
    let generated = std::fs::read_to_string(&test_library_path)?;
    assert!(
        generated.contains("enum BigSimple {"),
        "expected SimpleEnum path (native enum) for 200 trivial variants:\n{generated}"
    );
    assert!(
        generated.contains("return bcs_serialize_uleb128(uint256(input));"),
        "SimpleEnum serializer should go through bcs_serialize_uleb128:\n{generated}"
    );

    let test_code_path = path.join("test_code.sol");
    {
        let mut test_code_file = File::create(&test_code_path)?;
        writeln!(
            test_code_file,
            r#"/// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import "./Library.sol";

contract ExampleCode {{

    function test_round_trip(bytes calldata input, uint8 expected_choice) external {{
        Library.BigSimple t = Library.bcs_deserialize_BigSimple(input);
        require(uint8(t) == expected_choice, "wrong choice");
        bytes memory input_rev = Library.bcs_serialize_BigSimple(t);
        require(input.length == input_rev.length, "length mismatch");
        for (uint256 i=0; i<input.length; i++) {{
            require(input[i] == input_rev[i], "byte mismatch");
        }}
    }}

}}
"#
        )?;
    }

    let bytecode = get_bytecode(path, "test_code.sol", "ExampleCode")?;

    sol! {
        function test_round_trip(bytes calldata input, uint8 expected_choice);
    }

    // Exercise the single-byte (idx < 128) and multi-byte (idx >= 128) ULEB128
    // paths. 128 is the smallest multi-byte index; 199 is the largest variant.
    let cases: Vec<(Vec<u8>, u8)> = vec![
        (vec![0x00], 0),
        (vec![0x7f], 127),
        (vec![0x80, 0x01], 128),
        (vec![0xc7, 0x01], 199),
    ];

    for (input_bytes, expected_choice) in cases {
        let input = Bytes::copy_from_slice(&input_bytes);
        let fct_args = test_round_tripCall {
            input,
            expected_choice,
        };
        let fct_args = fct_args.abi_encode().into();
        test_contract(bytecode.clone(), fct_args);
    }

    Ok(())
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct ComplexStruct {
    v1: [u8; 32],
    v2: [u8; 20],
    v3: [u16; 10],
}

#[test]
fn test_bytes32_and_related() -> anyhow::Result<()> {
    let registry = get_registry_from_type::<ComplexStruct>();
    let dir = tempdir().unwrap();
    let path = dir.path();

    // The library code
    let test_library_path = path.join("Library.sol");
    {
        let mut test_library_file = File::create(&test_library_path)?;
        let name = "Library".to_string();
        let config = CodeGeneratorConfig::new(name);
        let generator = solidity::CodeGenerator::new(&config);
        generator.output(&mut test_library_file, &registry).unwrap();
    }

    // The test code
    let test_code_path = path.join("test_code.sol");
    {
        let mut test_code_file = File::create(&test_code_path)?;

        writeln!(
            test_code_file,
            r#"/// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import "./Library.sol";

contract ExampleCode {{

    function get_bytes32() internal returns (bytes32) {{
        bytes memory vect;
        for (uint8 i=0; i<32; i++) {{
            vect = abi.encodePacked(vect, i);
        }}
        bytes32 dest;
        assembly {{
            dest := mload(add(vect, 0x20))
        }}
        return dest;
    }}

    function get_bytes20() internal returns (bytes20) {{
        bytes memory vect;
        for (uint8 i=0; i<20; i++) {{
            vect = abi.encodePacked(vect, i);
        }}
        bytes20 dest;
        assembly {{
            dest := mload(add(vect, 0x20))
        }}
        return dest;
    }}

    function test_deserialization(bytes calldata input) external {{
      Library.ComplexStruct memory t = Library.bcs_deserialize_ComplexStruct(input);

      bytes memory input_rev = Library.bcs_serialize_ComplexStruct(t);
      require(input.length == input_rev.length);
      for (uint256 i=0; i<input.length; i++) {{
        require(input[i] == input_rev[i]);
      }}
      require(t.v1 == get_bytes32());
      require(t.v2 == get_bytes20());
    }}

}}
"#
        )?;
    }

    // Compiling the code and reading it.
    let bytecode = get_bytecode(path, "test_code.sol", "ExampleCode")?;

    // Building the test entry
    let mut v1 = [0_u8; 32];
    for (i, item) in v1.iter_mut().enumerate() {
        *item = i as u8;
    }
    //
    let mut v2 = [0_u8; 20];
    for (i, item) in v2.iter_mut().enumerate() {
        *item = i as u8;
    }
    //
    let mut v3 = [0_u16; 10];
    for (i, item) in v3.iter_mut().enumerate() {
        *item = i as u16;
    }
    //
    let t = ComplexStruct { v1, v2, v3 };
    let expected_input = bcs::to_bytes(&t).unwrap();

    // Building the input to the smart contract
    sol! {
        function test_deserialization(bytes calldata input);
    }
    let input = Bytes::copy_from_slice(&expected_input);
    let fct_args = test_deserializationCall { input };
    let fct_args = fct_args.abi_encode().into();

    test_contract(bytecode.clone(), fct_args);
    Ok(())
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct NestingBools {
    v1: Option<bool>,
    v2: Option<bool>,
    v3: Option<bool>,
    v4: bool,
}

#[test]
fn test_nesting_bools() -> anyhow::Result<()> {
    let registry = get_registry_from_type::<NestingBools>();
    let dir = tempdir().unwrap();
    let path = dir.path();

    // The library code
    let test_library_path = path.join("Library.sol");
    {
        let mut test_library_file = File::create(&test_library_path)?;
        let name = "Library".to_string();
        let config = CodeGeneratorConfig::new(name);
        let generator = solidity::CodeGenerator::new(&config);
        generator.output(&mut test_library_file, &registry).unwrap();
    }

    // The test code
    let test_code_path = path.join("test_code.sol");
    {
        let mut test_code_file = File::create(&test_code_path)?;

        writeln!(
            test_code_file,
            r#"/// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import "./Library.sol";

contract ExampleCode {{

    function test_deserialization(bytes calldata input) external {{
      Library.NestingBools memory t = Library.bcs_deserialize_NestingBools(input);

      bytes memory input_rev = Library.bcs_serialize_NestingBools(t);
      require(input.length == input_rev.length);
      for (uint256 i=0; i<input.length; i++) {{
        require(input[i] == input_rev[i]);
      }}
    }}

}}
"#
        )?;
    }

    // Compiling the code and reading it.
    let bytecode = get_bytecode(path, "test_code.sol", "ExampleCode")?;
    //
    let t = NestingBools {
        v1: None,
        v2: Some(true),
        v3: Some(false),
        v4: true,
    };
    let expected_input = bcs::to_bytes(&t).unwrap();

    // Building the input to the smart contract
    sol! {
        function test_deserialization(bytes calldata input);
    }
    let input = Bytes::copy_from_slice(&expected_input);
    let fct_args = test_deserializationCall { input };
    let fct_args = fct_args.abi_encode().into();

    test_contract(bytecode.clone(), fct_args);
    Ok(())
}