newton-chainio 0.5.2

newton prover chainio
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
//! AvsWriter

use crate::{
    avs::{
        cancel::{self, CancelOutcome, CancelParams, NonceCanceller},
        errors,
        nonce_allocator::NonceAllocator,
    },
    error::ChainIoError,
};
use alloy::{
    consensus::Transaction as _,
    contract::{CallBuilder, Error as ContractError},
    network::TransactionBuilder,
    primitives::{Address, Bytes, B256, U256},
    providers::{PendingTransactionError, Provider, SendableTx, WalletProvider},
    rpc::types::{TransactionReceipt, TransactionRequest},
    signers::local::PrivateKeySigner,
    sol_types::{SolCall, SolError, SolType},
    transports::{TransportError, TransportErrorKind},
};
use eigensdk::{
    common::{get_signer, SdkSigner},
    types::operator::{QuorumNum, QuorumThresholdPercentage},
};
use hex;
use newton_core::{
    batch_task_manager::{
        BatchTaskManager::BatchTaskManagerInstance,
        INewtonProverTaskManager::{Task as BatchTask, TaskResponse as BatchTaskResponse},
    },
    challenge_verifier::{
        INewtonProverTaskManager::{
            ResponseCertificate as CvResponseCertificate, Task as CvTask, TaskResponse as CvTaskResponse,
        },
        BN254::G1Point as CvG1Point,
    },
    common::task_id,
    config::key::EcdsaKey,
    keys::{error::KeyError, load_ecdsa},
    newton_prover_service_manager::NewtonProverServiceManager,
    newton_prover_task_manager::{
        INewtonProverTaskManager::{ChallengeData, ResponseCertificate, Task, TaskResponse},
        NewtonMessage,
        NewtonProverTaskManager::{
            self,
            // Input validation errors
            BitmapValueTooLarge,
            BytesArrayLengthTooLong,
            BytesArrayNotOrdered,
            // Pause/state errors
            CurrentlyPaused,
            // BLS/Crypto errors
            ECAddFailed,
            ECMulFailed,
            ExpModFailed,
            InputAddressZero,
            InputArrayLengthMismatch,
            InputEmptyQuorumNumbers,
            InputNonSignerLengthMismatch,
            InvalidBLSPairingKey,
            InvalidBLSSignature,
            InvalidNewPausedStatus,
            InvalidQuorumApkHash,
            // Task lifecycle errors
            InvalidReferenceBlocknumber,
            NonSignerPubkeysNotSorted,
            // Access control errors
            OnlyPauser,
            OnlyRegistryCoordinatorOwner,
            OnlyTaskGenerator,
            OnlyUnpauser,
            // Operator errors
            ScalarTooLarge,
            TaskAlreadyExists,
            TaskAlreadyResponded,
            TaskMismatch,
        },
        BN254::G1Point,
    },
    state_commit_registry::{
        IStateRootCommittable::StateCommit,
        StateCommitRegistry::{
            self, CertificateMessageHashMismatch, InvalidNewStateRoot, InvalidPcr0Commitment, InvalidSealedSnapshot,
            SequenceGap, StateCommitRegistryInstance, StateRootMismatch, TimestampRegression,
            UnsupportedStateCommitVersion,
        },
    },
    TaskId,
};
use std::{str::FromStr, sync::Arc, time::Duration};
use tokio::time::timeout;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, warn};

/// Receipt timeout for `commitStateRoot` transactions.
///
/// Flat 60s across all chains (not chain-adaptive like `batch_receipt_timeout`).
/// Rationale: the protocol commit cadence is fixed at 120s regardless of
/// underlying block time, so a flat half-cadence timeout gives consistent
/// retry behavior on every chain — and ensures a stuck commit never blocks
/// the next aggregator's prepare-phase tick.
///
/// See `docs/PRIVATE_DATA_STORAGE.md` §6.1 for the 120s commit-cadence rationale.
pub const STATE_COMMIT_RECEIPT_TIMEOUT: Duration = Duration::from_secs(60);

/// Outcome of a successful batch broadcast: the transaction hash plus the
/// nonce the signer's filler stack assigned to it.
///
/// Capturing the nonce at send time is the linchpin of nonce-anchored
/// submission: it lets the receipt tracker gas-bump or cancel the exact slot
/// without re-deriving it via `eth_getTransactionByHash` (which returns `None`
/// once the original is evicted from the mempool, orphaning the nonce). See
/// `docs/BATCH_SUBMISSION_NONCE_ANCHORING.md`.
#[derive(Debug, Clone, Copy)]
pub struct BroadcastedTx {
    /// Hash of the broadcast transaction.
    pub tx_hash: B256,
    /// Nonce assigned by the signer's `NonceFiller`.
    pub nonce: u64,
    /// `max_fee_per_gas` the transaction was broadcast with (0 if the node
    /// assigned it and we couldn't read it back — callers floor against this).
    pub max_fee_per_gas: u128,
    /// `max_priority_fee_per_gas` the transaction was broadcast with.
    pub max_priority_fee_per_gas: u128,
}

/// Multiple of `base_fee` reserved as `max_fee` headroom so the full priority
/// tip stays realizable as the base fee rises while a replacement is pending,
/// expressed as `NUM/DEN` (= 2.5×). EIP-1559 caps base-fee growth at 12.5%/block,
/// so 2.5× ≈ 8 blocks of runway (1.125^8 ≈ 2.57) — leans aggressive so the bid
/// stays competitive through a sustained spike. `max_fee` is only a ceiling on
/// what we'd pay, not the actual cost (you pay `base_fee + tip`), so a generous
/// multiple costs nothing when the market is calm.
const BASE_FEE_HEADROOM_NUM: u128 = 5;
const BASE_FEE_HEADROOM_DEN: u128 = 2;

/// Default absolute `max_fee_per_gas` ceiling for escalating replacement/cancel
/// txs: 5000 gwei. A finite default (not `u128::MAX`) so even an `AvsWriter`
/// whose ceiling isn't explicitly configured still has a backstop against a
/// runaway bump/cancel loop — the failure mode that priced a 21k cancel at
/// ~786k gwei. Callers override via [`AvsWriter::with_max_fee_per_gas_ceiling`].
pub const DEFAULT_MAX_FEE_PER_GAS_CEILING_WEI: u128 = 5_000 * 1_000_000_000;

/// Compute escalating replacement fees from a market quote `(base_fee,
/// market_priority)` and the previous attempt's fees. Returns
/// `(max_fee_per_gas, max_priority_fee_per_gas)` satisfying three properties:
///
/// 1. **Competitive, monotonic tip.** `priority = max(market_priority,
///    prev_prio × 1.10)` — tracks the live market tip AND always clears the
///    node's ≥10% replacement floor on the priority field, so the bid never
///    stalls and the replacement is never rejected "underpriced".
///
/// 2. **Realizable tip (the point of this function).** A validator's actual
///    tip is `min(priority, max_fee − base_fee)`, so a high priority bid is
///    wasted unless `max_fee` has headroom above `base_fee`. We size
///    `max_fee ≥ base_fee × 2.5 + priority`, which guarantees `max_fee − base_fee
///    ≥ priority` even as the base fee climbs across the blocks a replacement
///    waits — so the FULL priority reaches the validator, not a throttled
///    fraction. `max_fee` also clears its own ≥10% floor (`prev_max_fee × 1.10`)
///    so the max-fee field never trips the replacement rule either.
///
/// 3. **Bounded.** Both fields are clamped to `ceiling` (absolute `max_fee`
///    backstop, wei), and `priority` is re-clamped to the post-ceiling `max_fee`
///    so `priority ≤ max_fee` always holds. Pass `u128::MAX` to disable.
///
/// When the market quote is unavailable (`None` — fee-history RPC down), fall
/// back to bumping the previous fees by the floor only. The tip still climbs,
/// but without a fresh `base_fee` the headroom guarantee can't be recomputed;
/// the prior `max_fee` (which already carried headroom) is escalated as-is.
/// Pure function for unit testing.
fn escalate_floor(market: Option<(u128, u128)>, prev_max_fee: u128, prev_prio: u128, ceiling: u128) -> (u128, u128) {
    // Priority: track the market tip, floored at a ≥10% bump over the previous.
    let market_prio = market.map(|(_, p)| p).unwrap_or(0);
    let prio = market_prio.max(prev_prio.saturating_mul(110) / 100);

    // Max fee: clear its own ≥10% replacement floor, and — when we have a fresh
    // base fee — reserve enough headroom that the full `prio` is realizable as a
    // tip (`max_fee − base_fee ≥ prio`) even as the base fee rises.
    let floor_max = prev_max_fee.saturating_mul(110) / 100;
    let max_fee = match market {
        Some((base_fee, _)) => {
            let with_headroom = base_fee
                .saturating_mul(BASE_FEE_HEADROOM_NUM)
                .saturating_div(BASE_FEE_HEADROOM_DEN)
                .saturating_add(prio);
            floor_max.max(with_headroom)
        }
        None => floor_max,
    };

    // Apply the absolute ceiling, then keep priority ≤ (clamped) max_fee.
    let max_fee = max_fee.min(ceiling);
    let prio = prio.min(max_fee);
    (max_fee, prio)
}

/// load a signer from an ECDSA key and RPC URL
pub fn load_signer(ecdsa_key: &EcdsaKey, rpc_url: &str) -> eyre::Result<SdkSigner> {
    let signer = load_ecdsa(ecdsa_key)?;
    let signer_private_key = hex::encode(signer.to_field_bytes());
    Ok(get_signer(&signer_private_key, rpc_url))
}

/// AvsWriter struct
#[derive(Debug, Clone)]
pub struct AvsWriter {
    /// task manager
    task_manager_addr: Address,
    /// identity registry
    identity_registry_addr: Address,
    /// state commit registry — anchors the unified per-chain JMT root via
    /// 120s BLS-gated `commitStateRoot` calls. Sourced from the deployment
    /// JSON (`addresses.stateCommitRegistry`) at config load and passed through
    /// `NewtonAvsContractsConfig.state_commit_registry`; callers materialize
    /// `Address::ZERO` via `unwrap_or` when the registry hasn't been deployed
    /// on this chain yet. `commit_state_root` runtime-guards against the zero
    /// address so callers degrade gracefully on chains without PDS wiring.
    state_commit_registry_addr: Address,
    /// Provider used for signing and broadcasting transactions
    signer_provider: SdkSigner,
    /// signer
    pub signer: EcdsaKey,
    /// rpc url
    pub rpc_url: String,
    /// Chain ID — used for chain-adaptive tuning (e.g., receipt timeout)
    pub chain_id: u64,
    /// Absolute `max_fee_per_gas` ceiling (wei) for escalating replacement and
    /// cancel transactions. Defaults to [`DEFAULT_MAX_FEE_PER_GAS_CEILING_WEI`]
    /// (5000 gwei) — a finite backstop so a runaway bump/cancel loop can never
    /// price a tx above the signer's means and lock the slot in an
    /// unaffordable-and-still-climbing state. Only ever consulted on the
    /// escalation path (`gas_bump_batch_tx`/`cancel_nonce`), so it never
    /// interferes with normal node-priced sends. The batch submitter overrides
    /// it from config via [`with_max_fee_per_gas_ceiling`]. See `escalate_floor`.
    ///
    /// [`with_max_fee_per_gas_ceiling`]: AvsWriter::with_max_fee_per_gas_ceiling
    max_fee_per_gas_ceiling: u128,
    /// Optional owned nonce allocator. When `Some`, every broadcast path reserves
    /// its nonce here and sets it explicitly on the request, so alloy's
    /// `CachedNonceManager` never allocates and a failed broadcast can release the
    /// slot (gas-estimate revert) or drive it through confirm-or-cancel (send
    /// failure) instead of orphaning it. MUST be shared (same `Arc`) across every
    /// `AvsWriter` on a given signer — see [`NonceAllocator`] — so the explicit
    /// sequence has a single source of truth. When `None`, nonces fall back to the
    /// implicit filler allocation (legacy behavior for standalone writers).
    nonce_allocator: Option<Arc<NonceAllocator>>,
    /// Optional shutdown signal for the unbounded stuck-nonce cancel loop. When
    /// `Some`, an inline cancel resolution (`resolve_stuck_nonce`) exits promptly
    /// on shutdown instead of retrying forever; when `None` the loop is truly
    /// unbounded (acceptable for short-lived/standalone writers).
    cancel_token: Option<CancellationToken>,
}

/// Parameters for creating a task onchain
/// Note: policyTaskData is no longer sent with createNewTask - operators generate it independently
#[derive(Debug, Clone)]
pub struct SendTaskParams {
    /// Task ID
    pub task_id: TaskId,
    /// Task created block - the offchain estimated block number used as single source of truth
    /// for BLS signature verification. Must be > 0, < current block, and within 256 blocks.
    pub task_created_block: u32,
    /// Task request WASM args for operators to generate policyTaskData
    pub wasm_args: Bytes,
    /// Policy client address
    pub policy_client: Address,
    /// Intent
    pub intent: NewtonMessage::Intent,
    /// Intent signature
    pub intent_signature: Option<Bytes>,
    /// Quorum number
    pub quorum_number: Vec<QuorumNum>,
    /// Quorum threshold percentage
    pub quorum_threshold_percentage: QuorumThresholdPercentage,
    /// timestamp marking the offchain ingestion of the task
    pub initialization_timestamp: u64,
}

/// Parameters for challenging a privacy task with missing or invalid TEE attestation.
#[derive(Clone)]
#[allow(missing_debug_implementations)]
pub struct TeeAttestationChallengeParams {
    /// ChallengeVerifier contract address
    pub challenge_verifier_addr: Address,
    /// The task being challenged
    pub task: Task,
    /// The task response being challenged
    pub task_response: TaskResponse,
    /// Response certificate (for challenge window check)
    pub task_response_metadata: ResponseCertificate,
    /// SP1 attestation proof public values (empty for missing attestation)
    pub attestation_proof_data: Bytes,
    /// SP1 Groth16 proof bytes (empty for missing attestation)
    pub attestation_proof_bytes: Bytes,
    /// BLS G1 pubkeys of non-signing operators
    pub pub_keys_of_non_signing_operators: Vec<G1Point>,
}

