neo-devpack-solidity 0.22.0

Production-focused Solidity-to-NeoVM compilation system
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
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

static OUTPUT_SEQUENCE: AtomicU64 = AtomicU64::new(0);

fn get_compiler_path() -> PathBuf {
    // CARGO_BIN_EXE_<name> is set by Cargo for integration tests, pointing
    // to the correct binary for the current build profile (debug or release).
    PathBuf::from(env!("CARGO_BIN_EXE_neo-solc"))
}

fn get_example_path(contract: &str) -> PathBuf {
    // CARGO_MANIFEST_DIR is the project root — portable across CI and local dev.
    let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    manifest_dir.join("examples").join(contract)
}

fn unique_output_prefix(scope: &str, contract_path: &Path) -> Result<PathBuf, String> {
    let stem = contract_path
        .file_stem()
        .and_then(|s| s.to_str())
        .ok_or_else(|| format!("Invalid contract path: {}", contract_path.display()))?;
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    let seq = OUTPUT_SEQUENCE.fetch_add(1, Ordering::Relaxed);
    let output_dir = std::env::temp_dir().join(format!(
        "neo-sol-{scope}-{}-{nanos}-{seq}",
        std::process::id()
    ));
    std::fs::create_dir_all(&output_dir).map_err(|e| {
        format!(
            "Failed to create output directory '{}': {e}",
            output_dir.display()
        )
    })?;
    Ok(output_dir.join(stem))
}

/// Compile and assert success (exit-code only). Works for multi-contract files
/// where the compiler suffixes output with contract names.
fn assert_compiles(contract_path: &str) {
    let compiler = get_compiler_path();
    assert!(compiler.exists(), "Compiler not found");

    let contract_path = get_example_path(contract_path);
    let output_prefix = unique_output_prefix("test", &contract_path).expect("output prefix");

    let output = Command::new(&compiler)
        .arg(&contract_path)
        .arg("-I")
        .arg("devpack")
        .arg("-O2")
        .arg("-o")
        .arg(&output_prefix)
        .output()
        .expect("Failed to run compiler");

    assert!(
        output.status.success(),
        "Compilation failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

fn compile_contract(contract_path: &str) -> Result<(PathBuf, PathBuf), String> {
    let compiler = get_compiler_path();

    if !compiler.exists() {
        return Err(format!(
            "Compiler not found at {}. Run 'cargo build --release' first.",
            compiler.display()
        ));
    }

    let contract_path = get_example_path(contract_path);
    let output_prefix = unique_output_prefix("test", &contract_path)?;

    let output = Command::new(&compiler)
        .arg(&contract_path)
        .arg("-I")
        .arg("devpack")
        .arg("-O2")
        .arg("-o")
        .arg(&output_prefix)
        .output()
        .map_err(|e| format!("Failed to run compiler: {e}"))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!("Compilation failed: {stderr}"));
    }

    let nef_path = output_prefix.with_extension("nef");
    let manifest_path = output_prefix.with_extension("manifest.json");

    if !nef_path.exists() {
        return Err(format!("NEF file not generated: {}", nef_path.display()));
    }

    if !manifest_path.exists() {
        return Err(format!(
            "Manifest not generated: {}",
            manifest_path.display()
        ));
    }

    Ok((nef_path, manifest_path))
}

fn compile_contract_strict(contract_path: &str) -> Result<(PathBuf, PathBuf), String> {
    let compiler = get_compiler_path();

    if !compiler.exists() {
        return Err(format!(
            "Compiler not found at {}. Run 'cargo build --release' first.",
            compiler.display()
        ));
    }

    let contract_path = get_example_path(contract_path);
    let output_prefix = unique_output_prefix("test-strict", &contract_path)?;

    let output = Command::new(&compiler)
        .arg(&contract_path)
        .arg("-I")
        .arg("devpack")
        .arg("-O2")
        .arg("--deny-wildcard-permissions")
        .arg("--deny-wildcard-contracts")
        .arg("--deny-wildcard-methods")
        .arg("-o")
        .arg(&output_prefix)
        .output()
        .map_err(|e| format!("Failed to run compiler: {e}"))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!("Strict compilation failed: {stderr}"));
    }

    let nef_path = output_prefix.with_extension("nef");
    let manifest_path = output_prefix.with_extension("manifest.json");

    if !nef_path.exists() {
        return Err(format!("NEF file not generated: {}", nef_path.display()));
    }

    if !manifest_path.exists() {
        return Err(format!(
            "Manifest not generated: {}",
            manifest_path.display()
        ));
    }

    Ok((nef_path, manifest_path))
}

