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
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
fn manifest_type_name(ty: ManifestType) -> &'static str {
    match ty {
        ManifestType::Integer => "Integer",
        ManifestType::Boolean => "Boolean",
        ManifestType::String => "String",
        ManifestType::Hash160 => "Hash160",
        ManifestType::Hash256 => "Hash256",
        ManifestType::ByteArray => "ByteArray",
        ManifestType::Array => "Array",
        ManifestType::Map => "Map",
        ManifestType::Any => "Any",
    }
}

fn value_type_satisfies_manifest_type(actual: &ValueType, expected: ManifestType) -> Option<bool> {
    if expected == ManifestType::Any {
        return Some(true);
    }

    match actual {
        ValueType::Any => None,
        ValueType::Integer { .. } => Some(expected == ManifestType::Integer),
        ValueType::Boolean => Some(expected == ManifestType::Boolean),
        ValueType::String => Some(matches!(
            expected,
            ManifestType::String | ManifestType::ByteArray
        )),
        ValueType::Address => Some(matches!(
            expected,
            ManifestType::Hash160 | ManifestType::ByteArray
        )),
        ValueType::ByteArray { fixed_len } => match expected {
            ManifestType::Hash160 => Some(matches!(fixed_len, Some(20))),
            ManifestType::Hash256 => Some(matches!(fixed_len, Some(32))),
            ManifestType::ByteArray => Some(true),
            _ => Some(false),
        },
        ValueType::Array(_) => Some(expected == ManifestType::Array),
        ValueType::Mapping { .. } => Some(expected == ManifestType::Map),
        ValueType::Struct { .. } => Some(expected == ManifestType::Array),
    }
}

fn extract_string_literal(expr: &Expression) -> Option<String> {
    match expr {
        Expression::StringLiteral(parts) => {
            Some(String::from_utf8_lossy(&string_literal_bytes(parts)).to_string())
        }
        _ => None,
    }
}

fn extract_abi_encode_args(expr: &Expression) -> Option<&[Expression]> {
    let Expression::FunctionCall(_, func, args) = expr else {
        return None;
    };

    let Expression::MemberAccess(_, inner, member) = func.as_ref() else {
        return None;
    };
    let Expression::Variable(base) = inner.as_ref() else {
        return None;
    };

    if base.name == "abi"
        && (member.name == "encode" || member.name == "encodePacked" || member.name == "encodeCall")
    {
        Some(args.as_slice())
    } else {
        None
    }
}

fn validate_runtime_notify_call(args: &[Expression], ctx: &mut LoweringContext) {
    if args.len() != 2 {
        return;
    }

    let Some(event_name) = extract_string_literal(&args[0]) else {
        return;
    };

    let Some(expected_sig) = ctx.event_signature(&event_name).map(|sig| sig.to_vec()) else {
        ctx.record_error(format!(
            "Runtime.notify refers to event '{event_name}' which is not declared; declare a matching Solidity `event` so it is included in the contract manifest ABI"
        ));
        return;
    };

    let Some(encoded_args) = extract_abi_encode_args(&args[1]) else {
        return;
    };

    if expected_sig.len() != encoded_args.len() {
        ctx.record_error(format!(
            "Runtime.notify event '{event_name}' expects {} argument(s), but abi.encode(...) provides {}",
            expected_sig.len(),
            encoded_args.len()
        ));
        return;
    }

    for (index, (expected_ty, arg_expr)) in expected_sig
        .iter()
        .copied()
        .zip(encoded_args.iter())
        .enumerate()
    {
        if expected_ty == ManifestType::Any {
            continue;
        }

        let Some(actual_ty) = infer_type_from_expression(arg_expr, ctx) else {
            continue;
        };

        if value_type_satisfies_manifest_type(&actual_ty, expected_ty) == Some(false) {
            ctx.record_error(format!(
                "Runtime.notify event '{event_name}' argument #{} has incompatible type (expected {}, got {:?})",
                index,
                manifest_type_name(expected_ty),
                actual_ty
            ));
        }
    }
}

/// Task #106 — when an expression passed to `abi.encodeCall` is a bare
/// Variable reference to a struct-typed function parameter, return the
/// flattened parameter-slot range `(base_slot, field_count)` so the caller
/// can emit `LoadParameter(base..base+count)` and feed the flattened fields
/// into `abiEncode`. This implements per-field expansion for struct args:
/// `abi.encodeCall(this.f, (p))` where `p = P{uint256 a; bool b}` lowers to
/// `sel || abiEncode(p.a, p.b)` instead of `sel || abiEncode(p)` (which
/// would produce zero-slot output for the struct-as-Array shape).
///
/// Returns `None` if `expr` is not a bare Variable reference, the variable
/// is not a function parameter, or the parameter is not a struct type. The
/// caller should then fall through to the standard `lower_expression`
/// path.
fn resolve_struct_param_flat_slots(
    expr: &Expression,
    ctx: &LoweringContext,
) -> Option<(usize, usize)> {
    // Look through parentheses.
    let mut current = expr;
    while let Expression::Parenthesis(_, inner) = current {
        current = inner.as_ref();
    }
    let Expression::Variable(id) = current else {
        return None;
    };
    let &param_index = ctx.param_index_map.get(&id.name)?;
    let param_ty = ctx.param_types.get(param_index)?;
    // Only expand struct-typed params. Returns the flat slot range in the
    // post-flattening param layout (see `flatten_param_slot_map` in
    // bytecode_emit_ir). For Task #106 the expansion is single-level: a
    // struct's direct fields become consecutive slots; nested structs
    // would require recursive expansion, which is a follow-up.
    let ValueType::Struct { fields, .. } = param_ty else {
        return None;
    };
    // Compute the flattened starting slot for this struct param by counting
    // flat slots for all preceding params.
    let mut base_slot: usize = 0;
    for i in 0..param_index {
        let prev = ctx.param_types.get(i)?;
        base_slot += flat_slot_count_for_param_type(prev);
    }
    Some((base_slot, fields.len()))
}

/// Returns the number of flattened parameter slots this `ValueType` occupies
/// in the post-Task-#106 INITSLOT layout. Structs flatten to their direct
/// field count; all other value types count as 1. Nested structs flatten
/// only one level (fields that are themselves structs stay as single slots
/// for now — nested expansion is a follow-up).
fn flat_slot_count_for_param_type(ty: &ValueType) -> usize {
    match ty {
        ValueType::Struct { fields, .. } => fields.len(),
        _ => 1,
    }
}

/// Task #124 — `abi.encode(struct)` whole-struct expansion. If `expr` has a
/// struct type, emit per-field extraction instructions so the downstream
/// `AbiEncode` builtin receives N individual stack items (one per direct
/// field) instead of a single `StackItem::Array` that the runtime's
/// `abiencode` handler would misclassify as a DYNAMIC type (Task #121's
/// offset+length+elements shape).
///
/// EVM ABI spec: a struct whose fields are all static types is itself a
/// STATIC type, and `abi.encode(s)` must equal the byte-for-byte concatenation
/// of each field's 32-byte BE-padded slot (no offset/length header). For the
/// `keccak256(abi.encode(Voucher{amount, recipient, expiry}))` case this is
/// the 96-byte buffer `BE(amount) || BE(addr) || BE(expiry)`.
///
/// Emission shape (per field `i`):
///   `lower_expression(expr); push i; ArrayGet`
/// which reads the struct's `StackItem::Array` backing storage and indexes
/// into it. For a bare Variable reference to a struct param this is cheap
/// (each `lower_expression` is a single `LoadParameter`); for storage-
/// backed struct locals it re-runs the storage-load but is still correct.
/// The runtime's `ArrayGet` unwraps the field value (Integer / ByteArray /
/// Boolean) so `abi_pad32_be` in the runtime handler sees a scalar it can
/// classify as STATIC.
///
/// Returns `Some(field_count)` if flattening fired, `None` if the expression
/// is not struct-typed (caller falls through to standard `lower_expression`).
/// `success` is threaded through so the caller can short-circuit when a
/// nested lowering fails.
fn try_flatten_struct_arg_for_abi_encode(
    expr: &Expression,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
    success: &mut bool,
) -> Option<usize> {
    // Look through parentheses to reach the expression we'll type-check.
    let mut current = expr;
    while let Expression::Parenthesis(_, inner) = current {
        current = inner.as_ref();
    }
    let ValueType::Struct { fields, .. } = infer_type_from_expression(current, ctx)? else {
        return None;
    };
    // Only flatten when EVERY field is a STATIC EVM type. Dynamic fields
    // (string/bytes/T[]) would still need the head+tail layout, which the
    // runtime handler already produces for a top-level Array. Avoid muddying
    // the DD3 fix with nested dynamics — gate the flatten on all-static.
    let all_static = fields.iter().all(|f| is_static_abi_type_value(&f.ty));
    if !all_static {
        return None;
    }
    let field_count = fields.len();
    if field_count == 0 {
        return None;
    }
    for i in 0..field_count {
        if !lower_expression(current, ctx, instructions) {
            *success = false;
            return Some(field_count);
        }
        instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
            BigInt::from(i as u64),
        )));
        instructions.push(Instruction::ArrayGet);
    }
    Some(field_count)
}

/// Task #124 — true iff a `ValueType` is a STATIC EVM ABI type (all-static
/// structs fold to per-field 32-byte slots, no offset/length header). Mirrors
/// the `is_static_abi_type` predicate used by `abi_decode_expected_static_bytes`
/// but operates on the IR `ValueType` rather than a solang `PtType`.
fn is_static_abi_type_value(ty: &ValueType) -> bool {
    match ty {
        ValueType::Integer { .. } => true,
        ValueType::Boolean => true,
        ValueType::Address => true,
        ValueType::ByteArray { fixed_len: Some(_) } => true,
        // Unknown-width bytes arrays (`bytes memory`), strings, arrays, and
        // mappings are dynamic and must keep the head+tail layout.
        ValueType::ByteArray { fixed_len: None } => false,
        ValueType::String => false,
        ValueType::Array(_) => false,
        ValueType::Mapping { .. } => false,
        // Nested structs: conservative — keep at single-level and treat as
        // dynamic (so the outer encode uses the existing StackItem::Array
        // fallback path for nested structs). Nested-struct flattening is
        // a follow-up if harnesses need it.
        ValueType::Struct { .. } => false,
        ValueType::Any => false,
    }
}

fn lower_abi_encode_args_direct_from_slice(
    args: &[Expression],
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) -> Option<bool> {
    let refs: Vec<&Expression> = args.iter().collect();
    lower_abi_encode_args_direct(&refs, ctx, instructions)
}

fn lower_abi_encode_args_direct(
    args: &[&Expression],
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) -> Option<bool> {
    lower_abi_encode_args_direct_impl(args, ctx, instructions, false)
}

fn lower_abi_encode_args_direct_for_encode_call(
    args: &[&Expression],
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) -> Option<bool> {
    lower_abi_encode_args_direct_impl(args, ctx, instructions, true)
}