impl AvsWriter {
    /// new instance
    pub async fn new(
        task_manager_addr: Address,
        identity_registry_addr: Address,
        state_commit_registry_addr: Address,
        rpc_url: String,
        signer: EcdsaKey,
        chain_id: u64,
    ) -> Result<Self, ChainIoError> {
        let signer_provider = load_signer(&signer, &rpc_url).map_err(ChainIoError::SignerError)?;

        Ok(AvsWriter {
            task_manager_addr,
            identity_registry_addr,
            state_commit_registry_addr,
            signer_provider,
            signer,
            rpc_url,
            chain_id,
            max_fee_per_gas_ceiling: DEFAULT_MAX_FEE_PER_GAS_CEILING_WEI,
            nonce_allocator: None,
            cancel_token: None,
        })
    }

    /// Attach a shared owned nonce allocator. Builder-style; without it the writer
    /// uses the implicit filler nonce (legacy). Pass the SAME `Arc` to every
    /// `AvsWriter` sharing a signer so the explicit nonce sequence is coordinated.
    pub fn with_nonce_allocator(mut self, allocator: Arc<NonceAllocator>) -> Self {
        self.nonce_allocator = Some(allocator);
        self
    }

    /// Attach a shutdown signal so the unbounded stuck-nonce cancel loop exits
    /// promptly on shutdown instead of retrying forever. Builder-style; without
    /// it the loop is truly unbounded (fine for short-lived/standalone writers).
    pub fn with_cancel_token(mut self, token: CancellationToken) -> Self {
        self.cancel_token = Some(token);
        self
    }

    /// The shared nonce allocator, if one is attached. Exposed so the batch
    /// submitter can resync it on gap detection and the startup/runtime sweep can
    /// reconcile it with the chain.
    pub fn nonce_allocator(&self) -> Option<&Arc<NonceAllocator>> {
        self.nonce_allocator.as_ref()
    }

    /// Reserve an explicit nonce from the allocator if one is attached. Direct
    /// `.send()` paths (`send_task`, `commit_state_root`) call this and pin the
    /// result on the contract call so the implicit `CachedNonceManager` stays
    /// inert and their nonces stay coordinated with the batch path. Returns `None`
    /// when no allocator is attached (legacy implicit-nonce behavior).
    async fn reserve_nonce(&self) -> Result<Option<u64>, ChainIoError> {
        match self.nonce_allocator.as_ref() {
            Some(alloc) => Ok(Some(alloc.reserve().await?)),
            None => Ok(None),
        }
    }

    /// Override the absolute `max_fee_per_gas` ceiling (wei) for escalating
    /// replacement and cancel transactions. Builder-style; without it the writer
    /// keeps the finite [`DEFAULT_MAX_FEE_PER_GAS_CEILING_WEI`] backstop. A value
    /// of 0 is treated as "explicitly disabled" (`u128::MAX`) so an operator can
    /// opt out via config, while a mis-set/zeroed value can never make every
    /// replacement unpriced.
    pub fn with_max_fee_per_gas_ceiling(mut self, ceiling_wei: u128) -> Self {
        self.max_fee_per_gas_ceiling = if ceiling_wei == 0 { u128::MAX } else { ceiling_wei };
        self
    }

    /// Create a new instance with a shared `SdkSigner` provider.
    ///
    /// Use this when multiple `AvsWriter` instances share the same signing key
    /// so they share a single nonce manager and avoid "nonce too low" races.
    pub fn new_with_provider(
        task_manager_addr: Address,
        identity_registry_addr: Address,
        state_commit_registry_addr: Address,
        rpc_url: String,
        signer: EcdsaKey,
        signer_provider: SdkSigner,
        chain_id: u64,
    ) -> Self {
        // Verify signer key matches the provider's wallet (debug builds only)
        #[cfg(debug_assertions)]
        {
            use alloy::providers::WalletProvider;
            if let Ok(loaded) = load_ecdsa(&signer) {
                debug_assert_eq!(
                    signer_provider.default_signer_address(),
                    loaded.address(),
                    "signer key and provider wallet address must match"
                );
            }
        }
        AvsWriter {
            task_manager_addr,
            identity_registry_addr,
            state_commit_registry_addr,
            signer_provider,
            signer,
            rpc_url,
            chain_id,
            max_fee_per_gas_ceiling: DEFAULT_MAX_FEE_PER_GAS_CEILING_WEI,
            nonce_allocator: None,
            cancel_token: None,
        }
    }

    /// get task manager address
    pub fn task_manager_addr(&self) -> Address {
        self.task_manager_addr
    }

    /// get identity registry address
    pub fn identity_registry_addr(&self) -> Address {
        self.identity_registry_addr
    }

    /// get state commit registry address (`Address::ZERO` if not present in deployment JSON for this chain)
    pub fn state_commit_registry_addr(&self) -> Address {
        self.state_commit_registry_addr
    }

    /// Reference to the underlying RPC provider bound to this writer's chain.
    ///
    /// Exposed for read-only callers that need to issue arbitrary chain queries
    /// against the same provider (e.g., `eth_getTransactionByHash` for replaying
    /// historical `commitStateRoot` calldata in PDS Path A* signed-read).
    pub fn provider(&self) -> &SdkSigner {
        &self.signer_provider
    }

    /// Returns the current block number from the chain's RPC provider.
    pub async fn get_block_number(&self) -> Result<u64, ChainIoError> {
        Ok(self.signer_provider.get_block_number().await?)
    }

    /// Transaction count for the signer address. `pending = true` includes
    /// mempool transactions; `false` counts only mined transactions. The gap
    /// `pending − latest` > 0 indicates a wedged nonce slot (a broadcast TX
    /// that hasn't mined). Used for the `signer_nonce_gap` metric and the
    /// startup gap sweep.
    pub async fn signer_transaction_count(&self, pending: bool) -> Result<u64, ChainIoError> {
        let addr = self.signer_provider.default_signer_address();
        let call = self.signer_provider.get_transaction_count(addr);
        let count = if pending {
            call.pending().await
        } else {
            call.latest().await
        };
        count.map_err(ChainIoError::RpcError)
    }

    /// Broadcast a batch create+respond TX without waiting for the receipt.
    ///
    /// Returns the TX hash on successful broadcast. The caller is responsible
    /// for polling the receipt separately via `get_receipt_by_hash`.
    /// This is the send-only half of the pipelined batch submission path.
    pub async fn send_batch_create_and_respond(
        &self,
        batch_contract_addr: Address,
        tasks: Vec<Task>,
        responses: Vec<TaskResponse>,
        signature_data_array: Vec<Bytes>,
        attestation_data: Vec<Bytes>,
    ) -> Result<BroadcastedTx, ChainIoError> {
        let (batch_tasks, batch_responses, batch_sigs, batch_attestations, batch_size) =
            Self::encode_batch_items(tasks, responses, signature_data_array, attestation_data)?;

        let contract = BatchTaskManagerInstance::new(batch_contract_addr, self.signer_provider.clone());

        info!(
            batch_size,
            batch_contract = %batch_contract_addr,
            "pipelined: submitting batchCreateAndRespondToTasks"
        );

        let call = contract.batchCreateAndRespondToTasks(batch_tasks, batch_responses, batch_sigs, batch_attestations);

        // Fill-then-send so we capture the nonce the filler stack assigns. The
        // wallet filler signs into an `Envelope`; re-sending that envelope via
        // `send_tx_envelope` is a no-op for the fillers (they report `Finished`
        // on a built tx), so the `NonceFiller` increments its cache exactly once.
        self.broadcast_filled(call.into_transaction_request(), batch_size).await
    }

    /// Fill a request through the signer's filler stack, capture the assigned
    /// nonce + fees, then broadcast the resulting envelope. Shared by the
    /// initial send, gas bump, and cancel paths so every broadcast yields a
    /// `BroadcastedTx`.
    ///
    /// When an owned [`NonceAllocator`] is active and the request does not yet
    /// carry a nonce (initial send), this reserves a nonce and pins it on the
    /// request so alloy's `CachedNonceManager` stays inert (it only fills when the
    /// nonce is absent). The reserved nonce's lifecycle is then total:
    ///
    /// - `fill` fails (gas-estimate revert — nothing broadcast) → [`release`] the
    ///   nonce so the next reservation reuses it; the on-chain sequence stays
    ///   gap-free at zero cost.
    /// - `send` fails *after* fill (tx may have propagated) → return
    ///   [`ChainIoError::BroadcastSendFailed`] carrying the reserved nonce so the
    ///   caller resolves the slot via confirm-or-cancel. The nonce is NOT released
    ///   (a propagated tx could still mine).
    ///
    /// A caller-pinned nonce (bump/cancel replacement) is used as-is and never
    /// touches the allocator — the receipt tracker already owns that slot.
    ///
    /// [`release`]: NonceAllocator::release
    async fn broadcast_filled(
        &self,
        request: TransactionRequest,
        batch_size: usize,
    ) -> Result<BroadcastedTx, ChainIoError> {
        let (broadcast, _pending) = self.fill_and_send(request, batch_size).await?;
        Ok(broadcast)
    }

    /// Core of every allocator-aware broadcast: reserve + pin the nonce, run the
    /// filler stack, and broadcast — applying the fill-vs-send failure split that
    /// keeps the nonce sequence gap-free. Returns both the [`BroadcastedTx`]
    /// summary and the live [`PendingTransactionBuilder`] so receipt-waiting
    /// callers (`send_task`, `batch_respond_to_tasks`) reuse the exact same split
    /// instead of a coarse `.send()` that releases a possibly-live nonce.
    ///
    /// Failure handling:
    /// - `fill` fails (gas-estimate revert — nothing broadcast) → [`release`] the
    ///   reserved nonce; the slot is free and reused at zero cost.
    /// - `send` fails after fill (tx may have propagated) → return
    ///   [`ChainIoError::BroadcastSendFailed`] carrying the nonce AND the signed
    ///   fees so the caller resolves the slot via a correctly-priced cancel. The
    ///   nonce is NOT released (a propagated tx could still mine).
    ///
    /// A caller-pinned nonce (bump/cancel replacement) is used as-is and never
    /// touches the allocator — the receipt tracker already owns that slot.
    ///
    /// [`release`]: NonceAllocator::release
    async fn fill_and_send(
        &self,
        mut request: TransactionRequest,
        batch_size: usize,
    ) -> Result<
        (
            BroadcastedTx,
            alloy::providers::PendingTransactionBuilder<alloy::network::Ethereum>,
        ),
        ChainIoError,
    > {
        // Reserve + pin the nonce only for an allocator-owned initial send (no
        // nonce yet). Caller-pinned replacements skip this: their slot is already
        // owned, and reserving again would advance the counter spuriously.
        let reserved = match (request.nonce, self.nonce_allocator.as_ref()) {
            (None, Some(alloc)) => {
                let n = alloc.reserve().await?;
                request.set_nonce(n);
                Some(n)
            }
            _ => None,
        };

        // `fill` runs the gas + nonce fillers; a top-level revert (e.g.
        // `BatchPartialFailure`) surfaces here as `eth_estimateGas` revert data.
        // Nothing was broadcast, so the reserved nonce must not be orphaned:
        // LIFO-reclaim it if it's still the latest reservation (free, gap-less).
        // If a newer nonce was reserved concurrently, `release` returns false —
        // `n` is now a real gap below committed work, so resolve it on-chain via a
        // same-nonce cancel before returning. Then route the error through
        // `classify_send_error` so Tier 1 classification is preserved.
        let sendable = match self.signer_provider.fill(request).await {
            Ok(s) => s,
            Err(e) => {
                if let (Some(n), Some(alloc)) = (reserved, self.nonce_allocator.as_ref()) {
                    if !alloc.release(n).await {
                        self.spawn_resolve_stuck_nonce(n, 0, 0);
                    }
                }
                return Self::classify_send_error(ContractError::TransportError(e), batch_size);
            }
        };

        // After a full fill the tx is a signed `Envelope`; read nonce + fees off it.
        let (nonce, max_fee_per_gas, max_priority_fee_per_gas) = match &sendable {
            SendableTx::Envelope(env) => (
                env.nonce(),
                env.max_fee_per_gas(),
                env.max_priority_fee_per_gas().unwrap_or_default(),
            ),
            SendableTx::Builder(req) => (
                req.nonce().ok_or_else(|| ChainIoError::CreateNewTaskCallFail {
                    reason: "nonce filler did not assign a nonce".into(),
                })?,
                req.max_fee_per_gas().unwrap_or_default(),
                req.max_priority_fee_per_gas().unwrap_or_default(),
            ),
        };

        let send_result = match sendable {
            SendableTx::Envelope(env) => self.signer_provider.send_tx_envelope(env).await,
            SendableTx::Builder(req) => self.signer_provider.send_transaction(req).await,
        };

        match send_result {
            Ok(pending) => {
                let tx_hash = *pending.tx_hash();
                info!(
                    batch_size,
                    %tx_hash, nonce, max_fee_per_gas, max_priority_fee_per_gas,
                    "batch pipelined: TX broadcast, receipt pending"
                );
                Ok((
                    BroadcastedTx {
                        tx_hash,
                        nonce,
                        max_fee_per_gas,
                        max_priority_fee_per_gas,
                    },
                    pending,
                ))
            }
            Err(e) => {
                // The send failed AFTER fill succeeded: the tx was signed at
                // `nonce` and may already have propagated to the mempool. We must
                // NOT release the nonce — a propagated tx could still mine, and
                // reusing the slot would collide. When the allocator owns this
                // send, surface the reserved nonce + signed fees so the caller
                // resolves the slot via a correctly-priced cancel instead of
                // orphaning it.
                if reserved.is_some() {
                    return Err(ChainIoError::BroadcastSendFailed {
                        nonce,
                        max_fee_per_gas,
                        max_priority_fee_per_gas,
                        reason: e.to_string(),
                    });
                }
                Self::classify_send_error(ContractError::TransportError(e), batch_size)
            }
        }
    }

    /// Poll for a transaction receipt by hash with exponential backoff.
    ///
    /// Pass `None` for `timeout` to poll indefinitely (caller manages cancellation).
    /// Pass `Some(duration)` to return `TransactionTimeout` after the deadline.
    pub async fn get_receipt_by_hash(
        &self,
        tx_hash: B256,
        timeout: Option<std::time::Duration>,
    ) -> Result<TransactionReceipt, ChainIoError> {
        let mut backoff = std::time::Duration::from_millis(500);
        let max_backoff = std::time::Duration::from_secs(4);
        let deadline = timeout.map(|t| tokio::time::Instant::now() + t);

        loop {
            match self.signer_provider.get_transaction_receipt(tx_hash).await {
                Ok(Some(receipt)) => return Ok(receipt),
                Ok(None) => {
                    if let Some(dl) = deadline {
                        if tokio::time::Instant::now() >= dl {
                            return Err(ChainIoError::TransactionTimeout {
                                timeout_secs: timeout.unwrap().as_secs(),
                            });
                        }
                    }
                    tokio::time::sleep(backoff).await;
                    backoff = std::cmp::min(backoff * 2, max_backoff);
                }
                Err(e) => return Err(ChainIoError::RpcError(e)),
            }
        }
    }

