monad-revm 0.2.0

Monad-specific REVM implementation
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
//! State-mutating functions for the staking precompile.
//!
//! Implements all 8 user-callable write functions and 3 syscalls.
//! Uses the [`StakingStorage`] trait for storage access, enabling both
//! direct REVM (`ContextTr`) and Foundry (`EvmInternals`) integration.

use super::{
    abi::gas,
    constants::{
        ACTIVE_VALIDATOR_STAKE, ACTIVE_VALSET_SIZE, DUST_THRESHOLD, MAX_COMMISSION,
        MAX_EXTERNAL_REWARD, MIN_AUTH_ADDRESS_STAKE, MIN_EXTERNAL_REWARD, MON, SYSTEM_ADDRESS,
        UNIT_BIAS, WITHDRAWAL_DELAY,
    },
    interface::IMonadStaking::*,
    storage::{
        accumulator_key, bitset_bucket_key, consensus_view_key, delegator_key, delegator_offsets,
        global_slots, snapshot_view_key, val_id_secp_key, validator_key, validator_offsets,
        valset_slots, withdrawal_key, withdrawal_offsets, STAKING_ADDRESS,
    },
    types::{validator_flags, Delegator, ListNode, RefCountedAccumulator, Validator},
    StorageReader,
};
use alloy_sol_types::{SolCall, SolEvent};
use revm::{
    interpreter::{Gas, InstructionResult, InterpreterResult},
    precompile::PrecompileError,
    primitives::{Address, Bytes, Log, LogData, B256, U256},
};

// ═══════════════════════════════════════════════════════════════════════════════
// Checked Arithmetic Helpers
// ═══════════════════════════════════════════════════════════════════════════════

/// Checked addition for U256.
///
/// C++ parity: checked math failures map to staking internal error.
fn checked_add_u256(a: U256, b: U256) -> Result<U256, PrecompileError> {
    a.checked_add(b).ok_or_else(|| PrecompileError::Other("internal error".into()))
}

/// Checked subtraction for U256.
///
/// C++ parity: checked math failures map to staking internal error.
fn checked_sub_u256(a: U256, b: U256) -> Result<U256, PrecompileError> {
    a.checked_sub(b).ok_or_else(|| PrecompileError::Other("internal error".into()))
}

/// Checked multiply-then-divide for U256. Returns `PrecompileError` on
/// overflow (in the multiplication) or division by zero.
///
/// C++ parity: checked math failures map to staking internal error.
fn checked_mul_div_u256(a: U256, b: U256, d: U256) -> Result<U256, PrecompileError> {
    if d.is_zero() {
        return Err(PrecompileError::Other("internal error".into()));
    }
    let product =
        a.checked_mul(b).ok_or_else(|| PrecompileError::Other("internal error".into()))?;
    Ok(product / d)
}

// ═══════════════════════════════════════════════════════════════════════════════
// StakingStorage Trait
// ═══════════════════════════════════════════════════════════════════════════════

/// Extended storage trait for state-mutating staking operations.
///
/// Extends [`StorageReader`] with write capabilities needed by delegate,
/// undelegate, and other state-changing functions.
pub trait StakingStorage: StorageReader {
    /// Write a U256 value to storage at the given key.
    fn sstore(&mut self, key: U256, value: U256) -> Result<(), PrecompileError>;

    /// Transfer balance from one address to another.
    fn transfer(&mut self, from: Address, to: Address, amount: U256)
        -> Result<(), PrecompileError>;

    /// Emit a log entry.
    fn emit_log(&mut self, log: Log) -> Result<(), PrecompileError>;
}

// ═══════════════════════════════════════════════════════════════════════════════
// Storage Write Helpers
// ═══════════════════════════════════════════════════════════════════════════════

fn write_storage_u256<S: StakingStorage>(
    s: &mut S,
    key: U256,
    value: U256,
) -> Result<(), PrecompileError> {
    s.sstore(key, value)
}

/// Write a u64 value to storage (left-aligned, big-endian).
fn write_storage_u64<S: StakingStorage>(
    s: &mut S,
    key: U256,
    value: u64,
) -> Result<(), PrecompileError> {
    let mut bytes = [0u8; 32];
    bytes[0..8].copy_from_slice(&value.to_be_bytes());
    s.sstore(key, U256::from_be_bytes(bytes))
}

// ═══════════════════════════════════════════════════════════════════════════════
// Storage Read Helpers (using StorageReader trait)
// ═══════════════════════════════════════════════════════════════════════════════

fn read_u256<S: StorageReader>(s: &mut S, key: U256) -> Result<U256, PrecompileError> {
    s.sload(key)
}

fn read_u64<S: StorageReader>(s: &mut S, key: U256) -> Result<u64, PrecompileError> {
    let value = s.sload(key)?;
    let bytes = value.to_be_bytes::<32>();
    Ok(u64::from_be_bytes(bytes[0..8].try_into().unwrap()))
}

fn read_epoch<S: StorageReader>(s: &mut S) -> Result<u64, PrecompileError> {
    read_u64(s, global_slots::EPOCH)
}

fn read_in_boundary<S: StorageReader>(s: &mut S) -> Result<bool, PrecompileError> {
    let raw = read_u256(s, global_slots::IN_BOUNDARY)?;
    Ok(raw != U256::ZERO)
}

fn read_validator<S: StorageReader>(s: &mut S, val_id: u64) -> Result<Validator, PrecompileError> {
    let stake = read_u256(s, validator_key(val_id, validator_offsets::STAKE))?;
    let accumulated_reward_per_token =
        read_u256(s, validator_key(val_id, validator_offsets::ACCUMULATED_REWARD_PER_TOKEN))?;
    let commission = read_u256(s, validator_key(val_id, validator_offsets::COMMISSION))?;

    let keys_slot_0 =
        read_u256(s, validator_key(val_id, validator_offsets::KEYS))?.to_be_bytes::<32>();
    let keys_slot_1 =
        read_u256(s, validator_key(val_id, validator_offsets::KEYS + 1))?.to_be_bytes::<32>();
    let keys_slot_2 =
        read_u256(s, validator_key(val_id, validator_offsets::KEYS + 2))?.to_be_bytes::<32>();

    let mut keys_concat = [0u8; 96];
    keys_concat[0..32].copy_from_slice(&keys_slot_0);
    keys_concat[32..64].copy_from_slice(&keys_slot_1);
    keys_concat[64..96].copy_from_slice(&keys_slot_2);

    let mut secp_pubkey = [0u8; 33];
    let mut bls_pubkey = [0u8; 48];
    secp_pubkey.copy_from_slice(&keys_concat[0..33]);
    bls_pubkey.copy_from_slice(&keys_concat[33..81]);

    let address_flags_raw =
        read_u256(s, validator_key(val_id, validator_offsets::ADDRESS_FLAGS))?.to_be_bytes::<32>();
    let auth_address = Address::from_slice(&address_flags_raw[0..20]);
    let flags = u64::from_be_bytes(address_flags_raw[20..28].try_into().unwrap());

    let unclaimed_rewards =
        read_u256(s, validator_key(val_id, validator_offsets::UNCLAIMED_REWARDS))?;

    Ok(Validator {
        stake,
        accumulated_reward_per_token,
        commission,
        secp_pubkey,
        bls_pubkey,
        auth_address,
        flags,
        unclaimed_rewards,
    })
}

fn read_delegator<S: StorageReader>(
    s: &mut S,
    val_id: u64,
    addr: &Address,
) -> Result<Delegator, PrecompileError> {
    let stake = read_u256(s, delegator_key(val_id, addr, delegator_offsets::STAKE))?;
    let accumulated_reward_per_token =
        read_u256(s, delegator_key(val_id, addr, delegator_offsets::ACCUMULATED_REWARD_PER_TOKEN))?;
    let rewards = read_u256(s, delegator_key(val_id, addr, delegator_offsets::REWARDS))?;
    let delta_stake = read_u256(s, delegator_key(val_id, addr, delegator_offsets::DELTA_STAKE))?;
    let next_delta_stake =
        read_u256(s, delegator_key(val_id, addr, delegator_offsets::NEXT_DELTA_STAKE))?;
    let epochs_raw =
        read_u256(s, delegator_key(val_id, addr, delegator_offsets::EPOCHS))?.to_be_bytes::<32>();
    let delta_epoch = u64::from_be_bytes(epochs_raw[0..8].try_into().unwrap());
    let next_delta_epoch = u64::from_be_bytes(epochs_raw[8..16].try_into().unwrap());

    Ok(Delegator {
        stake,
        accumulated_reward_per_token,
        rewards,
        delta_stake,
        next_delta_stake,
        delta_epoch,
        next_delta_epoch,
    })
}

fn read_list_node<S: StorageReader>(
    s: &mut S,
    val_id: u64,
    addr: &Address,
) -> Result<ListNode, PrecompileError> {
    let slot6 = read_u256(s, delegator_key(val_id, addr, delegator_offsets::LIST_NODE))?
        .to_be_bytes::<32>();
    let slot7 = read_u256(s, delegator_key(val_id, addr, delegator_offsets::LIST_NODE + 1))?
        .to_be_bytes::<32>();
    Ok(ListNode::from_slots(slot6, slot7))
}

fn read_accumulator<S: StorageReader>(
    s: &mut S,
    epoch: u64,
    val_id: u64,
) -> Result<RefCountedAccumulator, PrecompileError> {
    let value = read_u256(s, accumulator_key(epoch, val_id, 0))?;
    // Refcount is stored as u256 (right-aligned standard integer encoding)
    let refcount_u256 = read_u256(s, accumulator_key(epoch, val_id, 1))?;
    let refcount = refcount_u256.as_limbs()[0];
    Ok(RefCountedAccumulator { value, refcount })
}

// ═══════════════════════════════════════════════════════════════════════════════
// Struct Write Helpers
// ═══════════════════════════════════════════════════════════════════════════════

fn write_validator_stake<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    stake: U256,
) -> Result<(), PrecompileError> {
    write_storage_u256(s, validator_key(val_id, validator_offsets::STAKE), stake)
}

fn write_validator_acc<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    acc: U256,
) -> Result<(), PrecompileError> {
    write_storage_u256(
        s,
        validator_key(val_id, validator_offsets::ACCUMULATED_REWARD_PER_TOKEN),
        acc,
    )
}

fn write_validator_commission<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    commission: U256,
) -> Result<(), PrecompileError> {
    write_storage_u256(s, validator_key(val_id, validator_offsets::COMMISSION), commission)
}

fn write_validator_unclaimed_rewards<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    rewards: U256,
) -> Result<(), PrecompileError> {
    write_storage_u256(s, validator_key(val_id, validator_offsets::UNCLAIMED_REWARDS), rewards)
}

fn write_validator_flags<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    val: &Validator,
    new_flags: u64,
) -> Result<(), PrecompileError> {
    // Slot 6 packs auth_address (20 bytes) + flags (8 bytes) + padding (4 bytes)
    let mut slot6 = [0u8; 32];
    slot6[0..20].copy_from_slice(val.auth_address.as_slice());
    slot6[20..28].copy_from_slice(&new_flags.to_be_bytes());
    write_storage_u256(
        s,
        validator_key(val_id, validator_offsets::ADDRESS_FLAGS),
        U256::from_be_bytes(slot6),
    )
}