fn lower_abi_encode_args_direct_impl(
    args: &[&Expression],
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
    flatten_struct_params: bool,
) -> Option<bool> {
    if args.is_empty() {
        instructions.push(Instruction::PushLiteral(
            LiteralValue::ByteArray(Vec::new()),
        ));
        return Some(true);
    }

    if let Some(result) = lower_abi_encode_head_tail_direct(args, ctx, instructions) {
        return Some(result);
    }

    let pre_len = instructions.len();
    let mut slot_count = 0usize;
    for arg in args {
        match lower_static_abi_slots_for_expr(arg, ctx, instructions, flatten_struct_params) {
            Some(slots) => slot_count += slots,
            None => {
                instructions.truncate(pre_len);
                return None;
            }
        }
    }

    if slot_count == 0 {
        instructions.truncate(pre_len);
        return None;
    }

    instructions.push(Instruction::CallBuiltin {
        builtin: BuiltinCall::BytesConcat,
        arg_count: slot_count,
    });
    Some(true)
}

fn lower_abi_encode_head_tail_direct(
    args: &[&Expression],
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) -> Option<bool> {
    let arg_types: Vec<ValueType> = args
        .iter()
        .map(|arg| infer_type_from_expression(arg, ctx))
        .collect::<Option<Vec<_>>>()?;

    if !arg_types.iter().any(abi_value_type_is_dynamic) {
        return None;
    }

    let mut head_slot_count = 0usize;
    for value_type in &arg_types {
        if abi_value_type_is_dynamic(value_type) {
            if !abi_dynamic_value_type_is_supported(value_type) {
                return None;
            }
            head_slot_count += 1;
        } else if let Some(slots) = abi_static_slot_count(value_type) {
            head_slot_count += slots;
        } else {
            return None;
        }
    }

    let pre_len = instructions.len();
    let mut value_locals = Vec::with_capacity(args.len());
    for (index, (arg, value_type)) in args.iter().zip(arg_types.iter()).enumerate() {
        if !lower_expression(arg, ctx, instructions) {
            instructions.truncate(pre_len);
            return Some(false);
        }
        let tmp_id = ctx.next_label();
        let local = ctx.allocate_local(
            format!("__abi_arg_{index}_{tmp_id}"),
            Some(value_type.clone()),
        );
        instructions.push(Instruction::StoreLocal(local));
        value_locals.push(local);
    }

    let offset_local = ctx.allocate_local("__abi_tail_offset".to_string(), None);
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
        (head_slot_count * 32) as u64,
    ))));
    instructions.push(Instruction::StoreLocal(offset_local));

    let mut tail_locals = Vec::new();
    let mut part_count = 0usize;

    for (local, value_type) in value_locals.iter().zip(arg_types.iter()) {
        if abi_value_type_is_dynamic(value_type) {
            instructions.push(Instruction::LoadLocal(offset_local));
            emit_abi_u256_slot(ctx, instructions);
            part_count += 1;

            instructions.push(Instruction::LoadLocal(*local));
            emit_abi_dynamic_tail_for_value_type(value_type, 0, ctx, instructions)?;
            let tail_local = ctx.allocate_local("__abi_tail".to_string(), None);
            instructions.push(Instruction::StoreLocal(tail_local));

            instructions.push(Instruction::LoadLocal(offset_local));
            instructions.push(Instruction::LoadLocal(tail_local));
            instructions.push(Instruction::GetSize);
            instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
            instructions.push(Instruction::StoreLocal(offset_local));
            tail_locals.push(tail_local);
        } else {
            let slots =
                emit_abi_static_slots_from_local(*local, value_type, ctx, instructions)?;
            part_count += slots;
        }
    }

    for tail_local in tail_locals {
        instructions.push(Instruction::LoadLocal(tail_local));
        part_count += 1;
    }

    if part_count == 0 {
        instructions.truncate(pre_len);
        return None;
    }

    instructions.push(Instruction::CallBuiltin {
        builtin: BuiltinCall::BytesConcat,
        arg_count: part_count,
    });
    Some(true)
}

fn lower_abi_encode_packed_args_direct_from_slice(
    args: &[Expression],
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) -> Option<bool> {
    if args.is_empty() {
        instructions.push(Instruction::PushLiteral(
            LiteralValue::ByteArray(Vec::new()),
        ));
        return Some(true);
    }

    let pre_len = instructions.len();
    for arg in args {
        if !lower_packed_abi_bytes_for_expr(arg, ctx, instructions)? {
            instructions.truncate(pre_len);
            return Some(false);
        }
    }

    instructions.push(Instruction::CallBuiltin {
        builtin: BuiltinCall::BytesConcat,
        arg_count: args.len(),
    });
    Some(true)
}

fn lower_static_abi_slots_for_expr(
    expr: &Expression,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
    flatten_struct_params: bool,
) -> Option<usize> {
    let value_type = infer_type_from_expression(expr, ctx)?;
    match value_type {
        ValueType::Struct { fields, .. } => {
            if fields.is_empty()
                || !fields
                    .iter()
                    .all(|field| is_static_abi_type_value(&field.ty))
            {
                return None;
            }

            if flatten_struct_params {
                if let Some((base_slot, field_count)) = resolve_struct_param_flat_slots(expr, ctx) {
                    if field_count != fields.len() {
                        return None;
                    }
                    for (index, field) in fields.iter().enumerate() {
                        instructions.push(Instruction::LoadParameter(base_slot + index));
                        emit_expr_static_abi_slot_for_value_type(&field.ty, ctx, instructions)?;
                    }
                    return Some(fields.len());
                }
            }

            let tmp_id = ctx.next_label();
            let struct_local = ctx.allocate_local(format!("__abi_static_struct_{tmp_id}"), None);
            if !lower_expression(expr, ctx, instructions) {
                return Some(0);
            }
            instructions.push(Instruction::StoreLocal(struct_local));

            for (index, field) in fields.iter().enumerate() {
                instructions.push(Instruction::LoadLocal(struct_local));
                instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
                    BigInt::from(index as u64),
                )));
                instructions.push(Instruction::ArrayGet);
                emit_expr_static_abi_slot_for_value_type(&field.ty, ctx, instructions)?;
            }
            Some(fields.len())
        }
        other if is_static_abi_type_value(&other) => {
            if !lower_expression(expr, ctx, instructions) {
                return Some(0);
            }
            emit_expr_static_abi_slot_for_value_type(&other, ctx, instructions)?;
            Some(1)
        }
        _ => None,
    }
}

fn emit_expr_static_abi_slot_for_value_type(
    value_type: &ValueType,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) -> Option<()> {
    match value_type {
        // Bug #23: signed integers must be sign-extended (0xff..) when negative,
        // not zero-padded. Route signed-true through the sign-aware buffer.
        ValueType::Integer { signed: true, .. } => {
            instructions.push(Instruction::Convert {
                target: ConvertTarget::ByteArray,
            });
            emit_abi_fixed_buffer_signed(ctx, instructions, 32);
            Some(())
        }
        ValueType::Integer { signed: false, .. } | ValueType::Boolean | ValueType::Address => {
            instructions.push(Instruction::Convert {
                target: ConvertTarget::ByteArray,
            });
            emit_abi_fixed_buffer(ctx, instructions, 32, true);
            Some(())
        }
        ValueType::ByteArray {
            fixed_len: Some(len),
        } if *len == 32 => Some(()),
        ValueType::ByteArray {
            fixed_len: Some(len),
        } if *len < 32 => {
            emit_abi_bytesn_slot(ctx, instructions, *len as usize);
            Some(())
        }
        _ => None,
    }
}

fn lower_packed_abi_bytes_for_expr(
    expr: &Expression,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) -> Option<bool> {
    let value_type = infer_type_from_expression(expr, ctx)?;
    let pre_len = instructions.len();
    if !lower_expression(expr, ctx, instructions) {
        return Some(false);
    }

    let lowered = match value_type {
        // Bug #23 (packed variant): negative signed integers must be
        // SIGN-EXTENDED (0xff fill) to their declared width, not zero-padded
        // — `abi.encodePacked(int16(-1))` is 0xffff, not 0x00ff. Route signed
        // through the sign-aware buffer at the packed width.
        ValueType::Integer { bits, signed: true } => {
            instructions.push(Instruction::Convert {
                target: ConvertTarget::ByteArray,
            });
            emit_abi_fixed_buffer_signed(ctx, instructions, (bits / 8) as usize);
            Some(true)
        }
        ValueType::Integer { bits, signed: false } => {
            instructions.push(Instruction::Convert {
                target: ConvertTarget::ByteArray,
            });
            emit_abi_fixed_buffer(ctx, instructions, (bits / 8) as usize, true);
            Some(true)
        }
        ValueType::Boolean => {
            instructions.push(Instruction::Convert {
                target: ConvertTarget::ByteArray,
            });
            emit_abi_fixed_buffer(ctx, instructions, 1, true);
            Some(true)
        }
        ValueType::Address => {
            instructions.push(Instruction::Convert {
                target: ConvertTarget::ByteArray,
            });
            emit_abi_fixed_buffer(ctx, instructions, 20, true);
            Some(true)
        }
        ValueType::ByteArray { fixed_len: Some(_) }
        | ValueType::ByteArray { fixed_len: None }
        | ValueType::String => Some(true),
        ValueType::Array(element_type) if is_static_abi_type_value(&element_type) => {
            emit_abi_packed_static_array(&element_type, ctx, instructions)?;
            Some(true)
        }
        _ => None,
    };

    if lowered.is_none() {
        instructions.truncate(pre_len);
    }
    lowered
}