    /// Quote the current market from a 10-block fee history: the latest block's
    /// base fee and a `bump_percent`-inflated 90th-percentile priority fee
    /// (tip). Returns `(base_fee, bumped_priority)`.
    ///
    /// Returns `None` only when the fee-history RPC fails or carries no base
    /// fee — callers MUST fall back to (and floor against) the previous
    /// attempt's fees so a replacement is never broadcast unpriced (which the
    /// node would reject as "replacement transaction underpriced").
    ///
    /// Unlike before, this returns the RAW base fee rather than a pre-combined
    /// `max_fee`, so [`escalate_floor`] can size `max_fee` to guarantee the tip
    /// is realizable (`max_fee − base_fee ≥ priority`) — see that function.
    async fn market_fees(&self, bump_percent: u32) -> Option<(u128, u128)> {
        let bump_multiplier = (100 + bump_percent) as u128;
        let fee_history = self
            .signer_provider
            .get_fee_history(10, Default::default(), &[90.0])
            .await
            .ok()?;
        let base_fee = fee_history.latest_block_base_fee()?;
        // 90th percentile priority fee across the 10-block window.
        let p90_priority = fee_history
            .reward
            .as_ref()
            .and_then(|rewards| {
                rewards
                    .iter()
                    .filter_map(|block_rewards| block_rewards.first().copied())
                    .max()
            })
            .unwrap_or(2_000_000_000); // fallback: 2 gwei
        let priority = p90_priority.saturating_mul(bump_multiplier) / 100;
        Some((base_fee, priority))
    }

    /// Compute escalating replacement fees: the max of a fresh market quote and
    /// a ≥10% bump over the previous attempt, on BOTH fee fields — and sized so
    /// the priority bid is actually realizable as a validator tip.
    ///
    /// `max(market, prev × 1.10)` guarantees the replacement always clears the
    /// node's EIP-1559 ≥10% replacement floor (so it is never rejected as
    /// underpriced) AND tracks a rising market. With `prev = 0` (first bump
    /// after the original, whose fees we always capture) the market quote wins.
    async fn escalated_fees(&self, prev_max_fee: u128, prev_prio: u128, bump_percent: u32) -> (u128, u128) {
        let market = self.market_fees(bump_percent).await;
        escalate_floor(market, prev_max_fee, prev_prio, self.max_fee_per_gas_ceiling)
    }

    /// Resubmit a batch TX at higher gas to replace a stuck transaction, at the
    /// SAME nonce. Used by the watchdog when a TX has no receipt after the
    /// configured timeout.
    ///
    /// Unlike the previous implementation, this takes the nonce + the previous
    /// attempt's fees directly (captured at broadcast via [`BroadcastedTx`])
    /// rather than re-deriving them from `eth_getTransactionByHash` — which
    /// returns `None` once the original is evicted, orphaning the slot. The
    /// returned [`BroadcastedTx`] carries the (escalated) fees so the caller
    /// can thread them into the next attempt for monotonic escalation.
    #[allow(clippy::too_many_arguments)]
    pub async fn gas_bump_batch_tx(
        &self,
        nonce: u64,
        batch_contract_addr: Address,
        tasks: Vec<Task>,
        responses: Vec<TaskResponse>,
        signature_data_array: Vec<Bytes>,
        attestation_data: Vec<Bytes>,
        prev_max_fee: u128,
        prev_priority_fee: u128,
        bump_percent: u32,
    ) -> Result<BroadcastedTx, ChainIoError> {
        let (batch_tasks, batch_responses, batch_sigs, batch_attestations, batch_size) =
            Self::encode_batch_items(tasks, responses, signature_data_array, attestation_data)?;

        let (max_fee, priority) = self.escalated_fees(prev_max_fee, prev_priority_fee, bump_percent).await;

        let contract = BatchTaskManagerInstance::new(batch_contract_addr, self.signer_provider.clone());
        let request = contract
            .batchCreateAndRespondToTasks(batch_tasks, batch_responses, batch_sigs, batch_attestations)
            .nonce(nonce)
            .max_fee_per_gas(max_fee)
            .max_priority_fee_per_gas(priority)
            .into_transaction_request();

        info!(
            batch_size,
            nonce, max_fee, priority, bump_percent, "batch pipelined: gas bump replacement broadcasting"
        );
        self.broadcast_filled(request, batch_size).await
    }

    /// Broadcast a same-nonce cancel: a 0-value self-send at the stuck `nonce`,
    /// priced to replace the stuck batch (escalated fees). This is the bounded
    /// escape for a structurally un-includable payload — it occupies the nonce
    /// slot cheaply (21k gas) so subsequent nonces can drain, upholding the
    /// "never abandon a consumed nonce" invariant. The intended payload is
    /// sacrificed by the caller (re-queued with a fresh nonce), never dropped.
    pub async fn cancel_nonce(
        &self,
        nonce: u64,
        prev_max_fee: u128,
        prev_priority_fee: u128,
        bump_percent: u32,
    ) -> Result<BroadcastedTx, ChainIoError> {
        let me = self.signer_provider.default_signer_address();
        let (max_fee, priority) = self.escalated_fees(prev_max_fee, prev_priority_fee, bump_percent).await;

        let request = TransactionRequest::default()
            .with_from(me)
            .with_to(me)
            .with_value(U256::ZERO)
            .with_nonce(nonce)
            .with_gas_limit(21_000)
            .with_max_fee_per_gas(max_fee)
            .with_max_priority_fee_per_gas(priority);

        warn!(
            nonce,
            max_fee, priority, "batch pipelined: broadcasting same-nonce cancel to free stuck slot"
        );
        // batch_size 0 — cancel carries no items; classify_send_error only uses it for logging.
        // The cancel pins its own nonce, so `fill_and_send` never reserves/releases.
        self.broadcast_filled(request, 0).await
    }

    /// Resolve a reserved nonce whose on-chain fate is **uncertain** — its tx may
    /// have propagated to the mempool (a post-fill send failure, or a receipt
    /// timeout after a successful broadcast). Releasing it would risk a collision
    /// with a tx that still mines; abandoning it strands every higher nonce
    /// (blocked-from-below). So we resolve it on-chain via the shared
    /// [`cancel::cancel_until_resolved`] loop — the SAME unbounded, escalating,
    /// shutdown-aware logic the pipelined batch path uses, so the "never abandon a
    /// nonce" invariant holds identically here.
    ///
    /// Used by the direct `.send()` / `send_with_retries` paths
    /// (`send_task`, `batch_respond_to_tasks`, `send_aggregated_response`,
    /// `commit_state_root`) which — unlike the pipelined path — have no background
    /// receipt tracker, so the loop runs inline. It is bounded only by the
    /// optional shutdown token (`with_cancel_token`); a wedged signer recovers
    /// automatically once unblocked. No-op when no allocator is attached.
    ///
    /// `seed_*` price the first cancel (pass the stuck tx's fees to out-price it;
    /// 0 falls back to a market quote).
    async fn resolve_stuck_nonce(&self, nonce: u64, seed_max_fee: u128, seed_priority: u128) {
        // Only meaningful when we own the sequence; otherwise the implicit filler
        // manages nonces and there is nothing to coordinate.
        if self.nonce_allocator.is_none() {
            return;
        }
        // Clamp the seed to the fee ceiling. The cancel's per-broadcast price is
        // already ceiling-clamped by `escalate_floor`, but clamping the seed too
        // keeps the starting bid within bounds (a propagated original priced at/above
        // the ceiling can't push the cancel's opening bid past it).
        let seed_max_fee = seed_max_fee.min(self.max_fee_per_gas_ceiling);
        let seed_priority = seed_priority.min(self.max_fee_per_gas_ceiling);
        let params = CancelParams {
            confirm_timeout: self.batch_receipt_timeout(),
            ..CancelParams::default()
        };
        match cancel::cancel_until_resolved(
            self,
            self.chain_id,
            nonce,
            seed_max_fee,
            seed_priority,
            params,
            self.cancel_token.as_ref(),
        )
        .await
        {
            CancelOutcome::Resolved => {
                info!(nonce, "resolve_stuck_nonce: slot resolved on-chain");
            }
            CancelOutcome::Shutdown => {
                warn!(
                    nonce,
                    "resolve_stuck_nonce: shutdown before slot resolved (startup sweep recovers it)"
                );
            }
        }
    }

    /// Whether a failed submission's on-chain outcome is *uncertain* — i.e. a tx
    /// may have propagated and consumed the nonce without us seeing a receipt — so
    /// the slot must be resolved on-chain. A mined revert (`TransactionReverted`,
    /// status=false) is NOT uncertain: the nonce is already consumed, so resolving
    /// it would be a wasted cancel and would muddy the poison signal callers key
    /// on. Fill-stage failures don't reach the resolve sites (the nonce is reclaimed
    /// or never reserved), so this only needs to separate "mined revert" from the
    /// timeout / post-send / retries-exhausted cases.
    fn is_uncertain_outcome(e: &ChainIoError) -> bool {
        !matches!(e, ChainIoError::TransactionReverted(_))
    }

    /// Spawn [`resolve_stuck_nonce`](Self::resolve_stuck_nonce) on a detached task
    /// and return immediately. The direct-send paths (`send_task`,
    /// `batch_respond_to_tasks`, `send_aggregated_response`, `commit_state_root`)
    /// run on serial drivers (the `tx_worker` loop, the 120s commit tick), so
    /// resolving inline would block every queued submission behind an unbounded
    /// cancel whenever the signer is wedged. Spawning matches the pipelined path
    /// (which detaches via `spawn_monitored`) so the driver keeps draining; the
    /// resolver still upholds the never-abandon invariant and exits cleanly on the
    /// shutdown token. Cheap: every `AvsWriter` field is `Arc`-backed or `Copy`.
    fn spawn_resolve_stuck_nonce(&self, nonce: u64, seed_max_fee: u128, seed_priority: u128) {
        // No allocator → nothing to coordinate; don't spawn a task that no-ops.
        if self.nonce_allocator.is_none() {
            return;
        }
        let resolver = self.clone();
        tokio::spawn(async move {
            resolver.resolve_stuck_nonce(nonce, seed_max_fee, seed_priority).await;
        });
    }

    /// Encode task/response/signature/attestation tuples into batch-compatible ABI types.
    /// Shared between `send_batch_create_and_respond` and `gas_bump_batch_tx`.
    #[allow(clippy::result_large_err, clippy::type_complexity)]
    fn encode_batch_items(
        tasks: Vec<Task>,
        responses: Vec<TaskResponse>,
        signature_data_array: Vec<Bytes>,
        attestation_data: Vec<Bytes>,
    ) -> Result<(Vec<BatchTask>, Vec<BatchTaskResponse>, Vec<Bytes>, Vec<Bytes>, usize), ChainIoError> {
        let batch_size = tasks.len();
        let mut batch_tasks: Vec<BatchTask> = Vec::with_capacity(batch_size);
        let mut batch_responses: Vec<BatchTaskResponse> = Vec::with_capacity(batch_size);
        let mut batch_sigs: Vec<Bytes> = Vec::with_capacity(batch_size);
        let mut batch_attestations: Vec<Bytes> = Vec::with_capacity(batch_size);

        for (i, (((t, r), sig), att)) in tasks
            .into_iter()
            .zip(responses)
            .zip(signature_data_array)
            .zip(attestation_data)
            .enumerate()
        {
            let task_encoded = Task::abi_encode(&t);
            let bt = match BatchTask::abi_decode(&task_encoded) {
                Ok(bt) => bt,
                Err(e) => {
                    warn!(error = %e, index = i, "batch ABI-decode task failed, skipping item");
                    continue;
                }
            };

            let resp_encoded = TaskResponse::abi_encode(&r);
            let br = match BatchTaskResponse::abi_decode(&resp_encoded) {
                Ok(br) => br,
                Err(e) => {
                    warn!(error = %e, index = i, "batch ABI-decode response failed, skipping item");
                    continue;
                }
            };

            batch_tasks.push(bt);
            batch_responses.push(br);
            batch_sigs.push(sig);
            batch_attestations.push(att);
        }

        let skipped = batch_size - batch_tasks.len();
        if skipped > 0 {
            warn!(
                batch_size,
                skipped, "batch: {} item(s) skipped due to ABI-decode failure", skipped
            );
        }
        if batch_tasks.is_empty() {
            return Err(ChainIoError::CreateNewTaskCallFail {
                reason: "all task/response items failed ABI-decode; batch is empty".to_string(),
            });
        }

        Ok((batch_tasks, batch_responses, batch_sigs, batch_attestations, batch_size))
    }

    /// Classify an error from `.send().await` into the appropriate `ChainIoError`.
    /// Shared between all batch submission methods.
    #[allow(clippy::result_large_err)]
    fn classify_send_error<T>(e: ContractError, batch_size: usize) -> Result<T, ChainIoError> {
        if let Some(failures) = Self::parse_batch_partial_failure(&e) {
            let fail_count = failures.len();
            info!(batch_size, fail_count, "batch: partial failure from simulation");
            Err(ChainIoError::BatchPartialFailure { failures })
        } else if let Some(revert_data) = e.as_revert_data() {
            let classified = errors::classify_top_level_revert(&revert_data);
            warn!(batch_size, error = %classified, "batch: top-level revert from simulation");
            Err(classified)
        } else {
            Err(ChainIoError::ContractError(e))
        }
    }