fn write_validator_full<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    val: &Validator,
) -> Result<(), PrecompileError> {
    write_validator_stake(s, val_id, val.stake)?;
    write_validator_acc(s, val_id, val.accumulated_reward_per_token)?;
    write_validator_commission(s, val_id, val.commission)?;

    // Keys: 3 slots (secp33 + bls48 = 81 bytes)
    let mut keys_concat = [0u8; 96];
    keys_concat[0..33].copy_from_slice(&val.secp_pubkey);
    keys_concat[33..81].copy_from_slice(&val.bls_pubkey);
    let slot0: [u8; 32] = keys_concat[0..32].try_into().unwrap();
    let slot1: [u8; 32] = keys_concat[32..64].try_into().unwrap();
    let slot2: [u8; 32] = keys_concat[64..96].try_into().unwrap();
    write_storage_u256(
        s,
        validator_key(val_id, validator_offsets::KEYS),
        U256::from_be_bytes(slot0),
    )?;
    write_storage_u256(
        s,
        validator_key(val_id, validator_offsets::KEYS + 1),
        U256::from_be_bytes(slot1),
    )?;
    write_storage_u256(
        s,
        validator_key(val_id, validator_offsets::KEYS + 2),
        U256::from_be_bytes(slot2),
    )?;

    // Address + flags packed
    write_validator_flags(s, val_id, val, val.flags)?;
    write_validator_unclaimed_rewards(s, val_id, val.unclaimed_rewards)?;
    Ok(())
}

fn write_delegator<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    addr: &Address,
    del: &Delegator,
) -> Result<(), PrecompileError> {
    write_storage_u256(s, delegator_key(val_id, addr, delegator_offsets::STAKE), del.stake)?;
    write_storage_u256(
        s,
        delegator_key(val_id, addr, delegator_offsets::ACCUMULATED_REWARD_PER_TOKEN),
        del.accumulated_reward_per_token,
    )?;
    write_storage_u256(s, delegator_key(val_id, addr, delegator_offsets::REWARDS), del.rewards)?;
    write_storage_u256(
        s,
        delegator_key(val_id, addr, delegator_offsets::DELTA_STAKE),
        del.delta_stake,
    )?;
    write_storage_u256(
        s,
        delegator_key(val_id, addr, delegator_offsets::NEXT_DELTA_STAKE),
        del.next_delta_stake,
    )?;
    // Pack delta_epoch + next_delta_epoch into one slot
    let mut epochs = [0u8; 32];
    epochs[0..8].copy_from_slice(&del.delta_epoch.to_be_bytes());
    epochs[8..16].copy_from_slice(&del.next_delta_epoch.to_be_bytes());
    write_storage_u256(
        s,
        delegator_key(val_id, addr, delegator_offsets::EPOCHS),
        U256::from_be_bytes(epochs),
    )?;
    Ok(())
}

fn write_list_node<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    addr: &Address,
    node: &ListNode,
) -> Result<(), PrecompileError> {
    let (slot6, slot7) = node.to_slots();
    write_storage_u256(
        s,
        delegator_key(val_id, addr, delegator_offsets::LIST_NODE),
        U256::from_be_bytes(slot6),
    )?;
    write_storage_u256(
        s,
        delegator_key(val_id, addr, delegator_offsets::LIST_NODE + 1),
        U256::from_be_bytes(slot7),
    )?;
    Ok(())
}

fn write_withdrawal_request<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    addr: &Address,
    wid: u8,
    amount: U256,
    acc: U256,
    epoch: u64,
) -> Result<(), PrecompileError> {
    write_storage_u256(s, withdrawal_key(val_id, addr, wid, withdrawal_offsets::AMOUNT), amount)?;
    write_storage_u256(s, withdrawal_key(val_id, addr, wid, withdrawal_offsets::ACCUMULATOR), acc)?;
    write_storage_u64(s, withdrawal_key(val_id, addr, wid, withdrawal_offsets::EPOCH), epoch)?;
    Ok(())
}

fn clear_withdrawal_request<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    addr: &Address,
    wid: u8,
) -> Result<(), PrecompileError> {
    write_storage_u256(
        s,
        withdrawal_key(val_id, addr, wid, withdrawal_offsets::AMOUNT),
        U256::ZERO,
    )?;
    write_storage_u256(
        s,
        withdrawal_key(val_id, addr, wid, withdrawal_offsets::ACCUMULATOR),
        U256::ZERO,
    )?;
    write_storage_u256(
        s,
        withdrawal_key(val_id, addr, wid, withdrawal_offsets::EPOCH),
        U256::ZERO,
    )?;
    Ok(())
}

fn write_accumulator<S: StakingStorage>(
    s: &mut S,
    epoch: u64,
    val_id: u64,
    acc: &RefCountedAccumulator,
) -> Result<(), PrecompileError> {
    write_storage_u256(s, accumulator_key(epoch, val_id, 0), acc.value)?;
    // Refcount stored as u256 (right-aligned standard integer encoding)
    write_storage_u256(s, accumulator_key(epoch, val_id, 1), U256::from(acc.refcount))?;
    Ok(())
}

// ═══════════════════════════════════════════════════════════════════════════════
// Core Business Logic
// ═══════════════════════════════════════════════════════════════════════════════

/// Get the activation epoch for new delegations.
///
/// Returns `epoch + 1` normally, or `epoch + 2` if in the epoch delay period.
fn get_activation_epoch<S: StorageReader>(s: &mut S) -> Result<u64, PrecompileError> {
    let epoch = read_epoch(s)?;
    let in_boundary = read_in_boundary(s)?;
    Ok(if in_boundary { epoch + 2 } else { epoch + 1 })
}

/// Check if an epoch is active (has passed).
const fn is_epoch_active(current_epoch: u64, active_epoch: u64) -> bool {
    active_epoch != 0 && active_epoch <= current_epoch
}

/// Calculate rewards using the accumulator formula.
///
/// `reward = (stake * (epoch_acc - last_acc)) / UNIT_BIAS`
fn calculate_rewards(
    stake: U256,
    epoch_acc: U256,
    last_acc: U256,
) -> Result<U256, PrecompileError> {
    // Mirror C++ ordering exactly:
    // 1) checked_sub(current_acc, last_checked_acc)
    // 2) checked_mul_div(delta, stake, UNIT_BIAS)
    let diff = checked_sub_u256(epoch_acc, last_acc)?;
    checked_mul_div_u256(diff, stake, UNIT_BIAS)
}

/// Increment the accumulator refcount for a validator at the activation epoch.
///
/// Snapshots the current validator accumulator value and increments the refcount.
fn increment_accumulator_refcount<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
) -> Result<(), PrecompileError> {
    let epoch = get_activation_epoch(s)?;
    let mut acc = read_accumulator(s, epoch, val_id)?;
    acc.refcount += 1;
    acc.value =
        read_u256(s, validator_key(val_id, validator_offsets::ACCUMULATED_REWARD_PER_TOKEN))?;
    write_accumulator(s, epoch, val_id, &acc)
}

/// Decrement the accumulator refcount and return the snapshotted value.
///
/// If refcount reaches 0, clears the accumulator storage.
fn decrement_accumulator_refcount<S: StakingStorage>(
    s: &mut S,
    epoch: u64,
    val_id: u64,
) -> Result<U256, PrecompileError> {
    let mut acc = read_accumulator(s, epoch, val_id)?;
    let value = acc.value;
    if acc.refcount == 0 {
        return Ok(U256::ZERO);
    }
    acc.refcount -= 1;
    if acc.refcount == 0 {
        // Clear storage
        write_storage_u256(s, accumulator_key(epoch, val_id, 0), U256::ZERO)?;
        write_storage_u256(s, accumulator_key(epoch, val_id, 1), U256::ZERO)?;
    } else {
        write_accumulator(s, epoch, val_id, &acc)?;
    }
    Ok(value)
}

/// Apply compound: calculate rewards from delta track activation and fold into active stake.
fn apply_compound<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    del: &mut Delegator,
) -> Result<U256, PrecompileError> {
    let epoch_acc = decrement_accumulator_refcount(s, del.delta_epoch, val_id)?;
    let rewards = calculate_rewards(del.stake, epoch_acc, del.accumulated_reward_per_token)?;
    del.accumulated_reward_per_token = epoch_acc;

    // Compound: active_stake += delta_stake
    del.stake = checked_add_u256(del.stake, del.delta_stake)?;

    // Promote next_delta → delta
    del.delta_stake = del.next_delta_stake;
    del.next_delta_stake = U256::ZERO;
    del.delta_epoch = del.next_delta_epoch;
    del.next_delta_epoch = 0;

    Ok(rewards)
}

/// Pull delegator state up to date.
///
/// Promotes pending delta stakes if their activation epochs have passed,
/// and calculates accumulated rewards.
fn pull_delegator_up_to_date<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    addr: &Address,
) -> Result<Delegator, PrecompileError> {
    let mut del = read_delegator(s, val_id, addr)?;
    let current_epoch = read_epoch(s)?;

    // Can promote next_delta → delta?
    let can_promote = del.delta_epoch == 0 && del.next_delta_epoch <= current_epoch + 1;
    if can_promote && del.next_delta_epoch != 0 {
        del.delta_stake = del.next_delta_stake;
        del.next_delta_stake = U256::ZERO;
        del.delta_epoch = del.next_delta_epoch;
        del.next_delta_epoch = 0;
    }

    // Track validator unclaimed_rewards for reward_invariant
    let mut unclaimed_rewards =
        read_u256(s, validator_key(val_id, validator_offsets::UNCLAIMED_REWARDS))?;

    // Check which delta tracks can be compounded.
    // Both checks use the state BEFORE any compounding.
    let can_compound = is_epoch_active(current_epoch, del.delta_epoch) && del.delta_epoch != 0;
    let can_compound_boundary =
        is_epoch_active(current_epoch, del.next_delta_epoch) && del.next_delta_epoch != 0;

    // Compound boundary track first.
    // When both tracks are active, apply_compound is called twice:
    //   1st: uses delta_epoch, promotes next_delta → delta
    //   2nd: uses the newly promoted delta (was next_delta)
    if can_compound_boundary {
        let rewards = apply_compound(s, val_id, &mut del)?;
        // reward_invariant: check solvency and deduct from unclaimed
        if unclaimed_rewards < rewards {
            return Err(PrecompileError::Other("solvency error".into()));
        }
        unclaimed_rewards = checked_sub_u256(unclaimed_rewards, rewards)?;
        del.rewards = checked_add_u256(del.rewards, rewards)?;
    }

    // Compound main delta track
    if can_compound {
        let rewards = apply_compound(s, val_id, &mut del)?;
        // reward_invariant: check solvency and deduct from unclaimed
        if unclaimed_rewards < rewards {
            return Err(PrecompileError::Other("solvency error".into()));
        }
        unclaimed_rewards = checked_sub_u256(unclaimed_rewards, rewards)?;
        del.rewards = checked_add_u256(del.rewards, rewards)?;
    }

    // Accrue rewards for active stake
    if !del.stake.is_zero() {
        let val_acc =
            read_u256(s, validator_key(val_id, validator_offsets::ACCUMULATED_REWARD_PER_TOKEN))?;
        let rewards = calculate_rewards(del.stake, val_acc, del.accumulated_reward_per_token)?;
        // reward_invariant: check solvency and deduct from unclaimed
        if unclaimed_rewards < rewards {
            return Err(PrecompileError::Other("solvency error".into()));
        }
        unclaimed_rewards = checked_sub_u256(unclaimed_rewards, rewards)?;
        del.accumulated_reward_per_token = val_acc;
        del.rewards = checked_add_u256(del.rewards, rewards)?;
    }

    // Write back updated unclaimed_rewards
    write_validator_unclaimed_rewards(s, val_id, unclaimed_rewards)?;
    write_delegator(s, val_id, addr, &del)?;
    Ok(del)
}