fn lower_abi_decode_direct(
    args: &[Expression],
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) -> Option<bool> {
    if args.len() != 2 {
        return None;
    }

    let types = abi_decode_value_types(&args[1], ctx)?;
    if types.is_empty() {
        return None;
    }

    // Each declared decode type must be either static (single- or multi-slot,
    // mirroring the canonical ENCODE side which emits per-field 32-byte slots
    // for all-static structs) or one of the dynamic types we know how to walk
    // (string / bytes / T[] for static T). Bug #24/#25 fix: previously we only
    // accepted static-1-slot types here and fell through to
    // `StdLib.deserialize` (which is Neo-native, NOT EVM-ABI-compatible) for
    // any dynamic type, producing an opaque StackItem callers couldn't
    // `.length` / re-decode. The multi-slot extension closes the same
    // asymmetry for all-static structs: `abi.encode(S(7,9))` produces 64
    // canonical bytes, so `abi.decode(buf, (S))` must walk those slots
    // instead of handing raw ABI bytes to `StdLib.deserialize`.
    let supported = types
        .iter()
        .all(|value_type| {
            abi_static_slot_count(value_type).is_some()
                || abi_dynamic_decode_value_type_is_supported(value_type)
        });
    if !supported {
        return None;
    }

    let pre_len = instructions.len();
    if !lower_expression(&args[0], ctx, instructions) {
        instructions.truncate(pre_len);
        return Some(false);
    }

    let buffer_local = ctx.allocate_local("__abi_decode_buf".to_string(), None);
    instructions.push(Instruction::StoreLocal(buffer_local));

    let any_dynamic = types
        .iter()
        .any(abi_dynamic_decode_value_type_is_supported);

    if !any_dynamic {
        // All declared types are static; total payload size is the SUM of
        // each type's slot count × 32 (multi-slot structs occupy one slot
        // per field, mirroring the encode side). Mismatches panic 0x41.
        let expected_bytes: usize = types
            .iter()
            .map(|value_type| abi_static_slot_count(value_type).unwrap_or(1) * 32)
            .sum();
        let decode_ok_label = ctx.next_label();
        instructions.push(Instruction::LoadLocal(buffer_local));
        instructions.push(Instruction::GetSize);
        instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
            expected_bytes as u64,
        ))));
        // Only an UNDER-length buffer reverts; `abi.decode` ignores trailing
        // bytes (matches solc/ethers). Use `<` rather than `!=`.
        instructions.push(Instruction::BinaryOp(BinaryOperator::Lt));
        instructions.push(Instruction::JumpIf {
            target: decode_ok_label,
        });
        emit_panic(0x41, instructions);
        instructions.push(Instruction::Label(decode_ok_label));
    }
    // For the dynamic case we cannot statically know the total size; the
    // per-slot decoders bound-check the length / offset reads themselves.

    if types.len() == 1 {
        let value_type = &types[0];
        if abi_dynamic_decode_value_type_is_supported(value_type) {
            emit_abi_decode_dynamic_top_level(buffer_local, value_type, ctx, instructions);
        } else {
            emit_abi_decode_static_slot(buffer_local, 0, value_type, ctx, instructions);
        }
        return Some(true);
    }

    let tuple_local = ctx.allocate_local(
        "__abi_decode_tuple".to_string(),
        Some(ValueType::Array(Box::new(ValueType::Any))),
    );
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
        types.len() as u64,
    ))));
    instructions.push(Instruction::NewArray {
        element_type: ValueType::Any,
    });
    instructions.push(Instruction::StoreLocal(tuple_local));

    // Track the running HEAD slot separately from the tuple index: a
    // multi-slot static member (all-static struct) consumes one head slot
    // per field, shifting every subsequent member's slot position.
    let mut head_slot = 0usize;
    for (index, value_type) in types.iter().enumerate() {
        instructions.push(Instruction::LoadLocal(tuple_local));
        instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
            index as u64,
        ))));
        if abi_dynamic_decode_value_type_is_supported(value_type) {
            // Tuple member is dynamic: head slot at index `head_slot` is a
            // u256 byte-offset (relative to the start of the encoded
            // buffer) pointing at the value's tail. Walk that offset to
            // reach the length+payload (string/bytes) or length+elements
            // (static-element array).
            emit_abi_decode_dynamic_tuple_member(
                buffer_local,
                head_slot,
                value_type,
                ctx,
                instructions,
            );
            head_slot += 1;
        } else {
            emit_abi_decode_static_slot(buffer_local, head_slot, value_type, ctx, instructions);
            head_slot += abi_static_slot_count(value_type).unwrap_or(1);
        }
        instructions.push(Instruction::ArraySet);
    }

    instructions.push(Instruction::LoadLocal(tuple_local));
    Some(true)
}

/// Predicate matching dynamic ABI value types whose `abi.decode` lowering
/// is implemented by [`emit_abi_decode_dynamic_top_level`] /
/// [`emit_abi_decode_dynamic_tuple_member`].
///
/// Currently: `string`, `bytes` (= `ByteArray { fixed_len: None }`), and
/// `T[]` where `T` is a static ABI type (uint/int/address/bool/bytesN, or
/// an all-static struct occupying `abi_static_slot_count(T)` slots per
/// element) OR a supported dynamic type — i.e. nested-dynamic shapes
/// (`string[]`, `bytes[]`, `T[][]`) walked via
/// [`emit_abi_decode_nested_array_tail_runtime`]. The recursion mirrors the
/// ENCODE side's `abi_dynamic_value_type_is_supported` exactly, so every
/// canonically-encoded shape round-trips through `abi.decode`.
fn abi_dynamic_decode_value_type_is_supported(value_type: &ValueType) -> bool {
    match value_type {
        ValueType::ByteArray { fixed_len: None } | ValueType::String => true,
        ValueType::Array(element_type) => {
            abi_static_slot_count(element_type).is_some()
                || abi_dynamic_decode_value_type_is_supported(element_type)
        }
        // Dynamic struct: decodable when every field is static or a supported
        // dynamic shape (mirrors the encode-side predicate).
        ValueType::Struct { fields, .. } => {
            fields.iter().any(|f| abi_value_type_is_dynamic(&f.ty))
                && fields.iter().all(|f| {
                    abi_static_slot_count(&f.ty).is_some()
                        || abi_dynamic_decode_value_type_is_supported(&f.ty)
                })
        }
        _ => false,
    }
}

/// Decode a single top-level dynamic value from the encoded buffer in
/// `buffer_local`.
///
/// Layout produced by `abi.encode(x)` for a single dynamic `x`:
///   `BE32(0x20) || <tail at offset 0x20>`
/// i.e. a leading 32-byte head holding the offset 0x20 (= 32) of the tail,
/// followed by the tail payload (length + bytes for `string`/`bytes`, or
/// length + elements for `T[]`).
///
/// Stack on exit: `[decoded_value]` (ByteString for string/bytes, Array
/// of element values for `T[]`).
fn emit_abi_decode_dynamic_top_level(
    buffer_local: usize,
    value_type: &ValueType,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) {
    // Read the ACTUAL tail offset from head slot 0 rather than assuming the
    // canonical 0x20: a non-canonical (but valid) encoder may place the tail at
    // a different offset, and EVM decoders honor the encoded head pointer.
    let tmp_id = ctx.next_label();
    let offset_local = ctx.allocate_local(format!("__abi_dyn_top_off_{tmp_id}"), None);
    emit_abi_decode_u256_at(buffer_local, 0, ctx, instructions);
    instructions.push(Instruction::StoreLocal(offset_local));
    emit_abi_decode_dynamic_tail_runtime(buffer_local, offset_local, value_type, 0, ctx, instructions);
}

/// Decode a dynamic tuple member at head index `index`.
///
/// Reads the u256 offset from `buffer[index*32 .. index*32+32]` (which is
/// the byte offset of the member's tail relative to the start of the
/// encoded buffer) and dispatches to [`emit_abi_decode_dynamic_tail`] at
/// that runtime offset.
fn emit_abi_decode_dynamic_tuple_member(
    buffer_local: usize,
    index: usize,
    value_type: &ValueType,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) {
    // Read the offset slot. We can fold it through a temp local.
    let tmp_id = ctx.next_label();
    let offset_local = ctx.allocate_local(format!("__abi_dyn_off_{tmp_id}"), None);
    emit_abi_decode_u256_at(buffer_local, index * 32, ctx, instructions);
    instructions.push(Instruction::StoreLocal(offset_local));
    emit_abi_decode_dynamic_tail_runtime(
        buffer_local,
        offset_local,
        value_type,
        0,
        ctx,
        instructions,
    );
}

/// Same as [`emit_abi_decode_dynamic_tail`] but with the tail offset
/// supplied at runtime via `offset_local`. Used for tuple members where
/// the offset is read from a head slot.
fn emit_abi_decode_dynamic_tail_runtime(
    buffer_local: usize,
    offset_local: usize,
    value_type: &ValueType,
    depth: usize,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) {
    match value_type {
        ValueType::ByteArray { fixed_len: None } | ValueType::String => {
            emit_abi_decode_bytes_tail_runtime(buffer_local, offset_local, ctx, instructions);
        }
        ValueType::Array(element_type) if abi_static_slot_count(element_type).is_some() => {
            emit_abi_decode_static_element_array_tail_runtime(
                buffer_local,
                offset_local,
                element_type,
                ctx,
                instructions,
            );
        }
        // `T[]` with a dynamic element type (string[], bytes[], T[][]): each
        // head entry is itself a u256 offset (relative to the start of the
        // head section) pointing at that element's tail — decode recursively.
        ValueType::Array(element_type) => {
            emit_abi_decode_nested_array_tail_runtime(
                buffer_local,
                offset_local,
                element_type,
                depth,
                ctx,
                instructions,
            );
        }
        // Dynamic struct: walk the tuple head/tail at this offset.
        ValueType::Struct { fields, .. } => {
            emit_abi_decode_dynamic_struct_tail_runtime(
                buffer_local,
                offset_local,
                fields,
                depth,
                ctx,
                instructions,
            );
        }
        _ => {
            instructions.push(Instruction::PushLiteral(LiteralValue::ByteArray(Vec::new())));
        }
    }
}

/// Read the (length-/offset-shaped) u256 stored at byte offset
/// `byte_offset` inside `buffer_local` (BE-encoded 32-byte slot) and
/// push it as a NeoVM `Integer`.
///
/// The runtime's `CONVERT → Integer` of a >8-byte ByteArray returns a
/// signed-LE `ByteArray`, NOT an `Integer`, to preserve precision (see
/// `convert_item` in `runtime/execution/execution_impl_part3_conversion.rs`
/// and the Task #111 history). That breaks downstream callers (SUBSTR
/// `pop_usize`) which require a real Integer.
///
/// EVM-canonical length/offset slots are bounded by `usize::MAX` in
/// practice (calldata cannot exceed a few MB on any real chain, let alone
/// 2^64 bytes), so it is safe to read only the low 8 bytes of the slot
/// and rely on the ≤8-byte fast path of `convert_item` which produces an
/// `Integer(i64)`. The high 24 bytes of every well-formed length/offset
/// slot are zero — if a malicious / corrupted payload claims a length
/// exceeding `i64::MAX`, the subsequent `SUBSTR` will fault on bounds
/// anyway.
/// Reject a non-canonical length/offset slot whose HIGH 24 bytes are nonzero.
///
/// The slot readers trust only the low 8 bytes (calldata lengths/offsets never
/// exceed a few MB), but a crafted payload could set bytes [0..24) to encode a
/// value in `[2^64, 2^192)` whose low 64 bits happen to be small and in-bounds.
/// Reading only the low 8 bytes would then silently use the truncated value and
/// decode the wrong region instead of reverting. `offset_push` pushes the byte
/// offset of the slot start; Panic(0x41) fires when any high byte is set. A
/// conformant slot always has zero high bytes, so this never faults valid input.
fn emit_abi_decode_slot_high_bits_guard(
    buffer_local: usize,
    offset_push: Instruction,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) {
    let ok = ctx.next_label();
    instructions.push(Instruction::LoadLocal(buffer_local));
    instructions.push(offset_push);
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(24u8))));
    instructions.push(Instruction::Substr);
    instructions.push(Instruction::Convert {
        target: ConvertTarget::ByteArray,
    });
    instructions.push(Instruction::PushLiteral(LiteralValue::ByteArray(vec![0u8; 24])));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Eq));
    instructions.push(Instruction::LogicalNot); // true when the high 24 bytes are NONZERO
    // JumpIf -> JMPIFNOT: branch to `ok` when the nonzero flag is FALSE (i.e.
    // the high bytes are all zero); otherwise fall through to the panic.
    instructions.push(Instruction::JumpIf { target: ok });
    emit_panic(0x41, instructions);
    instructions.push(Instruction::Label(ok));
}