    /// Send task. Returns tx receipt and the full Task struct from the on-chain event.
    ///
    /// The returned Task contains the actual `taskCreatedBlock` set by the contract,
    /// which should be used for response submission instead of any pre-estimated value.
    pub async fn send_task(&self, params: SendTaskParams) -> Result<(TransactionReceipt, Task), ChainIoError> {
        let SendTaskParams {
            task_id,
            task_created_block,
            wasm_args,
            policy_client,
            intent,
            intent_signature,
            quorum_number,
            quorum_threshold_percentage,
            initialization_timestamp,
        } = params.clone();

        let task_manager_contract = NewtonProverTaskManager::new(self.task_manager_addr, self.signer_provider.clone());

        // Log task_created_block for diagnostics (tracking InvalidTaskCreatedBlock issue)
        tracing::info!(
            task_id = %newton_core::hex!(task_id),
            task_created_block = task_created_block,
            policy_client = %policy_client,
            "send_task: creating task with taskCreatedBlock"
        );

        // Task is now minimal - policyTaskData is generated by operators independently
        // Use offchain estimated block as single source of truth for BLS verification
        let create_new_task_call = task_manager_contract.createNewTask(Task {
            taskId: task_id,
            policyClient: policy_client,
            taskCreatedBlock: task_created_block,
            quorumThresholdPercentage: quorum_threshold_percentage.into(),
            intent,
            intentSignature: intent_signature.unwrap_or_default(),
            wasmArgs: wasm_args,
            quorumNumbers: quorum_number.into(),
            initializationTimestamp: U256::from(initialization_timestamp),
        });

        // Route through `fill_and_send` so this path gets the same fill-vs-send
        // failure split as the pipelined batch path: a fill-stage failure releases
        // the reserved nonce, while a post-fill send failure surfaces
        // `BroadcastSendFailed` (nonce NOT released — the tx may have propagated).
        // A coarse `.send()` + release-on-any-error here would release a possibly
        // live nonce and re-create the blocked-from-below gap. batch_size 1 — one
        // task; only used for logging/classification.
        let create_new_task_result = self
            .fill_and_send(create_new_task_call.into_transaction_request(), 1)
            .await
            .map(|(_broadcast, pending)| pending);

        match create_new_task_result {
            Ok(create_new_task) => {
                let receipt_result = create_new_task.get_receipt().await;

                match receipt_result {
                    Ok(receipt) => {
                        let log_decoded_option = receipt
                            .inner
                            .logs()
                            .iter()
                            .find_map(|log| log.log_decode::<NewtonProverTaskManager::NewTaskCreated>().ok());

                        if let Some(new_task_created) = log_decoded_option {
                            let data = new_task_created.data();
                            // Return full Task from event with actual taskCreatedBlock
                            let onchain_task = data.task.clone();

                            Ok((receipt, onchain_task))
                        } else {
                            Err(ChainIoError::CreateNewTaskNoEventFound)
                        }
                    }

                    Err(e) => Err(ChainIoError::AlloyProviderError(e)),
                }
            }
            // Post-fill send failure: the nonce may be live on-chain. The caller
            // (tx_worker) only retries/logs — it does NOT resolve the slot — so we
            // must resolve it here, or the reserved nonce is abandoned and strands
            // every higher nonce (the blocked-from-below gap this PR exists to
            // kill). Drive the same-nonce cancel, seeded from the failed tx's fees,
            // then surface a transient error so the caller can re-attempt cleanly.
            Err(ChainIoError::BroadcastSendFailed {
                nonce,
                max_fee_per_gas,
                max_priority_fee_per_gas,
                reason,
            }) => {
                tracing::warn!(
                    task_id = %newton_core::hex!(task_id),
                    nonce,
                    %reason,
                    "send_task: send failed after fill, resolving stuck nonce off the hot path"
                );
                // Spawn the resolution so the serial tx_worker keeps draining
                // queued submissions instead of blocking on the unbounded cancel.
                self.spawn_resolve_stuck_nonce(nonce, max_fee_per_gas, max_priority_fee_per_gas);
                Err(ChainIoError::TransactionTimeout { timeout_secs: 0 })
            }
            Err(e) => {
                // Log the ACTUAL transaction error before simulation
                // This is critical for diagnosis - simulation may mask the real error
                tracing::error!(
                    task_id = %newton_core::hex!(task_id),
                    task_created_block = task_created_block,
                    error = %e,
                    "send_task: createNewTask transaction FAILED (actual error, not simulation)"
                );

                // Log simulation error details when the actual call fails
                // NOTE: Simulation uses hardcoded taskCreatedBlock=1, which will ALWAYS fail
                // with TaskCreatedBlockTooOld on real networks. The simulation is for identifying
                // OTHER errors, not block timing issues.
                if let Some(identified_error) = log_create_task_error(
                    self.task_manager_addr,
                    &self.signer_provider,
                    params.policy_client,
                    params.wasm_args.clone(),
                    &params.intent,
                    &params.intent_signature,
                    params.quorum_number,
                    params.quorum_threshold_percentage,
                    params.initialization_timestamp,
                )
                .await
                {
                    Err(ChainIoError::CreateNewTaskCallFail {
                        reason: identified_error,
                    })
                } else {
                    // `fill_and_send` already classified the fill-stage error into a
                    // typed `ChainIoError`; surface it directly.
                    Err(e)
                }
            }
        }
    }

    /// Raise challenge
    pub async fn raise_challenge(
        &self,
        task: Task,
        task_response: TaskResponse,
        task_response_metadata: ResponseCertificate,
        challenge: ChallengeData,
        pub_keys_of_non_signing_operators: Vec<G1Point>,
    ) -> Result<alloy::rpc::types::TransactionReceipt, ChainIoError> {
        let balance = self
            .signer_provider
            .get_balance(self.signer_provider.default_signer_address())
            .await;
        info!(
            "{} balance: {}",
            self.signer_provider.default_signer_address(),
            balance.unwrap_or_default()
        );
        let task_manager_contract = NewtonProverTaskManager::new(self.task_manager_addr, self.signer_provider.clone());
        let challenge_tx_call = task_manager_contract.raiseAndResolveChallenge(
            task,
            task_response.clone(),
            task_response_metadata,
            challenge,
            pub_keys_of_non_signing_operators,
        );

        match challenge_tx_call.send().await {
            Ok(challenge_tx) => {
                let receipt_result = challenge_tx.get_receipt().await;
                match receipt_result {
                    Ok(receipts) => {
                        info!(
                            "raiseAndResolveChallenge for task_id: {} tx_hash: {}",
                            hex!(task_response.taskId),
                            hex!(receipts.transaction_hash)
                        );
                        Ok(receipts)
                    }
                    Err(e) => Err(ChainIoError::AlloyProviderError(e)),
                }
            }

            Err(e) => Err(ChainIoError::ContractError(e)),
        }
    }

    /// Invalidate a directly-verified attestation whose hashes diverge from the canonical
    /// regular-path hashes (`createNewTask` + `respondToTask`).
    ///
    /// This never slashes. Hash divergence alone is not proof of operator misbehavior —
    /// the direct path may have stored a bad hash while operators signed the correct
    /// response. Slashing for incorrect responses is handled by `raiseAndResolveChallenge`,
    /// which re-executes the policy and produces a ZK proof.
    pub async fn challenge_directly_verified_mismatch(
        &self,
        task: Task,
        task_response: TaskResponse,
    ) -> Result<TransactionReceipt, ChainIoError> {
        let task_manager_contract = NewtonProverTaskManager::new(self.task_manager_addr, self.signer_provider.clone());

        let call = task_manager_contract.challengeDirectlyVerifiedMismatch(task, task_response.clone());

        match call.send().await {
            Ok(pending_tx) => {
                let receipt = pending_tx
                    .get_receipt()
                    .await
                    .map_err(ChainIoError::AlloyProviderError)?;
                info!(
                    "challengeDirectlyVerifiedMismatch for task_id: {} tx_hash: {}",
                    hex!(task_response.taskId),
                    hex!(receipt.transaction_hash)
                );
                Ok(receipt)
            }
            Err(e) => Err(ChainIoError::ContractError(e)),
        }
    }

    /// Challenge a privacy task with missing or invalid TEE attestation.
    ///
    /// Calls ChallengeVerifier.challengeInvalidTeeAttestation directly (not through
    /// TaskManager). For missing attestation, pass empty proof data. For invalid
    /// attestation, pass the SP1 attestation circuit proof.
    pub async fn challenge_invalid_tee_attestation(
        &self,
        params: TeeAttestationChallengeParams,
    ) -> Result<TransactionReceipt, ChainIoError> {
        let TeeAttestationChallengeParams {
            challenge_verifier_addr,
            task,
            task_response,
            task_response_metadata,
            attestation_proof_data,
            attestation_proof_bytes,
            pub_keys_of_non_signing_operators,
        } = params;
        let cv = newton_core::challenge_verifier::ChallengeVerifier::new(
            challenge_verifier_addr,
            self.signer_provider.clone(),
        );

        // ABI round-trip: alloy generates distinct struct types per contract binding
        let cv_task =
            CvTask::abi_decode(&Task::abi_encode(&task)).map_err(|e| ChainIoError::CreateNewTaskCallFail {
                reason: format!("ABI bridge Task failed: {e}"),
            })?;
        let cv_response = CvTaskResponse::abi_decode(&TaskResponse::abi_encode(&task_response)).map_err(|e| {
            ChainIoError::CreateNewTaskCallFail {
                reason: format!("ABI bridge TaskResponse failed: {e}"),
            }
        })?;
        let cv_metadata = CvResponseCertificate::abi_decode(&ResponseCertificate::abi_encode(&task_response_metadata))
            .map_err(|e| ChainIoError::CreateNewTaskCallFail {
                reason: format!("ABI bridge ResponseCertificate failed: {e}"),
            })?;
        let cv_pubkeys: Vec<CvG1Point> = pub_keys_of_non_signing_operators
            .iter()
            .map(|p| CvG1Point { X: p.X, Y: p.Y })
            .collect();

        let call = cv.challengeInvalidTeeAttestation(
            cv_task,
            cv_response,
            cv_metadata,
            attestation_proof_data,
            attestation_proof_bytes,
            cv_pubkeys,
        );

        match call.send().await {
            Ok(pending_tx) => {
                let receipt = pending_tx
                    .get_receipt()
                    .await
                    .map_err(ChainIoError::AlloyProviderError)?;
                info!(
                    "challengeInvalidTeeAttestation for task_id: {} tx_hash: {}",
                    hex!(task_response.taskId),
                    hex!(receipt.transaction_hash)
                );
                Ok(receipt)
            }
            Err(e) => Err(ChainIoError::ContractError(e)),
        }
    }

    /// Send aggregated response
    ///
    /// # Arguments
    ///
    /// * `task` - Task
    /// * `task_response` - Task response
    /// * `signature_data` - Signature data (non-signer stakes and aggregated signature)
    /// * `attestation_data` - Modal keccak256(pcr0) from operator commit responses
    /// * `chain_id` - Target chain ID
    pub async fn send_aggregated_response(
        &self,
        task: Task,
        task_response: TaskResponse,
        signature_data: Bytes,
        attestation_data: Bytes,
        chain_id: u64,
    ) -> Result<TransactionReceipt, ChainIoError> {
        let rpc_url = self.rpc_url.clone();
        let signer_provider = self.signer_provider.clone();
        let task_manager_addr = self.task_manager_addr;
        let receipt_timeout = self.batch_receipt_timeout();
        // Reserve one nonce for the whole retry sequence: every fee-escalation
        // retry replaces the SAME slot, so they all pin this nonce (keeping the
        // implicit filler inert and the sequence coordinated with the batch path).
        let reserved_nonce = self.reserve_nonce().await?;
        // Capture the fees of the LAST attempt so a stuck-nonce cancel can be
        // seeded to out-price a propagated original (see the resolve call below).
        // `send_with_retries` doesn't surface them, so the closure records them.
        let last_fees: Arc<std::sync::Mutex<Option<(u128, u128)>>> = Arc::new(std::sync::Mutex::new(None));
        let last_fees_inner = last_fees.clone();

        let result = crate::tx::send_with_retries(rpc_url.clone(), chain_id, move |fee_override| {
            let task = task.clone();
            let task_for_error_logging = task.clone();
            let task_response = task_response.clone();
            let signature_data = signature_data.clone();
            let attestation_data = attestation_data.clone();
            let signer = signer_provider.clone();
            let last_fees = last_fees_inner.clone();

            async move {
                let task_manager_contract = NewtonProverTaskManager::new(task_manager_addr, signer.clone());

                // DIAGNOSTIC: Log task and response data before submission
                debug!(
                    task_id = %newton_core::hex!(task.taskId),
                    task_created_block = task.taskCreatedBlock,
                    quorum_threshold = task.quorumThresholdPercentage,
                    policy_client = %task.policyClient,
                    task_response_task_id = %newton_core::hex!(task_response.taskId),
                    task_response_policy_id = %newton_core::hex!(task_response.policyId),
                    evaluation_result_len = task_response.evaluationResult.len(),
                    policy_task_data_len = task_response.policyTaskData.policyData.len(),
                    "[DEBUG] respondToTask call parameters"
                );

                // Create the transaction call
                let mut call_builder =
                    task_manager_contract.respondToTask(task, task_response, signature_data, attestation_data);

                // Apply EIP-1559 fee override if provided, recording it so a
                // stuck-nonce cancel can be seeded from the last-used price.
                if let Some(fees) = fee_override {
                    call_builder = call_builder
                        .max_fee_per_gas(fees.max_fee_per_gas)
                        .max_priority_fee_per_gas(fees.max_priority_fee_per_gas);
                    *last_fees.lock().unwrap() = Some((fees.max_fee_per_gas, fees.max_priority_fee_per_gas));
                }
                // Pin the reserved nonce so the implicit filler stays inert and
                // every retry replaces the same slot.
                if let Some(n) = reserved_nonce {
                    call_builder = call_builder.nonce(n);
                }

                let tx_from = signer.default_signer_address();
                let tx_to = task_manager_addr;
                let tx_value = format!("0x{:x}", U256::ZERO);
                let calldata_bytes = call_builder.calldata().to_vec();
                let tx_data = format!("0x{}", hex::encode(&calldata_bytes));

                // Try to send the transaction and get receipt
                match call_builder.send().await {
                    Ok(pending_tx) => {
                        // Wrap get_receipt() in a timeout to prevent indefinite hang
                        // if the tx is dropped from the mempool (same pattern as batch methods).
                        match timeout(receipt_timeout, pending_tx.get_receipt()).await {
                            Ok(Ok(receipt)) => Ok(receipt),
                            Ok(Err(e)) => Err(ChainIoError::AlloyProviderError(e)),
                            Err(_) => Err(ChainIoError::TransactionTimeout {
                                timeout_secs: receipt_timeout.as_secs(),
                            }),
                        }
                    }
                    Err(send_error) => {
                        // Log detailed error information for debugging
                        log_respond_to_task_error(
                            &send_error,
                            &task_for_error_logging,
                            task_manager_addr,
                            tx_from,
                            &calldata_bytes,
                            chain_id,
                        );

                        Err(ChainIoError::ContractErrorWithTx {
                            from: tx_from,
                            to: tx_to,
                            value: tx_value,
                            data: tx_data,
                            source: send_error,
                        })
                    }
                }
            }
        })
        .await;

        // `send_with_retries` reserved one nonce for the whole sequence (replacement
        // semantics). On a final failure whose on-chain outcome is UNCERTAIN (an
        // attempt may have propagated) the reserved nonce must be resolved on-chain
        // rather than left stranded (the next aggregated response reserves above it
        // → blocked-from-below). A mined revert is NOT uncertain — the nonce is
        // already consumed — so we skip the cancel there (see `is_uncertain_outcome`).
        // Spawned off the hot path so the serial caller keeps draining. Seed the
        // cancel from the last attempt's fees; 0 (attempt 1 used node-assigned fees
        // we can't read) falls back to a fresh market quote.
        if let (Err(e), Some(n)) = (&result, reserved_nonce) {
            if Self::is_uncertain_outcome(e) {
                let (seed_max, seed_prio) = last_fees.lock().unwrap().unwrap_or((0, 0));
                self.spawn_resolve_stuck_nonce(n, seed_max, seed_prio);
            }
        }
        result
    }