#[test]
fn test_compile_simple_storage() {
    let result = compile_contract("SimpleStorage.sol");
    assert!(
        result.is_ok(),
        "Failed to compile SimpleStorage: {:?}",
        result.err()
    );
    let (nef, manifest) = result.unwrap();
    assert!(nef.exists(), "NEF file should exist: {}", nef.display());
    assert!(
        manifest.exists(),
        "Manifest should exist: {}",
        manifest.display()
    );
}

#[test]
fn test_compile_erc20_token() {
    let result = compile_contract("ERC20Token.sol");
    assert!(
        result.is_ok(),
        "Failed to compile ERC20Token: {:?}",
        result.err()
    );
    let (nef, manifest) = result.unwrap();
    assert!(nef.exists(), "NEF file should exist: {}", nef.display());
    assert!(
        manifest.exists(),
        "Manifest should exist: {}",
        manifest.display()
    );
}

#[test]
fn test_compile_staking() {
    let result = compile_contract("Staking.sol");
    assert!(
        result.is_ok(),
        "Failed to compile Staking: {:?}",
        result.err()
    );
    let (nef, manifest) = result.unwrap();
    assert!(nef.exists(), "NEF file should exist: {}", nef.display());
    assert!(
        manifest.exists(),
        "Manifest should exist: {}",
        manifest.display()
    );
}

#[test]
fn test_compile_multisig_wallet() {
    let result = compile_contract("MultiSigWallet.sol");
    assert!(
        result.is_ok(),
        "Failed to compile MultiSigWallet: {:?}",
        result.err()
    );
    let (nef, manifest) = result.unwrap();
    assert!(nef.exists(), "NEF file should exist: {}", nef.display());
    assert!(
        manifest.exists(),
        "Manifest should exist: {}",
        manifest.display()
    );
}