fn emit_abi_decode_u256_at(
    buffer_local: usize,
    byte_offset: usize,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) {
    emit_abi_decode_slot_high_bits_guard(
        buffer_local,
        Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(byte_offset as u64))),
        ctx,
        instructions,
    );
    instructions.push(Instruction::LoadLocal(buffer_local));
    // The low 8 bytes of the 32-byte BE slot live at `byte_offset + 24`.
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
        (byte_offset + 24) as u64,
    ))));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(8u8))));
    instructions.push(Instruction::Substr);
    instructions.push(Instruction::Convert {
        target: ConvertTarget::ByteArray,
    });
    // Reverse BE→LE so the ≤8-byte CONVERT→Integer path interprets the
    // bytes correctly.
    materialize_byte_array_buffer(ctx, instructions, true);
    instructions.push(Instruction::Convert {
        target: ConvertTarget::Integer,
    });
}

/// Read the u256 stored at the runtime byte offset held in `offset_local`.
/// Same low-8-bytes shortcut as [`emit_abi_decode_u256_at`].
fn emit_abi_decode_u256_at_runtime(
    buffer_local: usize,
    offset_local: usize,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) {
    emit_abi_decode_slot_high_bits_guard(
        buffer_local,
        Instruction::LoadLocal(offset_local),
        ctx,
        instructions,
    );
    instructions.push(Instruction::LoadLocal(buffer_local));
    // adj_offset = offset_local + 24 (skip the 24 BE high-zero bytes).
    instructions.push(Instruction::LoadLocal(offset_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(24u8))));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(8u8))));
    instructions.push(Instruction::Substr);
    instructions.push(Instruction::Convert {
        target: ConvertTarget::ByteArray,
    });
    materialize_byte_array_buffer(ctx, instructions, true);
    instructions.push(Instruction::Convert {
        target: ConvertTarget::Integer,
    });
}

/// Decode a `string` / `bytes` tail at a runtime byte offset.
fn emit_abi_decode_bytes_tail_runtime(
    buffer_local: usize,
    offset_local: usize,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) {
    let tmp_id = ctx.next_label();
    let len_local = ctx.allocate_local(format!("__abi_dec_rblen_{tmp_id}"), None);

    emit_abi_decode_u256_at_runtime(buffer_local, offset_local, ctx, instructions);
    instructions.push(Instruction::StoreLocal(len_local));

    instructions.push(Instruction::LoadLocal(buffer_local));
    // payload starts at offset_local + 32.
    instructions.push(Instruction::LoadLocal(offset_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(32u8))));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
    instructions.push(Instruction::LoadLocal(len_local));
    instructions.push(Instruction::Substr);
    instructions.push(Instruction::Convert {
        target: ConvertTarget::ByteArray,
    });
}

/// Decode a `T[]` tail at a runtime byte offset (tuple-member case).
fn emit_abi_decode_static_element_array_tail_runtime(
    buffer_local: usize,
    offset_local: usize,
    element_type: &ValueType,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) {
    let element_byte_len = abi_static_slot_count(element_type).unwrap_or(1) * 32;
    let tmp_id = ctx.next_label();
    let len_local = ctx.allocate_local(format!("__abi_dec_ralen_{tmp_id}"), None);
    let base_local = ctx.allocate_local(format!("__abi_dec_rabase_{tmp_id}"), None);
    let arr_local = ctx.allocate_local(
        format!("__abi_dec_rarr_{tmp_id}"),
        Some(ValueType::Array(Box::new(element_type.clone()))),
    );
    let idx_local = ctx.allocate_local(format!("__abi_dec_raidx_{tmp_id}"), None);
    let elem_off_local = ctx.allocate_local(format!("__abi_dec_raelmoff_{tmp_id}"), None);

    emit_abi_decode_u256_at_runtime(buffer_local, offset_local, ctx, instructions);
    instructions.push(Instruction::StoreLocal(len_local));

    // base = offset_local + 32 (first element).
    instructions.push(Instruction::LoadLocal(offset_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(32u8))));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
    instructions.push(Instruction::StoreLocal(base_local));

    instructions.push(Instruction::LoadLocal(len_local));
    instructions.push(Instruction::NewArray {
        element_type: element_type.clone(),
    });
    instructions.push(Instruction::StoreLocal(arr_local));

    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::zero())));
    instructions.push(Instruction::StoreLocal(idx_local));

    let loop_label = ctx.next_label();
    let end_label = ctx.next_label();
    instructions.push(Instruction::Label(loop_label));
    instructions.push(Instruction::LoadLocal(idx_local));
    instructions.push(Instruction::LoadLocal(len_local));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Lt));
    instructions.push(Instruction::JumpIf { target: end_label });

    // elem_off = base + idx * element_byte_len.
    instructions.push(Instruction::LoadLocal(idx_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
        element_byte_len as u64,
    ))));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Mul));
    instructions.push(Instruction::LoadLocal(base_local));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
    instructions.push(Instruction::StoreLocal(elem_off_local));

    instructions.push(Instruction::LoadLocal(arr_local));
    instructions.push(Instruction::LoadLocal(idx_local));
    emit_abi_decode_static_slot_at_runtime_offset(buffer_local, elem_off_local, element_type, ctx, instructions);
    instructions.push(Instruction::ArraySet);

    instructions.push(Instruction::LoadLocal(idx_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::one())));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
    instructions.push(Instruction::StoreLocal(idx_local));
    instructions.push(Instruction::Jump { target: loop_label });
    instructions.push(Instruction::Label(end_label));

    instructions.push(Instruction::LoadLocal(arr_local));
}

/// Decode a `T[]` tail whose element type `T` is itself dynamic (string[],
/// bytes[], T[][]) at a runtime byte offset. The mirror of
/// [`emit_abi_dynamic_nested_array_tail`]: read the length, then for each
/// element read its offset (relative to the start of the head section) from
/// the head entry and decode the element tail recursively at that absolute
/// offset. Stack on exit: `[Array<decoded elements>]`.
fn emit_abi_decode_nested_array_tail_runtime(
    buffer_local: usize,
    offset_local: usize,
    element_type: &ValueType,
    depth: usize,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) {
    // Six reusable scratch locals for this nesting depth (see the encode-side
    // `emit_abi_dynamic_nested_array_tail` for the pooling rationale).
    let scratch = ctx.abi_nested_scratch_locals(depth, 6);
    let len_local = scratch[0];
    let base_local = scratch[1];
    let arr_local = scratch[2];
    let idx_local = scratch[3];
    let head_off_local = scratch[4];
    let elem_off_local = scratch[5];

    // n = length word at the tail offset.
    emit_abi_decode_u256_at_runtime(buffer_local, offset_local, ctx, instructions);
    instructions.push(Instruction::StoreLocal(len_local));

    // base = offset_local + 32 (start of the head section; element offsets are
    // relative to here).
    instructions.push(Instruction::LoadLocal(offset_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(32u8))));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
    instructions.push(Instruction::StoreLocal(base_local));

    instructions.push(Instruction::LoadLocal(len_local));
    instructions.push(Instruction::NewArray {
        element_type: element_type.clone(),
    });
    instructions.push(Instruction::StoreLocal(arr_local));

    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::zero())));
    instructions.push(Instruction::StoreLocal(idx_local));

    let loop_label = ctx.next_label();
    let end_label = ctx.next_label();
    instructions.push(Instruction::Label(loop_label));
    instructions.push(Instruction::LoadLocal(idx_local));
    instructions.push(Instruction::LoadLocal(len_local));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Lt));
    instructions.push(Instruction::JumpIf { target: end_label });

    // head_off = base + idx*32 (byte position of element idx's head entry).
    instructions.push(Instruction::LoadLocal(idx_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(32u8))));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Mul));
    instructions.push(Instruction::LoadLocal(base_local));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
    instructions.push(Instruction::StoreLocal(head_off_local));

    // elem_off = base + relative_offset(head_off).
    instructions.push(Instruction::LoadLocal(base_local));
    emit_abi_decode_u256_at_runtime(buffer_local, head_off_local, ctx, instructions);
    instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
    instructions.push(Instruction::StoreLocal(elem_off_local));

    // arr[idx] = decode_dynamic_tail(elem_off, element_type)  (recursive)
    instructions.push(Instruction::LoadLocal(arr_local));
    instructions.push(Instruction::LoadLocal(idx_local));
    emit_abi_decode_dynamic_tail_runtime(
        buffer_local,
        elem_off_local,
        element_type,
        depth + 1,
        ctx,
        instructions,
    );
    instructions.push(Instruction::ArraySet);

    instructions.push(Instruction::LoadLocal(idx_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::one())));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
    instructions.push(Instruction::StoreLocal(idx_local));
    instructions.push(Instruction::Jump { target: loop_label });
    instructions.push(Instruction::Label(end_label));

    instructions.push(Instruction::LoadLocal(arr_local));
}

/// Decode a DYNAMIC struct (≥1 dynamic field) tail at a runtime byte offset
/// into a fresh `StackItem::Array` of field values — the mirror of
/// [`emit_abi_dynamic_struct_tail`]. The head section layout is statically
/// known from the field types (static fields inline, dynamic fields one
/// offset word each), so the per-field head position is a compile-time
/// constant; dynamic fields read a relative offset and decode their tail
/// recursively. Stack on exit: `[Array<field values>]`.
fn emit_abi_decode_dynamic_struct_tail_runtime(
    buffer_local: usize,
    offset_local: usize,
    fields: &[StructField],
    depth: usize,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) {
    let tmp_id = ctx.next_label();
    let struct_local = ctx.allocate_local(format!("__abi_dec_dstruct_{tmp_id}"), None);
    let field_off_local = ctx.allocate_local(format!("__abi_dec_dstruct_foff_{tmp_id}"), None);

    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
        fields.len() as u64,
    ))));
    instructions.push(Instruction::NewArray {
        element_type: ValueType::Any,
    });
    instructions.push(Instruction::StoreLocal(struct_local));

    let mut head_byte_offset = 0usize;
    for (field_index, field) in fields.iter().enumerate() {
        if abi_value_type_is_dynamic(&field.ty) {
            // head slot position = offset_local + head_byte_offset.
            instructions.push(Instruction::LoadLocal(offset_local));
            instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
                head_byte_offset as u64,
            ))));
            instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
            instructions.push(Instruction::StoreLocal(field_off_local));
            // absolute tail offset = offset_local + rel(head slot).
            instructions.push(Instruction::LoadLocal(offset_local));
            emit_abi_decode_u256_at_runtime(buffer_local, field_off_local, ctx, instructions);
            instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
            instructions.push(Instruction::StoreLocal(field_off_local));
            // arr[field_index] = decode_dynamic_tail(field_off, field.ty)
            instructions.push(Instruction::LoadLocal(struct_local));
            instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
                field_index as u64,
            ))));
            emit_abi_decode_dynamic_tail_runtime(
                buffer_local,
                field_off_local,
                &field.ty,
                depth + 1,
                ctx,
                instructions,
            );
            instructions.push(Instruction::ArraySet);
            head_byte_offset += 32;
        } else {
            // static field at offset_local + head_byte_offset.
            instructions.push(Instruction::LoadLocal(offset_local));
            instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
                head_byte_offset as u64,
            ))));
            instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
            instructions.push(Instruction::StoreLocal(field_off_local));
            instructions.push(Instruction::LoadLocal(struct_local));
            instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
                field_index as u64,
            ))));
            emit_abi_decode_static_slot_at_runtime_offset(
                buffer_local,
                field_off_local,
                &field.ty,
                ctx,
                instructions,
            );
            instructions.push(Instruction::ArraySet);
            head_byte_offset += abi_static_slot_count(&field.ty).unwrap_or(1) * 32;
        }
    }

    instructions.push(Instruction::LoadLocal(struct_local));
}