    /// Submit a unified-tree state root commit to the per-chain `StateCommitRegistry`.
    ///
    /// `commit` is the BLS-signed `StateCommit` payload (version, sequenceNo,
    /// prevStateRoot, newStateRoot, timestamp, daCertHash, pcr0Commitment).
    /// `bls_certificate` is the ABI-encoded `BN254Certificate` covering
    /// `keccak256(abi.encode(commit))`. Both are produced by the aggregator at
    /// the 120s commit cadence.
    ///
    /// Uses `crate::tx::send_with_retries` for transient retry, but every typed
    /// revert classified by `log_commit_state_root_error` is a poison error —
    /// the aggregator must rebuild the commit against the registry's current
    /// `(sequenceNo, stateRoot)` before retrying.
    pub async fn commit_state_root(
        &self,
        commit: StateCommit,
        bls_certificate: Bytes,
    ) -> Result<TransactionReceipt, ChainIoError> {
        if self.state_commit_registry_addr == Address::ZERO {
            return Err(ChainIoError::CommitStateRootCallFail {
                reason: "state_commit_registry address not configured (still Address::ZERO)".to_string(),
            });
        }

        let rpc_url = self.rpc_url.clone();
        let signer_provider = self.signer_provider.clone();
        let registry_addr = self.state_commit_registry_addr;
        let chain_id = self.chain_id;
        // Reserve one nonce for the whole retry sequence (replacement semantics);
        // pinned on every attempt so this path shares the batch path's allocator.
        let reserved_nonce = self.reserve_nonce().await?;
        // Record the last attempt's fees to seed a stuck-nonce cancel (see below).
        let last_fees: Arc<std::sync::Mutex<Option<(u128, u128)>>> = Arc::new(std::sync::Mutex::new(None));
        let last_fees_inner = last_fees.clone();

        let result = crate::tx::send_with_retries(rpc_url, chain_id, move |fee_override| {
            let commit = commit.clone();
            let bls_certificate = bls_certificate.clone();
            let signer = signer_provider.clone();
            let last_fees = last_fees_inner.clone();

            async move {
                let registry = StateCommitRegistryInstance::new(registry_addr, signer.clone());

                debug!(
                    chain_id,
                    sequence_no = commit.sequenceNo,
                    timestamp = commit.timestamp,
                    prev_state_root = %commit.prevStateRoot,
                    new_state_root = %commit.newStateRoot,
                    da_cert_hash = %commit.daCertHash,
                    pcr0_commitment = %commit.pcr0Commitment,
                    cert_len = bls_certificate.len(),
                    "commitStateRoot call parameters"
                );

                let mut call_builder = registry.commitStateRoot(commit.clone(), bls_certificate);

                if let Some(fees) = fee_override {
                    call_builder = call_builder
                        .max_fee_per_gas(fees.max_fee_per_gas)
                        .max_priority_fee_per_gas(fees.max_priority_fee_per_gas);
                    *last_fees.lock().unwrap() = Some((fees.max_fee_per_gas, fees.max_priority_fee_per_gas));
                }
                if let Some(n) = reserved_nonce {
                    call_builder = call_builder.nonce(n);
                }

                let tx_from = signer.default_signer_address();
                let tx_to = registry_addr;
                let tx_value = format!("0x{:x}", U256::ZERO);
                let calldata_bytes = call_builder.calldata().to_vec();
                let tx_data = format!("0x{}", hex::encode(&calldata_bytes));

                match call_builder.send().await {
                    Ok(pending_tx) => match timeout(STATE_COMMIT_RECEIPT_TIMEOUT, pending_tx.get_receipt()).await {
                        Ok(Ok(receipt)) => {
                            let tx_hash = receipt.transaction_hash;
                            if !receipt.status() {
                                warn!(
                                    chain_id,
                                    sequence_no = commit.sequenceNo,
                                    tx_hash = %tx_hash,
                                    "commitStateRoot reverted on-chain (receipt status=false) — \
                                     proposal is poison; rebuild against current registry view before retrying"
                                );
                                return Err(ChainIoError::TransactionReverted(tx_hash));
                            }
                            Ok(receipt)
                        }
                        Ok(Err(e)) => Err(ChainIoError::AlloyProviderError(e)),
                        Err(_) => Err(ChainIoError::TransactionTimeout {
                            timeout_secs: STATE_COMMIT_RECEIPT_TIMEOUT.as_secs(),
                        }),
                    },
                    Err(send_error) => {
                        log_commit_state_root_error(
                            &send_error,
                            &commit,
                            registry_addr,
                            tx_from,
                            &calldata_bytes,
                            chain_id,
                        );

                        Err(ChainIoError::ContractErrorWithTx {
                            from: tx_from,
                            to: tx_to,
                            value: tx_value,
                            data: tx_data,
                            source: send_error,
                        })
                    }
                }
            }
        })
        .await;

        // Resolve the reserved nonce on-chain only when the outcome is UNCERTAIN
        // (timeout / post-send error — an attempt may have propagated). A mined
        // revert (`TransactionReverted`, status=false) already consumed the nonce,
        // so resolving there is a wasted cancel that also muddies the poison signal
        // the aggregator keys on to rebuild — skip it (see `is_uncertain_outcome`).
        // Spawned off the hot path so the 120s commit tick isn't blocked. No-op
        // without an allocator. Dev-stub-gated today (NEWT-1116) but correct the
        // moment the production orchestrator is wired.
        if let (Err(e), Some(n)) = (&result, reserved_nonce) {
            if Self::is_uncertain_outcome(e) {
                let (seed_max, seed_prio) = last_fees.lock().unwrap().unwrap_or((0, 0));
                self.spawn_resolve_stuck_nonce(n, seed_max, seed_prio);
            }
        }
        result
    }

    /// Chain-adaptive timeout for waiting on a batch transaction receipt.
    /// L1 chains (12s block time) need longer timeouts under congestion.
    /// L2 chains (2s block time) can use shorter timeouts.
    fn batch_receipt_timeout(&self) -> Duration {
        match self.chain_id {
            // Ethereum mainnet, Sepolia: 12s/block, 60s ≈ 5 blocks
            1 | 11155111 => Duration::from_secs(60),
            // Local anvil: use shorter timeout for fast test feedback
            31337 | 31338 => Duration::from_secs(30),
            // L2s (Base, Arbitrum, Optimism, Polygon, etc.): 2s/block, 30s ≈ 15 blocks
            _ => Duration::from_secs(30),
        }
    }

    /// Batch-create multiple tasks in a single transaction via BatchTaskManager contract.
    ///
    /// On success (all items pass): returns Ok with receipt. No event parsing needed —
    /// the caller knows all items in the batch succeeded.
    ///
    /// On partial failure: the contract reverts with `BatchPartialFailure` containing
    /// indices and reasons for each failed item. This is returned as
    /// `Err(ChainIoError::BatchPartialFailure)` with the parsed failure details.
    pub async fn batch_create_tasks(
        &self,
        batch_contract_addr: Address,
        tasks: Vec<Task>,
    ) -> Result<TransactionReceipt, ChainIoError> {
        let contract = BatchTaskManagerInstance::new(batch_contract_addr, self.signer_provider.clone());

        let batch_size = tasks.len();
        info!(
            batch_size = batch_size,
            batch_contract = %batch_contract_addr,
            "batch_create_tasks: submitting batch"
        );

        // Convert tasks from newton_prover_task_manager types to batch_task_manager types
        // Both are ABI-identical; round-trip through encoding bridges the type gap.
        let batch_tasks: Vec<BatchTask> = tasks
            .iter()
            .filter_map(|t| {
                let encoded = Task::abi_encode(t);
                match BatchTask::abi_decode(&encoded) {
                    Ok(bt) => Some(bt),
                    Err(e) => {
                        warn!(error = %e, "batch_create_tasks: failed to ABI-decode task, skipping");
                        None
                    }
                }
            })
            .collect();

        let skipped = batch_size - batch_tasks.len();
        if skipped > 0 {
            warn!(
                batch_size = batch_size,
                skipped = skipped,
                "batch_create_tasks: {} item(s) skipped due to ABI-decode failure",
                skipped
            );
        }
        if batch_tasks.is_empty() {
            error!(
                batch_size = batch_size,
                "batch_create_tasks: all items failed ABI-decode, aborting empty batch"
            );
            return Err(ChainIoError::CreateNewTaskCallFail {
                reason: "all tasks failed ABI-decode; batch is empty".to_string(),
            });
        }

        let send_result = contract.batchCreateTasks(batch_tasks).send().await;

        match send_result {
            Ok(pending) => {
                let receipt = match timeout(self.batch_receipt_timeout(), pending.get_receipt()).await {
                    Ok(Ok(r)) => r,
                    Ok(Err(e)) => return Err(ChainIoError::AlloyProviderError(e)),
                    Err(_) => {
                        warn!(
                            batch_size,
                            timeout_secs = self.batch_receipt_timeout().as_secs(),
                            "batch_create_tasks: receipt timed out"
                        );
                        return Err(ChainIoError::TransactionTimeout {
                            timeout_secs: self.batch_receipt_timeout().as_secs(),
                        });
                    }
                };
                let tx_hash = receipt.transaction_hash;
                if !receipt.status() {
                    return Err(ChainIoError::TransactionReverted(tx_hash));
                }
                info!(batch_size, %tx_hash, "batch_create_tasks: all items succeeded");
                Ok(receipt)
            }
            Err(e) => {
                if let Some(failures) = Self::parse_batch_partial_failure(&e) {
                    let fail_count = failures.len();
                    info!(
                        batch_size = batch_size,
                        fail_count = fail_count,
                        "batch_create_tasks: partial failure, {} items failed",
                        fail_count
                    );
                    Err(ChainIoError::BatchPartialFailure { failures })
                } else if let Some(revert_data) = e.as_revert_data() {
                    Err(errors::classify_top_level_revert(&revert_data))
                } else {
                    Err(ChainIoError::ContractError(e))
                }
            }
        }
    }

    /// Batch-respond to multiple tasks in a single transaction via BatchTaskManager contract.
    ///
    /// Same error semantics as `batch_create_tasks`: Ok on full success,
    /// `Err(BatchPartialFailure)` on partial failure with per-item details.
    pub async fn batch_respond_to_tasks(
        &self,
        batch_contract_addr: Address,
        tasks: Vec<Task>,
        responses: Vec<TaskResponse>,
        signature_data_array: Vec<Bytes>,
        attestation_data: Vec<Bytes>,
    ) -> Result<TransactionReceipt, ChainIoError> {
        let contract = BatchTaskManagerInstance::new(batch_contract_addr, self.signer_provider.clone());

        let batch_size = tasks.len();
        info!(
            batch_size = batch_size,
            batch_contract = %batch_contract_addr,
            "batch_respond_to_tasks: submitting batch"
        );

        let mut batch_tasks: Vec<BatchTask> = Vec::with_capacity(batch_size);
        let mut batch_responses: Vec<BatchTaskResponse> = Vec::with_capacity(batch_size);
        let mut batch_sigs: Vec<Bytes> = Vec::with_capacity(batch_size);
        let mut batch_attestations: Vec<Bytes> = Vec::with_capacity(batch_size);

        for (i, (((t, r), sig), att)) in tasks
            .into_iter()
            .zip(responses)
            .zip(signature_data_array)
            .zip(attestation_data)
            .enumerate()
        {
            let task_encoded = Task::abi_encode(&t);
            let bt = match BatchTask::abi_decode(&task_encoded) {
                Ok(bt) => bt,
                Err(e) => {
                    warn!(
                        error = %e,
                        index = i,
                        "batch_respond_to_tasks: failed to ABI-decode task, skipping triple"
                    );
                    continue;
                }
            };

            let resp_encoded = TaskResponse::abi_encode(&r);
            let br = match BatchTaskResponse::abi_decode(&resp_encoded) {
                Ok(br) => br,
                Err(e) => {
                    warn!(
                        error = %e,
                        index = i,
                        "batch_respond_to_tasks: failed to ABI-decode response, skipping triple"
                    );
                    continue;
                }
            };

            batch_tasks.push(bt);
            batch_responses.push(br);
            batch_sigs.push(sig);
            batch_attestations.push(att);
        }

        let skipped = batch_size - batch_tasks.len();
        if skipped > 0 {
            warn!(
                batch_size = batch_size,
                skipped = skipped,
                "batch_respond_to_tasks: {} triple(s) skipped due to ABI-decode failure",
                skipped
            );
        }
        if batch_tasks.is_empty() {
            error!(
                batch_size = batch_size,
                "batch_respond_to_tasks: all items failed ABI-decode, aborting empty batch"
            );
            return Err(ChainIoError::CreateNewTaskCallFail {
                reason: "all task/response triples failed ABI-decode; batch is empty".to_string(),
            });
        }

        // Route through `fill_and_send` so a fill-stage failure releases the
        // reserved nonce while a post-fill send failure surfaces
        // `BroadcastSendFailed` (the tx may have propagated — nonce NOT released).
        let call = contract.batchRespondToTasks(batch_tasks, batch_responses, batch_sigs, batch_attestations);
        let send_result = self.fill_and_send(call.into_transaction_request(), batch_size).await;

        match send_result {
            Ok((broadcast, pending)) => {
                let receipt = match timeout(self.batch_receipt_timeout(), pending.get_receipt()).await {
                    Ok(Ok(r)) => r,
                    Ok(Err(e)) => return Err(ChainIoError::AlloyProviderError(e)),
                    Err(_) => {
                        // Receipt timed out: the tx was accepted but hasn't mined.
                        // Its nonce is consumed-but-uncertain. The caller's retry
                        // loop would otherwise reserve a FRESH nonce and re-broadcast,
                        // stranding this one below it (blocked-from-below). Resolve
                        // the slot on-chain via a bounded same-nonce cancel before
                        // returning, seeded from the broadcast's own fees.
                        warn!(
                            batch_size,
                            nonce = broadcast.nonce,
                            timeout_secs = self.batch_receipt_timeout().as_secs(),
                            "batch_respond_to_tasks: receipt timed out, resolving stuck nonce off the hot path"
                        );
                        self.spawn_resolve_stuck_nonce(
                            broadcast.nonce,
                            broadcast.max_fee_per_gas,
                            broadcast.max_priority_fee_per_gas,
                        );
                        return Err(ChainIoError::TransactionTimeout {
                            timeout_secs: self.batch_receipt_timeout().as_secs(),
                        });
                    }
                };
                let tx_hash = receipt.transaction_hash;
                if !receipt.status() {
                    return Err(ChainIoError::TransactionReverted(tx_hash));
                }
                info!(batch_size, %tx_hash, "batch_respond_to_tasks: all items succeeded");
                Ok(receipt)
            }
            // Post-fill send failure: the nonce may be live. Resolve it on-chain
            // (the caller has no receipt tracker for this path) before returning a
            // transient error so its retry can safely re-reserve.
            Err(ChainIoError::BroadcastSendFailed {
                nonce,
                max_fee_per_gas,
                max_priority_fee_per_gas,
                reason,
            }) => {
                warn!(nonce, %reason, "batch_respond_to_tasks: send failed after fill, resolving stuck nonce off the hot path");
                self.spawn_resolve_stuck_nonce(nonce, max_fee_per_gas, max_priority_fee_per_gas);
                Err(ChainIoError::TransactionTimeout { timeout_secs: 0 })
            }
            // Fill-stage failures are already classified by `fill_and_send` (and
            // the reserved nonce released there).
            Err(e) => Err(e),
        }
    }