// ═══════════════════════════════════════════════════════════════════════════════
// Linked List Mutation
// ═══════════════════════════════════════════════════════════════════════════════

/// Insert a delegation into both linked lists.
///
/// - Validator → Delegator list (anext/aprev pointers)
/// - Delegator → Validator list (inext/iprev pointers)
fn linked_list_insert<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    delegator: &Address,
) -> Result<(), PrecompileError> {
    // Insert delegator into validator's list (key=val_id, ptr=delegator address)
    linked_list_insert_address(s, val_id, delegator)?;
    // Insert validator into delegator's list (key=delegator, ptr=val_id)
    linked_list_insert_val_id(s, val_id, delegator)?;
    Ok(())
}

/// Insert an address into the validator's delegator list.
fn linked_list_insert_address<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    ptr: &Address,
) -> Result<(), PrecompileError> {
    if *ptr == Address::ZERO || *ptr == ListNode::SENTINEL_ADDRESS {
        return Err(PrecompileError::Other("invalid input".into()));
    }

    let mut this_node = read_list_node(s, val_id, ptr)?;
    // If aprev != empty, already in list
    if this_node.aprev != Address::ZERO {
        return Ok(());
    }

    let mut sentinel = read_list_node(s, val_id, &ListNode::SENTINEL_ADDRESS)?;
    let next_ptr = sentinel.anext;

    if next_ptr != Address::ZERO {
        let mut next_node = read_list_node(s, val_id, &next_ptr)?;
        next_node.aprev = *ptr;
        write_list_node(s, val_id, &next_ptr, &next_node)?;
    }

    this_node.aprev = ListNode::SENTINEL_ADDRESS;
    this_node.anext = next_ptr;
    sentinel.anext = *ptr;

    write_list_node(s, val_id, ptr, &this_node)?;
    write_list_node(s, val_id, &ListNode::SENTINEL_ADDRESS, &sentinel)?;
    Ok(())
}

/// Insert a validator ID into the delegator's validator list.
fn linked_list_insert_val_id<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    delegator: &Address,
) -> Result<(), PrecompileError> {
    if val_id == 0 || val_id == ListNode::SENTINEL_VAL_ID {
        return Err(PrecompileError::Other("invalid input".into()));
    }

    let mut this_node = read_list_node(s, val_id, delegator)?;
    // If iprev != empty, already in list
    if this_node.iprev != 0 {
        return Ok(());
    }

    let mut sentinel = read_list_node(s, ListNode::SENTINEL_VAL_ID, delegator)?;
    let next_ptr = sentinel.inext;

    if next_ptr != 0 {
        let mut next_node = read_list_node(s, next_ptr, delegator)?;
        next_node.iprev = val_id;
        write_list_node(s, next_ptr, delegator, &next_node)?;
    }

    this_node.iprev = ListNode::SENTINEL_VAL_ID;
    this_node.inext = next_ptr;
    sentinel.inext = val_id;

    write_list_node(s, val_id, delegator, &this_node)?;
    write_list_node(s, ListNode::SENTINEL_VAL_ID, delegator, &sentinel)?;
    Ok(())
}

/// Remove a delegation from both linked lists.
fn linked_list_remove<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    delegator: &Address,
) -> Result<(), PrecompileError> {
    linked_list_remove_address(s, val_id, delegator)?;
    linked_list_remove_val_id(s, val_id, delegator)?;
    Ok(())
}

/// Remove an address from the validator's delegator list.
fn linked_list_remove_address<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    ptr: &Address,
) -> Result<(), PrecompileError> {
    let mut this_node = read_list_node(s, val_id, ptr)?;
    // If aprev == empty, not in list
    if this_node.aprev == Address::ZERO {
        return Ok(());
    }

    let prev_ptr = this_node.aprev;
    let next_ptr = this_node.anext;

    let mut prev_node = read_list_node(s, val_id, &prev_ptr)?;
    prev_node.anext = next_ptr;
    write_list_node(s, val_id, &prev_ptr, &prev_node)?;

    if next_ptr != Address::ZERO {
        let mut next_node = read_list_node(s, val_id, &next_ptr)?;
        next_node.aprev = prev_ptr;
        write_list_node(s, val_id, &next_ptr, &next_node)?;
    }

    // Clear this node's list pointers
    this_node.aprev = Address::ZERO;
    this_node.anext = Address::ZERO;
    write_list_node(s, val_id, ptr, &this_node)?;
    Ok(())
}

/// Remove a validator ID from the delegator's validator list.
fn linked_list_remove_val_id<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    delegator: &Address,
) -> Result<(), PrecompileError> {
    let mut this_node = read_list_node(s, val_id, delegator)?;
    // If iprev == empty, not in list
    if this_node.iprev == 0 {
        return Ok(());
    }

    let prev_ptr = this_node.iprev;
    let next_ptr = this_node.inext;

    let mut prev_node = read_list_node(s, prev_ptr, delegator)?;
    prev_node.inext = next_ptr;
    write_list_node(s, prev_ptr, delegator, &prev_node)?;

    if next_ptr != 0 {
        let mut next_node = read_list_node(s, next_ptr, delegator)?;
        next_node.iprev = prev_ptr;
        write_list_node(s, next_ptr, delegator, &next_node)?;
    }

    this_node.iprev = 0;
    this_node.inext = 0;
    write_list_node(s, val_id, delegator, &this_node)?;
    Ok(())
}

// ═══════════════════════════════════════════════════════════════════════════════
// Valset Management
// ═══════════════════════════════════════════════════════════════════════════════

/// Add a validator to the execution valset bitset. Returns true if newly inserted.
fn add_to_valset<S: StakingStorage>(s: &mut S, val_id: u64) -> Result<bool, PrecompileError> {
    let bucket_key = bitset_bucket_key(val_id);
    let set = read_u256(s, bucket_key)?;
    let bit = val_id & 0xFF;
    let mask = U256::from(1u64) << bit;
    let inserted = (set & mask).is_zero();
    let new_set = set | mask;
    write_storage_u256(s, bucket_key, new_set)?;

    if inserted {
        // Append to execution valset array
        let len = read_u64(s, valset_slots::EXECUTION)?;
        write_storage_u64(s, valset_slots::EXECUTION + U256::from(1 + len), val_id)?;
        write_storage_u64(s, valset_slots::EXECUTION, len + 1)?;
    }
    Ok(inserted)
}

/// Remove a validator from the execution valset bitset.
fn remove_from_valset<S: StakingStorage>(s: &mut S, val_id: u64) -> Result<(), PrecompileError> {
    let bucket_key = bitset_bucket_key(val_id);
    let set = read_u256(s, bucket_key)?;
    let bit = val_id & 0xFF;
    let mask = !(U256::from(1u64) << bit);
    let new_set = set & mask;
    write_storage_u256(s, bucket_key, new_set)
}

// ═══════════════════════════════════════════════════════════════════════════════
// Event Emission Helpers
// ═══════════════════════════════════════════════════════════════════════════════

fn emit_event<S: StakingStorage>(
    s: &mut S,
    topics: Vec<B256>,
    data: Vec<u8>,
) -> Result<(), PrecompileError> {
    s.emit_log(Log { address: STAKING_ADDRESS, data: LogData::new(topics, data.into()).unwrap() })
}

// ═══════════════════════════════════════════════════════════════════════════════
// Validator Flag Management
// ═══════════════════════════════════════════════════════════════════════════════

/// Update validator flags based on current state. Returns the new flags.
fn update_validator_flags_after_delegate<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    val: &Validator,
    del: &Delegator,
    caller: &Address,
) -> Result<u64, PrecompileError> {
    let mut flags = val.flags;

    // Clear STAKE_TOO_LOW if total stake meets threshold
    if val.stake >= ACTIVE_VALIDATOR_STAKE {
        flags &= !validator_flags::STAKE_TOO_LOW;
    }

    // Clear WITHDRAWN if auth address and their next-epoch stake meets minimum
    if *caller == val.auth_address && del.total_stake() >= MIN_AUTH_ADDRESS_STAKE {
        flags &= !validator_flags::WITHDRAWN;
    }

    if flags != val.flags {
        write_validator_flags(s, val_id, val, flags)?;
        // Emit ValidatorStatusChanged event
        let topics = vec![ValidatorStatusChanged::SIGNATURE_HASH, B256::from(U256::from(val_id))];
        let data = U256::from(flags).to_be_bytes::<32>().to_vec();
        emit_event(s, topics, data)?;
    }
    Ok(flags)
}

fn update_validator_flags_after_undelegate<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    val: &Validator,
    del: &Delegator,
    caller: &Address,
) -> Result<u64, PrecompileError> {
    let mut flags = val.flags;

    // Set STAKE_TOO_LOW if below threshold
    if val.stake < ACTIVE_VALIDATOR_STAKE {
        flags |= validator_flags::STAKE_TOO_LOW;
    }

    // Set WITHDRAWN if auth address and their next-epoch stake is below minimum
    if *caller == val.auth_address && del.total_stake() < MIN_AUTH_ADDRESS_STAKE {
        flags |= validator_flags::WITHDRAWN;
    }

    if flags != val.flags {
        write_validator_flags(s, val_id, val, flags)?;
        let topics = vec![ValidatorStatusChanged::SIGNATURE_HASH, B256::from(U256::from(val_id))];
        let data = U256::from(flags).to_be_bytes::<32>().to_vec();
        emit_event(s, topics, data)?;
    }
    Ok(flags)
}

// ═══════════════════════════════════════════════════════════════════════════════
// Internal delegate logic (shared by delegate, compound, addValidator)
// ═══════════════════════════════════════════════════════════════════════════════

fn internal_delegate<S: StakingStorage>(
    s: &mut S,
    val_id: u64,
    caller: &Address,
    amount: U256,
) -> Result<(), PrecompileError> {
    let mut del = pull_delegator_up_to_date(s, val_id, caller)?;
    let in_boundary = read_in_boundary(s)?;
    let activation_epoch = get_activation_epoch(s)?;

    // Add to appropriate delta track
    if in_boundary {
        let need_acc = del.next_delta_epoch == 0;
        del.next_delta_stake = checked_add_u256(del.next_delta_stake, amount)?;
        del.next_delta_epoch = activation_epoch;
        write_delegator(s, val_id, caller, &del)?;
        if need_acc {
            increment_accumulator_refcount(s, val_id)?;
        }
    } else {
        let need_acc = del.delta_epoch == 0;
        del.delta_stake = checked_add_u256(del.delta_stake, amount)?;
        del.delta_epoch = activation_epoch;
        write_delegator(s, val_id, caller, &del)?;
        if need_acc {
            increment_accumulator_refcount(s, val_id)?;
        }
    }

    // Update validator total stake
    let mut val = read_validator(s, val_id)?;
    val.stake = checked_add_u256(val.stake, amount)?;
    write_validator_stake(s, val_id, val.stake)?;

    // Update flags
    let flags = update_validator_flags_after_delegate(s, val_id, &val, &del, caller)?;

    // Add to valset if flags are now OK
    if flags == validator_flags::OK {
        add_to_valset(s, val_id)?;
    }

    // Insert into linked lists
    linked_list_insert(s, val_id, caller)?;

    // Emit Delegate event
    let topics = vec![
        Delegate::SIGNATURE_HASH,
        B256::from(U256::from(val_id)),
        B256::from(U256::from_be_slice(caller.as_slice())),
    ];
    let mut data = Vec::with_capacity(64);
    data.extend_from_slice(&amount.to_be_bytes::<32>());
    data.extend_from_slice(&U256::from(activation_epoch).to_be_bytes::<32>());
    emit_event(s, topics, data)?;

    Ok(())
}