/// Convert the little-endian byte Buffer on top of the stack into an
/// UNSIGNED integer.
///
/// NeoVM `CONVERT → Integer` interprets byte buffers as SIGNED
/// little-endian, so a canonical uint256 slot with the top bit set
/// (value >= 2^255) would decode negative — `abi.decode(abi.encode(
/// type(uint256).max), (uint256))` yielded -1. When the signed
/// interpretation is negative we append a single 0x00 sign byte before
/// the convert, matching the sign-byte discipline the wide bitwise path
/// already uses (`u256_bigint_to_stack_item` in
/// `runtime/execution/helpers/bitwise.rs`, Task #118). The append is
/// CONDITIONAL on negativity so the common case (< 2^255) keeps the
/// plain 32-byte convert.
///
/// Stack on entry: `[le_bytes_buffer]`.
/// Stack on exit:  `[unsigned_integer]`.
fn emit_le_buffer_to_unsigned_integer(
    _ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) {
    // The 32-byte little-endian slot buffer IS the conformant uint256
    // representation: a 32-byte two's-complement integer. Reading it as a signed
    // NeoVM integer yields the canonical value — a `uint256 >= 2^255` reads back
    // as its negative two's-complement, byte-identical to the same value produced
    // by a literal or by arithmetic, so `abi.decode(abi.encode(x)) == x` holds.
    //
    // The previous code appended a `0x00` sign byte to coerce values >= 2^255
    // into a POSITIVE 33-byte magnitude — the old unsigned-magnitude model, which
    // is non-conformant (a real node stores two's-complement) and not equal to
    // the two's-complement form the rest of the runtime uses.
    instructions.push(Instruction::Convert {
        target: ConvertTarget::Integer,
    });
}

/// Decode a single static element at a runtime byte offset inside
/// `buffer_local`. Mirrors [`emit_abi_decode_static_slot`] but operates
/// at a runtime offset rather than a compile-time slot index.
fn emit_abi_decode_static_slot_at_runtime_offset(
    buffer_local: usize,
    offset_local: usize,
    value_type: &ValueType,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) {
    match value_type {
        // Unsigned integers must NOT be read with NeoVM's signed-LE
        // CONVERT semantics — see `emit_le_buffer_to_unsigned_integer`.
        ValueType::Integer { signed: false, .. } => {
            instructions.push(Instruction::LoadLocal(buffer_local));
            instructions.push(Instruction::LoadLocal(offset_local));
            instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
                32u8,
            ))));
            instructions.push(Instruction::Substr);
            instructions.push(Instruction::Convert {
                target: ConvertTarget::ByteArray,
            });
            materialize_byte_array_buffer(ctx, instructions, true);
            emit_le_buffer_to_unsigned_integer(ctx, instructions);
        }
        ValueType::Integer { signed: true, .. } | ValueType::Boolean => {
            instructions.push(Instruction::LoadLocal(buffer_local));
            instructions.push(Instruction::LoadLocal(offset_local));
            instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
                32u8,
            ))));
            instructions.push(Instruction::Substr);
            instructions.push(Instruction::Convert {
                target: ConvertTarget::ByteArray,
            });
            materialize_byte_array_buffer(ctx, instructions, true);
            instructions.push(Instruction::Convert {
                target: ConvertTarget::Integer,
            });
        }
        // All-static struct element: decode each field from its consecutive
        // 32-byte slot into a fresh `StackItem::Array` (the Array-of-fields
        // shape the struct-constructor lowering produces and the encode
        // side reads back via ArrayGet).
        ValueType::Struct { fields, .. } => {
            let tmp_id = ctx.next_label();
            let struct_local =
                ctx.allocate_local(format!("__abi_dec_rstruct_{tmp_id}"), None);
            let field_off_local =
                ctx.allocate_local(format!("__abi_dec_rstruct_off_{tmp_id}"), None);
            instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
                fields.len() as u64,
            ))));
            instructions.push(Instruction::NewArray {
                element_type: ValueType::Any,
            });
            instructions.push(Instruction::StoreLocal(struct_local));
            let mut field_byte_offset = 0usize;
            for (field_index, field) in fields.iter().enumerate() {
                // field_off = offset_local + field_byte_offset.
                instructions.push(Instruction::LoadLocal(offset_local));
                instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
                    BigInt::from(field_byte_offset as u64),
                )));
                instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
                instructions.push(Instruction::StoreLocal(field_off_local));

                instructions.push(Instruction::LoadLocal(struct_local));
                instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
                    BigInt::from(field_index as u64),
                )));
                emit_abi_decode_static_slot_at_runtime_offset(
                    buffer_local,
                    field_off_local,
                    &field.ty,
                    ctx,
                    instructions,
                );
                instructions.push(Instruction::ArraySet);
                field_byte_offset += abi_static_slot_count(&field.ty).unwrap_or(1) * 32;
            }
            instructions.push(Instruction::LoadLocal(struct_local));
        }
        ValueType::Address => {
            // EVM ABI: addresses are 20 bytes left-padded with 12 zero
            // bytes inside a 32-byte slot, so the value lives in
            // `[slot+12 .. slot+32)`.
            instructions.push(Instruction::LoadLocal(buffer_local));
            instructions.push(Instruction::LoadLocal(offset_local));
            instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
                12u8,
            ))));
            instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
            instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
                20u8,
            ))));
            instructions.push(Instruction::Substr);
            instructions.push(Instruction::Convert {
                target: ConvertTarget::ByteArray,
            });
            materialize_byte_array_buffer(ctx, instructions, true);
        }
        ValueType::ByteArray {
            fixed_len: Some(len),
        } => {
            let len = (*len).min(32) as usize;
            instructions.push(Instruction::LoadLocal(buffer_local));
            instructions.push(Instruction::LoadLocal(offset_local));
            instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
                len as u64,
            ))));
            instructions.push(Instruction::Substr);
            instructions.push(Instruction::Convert {
                target: ConvertTarget::ByteArray,
            });
        }
        _ => {
            instructions.push(Instruction::LoadLocal(buffer_local));
            instructions.push(Instruction::LoadLocal(offset_local));
            instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
                32u8,
            ))));
            instructions.push(Instruction::Substr);
            instructions.push(Instruction::Convert {
                target: ConvertTarget::ByteArray,
            });
        }
    }
}

fn lower_neo_serialized_arg_array(
    args: &[Expression],
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) -> bool {
    let tmp_id = ctx.next_label();
    let array_local = ctx.allocate_local(format!("__neo_serialized_args_{tmp_id}"), None);

    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
        args.len() as u64,
    ))));
    instructions.push(Instruction::NewArray {
        element_type: ValueType::Any,
    });
    instructions.push(Instruction::StoreLocal(array_local));

    let mut success = true;
    for (index, arg) in args.iter().enumerate() {
        instructions.push(Instruction::LoadLocal(array_local));
        instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
            index as u64,
        ))));
        if !lower_expression(arg, ctx, instructions) {
            success = false;
            instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::zero())));
        }
        instructions.push(Instruction::ArraySet);
    }

    instructions.push(Instruction::LoadLocal(array_local));
    instructions.push(Instruction::CallBuiltin {
        builtin: BuiltinCall::NativeCall {
            contract: NativeContract::StdLib,
            method: "serialize".to_string(),
        },
        arg_count: 1,
    });

    success
}

fn abi_decode_value_types(
    types_expr: &Expression,
    ctx: &LoweringContext,
) -> Option<Vec<ValueType>> {
    match types_expr {
        Expression::List(_, params) => params
            .iter()
            .map(|(_, param)| {
                param
                    .as_ref()
                    .and_then(|parameter| infer_type_from_expression(&parameter.ty, ctx))
            })
            .collect(),
        Expression::Parenthesis(_, inner) => infer_type_from_expression(inner, ctx).map(|ty| vec![ty]),
        other => infer_type_from_expression(other, ctx).map(|ty| vec![ty]),
    }
}

fn abi_static_slot_count(value_type: &ValueType) -> Option<usize> {
    match value_type {
        ValueType::Struct { fields, .. }
            if !fields.is_empty()
                && fields.iter().all(|field| is_static_abi_type_value(&field.ty)) =>
        {
            Some(fields.len())
        }
        other if is_static_abi_type_value(other) => Some(1),
        _ => None,
    }
}

fn abi_value_type_is_dynamic(value_type: &ValueType) -> bool {
    match value_type {
        ValueType::ByteArray { fixed_len: None } | ValueType::String | ValueType::Array(_) => true,
        // A struct is dynamic iff any field is (recursively) dynamic — solc's
        // tuple rule. An all-static struct stays static (a flat run of inline
        // head slots); a struct with a string/bytes/array/dynamic-struct field
        // needs the head+tail layout.
        ValueType::Struct { fields, .. } => fields.iter().any(|f| abi_value_type_is_dynamic(&f.ty)),
        _ => false,
    }
}

fn abi_dynamic_value_type_is_supported(value_type: &ValueType) -> bool {
    match value_type {
        ValueType::ByteArray { fixed_len: None } | ValueType::String => true,
        // A `T[]` is encodable when its elements are either fixed-width
        // (head-only, e.g. `uint256[]`) or themselves a supported dynamic
        // shape (head+tail, e.g. `string[]`, `bytes[]`, `uint256[][]`). The
        // recursion mirrors `emit_abi_dynamic_tail_for_value_type`.
        ValueType::Array(element_type) => {
            abi_static_slot_count(element_type).is_some()
                || abi_dynamic_value_type_is_supported(element_type)
        }
        // Dynamic struct (has ≥1 dynamic field): encodable when EVERY field is
        // itself encodable (static or supported-dynamic). Encoded as a tuple.
        ValueType::Struct { fields, .. } => {
            fields.iter().any(|f| abi_value_type_is_dynamic(&f.ty))
                && fields.iter().all(|f| {
                    abi_static_slot_count(&f.ty).is_some()
                        || abi_dynamic_value_type_is_supported(&f.ty)
                })
        }
        _ => false,
    }
}