    /// Atomically create and respond to multiple tasks in a single transaction.
    ///
    /// Each item calls `createNewTask` then `respondToTask` within a single EVM execution
    /// context. If either call reverts for an item, the entire item reverts (no zombie tasks).
    /// Same failure semantics as `batch_create_tasks`: `Err(BatchPartialFailure)` on partial failure.
    pub async fn batch_create_and_respond_to_tasks(
        &self,
        batch_contract_addr: Address,
        tasks: Vec<Task>,
        responses: Vec<TaskResponse>,
        signature_data_array: Vec<Bytes>,
        attestation_data: Vec<Bytes>,
    ) -> Result<TransactionReceipt, ChainIoError> {
        let contract = BatchTaskManagerInstance::new(batch_contract_addr, self.signer_provider.clone());

        let batch_size = tasks.len();
        info!(
            batch_size = batch_size,
            batch_contract = %batch_contract_addr,
            "batch_create_and_respond: submitting batch"
        );

        let mut batch_tasks: Vec<BatchTask> = Vec::with_capacity(batch_size);
        let mut batch_responses: Vec<BatchTaskResponse> = Vec::with_capacity(batch_size);
        let mut batch_sigs: Vec<Bytes> = Vec::with_capacity(batch_size);
        let mut batch_attestations: Vec<Bytes> = Vec::with_capacity(batch_size);

        for (i, (((t, r), sig), att)) in tasks
            .into_iter()
            .zip(responses)
            .zip(signature_data_array)
            .zip(attestation_data)
            .enumerate()
        {
            let task_encoded = Task::abi_encode(&t);
            let bt = match BatchTask::abi_decode(&task_encoded) {
                Ok(bt) => bt,
                Err(e) => {
                    warn!(
                        error = %e,
                        index = i,
                        "batch_create_and_respond: failed to ABI-decode task, skipping triple"
                    );
                    continue;
                }
            };

            let resp_encoded = TaskResponse::abi_encode(&r);
            let br = match BatchTaskResponse::abi_decode(&resp_encoded) {
                Ok(br) => br,
                Err(e) => {
                    warn!(
                        error = %e,
                        index = i,
                        "batch_create_and_respond: failed to ABI-decode response, skipping triple"
                    );
                    continue;
                }
            };

            batch_tasks.push(bt);
            batch_responses.push(br);
            batch_sigs.push(sig);
            batch_attestations.push(att);
        }

        let skipped = batch_size - batch_tasks.len();
        if skipped > 0 {
            warn!(
                batch_size = batch_size,
                skipped = skipped,
                "batch_create_and_respond: {} triple(s) skipped due to ABI-decode failure",
                skipped
            );
        }
        if batch_tasks.is_empty() {
            error!(
                batch_size = batch_size,
                "batch_create_and_respond: all items failed ABI-decode, aborting empty batch"
            );
            return Err(ChainIoError::CreateNewTaskCallFail {
                reason: "all task/response triples failed ABI-decode; batch is empty".to_string(),
            });
        }

        let send_result = contract
            .batchCreateAndRespondToTasks(batch_tasks, batch_responses, batch_sigs, batch_attestations)
            .send()
            .await;

        match send_result {
            Ok(pending) => {
                let receipt = timeout(self.batch_receipt_timeout(), pending.get_receipt())
                    .await
                    .map_err(|_| {
                        warn!(
                            batch_size,
                            timeout_secs = self.batch_receipt_timeout().as_secs(),
                            "batch_create_and_respond: receipt timed out"
                        );
                        ChainIoError::TransactionTimeout {
                            timeout_secs: self.batch_receipt_timeout().as_secs(),
                        }
                    })?
                    .map_err(ChainIoError::AlloyProviderError)?;
                let tx_hash = receipt.transaction_hash;
                if !receipt.status() {
                    return Err(ChainIoError::TransactionReverted(tx_hash));
                }
                info!(batch_size, %tx_hash, "batch_create_and_respond: all items succeeded");
                Ok(receipt)
            }
            Err(e) => {
                if let Some(failures) = Self::parse_batch_partial_failure(&e) {
                    let fail_count = failures.len();
                    info!(
                        batch_size = batch_size,
                        fail_count = fail_count,
                        "batch_create_and_respond: partial failure"
                    );
                    Err(ChainIoError::BatchPartialFailure { failures })
                } else if let Some(revert_data) = e.as_revert_data() {
                    let classified = errors::classify_top_level_revert(&revert_data);
                    warn!(
                        batch_size,
                        error = %classified,
                        "batch_create_and_respond: top-level revert"
                    );
                    Err(classified)
                } else {
                    Err(ChainIoError::ContractError(e))
                }
            }
        }
    }

    /// Simulate a batch create+respond via `eth_call` (read-only, no transaction).
    ///
    /// Returns `Ok(())` if all items would succeed on-chain.
    /// Returns `Err(BatchPartialFailure)` if some items would fail (e.g., TaskAlreadyExists).
    /// Returns other `Err` variants for RPC or encoding failures.
    ///
    /// Used after receipt timeouts to determine which items already landed on-chain,
    /// and for poison detection without sending real transactions.
    pub async fn simulate_batch_create_and_respond(
        &self,
        batch_contract_addr: Address,
        tasks: Vec<Task>,
        responses: Vec<TaskResponse>,
        signature_data_array: Vec<Bytes>,
        attestation_data: Vec<Bytes>,
    ) -> Result<(), ChainIoError> {
        let contract = BatchTaskManagerInstance::new(batch_contract_addr, self.signer_provider.clone());

        let batch_size = tasks.len();

        let mut batch_tasks: Vec<BatchTask> = Vec::with_capacity(batch_size);
        let mut batch_responses: Vec<BatchTaskResponse> = Vec::with_capacity(batch_size);
        let mut batch_sigs: Vec<Bytes> = Vec::with_capacity(batch_size);
        let mut batch_attestations: Vec<Bytes> = Vec::with_capacity(batch_size);

        for (i, (((t, r), sig), att)) in tasks
            .into_iter()
            .zip(responses)
            .zip(signature_data_array)
            .zip(attestation_data)
            .enumerate()
        {
            let task_encoded = Task::abi_encode(&t);
            let bt = match BatchTask::abi_decode(&task_encoded) {
                Ok(bt) => bt,
                Err(e) => {
                    warn!(error = %e, index = i, "simulate_batch: ABI-decode task failed, skipping");
                    continue;
                }
            };
            let resp_encoded = TaskResponse::abi_encode(&r);
            let br = match BatchTaskResponse::abi_decode(&resp_encoded) {
                Ok(br) => br,
                Err(e) => {
                    warn!(error = %e, index = i, "simulate_batch: ABI-decode response failed, skipping");
                    continue;
                }
            };
            batch_tasks.push(bt);
            batch_responses.push(br);
            batch_sigs.push(sig);
            batch_attestations.push(att);
        }

        if batch_tasks.is_empty() {
            return Err(ChainIoError::CreateNewTaskCallFail {
                reason: "simulate_batch: all items failed ABI-decode".to_string(),
            });
        }

        // Use .call() (eth_call) instead of .send() — read-only simulation
        contract
            .batchCreateAndRespondToTasks(batch_tasks, batch_responses, batch_sigs, batch_attestations)
            .call()
            .await
            .map(|_| ())
            .map_err(|e| {
                if let Some(failures) = Self::parse_batch_partial_failure(&e) {
                    return ChainIoError::BatchPartialFailure { failures };
                }
                if let Some(revert_data) = e.as_revert_data() {
                    return errors::classify_top_level_revert(&revert_data);
                }
                ChainIoError::ContractError(e)
            })
    }

    /// Parse `BatchPartialFailure` error from a contract revert.
    ///
    /// Uses `as_revert_data()` to extract the raw revert bytes, then ABI-decodes the
    /// `BatchPartialFailure(FailedItem[])` struct where each `FailedItem` is
    /// `(uint256 index, bytes32 taskId, bytes reason)`.
    fn parse_batch_partial_failure(error: &alloy::contract::Error) -> Option<Vec<BatchFailedItem>> {
        use alloy::sol_types::SolType;

        let revert_data = error.as_revert_data()?;
        if revert_data.len() < 4 {
            return None;
        }
        let selector: [u8; 4] = revert_data[..4].try_into().ok()?;
        if selector != errors::selectors::BATCH_PARTIAL_FAILURE {
            return None;
        }

        // ABI layout: BatchPartialFailure(FailedItem[] failures)
        // FailedItem = (uint256 index, bytes32 taskId, bytes reason)
        type FailedItemArray = alloy::sol_types::sol_data::Array<(
            alloy::sol_types::sol_data::Uint<256>,
            alloy::sol_types::sol_data::FixedBytes<32>,
            alloy::sol_types::sol_data::Bytes,
        )>;

        let decoded = match FailedItemArray::abi_decode(&revert_data[4..]) {
            Ok(d) => d,
            Err(e) => {
                warn!(
                    error = %e,
                    revert_len = revert_data.len(),
                    "parse_batch_partial_failure: ABI decode failed"
                );
                return None;
            }
        };

        let items = decoded
            .into_iter()
            .map(|(index, task_id, reason)| BatchFailedItem {
                index: index.to::<usize>(),
                task_id: B256::from(task_id),
                reason,
            })
            .collect();

        Some(items)
    }
}

/// Drives the shared [`cancel::cancel_until_resolved`] loop from an `AvsWriter`
/// (the direct-send paths). Delegates to the writer's own broadcast/poll methods
/// and its attached allocator.
#[async_trait::async_trait]
impl NonceCanceller for AvsWriter {
    async fn broadcast_cancel(
        &self,
        nonce: u64,
        prev_max_fee: u128,
        prev_priority_fee: u128,
        bump_percent: u32,
    ) -> Result<cancel::CancelBroadcast, ChainIoError> {
        let b = self
            .cancel_nonce(nonce, prev_max_fee, prev_priority_fee, bump_percent)
            .await?;
        Ok(cancel::CancelBroadcast {
            tx_hash: b.tx_hash,
            max_fee_per_gas: b.max_fee_per_gas,
            max_priority_fee_per_gas: b.max_priority_fee_per_gas,
        })
    }

    async fn await_receipt(&self, tx_hash: B256, timeout: std::time::Duration) -> Result<(), ChainIoError> {
        self.get_receipt_by_hash(tx_hash, Some(timeout)).await.map(|_| ())
    }

    async fn latest_mined_nonce(&self) -> Result<u64, ChainIoError> {
        self.signer_transaction_count(false).await
    }

    async fn resync_allocator(&self) {
        if let Some(alloc) = self.nonce_allocator.as_ref() {
            let _ = alloc.resync().await;
        }
    }
}

/// A single failed item from a `BatchPartialFailure` revert.
#[derive(Debug, Clone)]
pub struct BatchFailedItem {
    /// Index of the failed item in the original batch array
    pub index: usize,
    /// Task ID of the failed item
    pub task_id: B256,
    /// ABI-encoded revert reason from the underlying call
    pub reason: Bytes,
}

/// Log detailed error information for createNewTask call failures.
/// This function performs a simulation call and logs detailed error information.
/// Returns the identified error message if one was identified, None otherwise.
#[allow(clippy::too_many_arguments)]
pub async fn log_create_task_error(
    task_manager_addr: Address,
    signer: &SdkSigner,
    policy_client: Address,
    wasm_args: Bytes,
    intent: &NewtonMessage::Intent,
    intent_signature: &Option<Bytes>,
    quorum_number: Vec<QuorumNum>,
    quorum_threshold_percentage: QuorumThresholdPercentage,
    initialization_timestamp: u64,
) -> Option<String> {
    info!("Simulating createNewTask call to identify exact revert location");

    let task_manager_contract = NewtonProverTaskManager::new(task_manager_addr, signer.clone());
    // Use a placeholder block for simulation - actual block validation is done in contract
    // NOTE: simulation uses hardcoded taskCreatedBlock=1, which will trigger InvalidTaskCreatedBlock
    // if the contract requires taskCreatedBlock > 0 and < block.number within buffer window.
    // This simulation is for identifying OTHER errors, not block validation issues.
    info!(
        simulation_task_created_block = 1,
        "log_create_task_error: simulation using hardcoded taskCreatedBlock=1"
    );
    let task = Task {
        taskId: task_id(None),
        policyClient: policy_client,
        taskCreatedBlock: 1,
        quorumThresholdPercentage: quorum_threshold_percentage.into(),
        intent: intent.clone(),
        intentSignature: intent_signature.clone().unwrap_or_default(),
        wasmArgs: wasm_args.clone(),
        quorumNumbers: quorum_number.clone().into(),
        initializationTimestamp: U256::from(initialization_timestamp),
    };

    let create_new_task_call = task_manager_contract.createNewTask(task.clone());

    let simulation_result = create_new_task_call.call().await;

    if let Err(error) = simulation_result {
        error!("createNewTask simulation error: {:?}", error);

        let error_str = format!("{:?}", error);
        if !error_str.contains("execution reverted") {
            return None;
        }

        // Check for empty revert data (0x)
        if error_str.contains("data: Some(RawValue(\"0x\"))") {
            use newton_core::newton_prover_task_manager::NewtonProverTaskManager::createNewTaskCall;
            let call_obj = createNewTaskCall { task };
            let call_data = call_obj.abi_encode();
            let signer_address = signer.default_signer_address();

            error!(
                task_manager = %task_manager_addr,
                signer = %signer_address,
                calldata_hex = %hex::encode(&call_data),
                "Empty revert (0x) in createNewTask"
            );
            return Some("Empty revert (0x) in createNewTask".to_string());
        }

        // Try to extract error selector from revert data
        if let Some(start_idx) = error_str.find("RawValue(\"0x") {
            if let Some(end_idx) = error_str[start_idx..].find("\")") {
                let hex_data = &error_str[start_idx + 11..start_idx + end_idx];
                if hex_data.len() >= 8 && hex_data != "0x" {
                    if let Ok(bytes) = Bytes::from_str(hex_data) {
                        if bytes.len() >= 4 {
                            let selector: [u8; 4] = bytes[..4].try_into().unwrap_or([0; 4]);
                            let selector_hex = hex::encode(selector);

                            if let Some(decoded_msg) = decode_error_selector(selector) {
                                error!(
                                    error_selector = %format!("0x{}", selector_hex),
                                    error_message = %decoded_msg,
                                    "createNewTask error identified"
                                );
                                return Some(decoded_msg);
                            }

                            // Unknown selector
                            error!(
                                error_selector = %format!("0x{}", selector_hex),
                                "Unknown error selector in createNewTask"
                            );
                            return Some(format!("Unknown error selector: 0x{}", selector_hex));
                        }
                    }
                }
            }
        }
    }
    None
}