// ═══════════════════════════════════════════════════════════════════════════════
// Write Function Handlers
// ═══════════════════════════════════════════════════════════════════════════════

/// Handle changeCommission(uint64, uint256) => bool
pub fn handle_change_commission<S: StakingStorage>(
    s: &mut S,
    input: &[u8],
    gas_limit: u64,
    caller: &Address,
) -> Result<(u64, Bytes), PrecompileError> {
    if gas_limit < gas::CHANGE_COMMISSION {
        return Err(PrecompileError::OutOfGas);
    }

    let call = changeCommissionCall::abi_decode_raw(&input[4..])
        .map_err(|e| PrecompileError::Other(format!("Invalid input: {e}").into()))?;

    let val = read_validator(s, call.validatorId)?;
    if !val.exists() {
        return Err(PrecompileError::Other("unknown validator".into()));
    }
    if *caller != val.auth_address {
        return Err(PrecompileError::Other("requires auth address".into()));
    }
    if call.commission > MAX_COMMISSION {
        return Err(PrecompileError::Other("commission too high".into()));
    }

    let old_commission = val.commission;
    if call.commission != old_commission {
        write_validator_commission(s, call.validatorId, call.commission)?;
        // Emit CommissionChanged event
        let topics =
            vec![CommissionChanged::SIGNATURE_HASH, B256::from(U256::from(call.validatorId))];
        let mut data = Vec::with_capacity(64);
        data.extend_from_slice(&old_commission.to_be_bytes::<32>());
        data.extend_from_slice(&call.commission.to_be_bytes::<32>());
        emit_event(s, topics, data)?;
    }

    let encoded = changeCommissionCall::abi_encode_returns(&true);
    Ok((gas::CHANGE_COMMISSION, encoded.into()))
}

/// Handle claimRewards(uint64) => bool
pub fn handle_claim_rewards<S: StakingStorage>(
    s: &mut S,
    input: &[u8],
    gas_limit: u64,
    caller: &Address,
) -> Result<(u64, Bytes), PrecompileError> {
    if gas_limit < gas::CLAIM_REWARDS {
        return Err(PrecompileError::OutOfGas);
    }

    let call = claimRewardsCall::abi_decode_raw(&input[4..])
        .map_err(|e| PrecompileError::Other(format!("Invalid input: {e}").into()))?;

    let mut del = pull_delegator_up_to_date(s, call.validatorId, caller)?;

    if !del.rewards.is_zero() {
        let rewards = del.rewards;

        // Transfer (solvency already checked in pull_delegator_up_to_date via reward_invariant)
        s.transfer(STAKING_ADDRESS, *caller, rewards)?;

        // Clear rewards
        del.rewards = U256::ZERO;
        write_delegator(s, call.validatorId, caller, &del)?;

        // Emit ClaimRewards event
        let epoch = read_epoch(s)?;
        let topics = vec![
            ClaimRewards::SIGNATURE_HASH,
            B256::from(U256::from(call.validatorId)),
            B256::from(U256::from_be_slice(caller.as_slice())),
        ];
        let mut data = Vec::with_capacity(64);
        data.extend_from_slice(&rewards.to_be_bytes::<32>());
        data.extend_from_slice(&U256::from(epoch).to_be_bytes::<32>());
        emit_event(s, topics, data)?;
    }

    let encoded = claimRewardsCall::abi_encode_returns(&true);
    Ok((gas::CLAIM_REWARDS, encoded.into()))
}

/// Handle externalReward(uint64) => bool
pub fn handle_external_reward<S: StakingStorage>(
    s: &mut S,
    input: &[u8],
    gas_limit: u64,
    caller: &Address,
    call_value: U256,
) -> Result<(u64, Bytes), PrecompileError> {
    if gas_limit < gas::EXTERNAL_REWARD {
        return Err(PrecompileError::OutOfGas);
    }

    let call = externalRewardCall::abi_decode_raw(&input[4..])
        .map_err(|e| PrecompileError::Other(format!("Invalid input: {e}").into()))?;

    let val = read_validator(s, call.validatorId)?;
    if !val.exists() {
        return Err(PrecompileError::Other("unknown validator".into()));
    }

    // Get active stake from consensus/snapshot view
    let in_boundary = read_in_boundary(s)?;
    let view_key = if in_boundary {
        snapshot_view_key(call.validatorId, 0)
    } else {
        consensus_view_key(call.validatorId, 0)
    };
    let active_stake = read_u256(s, view_key)?;
    if active_stake.is_zero() {
        return Err(PrecompileError::Other("not in validator set".into()));
    }

    if call_value < MIN_EXTERNAL_REWARD {
        return Err(PrecompileError::Other("external reward too small".into()));
    }
    if call_value > MAX_EXTERNAL_REWARD {
        return Err(PrecompileError::Other("external reward too large".into()));
    }

    // Apply reward: accumulator += (reward * UNIT_BIAS) / active_stake
    let reward_acc = checked_mul_div_u256(call_value, UNIT_BIAS, active_stake)?;
    let new_acc = checked_add_u256(val.accumulated_reward_per_token, reward_acc)?;
    write_validator_acc(s, call.validatorId, new_acc)?;
    write_validator_unclaimed_rewards(
        s,
        call.validatorId,
        checked_add_u256(val.unclaimed_rewards, call_value)?,
    )?;

    // Emit ValidatorRewarded event
    let epoch = read_epoch(s)?;
    let topics = vec![
        ValidatorRewarded::SIGNATURE_HASH,
        B256::from(U256::from(call.validatorId)),
        B256::from(U256::from_be_slice(caller.as_slice())),
    ];
    let mut data = Vec::with_capacity(64);
    data.extend_from_slice(&call_value.to_be_bytes::<32>());
    data.extend_from_slice(&U256::from(epoch).to_be_bytes::<32>());
    emit_event(s, topics, data)?;

    let encoded = externalRewardCall::abi_encode_returns(&true);
    Ok((gas::EXTERNAL_REWARD, encoded.into()))
}

/// Handle delegate(uint64) => bool
pub fn handle_delegate<S: StakingStorage>(
    s: &mut S,
    input: &[u8],
    gas_limit: u64,
    caller: &Address,
    call_value: U256,
) -> Result<(u64, Bytes), PrecompileError> {
    if gas_limit < gas::DELEGATE {
        return Err(PrecompileError::OutOfGas);
    }

    let call = delegateCall::abi_decode_raw(&input[4..])
        .map_err(|e| PrecompileError::Other(format!("Invalid input: {e}").into()))?;

    let val = read_validator(s, call.validatorId)?;
    if !val.exists() {
        return Err(PrecompileError::Other("unknown validator".into()));
    }
    // Zero-value delegate is a success no-op
    if call_value.is_zero() {
        let encoded = delegateCall::abi_encode_returns(&true);
        return Ok((gas::DELEGATE, encoded.into()));
    }
    if call_value < DUST_THRESHOLD {
        return Err(PrecompileError::Other("delegation is too small".into()));
    }

    internal_delegate(s, call.validatorId, caller, call_value)?;

    let encoded = delegateCall::abi_encode_returns(&true);
    Ok((gas::DELEGATE, encoded.into()))
}

/// Handle undelegate(uint64, uint256, uint8) => bool
pub fn handle_undelegate<S: StakingStorage>(
    s: &mut S,
    input: &[u8],
    gas_limit: u64,
    caller: &Address,
) -> Result<(u64, Bytes), PrecompileError> {
    if gas_limit < gas::UNDELEGATE {
        return Err(PrecompileError::OutOfGas);
    }

    let call = undelegateCall::abi_decode_raw(&input[4..])
        .map_err(|e| PrecompileError::Other(format!("Invalid input: {e}").into()))?;

    // No-op for zero amount
    if call.amount.is_zero() {
        let encoded = undelegateCall::abi_encode_returns(&true);
        return Ok((gas::UNDELEGATE, encoded.into()));
    }

    let val = read_validator(s, call.validatorId)?;
    if !val.exists() {
        return Err(PrecompileError::Other("unknown validator".into()));
    }

    // Check withdrawal ID doesn't exist
    let existing_wr = read_u256(
        s,
        withdrawal_key(call.validatorId, caller, call.withdrawId, withdrawal_offsets::AMOUNT),
    )?;
    if !existing_wr.is_zero() {
        return Err(PrecompileError::Other("withdrawal id exists".into()));
    }

    // Pull delegator up to date
    let mut del = pull_delegator_up_to_date(s, call.validatorId, caller)?;

    // Check sufficient stake
    let mut amount = call.amount;
    if del.stake < amount {
        return Err(PrecompileError::Other("insufficient stake".into()));
    }

    // Dust collection
    let remaining = checked_sub_u256(del.stake, amount)?;
    if !remaining.is_zero() && remaining < DUST_THRESHOLD {
        amount = del.stake; // collect all including dust
    }

    // Save the accumulator before potential reset (needed for withdrawal request)
    let wr_acc = del.accumulated_reward_per_token;

    // Update delegator stake
    del.stake = checked_sub_u256(del.stake, amount)?;
    if del.stake.is_zero() {
        del.accumulated_reward_per_token = U256::ZERO;
    }

    // Update validator stake
    let mut val = read_validator(s, call.validatorId)?;
    val.stake = checked_sub_u256(val.stake, amount)?;
    write_validator_stake(s, call.validatorId, val.stake)?;

    // Update flags. Don't remove from valset here — removal happens at snapshot time
    // via pop-and-swap compaction at snapshot time.
    update_validator_flags_after_undelegate(s, call.validatorId, &val, &del, caller)?;

    // Create withdrawal request with the pre-reset accumulator
    let activation_epoch = get_activation_epoch(s)?;
    write_withdrawal_request(
        s,
        call.validatorId,
        caller,
        call.withdrawId,
        amount,
        wr_acc,
        activation_epoch,
    )?;
    increment_accumulator_refcount(s, call.validatorId)?;

    // Write updated delegator
    write_delegator(s, call.validatorId, caller, &del)?;

    // Remove from linked lists if no more stake
    if !del.exists() {
        linked_list_remove(s, call.validatorId, caller)?;
    }

    // Emit Undelegate event
    let topics = vec![
        Undelegate::SIGNATURE_HASH,
        B256::from(U256::from(call.validatorId)),
        B256::from(U256::from_be_slice(caller.as_slice())),
    ];
    let mut data = Vec::with_capacity(96);
    data.extend_from_slice(&U256::from(call.withdrawId).to_be_bytes::<32>());
    data.extend_from_slice(&amount.to_be_bytes::<32>());
    data.extend_from_slice(&U256::from(activation_epoch).to_be_bytes::<32>());
    emit_event(s, topics, data)?;

    let encoded = undelegateCall::abi_encode_returns(&true);
    Ok((gas::UNDELEGATE, encoded.into()))
}