#[test]
fn test_compile_with_optimization() {
    let compiler = get_compiler_path();
    if !compiler.exists() {
        return;
    }

    let example_path = get_example_path("SimpleStorage.sol");
    let output_prefix = unique_output_prefix("opt-test", &example_path).expect("output prefix");
    let output = Command::new(&compiler)
        .arg(&example_path)
        .arg("-O3")
        .arg("-o")
        .arg(&output_prefix)
        .output()
        .expect("Failed to run compiler");

    assert!(
        output.status.success(),
        "High optimization should compile successfully: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_nef_file_structure() {
    let result = compile_contract("SimpleStorage.sol");
    assert!(result.is_ok(), "Failed to compile SimpleStorage");

    let (nef_path, _) = result.unwrap();
    let nef_data = std::fs::read(&nef_path)
        .map_err(|e| format!("Failed to read NEF: {e}"))
        .unwrap();

    assert!(!nef_data.is_empty(), "NEF should not be empty");
    assert!(
        nef_data.len() < 1024 * 1024,
        "NEF should be reasonable size"
    );

    // NEF3 format magic bytes
    let magic = &nef_data[..4];
    assert_eq!(
        magic, b"NEF3",
        "NEF should have correct magic bytes (NEF3 format)"
    );
}

#[test]
fn test_manifest_structure() {
    let result = compile_contract("SimpleStorage.sol");
    assert!(result.is_ok(), "Failed to compile SimpleStorage");

    let (_, manifest_path) = result.unwrap();
    let manifest_data = std::fs::read_to_string(&manifest_path)
        .map_err(|e| format!("Failed to read manifest: {e}"))
        .unwrap();

    let json: serde_json::Value = serde_json::from_str(&manifest_data)
        .map_err(|e| format!("Invalid JSON: {e}"))
        .unwrap();

    assert!(json.is_object(), "Manifest should be JSON object");
    assert!(
        json.get("name").is_some(),
        "Manifest should have name field"
    );
    assert!(json.get("abi").is_some(), "Manifest should have abi field");
    assert!(
        json.get("permissions").is_some(),
        "Manifest should have permissions field"
    );
}

#[test]
fn test_compile_name_service() {
    let result = compile_contract("NameService.sol");
    assert!(
        result.is_ok(),
        "Failed to compile NameService: {:?}",
        result.err()
    );
    let (nef, manifest) = result.unwrap();
    assert!(nef.exists(), "NEF file should exist: {}", nef.display());
    assert!(
        manifest.exists(),
        "Manifest should exist: {}",
        manifest.display()
    );
}

#[test]
fn test_compile_lottery() {
    let result = compile_contract("Lottery.sol");
    assert!(
        result.is_ok(),
        "Failed to compile Lottery: {:?}",
        result.err()
    );
    let (nef, manifest) = result.unwrap();
    assert!(nef.exists(), "NEF file should exist: {}", nef.display());
    assert!(
        manifest.exists(),
        "Manifest should exist: {}",
        manifest.display()
    );
}

#[test]
fn test_compile_escrow() {
    let result = compile_contract("Escrow.sol");
    assert!(
        result.is_ok(),
        "Failed to compile Escrow: {:?}",
        result.err()
    );
    let (nef, manifest) = result.unwrap();
    assert!(nef.exists(), "NEF file should exist: {}", nef.display());
    assert!(
        manifest.exists(),
        "Manifest should exist: {}",
        manifest.display()
    );
}

#[test]
fn test_compile_new_neo_interop_showcase() {
    let result = compile_contract("new/NeoInteropShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile NeoInteropShowcase: {:?}",
        result.err()
    );
    let (nef, manifest) = result.unwrap();
    assert!(nef.exists(), "NEF file should exist: {}", nef.display());
    assert!(
        manifest.exists(),
        "Manifest should exist: {}",
        manifest.display()
    );
}

#[test]
fn test_compile_new_low_level_call_showcase() {
    let result = compile_contract("new/LowLevelCallShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile LowLevelCallShowcase: {:?}",
        result.err()
    );
    let (nef, manifest) = result.unwrap();
    assert!(nef.exists(), "NEF file should exist: {}", nef.display());
    assert!(
        manifest.exists(),
        "Manifest should exist: {}",
        manifest.display()
    );
}

#[test]
fn test_compile_new_enum_array_showcase() {
    let result = compile_contract("new/EnumArrayShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile EnumArrayShowcase: {:?}",
        result.err()
    );
    let (nef, manifest) = result.unwrap();
    assert!(nef.exists(), "NEF file should exist: {}", nef.display());
    assert!(
        manifest.exists(),
        "Manifest should exist: {}",
        manifest.display()
    );
}

#[test]
fn test_optimization_reduces_size() {
    let compiler = get_compiler_path();
    if !compiler.exists() {
        return;
    }

    let example_path = get_example_path("SimpleStorage.sol");

    // Compile without optimization
    let output_no_opt = Command::new(&compiler)
        .arg(&example_path)
        .arg("-O0")
        .arg("-o")
        .arg("/tmp/no_opt_test")
        .output()
        .expect("Failed to run compiler");

    assert!(
        output_no_opt.status.success(),
        "No-opt compilation should succeed"
    );

    let no_opt_size = std::fs::metadata("/tmp/no_opt_test.nef")
        .map(|m| m.len())
        .unwrap_or(0);

    // Compile with optimization
    let output_opt = Command::new(&compiler)
        .arg(&example_path)
        .arg("-O3")
        .arg("-o")
        .arg("/tmp/opt_test")
        .output()
        .expect("Failed to run compiler");

    assert!(
        output_opt.status.success(),
        "Optimized compilation should succeed"
    );

    let opt_size = std::fs::metadata("/tmp/opt_test.nef")
        .map(|m| m.len())
        .unwrap_or(0);

    // Optimization should not significantly increase size
    // (Note: for simple contracts, O3 might be slightly larger due to inlining)
    assert!(
        opt_size <= no_opt_size * 2,
        "Optimized bytecode should not be more than 2x the original size"
    );
}

#[test]
fn test_manifest_has_valid_abi() {
    let result = compile_contract("ERC20Token.sol");
    assert!(result.is_ok(), "Failed to compile ERC20Token");

    let (_, manifest_path) = result.unwrap();
    let manifest_data = std::fs::read_to_string(&manifest_path)
        .map_err(|e| format!("Failed to read manifest: {e}"))
        .unwrap();

    let json: serde_json::Value = serde_json::from_str(&manifest_data)
        .map_err(|e| format!("Invalid JSON: {e}"))
        .unwrap();

    let abi = json.get("abi").expect("Manifest should have ABI");

    assert!(
        abi.is_object(),
        "ABI should be an object with methods and events"
    );

    let abi_obj = abi.as_object().unwrap();
    let methods = abi_obj.get("methods").expect("ABI should have methods");

    assert!(methods.is_array(), "ABI methods should be an array");

    let methods_array = methods.as_array().unwrap();
    assert!(
        !methods_array.is_empty(),
        "Contract should have at least one method"
    );

    // Check that methods have required fields
    for method in methods_array {
        assert!(method.get("name").is_some(), "Method should have a name");
        assert!(
            method.get("parameters").is_some(),
            "Method should have parameters"
        );
        assert!(
            method.get("returntype").is_some(),
            "Method should have return type"
        );
    }
}

// ========== Root examples — previously untested ==========

#[test]
fn test_compile_erc721_token() {
    let result = compile_contract("ERC721Token.sol");
    assert!(
        result.is_ok(),
        "Failed to compile ERC721Token: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_governance_token() {
    let result = compile_contract("GovernanceToken.sol");
    assert!(
        result.is_ok(),
        "Failed to compile GovernanceToken: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_uniswap_v2_pair() {
    let result = compile_contract("UniswapV2Pair.sol");
    assert!(
        result.is_ok(),
        "Failed to compile UniswapV2Pair: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_test_contract() {
    let result = compile_contract("TestContract.sol");
    assert!(
        result.is_ok(),
        "Failed to compile TestContract: {:?}",
        result.err()
    );
}

// ========== Existing new/ examples — previously untested ==========

#[test]
fn test_compile_new_counter() {
    let result = compile_contract("new/Counter.sol");
    assert!(
        result.is_ok(),
        "Failed to compile Counter: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_new_vault() {
    let result = compile_contract("new/Vault.sol");
    assert!(
        result.is_ok(),
        "Failed to compile Vault: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_new_nft() {
    let result = compile_contract("new/NFT.sol");
    assert!(result.is_ok(), "Failed to compile NFT: {:?}", result.err());
}

#[test]
fn test_compile_new_bank() {
    let result = compile_contract("new/Bank.sol");
    assert!(result.is_ok(), "Failed to compile Bank: {:?}", result.err());
}

#[test]
fn test_compile_new_multisig_wallet_nep17() {
    let result = compile_contract("new/MultiSigWalletNEP17.sol");
    assert!(
        result.is_ok(),
        "Failed to compile MultiSigWalletNEP17: {:?}",
        result.err()
    );
}

// ========== New showcase contracts ==========

#[test]
fn test_compile_new_custom_errors_showcase() {
    let result = compile_contract("new/CustomErrorsShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile CustomErrorsShowcase: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_new_inheritance_showcase() {
    // Multi-contract file: compiler suffixes output with contract names
    assert_compiles("new/InheritanceShowcase.sol");
}

#[test]
fn test_compile_new_interface_showcase() {
    let result = compile_contract("new/InterfaceShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile InterfaceShowcase: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_new_modifier_showcase() {
    let result = compile_contract("new/ModifierShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile ModifierShowcase: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_new_struct_mapping_showcase() {
    let result = compile_contract("new/StructMappingShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile StructMappingShowcase: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_new_type_casting_showcase() {
    let result = compile_contract("new/TypeCastingShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile TypeCastingShowcase: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_new_constants_immutable_showcase() {
    let result = compile_contract("new/ConstantsImmutableShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile ConstantsImmutableShowcase: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_new_bitwise_showcase() {
    let result = compile_contract("new/BitwiseShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile BitwiseShowcase: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_new_try_catch_showcase() {
    let result = compile_contract("new/TryCatchShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile TryCatchShowcase: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_new_catch_panic_showcase() {
    let result = compile_contract("new/CatchPanicShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile CatchPanicShowcase: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_new_event_indexed_showcase() {
    let result = compile_contract("new/EventIndexedShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile EventIndexedShowcase: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_new_oracle_showcase() {
    let result = compile_contract("new/OracleShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile OracleShowcase: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_new_multi_standard_token() {
    let result = compile_contract("new/MultiStandardToken.sol");
    assert!(
        result.is_ok(),
        "Failed to compile MultiStandardToken: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_new_upgrade_lifecycle_showcase_strict() {
    let result = compile_contract_strict("new/UpgradeLifecycleShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed strict compilation for UpgradeLifecycleShowcase: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_new_witness_guard_showcase_strict() {
    let result = compile_contract_strict("new/WitnessGuardShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed strict compilation for WitnessGuardShowcase: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_new_oracle_relay_strict_showcase_strict() {
    let result = compile_contract_strict("new/OracleRelayStrictShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed strict compilation for OracleRelayStrictShowcase: {:?}",
        result.err()
    );
}

// ========== Famous DeFi/Web3 contracts ==========

#[test]
fn test_compile_famous_wgas() {
    let result = compile_contract("famous/WGAS.sol");
    assert!(result.is_ok(), "Failed to compile WGAS: {:?}", result.err());
}

#[test]
fn test_compile_famous_flashloan() {
    let result = compile_contract("famous/FlashLoan.sol");
    assert!(
        result.is_ok(),
        "Failed to compile FlashLoan: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_famous_simple_amm() {
    let result = compile_contract("famous/SimpleAMM.sol");
    assert!(
        result.is_ok(),
        "Failed to compile SimpleAMM: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_famous_token_vesting() {
    let result = compile_contract("famous/TokenVesting.sol");
    assert!(
        result.is_ok(),
        "Failed to compile TokenVesting: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_famous_simple_lending() {
    let result = compile_contract("famous/SimpleLending.sol");
    assert!(
        result.is_ok(),
        "Failed to compile SimpleLending: {:?}",
        result.err()
    );
}

#[test]
fn test_compile_famous_simple_dao() {
    let result = compile_contract("famous/SimpleDAO.sol");
    assert!(
        result.is_ok(),
        "Failed to compile SimpleDAO: {:?}",
        result.err()
    );
}

// ========== Native contract integration tests (Phase 7c) ==========

#[test]
fn test_compile_native_contract_showcase() {
    let result = compile_contract("new/NativeContractShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile NativeContractShowcase: {:?}",
        result.err()
    );
}

#[test]
fn test_native_contract_showcase_manifest_methods() {
    let result = compile_contract("new/NativeContractShowcase.sol");
    assert!(result.is_ok(), "Failed to compile NativeContractShowcase");

    let (_, manifest_path) = result.unwrap();
    let manifest_data = std::fs::read_to_string(&manifest_path).expect("Failed to read manifest");

    let json: serde_json::Value = serde_json::from_str(&manifest_data).expect("Invalid JSON");

    let methods = json["abi"]["methods"]
        .as_array()
        .expect("ABI methods should be an array");

    let method_names: Vec<&str> = methods.iter().filter_map(|m| m["name"].as_str()).collect();

    // Verify key methods from each native contract section are present
    let expected = [
        "policyFeePerByte",
        "oraclePrice",
        "ledgerCurrentIndex",
        "ledgerCurrentHash",
        "notaryBalance",
        "treasuryIsValid",
        "isNative",
    ];

    for name in &expected {
        assert!(
            method_names.contains(name),
            "Manifest should contain method '{name}', found: {method_names:?}"
        );
    }
}

#[test]
fn test_native_contract_showcase_manifest_permissions() {
    let result = compile_contract("new/NativeContractShowcase.sol");
    assert!(result.is_ok(), "Failed to compile NativeContractShowcase");

    let (_, manifest_path) = result.unwrap();
    let manifest_data = std::fs::read_to_string(&manifest_path).expect("Failed to read manifest");

    let json: serde_json::Value = serde_json::from_str(&manifest_data).expect("Invalid JSON");

    let permissions = json["permissions"]
        .as_array()
        .expect("Permissions should be an array");

    // Contract calls native contracts → permissions must be non-empty
    assert!(
        !permissions.is_empty(),
        "NativeContractShowcase should have non-empty permissions for native contract calls"
    );
}

#[test]
fn test_native_contract_showcase_nef_valid() {
    let result = compile_contract("new/NativeContractShowcase.sol");
    assert!(result.is_ok(), "Failed to compile NativeContractShowcase");

    let (nef_path, _) = result.unwrap();
    let nef_data = std::fs::read(&nef_path).expect("Failed to read NEF");

    assert!(!nef_data.is_empty(), "NEF should not be empty");
    assert_eq!(
        &nef_data[..4],
        b"NEF3",
        "NEF should have correct magic bytes"
    );
    assert!(
        nef_data.len() > 50,
        "NEF should contain meaningful bytecode, got {} bytes",
        nef_data.len()
    );
}

#[test]
fn test_parallel_compilation_outputs_are_isolated() {
    let workers = 4usize;
    let iterations_per_worker = 2usize;

    let handles: Vec<_> = (0..workers)
        .map(|_| {
            std::thread::spawn(move || {
                for _ in 0..iterations_per_worker {
                    let (nef_path, manifest_path) =
                        compile_contract("new/NativeContractShowcase.sol")
                            .expect("parallel compile should succeed");

                    let nef_data = std::fs::read(&nef_path).expect("read NEF");
                    assert!(
                        nef_data.len() >= 4 && &nef_data[..4] == b"NEF3",
                        "parallel compile produced invalid NEF header"
                    );

                    let manifest_data =
                        std::fs::read_to_string(&manifest_path).expect("read manifest");
                    let json: serde_json::Value =
                        serde_json::from_str(&manifest_data).expect("manifest JSON");
                    let permissions = json["permissions"].as_array().expect("permissions array");
                    assert!(
                        !permissions.is_empty(),
                        "expected non-empty permissions in parallel compilation manifest"
                    );
                }
            })
        })
        .collect();

    for handle in handles {
        handle.join().expect("parallel worker panicked");
    }
}

// ========== EVM compatibility error tests ==========

/// Compile a contract and assert that compilation fails with stderr containing
/// the expected error substring.
fn assert_compile_error_contains(contract_path: &str, expected_error: &str) {
    let compiler = get_compiler_path();
    assert!(compiler.exists(), "Compiler not found");

    let contract_path = get_example_path(contract_path);
    let output_prefix =
        unique_output_prefix("evm-compat-error", &contract_path).expect("output prefix");

    let output = Command::new(&compiler)
        .arg(&contract_path)
        .arg("-I")
        .arg("devpack")
        .arg("-O2")
        .arg("-o")
        .arg(&output_prefix)
        .output()
        .expect("Failed to run compiler");

    assert!(
        !output.status.success(),
        "Expected compilation to fail for {contract_path:?}"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains(expected_error),
        "Expected stderr to contain '{expected_error}', got:\n{stderr}"
    );
}

/// Compile a contract and assert that compilation succeeds but stderr contains
/// the expected warning substring.
fn assert_compile_warns(contract_path: &str, expected_warning: &str) {
    let compiler = get_compiler_path();
    assert!(compiler.exists(), "Compiler not found");

    let contract_path = get_example_path(contract_path);
    let output_prefix =
        unique_output_prefix("evm-compat-warn", &contract_path).expect("output prefix");

    let output = Command::new(&compiler)
        .arg(&contract_path)
        .arg("-I")
        .arg("devpack")
        .arg("-O2")
        .arg("-o")
        .arg(&output_prefix)
        .output()
        .expect("Failed to run compiler");

    assert!(
        output.status.success(),
        "Expected compilation to succeed for {:?}, stderr:\n{}",
        contract_path,
        String::from_utf8_lossy(&output.stderr)
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains(expected_warning),
        "Expected stderr to contain warning '{expected_warning}', got:\n{stderr}"
    );
}

/// Compile a contract and assert that compilation succeeds and stderr does
/// not contain the given warning substring.
fn assert_compile_not_warns(contract_path: &str, unexpected_warning: &str) {
    let compiler = get_compiler_path();
    assert!(compiler.exists(), "Compiler not found");

    let contract_path = get_example_path(contract_path);
    let output_prefix =
        unique_output_prefix("evm-compat-no-warn", &contract_path).expect("output prefix");

    let output = Command::new(&compiler)
        .arg(&contract_path)
        .arg("-I")
        .arg("devpack")
        .arg("-O2")
        .arg("-o")
        .arg(&output_prefix)
        .output()
        .expect("Failed to run compiler");

    assert!(
        output.status.success(),
        "Expected compilation to succeed for {:?}, stderr:\n{}",
        contract_path,
        String::from_utf8_lossy(&output.stderr)
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains(unexpected_warning),
        "Did not expect stderr to contain warning '{unexpected_warning}', got:\n{stderr}"
    );
}

// block.coinbase/difficulty/gaslimit/basefee are now auto-mapped to Neo N3
// equivalents (address(0), Runtime.getRandom, Policy.getExecFeeFactor,
// Policy.getFeePerByte) with compile-time warnings instead of errors.
#[test]
fn test_evm_compat_block_auto_mapped() {
    assert_compiles("new/EvmCompatBlockErrors.sol");
}

// blockhash() is now auto-mapped to Ledger.getBlockHash() with warning.
#[test]
fn test_evm_compat_blockhash_auto_mapped() {
    assert_compiles("new/EvmCompatBlockhashError.sol");
}

#[test]
fn test_evm_compat_blockhash_warning() {
    assert_compile_warns(
        "new/EvmCompatBlockhashError.sol",
        "blockhash() auto-mapped to Ledger.getBlockHash() on Neo N3",
    );
}

// address.codehash is now auto-mapped to contract script hash with warning.
#[test]
fn test_evm_compat_address_codehash_auto_mapped() {
    assert_compiles("new/EvmCompatAddressCodehash.sol");
}

#[test]
fn test_evm_compat_address_code_warning() {
    assert_compile_warns(
        "new/EvmCompatAddressCode.sol",
        "address.code auto-mapped to the Neo contract script bytes via ContractManagement.getContract()",
    );
}

// selfdestruct() is now auto-mapped to ContractManagement.destroy() with warning.
#[test]
fn test_evm_compat_selfdestruct_auto_mapped() {
    assert_compiles("new/EvmCompatSelfdestructError.sol");
}

#[test]
fn test_evm_compat_ether_units_error() {
    assert_compile_error_contains(
        "new/EvmCompatEtherUnits.sol",
        "ether units (wei/gwei/ether) are not applicable on Neo N3",
    );
}

#[test]
fn test_evm_compat_msg_sig_warning() {
    assert_compile_warns(
        "new/EvmCompatMsgSig.sol",
        "msg.sig is approximated on Neo N3 using the current function selector",
    );
}

#[test]
fn test_evm_compat_msg_data_warning() {
    assert_compile_warns(
        "new/EvmCompatMsgData.sol",
        "msg.data is approximated on Neo N3 as `selector || abi.encode(current args)`",
    );
}

#[test]
fn test_evm_compat_encode_calldata_warning() {
    assert_compile_warns(
        "new/EvmCompatEncodeCalldata.sol",
        "abi.encodeWithSignature(...) is approximated on Neo N3 as selector bytes concatenated with abi.encode(args)",
    );
}

#[test]
fn test_evm_compat_tx_origin_warning() {
    assert_compile_warns(
        "new/EvmCompatTxOrigin.sol",
        "tx.origin has different semantics on Neo N3",
    );
}

// ── Phase 3: Showcase compilation tests ──────────────────────────────────

#[test]
fn test_expression_showcase_compiles() {
    assert_compiles("new/ExpressionShowcase.sol");
}

#[test]
fn test_storage_concat_showcase_compiles() {
    assert_compiles("new/StorageConcatShowcase.sol");
}

// ── Function polish: payable, receive, fallback, modifiers, overloading ──

#[test]
fn test_compile_function_polish_showcase() {
    let result = compile_contract("new/FunctionPolishShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile FunctionPolishShowcase: {:?}",
        result.err()
    );
}

// ── Unchecked block support ───────────────────────────────────────────────

#[test]
fn test_compile_unchecked_showcase() {
    let result = compile_contract("new/UncheckedShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile UncheckedShowcase: {:?}",
        result.err()
    );
}

// ── Virtual/override inheritance enforcement ─────────────────────────────

#[test]
fn test_compile_virtual_override_showcase() {
    // Multi-contract file: compiler suffixes output with contract names
    assert_compiles("new/VirtualOverrideShowcase.sol");
}

// ── Library support ──────────────────────────────────────────────────────

#[test]
fn test_compile_library_showcase() {
    let result = compile_contract("new/LibraryShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile LibraryShowcase: {:?}",
        result.err()
    );
}

#[test]
fn test_library_showcase_manifest_has_compute_method() {
    let result = compile_contract("new/LibraryShowcase.sol");
    assert!(result.is_ok(), "Failed to compile LibraryShowcase");

    let (_, manifest_path) = result.unwrap();
    let manifest_data = std::fs::read_to_string(&manifest_path).expect("Failed to read manifest");
    let json: serde_json::Value = serde_json::from_str(&manifest_data).expect("Invalid JSON");

    let methods = json["abi"]["methods"]
        .as_array()
        .expect("ABI methods should be an array");
    let method_names: Vec<&str> = methods.iter().filter_map(|m| m["name"].as_str()).collect();

    assert!(
        method_names.contains(&"compute"),
        "Manifest should contain 'compute' method, found: {method_names:?}"
    );
}

#[test]
fn test_library_external_function_showcase_compiles() {
    assert_compiles("new/LibraryExternalError.sol");
}

#[test]
fn test_solidity_features_complete_has_no_false_override_warning() {
    assert_compile_not_warns(
        "new/SolidityFeaturesComplete.sol",
        "overrides 'Ownable::add' which is not marked 'virtual'",
    );
}

#[test]
fn test_library_state_variable_error() {
    assert_compile_error_contains("new/LibraryStateVarError.sol", "cannot have state variable");
}

#[test]
fn test_library_constructor_error() {
    assert_compile_error_contains(
        "new/LibraryConstructorError.sol",
        "cannot have a constructor",
    );
}

// ── Type system error tests ─────────────────────────────────────────────

#[test]
fn test_fixed_point_type_error() {
    assert_compile_error_contains("new/FixedPointError.sol", "fixed-point type");
}

#[test]
fn test_fixed_point_suggestion() {
    assert_compile_error_contains("new/FixedPointError.sol", "not supported on NeoVM");
}

#[test]
fn test_user_defined_value_type_compiles() {
    // `type Price is uint256` with `Price.wrap(...)` is now supported.
    // User-defined value types are transparent aliases; wrap/unwrap are no-ops.
    assert_compiles("new/UserDefinedTypeError.sol");
}

#[test]
fn test_type_name_expression_compiles() {
    // `type(Contract).name` and `type(uint256).name` resolve to compile-time
    // string constants on NeoVM.
    assert_compiles("new/TypeNameShowcase.sol");
}

// ── Super keyword diagnostic tests ──────────────────────────────────────

#[test]
fn test_compile_super_showcase_workaround() {
    // SuperShowcase.sol demonstrates the internal-helper workaround pattern
    // for the `super` keyword. It must compile successfully.
    assert_compiles("new/SuperShowcase.sol");
}

#[test]
fn test_super_keyword_compiles() {
    // SuperError.sol uses `super.greet()` which is now supported via
    // inheritance flattening with __super_ method preservation.
    assert_compiles("new/SuperError.sol");
}

// ── require(condition, CustomError(...)) support ────────────────────────

#[test]
fn test_require_custom_error_compiles() {
    // Solidity 0.8.26+ `require(cond, CustomError(args))` syntax.
    // On NeoVM the error name and arg count are preserved in the THROW message.
    let result = compile_contract("new/RequireCustomErrorShowcase.sol");
    assert!(
        result.is_ok(),
        "Failed to compile RequireCustomErrorShowcase: {:?}",
        result.err()
    );
}