/// Decode an error selector to a human-readable message.
/// Uses generated bindings for Newton errors and the external registry for library errors.
fn decode_error_selector(selector: [u8; 4]) -> Option<String> {
    // Task lifecycle errors
    if selector == TaskMismatch::SELECTOR {
        return Some(format!(
            "{} - task hash differs from stored (check taskCreatedBlock)",
            TaskMismatch::SIGNATURE
        ));
    }
    if selector == TaskAlreadyResponded::SELECTOR {
        return Some(format!(
            "{} - task already has a response (existing hash in revert data)",
            TaskAlreadyResponded::SIGNATURE
        ));
    }
    if selector == TaskAlreadyExists::SELECTOR {
        return Some(format!(
            "{} - task with this ID already exists (existing hash in revert data)",
            TaskAlreadyExists::SIGNATURE
        ));
    }
    if selector == InvalidReferenceBlocknumber::SELECTOR {
        return Some(format!(
            "{} - taskCreatedBlock must be < current block",
            InvalidReferenceBlocknumber::SIGNATURE
        ));
    }

    // BLS/Crypto errors
    if selector == InvalidBLSPairingKey::SELECTOR {
        return Some(format!(
            "{} - BLS pairing verification failed",
            InvalidBLSPairingKey::SIGNATURE
        ));
    }
    if selector == InvalidBLSSignature::SELECTOR {
        return Some(format!(
            "{} - BLS signature verification failed",
            InvalidBLSSignature::SIGNATURE
        ));
    }
    if selector == InvalidQuorumApkHash::SELECTOR {
        return Some(format!(
            "{} - quorum APK hash mismatch",
            InvalidQuorumApkHash::SIGNATURE
        ));
    }
    if selector == NonSignerPubkeysNotSorted::SELECTOR {
        return Some(format!(
            "{} - non-signer public keys must be sorted",
            NonSignerPubkeysNotSorted::SIGNATURE
        ));
    }
    if selector == ECAddFailed::SELECTOR {
        return Some(format!(
            "{} - elliptic curve point addition failed",
            ECAddFailed::SIGNATURE
        ));
    }
    if selector == ECMulFailed::SELECTOR {
        return Some(format!(
            "{} - elliptic curve scalar multiplication failed",
            ECMulFailed::SIGNATURE
        ));
    }
    if selector == ExpModFailed::SELECTOR {
        return Some(format!("{} - modular exponentiation failed", ExpModFailed::SIGNATURE));
    }
    if selector == ScalarTooLarge::SELECTOR {
        return Some(format!(
            "{} - scalar value exceeds field modulus",
            ScalarTooLarge::SIGNATURE
        ));
    }

    // Access control errors
    if selector == OnlyTaskGenerator::SELECTOR {
        return Some(format!(
            "{} - caller not registered as task generator",
            OnlyTaskGenerator::SIGNATURE
        ));
    }
    if selector == OnlyPauser::SELECTOR {
        return Some(format!("{} - caller is not authorized pauser", OnlyPauser::SIGNATURE));
    }
    if selector == OnlyUnpauser::SELECTOR {
        return Some(format!(
            "{} - caller is not authorized unpauser",
            OnlyUnpauser::SIGNATURE
        ));
    }
    if selector == OnlyRegistryCoordinatorOwner::SELECTOR {
        return Some(format!(
            "{} - caller is not registry coordinator owner",
            OnlyRegistryCoordinatorOwner::SIGNATURE
        ));
    }

    // Input validation errors
    if selector == InputAddressZero::SELECTOR {
        return Some(format!(
            "{} - address parameter cannot be zero",
            InputAddressZero::SIGNATURE
        ));
    }
    if selector == InputArrayLengthMismatch::SELECTOR {
        return Some(format!(
            "{} - array lengths do not match",
            InputArrayLengthMismatch::SIGNATURE
        ));
    }
    if selector == InputEmptyQuorumNumbers::SELECTOR {
        return Some(format!(
            "{} - quorum numbers array is empty",
            InputEmptyQuorumNumbers::SIGNATURE
        ));
    }
    if selector == InputNonSignerLengthMismatch::SELECTOR {
        return Some(format!(
            "{} - non-signer arrays have mismatched lengths",
            InputNonSignerLengthMismatch::SIGNATURE
        ));
    }
    if selector == BitmapValueTooLarge::SELECTOR {
        return Some(format!(
            "{} - bitmap value exceeds maximum",
            BitmapValueTooLarge::SIGNATURE
        ));
    }
    if selector == BytesArrayLengthTooLong::SELECTOR {
        return Some(format!(
            "{} - bytes array exceeds maximum length",
            BytesArrayLengthTooLong::SIGNATURE
        ));
    }
    if selector == BytesArrayNotOrdered::SELECTOR {
        return Some(format!(
            "{} - bytes array elements not in required order",
            BytesArrayNotOrdered::SIGNATURE
        ));
    }

    // Pause/state errors
    if selector == CurrentlyPaused::SELECTOR {
        return Some(format!("{} - contract is currently paused", CurrentlyPaused::SIGNATURE));
    }
    if selector == InvalidNewPausedStatus::SELECTOR {
        return Some(format!(
            "{} - invalid pause status transition",
            InvalidNewPausedStatus::SIGNATURE
        ));
    }

    // PDS state-commit errors (StateCommitRegistry / IStateRootCommittable)
    if selector == SequenceGap::SELECTOR {
        return Some(format!(
            "{} - submitted sequenceNo != lastCommittedSequenceNo + 1 (out-of-order commit)",
            SequenceGap::SIGNATURE
        ));
    }
    if selector == StateRootMismatch::SELECTOR {
        return Some(format!(
            "{} - prevStateRoot != lastCommittedStateRoot (state divergence or stale view)",
            StateRootMismatch::SIGNATURE
        ));
    }
    if selector == TimestampRegression::SELECTOR {
        return Some(format!(
            "{} - commit.timestamp <= lastCommittedTimestamp (replay or reorg)",
            TimestampRegression::SIGNATURE
        ));
    }
    if selector == InvalidPcr0Commitment::SELECTOR {
        return Some(format!(
            "{} - pcr0Commitment is bytes32(0) (missing enclave attestation)",
            InvalidPcr0Commitment::SIGNATURE
        ));
    }
    if selector == InvalidNewStateRoot::SELECTOR {
        return Some(format!(
            "{} - newStateRoot is bytes32(0) (cannot represent any legitimate JMT root)",
            InvalidNewStateRoot::SIGNATURE
        ));
    }
    if selector == UnsupportedStateCommitVersion::SELECTOR {
        return Some(format!(
            "{} - StateCommit.version != STATE_COMMIT_V1 (schema mismatch)",
            UnsupportedStateCommitVersion::SIGNATURE
        ));
    }
    if selector == InvalidSealedSnapshot::SELECTOR {
        return Some(format!(
            "{} - sealed snapshot payload malformed or signature empty",
            InvalidSealedSnapshot::SIGNATURE
        ));
    }
    if selector == CertificateMessageHashMismatch::SELECTOR {
        return Some(format!(
            "{} - cert.messageHash != keccak256(abi.encode(StateCommit)) (cert reuse / digest drift)",
            CertificateMessageHashMismatch::SIGNATURE
        ));
    }

    // External errors from registry (library/policy errors not directly in TaskManager bindings)
    if let Some(ext_error) = errors::lookup_external_error(&selector) {
        return Some(format!("{} - {}", ext_error.name, ext_error.description));
    }

    None
}

/// Log detailed error information for respondToTask call failures.
/// This function analyzes the error to identify the cause and logs diagnostic information.
/// Returns the identified error message if one was identified, None otherwise.
pub fn log_respond_to_task_error(
    error: &alloy::contract::Error,
    task: &Task,
    task_manager_addr: Address,
    signer_address: Address,
    calldata: &[u8],
    chain_id: u64,
) -> Option<String> {
    info!("Analyzing respondToTask error to identify failure cause");

    // Use alloy's as_revert_data() method to extract revert data properly
    // This is more reliable than parsing Debug output strings
    if let Some(revert_data) = error.as_revert_data() {
        // Check for empty revert data (0x) - indicates BN254 EC operation failure or other assembly revert
        if revert_data.is_empty() {
            error!(
                chain_id,
                task_id = %newton_core::hex!(task.taskId),
                task_created_block = task.taskCreatedBlock,
                task_manager = %task_manager_addr,
                signer = %signer_address,
                calldata_len = calldata.len(),
                "[DEBUG] Empty revert (0x): BN254 EC operation failure"
            );

            // [DEBUG] Provide additional context for BN254 failure root cause analysis
            error!(
                chain_id,
                task_id = %newton_core::hex!(task.taskId),
                "[DEBUG] BN254 EC Operation Failure - Potential causes:\n\
                 1. Signers APK G2 is point at infinity (no valid signers aggregated)\n\
                 2. Aggregated signature is point at infinity (no valid signatures)\n\
                 3. Non-signer public keys contain invalid/malformed G1 points\n\
                 4. Quorum APK contains invalid G1 points\n\
                 5. Pairing check failed due to signature/message mismatch\n\
                 Check the [DEBUG] logs above for 'point at infinity' warnings."
            );

            return Some("Empty revert (0x): BN254 EC operation failure".to_string());
        }

        // Extract 4-byte selector from revert data
        if revert_data.len() >= 4 {
            let selector: [u8; 4] = revert_data[..4].try_into().unwrap_or([0; 4]);
            let selector_hex = hex::encode(selector);

            if let Some(decoded_msg) = decode_error_selector(selector) {
                error!(
                    chain_id,
                    task_id = %newton_core::hex!(task.taskId),
                    task_created_block = task.taskCreatedBlock,
                    error_selector = %format!("0x{}", selector_hex),
                    error_message = %decoded_msg,
                    task_manager = %task_manager_addr,
                    signer = %signer_address,
                    "respondToTask error identified"
                );
                // Log debug hint for transaction investigation
                error!("Debug hint: Run `cast run --trace <tx_hash> --rpc-url <rpc_url>` to investigate");
                return Some(decoded_msg);
            }

            // Unknown selector - log full revert data for debugging
            error!(
                chain_id,
                task_id = %newton_core::hex!(task.taskId),
                task_created_block = task.taskCreatedBlock,
                error_selector = %format!("0x{}", selector_hex),
                revert_data_hex = %format!("0x{}", hex::encode(&revert_data)),
                task_manager = %task_manager_addr,
                signer = %signer_address,
                "Unknown error selector in respondToTask"
            );
            error!("Debug hint: Run `cast run --trace <tx_hash> --rpc-url <rpc_url>` to investigate");
            return Some(format!("Unknown error selector: 0x{}", selector_hex));
        }
    }

    // Fallback: try to extract from error string for non-revert errors
    let error_str = format!("{:?}", error);
    error!(
        chain_id,
        task_id = %newton_core::hex!(task.taskId),
        task_created_block = task.taskCreatedBlock,
        task_manager = %task_manager_addr,
        signer = %signer_address,
        error = %error_str,
        "Failed to extract revert data from respondToTask error"
    );
    None
}