/// Handle withdraw(uint64, uint8) => bool
pub fn handle_withdraw<S: StakingStorage>(
    s: &mut S,
    input: &[u8],
    gas_limit: u64,
    caller: &Address,
) -> Result<(u64, Bytes), PrecompileError> {
    if gas_limit < gas::WITHDRAW {
        return Err(PrecompileError::OutOfGas);
    }

    let call = withdrawCall::abi_decode_raw(&input[4..])
        .map_err(|e| PrecompileError::Other(format!("Invalid input: {e}").into()))?;

    // Load withdrawal request
    let wr_amount = read_u256(
        s,
        withdrawal_key(call.validatorId, caller, call.withdrawId, withdrawal_offsets::AMOUNT),
    )?;
    if wr_amount.is_zero() {
        return Err(PrecompileError::Other("unknown withdrawal id".into()));
    }
    let wr_acc = read_u256(
        s,
        withdrawal_key(call.validatorId, caller, call.withdrawId, withdrawal_offsets::ACCUMULATOR),
    )?;
    let wr_epoch = read_u64(
        s,
        withdrawal_key(call.validatorId, caller, call.withdrawId, withdrawal_offsets::EPOCH),
    )?;

    // Check withdrawal ready
    let current_epoch = read_epoch(s)?;
    if !is_epoch_active(current_epoch, wr_epoch) || wr_epoch + WITHDRAWAL_DELAY > current_epoch {
        return Err(PrecompileError::Other("withdrawal not ready".into()));
    }

    // Decrement accumulator and calculate rewards
    let epoch_acc = decrement_accumulator_refcount(s, wr_epoch, call.validatorId)?;
    let rewards = calculate_rewards(wr_amount, epoch_acc, wr_acc)?;

    // Check solvency
    let val = read_validator(s, call.validatorId)?;
    if val.unclaimed_rewards < rewards {
        return Err(PrecompileError::Other("solvency error".into()));
    }
    write_validator_unclaimed_rewards(
        s,
        call.validatorId,
        checked_sub_u256(val.unclaimed_rewards, rewards)?,
    )?;

    // Transfer total payout
    let total_payout = checked_add_u256(wr_amount, rewards)?;
    s.transfer(STAKING_ADDRESS, *caller, total_payout)?;

    // Clear withdrawal request
    clear_withdrawal_request(s, call.validatorId, caller, call.withdrawId)?;

    // Emit Withdraw event
    let topics = vec![
        Withdraw::SIGNATURE_HASH,
        B256::from(U256::from(call.validatorId)),
        B256::from(U256::from_be_slice(caller.as_slice())),
    ];
    let mut data = Vec::with_capacity(96);
    data.extend_from_slice(&U256::from(call.withdrawId).to_be_bytes::<32>());
    data.extend_from_slice(&total_payout.to_be_bytes::<32>());
    data.extend_from_slice(&U256::from(current_epoch).to_be_bytes::<32>());
    emit_event(s, topics, data)?;

    let encoded = withdrawCall::abi_encode_returns(&true);
    Ok((gas::WITHDRAW, encoded.into()))
}

/// Handle compound(uint64) => bool
pub fn handle_compound<S: StakingStorage>(
    s: &mut S,
    input: &[u8],
    gas_limit: u64,
    caller: &Address,
) -> Result<(u64, Bytes), PrecompileError> {
    if gas_limit < gas::COMPOUND {
        return Err(PrecompileError::OutOfGas);
    }

    let call = compoundCall::abi_decode_raw(&input[4..])
        .map_err(|e| PrecompileError::Other(format!("Invalid input: {e}").into()))?;

    let mut del = pull_delegator_up_to_date(s, call.validatorId, caller)?;

    if !del.rewards.is_zero() {
        let rewards = del.rewards;

        // Clear rewards (solvency already checked in pull_delegator_up_to_date via reward_invariant)
        del.rewards = U256::ZERO;
        write_delegator(s, call.validatorId, caller, &del)?;

        // Emit ClaimRewards event
        let epoch = read_epoch(s)?;
        let topics = vec![
            ClaimRewards::SIGNATURE_HASH,
            B256::from(U256::from(call.validatorId)),
            B256::from(U256::from_be_slice(caller.as_slice())),
        ];
        let mut data = Vec::with_capacity(64);
        data.extend_from_slice(&rewards.to_be_bytes::<32>());
        data.extend_from_slice(&U256::from(epoch).to_be_bytes::<32>());
        emit_event(s, topics, data)?;

        // Re-delegate the rewards (compound)
        internal_delegate(s, call.validatorId, caller, rewards)?;
    }

    let encoded = compoundCall::abi_encode_returns(&true);
    Ok((gas::COMPOUND, encoded.into()))
}

/// Handle addValidator(bytes, bytes, bytes) => uint64
pub fn handle_add_validator<S: StakingStorage>(
    s: &mut S,
    input: &[u8],
    gas_limit: u64,
    _caller: &Address,
    call_value: U256,
) -> Result<(u64, Bytes), PrecompileError> {
    if gas_limit < gas::ADD_VALIDATOR {
        return Err(PrecompileError::OutOfGas);
    }

    let call = addValidatorCall::abi_decode_raw(&input[4..])
        .map_err(|e| PrecompileError::Other(format!("Invalid input: {e}").into()))?;

    // Decode payload: secp_pubkey(33) + bls_pubkey(48) + auth_address(20) + signed_stake(32) + commission(32) = 165 bytes
    let payload = &call.payload;
    if payload.len() < 165 {
        return Err(PrecompileError::Other("invalid input".into()));
    }

    let mut secp_pubkey = [0u8; 33];
    secp_pubkey.copy_from_slice(&payload[0..33]);
    let mut bls_pubkey = [0u8; 48];
    bls_pubkey.copy_from_slice(&payload[33..81]);
    let auth_address = Address::from_slice(&payload[81..101]);
    let signed_stake = U256::from_be_slice(&payload[101..133]);
    let commission = U256::from_be_slice(&payload[133..165]);

    // Validate
    if call_value != signed_stake {
        return Err(PrecompileError::Other("invalid input".into()));
    }
    if call_value < MIN_AUTH_ADDRESS_STAKE {
        return Err(PrecompileError::Other("insufficient stake".into()));
    }
    if commission > MAX_COMMISSION {
        return Err(PrecompileError::Other("commission too high".into()));
    }

    // Skip signature verification (per design decision)

    // Derive addresses from pubkeys for existence check
    // For secp: use keccak256 of uncompressed pubkey to get eth address
    // For now, use the auth_address directly as the secp lookup key
    let secp_addr = auth_address; // simplified: use auth_address
    let bls_addr = Address::from_slice(&bls_pubkey[0..20]); // simplified: first 20 bytes

    // Check validator doesn't already exist
    let existing_secp = read_u64(s, val_id_secp_key(&secp_addr))?;
    if existing_secp != 0 {
        return Err(PrecompileError::Other("validator exists".into()));
    }
    let existing_bls = read_u64(s, super::storage::val_id_bls_key(&bls_addr))?;
    if existing_bls != 0 {
        return Err(PrecompileError::Other("validator exists".into()));
    }

    // Increment last_val_id
    let last_val_id = read_u64(s, global_slots::LAST_VAL_ID)?;
    let new_val_id = last_val_id + 1;
    write_storage_u64(s, global_slots::LAST_VAL_ID, new_val_id)?;

    // Store ID mappings
    write_storage_u64(s, val_id_secp_key(&secp_addr), new_val_id)?;
    write_storage_u64(s, super::storage::val_id_bls_key(&bls_addr), new_val_id)?;

    // Create validator
    let val = Validator {
        stake: U256::ZERO,
        accumulated_reward_per_token: U256::ZERO,
        commission,
        secp_pubkey,
        bls_pubkey,
        auth_address,
        flags: validator_flags::STAKE_TOO_LOW,
        unclaimed_rewards: U256::ZERO,
    };
    write_validator_full(s, new_val_id, &val)?;

    // Emit ValidatorCreated event
    let topics = vec![
        ValidatorCreated::SIGNATURE_HASH,
        B256::from(U256::from(new_val_id)),
        B256::from(U256::from_be_slice(auth_address.as_slice())),
    ];
    let data = commission.to_be_bytes::<32>().to_vec();
    emit_event(s, topics, data)?;

    // Delegate initial stake (from auth_address, not caller)
    internal_delegate(s, new_val_id, &auth_address, call_value)?;

    let encoded = addValidatorCall::abi_encode_returns(&new_val_id);
    Ok((gas::ADD_VALIDATOR, encoded.into()))
}

// ═══════════════════════════════════════════════════════════════════════════════
// getDelegator Write Handler
// ═══════════════════════════════════════════════════════════════════════════════

/// Handle getDelegator as a write operation.
///
/// The canonical implementation calls `pull_delegator_up_to_date` which writes settled
/// state to storage. The gas cost (184,900) includes warm_sstores.
pub fn handle_get_delegator_write<S: StakingStorage>(
    s: &mut S,
    input: &[u8],
    gas_limit: u64,
) -> Result<(u64, Bytes), PrecompileError> {
    if gas_limit < gas::GET_DELEGATOR {
        return Err(PrecompileError::OutOfGas);
    }

    let call = getDelegatorCall::abi_decode_raw(&input[4..])
        .map_err(|e| PrecompileError::Other(format!("Invalid input: {e}").into()))?;

    // pull_delegator_up_to_date persists settled state
    let del = pull_delegator_up_to_date(s, call.validatorId, &call.delegator)?;

    let encoded = getDelegatorCall::abi_encode_returns(&getDelegatorReturn {
        stake: del.stake,
        accRewardPerToken: del.accumulated_reward_per_token,
        unclaimedRewards: del.rewards,
        deltaStake: del.delta_stake,
        nextDeltaStake: del.next_delta_stake,
        deltaEpoch: del.delta_epoch,
        nextDeltaEpoch: del.next_delta_epoch,
    });
    Ok((gas::GET_DELEGATOR, encoded.into()))
}

// ═══════════════════════════════════════════════════════════════════════════════
// Syscall Handlers
// ═══════════════════════════════════════════════════════════════════════════════