fn emit_abi_static_slots_from_local(
    local: usize,
    value_type: &ValueType,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) -> Option<usize> {
    match value_type {
        ValueType::Struct { fields, .. }
            if !fields.is_empty()
                && fields.iter().all(|field| is_static_abi_type_value(&field.ty)) =>
        {
            for (index, field) in fields.iter().enumerate() {
                instructions.push(Instruction::LoadLocal(local));
                instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
                    index as u64,
                ))));
                instructions.push(Instruction::ArrayGet);
                emit_expr_static_abi_slot_for_value_type(&field.ty, ctx, instructions)?;
            }
            Some(fields.len())
        }
        other if is_static_abi_type_value(other) => {
            instructions.push(Instruction::LoadLocal(local));
            emit_expr_static_abi_slot_for_value_type(other, ctx, instructions)?;
            Some(1)
        }
        _ => None,
    }
}

fn emit_abi_encode_single_stack_value_for_type(
    value_type: &ValueType,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) -> Option<()> {
    if abi_value_type_is_dynamic(value_type) {
        if !abi_dynamic_value_type_is_supported(value_type) {
            return None;
        }

        let value_local = ctx.allocate_local("__abi_single_value".to_string(), None);
        instructions.push(Instruction::StoreLocal(value_local));
        instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
            32u8,
        ))));
        emit_abi_u256_slot(ctx, instructions);
        instructions.push(Instruction::LoadLocal(value_local));
        emit_abi_dynamic_tail_for_value_type(value_type, 0, ctx, instructions)?;
        instructions.push(Instruction::CallBuiltin {
            builtin: BuiltinCall::BytesConcat,
            arg_count: 2,
        });
        return Some(());
    }

    if abi_static_slot_count(value_type) == Some(1) {
        emit_expr_static_abi_slot_for_value_type(value_type, ctx, instructions)?;
        return Some(());
    }

    None
}

fn emit_abi_dynamic_tail_for_value_type(
    value_type: &ValueType,
    depth: usize,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) -> Option<()> {
    match value_type {
        ValueType::ByteArray { fixed_len: None } | ValueType::String => {
            emit_abi_dynamic_bytes_tail(ctx, instructions);
            Some(())
        }
        ValueType::Array(element_type) if abi_static_slot_count(element_type).is_some() => {
            emit_abi_dynamic_static_array_tail(element_type, ctx, instructions)
        }
        // `T[]` where each element is itself dynamic (string[], bytes[],
        // uint256[][], ...). The element offsets form a head section and the
        // element encodings a tail section, recursively — full EVM layout.
        ValueType::Array(element_type)
            if abi_dynamic_value_type_is_supported(element_type) =>
        {
            emit_abi_dynamic_nested_array_tail(element_type, depth, ctx, instructions)
        }
        // Dynamic struct → encode as a tuple of its fields (head+tail).
        ValueType::Struct { fields, .. }
            if abi_dynamic_value_type_is_supported(value_type) =>
        {
            emit_abi_dynamic_struct_tail(fields, depth, ctx, instructions)
        }
        _ => None,
    }
}

fn emit_abi_dynamic_bytes_tail(
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) {
    let tmp_id = ctx.next_label();
    let src_local = ctx.allocate_local(format!("__abi_dyn_bytes_src_{tmp_id}"), None);
    let len_local = ctx.allocate_local(format!("__abi_dyn_bytes_len_{tmp_id}"), None);
    let padded_len_local =
        ctx.allocate_local(format!("__abi_dyn_bytes_padded_len_{tmp_id}"), None);
    let padded_local = ctx.allocate_local(format!("__abi_dyn_bytes_padded_{tmp_id}"), None);
    let len_slot_local = ctx.allocate_local(format!("__abi_dyn_bytes_len_slot_{tmp_id}"), None);

    instructions.push(Instruction::StoreLocal(src_local));
    instructions.push(Instruction::LoadLocal(src_local));
    instructions.push(Instruction::GetSize);
    instructions.push(Instruction::StoreLocal(len_local));

    instructions.push(Instruction::LoadLocal(len_local));
    emit_abi_u256_slot(ctx, instructions);
    instructions.push(Instruction::StoreLocal(len_slot_local));

    instructions.push(Instruction::LoadLocal(len_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
        31u8,
    ))));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
        32u8,
    ))));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Div));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
        32u8,
    ))));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Mul));
    instructions.push(Instruction::StoreLocal(padded_len_local));

    instructions.push(Instruction::LoadLocal(padded_len_local));
    instructions.push(Instruction::NewBuffer);
    instructions.push(Instruction::StoreLocal(padded_local));

    instructions.push(Instruction::LoadLocal(padded_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::zero())));
    instructions.push(Instruction::LoadLocal(src_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::zero())));
    instructions.push(Instruction::LoadLocal(len_local));
    instructions.push(Instruction::MemCpy);

    instructions.push(Instruction::LoadLocal(len_slot_local));
    instructions.push(Instruction::LoadLocal(padded_local));
    instructions.push(Instruction::Convert {
        target: ConvertTarget::ByteArray,
    });
    instructions.push(Instruction::CallBuiltin {
        builtin: BuiltinCall::BytesConcat,
        arg_count: 2,
    });
}

fn emit_abi_dynamic_static_array_tail(
    element_type: &ValueType,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) -> Option<()> {
    emit_abi_static_array_buffer(element_type, ctx, instructions, true)
}

/// Emit the ABI tail for a `T[]` whose element type `T` is itself dynamic
/// (e.g. `string[]`, `bytes[]`, `uint256[][]`). Consumes the array value from
/// the top of the stack and leaves the encoded tail (a `ByteString`) in its
/// place. Layout (all offsets relative to the start of the head section, i.e.
/// the slot immediately after the length word — standard EVM ABI):
///
/// ```text
///   [ length n ]                                  # 32-byte word
///   [ off_0 ][ off_1 ] ... [ off_{n-1} ]          # head: n × 32-byte words
///   [ tail_0 ][ tail_1 ] ... [ tail_{n-1} ]       # tail: element encodings
/// ```
///
/// where `off_i = n*32 + Σ_{j<i} len(tail_j)` and each `tail_i` is produced by
/// recursively encoding element `i` via [`emit_abi_dynamic_tail_for_value_type`].
fn emit_abi_dynamic_nested_array_tail(
    element_type: &ValueType,
    depth: usize,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) -> Option<()> {
    // Seven reusable scratch locals for this nesting depth. Distinct depths
    // never collide (the inner element is encoded while these are live); call
    // sites at the same depth share the block.
    let scratch = ctx.abi_nested_scratch_locals(depth, 7);
    let arr_local = scratch[0];
    let n_local = scratch[1];
    let off_local = scratch[2];
    let heads_local = scratch[3];
    let tails_local = scratch[4];
    let idx_local = scratch[5];
    let et_local = scratch[6];

    // arr := top of stack; n := arr.length
    instructions.push(Instruction::StoreLocal(arr_local));
    instructions.push(Instruction::LoadLocal(arr_local));
    instructions.push(Instruction::GetSize);
    instructions.push(Instruction::StoreLocal(n_local));

    // off := n * 32  (head section size; first element tail begins here)
    instructions.push(Instruction::LoadLocal(n_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
        32u8,
    ))));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Mul));
    instructions.push(Instruction::StoreLocal(off_local));

    // heads := "" ; tails := ""
    instructions.push(Instruction::PushLiteral(LiteralValue::ByteArray(Vec::new())));
    instructions.push(Instruction::StoreLocal(heads_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::ByteArray(Vec::new())));
    instructions.push(Instruction::StoreLocal(tails_local));

    // idx := 0
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::zero())));
    instructions.push(Instruction::StoreLocal(idx_local));

    let loop_label = ctx.next_label();
    let end_label = ctx.next_label();
    instructions.push(Instruction::Label(loop_label));
    // while idx < n  (JumpIf -> JMPIFNOT exits when the condition is false)
    instructions.push(Instruction::LoadLocal(idx_local));
    instructions.push(Instruction::LoadLocal(n_local));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Lt));
    instructions.push(Instruction::JumpIf { target: end_label });

    // et := encode(arr[idx])  (recursive element tail)
    instructions.push(Instruction::LoadLocal(arr_local));
    instructions.push(Instruction::LoadLocal(idx_local));
    instructions.push(Instruction::ArrayGet);
    emit_abi_dynamic_tail_for_value_type(element_type, depth + 1, ctx, instructions)?;
    instructions.push(Instruction::StoreLocal(et_local));

    // heads := heads ++ u256_slot(off)
    instructions.push(Instruction::LoadLocal(heads_local));
    instructions.push(Instruction::LoadLocal(off_local));
    emit_abi_u256_slot(ctx, instructions);
    instructions.push(Instruction::CallBuiltin {
        builtin: BuiltinCall::BytesConcat,
        arg_count: 2,
    });
    instructions.push(Instruction::StoreLocal(heads_local));

    // off := off + len(et)
    instructions.push(Instruction::LoadLocal(off_local));
    instructions.push(Instruction::LoadLocal(et_local));
    instructions.push(Instruction::GetSize);
    instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
    instructions.push(Instruction::StoreLocal(off_local));

    // tails := tails ++ et
    instructions.push(Instruction::LoadLocal(tails_local));
    instructions.push(Instruction::LoadLocal(et_local));
    instructions.push(Instruction::CallBuiltin {
        builtin: BuiltinCall::BytesConcat,
        arg_count: 2,
    });
    instructions.push(Instruction::StoreLocal(tails_local));

    // idx := idx + 1
    instructions.push(Instruction::LoadLocal(idx_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::one())));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
    instructions.push(Instruction::StoreLocal(idx_local));
    instructions.push(Instruction::Jump { target: loop_label });
    instructions.push(Instruction::Label(end_label));

    // result := u256_slot(n) ++ heads ++ tails
    instructions.push(Instruction::LoadLocal(n_local));
    emit_abi_u256_slot(ctx, instructions);
    instructions.push(Instruction::LoadLocal(heads_local));
    instructions.push(Instruction::LoadLocal(tails_local));
    instructions.push(Instruction::CallBuiltin {
        builtin: BuiltinCall::BytesConcat,
        arg_count: 3,
    });
    Some(())
}