/// Log detailed error information for `commitStateRoot` call failures.
///
/// Follows the same pattern as `log_respond_to_task_error` — extract revert data,
/// route through `decode_error_selector`, fall back to raw revert hex on unknown
/// selectors. Log fields are commit-specific (sequenceNo, prev/newStateRoot,
/// daCertHash, pcr0Commitment) and the empty-revert cause list is specific to
/// the `ViewBN254CertificateVerifier` + `StateCommitRegistry` path.
///
/// Returns the identified error message if one was decoded, None otherwise.
pub fn log_commit_state_root_error(
    error: &alloy::contract::Error,
    commit: &StateCommit,
    registry_addr: Address,
    signer_address: Address,
    calldata: &[u8],
    chain_id: u64,
) -> Option<String> {
    info!("Analyzing commitStateRoot error to identify failure cause");

    if let Some(revert_data) = error.as_revert_data() {
        // Empty 0x revert: BLS pairing failure or assembly-level revert in
        // the on-chain certificate verifier
        if revert_data.is_empty() {
            error!(
                chain_id,
                sequence_no = commit.sequenceNo,
                timestamp = commit.timestamp,
                prev_state_root = %commit.prevStateRoot,
                new_state_root = %commit.newStateRoot,
                registry = %registry_addr,
                signer = %signer_address,
                calldata_len = calldata.len(),
                "[DEBUG] Empty revert (0x): possible BLS pairing failure or assembly revert in cert verifier"
            );

            // [DEBUG] Provide additional context for state-commit empty-revert root cause analysis
            error!(
                chain_id,
                sequence_no = commit.sequenceNo,
                "[DEBUG] State Commit Empty Revert - Potential causes:\n\
                 1. ViewBN254CertificateVerifier BLS pairing math failed: signers APK at infinity, quorum APK invalid, or quorum stake below threshold. Note: cert.messageHash drift fires typed CertificateMessageHashMismatch (0x822ef683), NOT empty revert.\n\
                 2. Operator set table not yet populated on this chain (source: BN254TableCalculator unseeded after redeployment; destination: ECDSAOperatorTableUpdater behind transporter sync)\n\
                 3. Out-of-gas during BN254 EC operations in cert verification\n\
                 4. Assembly-level revert in StateCommitRegistry (check redeployment / storage-layout integrity)\n\
                 Verify cert with `cast call` on viewBN254CertificateVerifier; check operator table population on this chain."
            );

            return Some("Empty revert (0x): BLS verification or assembly revert".to_string());
        }

        if revert_data.len() >= 4 {
            let selector: [u8; 4] = revert_data[..4].try_into().unwrap_or([0; 4]);
            let selector_hex = hex::encode(selector);

            if let Some(decoded_msg) = decode_error_selector(selector) {
                error!(
                    chain_id,
                    sequence_no = commit.sequenceNo,
                    timestamp = commit.timestamp,
                    prev_state_root = %commit.prevStateRoot,
                    new_state_root = %commit.newStateRoot,
                    da_cert_hash = %commit.daCertHash,
                    pcr0_commitment = %commit.pcr0Commitment,
                    error_selector = %format!("0x{}", selector_hex),
                    error_message = %decoded_msg,
                    registry = %registry_addr,
                    signer = %signer_address,
                    "commitStateRoot error identified"
                );
                error!("Debug hint: Run `cast run --trace <tx_hash> --rpc-url <rpc_url>` to investigate");
                return Some(decoded_msg);
            }

            error!(
                chain_id,
                sequence_no = commit.sequenceNo,
                timestamp = commit.timestamp,
                prev_state_root = %commit.prevStateRoot,
                new_state_root = %commit.newStateRoot,
                error_selector = %format!("0x{}", selector_hex),
                revert_data_hex = %format!("0x{}", hex::encode(&revert_data)),
                registry = %registry_addr,
                signer = %signer_address,
                "Unknown error selector in commitStateRoot"
            );
            error!("Debug hint: Run `cast run --trace <tx_hash> --rpc-url <rpc_url>` to investigate");
            return Some(format!("Unknown error selector: 0x{}", selector_hex));
        }
    }

    let error_str = format!("{:?}", error);
    error!(
        chain_id,
        sequence_no = commit.sequenceNo,
        timestamp = commit.timestamp,
        prev_state_root = %commit.prevStateRoot,
        new_state_root = %commit.newStateRoot,
        registry = %registry_addr,
        signer = %signer_address,
        error = %error_str,
        "Failed to extract revert data from commitStateRoot error"
    );
    None
}

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

    // ----- STATE_COMMIT_RECEIPT_TIMEOUT --------------------------------------
    //
    // The 60s receipt timeout is half of the protocol's 120s commit cadence
    // (see PRIVATE_DATA_STORAGE.md §6.1). A drift here means a stuck commit
    // could block the next aggregator's prepare-phase tick. Pin the constant
    // so refactors that change the cadence have to update this test too.

    #[test]
    fn test_state_commit_receipt_timeout_is_60s() {
        assert_eq!(STATE_COMMIT_RECEIPT_TIMEOUT, Duration::from_secs(60));
    }

    // ----- escalate_floor — gas-bump replacement pricing ---------------------
    //
    // The bump must always beat the replaced TX by >=10% on BOTH fee fields
    // (EIP-1559 replacement rule) AND track a rising market AND keep the tip
    // realizable. `market` is now `(base_fee, market_priority)`; the function
    // sizes max_fee = max(prev × 1.10, base_fee × 2.5 + priority) so the validator
    // tip `min(priority, max_fee − base_fee)` always equals the full priority.
    // These pin the floor logic that prevents "replacement transaction
    // underpriced" (see docs/BATCH_SUBMISSION_NONCE_ANCHORING.md).

    // Sentinel for "no ceiling" in the floor tests.
    const NO_CEIL: u128 = u128::MAX;

    /// The realized validator tip from a 1559 tx: `min(priority, max_fee − base)`.
    fn realized_tip(max_fee: u128, prio: u128, base_fee: u128) -> u128 {
        prio.min(max_fee.saturating_sub(base_fee))
    }

    #[test]
    fn escalate_floor_market_priority_wins_and_is_fully_realizable() {
        // Hot market: priority tracks the market tip (100 > prev×1.10=55), and
        // max_fee carries enough headroom that the FULL tip reaches the validator.
        let base_fee = 1_000;
        let (max_fee, prio) = escalate_floor(Some((base_fee, 100)), 500, 50, NO_CEIL);
        assert_eq!(prio, 100, "priority tracks the market tip");
        assert_eq!(
            max_fee,
            base_fee * 5 / 2 + 100,
            "max_fee = base×2.5 + priority headroom"
        );
        assert_eq!(
            realized_tip(max_fee, prio, base_fee),
            prio,
            "the full priority must be realizable as a tip"
        );
    }

    #[test]
    fn escalate_floor_applies_10pct_floor_when_market_cooled() {
        // Cooled market (low base, low tip): the ≥10% floor over prev wins on
        // both fields, else the replacement is rejected as underpriced.
        let (max_fee, prio) = escalate_floor(Some((100, 40)), 500, 50, NO_CEIL);
        assert_eq!(max_fee, 550, "prev_max_fee × 1.10 floor wins over base×2.5+prio=305");
        assert_eq!(prio, 55, "prev_prio × 1.10 floor wins over market tip 40");
    }

    #[test]
    fn escalate_floor_market_unavailable_still_escalates() {
        // fee-history failed (None): never broadcast at/below prev — apply the
        // floor so the replacement still clears the >=10% rule on both fields.
        let (max_fee, prio) = escalate_floor(None, 500, 50, NO_CEIL);
        assert_eq!(max_fee, 550);
        assert_eq!(prio, 55, "priority still climbs even with no market quote");
    }

    #[test]
    fn escalate_floor_tip_realizable_as_base_fee_rises() {
        // The core of Fix: the base fee climbs sharply between attempts. The
        // headroom (base × 2.5) must keep the full priority tip realizable at the
        // NEW base fee, not a fraction throttled by a stale max_fee.
        let prev_base = 100;
        let (prev_max, prev_prio) = escalate_floor(Some((prev_base, 30)), 0, 0, NO_CEIL);
        // Base fee doubles (≈6 blocks of max EIP-1559 growth) by the next attempt.
        let new_base = 200;
        let (max_fee, prio) = escalate_floor(Some((new_base, 30)), prev_max, prev_prio, NO_CEIL);
        assert_eq!(
            realized_tip(max_fee, prio, new_base),
            prio,
            "full tip must survive a doubling base fee: max_fee {max_fee}, base {new_base}, prio {prio}"
        );
    }

    #[test]
    fn escalate_floor_is_monotonic_across_attempts() {
        // 3 attempts in a cooled market (None each): each must strictly exceed
        // the previous on both fields, so the node never rejects the replacement.
        let mut max_fee = 1_000u128;
        let mut prio = 100u128;
        for _ in 0..3 {
            let (nm, np) = escalate_floor(None, max_fee, prio, NO_CEIL);
            assert!(nm > max_fee, "max_fee must climb: {nm} !> {max_fee}");
            assert!(np > prio, "priority must climb: {np} !> {prio}");
            max_fee = nm;
            prio = np;
        }
    }

    #[test]
    fn escalate_floor_saturates_without_overflow() {
        // Near u128::MAX the ×1.10 / ×2 must saturate, not panic or wrap to a
        // small value. (Saturating-mul-then-divide lands below u128::MAX — that's
        // fine; the only real invariants are "didn't wrap" and "priority ≤ max".)
        // Saturating ×110 then ÷100 lands near u128::MAX/100; assert we stay far
        // above any "wrapped to small" value without pinning the exact figure.
        let huge = u128::MAX / 1000;
        for market in [Some((u128::MAX, u128::MAX)), None] {
            let (max_fee, prio) = escalate_floor(market, u128::MAX, u128::MAX, NO_CEIL);
            assert!(max_fee > huge, "max_fee must stay huge (no wrap): {max_fee}");
            assert!(prio > huge, "priority must stay huge (no wrap): {prio}");
            assert!(prio <= max_fee, "priority {prio} must not exceed max_fee {max_fee}");
        }
    }

    #[test]
    fn escalate_floor_clamps_to_ceiling() {
        // A hot market quote above the ceiling must be clamped down. The runaway
        // bug priced a 21k cancel at ~786k gwei; a sane ceiling caps it.
        let ceiling = 1_000u128;
        let (max_fee, prio) = escalate_floor(Some((5_000, 4_000)), 500, 50, ceiling);
        assert_eq!(max_fee, 1_000, "max_fee clamped to ceiling");
        assert_eq!(
            prio, 1_000,
            "priority clamped to the post-ceiling max_fee, never above it"
        );
    }

    #[test]
    fn escalate_floor_ceiling_breaks_runaway_escalation() {
        // The runaway regression: without a ceiling, repeated cooled-market floor
        // bumps compound geometrically. With one, fees plateau at the ceiling
        // instead of climbing until the signer can't pay.
        let ceiling = 10_000u128;
        let mut max_fee = 1_000u128;
        let mut prio = 100u128;
        for _ in 0..50 {
            let (nm, np) = escalate_floor(None, max_fee, prio, ceiling);
            max_fee = nm;
            prio = np;
        }
        assert_eq!(max_fee, ceiling, "max_fee must plateau at the ceiling, not run away");
        assert!(prio <= max_fee, "priority must never exceed max_fee");
    }

    #[test]
    fn escalate_floor_keeps_priority_below_clamped_max_fee() {
        // Even when prev priority was already near the ceiling, clamping max_fee
        // down must drag priority with it so priority ≤ max_fee holds.
        let ceiling = 2_000u128;
        let (max_fee, prio) = escalate_floor(None, 10_000, 9_000, ceiling);
        assert_eq!(max_fee, 2_000);
        assert!(
            prio <= max_fee,
            "priority {prio} must not exceed clamped max_fee {max_fee}"
        );
    }

    // ----- decode_error_selector — PDS state-commit selectors ----------------
    //
    // Selector hex values are pinned per `.claude/rules/error-selectors.md` to
    // catch silent ABI drift in `StateCommitRegistry.sol` / `IStateRootCommittable.sol`.
    // A renamed field or reordered struct in the Solidity source would shift the
    // keccak256-derived selector, which would route to the unknown-selector
    // branch (raw hex in logs) instead of the typed diagnostic path.

    #[test]
    fn test_decode_sequence_gap() {
        let selector = [0x10, 0x4d, 0x00, 0x50];
        assert_eq!(SequenceGap::SELECTOR, selector);
        let decoded = decode_error_selector(selector);
        assert!(decoded.is_some());
        let msg = decoded.unwrap();
        assert!(msg.contains("SequenceGap"));
        assert!(msg.contains("out-of-order commit"));
    }

    #[test]
    fn test_decode_state_root_mismatch() {
        let selector = [0x37, 0xf0, 0x4d, 0x41];
        assert_eq!(StateRootMismatch::SELECTOR, selector);
        let decoded = decode_error_selector(selector);
        assert!(decoded.is_some());
        let msg = decoded.unwrap();
        assert!(msg.contains("StateRootMismatch"));
        assert!(msg.contains("state divergence"));
    }

    #[test]
    fn test_decode_timestamp_regression() {
        let selector = [0x5a, 0x61, 0x2e, 0x4c];
        assert_eq!(TimestampRegression::SELECTOR, selector);
        let decoded = decode_error_selector(selector);
        assert!(decoded.is_some());
        let msg = decoded.unwrap();
        assert!(msg.contains("TimestampRegression"));
        assert!(msg.contains("replay or reorg"));
    }

    #[test]
    fn test_decode_invalid_pcr0_commitment() {
        let selector = [0x6d, 0xfb, 0xfc, 0x74];
        assert_eq!(InvalidPcr0Commitment::SELECTOR, selector);
        let decoded = decode_error_selector(selector);
        assert!(decoded.is_some());
        let msg = decoded.unwrap();
        assert!(msg.contains("InvalidPcr0Commitment"));
        assert!(msg.contains("missing enclave attestation"));
    }

    #[test]
    fn test_decode_invalid_new_state_root() {
        let selector = [0x5b, 0xf0, 0xf7, 0x68];
        assert_eq!(InvalidNewStateRoot::SELECTOR, selector);
        let decoded = decode_error_selector(selector);
        assert!(decoded.is_some());
        let msg = decoded.unwrap();
        assert!(msg.contains("InvalidNewStateRoot"));
        assert!(msg.contains("legitimate JMT root"));
    }

    #[test]
    fn test_decode_unsupported_state_commit_version() {
        let selector = [0xb6, 0x81, 0x66, 0x8e];
        assert_eq!(UnsupportedStateCommitVersion::SELECTOR, selector);
        let decoded = decode_error_selector(selector);
        assert!(decoded.is_some());
        let msg = decoded.unwrap();
        assert!(msg.contains("UnsupportedStateCommitVersion"));
        assert!(msg.contains("schema mismatch"));
    }

    #[test]
    fn test_decode_invalid_sealed_snapshot() {
        let selector = [0xdc, 0x4e, 0x1d, 0x57];
        assert_eq!(InvalidSealedSnapshot::SELECTOR, selector);
        let decoded = decode_error_selector(selector);
        assert!(decoded.is_some());
        let msg = decoded.unwrap();
        assert!(msg.contains("InvalidSealedSnapshot"));
        assert!(msg.contains("malformed"));
    }

    #[test]
    fn test_decode_certificate_message_hash_mismatch() {
        let selector = [0x82, 0x2e, 0xf6, 0x83];
        assert_eq!(CertificateMessageHashMismatch::SELECTOR, selector);
        let decoded = decode_error_selector(selector);
        assert!(decoded.is_some());
        let msg = decoded.unwrap();
        assert!(msg.contains("CertificateMessageHashMismatch"));
        assert!(msg.contains("cert reuse"));
    }

    #[test]
    fn test_decode_unknown_selector_returns_none() {
        // 0xfefdfcfb is a synthetic value not present in any Newton or external
        // error registry. If this test starts failing, audit the new selector
        // before adjusting — a recognized selector should add a typed test above.
        let selector = [0xfe, 0xfd, 0xfc, 0xfb];
        let decoded = decode_error_selector(selector);
        assert!(decoded.is_none());
    }
}