/// Handle syscallReward(address) — distribute block rewards.
///
/// The block reward amount is resolved from two sources (in priority order):
/// 1. **Extended calldata**: If `input` is >= 68 bytes, the reward is read from
///    bytes `[36..68]` (appended after the standard ABI data). This is used by
///    [`crate::api::block::apply_syscall_reward`] for `SystemCallEvm` integration.
/// 2. **`msg.value`** (`call_value`): Fallback for direct calls (e.g., Foundry
///    `vm.prank(SYSTEM_ADDRESS)` with `{value: reward}`).
pub fn handle_syscall_reward<S: StakingStorage>(
    s: &mut S,
    input: &[u8],
    gas_limit: u64,
    caller: &Address,
    call_value: U256,
) -> Result<(u64, Bytes), PrecompileError> {
    if gas_limit < gas::SYSCALL_REWARD {
        return Err(PrecompileError::OutOfGas);
    }
    if *caller != SYSTEM_ADDRESS {
        return Err(PrecompileError::Other("Unauthorized: not system address".into()));
    }

    let call = syscallRewardCall::abi_decode_raw(&input[4..])
        .map_err(|e| PrecompileError::Other(format!("Invalid input: {e}").into()))?;

    let block_author = call.blockAuthor;

    // Resolve block reward: extended calldata (36..68) takes priority over msg.value
    // Standard ABI: 4 (selector) + 32 (address) = 36 bytes
    // Extended:     4 (selector) + 32 (address) + 32 (reward) = 68 bytes
    let block_reward =
        if input.len() >= 68 { U256::from_be_slice(&input[36..68]) } else { call_value };

    // Look up validator from block author address
    let val_id = read_u64(s, val_id_secp_key(&block_author))?;
    if val_id == 0 {
        // Unknown author — return NotInValidatorSet error
        return Err(PrecompileError::Other("not in validator set".into()));
    }

    // Get active stake from the appropriate view
    let in_boundary = read_in_boundary(s)?;
    let view_key =
        if in_boundary { snapshot_view_key(val_id, 0) } else { consensus_view_key(val_id, 0) };
    let active_stake = read_u256(s, view_key)?;
    if active_stake.is_zero() {
        // Zero active stake — return NotInValidatorSet error
        return Err(PrecompileError::Other("not in validator set".into()));
    }

    // Mint tokens: add block_reward to staking contract balance
    // Note: for syscalls, the balance isn't transferred via msg.value,
    // so we need to mint directly
    // We handle this by adding to staking address balance
    // (In the real implementation, mint_tokens adds to the STAKING_CA balance)

    // Get commission rate
    let commission_view_key =
        if in_boundary { snapshot_view_key(val_id, 1) } else { consensus_view_key(val_id, 1) };
    let commission_rate = read_u256(s, commission_view_key)?;

    // Calculate commission: commission_amount = (block_reward * commission_rate) / MON
    let commission_amount = checked_mul_div_u256(block_reward, commission_rate, MON)?;
    let del_reward = checked_sub_u256(block_reward, commission_amount)?;

    // Credit commission to auth address delegator rewards
    let val = read_validator(s, val_id)?;
    let auth_addr = val.auth_address;
    let mut auth_del = read_delegator(s, val_id, &auth_addr)?;
    auth_del.rewards = checked_add_u256(auth_del.rewards, commission_amount)?;
    write_delegator(s, val_id, &auth_addr, &auth_del)?;

    // Add del_reward (not block_reward) to unclaimed_rewards
    write_validator_unclaimed_rewards(
        s,
        val_id,
        checked_add_u256(val.unclaimed_rewards, del_reward)?,
    )?;

    // Apply reward to accumulator: acc += (del_reward * UNIT_BIAS) / active_stake
    if !del_reward.is_zero() && !active_stake.is_zero() {
        let reward_acc = checked_mul_div_u256(del_reward, UNIT_BIAS, active_stake)?;
        let new_acc = checked_add_u256(val.accumulated_reward_per_token, reward_acc)?;
        write_validator_acc(s, val_id, new_acc)?;
    }

    // Write proposer_val_id
    write_storage_u64(s, global_slots::PROPOSER_VAL_ID, val_id)?;

    // Emit ValidatorRewarded event
    let epoch = read_epoch(s)?;
    let topics = vec![
        ValidatorRewarded::SIGNATURE_HASH,
        B256::from(U256::from(val_id)),
        B256::from(U256::from_be_slice(SYSTEM_ADDRESS.as_slice())),
    ];
    let mut data = Vec::with_capacity(64);
    data.extend_from_slice(&del_reward.to_be_bytes::<32>());
    data.extend_from_slice(&U256::from(epoch).to_be_bytes::<32>());
    emit_event(s, topics, data)?;

    Ok((gas::SYSCALL_REWARD, Bytes::new()))
}

/// Handle syscallSnapshot() — take epoch boundary snapshot.
pub fn handle_syscall_snapshot<S: StakingStorage>(
    s: &mut S,
    _input: &[u8],
    gas_limit: u64,
    caller: &Address,
) -> Result<(u64, Bytes), PrecompileError> {
    if gas_limit < gas::SYSCALL_SNAPSHOT {
        return Err(PrecompileError::OutOfGas);
    }
    if *caller != SYSTEM_ADDRESS {
        return Err(PrecompileError::Other("Unauthorized: not system address".into()));
    }

    // Check not already in boundary
    let in_boundary = read_in_boundary(s)?;
    if in_boundary {
        return Err(PrecompileError::Other("called snapshot while in boundary".into()));
    }

    // Set in_epoch_delay_period = true (left-aligned bool: byte 0 = 1)
    let mut boundary_true = [0u8; 32];
    boundary_true[0] = 1;
    write_storage_u256(s, global_slots::IN_BOUNDARY, U256::from_be_bytes(boundary_true))?;

    // Read consensus set for snapshot
    let consensus_len = read_u64(s, valset_slots::CONSENSUS)?;

    // 1. Clear old snapshot set: pop each entry and clear its view slots
    let old_snapshot_len = read_u64(s, valset_slots::SNAPSHOT)?;
    for i in 0..old_snapshot_len {
        let old_val_id = read_u64(s, valset_slots::SNAPSHOT + U256::from(1 + i))?;
        write_storage_u256(s, snapshot_view_key(old_val_id, 0), U256::ZERO)?;
        write_storage_u256(s, snapshot_view_key(old_val_id, 1), U256::ZERO)?;
        write_storage_u64(s, valset_slots::SNAPSHOT + U256::from(1 + i), 0)?;
    }

    // 2. Copy consensus → snapshot (both array and view)
    write_storage_u64(s, valset_slots::SNAPSHOT, consensus_len)?;
    for i in 0..consensus_len {
        let val_id = read_u64(s, valset_slots::CONSENSUS + U256::from(1 + i))?;
        write_storage_u64(s, valset_slots::SNAPSHOT + U256::from(1 + i), val_id)?;

        // Copy consensus view → snapshot view
        let c_stake = read_u256(s, consensus_view_key(val_id, 0))?;
        let c_commission = read_u256(s, consensus_view_key(val_id, 1))?;
        write_storage_u256(s, snapshot_view_key(val_id, 0), c_stake)?;
        write_storage_u256(s, snapshot_view_key(val_id, 1), c_commission)?;
    }

    // 3. Clear old consensus set: pop each entry and clear its view slots
    for i in 0..consensus_len {
        let old_val_id = read_u64(s, valset_slots::CONSENSUS + U256::from(1 + i))?;
        write_storage_u256(s, consensus_view_key(old_val_id, 0), U256::ZERO)?;
        write_storage_u256(s, consensus_view_key(old_val_id, 1), U256::ZERO)?;
        write_storage_u64(s, valset_slots::CONSENSUS + U256::from(1 + i), 0)?;
    }

    // 4. Build new consensus set from execution set (top N by stake)
    let exec_len = read_u64(s, valset_slots::EXECUTION)?;
    let mut validators: Vec<(u64, U256)> = Vec::with_capacity(exec_len as usize);
    for i in 0..exec_len {
        let val_id = read_u64(s, valset_slots::EXECUTION + U256::from(1 + i))?;
        let stake = read_u256(s, validator_key(val_id, validator_offsets::STAKE))?;
        // Only include validators with OK flags
        let addr_flags = read_u256(s, validator_key(val_id, validator_offsets::ADDRESS_FLAGS))?
            .to_be_bytes::<32>();
        let flags = u64::from_be_bytes(addr_flags[20..28].try_into().unwrap());
        if flags == validator_flags::OK {
            validators.push((val_id, stake));
        }
    }

    // Sort by stake descending, then val_id ascending as tie-breaker
    validators.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));

    // Take top ACTIVE_VALSET_SIZE
    let new_consensus_len = validators.len().min(ACTIVE_VALSET_SIZE as usize);

    // 5. Write new consensus set with view
    write_storage_u64(s, valset_slots::CONSENSUS, new_consensus_len as u64)?;
    for (i, (val_id, _)) in validators.iter().take(new_consensus_len).enumerate() {
        write_storage_u64(s, valset_slots::CONSENSUS + U256::from(1 + i as u64), *val_id)?;
        // Write consensus view
        let val = read_validator(s, *val_id)?;
        write_storage_u256(s, consensus_view_key(*val_id, 0), val.stake)?;
        write_storage_u256(s, consensus_view_key(*val_id, 1), val.commission)?;
    }

    // Compact execution set: remove non-OK validators using pop-and-swap.
    // Re-read exec_len since we need the current value.
    let exec_len = read_u64(s, valset_slots::EXECUTION)?;
    let mut removals: Vec<u64> = Vec::new();
    for i in 0..exec_len {
        let vid = read_u64(s, valset_slots::EXECUTION + U256::from(1 + i))?;
        let addr_flags =
            read_u256(s, validator_key(vid, validator_offsets::ADDRESS_FLAGS))?.to_be_bytes::<32>();
        let flags = u64::from_be_bytes(addr_flags[20..28].try_into().unwrap());
        if flags != validator_flags::OK {
            removals.push(i);
        }
    }
    let mut current_len = exec_len;
    for &idx in removals.iter().rev() {
        let removed_vid = read_u64(s, valset_slots::EXECUTION + U256::from(1 + idx))?;
        remove_from_valset(s, removed_vid)?;
        current_len -= 1;
        if idx < current_len {
            let last_vid = read_u64(s, valset_slots::EXECUTION + U256::from(1 + current_len))?;
            write_storage_u64(s, valset_slots::EXECUTION + U256::from(1 + idx), last_vid)?;
        }
        write_storage_u64(s, valset_slots::EXECUTION + U256::from(1 + current_len), 0)?;
    }
    write_storage_u64(s, valset_slots::EXECUTION, current_len)?;

    Ok((gas::SYSCALL_SNAPSHOT, Bytes::new()))
}

/// Handle syscallOnEpochChange(uint64) — finalize epoch transition.
pub fn handle_syscall_on_epoch_change<S: StakingStorage>(
    s: &mut S,
    input: &[u8],
    gas_limit: u64,
    caller: &Address,
) -> Result<(u64, Bytes), PrecompileError> {
    if gas_limit < gas::SYSCALL_ON_EPOCH_CHANGE {
        return Err(PrecompileError::OutOfGas);
    }
    if *caller != SYSTEM_ADDRESS {
        return Err(PrecompileError::Other("Unauthorized: not system address".into()));
    }

    let call = syscallOnEpochChangeCall::abi_decode_raw(&input[4..])
        .map_err(|e| PrecompileError::Other(format!("Invalid input: {e}").into()))?;

    let current_epoch = read_epoch(s)?;
    // Allow any strictly increasing epoch (next > last), not just +1
    if call.epoch <= current_epoch {
        return Err(PrecompileError::Other("invalid epoch change".into()));
    }

    let next_epoch = call.epoch;
    let next_next_epoch = next_epoch + 1;

    // Emit EpochChanged event before state changes
    let topics = vec![EpochChanged::SIGNATURE_HASH];
    let mut data = Vec::with_capacity(64);
    data.extend_from_slice(&U256::from(current_epoch).to_be_bytes::<32>());
    data.extend_from_slice(&U256::from(next_epoch).to_be_bytes::<32>());
    emit_event(s, topics, data)?;

    // Update accumulator values for snapshot validators.
    // For each validator in the snapshot set, update existing accumulator entries
    // for next_epoch and next_epoch+1 to the current validator acc value.
    // This ensures delta_stake activations use the accumulator at epoch transition,
    // not the stale value from delegation time.
    let snapshot_len = read_u64(s, valset_slots::SNAPSHOT)?;
    for i in 0..snapshot_len {
        let val_slot = valset_slots::SNAPSHOT.saturating_add(U256::from(i + 1));
        let val_id = read_u64(s, val_slot)?;
        let current_val_acc =
            read_u256(s, validator_key(val_id, validator_offsets::ACCUMULATED_REWARD_PER_TOKEN))?;

        // Update accumulator for next_epoch if it has refcount > 0
        let acc_next = read_accumulator(s, next_epoch, val_id)?;
        if acc_next.refcount > 0 {
            write_accumulator(
                s,
                next_epoch,
                val_id,
                &RefCountedAccumulator { value: current_val_acc, refcount: acc_next.refcount },
            )?;
        }

        // Update accumulator for next_epoch+1 if it has refcount > 0
        let acc_next_next = read_accumulator(s, next_next_epoch, val_id)?;
        if acc_next_next.refcount > 0 {
            write_accumulator(
                s,
                next_next_epoch,
                val_id,
                &RefCountedAccumulator { value: current_val_acc, refcount: acc_next_next.refcount },
            )?;
        }
    }

    // Clear in_epoch_delay_period and set new epoch
    write_storage_u256(s, global_slots::IN_BOUNDARY, U256::ZERO)?;
    write_storage_u64(s, global_slots::EPOCH, next_epoch)?;

    Ok((gas::SYSCALL_ON_EPOCH_CHANGE, Bytes::new()))
}