/// Emit the ABI tail for a DYNAMIC struct (one with ≥1 dynamic field).
/// Consumes the struct value (a NeoVM `Array` of field values) from the top
/// of the stack and leaves its tuple encoding (a `ByteString`). The layout
/// is the standard EVM tuple: a head section (static fields inline, dynamic
/// fields as 32-byte offsets relative to the start of the head) followed by
/// the dynamic-field tails — identical to `lower_abi_encode_head_tail_direct`
/// but reading fields from the struct array rather than argument expressions.
fn emit_abi_dynamic_struct_tail(
    fields: &[StructField],
    depth: usize,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) -> Option<()> {
    // Head size in 32-byte words: dynamic fields take one offset word; static
    // fields occupy their inline slot count.
    let mut head_slot_count = 0usize;
    for field in fields {
        if abi_value_type_is_dynamic(&field.ty) {
            if !abi_dynamic_value_type_is_supported(&field.ty) {
                return None;
            }
            head_slot_count += 1;
        } else if let Some(slots) = abi_static_slot_count(&field.ty) {
            head_slot_count += slots;
        } else {
            return None;
        }
    }

    let tmp_id = ctx.next_label();
    let struct_local = ctx.allocate_local(format!("__abi_dstruct_{tmp_id}"), None);
    instructions.push(Instruction::StoreLocal(struct_local));

    let offset_local = ctx.allocate_local(format!("__abi_dstruct_off_{tmp_id}"), None);
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
        (head_slot_count * 32) as u64,
    ))));
    instructions.push(Instruction::StoreLocal(offset_local));

    let mut tail_locals = Vec::new();
    let mut part_count = 0usize;

    for (field_index, field) in fields.iter().enumerate() {
        if abi_value_type_is_dynamic(&field.ty) {
            // Head: the offset word pointing at this field's tail.
            instructions.push(Instruction::LoadLocal(offset_local));
            emit_abi_u256_slot(ctx, instructions);
            part_count += 1;

            // Compute the field tail and stash it for the tail section.
            instructions.push(Instruction::LoadLocal(struct_local));
            instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
                field_index as u64,
            ))));
            instructions.push(Instruction::ArrayGet);
            emit_abi_dynamic_tail_for_value_type(&field.ty, depth + 1, ctx, instructions)?;
            let tail_local =
                ctx.allocate_local(format!("__abi_dstruct_tail_{tmp_id}_{field_index}"), None);
            instructions.push(Instruction::StoreLocal(tail_local));

            // offset += len(tail)
            instructions.push(Instruction::LoadLocal(offset_local));
            instructions.push(Instruction::LoadLocal(tail_local));
            instructions.push(Instruction::GetSize);
            instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
            instructions.push(Instruction::StoreLocal(offset_local));
            tail_locals.push(tail_local);
        } else {
            // Static field: inline its slot(s) into the head section.
            instructions.push(Instruction::LoadLocal(struct_local));
            instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
                field_index as u64,
            ))));
            instructions.push(Instruction::ArrayGet);
            let slots = emit_abi_static_slots_for_stack_value(&field.ty, ctx, instructions)?;
            part_count += slots;
        }
    }

    for tail_local in tail_locals {
        instructions.push(Instruction::LoadLocal(tail_local));
        part_count += 1;
    }

    if part_count == 0 {
        return None;
    }
    instructions.push(Instruction::CallBuiltin {
        builtin: BuiltinCall::BytesConcat,
        arg_count: part_count,
    });
    Some(())
}

fn emit_abi_packed_static_array(
    element_type: &ValueType,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) -> Option<()> {
    emit_abi_static_array_buffer(element_type, ctx, instructions, false)
}

fn emit_abi_static_slots_for_stack_value(
    value_type: &ValueType,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) -> Option<usize> {
    match value_type {
        ValueType::Struct { fields, .. }
            if !fields.is_empty()
                && fields.iter().all(|field| is_static_abi_type_value(&field.ty)) =>
        {
            let tmp_id = ctx.next_label();
            let struct_local = ctx.allocate_local(format!("__abi_stack_struct_{tmp_id}"), None);
            instructions.push(Instruction::StoreLocal(struct_local));
            for (index, field) in fields.iter().enumerate() {
                instructions.push(Instruction::LoadLocal(struct_local));
                instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
                    index as u64,
                ))));
                instructions.push(Instruction::ArrayGet);
                emit_expr_static_abi_slot_for_value_type(&field.ty, ctx, instructions)?;
            }
            Some(fields.len())
        }
        other if is_static_abi_type_value(other) => {
            emit_expr_static_abi_slot_for_value_type(other, ctx, instructions)?;
            Some(1)
        }
        _ => None,
    }
}

fn emit_abi_static_array_buffer(
    element_type: &ValueType,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
    include_length: bool,
) -> Option<()> {
    let element_slot_count = abi_static_slot_count(element_type)?;
    if element_slot_count == 0 {
        return None;
    }
    let element_byte_len = element_slot_count * 32;
    let tmp_id = ctx.next_label();
    let arr_local = ctx.allocate_local(format!("__abi_arr_{tmp_id}"), None);
    let len_local = ctx.allocate_local(format!("__abi_arr_len_{tmp_id}"), None);
    let out_local = ctx.allocate_local(format!("__abi_arr_out_{tmp_id}"), None);
    let idx_local = ctx.allocate_local(format!("__abi_arr_idx_{tmp_id}"), None);
    let elem_slot_local = ctx.allocate_local(format!("__abi_arr_elem_slot_{tmp_id}"), None);

    instructions.push(Instruction::StoreLocal(arr_local));
    instructions.push(Instruction::LoadLocal(arr_local));
    instructions.push(Instruction::GetSize);
    instructions.push(Instruction::StoreLocal(len_local));

    instructions.push(Instruction::LoadLocal(len_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
        element_byte_len as u64,
    ))));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Mul));
    if include_length {
        instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
            32u8,
        ))));
        instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
    }
    instructions.push(Instruction::NewBuffer);
    instructions.push(Instruction::StoreLocal(out_local));

    if include_length {
        instructions.push(Instruction::LoadLocal(len_local));
        emit_abi_u256_slot(ctx, instructions);
        let len_slot_local = ctx.allocate_local(format!("__abi_arr_len_slot_{tmp_id}"), None);
        instructions.push(Instruction::StoreLocal(len_slot_local));
        instructions.push(Instruction::LoadLocal(out_local));
        instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::zero())));
        instructions.push(Instruction::LoadLocal(len_slot_local));
        instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::zero())));
        instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
            32u8,
        ))));
        instructions.push(Instruction::MemCpy);
    }

    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::zero())));
    instructions.push(Instruction::StoreLocal(idx_local));

    let loop_label = ctx.next_label();
    let end_label = ctx.next_label();
    instructions.push(Instruction::Label(loop_label));
    instructions.push(Instruction::LoadLocal(idx_local));
    instructions.push(Instruction::LoadLocal(len_local));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Lt));
    instructions.push(Instruction::JumpIf { target: end_label });

    instructions.push(Instruction::LoadLocal(arr_local));
    instructions.push(Instruction::LoadLocal(idx_local));
    instructions.push(Instruction::ArrayGet);
    let emitted_slots = emit_abi_static_slots_for_stack_value(element_type, ctx, instructions)?;
    if emitted_slots != element_slot_count {
        return None;
    }
    if emitted_slots > 1 {
        instructions.push(Instruction::CallBuiltin {
            builtin: BuiltinCall::BytesConcat,
            arg_count: emitted_slots,
        });
    }
    instructions.push(Instruction::StoreLocal(elem_slot_local));

    instructions.push(Instruction::LoadLocal(out_local));
    if include_length {
        instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
            32u8,
        ))));
    } else {
        instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::zero())));
    }
    instructions.push(Instruction::LoadLocal(idx_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
        element_byte_len as u64,
    ))));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Mul));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
    instructions.push(Instruction::LoadLocal(elem_slot_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::zero())));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
        element_byte_len as u64,
    ))));
    instructions.push(Instruction::MemCpy);

    instructions.push(Instruction::LoadLocal(idx_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::one())));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Add));
    instructions.push(Instruction::StoreLocal(idx_local));
    instructions.push(Instruction::Jump { target: loop_label });
    instructions.push(Instruction::Label(end_label));

    instructions.push(Instruction::LoadLocal(out_local));
    instructions.push(Instruction::Convert {
        target: ConvertTarget::ByteArray,
    });
    Some(())
}

fn emit_abi_decode_static_slot(
    buffer_local: usize,
    index: usize,
    value_type: &ValueType,
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) {
    match value_type {
        // Unsigned integers must NOT be read with NeoVM's signed-LE
        // CONVERT semantics — see `emit_le_buffer_to_unsigned_integer`.
        ValueType::Integer { signed: false, .. } => {
            emit_abi_decode_slot_slice(buffer_local, index, 0, 32, instructions);
            instructions.push(Instruction::Convert {
                target: ConvertTarget::ByteArray,
            });
            materialize_byte_array_buffer(ctx, instructions, true);
            emit_le_buffer_to_unsigned_integer(ctx, instructions);
        }
        // Signed intN: the canonical slot is sign-extended big-endian, so
        // the signed-LE CONVERT after the reversal is exactly right.
        ValueType::Integer { signed: true, .. } | ValueType::Boolean => {
            emit_abi_decode_slot_slice(buffer_local, index, 0, 32, instructions);
            instructions.push(Instruction::Convert {
                target: ConvertTarget::ByteArray,
            });
            materialize_byte_array_buffer(ctx, instructions, true);
            instructions.push(Instruction::Convert {
                target: ConvertTarget::Integer,
            });
        }
        // All-static struct: decode each field from consecutive head slots
        // starting at `index` into a fresh `StackItem::Array` (the
        // Array-of-fields shape the struct-constructor lowering produces
        // and the encode side reads back via ArrayGet). Mirrors
        // `lower_static_abi_slots_for_expr` on the encode side.
        ValueType::Struct { fields, .. } => {
            let tmp_id = ctx.next_label();
            let struct_local = ctx.allocate_local(format!("__abi_dec_struct_{tmp_id}"), None);
            instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
                fields.len() as u64,
            ))));
            instructions.push(Instruction::NewArray {
                element_type: ValueType::Any,
            });
            instructions.push(Instruction::StoreLocal(struct_local));
            let mut field_slot = index;
            for (field_index, field) in fields.iter().enumerate() {
                instructions.push(Instruction::LoadLocal(struct_local));
                instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
                    BigInt::from(field_index as u64),
                )));
                emit_abi_decode_static_slot(buffer_local, field_slot, &field.ty, ctx, instructions);
                instructions.push(Instruction::ArraySet);
                field_slot += abi_static_slot_count(&field.ty).unwrap_or(1);
            }
            instructions.push(Instruction::LoadLocal(struct_local));
        }
        ValueType::Address => {
            emit_abi_decode_slot_slice(buffer_local, index, 12, 20, instructions);
            instructions.push(Instruction::Convert {
                target: ConvertTarget::ByteArray,
            });
            materialize_byte_array_buffer(ctx, instructions, true);
        }
        ValueType::ByteArray {
            fixed_len: Some(len),
        } => {
            let len = (*len).min(32) as usize;
            emit_abi_decode_slot_slice(buffer_local, index, 0, len, instructions);
            instructions.push(Instruction::Convert {
                target: ConvertTarget::ByteArray,
            });
        }
        _ => {
            emit_abi_decode_slot_slice(buffer_local, index, 0, 32, instructions);
            instructions.push(Instruction::Convert {
                target: ConvertTarget::ByteArray,
            });
        }
    }
}

fn emit_abi_decode_slot_slice(
    buffer_local: usize,
    index: usize,
    slot_offset: usize,
    len: usize,
    instructions: &mut Vec<Instruction>,
) {
    instructions.push(Instruction::LoadLocal(buffer_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
        (index * 32 + slot_offset) as u64,
    ))));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::from(
        len as u64,
    ))));
    instructions.push(Instruction::Substr);
}

fn emit_abi_u256_slot(
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
) {
    let _ = emit_expr_static_abi_slot_for_value_type(
        &ValueType::Integer {
            signed: false,
            bits: 256,
        },
        ctx,
        instructions,
    );
}

fn emit_abi_fixed_buffer(
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
    len: usize,
    reverse: bool,
) {
    let tmp_id = ctx.next_label();
    let src_local = ctx.allocate_local(format!("__abi_fixed_src_{tmp_id}"), None);
    let dst_local = ctx.allocate_local(format!("__abi_fixed_dst_{tmp_id}"), None);
    let size_local = ctx.allocate_local(format!("__abi_fixed_size_{tmp_id}"), None);
    let count_local = ctx.allocate_local(format!("__abi_fixed_count_{tmp_id}"), None);

    instructions.push(Instruction::StoreLocal(src_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
        BigInt::from(len as u64),
    )));
    instructions.push(Instruction::NewBuffer);
    instructions.push(Instruction::StoreLocal(dst_local));

    instructions.push(Instruction::LoadLocal(src_local));
    instructions.push(Instruction::GetSize);
    instructions.push(Instruction::StoreLocal(size_local));

    let ge_label = ctx.next_label();
    let end_label = ctx.next_label();
    instructions.push(Instruction::LoadLocal(size_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
        BigInt::from(len as u64),
    )));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Lt));
    instructions.push(Instruction::JumpIf { target: ge_label });
    instructions.push(Instruction::LoadLocal(size_local));
    instructions.push(Instruction::StoreLocal(count_local));
    instructions.push(Instruction::Jump { target: end_label });
    instructions.push(Instruction::Label(ge_label));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
        BigInt::from(len as u64),
    )));
    instructions.push(Instruction::StoreLocal(count_local));
    instructions.push(Instruction::Label(end_label));

    instructions.push(Instruction::LoadLocal(dst_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
        BigInt::zero(),
    )));
    instructions.push(Instruction::LoadLocal(src_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
        BigInt::zero(),
    )));
    instructions.push(Instruction::LoadLocal(count_local));
    instructions.push(Instruction::MemCpy);

    if reverse {
        instructions.push(Instruction::LoadLocal(dst_local));
        instructions.push(Instruction::LoadLocal(dst_local));
        instructions.push(Instruction::ReverseItems);
    } else {
        instructions.push(Instruction::LoadLocal(dst_local));
    }
    instructions.push(Instruction::Convert {
        target: ConvertTarget::ByteArray,
    });
}

/// Bug #23 fix: emit a `len`-byte big-endian buffer for a signed integer
/// whose signed-LE byte representation is on top of the stack. The 32-byte
/// slot encoder passes `len = 32`; `abi.encodePacked(intN)` passes
/// `len = N / 8`.
///
/// Differs from `emit_abi_fixed_buffer(.., len, true)` in one key way: when
/// the source value is negative (high bit of its highest LE byte is set), the
/// destination buffer is initialised to all `0xff` bytes (sign-extension)
/// rather than zeros. The low `count` bytes (= min(size, len)) of the source
/// are then copied in, and the result is reversed to big-endian — matching
/// EVM canonical ABI sign-extension for `intN` (N ∈ {8, 16, 32, 64, 128}).
///
/// Stack on entry: `[src_signed_le_bytearray]`.
/// Stack on exit:  `[buffer_bytearray]` (`len`-byte big-endian, sign-extended).
fn emit_abi_fixed_buffer_signed(
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
    len: usize,
) {
    let tmp_id = ctx.next_label();
    let src_local = ctx.allocate_local(format!("__abi_sfixed_src_{tmp_id}"), None);
    let dst_local = ctx.allocate_local(format!("__abi_sfixed_dst_{tmp_id}"), None);
    let size_local = ctx.allocate_local(format!("__abi_sfixed_size_{tmp_id}"), None);
    let count_local = ctx.allocate_local(format!("__abi_sfixed_count_{tmp_id}"), None);
    let fill_local = ctx.allocate_local(format!("__abi_sfixed_fill_{tmp_id}"), None);

    // Save the source ByteArray.
    instructions.push(Instruction::StoreLocal(src_local));

    // size = src.size().
    instructions.push(Instruction::LoadLocal(src_local));
    instructions.push(Instruction::GetSize);
    instructions.push(Instruction::StoreLocal(size_local));

    // count = min(size, len). Same shape as `emit_abi_fixed_buffer`.
    let ge_label = ctx.next_label();
    let count_done_label = ctx.next_label();
    instructions.push(Instruction::LoadLocal(size_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
        BigInt::from(len as u64),
    )));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Lt));
    instructions.push(Instruction::JumpIf { target: ge_label });
    instructions.push(Instruction::LoadLocal(size_local));
    instructions.push(Instruction::StoreLocal(count_local));
    instructions.push(Instruction::Jump {
        target: count_done_label,
    });
    instructions.push(Instruction::Label(ge_label));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
        BigInt::from(len as u64),
    )));
    instructions.push(Instruction::StoreLocal(count_local));
    instructions.push(Instruction::Label(count_done_label));

    // Detect negative: convert src (signed-LE ByteArray) to Integer and test < 0.
    // NeoVM's CONVERT to Integer treats the operand as signed little-endian, so
    // this matches the original Solidity-level sign of the value.
    //
    // CRITICAL: in this codebase `Instruction::JumpIf` lowers to NeoVM
    // `JMPIFNOT_L` (see `bytecode_emit_ir.rs` ~line 340) — i.e. jumps when the
    // condition is FALSE. So `JumpIf { target }` after `Lt` jumps when
    // `val < 0` is FALSE → fall-through is the negative case.
    let pos_label = ctx.next_label();
    let init_done_label = ctx.next_label();
    instructions.push(Instruction::LoadLocal(src_local));
    instructions.push(Instruction::Convert {
        target: ConvertTarget::Integer,
    });
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::zero())));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Lt));
    // Jump to pos_label when `val < 0` is FALSE (positive/zero).
    instructions.push(Instruction::JumpIf { target: pos_label });

    // Negative path (fall-through when `val < 0` is TRUE): 0xff-filled
    // `len`-byte buffer. NewBuffer only zero-fills, so we allocate a fresh
    // zero buffer and MemCpy a literal `[0xff; len]` ByteArray over it.
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
        BigInt::from(len as u64),
    )));
    instructions.push(Instruction::NewBuffer);
    instructions.push(Instruction::StoreLocal(dst_local));
    // Stash the literal ByteArray into a local so MemCpy's [src, src_offset]
    // operands resolve to a stable ByteString (mirrors the dynamic-bytes-tail
    // pattern at line 832+).
    instructions.push(Instruction::PushLiteral(LiteralValue::ByteArray(vec![
        0xffu8;
        len
    ])));
    instructions.push(Instruction::StoreLocal(fill_local));
    instructions.push(Instruction::LoadLocal(dst_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::zero())));
    instructions.push(Instruction::LoadLocal(fill_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::zero())));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
        BigInt::from(len as u64),
    )));
    instructions.push(Instruction::MemCpy);
    instructions.push(Instruction::Jump {
        target: init_done_label,
    });

    // Positive (or zero) path: zero-filled buffer.
    instructions.push(Instruction::Label(pos_label));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
        BigInt::from(len as u64),
    )));
    instructions.push(Instruction::NewBuffer);
    instructions.push(Instruction::StoreLocal(dst_local));

    instructions.push(Instruction::Label(init_done_label));

    // MemCpy the low `count` bytes of src into dst at offset 0. The remaining
    // `len - count` high bytes of dst keep their fill value (0x00 or 0xff).
    instructions.push(Instruction::LoadLocal(dst_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::zero())));
    instructions.push(Instruction::LoadLocal(src_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(BigInt::zero())));
    instructions.push(Instruction::LoadLocal(count_local));
    instructions.push(Instruction::MemCpy);

    // Reverse to big-endian and convert Buffer → ByteArray.
    instructions.push(Instruction::LoadLocal(dst_local));
    instructions.push(Instruction::LoadLocal(dst_local));
    instructions.push(Instruction::ReverseItems);
    instructions.push(Instruction::Convert {
        target: ConvertTarget::ByteArray,
    });
}

fn emit_abi_bytesn_slot(
    ctx: &mut LoweringContext,
    instructions: &mut Vec<Instruction>,
    len: usize,
) {
    let tmp_id = ctx.next_label();
    let src_local = ctx.allocate_local(format!("__abi_bytesn_src_{tmp_id}"), None);
    let dst_local = ctx.allocate_local(format!("__abi_bytesn_dst_{tmp_id}"), None);
    let size_local = ctx.allocate_local(format!("__abi_bytesn_size_{tmp_id}"), None);
    let count_local = ctx.allocate_local(format!("__abi_bytesn_count_{tmp_id}"), None);

    instructions.push(Instruction::StoreLocal(src_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
        BigInt::from(32u64),
    )));
    instructions.push(Instruction::NewBuffer);
    instructions.push(Instruction::StoreLocal(dst_local));

    instructions.push(Instruction::LoadLocal(src_local));
    instructions.push(Instruction::GetSize);
    instructions.push(Instruction::StoreLocal(size_local));

    let ge_label = ctx.next_label();
    let end_label = ctx.next_label();
    instructions.push(Instruction::LoadLocal(size_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
        BigInt::from(len as u64),
    )));
    instructions.push(Instruction::BinaryOp(BinaryOperator::Lt));
    instructions.push(Instruction::JumpIf { target: ge_label });
    instructions.push(Instruction::LoadLocal(size_local));
    instructions.push(Instruction::StoreLocal(count_local));
    instructions.push(Instruction::Jump { target: end_label });
    instructions.push(Instruction::Label(ge_label));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
        BigInt::from(len as u64),
    )));
    instructions.push(Instruction::StoreLocal(count_local));
    instructions.push(Instruction::Label(end_label));

    instructions.push(Instruction::LoadLocal(dst_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
        BigInt::zero(),
    )));
    instructions.push(Instruction::LoadLocal(src_local));
    instructions.push(Instruction::PushLiteral(LiteralValue::Integer(
        BigInt::zero(),
    )));
    instructions.push(Instruction::LoadLocal(count_local));
    instructions.push(Instruction::MemCpy);
    instructions.push(Instruction::LoadLocal(dst_local));
    instructions.push(Instruction::Convert {
        target: ConvertTarget::ByteArray,
    });
}