// ═══════════════════════════════════════════════════════════════════════════════
// Dispatch Entry Point for Write Operations
// ═══════════════════════════════════════════════════════════════════════════════

/// Check if a selector corresponds to a payable function.
pub const fn is_payable_selector(selector: [u8; 4]) -> bool {
    matches!(
        selector,
        delegateCall::SELECTOR | addValidatorCall::SELECTOR | externalRewardCall::SELECTOR
    )
}

/// Check if a selector corresponds to a syscall.
pub const fn is_syscall_selector(selector: [u8; 4]) -> bool {
    matches!(
        selector,
        syscallRewardCall::SELECTOR
            | syscallSnapshotCall::SELECTOR
            | syscallOnEpochChangeCall::SELECTOR
    )
}

/// Check if a selector corresponds to a write function (user-callable, syscall, or mutating getter).
pub const fn is_write_selector(selector: [u8; 4]) -> bool {
    matches!(
        selector,
        delegateCall::SELECTOR
            | undelegateCall::SELECTOR
            | withdrawCall::SELECTOR
            | compoundCall::SELECTOR
            | claimRewardsCall::SELECTOR
            | addValidatorCall::SELECTOR
            | changeCommissionCall::SELECTOR
            | externalRewardCall::SELECTOR
            | syscallRewardCall::SELECTOR
            | syscallSnapshotCall::SELECTOR
            | syscallOnEpochChangeCall::SELECTOR
            | getDelegatorCall::SELECTOR
    )
}

/// Check that msg.value is zero (non-payable method guard).
/// Matches C++ `function_not_payable` which is called inside each non-payable method.
fn function_not_payable(call_value: &U256) -> Result<(), PrecompileError> {
    if !call_value.is_zero() {
        return Err(PrecompileError::Other("value non-zero".into()));
    }
    Ok(())
}

/// Create a fallback result for unknown/short selectors.
/// Consumes FALLBACK gas (40k) and returns "method not supported" revert.
fn fallback_result(gas_limit: u64) -> InterpreterResult {
    if gas_limit < gas::FALLBACK {
        return InterpreterResult {
            result: InstructionResult::PrecompileOOG,
            output: Bytes::new(),
            gas: Gas::new(gas_limit),
        };
    }
    let mut gas = Gas::new(gas_limit);
    let _ = gas.record_cost(gas_limit);
    InterpreterResult {
        result: InstructionResult::Revert,
        output: Bytes::from("method not supported"),
        gas,
    }
}

/// Dispatch a write operation using the StakingStorage trait.
///
/// Returns `Ok(InterpreterResult)` or `Err(String)`.
pub fn run_staking_write<S: StakingStorage>(
    input: &[u8],
    gas_limit: u64,
    storage: &mut S,
    caller: &Address,
    call_value: U256,
) -> Result<InterpreterResult, String> {
    // Short input routes to fallback with 40k gas cost
    let selector: [u8; 4] = match input.get(..4).and_then(|s| s.try_into().ok()) {
        Some(s) => s,
        None => return Ok(fallback_result(gas_limit)),
    };

    // Dispatch to handler. Payability is checked per-method (matching C++ dispatch-first
    // semantics). Unknown/fallback selectors don't check payability.
    let result = match selector {
        // Payable methods (accept msg.value)
        delegateCall::SELECTOR => handle_delegate(storage, input, gas_limit, caller, call_value),
        addValidatorCall::SELECTOR => {
            handle_add_validator(storage, input, gas_limit, caller, call_value)
        }
        externalRewardCall::SELECTOR => {
            handle_external_reward(storage, input, gas_limit, caller, call_value)
        }
        // Non-payable methods (reject msg.value > 0 inside dispatch)
        changeCommissionCall::SELECTOR => function_not_payable(&call_value)
            .and_then(|_| handle_change_commission(storage, input, gas_limit, caller)),
        claimRewardsCall::SELECTOR => function_not_payable(&call_value)
            .and_then(|_| handle_claim_rewards(storage, input, gas_limit, caller)),
        undelegateCall::SELECTOR => function_not_payable(&call_value)
            .and_then(|_| handle_undelegate(storage, input, gas_limit, caller)),
        withdrawCall::SELECTOR => function_not_payable(&call_value)
            .and_then(|_| handle_withdraw(storage, input, gas_limit, caller)),
        compoundCall::SELECTOR => function_not_payable(&call_value)
            .and_then(|_| handle_compound(storage, input, gas_limit, caller)),
        // Syscalls: reward accepts value, snapshot/epoch-change are non-payable.
        syscallRewardCall::SELECTOR => {
            handle_syscall_reward(storage, input, gas_limit, caller, call_value)
        }
        syscallSnapshotCall::SELECTOR => function_not_payable(&call_value)
            .and_then(|_| handle_syscall_snapshot(storage, input, gas_limit, caller)),
        syscallOnEpochChangeCall::SELECTOR => function_not_payable(&call_value)
            .and_then(|_| handle_syscall_on_epoch_change(storage, input, gas_limit, caller)),
        // Mutating getter (non-payable)
        getDelegatorCall::SELECTOR => function_not_payable(&call_value)
            .and_then(|_| handle_get_delegator_write(storage, input, gas_limit)),
        // Unknown selector → fallback (no payability check, just "method not supported")
        _ => return Ok(fallback_result(gas_limit)),
    };

    match result {
        Ok((gas_used, output)) => {
            let mut ir = InterpreterResult {
                result: InstructionResult::Return,
                gas: Gas::new(gas_limit),
                output,
            };
            if !ir.gas.record_cost(gas_used) {
                ir.result = InstructionResult::PrecompileOOG;
            }
            Ok(ir)
        }
        Err(e) => {
            // Consume all gas on revert (gas_left = 0)
            let mut gas = Gas::new(gas_limit);
            let _ = gas.record_cost(gas_limit);
            Ok(InterpreterResult {
                result: if e.is_oog() {
                    InstructionResult::PrecompileOOG
                } else {
                    InstructionResult::Revert
                },
                gas,
                output: Bytes::copy_from_slice(e.to_string().as_bytes()),
            })
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[derive(Default)]
    struct MockStorage {
        slots: HashMap<U256, U256>,
        logs: Vec<Log>,
        transfers: Vec<(Address, Address, U256)>,
    }

    impl MockStorage {
        fn set_u64_left(&mut self, key: U256, value: u64) {
            let mut bytes = [0u8; 32];
            bytes[..8].copy_from_slice(&value.to_be_bytes());
            self.slots.insert(key, U256::from_be_bytes(bytes));
        }

        fn get_u64_left(&self, key: U256) -> u64 {
            let value = self.slots.get(&key).copied().unwrap_or(U256::ZERO);
            let bytes = value.to_be_bytes::<32>();
            u64::from_be_bytes(bytes[..8].try_into().unwrap())
        }
    }

    impl StorageReader for MockStorage {
        fn sload(&mut self, key: U256) -> Result<U256, PrecompileError> {
            Ok(self.slots.get(&key).copied().unwrap_or(U256::ZERO))
        }
    }

    impl StakingStorage for MockStorage {
        fn sstore(&mut self, key: U256, value: U256) -> Result<(), PrecompileError> {
            self.slots.insert(key, value);
            Ok(())
        }

        fn transfer(
            &mut self,
            from: Address,
            to: Address,
            amount: U256,
        ) -> Result<(), PrecompileError> {
            self.transfers.push((from, to, amount));
            Ok(())
        }

        fn emit_log(&mut self, log: Log) -> Result<(), PrecompileError> {
            self.logs.push(log);
            Ok(())
        }
    }

    fn address_flags_slot(auth: Address, flags: u64) -> U256 {
        let mut bytes = [0u8; 32];
        bytes[..20].copy_from_slice(auth.as_slice());
        bytes[20..28].copy_from_slice(&flags.to_be_bytes());
        U256::from_be_bytes(bytes)
    }

    #[test]
    fn test_syscall_reward_accepts_nonzero_call_value() {
        let mut storage = MockStorage::default();

        let block_author = Address::new([0x11; 20]);
        let auth_address = Address::new([0x22; 20]);
        let val_id = 7u64;
        let reward = U256::from(5u64);

        // Resolve block author -> validator ID
        storage.set_u64_left(val_id_secp_key(&block_author), val_id);

        // Active in consensus set with zero commission.
        storage.slots.insert(consensus_view_key(val_id, 0), U256::from(10u64));
        storage.slots.insert(consensus_view_key(val_id, 1), U256::ZERO);

        // Validator metadata (exists + auth address).
        storage.slots.insert(
            validator_key(val_id, validator_offsets::ADDRESS_FLAGS),
            address_flags_slot(auth_address, validator_flags::OK),
        );

        // Standard ABI calldata (36 bytes). Reward comes from call_value.
        let input = syscallRewardCall { blockAuthor: block_author }.abi_encode();
        let result = run_staking_write(
            &input,
            gas::SYSCALL_REWARD + 1_000,
            &mut storage,
            &SYSTEM_ADDRESS,
            reward,
        )
        .expect("syscall reward should execute");

        assert_eq!(result.result, InstructionResult::Return);
        assert_eq!(result.output, Bytes::new());
        assert_eq!(storage.get_u64_left(global_slots::PROPOSER_VAL_ID), val_id);
        assert_eq!(
            storage
                .slots
                .get(&validator_key(val_id, validator_offsets::UNCLAIMED_REWARDS))
                .copied()
                .unwrap_or(U256::ZERO),
            reward
        );
    }

    #[test]
    fn test_snapshot_clears_stale_snapshot_and_consensus_views() {
        let mut storage = MockStorage::default();

        let old_snapshot_val = 11u64;
        let old_consensus_val = 22u64;
        let new_consensus_val = 33u64;

        // Old snapshot set with stale view.
        storage.set_u64_left(valset_slots::SNAPSHOT, 1);
        storage.set_u64_left(valset_slots::SNAPSHOT + U256::from(1u64), old_snapshot_val);
        storage.slots.insert(snapshot_view_key(old_snapshot_val, 0), U256::from(101u64));
        storage.slots.insert(snapshot_view_key(old_snapshot_val, 1), U256::from(202u64));

        // Old consensus set and view.
        storage.set_u64_left(valset_slots::CONSENSUS, 1);
        storage.set_u64_left(valset_slots::CONSENSUS + U256::from(1u64), old_consensus_val);
        storage.slots.insert(consensus_view_key(old_consensus_val, 0), U256::from(303u64));
        storage.slots.insert(consensus_view_key(old_consensus_val, 1), U256::from(404u64));

        // Execution set with one OK validator to become the new consensus entry.
        storage.set_u64_left(valset_slots::EXECUTION, 1);
        storage.set_u64_left(valset_slots::EXECUTION + U256::from(1u64), new_consensus_val);
        storage
            .slots
            .insert(validator_key(new_consensus_val, validator_offsets::STAKE), U256::from(999u64));
        storage.slots.insert(
            validator_key(new_consensus_val, validator_offsets::COMMISSION),
            U256::from(77u64),
        );
        storage.slots.insert(
            validator_key(new_consensus_val, validator_offsets::ADDRESS_FLAGS),
            address_flags_slot(Address::new([0x33; 20]), validator_flags::OK),
        );

        let (_gas, output) = handle_syscall_snapshot(
            &mut storage,
            &[],
            gas::SYSCALL_SNAPSHOT + 1_000,
            &SYSTEM_ADDRESS,
        )
        .expect("snapshot should succeed");
        assert!(output.is_empty());

        // Old snapshot val view cleared.
        assert_eq!(
            storage
                .slots
                .get(&snapshot_view_key(old_snapshot_val, 0))
                .copied()
                .unwrap_or(U256::ZERO),
            U256::ZERO
        );
        assert_eq!(
            storage
                .slots
                .get(&snapshot_view_key(old_snapshot_val, 1))
                .copied()
                .unwrap_or(U256::ZERO),
            U256::ZERO
        );

        // Old consensus val view cleared.
        assert_eq!(
            storage
                .slots
                .get(&consensus_view_key(old_consensus_val, 0))
                .copied()
                .unwrap_or(U256::ZERO),
            U256::ZERO
        );
        assert_eq!(
            storage
                .slots
                .get(&consensus_view_key(old_consensus_val, 1))
                .copied()
                .unwrap_or(U256::ZERO),
            U256::ZERO
        );

        // Snapshot now contains previous consensus val.
        assert_eq!(storage.get_u64_left(valset_slots::SNAPSHOT), 1);
        assert_eq!(
            storage.get_u64_left(valset_slots::SNAPSHOT + U256::from(1u64)),
            old_consensus_val
        );
        assert_eq!(
            storage
                .slots
                .get(&snapshot_view_key(old_consensus_val, 0))
                .copied()
                .unwrap_or(U256::ZERO),
            U256::from(303u64)
        );
        assert_eq!(
            storage
                .slots
                .get(&snapshot_view_key(old_consensus_val, 1))
                .copied()
                .unwrap_or(U256::ZERO),
            U256::from(404u64)
        );

        // Consensus rebuilt from execution.
        assert_eq!(storage.get_u64_left(valset_slots::CONSENSUS), 1);
        assert_eq!(
            storage.get_u64_left(valset_slots::CONSENSUS + U256::from(1u64)),
            new_consensus_val
        );
        assert_eq!(
            storage
                .slots
                .get(&consensus_view_key(new_consensus_val, 0))
                .copied()
                .unwrap_or(U256::ZERO),
            U256::from(999u64)
        );
        assert_eq!(
            storage
                .slots
                .get(&consensus_view_key(new_consensus_val, 1))
                .copied()
                .unwrap_or(U256::ZERO),
            U256::from(77u64)
        );
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Checked arithmetic helper unit tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_checked_add_normal() {
        assert_eq!(checked_add_u256(U256::from(1), U256::from(2)).unwrap(), U256::from(3));
    }

    #[test]
    fn test_checked_add_overflow_reverts() {
        let result = checked_add_u256(U256::MAX, U256::from(1));
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().to_string(), "internal error");
    }

    #[test]
    fn test_checked_sub_normal() {
        assert_eq!(checked_sub_u256(U256::from(5), U256::from(3)).unwrap(), U256::from(2));
    }

    #[test]
    fn test_checked_sub_underflow_reverts() {
        let result = checked_sub_u256(U256::from(3), U256::from(5));
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().to_string(), "internal error");
    }

    #[test]
    fn test_checked_mul_div_normal() {
        // (10 * 3) / 5 = 6
        assert_eq!(
            checked_mul_div_u256(U256::from(10), U256::from(3), U256::from(5)).unwrap(),
            U256::from(6)
        );
    }

    #[test]
    fn test_checked_mul_div_overflow_reverts() {
        let result = checked_mul_div_u256(U256::MAX, U256::from(2), U256::from(1));
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().to_string(), "internal error");
    }

    #[test]
    fn test_checked_mul_div_zero_divisor_reverts() {
        let result = checked_mul_div_u256(U256::from(10), U256::from(3), U256::ZERO);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().to_string(), "internal error");
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Reward calculation overflow tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_calculate_rewards_normal() {
        // reward = (stake * (epoch_acc - last_acc)) / UNIT_BIAS
        let stake = U256::from(1000) * MON;
        let last_acc = U256::from(100);
        let epoch_acc = U256::from(200);
        let result = calculate_rewards(stake, epoch_acc, last_acc);
        assert!(result.is_ok());
    }

    #[test]
    fn test_calculate_rewards_zero_stake() {
        let result = calculate_rewards(U256::ZERO, U256::from(100), U256::from(100));
        assert_eq!(result.unwrap(), U256::ZERO);
    }

    #[test]
    fn test_calculate_rewards_epoch_acc_eq_last_acc() {
        let result = calculate_rewards(U256::from(1000), U256::from(100), U256::from(100));
        assert_eq!(result.unwrap(), U256::ZERO);
    }

    #[test]
    fn test_calculate_rewards_epoch_acc_lt_last_acc_reverts() {
        let result = calculate_rewards(U256::from(1000), U256::from(100), U256::from(200));
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().to_string(), "internal error");
    }

    #[test]
    fn test_calculate_rewards_overflow_reverts() {
        // stake * diff would overflow U256 when both are near MAX
        let result = calculate_rewards(U256::MAX, U256::MAX, U256::ZERO);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().to_string(), "internal error");
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Syscall reward overflow tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_syscall_reward_commission_mul_overflow_reverts() {
        let mut storage = MockStorage::default();
        let block_author = Address::new([0x11; 20]);
        let auth_address = Address::new([0x22; 20]);
        let val_id = 1u64;

        // Setup validator
        storage.set_u64_left(val_id_secp_key(&block_author), val_id);
        storage.slots.insert(consensus_view_key(val_id, 0), U256::from(10u64));
        // Commission rate near MAX to trigger mul overflow with large reward
        storage.slots.insert(consensus_view_key(val_id, 1), U256::MAX);
        storage.slots.insert(
            validator_key(val_id, validator_offsets::ADDRESS_FLAGS),
            address_flags_slot(auth_address, validator_flags::OK),
        );

        let input = syscallRewardCall { blockAuthor: block_author }.abi_encode();
        // block_reward near MAX * commission_rate near MAX → overflow
        let result = run_staking_write(
            &input,
            gas::SYSCALL_REWARD + 1_000,
            &mut storage,
            &SYSTEM_ADDRESS,
            U256::MAX / U256::from(2),
        )
        .expect("dispatch should not error");

        // Should revert (not silently clamp)
        assert_eq!(result.result, InstructionResult::Revert);
    }

    #[test]
    fn test_syscall_reward_normal_values_succeed() {
        let mut storage = MockStorage::default();
        let block_author = Address::new([0x11; 20]);
        let auth_address = Address::new([0x22; 20]);
        let val_id = 1u64;
        let block_reward = U256::from(2) * MON; // 2 MON

        // Setup validator
        storage.set_u64_left(val_id_secp_key(&block_author), val_id);
        storage.slots.insert(consensus_view_key(val_id, 0), U256::from(100) * MON);
        // 10% commission
        storage.slots.insert(consensus_view_key(val_id, 1), MON / U256::from(10));
        storage.slots.insert(
            validator_key(val_id, validator_offsets::ADDRESS_FLAGS),
            address_flags_slot(auth_address, validator_flags::OK),
        );

        let input = syscallRewardCall { blockAuthor: block_author }.abi_encode();
        let result = run_staking_write(
            &input,
            gas::SYSCALL_REWARD + 1_000,
            &mut storage,
            &SYSTEM_ADDRESS,
            block_reward,
        )
        .expect("dispatch should not error");

        assert_eq!(result.result, InstructionResult::Return);
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // External reward overflow tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_external_reward_accumulator_overflow_reverts() {
        let mut storage = MockStorage::default();
        let caller = Address::new([0xAA; 20]);
        let val_id = 1u64;

        // Setup validator with accumulator near MAX
        storage.slots.insert(
            validator_key(val_id, validator_offsets::ADDRESS_FLAGS),
            address_flags_slot(caller, validator_flags::OK),
        );
        storage.slots.insert(
            validator_key(val_id, validator_offsets::ACCUMULATED_REWARD_PER_TOKEN),
            U256::MAX,
        );
        storage.slots.insert(consensus_view_key(val_id, 0), U256::from(1u64));
        storage.slots.insert(consensus_view_key(val_id, 1), U256::ZERO);

        // call_value * UNIT_BIAS overflows when call_value is large
        let call_value = MAX_EXTERNAL_REWARD;
        let input = externalRewardCall { validatorId: val_id }.abi_encode();
        let result = handle_external_reward(
            &mut storage,
            &input,
            gas::EXTERNAL_REWARD + 1_000,
            &caller,
            call_value,
        );

        // Should fail because new_acc = MAX + reward_acc overflows
        assert!(result.is_err());
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Delegate overflow tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_internal_delegate_validator_stake_overflow_reverts() {
        let mut storage = MockStorage::default();
        let caller = Address::new([0xBB; 20]);
        let val_id = 1u64;

        // Validator exists with stake near MAX
        storage.slots.insert(
            validator_key(val_id, validator_offsets::ADDRESS_FLAGS),
            address_flags_slot(caller, validator_flags::OK),
        );
        storage.slots.insert(validator_key(val_id, validator_offsets::STAKE), U256::MAX);
        // Set epoch so pull_delegator_up_to_date works
        storage.set_u64_left(global_slots::EPOCH, 1);

        // Delegate amount that would overflow validator stake
        let result = internal_delegate(&mut storage, val_id, &caller, U256::from(1));

        assert!(result.is_err());
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Withdraw payout overflow tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_withdraw_payout_overflow_reverts() {
        let mut storage = MockStorage::default();
        let caller = Address::new([0xCC; 20]);
        let val_id = 1u64;
        let wid = 0u8;

        // Withdrawal request with near-MAX amount
        storage
            .slots
            .insert(withdrawal_key(val_id, &caller, wid, withdrawal_offsets::AMOUNT), U256::MAX);
        // Accumulator with diff that would produce non-zero rewards
        storage.slots.insert(
            withdrawal_key(val_id, &caller, wid, withdrawal_offsets::ACCUMULATOR),
            U256::from(1u64),
        );
        // Withdrawal epoch set to far past
        let mut wr_epoch_bytes = [0u8; 32];
        wr_epoch_bytes[..8].copy_from_slice(&1u64.to_be_bytes());
        storage.slots.insert(
            withdrawal_key(val_id, &caller, wid, withdrawal_offsets::EPOCH),
            U256::from_be_bytes(wr_epoch_bytes),
        );

        // Current epoch well past withdrawal delay
        storage.set_u64_left(global_slots::EPOCH, 100);

        // Accumulator for epoch 1, val_id: has refcount and value > wr_acc
        storage.slots.insert(accumulator_key(1, val_id, 0), U256::from(100u64));
        storage.slots.insert(accumulator_key(1, val_id, 1), U256::from(1u64));

        // Validator unclaimed_rewards large enough for solvency
        storage
            .slots
            .insert(validator_key(val_id, validator_offsets::UNCLAIMED_REWARDS), U256::MAX);
        storage.slots.insert(
            validator_key(val_id, validator_offsets::ADDRESS_FLAGS),
            address_flags_slot(caller, validator_flags::OK),
        );

        let input = withdrawCall { validatorId: val_id, withdrawId: wid }.abi_encode();
        let result = handle_withdraw(&mut storage, &input, gas::WITHDRAW + 1_000, &caller);

        // calculate_rewards with stake=MAX and acc diff will overflow in mul_div
        assert!(result.is_err());
    }
}