quantus-cli 2.1.1

Command line interface and library for interacting with the Quantus Network
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
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
use crate::{
	chain::{
		client::{ChainConfig, QuantusClient},
		quantus_subxt::{self as quantus_node, api::wormhole},
	},
	cli::{
		address_format::{bytes_to_quantus_ss58, slice_to_quantus_ss58},
		common::{ExecutionMode, TransactionStage},
		send::get_balance,
	},
	log_error, log_print, log_success, log_verbose,
	wallet::{password, QuantumKeyPair, WalletManager},
};
use clap::Subcommand;
use indicatif::{ProgressBar, ProgressStyle};
use plonky2::plonk::proof::ProofWithPublicInputs;
use qp_rusty_crystals_hdwallet::{
	derive_wormhole_from_mnemonic, WormholePair, QUANTUS_WORMHOLE_CHAIN_ID,
};
use qp_wormhole_aggregator::config::CircuitBinsConfig;
use qp_wormhole_circuit::inputs::ParsePrivateBatchPublicInputs;
use qp_wormhole_inputs::PrivateBatchPublicInputs;
use qp_zk_circuits_common::{
	circuit::{C, D, F},
	utils::BytesDigest,
};
use sp_core::crypto::{AccountId32, Ss58Codec};
use subxt::{
	blocks::Block,
	ext::{
		codec::Encode,
		jsonrpsee::{core::client::ClientT, rpc_params},
	},
	utils::AccountId32 as SubxtAccountId,
	OnlineClient,
};

// Re-export constants and functions from wormhole_lib module for backward compatibility
use crate::wormhole_lib;
pub use crate::wormhole_lib::{
	compute_output_amount, NATIVE_ASSET_ID, SCALE_DOWN_FACTOR, VOLUME_FEE_BPS,
};

// ============================================================================
// ZK Tree Types (for 4-ary Poseidon Merkle proofs)
// ============================================================================

/// A 32-byte hash output.
pub type Hash256 = [u8; 32];

/// Merkle proof from the ZK tree RPC.
///
/// This is the client-side representation of the proof returned by `zkTree_getMerkleProof`.
/// Siblings are unsorted - the client computes position hints by sorting siblings + current hash.
#[derive(Debug, Clone)]
#[allow(dead_code)] // Fields used for deserialization and future use when ZK trie is deployed
pub struct ZkMerkleProofRpc {
	/// Index of the leaf
	pub leaf_index: u64,
	/// The leaf data (SCALE-encoded ZkLeaf)
	pub leaf_data: Vec<u8>,
	/// Leaf hash
	pub leaf_hash: Hash256,
	/// Sibling hashes at each level (3 siblings per level for 4-ary tree).
	/// These are unsorted - client sorts and computes positions.
	pub siblings: Vec<[Hash256; 3]>,
	/// Current tree root
	pub root: Hash256,
	/// Current tree depth
	pub depth: u8,
}

impl<'de> serde::Deserialize<'de> for ZkMerkleProofRpc {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: serde::Deserializer<'de>,
	{
		#[derive(serde::Deserialize)]
		struct RawZkMerkleProofRpc {
			leaf_index: u64,
			#[serde(with = "byte_array")]
			leaf_data: Vec<u8>,
			#[serde(with = "hash_array")]
			leaf_hash: Hash256,
			#[serde(with = "siblings_format")]
			siblings: Vec<[Hash256; 3]>,
			#[serde(with = "hash_array")]
			root: Hash256,
			depth: u8,
		}

		let raw = <RawZkMerkleProofRpc as serde::Deserialize>::deserialize(deserializer)?;
		if raw.depth as usize != raw.siblings.len() {
			return Err(serde::de::Error::custom(format!(
				"depth {} does not match siblings length {}",
				raw.depth,
				raw.siblings.len()
			)));
		}

		Ok(Self {
			leaf_index: raw.leaf_index,
			leaf_data: raw.leaf_data,
			leaf_hash: raw.leaf_hash,
			siblings: raw.siblings,
			root: raw.root,
			depth: raw.depth,
		})
	}
}

/// Helper module for deserializing byte arrays (chain sends as array of numbers)
mod byte_array {
	use serde::{Deserialize, Deserializer};

	const ZK_LEAF_DATA_LEN: usize = 60;

	pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
	where
		D: Deserializer<'de>,
	{
		let bytes = Vec::<u8>::deserialize(deserializer)?;
		if bytes.len() != ZK_LEAF_DATA_LEN {
			return Err(serde::de::Error::custom(format!(
				"expected {} bytes, got {}",
				ZK_LEAF_DATA_LEN,
				bytes.len()
			)));
		}
		Ok(bytes)
	}
}

/// Helper module for deserializing 32-byte hashes (chain sends as array of numbers)
mod hash_array {
	use serde::{Deserialize, Deserializer};

	pub fn deserialize<'de, D>(deserializer: D) -> Result<[u8; 32], D::Error>
	where
		D: Deserializer<'de>,
	{
		let bytes: Vec<u8> = Deserialize::deserialize(deserializer)?;
		bytes.try_into().map_err(|v: Vec<u8>| {
			serde::de::Error::custom(format!("expected 32 bytes, got {}", v.len()))
		})
	}
}

/// Helper module for deserializing siblings array (chain sends as array of arrays of numbers)
mod siblings_format {
	use qp_zk_circuits_common::zk_merkle::MAX_DEPTH;
	use serde::{Deserialize, Deserializer};

	pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<[[u8; 32]; 3]>, D::Error>
	where
		D: Deserializer<'de>,
	{
		// Chain sends: Vec<[[u8; 32]; 3]> serialized as array of arrays of arrays of numbers
		let levels: Vec<Vec<Vec<u8>>> = Deserialize::deserialize(deserializer)?;
		if levels.len() > MAX_DEPTH {
			return Err(serde::de::Error::custom(format!(
				"proof depth {} exceeds max {}",
				levels.len(),
				MAX_DEPTH
			)));
		}
		levels
			.into_iter()
			.map(|level| {
				if level.len() != 3 {
					return Err(serde::de::Error::custom(format!(
						"expected 3 siblings per level, got {}",
						level.len()
					)));
				}
				let mut siblings = [[0u8; 32]; 3];
				for (i, bytes) in level.into_iter().enumerate() {
					siblings[i] = bytes.try_into().map_err(|v: Vec<u8>| {
						serde::de::Error::custom(format!("expected 32 bytes, got {}", v.len()))
					})?;
				}
				Ok(siblings)
			})
			.collect()
	}
}

/// Fetch a ZK Merkle proof from the chain via RPC at a specific block.
///
/// # Arguments
/// * `quantus_client` - The chain client
/// * `leaf_index` - The index of the leaf to get the proof for
/// * `at_block` - The block hash to fetch the proof at (MUST match the block you're proving
///   against)
///
/// # Returns
/// The Merkle proof if the leaf exists, or an error
///
/// # Important
/// The `at_block` parameter is critical for ZK proof generation. The tree root changes
/// with each block, so the Merkle proof MUST be fetched at the same block whose header
/// you're including in the ZK proof.
#[allow(dead_code)] // Will be used when ZK tree is deployed to production
pub async fn get_zk_merkle_proof(
	quantus_client: &QuantusClient,
	leaf_index: u64,
	at_block: subxt::utils::H256,
) -> crate::error::Result<ZkMerkleProofRpc> {
	let proof_params = rpc_params![leaf_index, at_block];
	let proof: Option<ZkMerkleProofRpc> = quantus_client
		.rpc_client()
		.request("zkTree_getMerkleProof", proof_params)
		.await
		.map_err(|e| {
			crate::error::QuantusError::Generic(format!(
				"RPC error fetching proof at block {:?}: {}",
				at_block, e
			))
		})?;

	proof.ok_or_else(|| {
		crate::error::QuantusError::Generic(format!(
			"Leaf index {} not found in ZK tree at block {:?}",
			leaf_index, at_block
		))
	})
}

/// Compute sorted siblings and position hints from unsorted siblings.
///
/// The chain returns unsorted siblings at each level. This function:
/// 1. Combines current hash with the 3 siblings
/// 2. Sorts all 4 hashes
/// 3. Finds the position (0-3) of the current hash in the sorted order
/// 4. Extracts the 3 sorted siblings (excluding current hash)
/// 5. Computes the parent hash for the next level
///
/// # Arguments
/// * `unsorted_siblings` - Siblings at each level (3 per level), unsorted
/// * `leaf_hash` - The hash of the leaf
///
/// # Returns
/// A tuple of (sorted_siblings, positions) ready for the circuit
pub fn compute_merkle_positions(
	unsorted_siblings: &[[Hash256; 3]],
	leaf_hash: Hash256,
) -> (Vec<[Hash256; 3]>, Vec<u8>) {
	use qp_zk_circuits_common::zk_merkle::hash_node_presorted;

	let mut current_hash = leaf_hash;
	let mut sorted_siblings = Vec::with_capacity(unsorted_siblings.len());
	let mut positions = Vec::with_capacity(unsorted_siblings.len());

	for level_siblings in unsorted_siblings.iter() {
		// Combine current hash with the 3 siblings
		let mut all_four: [Hash256; 4] =
			[current_hash, level_siblings[0], level_siblings[1], level_siblings[2]];

		// Sort to get the order used by hash_node
		all_four.sort();

		// Find position of current_hash in sorted order
		let pos = all_four
			.iter()
			.position(|h| *h == current_hash)
			.expect("current hash must be in the array") as u8;
		positions.push(pos);

		// Extract the 3 siblings in sorted order (excluding current_hash)
		let sorted_sibs: [Hash256; 3] = {
			let mut sibs = [[0u8; 32]; 3];
			let mut sib_idx = 0;
			for (i, h) in all_four.iter().enumerate() {
				if i as u8 != pos {
					sibs[sib_idx] = *h;
					sib_idx += 1;
				}
			}
			sibs
		};
		sorted_siblings.push(sorted_sibs);

		// Compute parent hash for next level using Poseidon
		current_hash = hash_node_presorted(&all_four)
			.expect("merkle node children from chain must be valid field elements");
	}

	(sorted_siblings, positions)
}

/// Parse a hex-encoded secret string into a 32-byte array
pub fn parse_secret_hex(secret_hex: &str) -> Result<[u8; 32], String> {
	let secret_bytes = hex::decode(secret_hex.trim_start_matches("0x"))
		.map_err(|e| format!("Invalid secret hex: {}", e))?;

	if secret_bytes.len() != 32 {
		return Err(format!("Secret must be exactly 32 bytes, got {} bytes", secret_bytes.len()));
	}

	secret_bytes
		.try_into()
		.map_err(|_| "Failed to convert secret to 32-byte array".to_string())
}

/// Read a hex-encoded secret from a file and validate that it is exactly 32 bytes.
fn read_secret_hex_file(path: &str) -> Result<String, String> {
	let secret_hex =
		std::fs::read_to_string(path).map_err(|e| format!("Failed to read secret file: {}", e))?;
	let secret_hex = secret_hex.trim().to_string();
	parse_secret_hex(&secret_hex)?;
	Ok(secret_hex)
}

/// Read a mnemonic phrase from a file (never from argv).
fn read_mnemonic_file(path: &str) -> Result<String, String> {
	let mnemonic = std::fs::read_to_string(path)
		.map_err(|e| format!("Failed to read mnemonic file: {}", e))?;
	let mnemonic = mnemonic.trim().to_string();
	if mnemonic.is_empty() {
		return Err("Mnemonic file is empty".to_string());
	}
	Ok(mnemonic)
}

/// Parse an exit account from either hex or SS58 format
pub fn parse_exit_account(exit_account_str: &str) -> Result<[u8; 32], String> {
	if let Some(hex_str) = exit_account_str.strip_prefix("0x") {
		let bytes = hex::decode(hex_str).map_err(|e| format!("Invalid exit account hex: {}", e))?;

		if bytes.len() != 32 {
			return Err(format!("Exit account must be 32 bytes, got {} bytes", bytes.len()));
		}

		bytes.try_into().map_err(|_| "Failed to convert exit account".to_string())
	} else {
		// Try to parse as SS58
		let account_id = AccountId32::from_ss58check(exit_account_str)
			.map_err(|e| format!("Invalid SS58 address: {}", e))?;

		Ok(account_id.into())
	}
}

/// Quantize a funding amount from 12 decimal places to 2 decimal places
/// Returns an error if the quantized value doesn't fit in u32
pub fn quantize_funding_amount(amount: u128) -> Result<u32, String> {
	wormhole_lib::quantize_amount(amount).map_err(|e| e.message)
}

/// Read and decode a hex-encoded proof file
pub fn read_proof_file(path: &str) -> Result<Vec<u8>, String> {
	let proof_hex =
		std::fs::read_to_string(path).map_err(|e| format!("Failed to read proof file: {}", e))?;

	hex::decode(proof_hex.trim()).map_err(|e| format!("Failed to decode proof hex: {}", e))
}

/// Write a proof to a hex-encoded file
pub fn write_proof_file(path: &str, proof_bytes: &[u8]) -> Result<(), String> {
	let proof_hex = hex::encode(proof_bytes);
	std::fs::write(path, proof_hex).map_err(|e| format!("Failed to write proof file: {}", e))
}

/// Format a balance amount from raw units (12 decimals) to human-readable format
pub fn format_balance(amount: u128) -> String {
	let whole = amount / 1_000_000_000_000;
	let frac = (amount % 1_000_000_000_000) / 10_000_000_000; // 2 decimal places
	format!("{}.{:02} DEV", whole, frac)
}

/// Randomly partition a total amount into n parts.
/// Each part will be at least `min_per_part` and the sum equals `total`.
/// Returns amounts aligned to SCALE_DOWN_FACTOR for clean quantization.
pub fn random_partition(total: u128, n: usize, min_per_part: u128) -> Vec<u128> {
	use rand::Rng;

	if n == 0 {
		return vec![];
	}
	if n == 1 {
		return vec![total];
	}

	// Ensure minimum is achievable
	let min_total = min_per_part * n as u128;
	if total < min_total {
		// Fall back to equal distribution if total is too small
		let per_part = total / n as u128;
		let remainder = total % n as u128;
		let mut parts: Vec<u128> = vec![per_part; n];
		// Add remainder to last part
		parts[n - 1] += remainder;
		return parts;
	}

	// Amount available for random distribution after ensuring minimums
	let distributable = total - min_total;

	// Generate n-1 random cut points in [0, distributable]
	let mut rng = rand::rng();
	let mut cuts: Vec<u128> = (0..n - 1).map(|_| rng.random_range(0..=distributable)).collect();
	cuts.sort();

	// Convert cuts to amounts
	let mut parts = Vec::with_capacity(n);
	let mut prev = 0u128;
	for cut in cuts {
		parts.push(min_per_part + (cut - prev));
		prev = cut;
	}
	parts.push(min_per_part + (distributable - prev));

	// Note: Input 'total' is already in quantized units (e.g., 998 = 9.98 DEV).
	// No further alignment is needed - just ensure the sum equals total.
	let sum: u128 = parts.iter().sum();
	let diff = total as i128 - sum as i128;
	if diff != 0 {
		// Add/subtract difference from a random part
		let idx = rng.random_range(0..n);
		parts[idx] = (parts[idx] as i128 + diff).max(0) as u128;
	}

	parts
}

/// Output assignment for a single proof (supports dual outputs)
#[derive(Debug, Clone)]
pub struct ProofOutputAssignment {
	/// Amount for output 1 (quantized, 2 decimal places)
	pub output_amount_1: u32,
	/// Exit account for output 1
	pub exit_account_1: [u8; 32],
	/// Amount for output 2 (quantized, 0 if unused)
	pub output_amount_2: u32,
	/// Exit account for output 2 (all zeros if unused)
	pub exit_account_2: [u8; 32],
}

/// Compute random output assignments for a set of proofs.
///
/// This takes the input amounts for each proof and randomly distributes the outputs
/// across the target exit accounts. Each proof can have up to 2 outputs.
///
/// # Algorithm:
/// 1. Compute total output amount (sum of inputs after fee deduction)
/// 2. Randomly partition total output across all target addresses
/// 3. Greedily assign outputs to proofs, using dual outputs when necessary
///
/// # Arguments
/// * `input_amounts` - The input amount for each proof (in planck, before fee)
/// * `target_accounts` - The exit accounts to distribute outputs to
/// * `fee_bps` - Fee in basis points
///
/// # Returns
/// A vector of output assignments, one per proof, or an error if quantization fails
pub fn compute_random_output_assignments(
	input_amounts: &[u128],
	target_accounts: &[[u8; 32]],
	fee_bps: u32,
) -> Result<Vec<ProofOutputAssignment>, String> {
	use rand::seq::SliceRandom;

	let num_proofs = input_amounts.len();
	let num_targets = target_accounts.len();

	if num_proofs == 0 || num_targets == 0 {
		return Ok(vec![]);
	}

	// Step 1: Compute output amounts per proof (after fee deduction)
	let mut proof_outputs: Vec<u32> = Vec::with_capacity(input_amounts.len());
	for (i, &input) in input_amounts.iter().enumerate() {
		let input_quantized = quantize_funding_amount(input).map_err(|e| {
			format!("Failed to quantize input amount {} for proof {}: {}", input, i, e)
		})?;
		proof_outputs.push(compute_output_amount(input_quantized, fee_bps));
	}

	let total_output: u64 = proof_outputs.iter().map(|&x| x as u64).sum();

	// Step 2: Randomly partition total output across target accounts
	// Minimum 3 quantized units (0.03 DEV) per target. After fee deduction in the
	// next round: compute_output_amount(3, 10) = 3 * 9990 / 10000 = 2, which is safe.
	// With 2: compute_output_amount(2, 10) = 1, borderline.
	// With 1: compute_output_amount(1, 10) = 0, causes circuit failure.
	let min_per_target = 3u128;
	let target_amounts_u128 = random_partition(total_output as u128, num_targets, min_per_target);
	let target_amounts: Vec<u32> = target_amounts_u128.iter().map(|&x| x as u32).collect();

	// Step 3: Assign outputs to proofs.
	// Each proof can have at most 2 outputs to different targets.
	//
	// Strategy:
	//   Pass 1 - Guarantee every target gets at least one output slot by round-robin
	//            assigning each target as output_1 of successive proofs.
	//   Pass 2 - Fill remaining capacity (output_2 slots and any leftover amounts)
	//            greedily from targets that still have remaining allocation.
	//
	// This ensures every target address appears in at least one proof output,
	// which is critical for the multiround flow where each target is a next-round
	// wormhole address that must receive minted tokens.

	let mut rng = rand::rng();

	// Track remaining needs per target
	let mut target_remaining: Vec<u32> = target_amounts.clone();

	// Pre-allocate assignments with output_1 = full proof output, output_2 = 0
	let mut assignments: Vec<ProofOutputAssignment> = proof_outputs
		.iter()
		.map(|&po| ProofOutputAssignment {
			output_amount_1: po,
			exit_account_1: [0u8; 32],
			output_amount_2: 0,
			exit_account_2: [0u8; 32],
		})
		.collect();

	// Pass 1: Round-robin assign each target to a proof's output_1.
	// If num_targets <= num_proofs, each target gets its own proof.
	// If num_targets > num_proofs, later targets share proofs via output_2.
	let mut shuffled_targets: Vec<usize> = (0..num_targets).collect();
	shuffled_targets.shuffle(&mut rng);

	for (assign_idx, &tidx) in shuffled_targets.iter().enumerate() {
		let proof_idx = assign_idx % num_proofs;
		let assignment = &mut assignments[proof_idx];

		if assignment.exit_account_1 == [0u8; 32] {
			// First target for this proof -> use output_1
			let assign = assignment.output_amount_1.min(target_remaining[tidx]);
			assignment.exit_account_1 = target_accounts[tidx];
			// We'll fix up the exact amounts in pass 2; for now just mark the account
			assignment.output_amount_1 = assign;
			target_remaining[tidx] -= assign;
		} else if assignment.exit_account_2 == [0u8; 32] {
			// Second target for this proof -> use output_2
			let avail = proof_outputs[proof_idx].saturating_sub(assignment.output_amount_1);
			let assign = avail.min(target_remaining[tidx]);
			assignment.exit_account_2 = target_accounts[tidx];
			assignment.output_amount_2 = assign;
			target_remaining[tidx] -= assign;
		}
		// If both slots taken, skip (shouldn't happen when num_targets <= 2*num_proofs)
	}

	// Pass 2: Distribute any remaining target allocations into available proof outputs.
	// Also ensure each proof's output_1 + output_2 == proof_outputs[i].
	for proof_idx in 0..num_proofs {
		let total_proof_output = proof_outputs[proof_idx];
		let current_sum =
			assignments[proof_idx].output_amount_1 + assignments[proof_idx].output_amount_2;
		let mut shortfall = total_proof_output.saturating_sub(current_sum);

		if shortfall > 0 {
			// Add shortfall to output_1 (its account is already set)
			assignments[proof_idx].output_amount_1 += shortfall;
			shortfall = 0;
		}

		// If output_1_account is still [0;32] (shouldn't happen), assign first target as fallback
		if assignments[proof_idx].exit_account_1 == [0u8; 32] && num_targets > 0 {
			assignments[proof_idx].exit_account_1 = target_accounts[0];
		}

		let _ = shortfall; // suppress unused warning
	}

	Ok(assignments)
}

/// Result of checking proof verification events
pub struct VerificationResult {
	pub success: bool,
	pub exit_amount: Option<u128>,
	pub error_message: Option<String>,
}

/// Apply ProofVerified evidence with failure-dominant semantics.
fn apply_proof_verified_to_result(result: &mut VerificationResult, exit_amount: u128) {
	result.exit_amount = Some(exit_amount);
	if result.error_message.is_none() {
		result.success = true;
	}
}

/// Apply ExtrinsicFailed evidence; dispatch failure always clears success.
fn apply_extrinsic_failed_to_result(result: &mut VerificationResult, error_msg: String) {
	result.success = false;
	result.error_message = Some(error_msg);
}

/// Require the submitted extrinsic hash to be present in the included block.
///
/// Missing hash is an explicit error (reorg / wrong block), not a verification failure.
fn require_proof_verification_extrinsic_index(
	our_extrinsic_index: Option<usize>,
) -> crate::error::Result<usize> {
	our_extrinsic_index.ok_or_else(|| {
		crate::error::QuantusError::Generic(
			"Could not find submitted extrinsic in included block".to_string(),
		)
	})
}

/// Finalize SDK event collection: any ExtrinsicFailed dominates ProofVerified.
fn finalize_wormhole_event_collection(
	found_proof_verified: bool,
	dispatch_error_message: Option<String>,
	transfer_events: Vec<wormhole::events::NativeTransferred>,
) -> crate::error::Result<(bool, Vec<wormhole::events::NativeTransferred>)> {
	if let Some(error_msg) = dispatch_error_message {
		return Err(crate::error::QuantusError::Generic(error_msg));
	}
	Ok((found_proof_verified, transfer_events))
}

/// Check for proof verification events in a transaction
/// Returns whether ProofVerified event was found and the exit amount
async fn check_proof_verification_events(
	client: &subxt::OnlineClient<ChainConfig>,
	block_hash: &subxt::utils::H256,
	tx_hash: &subxt::utils::H256,
	verbose: bool,
) -> crate::error::Result<VerificationResult> {
	use crate::chain::quantus_subxt::api::system::events::ExtrinsicFailed;
	use colored::Colorize;

	let block = client.blocks().at(*block_hash).await.map_err(|e| {
		crate::error::QuantusError::NetworkError(format!("Failed to get block: {e:?}"))
	})?;

	let extrinsics = block.extrinsics().await.map_err(|e| {
		crate::error::QuantusError::NetworkError(format!("Failed to get extrinsics: {e:?}"))
	})?;

	// Find our extrinsic index — fail closed if the hash is absent from this block.
	let our_extrinsic_index = extrinsics
		.iter()
		.enumerate()
		.find(|(_, ext)| ext.hash() == *tx_hash)
		.map(|(idx, _)| idx);
	let ext_idx = require_proof_verification_extrinsic_index(our_extrinsic_index)?;

	let events = block.events().await.map_err(|e| {
		crate::error::QuantusError::NetworkError(format!("Failed to fetch events: {e:?}"))
	})?;

	let metadata = client.metadata();

	let mut verification_result =
		VerificationResult { success: false, exit_amount: None, error_message: None };

	if verbose {
		log_print!("");
		log_print!("📋 Transaction Events:");
	}

	for event_result in events.iter() {
		let event = event_result.map_err(|e| {
			crate::error::QuantusError::NetworkError(format!("Failed to decode event: {e:?}"))
		})?;

		// Only process events for our extrinsic
		if let subxt::events::Phase::ApplyExtrinsic(event_ext_idx) = event.phase() {
			if event_ext_idx != ext_idx as u32 {
				continue;
			}

			// Display event in verbose mode
			if verbose {
				log_print!(
					"  📌 {}.{}",
					event.pallet_name().bright_cyan(),
					event.variant_name().bright_yellow()
				);

				// Try to decode and display event details
				if let Ok(typed_event) =
					event.as_root_event::<crate::chain::quantus_subxt::api::Event>()
				{
					log_print!("     📝 {:?}", typed_event);
				}
			}

			// Check for ProofVerified event
			if let Ok(Some(proof_verified)) = event.as_event::<wormhole::events::ProofVerified>() {
				apply_proof_verified_to_result(
					&mut verification_result,
					proof_verified.exit_amount,
				);
			}

			// Check for ExtrinsicFailed event. Dispatch failure dominates any
			// ProofVerified event regardless of event ordering.
			if let Ok(Some(ExtrinsicFailed { dispatch_error, .. })) =
				event.as_event::<ExtrinsicFailed>()
			{
				let error_msg = format_dispatch_error(&dispatch_error, &metadata);
				apply_extrinsic_failed_to_result(&mut verification_result, error_msg);
			}
		}
	}

	if verbose {
		log_print!("");
	}

	Ok(verification_result)
}

/// Format dispatch error for display
fn format_dispatch_error(
	error: &crate::chain::quantus_subxt::api::runtime_types::sp_runtime::DispatchError,
	metadata: &subxt::Metadata,
) -> String {
	use crate::chain::quantus_subxt::api::runtime_types::sp_runtime::DispatchError;

	match error {
		DispatchError::Module(module_error) => {
			let pallet_name = metadata
				.pallet_by_index(module_error.index)
				.map(|p| p.name())
				.unwrap_or("Unknown");
			let error_index = module_error.error[0];

			// Try to decode the error name and docs from metadata
			let error_info = metadata.pallet_by_index(module_error.index).and_then(|p| {
				p.error_variant_by_index(error_index)
					.map(|v| (v.name.clone(), v.docs.join(" ")))
			});

			match error_info {
				Some((name, docs)) if !docs.is_empty() => {
					format!("{}::{} ({})", pallet_name, name, docs)
				},
				Some((name, _)) => format!("{}::{}", pallet_name, name),
				None => format!("{}::Error[{}]", pallet_name, error_index),
			}
		},
		DispatchError::BadOrigin => "BadOrigin".to_string(),
		DispatchError::CannotLookup => "CannotLookup".to_string(),
		DispatchError::Other => "Other".to_string(),
		_ => format!("{:?}", error),
	}
}

#[derive(Subcommand, Debug)]
pub enum WormholeCommands {
	/// Derive the unspendable wormhole address from a secret file
	Address {
		/// File containing the secret (32-byte hex string) used to derive the unspendable account
		#[arg(long)]
		secret_file: String,
	},
	/// Generate a wormhole proof from an existing transfer
	Prove {
		/// File containing the secret (32-byte hex string) used for the transfer
		#[arg(long)]
		secret_file: String,

		/// Funding amount that was transferred
		#[arg(long)]
		amount: u128,

		/// Exit account (where funds will be withdrawn, hex or SS58)
		#[arg(long)]
		exit_account: String,

		/// Block hash to generate proof against (hex)
		#[arg(long)]
		block: String,

		/// Transfer count from the transfer event
		#[arg(long)]
		transfer_count: u64,

		/// ZK trie leaf index from the transfer event (for Merkle proof lookup)
		#[arg(long)]
		leaf_index: u64,

		/// Funding account (sender of transfer, hex or SS58)
		#[arg(long)]
		funding_account: String,

		/// Output file for the proof (default: proof.hex)
		#[arg(short, long, default_value = "proof.hex")]
		output: String,
	},
	/// Aggregate multiple wormhole proofs into a single proof
	Aggregate {
		/// Input proof files (hex-encoded)
		#[arg(short, long, num_args = 1..)]
		proofs: Vec<String>,

		/// Output file for the aggregated proof (default: aggregated_proof.hex)
		#[arg(short, long, default_value = "aggregated_proof.hex")]
		output: String,
	},
	/// Verify an aggregated wormhole proof on-chain
	VerifyAggregated {
		/// Path to the aggregated proof file (hex-encoded)
		#[arg(short, long, default_value = "aggregated_proof.hex")]
		proof: String,
	},
	/// Aggregate private-batch proofs into a public batch (delegated, non-private
	/// aggregation). The aggregator address earns a rebate from the burn portion
	/// of the volume fee when the proof is verified on-chain.
	AggregatePublic {
		/// Input private-batch proof files (hex-encoded, from `wormhole aggregate`)
		#[arg(short, long, num_args = 1..)]
		proofs: Vec<String>,

		/// Aggregator address receiving the fee rebate (hex or SS58)
		#[arg(short, long)]
		aggregator: String,

		/// Output file for the public-batch proof
		#[arg(short, long, default_value = "public_batch_proof.hex")]
		output: String,
	},
	/// Verify a public-batch wormhole proof on-chain
	VerifyPublicBatch {
		/// Path to the public-batch proof file (hex-encoded)
		#[arg(short, long, default_value = "public_batch_proof.hex")]
		proof: String,
	},
	/// Parse and display the contents of a proof file (for debugging)
	ParseProof {
		/// Path to the proof file (hex-encoded)
		#[arg(short, long)]
		proof: String,

		/// Parse as aggregated proof (default: false, parses as leaf proof)
		#[arg(long, conflicts_with = "public_batch")]
		aggregated: bool,

		/// Parse as public-batch proof
		#[arg(long)]
		public_batch: bool,

		/// Verify the proof cryptographically (local verification, not on-chain)
		#[arg(long)]
		verify: bool,
	},
	/// Run a multi-round wormhole test: wallet -> wormhole -> ... -> wallet
	Multiround {
		/// Number of proofs per round (default: 2, max: 8)
		#[arg(short, long, default_value = "2")]
		num_proofs: usize,

		/// Number of rounds (default: 2)
		#[arg(short, long, default_value = "2")]
		rounds: usize,

		/// Total amount in DEV to partition across all proofs (default: 100)
		#[arg(short, long, default_value = "100")]
		amount: f64,

		/// Wallet name to use for funding and final exit
		#[arg(short, long)]
		wallet: String,

		/// Password for the wallet
		#[arg(short, long, hide = true)]
		password: Option<String>,

		/// Read password from file
		#[arg(long)]
		password_file: Option<String>,

		/// Keep proof files after completion
		#[arg(short, long)]
		keep_files: bool,

		/// Output directory for proof files
		#[arg(short, long, default_value = "/tmp/wormhole_multiround")]
		output_dir: String,

		/// Dry run - show what would be done without executing
		#[arg(long)]
		dry_run: bool,

		/// Route each round through a public batch (second aggregation layer).
		/// The wallet address is used as the aggregator and earns the fee rebate.
		#[arg(long)]
		public: bool,
	},
	/// Dissolve a large wormhole deposit into many small outputs for better privacy.
	///
	/// Creates a tree of wormhole transactions: each layer splits outputs into two,
	/// doubling the number of outputs until all are below the target size. This moves
	/// funds from a high-amount bucket (few deposits, low privacy score) into the
	/// low-amount bucket (many miner rewards, high privacy score).
	Dissolve {
		/// Amount in DEV to dissolve
		#[arg(short, long)]
		amount: f64,

		/// Target output size in DEV (stop splitting when all outputs are below this)
		#[arg(short, long, default_value = "1.0")]
		target_size: f64,

		/// Wallet name to use for funding
		#[arg(short, long)]
		wallet: String,

		/// Password for the wallet
		#[arg(short, long, hide = true)]
		password: Option<String>,

		/// Read password from file
		#[arg(long)]
		password_file: Option<String>,

		/// Keep proof files after completion
		#[arg(short, long)]
		keep_files: bool,

		/// Output directory for proof files
		#[arg(short, long, default_value = "/tmp/wormhole_dissolve")]
		output_dir: String,
	},
	/// Fuzz test the leaf verification by attempting invalid proofs
	Fuzz {
		/// Wallet name to use for funding
		#[arg(short, long)]
		wallet: String,

		/// Password for the wallet
		#[arg(short, long, hide = true)]
		password: Option<String>,

		/// Read password from file
		#[arg(long)]
		password_file: Option<String>,

		/// Amount in DEV to use for the test transfer (default: 1.0)
		#[arg(short, long, default_value = "1.0")]
		amount: f64,
	},
	/// Collect miner rewards from a wormhole address.
	///
	/// This command queries Subsquid for pending transfers to your wormhole address,
	/// generates ZK proofs, and submits a withdrawal transaction to claim your rewards.
	/// It mirrors the withdrawal flow used by the miner app.
	CollectRewards {
		/// Wallet name (used for HD derivation of wormhole secret and exit address)
		/// Either --wallet, --mnemonic-file, or --secret-file must be provided.
		#[arg(short, long, required_unless_present_any = ["mnemonic_file", "secret_file"], conflicts_with_all = ["mnemonic_file", "secret_file"])]
		wallet: Option<String>,

		/// File containing a mnemonic phrase for HD derivation (alternative to --wallet).
		/// The phrase is never accepted on argv.
		#[arg(long, required_unless_present_any = ["wallet", "secret_file"], conflicts_with_all = ["wallet", "secret_file"])]
		mnemonic_file: Option<String>,

		/// File containing the direct wormhole secret (32-byte hex string, alternative to --wallet
		/// or --mnemonic-file). Use this with a secret generated by `quantus-node key quantus
		/// --scheme wormhole`.
		#[arg(long, required_unless_present_any = ["wallet", "mnemonic_file"], conflicts_with_all = ["wallet", "mnemonic_file"])]
		secret_file: Option<String>,

		/// Password for the wallet (only used with --wallet)
		#[arg(short, long, hide = true)]
		password: Option<String>,

		/// Read password from file (only used with --wallet)
		#[arg(long)]
		password_file: Option<String>,

		/// Amount in DEV to withdraw (default: withdraw all available)
		#[arg(short, long)]
		amount: Option<f64>,

		/// Destination address for withdrawn funds (required when using --mnemonic-file or
		/// --secret-file)
		#[arg(long)]
		destination: Option<String>,

		/// Subsquid indexer URL for querying transfers
		#[arg(long, default_value = "https://sub2.quantus.com/v1/graphql")]
		subsquid_url: String,

		/// Wormhole address index for HD derivation (default: 0, ignored when using --secret-file)
		#[arg(long, default_value = "0")]
		wormhole_index: usize,

		/// Dry run - show available transfers without withdrawing
		#[arg(long)]
		dry_run: bool,

		/// Specific block number to use for proofs (default: use latest block)
		#[arg(long)]
		at_block: Option<u32>,
	},
	/// Check if nullifiers have been spent (consumed by a withdrawal).
	///
	/// Given a secret (or wallet) and transfer count(s), computes the nullifier(s) and checks
	/// if they exist in Subsquid (meaning the corresponding transfer has been withdrawn).
	CheckNullifier {
		/// File containing the secret (32-byte hex string) for the wormhole secret.
		/// Either --secret-file or --wallet must be provided.
		#[arg(long, required_unless_present = "wallet")]
		secret_file: Option<String>,

		/// Wallet name (used for HD derivation of wormhole secret).
		/// Either --secret-file or --wallet must be provided.
		#[arg(short, long, required_unless_present = "secret_file")]
		wallet: Option<String>,

		/// Password for the wallet (only used with --wallet)
		#[arg(short, long, hide = true)]
		password: Option<String>,

		/// Read password from file (only used with --wallet)
		#[arg(long)]
		password_file: Option<String>,

		/// Wormhole address index for HD derivation (default: 0, only used with --wallet)
		#[arg(long, default_value = "0")]
		wormhole_index: usize,

		/// Transfer count(s) to check. Can be a single number or a range (e.g., "0-10")
		#[arg(long)]
		transfer_counts: String,

		/// Subsquid indexer URL for querying nullifiers
		#[arg(long, default_value = "https://sub2.quantus.com/v1/graphql")]
		subsquid_url: String,
	},
}

/// Wait mode for wormhole steps that must observe inclusion (events / next-round inputs).
/// Honors `--finalized-tx`; otherwise waits for best-block inclusion only.
fn wormhole_inclusion_mode(execution_mode: ExecutionMode) -> ExecutionMode {
	ExecutionMode { wait_for_transaction: true, ..execution_mode }
}

fn wormhole_inclusion_stage(execution_mode: ExecutionMode) -> TransactionStage {
	wormhole_inclusion_mode(execution_mode).transaction_stage()
}

fn included_at_for_stage(stage: TransactionStage) -> IncludedAt {
	match stage {
		TransactionStage::Finalized => IncludedAt::Finalized,
		TransactionStage::Included | TransactionStage::Submitted => IncludedAt::Best,
	}
}

/// Tip block used for pre-submit storage reads and for ZK Merkle proof generation.
///
/// Must match the wait mode: if funding/verify only waited for best-block inclusion,
/// freshly written leaves are not yet in the finalized tree.
async fn wormhole_tip_block(
	quantus_client: &QuantusClient,
	execution_mode: ExecutionMode,
) -> crate::error::Result<Block<ChainConfig, OnlineClient<ChainConfig>>> {
	if execution_mode.finalized {
		at_finalized_block(quantus_client).await
	} else {
		at_best_block(quantus_client).await
	}
}

pub async fn handle_wormhole_command(
	command: WormholeCommands,
	node_url: &str,
	execution_mode: ExecutionMode,
) -> crate::error::Result<()> {
	match command {
		WormholeCommands::Address { secret_file } => show_wormhole_address(secret_file),
		WormholeCommands::Prove {
			secret_file,
			amount,
			exit_account,
			block,
			transfer_count,
			leaf_index,
			funding_account,
			output,
		} => {
			log_print!("Generating proof from existing transfer...");

			// Connect to node
			let quantus_client = QuantusClient::new(node_url).await.map_err(|e| {
				crate::error::QuantusError::Generic(format!("Failed to connect: {}", e))
			})?;

			// Parse exit account
			let exit_account_bytes =
				parse_exit_account(&exit_account).map_err(crate::error::QuantusError::Generic)?;

			// Quantize amount and compute output (single output, no change)
			let input_amount_quantized =
				quantize_funding_amount(amount).map_err(crate::error::QuantusError::Generic)?;
			let output_amount = compute_output_amount(input_amount_quantized, VOLUME_FEE_BPS);

			let output_assignment = ProofOutputAssignment {
				output_amount_1: output_amount,
				exit_account_1: exit_account_bytes,
				output_amount_2: 0,
				exit_account_2: [0u8; 32],
			};

			let secret =
				read_secret_hex_file(&secret_file).map_err(crate::error::QuantusError::Generic)?;

			let prove_start = std::time::Instant::now();
			generate_proof(
				&secret,
				amount,
				&output_assignment,
				&block,
				transfer_count,
				&funding_account,
				leaf_index,
				&output,
				&quantus_client,
			)
			.await?;
			let prove_elapsed = prove_start.elapsed();
			log_print!("Proof generation: {:.2}s", prove_elapsed.as_secs_f64());
			Ok(())
		},
		WormholeCommands::Aggregate { proofs, output } => aggregate_proofs(proofs, output).await,
		WormholeCommands::VerifyAggregated { proof } =>
			verify_private_batch(proof, node_url, execution_mode).await,
		WormholeCommands::AggregatePublic { proofs, aggregator, output } =>
			aggregate_public_batch(proofs, aggregator, output).await,
		WormholeCommands::VerifyPublicBatch { proof } =>
			verify_public_batch(proof, node_url, execution_mode).await,
		WormholeCommands::ParseProof { proof, aggregated, public_batch, verify } =>
			parse_proof_file(proof, aggregated, public_batch, verify).await,
		WormholeCommands::Multiround {
			num_proofs,
			rounds,
			amount,
			wallet,
			password,
			password_file,
			keep_files,
			output_dir,
			dry_run,
			public,
		} => {
			// Convert DEV to planck and align to SCALE_DOWN_FACTOR for clean quantization
			let amount_planck = (amount * 1_000_000_000_000.0) as u128;
			let amount_aligned = (amount_planck / SCALE_DOWN_FACTOR) * SCALE_DOWN_FACTOR;
			run_multiround(
				num_proofs,
				rounds,
				amount_aligned,
				wallet,
				password,
				password_file,
				keep_files,
				output_dir,
				dry_run,
				public,
				node_url,
				execution_mode,
			)
			.await
		},
		WormholeCommands::Dissolve {
			amount,
			target_size,
			wallet,
			password,
			password_file,
			keep_files,
			output_dir,
		} => {
			let amount_planck = (amount * 1_000_000_000_000.0) as u128;
			let amount_aligned = (amount_planck / SCALE_DOWN_FACTOR) * SCALE_DOWN_FACTOR;
			let target_planck = (target_size * 1_000_000_000_000.0) as u128;
			let target_aligned = (target_planck / SCALE_DOWN_FACTOR) * SCALE_DOWN_FACTOR;
			run_dissolve(
				amount_aligned,
				target_aligned,
				wallet,
				password,
				password_file,
				keep_files,
				output_dir,
				node_url,
				execution_mode,
			)
			.await
		},
		WormholeCommands::Fuzz { wallet: _, password: _, password_file: _, amount: _ } => {
			// TODO: Re-enable fuzz tests once ZK tree is deployed to a test chain.
			// The fuzz tests need to be rewritten to use zkTree_getMerkleProof RPC
			// instead of the old state_getReadProof storage proofs.
			// See run_fuzz_test() and try_generate_fuzz_proof() below for the old implementation.
			Err(crate::error::QuantusError::Generic(
				"Fuzz testing is temporarily disabled during the migration to ZK tree proofs. \
				 The fuzz tests require a chain with pallet-zk-tree deployed and the \
				 zkTree_getMerkleProof RPC endpoint available."
					.to_string(),
			))
		},
		WormholeCommands::CollectRewards {
			wallet,
			mnemonic_file,
			secret_file,
			password,
			password_file,
			amount,
			destination,
			subsquid_url,
			wormhole_index,
			dry_run,
			at_block,
		} =>
			run_collect_rewards(
				wallet,
				mnemonic_file,
				secret_file,
				password,
				password_file,
				amount,
				destination,
				subsquid_url,
				wormhole_index,
				dry_run,
				node_url,
				at_block,
			)
			.await,
		WormholeCommands::CheckNullifier {
			secret_file,
			wallet,
			password,
			password_file,
			wormhole_index,
			transfer_counts,
			subsquid_url,
		} =>
			run_check_nullifier(
				secret_file,
				wallet,
				password,
				password_file,
				wormhole_index,
				transfer_counts,
				subsquid_url,
			)
			.await,
	}
}

// NOTE: TransferProofKey and TransferProofData type aliases were removed during
// the migration to ZK tree. The new ZK leaf structure is:
// (to: AccountId32, transfer_count: u64, asset_id: u32, amount: u32)
// No longer includes `from` (funding_account).

/// Derive and display the unspendable wormhole address from a secret.
/// Users can then send funds to this address using `quantus send`.
fn show_wormhole_address(secret_file: String) -> crate::error::Result<()> {
	use colored::Colorize;

	let secret_hex =
		read_secret_hex_file(&secret_file).map_err(crate::error::QuantusError::Generic)?;
	let secret_array =
		parse_secret_hex(&secret_hex).map_err(crate::error::QuantusError::Generic)?;
	let secret: BytesDigest = secret_array.try_into().map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to convert secret: {:?}", e))
	})?;

	let unspendable_account =
		qp_wormhole_circuit::unspendable_account::UnspendableAccount::from_secret(secret)
			.account_id;
	let unspendable_account_bytes_digest =
		qp_zk_circuits_common::utils::digest_to_bytes(unspendable_account);
	let unspendable_account_bytes: [u8; 32] = unspendable_account_bytes_digest
		.as_ref()
		.try_into()
		.expect("BytesDigest is always 32 bytes");

	let account_id = sp_core::crypto::AccountId32::new(unspendable_account_bytes);
	let ss58_address =
		account_id.to_ss58check_with_version(sp_core::crypto::Ss58AddressFormat::custom(189));

	log_print!("{}", "Wormhole Address".bright_cyan());
	log_print!("  SS58:  {}", ss58_address.bright_green());
	log_print!("  Hex:   0x{}", hex::encode(unspendable_account_bytes));
	log_print!("");
	log_print!("To fund this address:");
	log_print!("  quantus send --from <wallet> --to {} --amount <amount>", ss58_address);

	Ok(())
}

/// Fetch the latest finalized block as a fully materialised subxt `Block`.
///
/// Uses [`crate::error::Result`] (not `anyhow`) so it composes with the rest
/// of the SDK surface. Network/decoding failures are wrapped in
/// [`crate::error::QuantusError::NetworkError`].
pub async fn at_finalized_block(
	quantus_client: &QuantusClient,
) -> crate::error::Result<Block<ChainConfig, OnlineClient<ChainConfig>>> {
	let finalized_block: subxt::utils::H256 = quantus_client
		.rpc_client()
		.request("chain_getFinalizedHead", rpc_params![])
		.await
		.map_err(|e| {
			crate::error::QuantusError::NetworkError(format!(
				"Failed to fetch finalized block hash: {e:?}"
			))
		})?;
	let block = quantus_client.client().blocks().at(finalized_block).await.map_err(|e| {
		crate::error::QuantusError::NetworkError(format!(
			"Failed to fetch finalized block {finalized_block:?}: {e:?}"
		))
	})?;
	Ok(block)
}

/// Fetch the latest (best) block as a fully materialised subxt `Block`.
///
/// Uses [`crate::error::Result`] (not `anyhow`) so it composes with the rest
/// of the SDK surface. Network/decoding failures are wrapped in
/// [`crate::error::QuantusError::NetworkError`].
pub async fn at_best_block(
	quantus_client: &QuantusClient,
) -> crate::error::Result<Block<ChainConfig, OnlineClient<ChainConfig>>> {
	let best_block = quantus_client.get_latest_block().await?;
	let block = quantus_client.client().blocks().at(best_block).await.map_err(|e| {
		crate::error::QuantusError::NetworkError(format!(
			"Failed to fetch best block {best_block:?}: {e:?}"
		))
	})?;
	Ok(block)
}

/// Load leaf-circuit common data for deserializing leaf proofs from `bins_dir`.
fn load_leaf_common_data(
	bins_dir: &std::path::Path,
) -> crate::error::Result<plonky2::plonk::circuit_data::CommonCircuitData<F, D>> {
	use qp_wormhole_aggregator::common::utils::load_canonical_leaf_verifier_data;

	let common_bytes = std::fs::read(bins_dir.join("common.bin")).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to read common.bin: {}", e))
	})?;
	let verifier_bytes = std::fs::read(bins_dir.join("verifier.bin")).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to read verifier.bin: {}", e))
	})?;
	let leaf = load_canonical_leaf_verifier_data(&common_bytes, &verifier_bytes).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to load leaf circuit data: {}", e))
	})?;
	Ok(leaf.common)
}

pub async fn aggregate_proofs(
	proof_files: Vec<String>,
	output_file: String,
) -> crate::error::Result<()> {
	use qp_wormhole_aggregator::private_batch::prover::PrivateBatchProver;

	log_print!("Aggregating {} proofs...", proof_files.len());

	let bins_dir = crate::bins::ensure_bins_dir()?;
	let agg_config = CircuitBinsConfig::load(&bins_dir).map_err(|e| {
		crate::error::QuantusError::Generic(format!(
			"Failed to load circuit bins config from {:?}: {}",
			bins_dir, e
		))
	})?;

	// Validate number of proofs before doing expensive work
	if proof_files.is_empty() {
		return Err(crate::error::QuantusError::Generic(
			"At least one leaf proof is required".to_string(),
		));
	}
	if proof_files.len() > agg_config.num_leaf_proofs {
		return Err(crate::error::QuantusError::Generic(format!(
			"Too many proofs: {} provided, max {} supported by circuit",
			proof_files.len(),
			agg_config.num_leaf_proofs
		)));
	}

	let num_padding_proofs = agg_config.num_leaf_proofs - proof_files.len();
	log_print!("  Loading private-batch prover (will pad with {} dummies)...", num_padding_proofs);
	log_verbose!("Aggregation config: num_leaf_proofs={}", agg_config.num_leaf_proofs);

	let common_data = load_leaf_common_data(&bins_dir)?;

	let mut proofs = Vec::with_capacity(proof_files.len());
	for (idx, proof_file) in proof_files.iter().enumerate() {
		log_verbose!("Loading proof {}/{}: {}", idx + 1, proof_files.len(), proof_file);

		let proof_bytes = read_proof_file(proof_file).map_err(|e| {
			crate::error::QuantusError::Generic(format!("Failed to load {}: {}", proof_file, e))
		})?;

		let proof = ProofWithPublicInputs::<F, C, D>::from_bytes(proof_bytes, &common_data)
			.map_err(|e| {
				crate::error::QuantusError::Generic(format!(
					"Failed to deserialize proof from {}: {}",
					proof_file, e
				))
			})?;
		proofs.push(proof);
	}

	let prover = PrivateBatchProver::new_from_binaries_dir(&bins_dir).map_err(|e| {
		crate::error::QuantusError::Generic(format!(
			"Failed to load private-batch prover from pre-built bins: {}",
			e
		))
	})?;

	log_print!("  Running aggregation...");
	let agg_start = std::time::Instant::now();
	let aggregated_proof = prover
		.aggregate(proofs)
		.map_err(|e| crate::error::QuantusError::Generic(format!("Aggregation failed: {}", e)))?;
	let agg_elapsed = agg_start.elapsed();
	log_print!("  Aggregation: {:.2}s", agg_elapsed.as_secs_f64());

	// Parse and display aggregated public inputs
	let aggregated_public_inputs =
		PrivateBatchPublicInputs::try_from_felts(aggregated_proof.public_inputs.as_slice())
			.map_err(|e| {
				crate::error::QuantusError::Generic(format!(
					"Failed to parse aggregated public inputs: {}",
					e
				))
			})?;

	log_verbose!("Aggregated public inputs: {:#?}", aggregated_public_inputs);

	// Log exit accounts and amounts that will be minted
	log_print!("  Exit accounts in aggregated proof:");
	for (idx, account_data) in aggregated_public_inputs.account_data.iter().enumerate() {
		let exit_bytes: &[u8] = account_data.exit_account.as_ref();
		let is_dummy = exit_bytes.iter().all(|&b| b == 0) || account_data.summed_output_amount == 0;
		if is_dummy {
			log_verbose!("    [{}] DUMMY (skipped)", idx);
		} else {
			// De-quantize to show actual amount that will be minted
			let dequantized_amount =
				(account_data.summed_output_amount as u128) * SCALE_DOWN_FACTOR;
			let ss58_address = slice_to_quantus_ss58(exit_bytes)?;
			log_print!(
				"    [{}] {} -> {} quantized ({} planck = {})",
				idx,
				ss58_address,
				account_data.summed_output_amount,
				dequantized_amount,
				format_balance(dequantized_amount)
			);
		}
	}

	// Verify via the verifier crate (byte round-trip keeps proof types aligned).
	log_verbose!("Verifying aggregated proof locally...");
	let proof_bytes = aggregated_proof.to_bytes();
	let verifier = crate::batch_verifier::load_private_batch_verifier(&bins_dir).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to load private-batch verifier: {}", e))
	})?;
	let verify_proof = qp_wormhole_verifier::ProofWithPublicInputs::from_bytes(
		proof_bytes.clone(),
		&verifier.circuit_data.common,
	)
	.map_err(|e| {
		crate::error::QuantusError::Generic(format!(
			"Failed to deserialize aggregated proof for verification: {}",
			e
		))
	})?;
	verifier.verify(verify_proof).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Aggregated proof verification failed: {}", e))
	})?;

	write_proof_file(&output_file, &proof_bytes).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to write proof: {}", e))
	})?;

	log_success!("Aggregation complete!");
	log_success!("Output: {}", output_file);
	log_print!(
		"Aggregated {} proofs into 1 proof with {} exit accounts",
		proof_files.len(),
		aggregated_public_inputs.account_data.len()
	);

	Ok(())
}

/// Aggregate private-batch proofs into a public batch with the given aggregator address.
///
/// Partial batches are padded with dummy private-batch proofs by the prover, so any
/// number of proofs from 1 up to the circuit's `num_private_batch_proofs` is accepted.
pub async fn aggregate_public_batch(
	proof_files: Vec<String>,
	aggregator_address_str: String,
	output_file: String,
) -> crate::error::Result<()> {
	use plonky2::field::types::PrimeField64;
	use qp_wormhole_aggregator::aggregator::PublicBatchAggregator;
	use qp_wormhole_inputs::PublicBatchPublicInputs;

	log_print!("Aggregating {} private-batch proofs into a public batch...", proof_files.len());

	let aggregator_bytes = parse_exit_account(&aggregator_address_str).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Invalid aggregator address: {}", e))
	})?;
	let aggregator_address = BytesDigest::try_from(aggregator_bytes).map_err(|e| {
		crate::error::QuantusError::Generic(format!(
			"Aggregator address is not representable as field elements (must be a hash-derived account): {}",
			e
		))
	})?;
	log_print!(
		"  Aggregator (fee rebate recipient): {}",
		slice_to_quantus_ss58(&aggregator_bytes)?
	);

	let bins_dir = crate::bins::ensure_bins_dir()?;
	let agg_config = CircuitBinsConfig::load(&bins_dir).map_err(|e| {
		crate::error::QuantusError::Generic(format!(
			"Failed to load circuit bins config from {:?}: {}",
			bins_dir, e
		))
	})?;
	let num_private_batch_proofs = agg_config.num_private_batch_proofs.ok_or_else(|| {
		crate::error::QuantusError::Generic(
			"Circuit binaries were generated without public-batch support; \
				 delete the generated-bins directory to regenerate them"
				.to_string(),
		)
	})?;

	if proof_files.is_empty() {
		return Err(crate::error::QuantusError::Generic(
			"At least one private-batch proof is required".to_string(),
		));
	}
	if proof_files.len() > num_private_batch_proofs {
		return Err(crate::error::QuantusError::Generic(format!(
			"Too many proofs: {} provided, max {} supported by circuit",
			proof_files.len(),
			num_private_batch_proofs
		)));
	}

	let mut aggregator =
		PublicBatchAggregator::new(&bins_dir, aggregator_address).map_err(|e| {
			crate::error::QuantusError::Generic(format!(
				"Failed to load public-batch aggregator from pre-built bins: {}",
				e
			))
		})?;

	// Inner proofs for the public-batch aggregator are private-batch proofs.
	let common_data = aggregator.private_batch_common().clone();

	let mut batch_key = None;
	for (idx, proof_file) in proof_files.iter().enumerate() {
		log_verbose!("Loading proof {}/{}: {}", idx + 1, proof_files.len(), proof_file);
		let proof_bytes = read_hex_proof_file_to_bytes(proof_file)?;
		let proof = ProofWithPublicInputs::<F, C, D>::from_bytes(proof_bytes, &common_data)
			.map_err(|e| {
				crate::error::QuantusError::Generic(format!(
					"Failed to deserialize private-batch proof from {}: {}",
					proof_file, e
				))
			})?;
		let key = aggregator.push_proof(proof).map_err(|e| {
			crate::error::QuantusError::Generic(format!("Failed to add proof: {}", e))
		})?;
		match &batch_key {
			None => batch_key = Some(key),
			Some(existing) if existing != &key => {
				return Err(crate::error::QuantusError::Generic(format!(
					"Proof {} is incompatible with earlier proofs (block_hash/asset_id/fee mismatch)",
					proof_file
				)));
			},
			Some(_) => {},
		}
	}

	let batch_key = batch_key.ok_or_else(|| {
		crate::error::QuantusError::Generic("No private-batch proofs were admitted".to_string())
	})?;

	let num_dummies = num_private_batch_proofs - proof_files.len();
	if num_dummies > 0 {
		log_print!("  Padding with {} dummy private-batch proof(s)...", num_dummies);
	}

	log_print!("  Running public-batch aggregation...");
	let agg_start = std::time::Instant::now();
	let public_batch_proof = aggregator.aggregate(&batch_key).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Public-batch aggregation failed: {}", e))
	})?;
	log_print!("  Aggregation: {:.2}s", agg_start.elapsed().as_secs_f64());

	// Parse and display the public-batch public inputs
	let pi_u64s: Vec<u64> =
		public_batch_proof.public_inputs.iter().map(|f| f.to_canonical_u64()).collect();
	let public_inputs = PublicBatchPublicInputs::try_from_u64_slice(
		&pi_u64s,
		num_private_batch_proofs,
		agg_config.num_leaf_proofs,
	)
	.map_err(|e| {
		crate::error::QuantusError::Generic(format!(
			"Failed to parse public-batch public inputs: {}",
			e
		))
	})?;

	log_verbose!("Public-batch public inputs: {:#?}", public_inputs);
	log_print!("  Exit accounts in public batch:");
	for (idx, account_data) in public_inputs.account_data.iter().enumerate() {
		let exit_bytes: &[u8] = account_data.exit_account.as_ref();
		let is_dummy = exit_bytes.iter().all(|&b| b == 0) || account_data.summed_output_amount == 0;
		if is_dummy {
			log_verbose!("    [{}] DUMMY (skipped)", idx);
		} else {
			let dequantized_amount =
				(account_data.summed_output_amount as u128) * SCALE_DOWN_FACTOR;
			log_print!(
				"    [{}] {} -> {}",
				idx,
				slice_to_quantus_ss58(exit_bytes)?,
				format_balance(dequantized_amount)
			);
		}
	}

	log_verbose!("Verifying public-batch proof locally...");
	aggregator.verify(public_batch_proof.clone()).map_err(|e| {
		crate::error::QuantusError::Generic(format!(
			"Public-batch proof verification failed: {}",
			e
		))
	})?;

	write_proof_file(&output_file, &public_batch_proof.to_bytes()).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to write proof: {}", e))
	})?;

	log_success!("Public-batch aggregation complete!");
	log_success!("Output: {}", output_file);
	Ok(())
}

/// Where in the chain a submitted extrinsic has been observed.
///
/// `Best` means it landed in the current best block (not yet finalised);
/// `Finalized` means it's in a block past the finality gadget. Returned by
/// [`submit_unsigned_verify_private_batch`] alongside the block + tx hash.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IncludedAt {
	/// Inclusion in a best (non-finalized) block. Kept for SDK callers.
	#[allow(dead_code)]
	Best,
	Finalized,
}

impl IncludedAt {
	/// Short human-readable label. Equivalent to [`std::fmt::Display`] output.
	pub fn label(self) -> &'static str {
		match self {
			IncludedAt::Best => "best block",
			IncludedAt::Finalized => "finalized block",
		}
	}
}

impl std::fmt::Display for IncludedAt {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.write_str(self.label())
	}
}

fn read_hex_proof_file_to_bytes(proof_file: &str) -> crate::error::Result<Vec<u8>> {
	let proof_hex = std::fs::read_to_string(proof_file).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to read proof file: {}", e))
	})?;

	let proof_bytes = hex::decode(proof_hex.trim())
		.map_err(|e| crate::error::QuantusError::Generic(format!("Failed to decode hex: {}", e)))?;

	Ok(proof_bytes)
}

/// Submit unsigned `verify_private_batch` and wait until best-block inclusion.
///
/// Use [`submit_unsigned_verify_private_batch_until`] with
/// [`TransactionStage::Finalized`] when finalization is required.
#[allow(dead_code)] // SDK re-export; CLI uses the `_until` variant.
pub async fn submit_unsigned_verify_private_batch(
	quantus_client: &QuantusClient,
	proof_bytes: Vec<u8>,
) -> crate::error::Result<(IncludedAt, subxt::utils::H256, subxt::utils::H256)> {
	submit_unsigned_verify_private_batch_until(
		quantus_client,
		proof_bytes,
		TransactionStage::Included,
	)
	.await
}

/// Submit unsigned `verify_private_batch` and wait until `target_stage`.
///
/// `Submitted` is treated as [`TransactionStage::Included`] because callers need
/// the inclusion block to inspect events.
pub async fn submit_unsigned_verify_private_batch_until(
	quantus_client: &QuantusClient,
	proof_bytes: Vec<u8>,
	target_stage: TransactionStage,
) -> crate::error::Result<(IncludedAt, subxt::utils::H256, subxt::utils::H256)> {
	let stage = match target_stage {
		TransactionStage::Finalized => TransactionStage::Finalized,
		TransactionStage::Included | TransactionStage::Submitted => TransactionStage::Included,
	};
	let verify_tx = quantus_node::api::tx().wormhole().verify_private_batch(proof_bytes);

	let unsigned_tx = quantus_client.client().tx().create_unsigned(&verify_tx).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to create unsigned tx: {}", e))
	})?;

	let mut tx_progress = unsigned_tx
		.submit_and_watch()
		.await
		.map_err(|e| crate::error::QuantusError::Generic(format!("Failed to submit tx: {}", e)))?;

	let tx_hash = tx_progress.extrinsic_hash();
	let block_hash = crate::cli::common::wait_tx_inclusion(
		&mut tx_progress,
		quantus_client.client(),
		&tx_hash,
		stage,
	)
	.await?;
	Ok((included_at_for_stage(stage), block_hash, tx_hash))
}

/// Collect wormhole events for our extrinsic (by tx_hash) in a given block.
/// Returns (found_proof_verified, native_transfers).
async fn collect_wormhole_events_for_extrinsic(
	quantus_client: &QuantusClient,
	block_hash: subxt::utils::H256,
	tx_hash: subxt::utils::H256,
) -> crate::error::Result<(bool, Vec<wormhole::events::NativeTransferred>)> {
	use crate::chain::quantus_subxt::api::system::events::ExtrinsicFailed;

	let block =
		quantus_client.client().blocks().at(block_hash).await.map_err(|e| {
			crate::error::QuantusError::Generic(format!("Failed to get block: {}", e))
		})?;

	let events = block
		.events()
		.await
		.map_err(|e| crate::error::QuantusError::Generic(format!("Failed to get events: {}", e)))?;

	let extrinsics = block.extrinsics().await.map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to get extrinsics: {}", e))
	})?;

	let our_ext_idx = extrinsics
		.iter()
		.enumerate()
		.find(|(_, ext)| ext.hash() == tx_hash)
		.map(|(idx, _)| idx as u32)
		.ok_or_else(|| {
			crate::error::QuantusError::Generic(
				"Could not find submitted extrinsic in included block".to_string(),
			)
		})?;

	let mut transfer_events = Vec::new();
	let mut found_proof_verified = false;
	let mut dispatch_error_message = None;

	log_verbose!("  Events for our extrinsic (idx={}):", our_ext_idx);

	for event_result in events.iter() {
		let event = event_result.map_err(|e| {
			crate::error::QuantusError::Generic(format!("Failed to decode event: {}", e))
		})?;

		if let subxt::events::Phase::ApplyExtrinsic(ext_idx) = event.phase() {
			if ext_idx == our_ext_idx {
				log_print!("    Event: {}::{}", event.pallet_name(), event.variant_name());

				// Decode ExtrinsicFailed to get the specific error
				if let Ok(Some(ExtrinsicFailed { dispatch_error, .. })) =
					event.as_event::<ExtrinsicFailed>()
				{
					let metadata = quantus_client.client().metadata();
					let error_msg = format_dispatch_error(&dispatch_error, &metadata);
					log_print!("    DispatchError: {}", error_msg);
					dispatch_error_message = Some(error_msg);
				}

				if let Ok(Some(_)) = event.as_event::<wormhole::events::ProofVerified>() {
					found_proof_verified = true;
				}

				if let Ok(Some(transfer)) = event.as_event::<wormhole::events::NativeTransferred>()
				{
					transfer_events.push(transfer);
				}
			}
		}
	}

	finalize_wormhole_event_collection(
		found_proof_verified,
		dispatch_error_message,
		transfer_events,
	)
}

async fn verify_private_batch(
	proof_file: String,
	node_url: &str,
	execution_mode: ExecutionMode,
) -> crate::error::Result<()> {
	log_print!("Verifying aggregated wormhole proof on-chain...");

	let proof_bytes = read_hex_proof_file_to_bytes(&proof_file)?;
	log_verbose!("Aggregated proof size: {} bytes", proof_bytes.len());

	// Connect to node
	let quantus_client = QuantusClient::new(node_url)
		.await
		.map_err(|e| crate::error::QuantusError::Generic(format!("Failed to connect: {}", e)))?;
	log_verbose!("Connected to node");

	log_verbose!("Submitting unsigned aggregated verification transaction...");

	let (included_at, block_hash, tx_hash) = submit_unsigned_verify_private_batch_until(
		&quantus_client,
		proof_bytes,
		wormhole_inclusion_stage(execution_mode),
	)
	.await?;

	// One unified check (no best/finalized copy-paste)
	let result = check_proof_verification_events(
		quantus_client.client(),
		&block_hash,
		&tx_hash,
		crate::log::is_verbose(),
	)
	.await?;

	if result.success {
		log_success!("Aggregated proof verified successfully on-chain!");
		if let Some(amount) = result.exit_amount {
			log_success!("Total exit amount: {}", format_balance(amount));
		}

		log_print!("  Block: 0x{}", hex::encode(block_hash.0));
		log_print!("  Extrinsic: 0x{}", hex::encode(tx_hash.0));
		log_verbose!("Included in {}: {:?}", included_at.label(), block_hash);
		return Ok(());
	}

	let error_msg = result.error_message.unwrap_or_else(|| {
		"Aggregated proof verification failed - no ProofVerified event found".to_string()
	});
	log_error!("❌ {}", error_msg);
	Err(crate::error::QuantusError::Generic(error_msg))
}

/// Submit unsigned `verify_public_batch` and wait until best-block inclusion.
///
/// Use [`submit_unsigned_verify_public_batch_until`] with
/// [`TransactionStage::Finalized`] when finalization is required.
#[allow(dead_code)] // SDK re-export; CLI uses the `_until` variant.
pub async fn submit_unsigned_verify_public_batch(
	quantus_client: &QuantusClient,
	proof_bytes: Vec<u8>,
) -> crate::error::Result<(IncludedAt, subxt::utils::H256, subxt::utils::H256)> {
	submit_unsigned_verify_public_batch_until(
		quantus_client,
		proof_bytes,
		TransactionStage::Included,
	)
	.await
}

/// Submit unsigned `verify_public_batch` and wait until `target_stage`.
///
/// `Submitted` is treated as [`TransactionStage::Included`] because callers need
/// the inclusion block to inspect events.
pub async fn submit_unsigned_verify_public_batch_until(
	quantus_client: &QuantusClient,
	proof_bytes: Vec<u8>,
	target_stage: TransactionStage,
) -> crate::error::Result<(IncludedAt, subxt::utils::H256, subxt::utils::H256)> {
	let stage = match target_stage {
		TransactionStage::Finalized => TransactionStage::Finalized,
		TransactionStage::Included | TransactionStage::Submitted => TransactionStage::Included,
	};
	let verify_tx = quantus_node::api::tx().wormhole().verify_public_batch(proof_bytes);

	let unsigned_tx = quantus_client.client().tx().create_unsigned(&verify_tx).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to create unsigned tx: {}", e))
	})?;

	let mut tx_progress = unsigned_tx
		.submit_and_watch()
		.await
		.map_err(|e| crate::error::QuantusError::Generic(format!("Failed to submit tx: {}", e)))?;

	let tx_hash = tx_progress.extrinsic_hash();
	let block_hash = crate::cli::common::wait_tx_inclusion(
		&mut tx_progress,
		quantus_client.client(),
		&tx_hash,
		stage,
	)
	.await?;
	Ok((included_at_for_stage(stage), block_hash, tx_hash))
}

async fn verify_public_batch(
	proof_file: String,
	node_url: &str,
	execution_mode: ExecutionMode,
) -> crate::error::Result<()> {
	log_print!("Verifying public-batch wormhole proof on-chain...");

	let proof_bytes = read_hex_proof_file_to_bytes(&proof_file)?;
	log_verbose!("Public-batch proof size: {} bytes", proof_bytes.len());

	let quantus_client = QuantusClient::new(node_url)
		.await
		.map_err(|e| crate::error::QuantusError::Generic(format!("Failed to connect: {}", e)))?;
	log_verbose!("Connected to node");

	log_verbose!("Submitting unsigned public-batch verification transaction...");

	let (included_at, block_hash, tx_hash) = submit_unsigned_verify_public_batch_until(
		&quantus_client,
		proof_bytes,
		wormhole_inclusion_stage(execution_mode),
	)
	.await?;

	let result = check_proof_verification_events(
		quantus_client.client(),
		&block_hash,
		&tx_hash,
		crate::log::is_verbose(),
	)
	.await?;

	if result.success {
		log_success!("Public-batch proof verified successfully on-chain!");
		if let Some(amount) = result.exit_amount {
			log_success!("Total exit amount: {}", format_balance(amount));
		}

		log_print!("  Block: 0x{}", hex::encode(block_hash.0));
		log_print!("  Extrinsic: 0x{}", hex::encode(tx_hash.0));
		log_verbose!("Included in {}: {:?}", included_at.label(), block_hash);
		return Ok(());
	}

	let error_msg = result.error_message.unwrap_or_else(|| {
		"Public-batch proof verification failed - no ProofVerified event found".to_string()
	});
	log_error!("❌ {}", error_msg);
	Err(crate::error::QuantusError::Generic(error_msg))
}

// ============================================================================
// Multi-round wormhole flow implementation
// ============================================================================

/// Information about a transfer needed for proof generation.
///
/// Returned by [`parse_transfer_events`] for every confirmed deposit; carries
/// the on-chain identifiers (`block_hash`, `transfer_count`, `leaf_index`)
/// plus the amount and the source/destination accounts. SDK consumers feed
/// these into [`crate::wormhole_lib::generate_proof`] to build the ZK proof.
//
// `block_hash` and `wormhole_address` are read by SDK consumers (e.g.
// `stress-test`, downstream wormhole clients) but not by the CLI binary
// itself; rustc only sees the bin target's usage and would otherwise warn.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct TransferInfo {
	/// Block hash where the transfer was included
	pub block_hash: subxt::utils::H256,
	/// Transfer count for this specific transfer
	pub transfer_count: u64,
	/// Amount transferred
	pub amount: u128,
	/// The wormhole address (destination of transfer)
	pub wormhole_address: SubxtAccountId,
	/// The funding account (source of transfer)
	pub funding_account: SubxtAccountId,
	/// Index of this transfer in the ZK trie (for Merkle proof lookup)
	pub leaf_index: u64,
}

/// Expected attributes used to uniquely bind a `NativeTransferred` event.
///
/// Optional fields are wildcards when `None`. Call sites that know the intended
/// funding account / amount / transfer_count should set them so a same-block
/// transfer to the same destination cannot be selected by destination alone.
#[derive(Debug, Clone)]
struct ExpectedTransferEvent {
	wormhole_address: SubxtAccountId,
	funding_account: Option<SubxtAccountId>,
	amount: Option<u128>,
	transfer_count: Option<u64>,
	leaf_index: Option<u64>,
}

struct RoundProofGeneration {
	proof_files: Vec<String>,
	expected_transfers: Vec<ExpectedTransferEvent>,
}

fn push_expected_transfer(
	expected: &mut Vec<ExpectedTransferEvent>,
	wormhole_address: SubxtAccountId,
	funding_account: SubxtAccountId,
	amount: u128,
	transfer_count: Option<u64>,
	leaf_index: Option<u64>,
) {
	if let Some(existing) = expected.iter_mut().find(|e| {
		e.wormhole_address == wormhole_address &&
			e.funding_account.as_ref() == Some(&funding_account) &&
			e.transfer_count == transfer_count &&
			e.leaf_index == leaf_index
	}) {
		let current = existing.amount.unwrap_or(0);
		existing.amount = Some(current.saturating_add(amount));
	} else {
		expected.push(ExpectedTransferEvent {
			wormhole_address,
			funding_account: Some(funding_account),
			amount: Some(amount),
			transfer_count,
			leaf_index,
		});
	}
}

fn event_matches_expected(
	event: &wormhole::events::NativeTransferred,
	expected: &ExpectedTransferEvent,
) -> bool {
	event.to == expected.wormhole_address &&
		expected.funding_account.as_ref().is_none_or(|from| &event.from == from) &&
		expected.amount.is_none_or(|amount| event.amount == amount) &&
		expected.transfer_count.is_none_or(|count| event.transfer_count == count) &&
		expected.leaf_index.is_none_or(|leaf| event.leaf_index == leaf)
}

fn parse_expected_transfer_events(
	events: &[wormhole::events::NativeTransferred],
	expected_transfers: &[ExpectedTransferEvent],
	block_hash: subxt::utils::H256,
) -> Result<Vec<TransferInfo>, crate::error::QuantusError> {
	let mut transfer_infos = Vec::with_capacity(expected_transfers.len());

	for expected in expected_transfers {
		let matches: Vec<&wormhole::events::NativeTransferred> =
			events.iter().filter(|event| event_matches_expected(event, expected)).collect();

		let matching_event = match matches.as_slice() {
			[event] => *event,
			[] => {
				return Err(crate::error::QuantusError::Generic(format!(
					"No transfer event found matching expected attributes for address {:?}",
					expected.wormhole_address
				)));
			},
			_ => {
				return Err(crate::error::QuantusError::Generic(format!(
					"Ambiguous transfer events matching expected attributes for address {:?}",
					expected.wormhole_address
				)));
			},
		};

		transfer_infos.push(TransferInfo {
			block_hash,
			transfer_count: matching_event.transfer_count,
			amount: matching_event.amount,
			wormhole_address: expected.wormhole_address.clone(),
			funding_account: matching_event.from.clone(),
			leaf_index: matching_event.leaf_index,
		});
	}

	Ok(transfer_infos)
}

/// Derive a wormhole secret using HD derivation
/// Path: m/44'/189189189'/0'/round'/index'
fn derive_wormhole_secret(
	mnemonic: &str,
	round: usize,
	index: usize,
) -> Result<WormholePair, crate::error::QuantusError> {
	// QUANTUS_WORMHOLE_CHAIN_ID already includes the ' (e.g., "189189189'")
	let path = format!("m/44'/{}/0'/{}'/{}'", QUANTUS_WORMHOLE_CHAIN_ID, round, index);
	derive_wormhole_from_mnemonic(mnemonic, None, &path)
		.map_err(|e| crate::error::QuantusError::Generic(format!("HD derivation failed: {:?}", e)))
}

/// Calculate the amount for a given round, accounting for fees
/// Each round deducts the on-chain volume fee (`VOLUME_FEE_BPS`)
/// Round 1: fee applied once, Round 2: fee applied twice, etc.
fn calculate_round_amount(initial_amount: u128, round: usize) -> u128 {
	let mut amount = initial_amount;
	for _ in 0..round {
		// Output = Input * (10000 - 10) / 10000
		amount = amount * 9990 / 10000;
	}
	amount
}

/// Get the minting account from chain constants
async fn get_minting_account(
	client: &OnlineClient<ChainConfig>,
) -> Result<SubxtAccountId, crate::error::QuantusError> {
	let minting_account_addr = quantus_node::api::constants().wormhole().minting_account();
	let minting_account = client.constants().at(&minting_account_addr).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to get minting account: {}", e))
	})?;
	Ok(minting_account)
}

/// Parse transfer info from NativeTransferred events in a block and updates block hash for all
/// transfers.
///
/// Destination-only matching rejects ambiguous duplicate destinations instead of
/// accepting the first event. Internal call sites that know intended
/// from/amount/transfer_count bind those attributes before accepting an event.
// Public SDK helper (re-exported from lib); unused by the CLI binary itself.
#[allow(dead_code)]
pub fn parse_transfer_events(
	events: &[wormhole::events::NativeTransferred],
	expected_addresses: &[SubxtAccountId],
	block_hash: subxt::utils::H256,
) -> Result<Vec<TransferInfo>, crate::error::QuantusError> {
	let expected_transfers: Vec<ExpectedTransferEvent> = expected_addresses
		.iter()
		.cloned()
		.map(|wormhole_address| ExpectedTransferEvent {
			wormhole_address,
			funding_account: None,
			amount: None,
			transfer_count: None,
			leaf_index: None,
		})
		.collect();

	parse_expected_transfer_events(events, &expected_transfers, block_hash)
}

/// Configuration for multiround execution
struct MultiroundConfig {
	num_proofs: usize,
	rounds: usize,
	amount: u128,
	output_dir: String,
	keep_files: bool,
}

/// Wallet context for multiround execution
struct MultiroundWalletContext {
	wallet_name: String,
	wallet_address: String,
	wallet_account_id: SubxtAccountId,
	keypair: QuantumKeyPair,
	mnemonic: String,
}

/// Validate multiround parameters
fn validate_multiround_params(
	num_proofs: usize,
	rounds: usize,
	max_proofs: usize,
) -> crate::error::Result<()> {
	if !(1..=max_proofs).contains(&num_proofs) {
		return Err(crate::error::QuantusError::Generic(format!(
			"num_proofs must be between 1 and {} (got: {})",
			max_proofs, num_proofs
		)));
	}
	if rounds < 1 {
		return Err(crate::error::QuantusError::Generic(format!(
			"rounds must be at least 1 (got: {})",
			rounds
		)));
	}
	Ok(())
}

/// Load wallet and prepare context for multiround execution
fn load_multiround_wallet(
	wallet_name: &str,
	password: Option<String>,
	password_file: Option<String>,
) -> crate::error::Result<MultiroundWalletContext> {
	let wallet_manager = WalletManager::new()?;
	let wallet_password = password::get_wallet_password(wallet_name, password, password_file)?;
	let mut wallet_data = wallet_manager.load_wallet(wallet_name, &wallet_password)?;
	let wallet_address = wallet_data.keypair.try_to_account_id_ss58check()?;
	let wallet_account_id = SubxtAccountId(wallet_data.keypair.try_to_account_id_32()?.into());

	// Require a persisted mnemonic for deterministic wormhole HD derivation.
	let mnemonic = wallet_data.take_mnemonic().ok_or_else(|| {
		crate::error::QuantusError::Generic(
			"Wallet does not contain a mnemonic. Use a wallet created from a mnemonic, or supply --mnemonic-file/--secret-file where supported.".to_string(),
		)
	})?;
	log_verbose!("Using wallet mnemonic for HD derivation");

	Ok(MultiroundWalletContext {
		wallet_name: wallet_name.to_string(),
		wallet_address,
		wallet_account_id,
		keypair: wallet_data.take_keypair(),
		mnemonic,
	})
}

/// Print multiround configuration summary
fn print_multiround_config(
	config: &MultiroundConfig,
	wallet: &MultiroundWalletContext,
	num_leaf_proofs: usize,
) {
	use colored::Colorize;

	log_print!("{}", "Configuration:".bright_cyan());
	log_print!("  Wallet: {}", wallet.wallet_name);
	log_print!("  Wallet address: {}", wallet.wallet_address);
	log_print!(
		"  Total amount: {} ({}) - randomly partitioned across {} proofs",
		config.amount,
		format_balance(config.amount),
		config.num_proofs
	);
	log_print!("  Proofs per round: {}", config.num_proofs);
	log_print!("  Rounds: {}", config.rounds);
	log_print!("  Aggregation: num_leaf_proofs={}", num_leaf_proofs);
	log_print!("  Output directory: {}", config.output_dir);
	log_print!("  Keep files: {}", config.keep_files);
	log_print!("");

	// Show expected amounts per round
	log_print!("{}", "Expected amounts per round:".bright_cyan());
	for r in 1..=config.rounds {
		let round_amount = calculate_round_amount(config.amount, r);
		log_print!("  Round {}: {} ({})", r, round_amount, format_balance(round_amount));
	}
	log_print!("");
}

/// Execute initial transfers from wallet to wormhole addresses (round 1 only).
///
/// Sends all transfers in a single batched extrinsic using `utility.batch()`.
/// Transfer counts are queried from chain storage (not events) to determine the
/// `transfer_count` for each recipient, which is needed for proof generation.
///
/// Note: We query `TransferCount` storage BEFORE submitting the batch because
/// the transfer_count in the proof must be the value at the time of transfer
/// (i.e., before the increment that happens during `record_transfer`).
async fn execute_initial_transfers(
	quantus_client: &QuantusClient,
	wallet: &MultiroundWalletContext,
	secrets: &[WormholePair],
	amount: u128,
	num_proofs: usize,
	execution_mode: ExecutionMode,
) -> crate::error::Result<Vec<TransferInfo>> {
	use colored::Colorize;
	use quantus_node::api::runtime_types::{
		pallet_balances::pallet::Call as BalancesCall, quantus_runtime::RuntimeCall,
	};

	log_print!("{}", "Step 1: Sending batched transfer to wormhole addresses...".bright_yellow());

	// Randomly partition the total amount among proofs
	// Each partition must meet the on-chain minimum transfer amount
	// Minimum per partition is 0.02 DEV (2 quantized units) to ensure non-trivial amounts
	let partition_amounts = random_partition(amount, num_proofs, 3 * SCALE_DOWN_FACTOR);
	log_print!("  Random partition of {} ({}):", amount, format_balance(amount));
	for (i, &amt) in partition_amounts.iter().enumerate() {
		log_print!("    Proof {}: {} ({})", i + 1, amt, format_balance(amt));
	}

	// Build batch of transfer calls
	let mut calls = Vec::with_capacity(num_proofs);
	for (i, secret) in secrets.iter().enumerate() {
		let wormhole_address = SubxtAccountId(*secret.address());
		let transfer_call = RuntimeCall::Balances(BalancesCall::transfer_allow_death {
			dest: subxt::ext::subxt_core::utils::MultiAddress::Id(wormhole_address),
			value: partition_amounts[i],
		});
		calls.push(transfer_call);
	}

	// batch_all is atomic: either every wormhole funding transfer lands or none
	// do, so the per-secret proof bookkeeping below can't diverge from chain state.
	let batch_tx = quantus_node::api::tx().utility().batch_all(calls);

	let quantum_keypair = QuantumKeyPair {
		public_key: wallet.keypair.public_key.clone(),
		private_key: wallet.keypair.private_key.clone(),
		scheme: wallet.keypair.scheme,
	};

	log_print!("  Submitting batch of {} transfers...", num_proofs);

	// Query transfer counts BEFORE submitting the batch.
	// The transfer_count used in the proof is the count at the time of transfer,
	// which equals the count before the transfer (since it increments after).
	let client = quantus_client.client();
	let tip_block_hash = wormhole_tip_block(quantus_client, execution_mode)
		.await
		.map_err(|e| {
			crate::error::QuantusError::Generic(format!(
				"Failed to get tip block for transfer counts: {}",
				e
			))
		})?
		.hash();
	let mut transfer_counts_before: Vec<u64> = Vec::with_capacity(num_proofs);
	for secret in secrets.iter() {
		let wormhole_address = SubxtAccountId(*secret.address());
		let count = client
			.storage()
			.at(tip_block_hash)
			.fetch(&quantus_node::api::storage().wormhole().transfer_count(wormhole_address))
			.await
			.map_err(|e| {
				crate::error::QuantusError::Generic(format!(
					"Failed to fetch transfer count for {}: {}",
					hex::encode(secret.address()),
					e
				))
			})?
			.unwrap_or(0);
		transfer_counts_before.push(count);
	}

	let wait_mode = wormhole_inclusion_mode(execution_mode);
	let (_tx_hash, included_in) = crate::cli::common::submit_transaction_with_inclusion_block(
		quantus_client,
		&quantum_keypair,
		batch_tx,
		None,
		wait_mode,
	)
	.await
	.map_err(|e| crate::error::QuantusError::Generic(format!("Batch transfer failed: {}", e)))?;

	// Read events from the transaction's own inclusion block; the tip may already
	// have moved past it by the time we query.
	let block_hash = included_in.ok_or_else(|| {
		crate::error::QuantusError::Generic(
			"Batch transfer watch returned no inclusion block".to_string(),
		)
	})?;

	let events_api =
		quantus_client.client().events().at(block_hash).await.map_err(|e| {
			crate::error::QuantusError::Generic(format!("Failed to get events: {}", e))
		})?;
	let transfer_events: Vec<wormhole::events::NativeTransferred> = events_api
		.find::<wormhole::events::NativeTransferred>()
		.filter_map(|e| e.ok())
		.collect();

	let funding_account: SubxtAccountId =
		SubxtAccountId(wallet.keypair.try_to_account_id_32()?.into());
	let expected_transfers: Vec<ExpectedTransferEvent> = secrets
		.iter()
		.enumerate()
		.map(|(i, secret)| ExpectedTransferEvent {
			wormhole_address: SubxtAccountId(*secret.address()),
			funding_account: Some(funding_account.clone()),
			amount: Some(partition_amounts[i]),
			transfer_count: Some(transfer_counts_before[i]),
			leaf_index: None,
		})
		.collect();
	let transfers =
		parse_expected_transfer_events(&transfer_events, &expected_transfers, block_hash)?;

	log_success!(
		"  {} transfers submitted in a single batch ({} block {})",
		num_proofs,
		wait_mode.transaction_stage().status_label(),
		hex::encode(block_hash.0)
	);

	Ok(transfers)
}

/// Generate proofs for a round with random output partitioning
async fn generate_round_proofs(
	quantus_client: &QuantusClient,
	secrets: &[WormholePair],
	transfers: &[TransferInfo],
	exit_accounts: &[SubxtAccountId],
	minting_account: &SubxtAccountId,
	round_dir: &str,
	num_proofs: usize,
	execution_mode: ExecutionMode,
) -> crate::error::Result<RoundProofGeneration> {
	use colored::Colorize;

	log_print!("{}", "Step 2: Generating proofs...".bright_yellow());

	// All proofs in an aggregation batch must use the same tip block for storage
	// proofs. Use best (not finalized) unless `--finalized-tx`, otherwise freshly
	// included leaves from the funding/verify step are missing from the tree.
	let proof_block = wormhole_tip_block(quantus_client, execution_mode)
		.await
		.map_err(|e| crate::error::QuantusError::Generic(format!("Failed to get block: {}", e)))?;
	let proof_block_hash = proof_block.hash();
	log_print!(
		"  Using {} block {} for all proofs",
		if execution_mode.finalized { "finalized" } else { "best" },
		hex::encode(proof_block_hash.0)
	);

	// Collect input amounts and exit accounts for random assignment
	let input_amounts: Vec<u128> = transfers.iter().map(|t| t.amount).collect();
	let exit_account_bytes: Vec<[u8; 32]> = exit_accounts.iter().map(|a| a.0).collect();

	// Compute random output assignments (each proof can have 2 outputs)
	let output_assignments =
		compute_random_output_assignments(&input_amounts, &exit_account_bytes, VOLUME_FEE_BPS)
			.map_err(crate::error::QuantusError::Generic)?;

	// Log the random partition
	log_print!("  Random output partition:");
	let mut expected_transfers = Vec::new();
	for (i, assignment) in output_assignments.iter().enumerate() {
		let amt1_planck = (assignment.output_amount_1 as u128) * SCALE_DOWN_FACTOR;
		let ss58_1 = bytes_to_quantus_ss58(&assignment.exit_account_1);
		if assignment.output_amount_1 > 0 {
			push_expected_transfer(
				&mut expected_transfers,
				SubxtAccountId(assignment.exit_account_1),
				minting_account.clone(),
				amt1_planck,
				None,
				None,
			);
		}
		if assignment.output_amount_2 > 0 {
			let amt2_planck = (assignment.output_amount_2 as u128) * SCALE_DOWN_FACTOR;
			let ss58_2 = bytes_to_quantus_ss58(&assignment.exit_account_2);
			push_expected_transfer(
				&mut expected_transfers,
				SubxtAccountId(assignment.exit_account_2),
				minting_account.clone(),
				amt2_planck,
				None,
				None,
			);
			log_print!(
				"    Proof {}: {} ({}) -> {}, {} ({}) -> {}",
				i + 1,
				assignment.output_amount_1,
				format_balance(amt1_planck),
				ss58_1,
				assignment.output_amount_2,
				format_balance(amt2_planck),
				ss58_2
			);
		} else {
			log_print!(
				"    Proof {}: {} ({}) -> {}",
				i + 1,
				assignment.output_amount_1,
				format_balance(amt1_planck),
				ss58_1
			);
		}
	}

	let pb = ProgressBar::new(num_proofs as u64);
	pb.set_style(
		ProgressStyle::default_bar()
			.template("{spinner:.green} [{bar:40.cyan/blue}] {pos}/{len} {msg}")
			.unwrap()
			.progress_chars("#>-"),
	);

	let proof_gen_start = std::time::Instant::now();
	let mut proof_files = Vec::new();
	for (i, (secret, transfer)) in secrets.iter().zip(transfers.iter()).enumerate() {
		pb.set_message(format!("Proof {}/{}", i + 1, num_proofs));

		let proof_file = format!("{}/proof_{}.hex", round_dir, i + 1);

		// Use the funding account from the transfer info
		let funding_account_hex = format!("0x{}", hex::encode(transfer.funding_account.0));

		let single_start = std::time::Instant::now();

		// Generate proof with dual output assignment. Bind the hex-encoded
		// secret so it can be wiped instead of dropping as a temporary.
		let mut secret_hex = hex::encode(secret.secret().as_bytes());
		let proof_result = generate_proof(
			&secret_hex,
			transfer.amount, // Use actual transfer amount for storage key
			&output_assignments[i],
			&format!("0x{}", hex::encode(proof_block_hash.0)),
			transfer.transfer_count,
			&funding_account_hex,
			transfer.leaf_index, // ZK trie leaf index for Merkle proof lookup
			&proof_file,
			quantus_client,
		)
		.await;
		crate::wallet::keystore::zeroize_string(&mut secret_hex);
		proof_result?;

		let single_elapsed = single_start.elapsed();
		log_verbose!("  Proof {} generated in {:.2}s", i + 1, single_elapsed.as_secs_f64());

		proof_files.push(proof_file);
		pb.inc(1);
	}
	pb.finish_with_message("Proofs generated");
	let proof_gen_elapsed = proof_gen_start.elapsed();
	log_print!(
		"  Proof generation: {:.2}s ({} proofs, {:.2}s avg)",
		proof_gen_elapsed.as_secs_f64(),
		num_proofs,
		proof_gen_elapsed.as_secs_f64() / num_proofs as f64,
	);

	Ok(RoundProofGeneration { proof_files, expected_transfers })
}

/// Derive wormhole secrets for a round
fn derive_round_secrets(
	mnemonic: &str,
	round: usize,
	num_proofs: usize,
) -> crate::error::Result<Vec<WormholePair>> {
	let pb = ProgressBar::new(num_proofs as u64);
	pb.set_style(
		ProgressStyle::default_bar()
			.template("{spinner:.green} [{bar:40.cyan/blue}] {pos}/{len} {msg}")
			.unwrap()
			.progress_chars("#>-"),
	);
	pb.set_message("Deriving secrets...");

	let mut secrets = Vec::new();
	for i in 1..=num_proofs {
		let secret = derive_wormhole_secret(mnemonic, round, i)?;
		secrets.push(secret);
		pb.inc(1);
	}
	pb.finish_with_message("Secrets derived");

	Ok(secrets)
}

/// Verify final balance and print summary
fn verify_final_balance(
	initial_balance: u128,
	final_balance: u128,
	total_sent: u128,
	rounds: usize,
	num_proofs: usize,
) {
	use colored::Colorize;

	log_print!("{}", "Balance Verification:".bright_cyan());

	// Total received in final round: apply fee deduction for each round
	let total_received = calculate_round_amount(total_sent, rounds);

	// Expected net change (may be negative due to fees)
	let expected_change = total_received as i128 - total_sent as i128;
	let actual_change = final_balance as i128 - initial_balance as i128;

	log_print!("  Initial balance: {} ({})", initial_balance, format_balance(initial_balance));
	log_print!("  Final balance:   {} ({})", final_balance, format_balance(final_balance));
	log_print!("");
	log_print!("  Total sent (round 1):     {} ({})", total_sent, format_balance(total_sent));
	log_print!(
		"  Total received (round {}): {} ({})",
		rounds,
		total_received,
		format_balance(total_received)
	);
	log_print!("");

	// Format signed amounts for display
	let expected_change_str = if expected_change >= 0 {
		format!("+{}", expected_change)
	} else {
		format!("{}", expected_change)
	};
	let actual_change_str = if actual_change >= 0 {
		format!("+{}", actual_change)
	} else {
		format!("{}", actual_change)
	};

	log_print!("  Expected change: {} planck", expected_change_str);
	log_print!("  Actual change:   {} planck", actual_change_str);
	log_print!("");

	// Allow some tolerance for transaction fees
	let tolerance = (total_sent / 100).max(1_000_000_000_000); // 1% or 1 QNT minimum

	let diff = (actual_change - expected_change).unsigned_abs();
	if diff <= tolerance {
		log_success!(
			"  {} Balance verification PASSED (within tolerance of {} planck)",
			"".bright_green(),
			tolerance
		);
	} else {
		log_print!(
			"  {} Balance verification: difference of {} planck (tolerance: {} planck)",
			"!".bright_yellow(),
			diff,
			tolerance
		);
		log_print!(
			"    Note: Transaction fees for {} initial transfers may account for the difference",
			num_proofs
		);
	}
	log_print!("");
}

/// Run the multi-round wormhole flow
#[allow(clippy::too_many_arguments)]
async fn run_multiround(
	num_proofs: usize,
	rounds: usize,
	amount: u128,
	wallet_name: String,
	password: Option<String>,
	password_file: Option<String>,
	keep_files: bool,
	output_dir: String,
	dry_run: bool,
	public: bool,
	node_url: &str,
	execution_mode: ExecutionMode,
) -> crate::error::Result<()> {
	use colored::Colorize;

	log_print!("");
	log_print!("==================================================");
	log_print!("  Wormhole Multi-Round Flow Test");
	log_print!("==================================================");
	log_print!("");

	let bins_dir = crate::bins::ensure_bins_dir()?;
	let agg_config = CircuitBinsConfig::load(&bins_dir).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to load aggregation config: {}", e))
	})?;

	// Validate parameters
	validate_multiround_params(num_proofs, rounds, agg_config.num_leaf_proofs)?;

	// Load wallet
	let wallet = load_multiround_wallet(&wallet_name, password, password_file)?;

	// Create config struct
	let config =
		MultiroundConfig { num_proofs, rounds, amount, output_dir: output_dir.clone(), keep_files };

	// Print configuration
	print_multiround_config(&config, &wallet, agg_config.num_leaf_proofs);
	log_print!("  Dry run: {}", dry_run);
	log_print!("");

	// Create output directory
	std::fs::create_dir_all(&output_dir).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to create output directory: {}", e))
	})?;

	if dry_run {
		return run_multiround_dry_run(
			&wallet.mnemonic,
			num_proofs,
			rounds,
			amount,
			&wallet.wallet_address,
		);
	}

	// Connect to node
	let quantus_client = QuantusClient::new(node_url).await.map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to connect to node: {}", e))
	})?;
	let client = quantus_client.client();

	// Get minting account from chain
	let minting_account = get_minting_account(client).await?;
	log_verbose!("Minting account: {:?}", minting_account);

	// Record initial wallet balance for verification
	let initial_balance = get_balance(&quantus_client, &wallet.wallet_address).await?;
	log_print!("{}", "Initial Balance:".bright_cyan());
	log_print!("  Wallet balance: {} ({})", initial_balance, format_balance(initial_balance));
	log_print!("");

	// Track transfer info for the current round
	let mut current_transfers: Vec<TransferInfo> = Vec::new();

	for round in 1..=rounds {
		let is_final = round == rounds;

		log_print!("");
		log_print!("--------------------------------------------------");
		log_print!(
			"  {} Round {} of {} {}",
			">>>".bright_blue(),
			round,
			rounds,
			"<<<".bright_blue()
		);
		log_print!("--------------------------------------------------");
		log_print!("");

		// Create round output directory
		let round_dir = format!("{}/round{}", output_dir, round);
		std::fs::create_dir_all(&round_dir).map_err(|e| {
			crate::error::QuantusError::Generic(format!("Failed to create round directory: {}", e))
		})?;

		// Derive secrets for this round
		let secrets = derive_round_secrets(&wallet.mnemonic, round, num_proofs)?;

		// Determine exit accounts
		let exit_accounts: Vec<SubxtAccountId> = if is_final {
			log_print!("Final round - all proofs exit to wallet: {}", wallet.wallet_address);
			vec![wallet.wallet_account_id.clone(); num_proofs]
		} else {
			log_print!(
				"Intermediate round - proofs exit to round {} wormhole addresses",
				round + 1
			);
			let mut addrs = Vec::new();
			for i in 1..=num_proofs {
				let next_secret = derive_wormhole_secret(&wallet.mnemonic, round + 1, i)?;
				addrs.push(SubxtAccountId(*next_secret.address()));
			}
			addrs
		};

		// Step 1: Get transfer info (execute transfers for round 1, reuse from previous round
		// otherwise)
		if round == 1 {
			current_transfers = execute_initial_transfers(
				&quantus_client,
				&wallet,
				&secrets,
				amount,
				num_proofs,
				execution_mode,
			)
			.await?;

			// Log balance immediately after funding transfers
			let balance_after_funding =
				get_balance(&quantus_client, &wallet.wallet_address).await?;
			let funding_deducted = initial_balance.saturating_sub(balance_after_funding);
			log_print!(
				"  Balance after funding: {} ({}) [deducted: {} planck]",
				balance_after_funding,
				format_balance(balance_after_funding),
				funding_deducted
			);
		} else {
			log_print!("{}", "Step 1: Using transfer info from previous round...".bright_yellow());
			log_print!("  Found {} transfer(s) from previous round", current_transfers.len());
		}

		// Step 2: Generate proofs with random output partitioning
		let RoundProofGeneration { proof_files, expected_transfers } = generate_round_proofs(
			&quantus_client,
			&secrets,
			&current_transfers,
			&exit_accounts,
			&minting_account,
			&round_dir,
			num_proofs,
			execution_mode,
		)
		.await?;

		// Step 3: Aggregate proofs
		log_print!("{}", "Step 3: Aggregating proofs...".bright_yellow());

		let aggregated_file = format!("{}/aggregated.hex", round_dir);
		aggregate_proofs(proof_files, aggregated_file.clone()).await?;

		log_print!("  Aggregated proof saved to {}", aggregated_file);

		// Step 4: Verify on-chain (optionally wrapping in a public batch first)
		let (verification_block, extrinsic_hash, transfer_events) = if public {
			log_print!(
				"{}",
				"Step 4: Wrapping in a public batch and submitting on-chain...".bright_yellow()
			);
			let public_batch_file = format!("{}/public_batch.hex", round_dir);
			aggregate_public_batch(
				vec![aggregated_file.clone()],
				wallet.wallet_address.clone(),
				public_batch_file.clone(),
			)
			.await?;
			verify_public_batch_and_get_events_until(
				&public_batch_file,
				&quantus_client,
				wormhole_inclusion_stage(execution_mode),
			)
			.await?
		} else {
			log_print!("{}", "Step 4: Submitting aggregated proof on-chain...".bright_yellow());
			verify_private_batch_and_get_events_until(
				&aggregated_file,
				&quantus_client,
				wormhole_inclusion_stage(execution_mode),
			)
			.await?
		};

		log_print!(
			"  {} Proof verified in block {} (extrinsic: 0x{})",
			"".bright_green(),
			hex::encode(verification_block.0),
			hex::encode(extrinsic_hash.0)
		);

		// If not final round, prepare transfer info for next round
		if !is_final {
			log_print!("{}", "Step 5: Capturing transfer info for next round...".bright_yellow());

			// Reorder expected transfers to match next-round secret indices.
			let next_round_addresses: Vec<SubxtAccountId> = (1..=num_proofs)
				.map(|i| {
					let next_secret =
						derive_wormhole_secret(&wallet.mnemonic, round + 1, i).unwrap();
					SubxtAccountId(*next_secret.address())
				})
				.collect();
			let expected_ordered: Vec<ExpectedTransferEvent> = next_round_addresses
				.iter()
				.map(|addr| {
					expected_transfers
						.iter()
						.find(|e| &e.wormhole_address == addr)
						.cloned()
						.ok_or_else(|| {
							crate::error::QuantusError::Generic(format!(
								"No expected transfer for next-round address {:?}",
								addr
							))
						})
				})
				.collect::<Result<_, _>>()?;

			current_transfers = parse_expected_transfer_events(
				&transfer_events,
				&expected_ordered,
				verification_block,
			)?;

			log_print!(
				"  Captured {} transfer(s) for round {}",
				current_transfers.len(),
				round + 1
			);
		}

		// Log balance after this round
		let balance_after_round = get_balance(&quantus_client, &wallet.wallet_address).await?;
		let change_from_initial = balance_after_round as i128 - initial_balance as i128;
		let change_str = if change_from_initial >= 0 {
			format!("+{}", change_from_initial)
		} else {
			format!("{}", change_from_initial)
		};
		log_print!("");
		log_print!(
			"  Balance after round {}: {} ({}) [change: {} planck]",
			round,
			balance_after_round,
			format_balance(balance_after_round),
			change_str
		);

		log_print!("");
		log_print!("  {} Round {} complete!", "".bright_green(), round);
	}

	log_print!("");
	log_print!("==================================================");
	log_success!("  All {} rounds completed successfully!", rounds);
	log_print!("==================================================");
	log_print!("");

	// Final balance verification
	let final_balance = get_balance(&quantus_client, &wallet.wallet_address).await?;
	verify_final_balance(initial_balance, final_balance, amount, rounds, num_proofs);

	if keep_files {
		log_print!("Proof files preserved in: {}", output_dir);
	} else {
		log_print!("Cleaning up proof files...");
		std::fs::remove_dir_all(&output_dir).ok();
	}

	Ok(())
}

/// Generate a wormhole proof with dual outputs (used for random partitioning in multiround)
///
/// This function fetches the necessary data from the chain and delegates to
/// `wormhole_lib::generate_proof` for the actual proof generation.
async fn generate_proof(
	secret_hex: &str,
	_funding_amount: u128, // No longer needed - input_amount comes from ZK leaf
	output_assignment: &ProofOutputAssignment,
	block_hash_str: &str,
	transfer_count: u64,
	_funding_account_str: &str, // No longer needed - no `from` field in ZK leaf
	leaf_index: u64,            // ZK trie leaf index for Merkle proof lookup
	output_file: &str,
	quantus_client: &QuantusClient,
) -> crate::error::Result<()> {
	// Parse inputs
	let mut secret = parse_secret_hex(secret_hex).map_err(crate::error::QuantusError::Generic)?;

	let block_hash_bytes: [u8; 32] = hex::decode(block_hash_str.trim_start_matches("0x"))
		.map_err(|e| crate::error::QuantusError::Generic(format!("Invalid block hash: {}", e)))?
		.try_into()
		.map_err(|_| {
			crate::error::QuantusError::Generic("Block hash must be 32 bytes".to_string())
		})?;

	// Compute wormhole address using wormhole_lib
	let wormhole_address = wormhole_lib::compute_wormhole_address(&secret)
		.map_err(|e| crate::error::QuantusError::Generic(e.message))?;

	// Fetch data from chain
	let block_hash = subxt::utils::H256::from(block_hash_bytes);
	let client = quantus_client.client();

	// Get block header
	let blocks =
		client.blocks().at(block_hash).await.map_err(|e| {
			crate::error::QuantusError::Generic(format!("Failed to get block: {}", e))
		})?;

	// Fetch ZK Merkle proof from chain via RPC using the leaf_index
	// CRITICAL: We MUST fetch the proof at the same block we're proving against.
	// The tree root changes with each block, so proof must match header.zk_tree_root.
	let proof_params = rpc_params![leaf_index, block_hash];
	let zk_proof: Option<ZkMerkleProofRpc> = quantus_client
		.rpc_client()
		.request("zkTree_getMerkleProof", proof_params)
		.await
		.map_err(|e| {
			crate::error::QuantusError::Generic(format!(
				"Failed to get ZK Merkle proof at block {:?}: {}",
				block_hash, e
			))
		})?;

	let zk_proof = zk_proof.ok_or_else(|| {
		crate::error::QuantusError::Generic(format!(
			"No ZK Merkle proof found for leaf_index {}",
			leaf_index
		))
	})?;

	// Decode the input amount from the leaf data
	// The leaf data is SCALE-encoded ZkLeaf: (to: AccountId, transfer_count: u64, asset_id:
	// AssetId, amount: Balance) For now, we'll use the quantized amount that the circuit expects
	// The chain stores the quantized amount directly in the ZK leaf
	let input_amount = decode_input_amount_from_leaf(&zk_proof.leaf_data)?;

	// Extract header data
	let header = blocks.header();
	let parent_hash: [u8; 32] = header.parent_hash.0;
	let state_root: [u8; 32] = header.state_root.0;
	let extrinsics_root: [u8; 32] = header.extrinsics_root.0;
	let digest = header.digest.encode();
	let block_number = header.number;

	// Compute sorted siblings and positions from unsorted siblings returned by chain
	// The chain returns unsorted siblings; we sort them and compute position hints
	let (sorted_siblings, positions) =
		compute_merkle_positions(&zk_proof.siblings, zk_proof.leaf_hash);

	// Build ProofGenerationInput using wormhole_lib types with ZK Merkle proof.
	// generate_proof zeroizes input.secret before returning; wipe the local
	// copy as soon as it has been moved into the input struct.
	let mut input = wormhole_lib::ProofGenerationInput {
		secret,
		transfer_count,
		wormhole_address,
		input_amount,
		block_hash: block_hash_bytes,
		block_number,
		parent_hash,
		state_root,
		extrinsics_root,
		digest,
		zk_tree_root: zk_proof.root,
		zk_merkle_siblings: sorted_siblings,
		zk_merkle_positions: positions,
		exit_account_1: output_assignment.exit_account_1,
		exit_account_2: output_assignment.exit_account_2,
		output_amount_1: output_assignment.output_amount_1,
		output_amount_2: output_assignment.output_amount_2,
		volume_fee_bps: VOLUME_FEE_BPS,
		asset_id: NATIVE_ASSET_ID,
	};
	crate::wallet::keystore::zeroize_bytes(&mut secret);

	let bins_dir = crate::bins::ensure_bins_dir()?;
	let result = wormhole_lib::generate_proof(
		&mut input,
		&bins_dir.join("prover.bin"),
		&bins_dir.join("common.bin"),
	)
	.map_err(|e| crate::error::QuantusError::Generic(e.message))?;

	// Write proof to file
	let proof_hex = hex::encode(result.proof_bytes);
	std::fs::write(output_file, proof_hex).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to write proof: {}", e))
	})?;

	Ok(())
}

/// Decode the input amount from SCALE-encoded ZkLeaf data.
/// ZkLeaf structure: (to: AccountId32, transfer_count: u64, asset_id: u32, amount: u128)
///
/// The chain stores the RAW amount (in planck), but hash_leaf() quantizes it.
/// We need to return the QUANTIZED amount for the circuit.
fn decode_input_amount_from_leaf(leaf_data: &[u8]) -> crate::error::Result<u32> {
	// ZkLeaf is: (AccountId32, u64, u32, u128)
	// AccountId32 = 32 bytes
	// u64 = 8 bytes (transfer_count)
	// u32 = 4 bytes (asset_id)
	// u128 = 16 bytes (amount - RAW in planck)
	// Total = 60 bytes

	if leaf_data.len() < 60 {
		return Err(crate::error::QuantusError::Generic(format!(
			"Invalid leaf data length: expected at least 60 bytes, got {}",
			leaf_data.len()
		)));
	}

	// The amount is bytes 44-60 (u128, little-endian)
	let amount_bytes: [u8; 16] = leaf_data[44..60].try_into().map_err(|_| {
		crate::error::QuantusError::Generic("Failed to extract amount bytes".to_string())
	})?;

	let raw_amount = u128::from_le_bytes(amount_bytes);

	// Quantize: divide by 10^10 to get 2 decimal places (matches chain's hash_leaf)
	const AMOUNT_SCALE_DOWN_FACTOR: u128 = 10_000_000_000;
	let quantized = (raw_amount / AMOUNT_SCALE_DOWN_FACTOR) as u32;

	Ok(quantized)
}

/// Decode all fields from SCALE-encoded ZkLeaf data.
///
/// `ZkLeaf` is the on-chain leaf payload sitting in the ZK trie (`AccountId32`,
/// `u64`, `u32`, `u128`). Returned tuple is `(to_account, transfer_count,
/// asset_id, raw_amount_u128)` — the raw amount is in planck (12 decimals);
/// use [`crate::wormhole_lib::quantize_amount`] before feeding into a circuit.
//
// SDK helper: the CLI binary uses `decode_input_amount_from_leaf` for its own
// flow; this fuller decoder is exported for downstream consumers (the bin
// target itself doesn't reference it, hence `allow(dead_code)`).
#[allow(dead_code)]
pub fn decode_full_leaf_data(leaf_data: &[u8]) -> crate::error::Result<([u8; 32], u64, u32, u128)> {
	// ZkLeaf is: (AccountId32, u64, u32, u128)
	// AccountId32 = 32 bytes
	// u64 = 8 bytes (transfer_count)
	// u32 = 4 bytes (asset_id)
	// u128 = 16 bytes (amount - RAW in planck)
	// Total = 60 bytes

	if leaf_data.len() < 60 {
		return Err(crate::error::QuantusError::Generic(format!(
			"Invalid leaf data length: expected at least 60 bytes, got {}",
			leaf_data.len()
		)));
	}

	let to_account: [u8; 32] = leaf_data[0..32].try_into().map_err(|_| {
		crate::error::QuantusError::Generic("Failed to extract to_account".to_string())
	})?;

	let transfer_count = u64::from_le_bytes(leaf_data[32..40].try_into().map_err(|_| {
		crate::error::QuantusError::Generic("Failed to extract transfer_count".to_string())
	})?);

	let asset_id = u32::from_le_bytes(leaf_data[40..44].try_into().map_err(|_| {
		crate::error::QuantusError::Generic("Failed to extract asset_id".to_string())
	})?);

	let amount = u128::from_le_bytes(leaf_data[44..60].try_into().map_err(|_| {
		crate::error::QuantusError::Generic("Failed to extract amount".to_string())
	})?);

	Ok((to_account, transfer_count, asset_id, amount))
}

/// Verify an aggregated proof and return the block hash, extrinsic hash, and transfer events.
///
/// Waits for best-block inclusion by default. Prefer
/// [`verify_private_batch_and_get_events_until`] when `--finalized-tx` is set.
#[allow(dead_code)] // SDK re-export; CLI uses the `_until` variant.
pub async fn verify_private_batch_and_get_events(
	proof_file: &str,
	quantus_client: &QuantusClient,
) -> crate::error::Result<(
	subxt::utils::H256,
	subxt::utils::H256,
	Vec<wormhole::events::NativeTransferred>,
)> {
	verify_private_batch_and_get_events_until(
		proof_file,
		quantus_client,
		TransactionStage::Included,
	)
	.await
}

/// Like [`verify_private_batch_and_get_events`], waiting until `target_stage`.
pub async fn verify_private_batch_and_get_events_until(
	proof_file: &str,
	quantus_client: &QuantusClient,
	target_stage: TransactionStage,
) -> crate::error::Result<(
	subxt::utils::H256,
	subxt::utils::H256,
	Vec<wormhole::events::NativeTransferred>,
)> {
	let proof_bytes = read_hex_proof_file_to_bytes(proof_file)?;

	log_verbose!("Verifying aggregated proof locally before on-chain submission...");
	let bins_dir = crate::bins::ensure_bins_dir()?;

	let common_bytes = std::fs::read(bins_dir.join("private_batch_common.bin")).map_err(|e| {
		crate::error::QuantusError::Generic(format!(
			"Failed to read private_batch_common.bin: {}",
			e
		))
	})?;
	let verifier_bytes =
		std::fs::read(bins_dir.join("private_batch_verifier.bin")).map_err(|e| {
			crate::error::QuantusError::Generic(format!(
				"Failed to read private_batch_verifier.bin: {}",
				e
			))
		})?;
	log_verbose!(
		"Circuit binaries: common_bytes.len={}, verifier_bytes.len={}, common_hash={}, verifier_hash={}",
		common_bytes.len(),
		verifier_bytes.len(),
		hex::encode(blake3::hash(&common_bytes).as_bytes()),
		hex::encode(blake3::hash(&verifier_bytes).as_bytes()),
	);

	let verifier = crate::batch_verifier::load_private_batch_verifier(&bins_dir).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to load aggregated verifier: {}", e))
	})?;

	let proof = qp_wormhole_verifier::ProofWithPublicInputs::<
		qp_wormhole_verifier::F,
		qp_wormhole_verifier::C,
		{ qp_wormhole_verifier::D },
	>::from_bytes(proof_bytes.clone(), &verifier.circuit_data.common)
	.map_err(|e| {
		crate::error::QuantusError::Generic(format!(
			"Failed to deserialize aggregated proof: {}",
			e
		))
	})?;

	verifier.verify(proof).map_err(|e| {
		crate::error::QuantusError::Generic(format!(
			"Local aggregated proof verification failed: {}",
			e
		))
	})?;
	log_verbose!("Local verification passed!");

	// Submit unsigned tx + wait for inclusion (best by default; finalized only if requested)
	let (included_at, block_hash, tx_hash) =
		submit_unsigned_verify_private_batch_until(quantus_client, proof_bytes, target_stage)
			.await?;

	log_verbose!(
		"Submitted tx included in {}: block={:?}, tx={:?}",
		included_at.label(),
		block_hash,
		tx_hash
	);

	// Collect events for our extrinsic only
	let (found_proof_verified, transfer_events) =
		collect_wormhole_events_for_extrinsic(quantus_client, block_hash, tx_hash).await?;

	if !found_proof_verified {
		return Err(crate::error::QuantusError::Generic(
			"Proof verification failed - no ProofVerified event".to_string(),
		));
	}

	// Log minted amounts
	log_print!("  Tokens minted (from NativeTransferred events):");
	for (idx, transfer) in transfer_events.iter().enumerate() {
		let ss58_address = bytes_to_quantus_ss58(&transfer.to.0);
		log_print!(
			"    [{}] {} -> {} planck ({})",
			idx,
			ss58_address,
			transfer.amount,
			format_balance(transfer.amount)
		);
	}

	Ok((block_hash, tx_hash, transfer_events))
}

/// Verify a public-batch proof and return the block hash, extrinsic hash, and transfer events.
///
/// Waits for best-block inclusion by default. Prefer
/// [`verify_public_batch_and_get_events_until`] when `--finalized-tx` is set.
#[allow(dead_code)] // SDK re-export; CLI uses the `_until` variant.
pub async fn verify_public_batch_and_get_events(
	proof_file: &str,
	quantus_client: &QuantusClient,
) -> crate::error::Result<(
	subxt::utils::H256,
	subxt::utils::H256,
	Vec<wormhole::events::NativeTransferred>,
)> {
	verify_public_batch_and_get_events_until(proof_file, quantus_client, TransactionStage::Included)
		.await
}

/// Like [`verify_public_batch_and_get_events`], waiting until `target_stage`.
pub async fn verify_public_batch_and_get_events_until(
	proof_file: &str,
	quantus_client: &QuantusClient,
	target_stage: TransactionStage,
) -> crate::error::Result<(
	subxt::utils::H256,
	subxt::utils::H256,
	Vec<wormhole::events::NativeTransferred>,
)> {
	let proof_bytes = read_hex_proof_file_to_bytes(proof_file)?;

	log_verbose!("Verifying public-batch proof locally before on-chain submission...");
	let bins_dir = crate::bins::ensure_bins_dir()?;

	let verifier = crate::batch_verifier::load_public_batch_verifier(&bins_dir).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to load public-batch verifier: {}", e))
	})?;

	let proof = qp_wormhole_verifier::ProofWithPublicInputs::<
		qp_wormhole_verifier::F,
		qp_wormhole_verifier::C,
		{ qp_wormhole_verifier::D },
	>::from_bytes(proof_bytes.clone(), &verifier.circuit_data.common)
	.map_err(|e| {
		crate::error::QuantusError::Generic(format!(
			"Failed to deserialize public-batch proof: {}",
			e
		))
	})?;

	verifier.verify(proof).map_err(|e| {
		crate::error::QuantusError::Generic(format!(
			"Local public-batch proof verification failed: {}",
			e
		))
	})?;
	log_verbose!("Local verification passed!");

	// Submit unsigned tx + wait for inclusion (best by default; finalized only if requested)
	let (included_at, block_hash, tx_hash) =
		submit_unsigned_verify_public_batch_until(quantus_client, proof_bytes, target_stage)
			.await?;

	log_verbose!(
		"Submitted tx included in {}: block={:?}, tx={:?}",
		included_at.label(),
		block_hash,
		tx_hash
	);

	// Collect events for our extrinsic only
	let (found_proof_verified, transfer_events) =
		collect_wormhole_events_for_extrinsic(quantus_client, block_hash, tx_hash).await?;

	if !found_proof_verified {
		return Err(crate::error::QuantusError::Generic(
			"Public-batch proof verification failed - no ProofVerified event".to_string(),
		));
	}

	// Log minted amounts
	log_print!("  Tokens minted (from NativeTransferred events):");
	for (idx, transfer) in transfer_events.iter().enumerate() {
		let ss58_address = bytes_to_quantus_ss58(&transfer.to.0);
		log_print!(
			"    [{}] {} -> {} planck ({})",
			idx,
			ss58_address,
			transfer.amount,
			format_balance(transfer.amount)
		);
	}

	Ok((block_hash, tx_hash, transfer_events))
}

/// Dry run - show what would happen without executing
fn run_multiround_dry_run(
	mnemonic: &str,
	num_proofs: usize,
	rounds: usize,
	amount: u128,
	wallet_address: &str,
) -> crate::error::Result<()> {
	use colored::Colorize;

	log_print!("");
	log_print!("{}", "=== DRY RUN MODE ===".bright_yellow());
	log_print!("No transactions will be executed.");
	log_print!("");

	for round in 1..=rounds {
		let is_final = round == rounds;
		let round_amount = calculate_round_amount(amount, round);

		log_print!("");
		log_print!("{}", format!("Round {}", round).bright_cyan());
		log_print!("  Total amount: {} ({})", round_amount, format_balance(round_amount));

		// Show sample random partition for round 1
		if round == 1 {
			let partition = random_partition(amount, num_proofs, 3 * SCALE_DOWN_FACTOR);
			log_print!("  Sample random partition (actual partition will differ):");
			for (i, &amt) in partition.iter().enumerate() {
				log_print!("    Proof {}: {} ({})", i + 1, amt, format_balance(amt));
			}
		}
		log_print!("");

		log_print!("  Wormhole addresses (to be funded):");
		for i in 1..=num_proofs {
			let secret = derive_wormhole_secret(mnemonic, round, i)?;
			let address = sp_core::crypto::AccountId32::new(*secret.address())
				.to_ss58check_with_version(sp_core::crypto::Ss58AddressFormat::custom(189));
			log_print!("    [{}] {}", i, address);
		}

		log_print!("");
		log_print!("  Exit accounts:");
		if is_final {
			log_print!("    All proofs exit to wallet: {}", wallet_address);
		} else {
			for i in 1..=num_proofs {
				let next_secret = derive_wormhole_secret(mnemonic, round + 1, i)?;
				let address = sp_core::crypto::AccountId32::new(*next_secret.address())
					.to_ss58check_with_version(sp_core::crypto::Ss58AddressFormat::custom(189));
				log_print!("    [{}] {} (round {} wormhole)", i, address, round + 1);
			}
		}
	}

	log_print!("");
	log_print!("{}", "=== END DRY RUN ===".bright_yellow());
	log_print!("");

	Ok(())
}

/// Parse and display the contents of a proof file for debugging
async fn parse_proof_file(
	proof_file: String,
	aggregated: bool,
	public_batch: bool,
	verify: bool,
) -> crate::error::Result<()> {
	use qp_wormhole_verifier::WormholeVerifier;

	log_print!("Parsing proof file: {}", proof_file);

	// Read proof bytes
	let proof_bytes = read_proof_file(&proof_file)
		.map_err(|e| crate::error::QuantusError::Generic(format!("Failed to read proof: {}", e)))?;

	log_print!("Proof size: {} bytes", proof_bytes.len());

	let bins_dir = crate::bins::ensure_bins_dir()?;

	if public_batch {
		use plonky2::field::types::PrimeField64;
		use qp_wormhole_inputs::PublicBatchPublicInputs;

		let agg_config = CircuitBinsConfig::load(&bins_dir).map_err(|e| {
			crate::error::QuantusError::Generic(format!("Failed to load bins config: {}", e))
		})?;
		let num_private_batch_proofs = agg_config.num_private_batch_proofs.ok_or_else(|| {
			crate::error::QuantusError::Generic(
				"Circuit binaries lack public-batch support; regenerate them".to_string(),
			)
		})?;

		let verifier =
			crate::batch_verifier::load_public_batch_verifier(&bins_dir).map_err(|e| {
				crate::error::QuantusError::Generic(format!("Failed to load verifier: {}", e))
			})?;

		let proof = qp_wormhole_verifier::ProofWithPublicInputs::<
			qp_wormhole_verifier::F,
			qp_wormhole_verifier::C,
			{ qp_wormhole_verifier::D },
		>::from_bytes(proof_bytes.clone(), &verifier.circuit_data.common)
		.map_err(|e| {
			crate::error::QuantusError::Generic(format!(
				"Failed to deserialize public-batch proof: {:?}",
				e
			))
		})?;

		log_print!("\nPublic inputs count: {}", proof.public_inputs.len());

		let pi_u64s: Vec<u64> = proof.public_inputs.iter().map(|f| f.to_canonical_u64()).collect();
		match PublicBatchPublicInputs::try_from_u64_slice(
			&pi_u64s,
			num_private_batch_proofs,
			agg_config.num_leaf_proofs,
		) {
			Ok(inputs) => {
				log_print!("\n=== Parsed Public-Batch Public Inputs ===");
				log_print!(
					"Aggregator: 0x{} ({})",
					hex::encode(inputs.aggregator_address.as_ref()),
					slice_to_quantus_ss58(inputs.aggregator_address.as_ref())?
				);
				log_print!("Asset ID: {}", inputs.asset_id);
				log_print!("Volume Fee BPS: {}", inputs.volume_fee_bps);
				log_print!("Block Hash: 0x{}", hex::encode(inputs.block_data.block_hash.as_ref()));
				log_print!("Block Number: {}", inputs.block_data.block_number);
				log_print!("Total Exit Slots: {}", inputs.total_exit_slots);
				log_print!("\nAccount Data ({} slots):", inputs.account_data.len());
				for (i, acct) in inputs.account_data.iter().enumerate() {
					log_print!(
						"  [{}] amount={}, exit=0x{}",
						i,
						acct.summed_output_amount,
						hex::encode(acct.exit_account.as_ref())
					);
				}
				log_print!("\nNullifiers ({} nullifiers):", inputs.nullifiers.len());
				for (i, nullifier) in inputs.nullifiers.iter().enumerate() {
					log_print!("  [{}] 0x{}", i, hex::encode(nullifier.as_ref()));
				}
			},
			Err(e) => {
				log_print!("Failed to parse as public-batch inputs: {}", e);
			},
		}

		if verify {
			log_print!("\n=== Verifying Proof ===");
			match verifier.verify(proof) {
				Ok(()) => log_success!("Proof verification PASSED"),
				Err(e) => {
					log_error!("Proof verification FAILED: {}", e);
					return Err(crate::error::QuantusError::Generic(format!(
						"Proof verification failed: {}",
						e
					)));
				},
			}
		}
	} else if aggregated {
		// Load aggregated verifier (batch profile checks; not the leaf keccak pin).
		let verifier =
			crate::batch_verifier::load_private_batch_verifier(&bins_dir).map_err(|e| {
				crate::error::QuantusError::Generic(format!("Failed to load verifier: {}", e))
			})?;

		// Deserialize proof using verifier's types
		let proof = qp_wormhole_verifier::ProofWithPublicInputs::<
			qp_wormhole_verifier::F,
			qp_wormhole_verifier::C,
			{ qp_wormhole_verifier::D },
		>::from_bytes(proof_bytes.clone(), &verifier.circuit_data.common)
		.map_err(|e| {
			crate::error::QuantusError::Generic(format!(
				"Failed to deserialize aggregated proof: {:?}",
				e
			))
		})?;

		log_print!("\nPublic inputs count: {}", proof.public_inputs.len());
		log_verbose!("\nPublic inputs count: {}", proof.public_inputs.len());

		// Try to parse as aggregated
		match qp_wormhole_verifier::parse_private_batch_public_inputs(&proof) {
			Ok(agg_inputs) => {
				log_print!("\n=== Parsed Aggregated Public Inputs ===");
				log_print!("Asset ID: {}", agg_inputs.asset_id);
				log_print!("Volume Fee BPS: {}", agg_inputs.volume_fee_bps);
				log_print!(
					"Block Hash: 0x{}",
					hex::encode(agg_inputs.block_data.block_hash.as_ref())
				);
				log_print!("Block Number: {}", agg_inputs.block_data.block_number);
				log_print!("\nAccount Data ({} accounts):", agg_inputs.account_data.len());
				for (i, acct) in agg_inputs.account_data.iter().enumerate() {
					log_print!(
						"  [{}] amount={}, exit=0x{}",
						i,
						acct.summed_output_amount,
						hex::encode(acct.exit_account.as_ref())
					);
				}
				log_print!("\nNullifiers ({} nullifiers):", agg_inputs.nullifiers.len());
				for (i, nullifier) in agg_inputs.nullifiers.iter().enumerate() {
					log_print!("  [{}] 0x{}", i, hex::encode(nullifier.as_ref()));
				}
			},
			Err(e) => {
				log_print!("Failed to parse as aggregated inputs: {}", e);
			},
		}

		// Verify if requested
		if verify {
			log_print!("\n=== Verifying Proof ===");
			match verifier.verify(proof) {
				Ok(()) => {
					log_success!("Proof verification PASSED");
				},
				Err(e) => {
					log_error!("Proof verification FAILED: {}", e);
					return Err(crate::error::QuantusError::Generic(format!(
						"Proof verification failed: {}",
						e
					)));
				},
			}
		}
	} else {
		// Load leaf verifier
		let verifier = WormholeVerifier::new_from_files(
			&bins_dir.join("verifier.bin"),
			&bins_dir.join("common.bin"),
		)
		.map_err(|e| {
			crate::error::QuantusError::Generic(format!("Failed to load verifier: {}", e))
		})?;

		// Deserialize proof using verifier's types
		let proof = qp_wormhole_verifier::ProofWithPublicInputs::<
			qp_wormhole_verifier::F,
			qp_wormhole_verifier::C,
			{ qp_wormhole_verifier::D },
		>::from_bytes(proof_bytes, &verifier.circuit_data.common)
		.map_err(|e| {
			crate::error::QuantusError::Generic(format!("Failed to deserialize proof: {:?}", e))
		})?;

		log_print!("\nPublic inputs count: {}", proof.public_inputs.len());

		let pi = qp_wormhole_verifier::parse_public_inputs(&proof).map_err(|e| {
			crate::error::QuantusError::Generic(format!("Failed to parse public inputs: {}", e))
		})?;

		log_print!("\n=== Parsed Leaf Public Inputs ===");
		log_print!("Asset ID: {}", pi.asset_id);
		log_print!("Output Amount 1: {}", pi.output_amount_1);
		log_print!("Output Amount 2: {}", pi.output_amount_2);
		log_print!("Volume Fee BPS: {}", pi.volume_fee_bps);
		log_print!("Nullifier: 0x{}", hex::encode(pi.nullifier.as_ref()));
		log_print!("Exit Account 1: 0x{}", hex::encode(pi.exit_account_1.as_ref()));
		log_print!("Exit Account 2: 0x{}", hex::encode(pi.exit_account_2.as_ref()));
		log_print!("Block Hash: 0x{}", hex::encode(pi.block_hash.as_ref()));
		log_print!("Block Number: {}", pi.block_number);

		// Verify if requested
		if verify {
			log_print!("\n=== Verifying Proof ===");
			match verifier.verify(proof) {
				Ok(()) => {
					log_success!("Proof verification PASSED");
				},
				Err(e) => {
					log_error!("Proof verification FAILED: {}", e);
					return Err(crate::error::QuantusError::Generic(format!(
						"Proof verification failed: {}",
						e
					)));
				},
			}
		}
	}

	Ok(())
}

/// A pending wormhole output that can be used as input for the next dissolve layer.
#[derive(Clone)]
struct DissolveOutput {
	/// The secret used to derive the wormhole address
	secret: [u8; 32],
	/// Amount in planck
	amount: u128,
	/// Transfer count from the NativeTransferred event
	transfer_count: u64,
	/// Funding account (sender)
	funding_account: SubxtAccountId,
	/// Block hash where the transfer was recorded (needed for storage proof)
	proof_block_hash: subxt::utils::H256,
	/// ZK trie leaf index for Merkle proof lookup
	leaf_index: u64,
}

impl Drop for DissolveOutput {
	fn drop(&mut self) {
		crate::wallet::keystore::zeroize_bytes(&mut self.secret);
	}
}

impl std::fmt::Debug for DissolveOutput {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.debug_struct("DissolveOutput")
			.field("secret", &"<redacted>")
			.field("amount", &self.amount)
			.field("transfer_count", &self.transfer_count)
			.field("funding_account", &self.funding_account)
			.field("proof_block_hash", &self.proof_block_hash)
			.field("leaf_index", &self.leaf_index)
			.finish()
	}
}

/// Dissolve a large wormhole deposit into many small outputs for better privacy.
///
/// Creates a tree of wormhole transactions where each layer doubles the number of outputs
/// by splitting each input into 2 via the dual-output proof mechanism.
///
/// ```text
/// Layer 0: 1 input  → 2 outputs
/// Layer 1: 2 inputs → 4 outputs
/// Layer 2: 4 inputs → 8 outputs
/// ...
/// Layer N: 2^(N-1) inputs → 2^N outputs (all below target_size)
/// ```
///
/// Each layer: batch inputs into groups of ≤DEFAULT_NUM_LEAF_PROOFS, generate proofs, aggregate,
/// verify on-chain. The final outputs are small enough to blend with the miner reward noise floor.
#[allow(clippy::too_many_arguments)]
async fn run_dissolve(
	amount: u128,
	target_size: u128,
	wallet_name: String,
	password: Option<String>,
	password_file: Option<String>,
	keep_files: bool,
	output_dir: String,
	node_url: &str,
	execution_mode: ExecutionMode,
) -> crate::error::Result<()> {
	use colored::Colorize;

	log_print!("");
	log_print!("==================================================");
	log_print!("  Wormhole Dissolve");
	log_print!("==================================================");
	log_print!("");

	// Calculate number of layers needed
	let mut num_outputs = 1u128;
	let mut layers = 0usize;
	while amount / num_outputs > target_size {
		num_outputs *= 2;
		layers += 1;
	}
	let final_output_count = num_outputs as usize;

	log_print!("  Amount: {} ({})", amount, format_balance(amount));
	log_print!("  Target size: {} ({})", target_size, format_balance(target_size));
	log_print!("  Layers: {}", layers);
	log_print!("  Final outputs: {}", final_output_count);
	log_print!(
		"  Approximate output size: {} ({})",
		amount / num_outputs,
		format_balance(amount / num_outputs)
	);
	log_print!("");

	// Load wallet (reuse multiround wallet loader for HD derivation)
	let wallet = load_multiround_wallet(&wallet_name, password, password_file)?;
	let funding_account = wallet.wallet_account_id.clone();

	// Connect to node
	let quantus_client = QuantusClient::new(node_url)
		.await
		.map_err(|e| crate::error::QuantusError::Generic(format!("Failed to connect: {}", e)))?;
	let minting_account = get_minting_account(quantus_client.client()).await?;

	// Create output directory
	std::fs::create_dir_all(&output_dir).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to create output directory: {}", e))
	})?;

	let bins_dir = crate::bins::ensure_bins_dir()?;
	let agg_config = CircuitBinsConfig::load(&bins_dir).map_err(|e| {
		crate::error::QuantusError::Generic(format!(
			"Failed to load aggregation circuit config: {}",
			e
		))
	})?;

	// === Layer 0: Initial funding ===
	log_print!("{}", "Layer 0: Initial funding".bright_yellow());

	let initial_secret = derive_wormhole_secret(&wallet.mnemonic, 0, 1)?;
	let wormhole_address = SubxtAccountId(*initial_secret.address());

	let tip_block_hash = wormhole_tip_block(&quantus_client, execution_mode)
		.await
		.map_err(|e| {
			crate::error::QuantusError::Generic(format!(
				"Failed to get tip block for dissolve transfer count: {}",
				e
			))
		})?
		.hash();
	let transfer_count_before = quantus_client
		.client()
		.storage()
		.at(tip_block_hash)
		.fetch(&quantus_node::api::storage().wormhole().transfer_count(wormhole_address.clone()))
		.await
		.map_err(|e| {
			crate::error::QuantusError::Generic(format!(
				"Failed to fetch transfer count for initial dissolve address: {}",
				e
			))
		})?
		.unwrap_or(0);

	// Transfer to the wormhole address
	let transfer_tx = quantus_node::api::tx().balances().transfer_allow_death(
		subxt::ext::subxt_core::utils::MultiAddress::Id(wormhole_address.clone()),
		amount,
	);

	let quantum_keypair = QuantumKeyPair {
		public_key: wallet.keypair.public_key.clone(),
		private_key: wallet.keypair.private_key.clone(),
		scheme: wallet.keypair.scheme,
	};

	let (_tx_hash, included_in) = crate::cli::common::submit_transaction_with_inclusion_block(
		&quantus_client,
		&quantum_keypair,
		transfer_tx,
		None,
		wormhole_inclusion_mode(execution_mode),
	)
	.await
	.map_err(|e| crate::error::QuantusError::Generic(format!("Initial transfer failed: {}", e)))?;

	// Read events from the transaction's own inclusion block; the tip may already
	// have moved past it by the time we query.
	let block_hash = included_in.ok_or_else(|| {
		crate::error::QuantusError::Generic(
			"Initial transfer watch returned no inclusion block".to_string(),
		)
	})?;
	let events_api =
		quantus_client.client().events().at(block_hash).await.map_err(|e| {
			crate::error::QuantusError::Generic(format!("Failed to get events: {}", e))
		})?;
	let transfer_events: Vec<wormhole::events::NativeTransferred> = events_api
		.find::<wormhole::events::NativeTransferred>()
		.filter_map(|e| e.ok())
		.collect();
	let expected_initial = [ExpectedTransferEvent {
		wormhole_address: wormhole_address.clone(),
		funding_account: Some(funding_account.clone()),
		amount: Some(amount),
		transfer_count: Some(transfer_count_before),
		leaf_index: None,
	}];
	let initial_transfer =
		parse_expected_transfer_events(&transfer_events, &expected_initial, block_hash)?
			.into_iter()
			.next()
			.ok_or_else(|| {
				crate::error::QuantusError::Generic("No initial transfer event found".to_string())
			})?;

	let mut current_outputs = vec![DissolveOutput {
		secret: *initial_secret.secret().as_bytes(),
		amount: initial_transfer.amount,
		transfer_count: initial_transfer.transfer_count,
		funding_account: initial_transfer.funding_account,
		proof_block_hash: block_hash,
		leaf_index: initial_transfer.leaf_index,
	}];

	log_success!("  Funded 1 wormhole address with {}", format_balance(amount));

	// === Layers 1..N: Split outputs ===
	for layer in 1..=layers {
		let num_inputs = current_outputs.len();
		let layer_dir = format!("{}/layer{}", output_dir, layer);
		std::fs::create_dir_all(&layer_dir).map_err(|e| {
			crate::error::QuantusError::Generic(format!("Failed to create layer directory: {}", e))
		})?;

		log_print!("");
		log_print!(
			"{} Layer {}/{}: {} inputs → {} outputs {}",
			">>>".bright_blue(),
			layer,
			layers,
			num_inputs,
			num_inputs * 2,
			"<<<".bright_blue()
		);

		// Derive secrets for this layer's outputs (2 per input)
		let mut next_secrets: Vec<WormholePair> = Vec::new();
		for i in 0..(num_inputs * 2) {
			next_secrets.push(derive_wormhole_secret(&wallet.mnemonic, layer, i + 1)?);
		}

		// Process inputs in batches (aggregation batch size from config)
		let batch_size = agg_config.num_leaf_proofs;
		let mut all_next_outputs: Vec<DissolveOutput> = Vec::new();
		let num_batches = num_inputs.div_ceil(batch_size);

		for batch_idx in 0..num_batches {
			let batch_start = batch_idx * batch_size;
			let batch_end = (batch_start + batch_size).min(num_inputs);
			let batch_inputs = &current_outputs[batch_start..batch_end];
			let batch_num_proofs = batch_inputs.len();

			log_print!("  Batch {}/{}: {} proofs", batch_idx + 1, num_batches, batch_num_proofs);

			// Each input splits into 2 outputs (equal split)
			let mut proof_files = Vec::new();
			let proof_gen_start = std::time::Instant::now();

			// All inputs in a batch must use the same block for proof generation.
			// Use the proof_block_hash from the first input (all inputs in a batch
			// were created in the same verification block from the previous layer).
			let batch_proof_block_hash = batch_inputs[0].proof_block_hash;
			let mut expected_child_outputs: Vec<([u8; 32], ExpectedTransferEvent)> = Vec::new();

			for (i, input) in batch_inputs.iter().enumerate() {
				let global_idx = batch_start + i;
				let exit_1_idx = global_idx * 2;
				let exit_2_idx = global_idx * 2 + 1;

				let input_quantized = quantize_funding_amount(input.amount)
					.map_err(crate::error::QuantusError::Generic)?;
				let total_output = compute_output_amount(input_quantized, VOLUME_FEE_BPS);
				let output_1 = total_output / 2;
				let output_2 = total_output - output_1;

				let assignment = ProofOutputAssignment {
					output_amount_1: output_1.max(1),
					exit_account_1: *next_secrets[exit_1_idx].address(),
					output_amount_2: output_2.max(1),
					exit_account_2: *next_secrets[exit_2_idx].address(),
				};
				expected_child_outputs.push((
					*next_secrets[exit_1_idx].secret().as_bytes(),
					ExpectedTransferEvent {
						wormhole_address: SubxtAccountId(*next_secrets[exit_1_idx].address()),
						funding_account: Some(minting_account.clone()),
						amount: Some((assignment.output_amount_1 as u128) * SCALE_DOWN_FACTOR),
						transfer_count: None,
						leaf_index: None,
					},
				));
				expected_child_outputs.push((
					*next_secrets[exit_2_idx].secret().as_bytes(),
					ExpectedTransferEvent {
						wormhole_address: SubxtAccountId(*next_secrets[exit_2_idx].address()),
						funding_account: Some(minting_account.clone()),
						amount: Some((assignment.output_amount_2 as u128) * SCALE_DOWN_FACTOR),
						transfer_count: None,
						leaf_index: None,
					},
				));

				let proof_file = format!("{}/batch{}_proof{}.hex", layer_dir, batch_idx, i);

				// Bind the hex-encoded secret so it can be wiped instead of
				// dropping as a temporary.
				let mut secret_hex = hex::encode(input.secret);
				let proof_result = generate_proof(
					&secret_hex,
					input.amount,
					&assignment,
					&format!("0x{}", hex::encode(batch_proof_block_hash.0)),
					input.transfer_count,
					&format!("0x{}", hex::encode(input.funding_account.0)),
					input.leaf_index, // ZK trie leaf index for Merkle proof lookup
					&proof_file,
					&quantus_client,
				)
				.await;
				crate::wallet::keystore::zeroize_string(&mut secret_hex);
				proof_result?;

				proof_files.push(proof_file);
			}

			let proof_gen_elapsed = proof_gen_start.elapsed();
			log_print!(
				"    Proof generation: {:.2}s ({} proofs)",
				proof_gen_elapsed.as_secs_f64(),
				batch_num_proofs
			);

			// Aggregate
			log_print!("    Aggregating...");
			let aggregated_file = format!("{}/batch{}_aggregated.hex", layer_dir, batch_idx);
			aggregate_proofs_to_file(&proof_files, &aggregated_file)?;

			// Verify on-chain
			log_print!("    Verifying on-chain...");
			let (verification_block, _extrinsic_hash, transfer_events) =
				verify_private_batch_and_get_events_until(
					&aggregated_file,
					&quantus_client,
					wormhole_inclusion_stage(execution_mode),
				)
				.await?;

			log_success!("    Verified in block 0x{}", hex::encode(verification_block.0));

			// Collect next layer's outputs from the transfer events.
			// Use the verification_block as the proof_block_hash for the next layer.
			let expected_events: Vec<ExpectedTransferEvent> =
				expected_child_outputs.iter().map(|(_, expected)| expected.clone()).collect();
			let parsed_outputs = parse_expected_transfer_events(
				&transfer_events,
				&expected_events,
				verification_block,
			)?;

			for ((secret, _expected), transfer) in
				expected_child_outputs.into_iter().zip(parsed_outputs.into_iter())
			{
				all_next_outputs.push(DissolveOutput {
					secret,
					amount: transfer.amount,
					transfer_count: transfer.transfer_count,
					funding_account: transfer.funding_account,
					proof_block_hash: verification_block,
					leaf_index: transfer.leaf_index,
				});
			}
		}

		log_print!("  Layer {} complete: {} outputs", layer, all_next_outputs.len());

		current_outputs = all_next_outputs;
	}

	// Summary
	log_print!("");
	log_print!("==================================================");
	log_success!("  Dissolve complete!");
	log_print!("==================================================");
	log_print!("");
	log_print!("  Final outputs: {}", current_outputs.len());
	let min_output = current_outputs.iter().map(|o| o.amount).min().unwrap_or(0);
	let max_output = current_outputs.iter().map(|o| o.amount).max().unwrap_or(0);
	let total_output: u128 = current_outputs.iter().map(|o| o.amount).sum();
	log_print!(
		"  Output range: {} - {} ({})",
		format_balance(min_output),
		format_balance(max_output),
		format_balance(total_output)
	);

	if keep_files {
		log_print!("  Proof files preserved in: {}", output_dir);
	} else {
		log_print!("  Cleaning up proof files...");
		std::fs::remove_dir_all(&output_dir).ok();
	}

	Ok(())
}

/// Collect miner rewards from a wormhole address.
///
/// This mirrors the withdrawal flow from the miner app:
/// 1. Query Subsquid for pending transfers to the wormhole address
/// 2. Filter out already-spent transfers (nullifier check)
/// 3. Generate ZK proofs for each transfer
/// 4. Aggregate proofs
/// 5. Submit withdrawal transaction
#[allow(clippy::too_many_arguments)]
async fn run_collect_rewards(
	wallet_name: Option<String>,
	mnemonic_file_arg: Option<String>,
	secret_file_arg: Option<String>,
	password: Option<String>,
	password_file: Option<String>,
	amount: Option<f64>,
	destination: Option<String>,
	subsquid_url: String,
	wormhole_index: usize,
	dry_run: bool,
	node_url: &str,
	at_block: Option<u32>,
) -> crate::error::Result<()> {
	use crate::collect_rewards_lib::{
		collect_rewards, CollectRewardsConfig, ProgressCallback, WormholeCredential,
	};
	use colored::Colorize;

	log_print!("");
	log_print!("==================================================");
	log_print!("  Wormhole Collect Rewards");
	log_print!("==================================================");
	log_print!("");

	// Get credential and wallet address from wallet, mnemonic file, or secret file
	let (credential, wallet_address) = if let Some(wallet_name) = wallet_name {
		// Load from stored wallet
		let wallet = load_multiround_wallet(&wallet_name, password, password_file)?;
		(
			WormholeCredential::Mnemonic { phrase: wallet.mnemonic, wormhole_index },
			Some(wallet.wallet_address),
		)
	} else if let Some(mnemonic_file) = mnemonic_file_arg {
		let mnemonic =
			read_mnemonic_file(&mnemonic_file).map_err(crate::error::QuantusError::Generic)?;
		(WormholeCredential::Mnemonic { phrase: mnemonic, wormhole_index }, None)
	} else if let Some(secret_file) = secret_file_arg {
		// Use provided secret file directly (no HD derivation)
		let secret =
			read_secret_hex_file(&secret_file).map_err(crate::error::QuantusError::Generic)?;
		(WormholeCredential::Secret { hex: secret }, None)
	} else {
		return Err(crate::error::QuantusError::Generic(
			"Either --wallet, --mnemonic-file, or --secret-file must be provided".to_string(),
		));
	};

	// Destination address - required when using mnemonic-file or secret file directly
	let destination_address = if let Some(dest) = &destination {
		dest.clone()
	} else if let Some(addr) = wallet_address.as_ref() {
		addr.clone()
	} else {
		return Err(crate::error::QuantusError::Generic(
			"--destination is required when using --mnemonic-file or --secret-file".to_string(),
		));
	};

	// Convert amount from DEV to planck
	let amount_planck = amount.map(|a| (a * 1_000_000_000_000.0) as u128);

	// Print initial info
	if let Some(ref addr) = wallet_address {
		log_print!("  Wallet:            {}", addr.bright_yellow());
	} else {
		match &credential {
			WormholeCredential::Mnemonic { .. } => {
				log_print!("  Wallet:            {}", "(from mnemonic)".bright_yellow());
			},
			WormholeCredential::Secret { .. } => {
				log_print!("  Wallet:            {}", "(from secret)".bright_yellow());
			},
		}
	}
	match &credential {
		WormholeCredential::Mnemonic { wormhole_index, .. } => {
			log_print!("  Wormhole index:    {}", wormhole_index);
		},
		WormholeCredential::Secret { .. } => {
			log_print!("  Wormhole index:    {}", "(N/A - using direct secret)".dimmed());
		},
	}
	log_print!("  Destination:       {}", destination_address.bright_green());
	log_print!("  Subsquid URL:      {}", subsquid_url);
	log_print!("  Node URL:          {}", node_url);
	log_print!("");

	// Create CLI progress callback
	struct CliProgress;
	impl ProgressCallback for CliProgress {
		fn on_step(&self, step: &str, details: &str) {
			use colored::Colorize;
			match step {
				"derive" => log_print!("{}", format!("Step 1: {}...", details).bright_yellow()),
				"query" => log_print!("{}", format!("Step 2: {}...", details).bright_yellow()),
				"connect" => log_print!("{}", format!("Step 3: {}...", details).bright_yellow()),
				"nullifiers" => log_print!("{}", format!("Step 4: {}...", details).bright_yellow()),
				"proofs" => log_print!("{}", format!("Step 5: {}...", details).bright_yellow()),
				"submit" => log_print!("{}", format!("Step 6: {}...", details).bright_yellow()),
				_ => log_print!("  {}: {}", step, details),
			}
		}
		fn on_proof_generated(&self, index: usize, total: usize) {
			log_print!("  [{}/{}] Proof generated", index, total);
		}
		fn on_batch_submitted(&self, batch_index: usize, total_batches: usize, amount: u128) {
			use colored::Colorize;
			log_print!(
				"  Batch {}/{}: {} withdrawn",
				batch_index,
				total_batches,
				format_balance(amount).bright_cyan()
			);
		}
		fn on_error(&self, message: &str) {
			log_error!("{}", message);
		}
	}

	let config = CollectRewardsConfig {
		credential,
		destination_address: destination_address.clone(),
		subsquid_url,
		node_url: node_url.to_string(),
		bins_dir: crate::bins::ensure_bins_dir()?.to_string_lossy().into_owned(),
		amount: amount_planck,
		dry_run,
		at_block,
	};

	let result = collect_rewards(config, &CliProgress)
		.await
		.map_err(|e| crate::error::QuantusError::Generic(e.message))?;

	// Show summary
	log_print!("");
	if result.total_withdrawn > 0 {
		log_print!("{}", "Withdrawal complete!".bright_green().bold());
		log_print!(
			"  Total withdrawn: {} across {} batch(es)",
			format_balance(result.total_withdrawn).bright_cyan(),
			result.batches.len()
		);
		log_print!("  Transfers processed: {}", result.transfers_processed);
		log_print!("  Destination: {}", destination_address.bright_green());

		for (i, batch) in result.batches.iter().enumerate() {
			log_print!(
				"  Batch {}: {} (tx: 0x{}...)",
				i + 1,
				format_balance(batch.amount_withdrawn).bright_cyan(),
				&batch.tx_hash[..16]
			);
		}
	} else if dry_run {
		log_print!("{}", "Dry run complete - no transactions submitted.".bright_blue());
		log_print!("  Transfers available: {}", result.transfers_processed);
	} else {
		log_print!("{}", "No transfers to withdraw.".bright_yellow());
	}

	Ok(())
}

/// Helper to aggregate proof files and write the result (used by dissolve command)
fn aggregate_proofs_to_file(proof_files: &[String], output_file: &str) -> crate::error::Result<()> {
	use qp_wormhole_aggregator::private_batch::prover::PrivateBatchProver;

	let bins_dir = crate::bins::ensure_bins_dir()?;
	let common_data = load_leaf_common_data(&bins_dir)?;

	let mut proofs = Vec::with_capacity(proof_files.len());
	for proof_file in proof_files {
		let proof_bytes = read_hex_proof_file_to_bytes(proof_file)?;
		let proof = ProofWithPublicInputs::<F, C, D>::from_bytes(proof_bytes, &common_data)
			.map_err(|e| {
				crate::error::QuantusError::Generic(format!(
					"Failed to deserialize proof from {}: {:?}",
					proof_file, e
				))
			})?;
		proofs.push(proof);
	}

	let prover = PrivateBatchProver::new_from_binaries_dir(&bins_dir).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to create private-batch prover: {}", e))
	})?;

	let agg_start = std::time::Instant::now();
	let proof = prover
		.aggregate(proofs)
		.map_err(|e| crate::error::QuantusError::Generic(format!("Aggregation failed: {}", e)))?;
	let agg_elapsed = agg_start.elapsed();
	log_print!("    Aggregation: {:.2}s", agg_elapsed.as_secs_f64());

	let proof_hex = hex::encode(proof.to_bytes());
	std::fs::write(output_file, &proof_hex).map_err(|e| {
		crate::error::QuantusError::Generic(format!("Failed to write proof: {}", e))
	})?;

	Ok(())
}

// =============================================================================
// FUZZ TEST FUNCTIONS - TEMPORARILY DISABLED
// =============================================================================
//
// The fuzz tests below are temporarily disabled during the migration from MPT
// storage proofs to ZK tree Merkle proofs. To re-enable:
//
// 1. Deploy pallet-zk-tree to a test chain
// 2. Update run_fuzz_test() to use zkTree_getMerkleProof RPC instead of state_getReadProof
// 3. Update try_generate_fuzz_proof() to use the new PrivateCircuitInputs fields:
//    - zk_tree_root: [u8; 32]
//    - zk_merkle_siblings: Vec<[[u8; 32]; 3]>
//    - zk_merkle_positions: Vec<u8>
// 4. Note: The ZK leaf no longer contains `from` (funding_account) - it's now: (to: AccountId,
//    transfer_count: u64, asset_id: u32, amount: u32)
// 5. Update generate_fuzz_cases() to remove from-address fuzzing since it's no longer in the leaf
//
// See qp-zk-circuits/wormhole/tests/src/prover/prover_tests.rs for examples of
// how to construct ZK Merkle proofs for testing.
// =============================================================================

// TODO: Re-enable fuzz tests once ZK tree is deployed
// The old implementation used:
// - state_getReadProof RPC to fetch MPT storage proofs
// - prepare_proof_for_circuit() to process proofs
// - PrivateCircuitInputs with funding_account and storage_proof fields
//
// The new implementation should:
// - Use zkTree_getMerkleProof RPC
// - Directly use ZkMerkleProofRpc response (siblings, positions)
// - Use PrivateCircuitInputs with zk_tree_root, zk_merkle_siblings, zk_merkle_positions

/// Check if nullifiers have been spent by querying Subsquid.
///
/// Given a secret (or wallet) and transfer count(s), computes the nullifier(s) and checks
/// if they exist in the indexer (meaning the transfer was already withdrawn).
async fn run_check_nullifier(
	secret_file: Option<String>,
	wallet_name: Option<String>,
	password: Option<String>,
	password_file: Option<String>,
	wormhole_index: usize,
	transfer_counts_arg: String,
	subsquid_url: String,
) -> crate::error::Result<()> {
	use crate::subsquid::{compute_address_hash, SubsquidClient};
	use colored::Colorize;

	// Get secret either directly from a file or from wallet
	let secret = if let Some(path) = secret_file {
		let hex = read_secret_hex_file(&path).map_err(crate::error::QuantusError::Generic)?;
		parse_secret_hex(&hex).map_err(crate::error::QuantusError::Generic)?
	} else if let Some(wallet) = wallet_name {
		// Load wallet and derive wormhole secret
		let wallet_manager = WalletManager::new()?;
		let wallet_password = password::get_wallet_password(&wallet, password, password_file)?;
		let mut wallet_data = wallet_manager.load_wallet(&wallet, &wallet_password)?;

		let mnemonic = wallet_data.take_mnemonic().ok_or_else(|| {
			crate::error::QuantusError::Generic(
				"Wallet does not contain a mnemonic. Use --secret-file instead.".to_string(),
			)
		})?;

		// Derive wormhole secret using HD path for miner rewards (purpose = 1)
		let path = format!("m/44'/{}/0'/1'/{}'", QUANTUS_WORMHOLE_CHAIN_ID, wormhole_index);
		let wormhole_pair = derive_wormhole_from_mnemonic(&mnemonic, None, &path).map_err(|e| {
			crate::error::QuantusError::Generic(format!("HD derivation failed: {:?}", e))
		})?;

		let secret: [u8; 32] = *wormhole_pair.secret().as_bytes();
		log_print!("Derived wormhole secret from wallet '{}' (index {})", wallet, wormhole_index);
		secret
	} else {
		return Err(crate::error::QuantusError::Generic(
			"Either --secret-file or --wallet must be provided".to_string(),
		));
	};

	// Parse transfer counts (single number or range like "0-10")
	let transfer_counts: Vec<u64> = if transfer_counts_arg.contains('-') {
		let parts: Vec<&str> = transfer_counts_arg.split('-').collect();
		if parts.len() != 2 {
			return Err(crate::error::QuantusError::Generic(
				"Invalid range format. Use 'start-end' (e.g., '0-10')".to_string(),
			));
		}
		let start: u64 = parts[0].parse().map_err(|_| {
			crate::error::QuantusError::Generic(format!("Invalid start number: {}", parts[0]))
		})?;
		let end: u64 = parts[1].parse().map_err(|_| {
			crate::error::QuantusError::Generic(format!("Invalid end number: {}", parts[1]))
		})?;
		(start..=end).collect()
	} else {
		vec![transfer_counts_arg.parse().map_err(|_| {
			crate::error::QuantusError::Generic(format!(
				"Invalid transfer count: {}",
				transfer_counts_arg
			))
		})?]
	};

	log_print!("{}", "Checking Nullifiers".bright_cyan());
	log_print!("  Transfer counts: {:?}", transfer_counts);
	log_print!("  Subsquid URL: {}", subsquid_url);
	log_print!("");

	// Compute nullifiers for each transfer count
	let mut nullifiers_to_check: Vec<(String, String, u64)> = Vec::new(); // (nullifier_hex, nullifier_hash, transfer_count)

	for tc in &transfer_counts {
		let nullifier = wormhole_lib::compute_nullifier(&secret, *tc).map_err(|e| {
			crate::error::QuantusError::Generic(format!(
				"Failed to compute nullifier for transfer_count {}: {}",
				tc, e.message
			))
		})?;
		let nullifier_hex = hex::encode(nullifier);
		let nullifier_hash = compute_address_hash(&nullifier);
		nullifiers_to_check.push((nullifier_hex, nullifier_hash, *tc));
	}

	// Query Subsquid
	let client = SubsquidClient::new(subsquid_url)?;

	// Build prefix queries (8 char prefix for privacy)
	let prefix_len = 8;
	let nullifier_pairs: Vec<(String, String)> = nullifiers_to_check
		.iter()
		.map(|(nul, hash, _)| (nul.clone(), hash.clone()))
		.collect();

	let spent_set = client.check_nullifiers_spent(&nullifier_pairs, prefix_len).await?;

	// Display results
	log_print!("{}", "Results:".bright_yellow());
	let mut spent_count = 0;
	let mut unspent_count = 0;

	for (nullifier_hex, _nullifier_hash, tc) in &nullifiers_to_check {
		let is_spent = spent_set.contains(nullifier_hex);
		if is_spent {
			log_print!(
				"  [{}] transfer_count={}: {} (nullifier: 0x{}...)",
				"SPENT".bright_red(),
				tc,
				"Already withdrawn".red(),
				&nullifier_hex[..16]
			);
			spent_count += 1;
		} else {
			log_print!(
				"  [{}] transfer_count={}: {} (nullifier: 0x{}...)",
				"UNSPENT".bright_green(),
				tc,
				"Available for withdrawal".green(),
				&nullifier_hex[..16]
			);
			unspent_count += 1;
		}
	}

	log_print!("");
	log_print!(
		"Summary: {} spent, {} unspent out of {} checked",
		spent_count,
		unspent_count,
		nullifiers_to_check.len()
	);

	Ok(())
}

#[cfg(test)]
mod tests {
	use super::*;
	use qp_zk_circuits_common::zk_merkle::MAX_DEPTH;
	use serde_json::json;
	use std::collections::HashSet;
	use tempfile::NamedTempFile;

	fn hash_bytes(seed: u16) -> Vec<u8> {
		let mut out = vec![0u8; 32];
		for (i, byte) in out.iter_mut().enumerate() {
			*byte = seed.wrapping_add(i as u16) as u8;
		}
		out
	}

	/// #160110: oversized/mismatched Merkle proof RPC payloads must fail deserialization.
	#[test]
	fn malicious_zk_merkle_rpc_rejects_oversized_mismatched_depth() {
		let sibling_levels: Vec<_> = (0..=u8::MAX as u16)
			.map(|level| {
				vec![
					hash_bytes(level.wrapping_mul(3)),
					hash_bytes(level.wrapping_mul(3).wrapping_add(1)),
					hash_bytes(level.wrapping_mul(3).wrapping_add(2)),
				]
			})
			.collect();

		let malicious_rpc_response = json!({
			"leaf_index": 7_u64,
			"leaf_data": [42_u8],
			"leaf_hash": hash_bytes(900),
			"siblings": sibling_levels,
			"root": hash_bytes(901),
			"depth": 1_u8
		});

		let err = serde_json::from_value::<ZkMerkleProofRpc>(malicious_rpc_response)
			.expect_err("oversized mismatched Merkle proof must be rejected");
		let message = err.to_string();
		assert!(
			message.contains("exceeds max") ||
				message.contains("expected 60 bytes") ||
				message.contains("does not match siblings length"),
			"unexpected rejection reason: {message}"
		);
		assert!(
			MAX_DEPTH < u8::MAX as usize,
			"test assumes circuit MAX_DEPTH is below attacker-supplied depth"
		);
	}

	#[test]
	fn zk_merkle_rpc_rejects_depth_sibling_mismatch() {
		let siblings = vec![vec![hash_bytes(1), hash_bytes(2), hash_bytes(3)]];
		let response = json!({
			"leaf_index": 1_u64,
			"leaf_data": vec![0_u8; 60],
			"leaf_hash": hash_bytes(10),
			"siblings": siblings,
			"root": hash_bytes(11),
			"depth": 2_u8
		});
		let err = serde_json::from_value::<ZkMerkleProofRpc>(response)
			.expect_err("depth must match siblings length");
		assert!(err.to_string().contains("does not match siblings length"));
	}

	#[test]
	fn recursive_flows_align_tip_reads_with_tx_wait_mode() {
		// Funding/verify wait for best-block inclusion by default; tip reads and
		// ZK Merkle proofs must use the same tip (best vs finalized), or freshly
		// written leaves are missing from the tree.
		assert_eq!(IncludedAt::Finalized.label(), "finalized block");
		assert_ne!(IncludedAt::Best.label(), IncludedAt::Finalized.label());
		let _: *const () = at_finalized_block as *const ();
		let _: *const () = at_best_block as *const ();
		assert_eq!(wormhole_inclusion_stage(ExecutionMode::default()), TransactionStage::Included);
		assert_eq!(
			wormhole_inclusion_stage(ExecutionMode {
				finalized: true,
				wait_for_transaction: false,
			}),
			TransactionStage::Finalized
		);
	}

	#[test]
	fn unsigned_verify_submitters_use_bounded_inclusion_wait() {
		// The unbounded `while let Some(Ok(status)) = tx_progress.next()` loops
		// must stay gone; unsigned verify shares wait_tx_inclusion's deadlines.
		let source = include_str!("wormhole.rs");
		let private_fn = source
			.split("pub async fn submit_unsigned_verify_private_batch_until")
			.nth(1)
			.and_then(|s| s.split("pub async fn ").next())
			.expect("private batch submitter");
		let public_fn = source
			.split("pub async fn submit_unsigned_verify_public_batch_until")
			.nth(1)
			.and_then(|s| s.split("pub async fn ").next())
			.expect("public batch submitter");
		for body in [private_fn, public_fn] {
			assert!(
				body.contains("wait_tx_inclusion"),
				"unsigned verify must use the bounded wait_tx_inclusion helper"
			);
			assert!(
				!body.contains("tx_progress.next().await"),
				"unsigned verify must not wait on an unbounded status stream"
			);
			// Match arms may mention Finalized for passthrough; the wait helper
			// must still receive the normalized `stage` local, not a Finalized literal.
			assert!(
				body.contains("&tx_hash,\n\t\tstage,\n\t)"),
				"wait_tx_inclusion must receive the caller-selected stage parameter"
			);
		}
	}

	#[test]
	fn test_compute_output_amount() {
		// 0.1% fee (10 bps): output = input * 9990 / 10000
		assert_eq!(compute_output_amount(1000, 10), 999);
		assert_eq!(compute_output_amount(10000, 10), 9990);

		// 1% fee (100 bps): output = input * 9900 / 10000
		assert_eq!(compute_output_amount(1000, 100), 990);
		assert_eq!(compute_output_amount(10000, 100), 9900);

		// 0% fee
		assert_eq!(compute_output_amount(1000, 0), 1000);

		// Edge cases
		assert_eq!(compute_output_amount(0, 10), 0);
		assert_eq!(compute_output_amount(1, 10), 0); // rounds down
		assert_eq!(compute_output_amount(100, 10), 99);
	}

	#[test]
	fn test_parse_secret_hex() {
		// Valid hex with and without 0x prefix
		let secret = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
		assert!(parse_secret_hex(secret).is_ok());
		assert!(parse_secret_hex(&format!("0x{}", secret)).is_ok());

		// Wrong length
		assert!(parse_secret_hex("0123456789abcdef").unwrap_err().contains("32 bytes"));

		// Invalid hex characters
		assert!(parse_secret_hex("ghij".repeat(16).as_str())
			.unwrap_err()
			.contains("Invalid secret hex"));
	}

	#[test]
	fn test_parse_exit_account() {
		// Valid hex account
		let hex = "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
		assert!(parse_exit_account(hex).is_ok());

		// Wrong length
		assert!(parse_exit_account("0x0123456789abcdef").unwrap_err().contains("32 bytes"));

		// Invalid SS58
		assert!(parse_exit_account("not_valid").unwrap_err().contains("Invalid SS58"));
	}

	#[test]
	fn test_quantize_funding_amount() {
		// Basic quantization: 1 token (12 decimals) -> 100 (2 decimals)
		assert_eq!(quantize_funding_amount(1_000_000_000_000).unwrap(), 100);

		// Zero and small amounts
		assert_eq!(quantize_funding_amount(0).unwrap(), 0);
		assert_eq!(quantize_funding_amount(5_000_000_000).unwrap(), 0); // < 10^10

		// Max valid and overflow
		let max_valid = (u32::MAX as u128) * SCALE_DOWN_FACTOR;
		assert_eq!(quantize_funding_amount(max_valid).unwrap(), u32::MAX);
		assert!(quantize_funding_amount(max_valid + SCALE_DOWN_FACTOR)
			.unwrap_err()
			.contains("exceeds u32::MAX"));
	}

	#[test]
	fn test_proof_file_roundtrip() {
		let temp_file = NamedTempFile::new().unwrap();
		let path = temp_file.path().to_str().unwrap();
		let proof_bytes = vec![0x01, 0x02, 0x03, 0xaa, 0xbb, 0xcc];

		write_proof_file(path, &proof_bytes).unwrap();
		assert_eq!(read_proof_file(path).unwrap(), proof_bytes);
	}

	#[test]
	fn test_read_proof_file_errors() {
		// File not found
		assert!(read_proof_file("/nonexistent/path/proof.hex")
			.unwrap_err()
			.contains("Failed to read"));

		// Invalid hex content
		let temp_file = NamedTempFile::new().unwrap();
		std::fs::write(temp_file.path(), "not valid hex!").unwrap();
		assert!(read_proof_file(temp_file.path().to_str().unwrap())
			.unwrap_err()
			.contains("Failed to decode"));
	}

	#[test]
	fn test_fee_calculation_edge_cases() {
		// Test the circuit fee constraint: output_amount * 10000 <= input_amount * (10000 -
		// volume_fee_bps) This is equivalent to: output <= input * (1 - fee_rate)
		// VOLUME_FEE_BPS is 4 → keep factor 9996/10000.

		// Small amounts where fee rounds down
		let input_small: u32 = 100;
		let output_small = compute_output_amount(input_small, VOLUME_FEE_BPS);
		assert_eq!(output_small, 99);
		// Verify constraint: 99 * 10000 = 990000 <= 100 * 9996 = 999600 ✓
		assert!(
			(output_small as u64) * 10000 <= (input_small as u64) * (10000 - VOLUME_FEE_BPS as u64)
		);

		// Medium amounts: 10000 * 9996 / 10000 = 9996
		let input_medium: u32 = 10000;
		let output_medium = compute_output_amount(input_medium, VOLUME_FEE_BPS);
		assert_eq!(output_medium, 9996);
		assert!(
			(output_medium as u64) * 10000 <=
				(input_medium as u64) * (10000 - VOLUME_FEE_BPS as u64)
		);

		// Large amounts near u32::MAX
		let input_large: u32 = u32::MAX / 2;
		let output_large = compute_output_amount(input_large, VOLUME_FEE_BPS);
		assert!(
			(output_large as u64) * 10000 <= (input_large as u64) * (10000 - VOLUME_FEE_BPS as u64)
		);

		// Test with different fee rates
		for fee_bps in [0u32, 1, 10, 50, 100, 500, 1000] {
			let input: u32 = 100000;
			let output = compute_output_amount(input, fee_bps);
			assert!(
				(output as u64) * 10000 <= (input as u64) * (10000 - fee_bps as u64),
				"Fee constraint violated for fee_bps={}: {} * 10000 > {} * {}",
				fee_bps,
				output,
				input,
				10000 - fee_bps
			);
		}
	}

	#[test]
	fn test_nullifier_determinism() {
		use qp_wormhole_circuit::nullifier::Nullifier;
		use qp_zk_circuits_common::utils::BytesDigest;

		let secret: BytesDigest = [1u8; 32].try_into().expect("valid secret");
		let transfer_count = 42u64;

		// Generate nullifier multiple times - should be identical
		let nullifier1 = Nullifier::from_preimage(secret, transfer_count);
		let nullifier2 = Nullifier::from_preimage(secret, transfer_count);
		let nullifier3 = Nullifier::from_preimage(secret, transfer_count);

		assert_eq!(nullifier1.hash, nullifier2.hash);
		assert_eq!(nullifier2.hash, nullifier3.hash);

		// Different transfer count should produce different nullifier
		let nullifier_different = Nullifier::from_preimage(secret, transfer_count + 1);
		assert_ne!(nullifier1.hash, nullifier_different.hash);

		// Different secret should produce different nullifier
		let different_secret: BytesDigest = [2u8; 32].try_into().expect("valid secret");
		let nullifier_different_secret = Nullifier::from_preimage(different_secret, transfer_count);
		assert_ne!(nullifier1.hash, nullifier_different_secret.hash);
	}

	#[test]
	fn test_unspendable_account_determinism() {
		use qp_wormhole_circuit::unspendable_account::UnspendableAccount;
		use qp_zk_circuits_common::utils::BytesDigest;

		let secret: BytesDigest = [1u8; 32].try_into().expect("valid secret");

		// Generate unspendable account multiple times - should be identical
		let account1 = UnspendableAccount::from_secret(secret);
		let account2 = UnspendableAccount::from_secret(secret);

		assert_eq!(account1.account_id, account2.account_id);

		// Different secret should produce different account
		let different_secret: BytesDigest = [2u8; 32].try_into().expect("valid secret");
		let account_different = UnspendableAccount::from_secret(different_secret);
		assert_ne!(account1.account_id, account_different.account_id);
	}

	// Note: Integration tests for proof generation, serialization, aggregation, and
	// multi-account aggregation have been moved to qp-zk-circuits/wormhole/tests/
	// where the test-helpers crate (with TestInputs) is available as a workspace dep.

	/// Test that public inputs parsing matches expected structure
	#[test]
	fn test_public_inputs_structure() {
		use qp_wormhole_inputs::{
			ASSET_ID_INDEX, BLOCK_HASH_END_INDEX, BLOCK_HASH_START_INDEX, BLOCK_NUMBER_INDEX,
			EXIT_ACCOUNT_1_END_INDEX, EXIT_ACCOUNT_1_START_INDEX, EXIT_ACCOUNT_2_END_INDEX,
			EXIT_ACCOUNT_2_START_INDEX, NULLIFIER_END_INDEX, NULLIFIER_START_INDEX,
			OUTPUT_AMOUNT_1_INDEX, OUTPUT_AMOUNT_2_INDEX, PUBLIC_INPUTS_FELTS_LEN,
			VOLUME_FEE_BPS_INDEX,
		};

		// Verify expected public inputs layout for dual-output circuit
		assert_eq!(PUBLIC_INPUTS_FELTS_LEN, 21, "Public inputs should be 21 field elements");
		assert_eq!(ASSET_ID_INDEX, 0, "Asset ID should be first");
		assert_eq!(OUTPUT_AMOUNT_1_INDEX, 1, "Output amount 1 should be at index 1");
		assert_eq!(OUTPUT_AMOUNT_2_INDEX, 2, "Output amount 2 should be at index 2");
		assert_eq!(VOLUME_FEE_BPS_INDEX, 3, "Volume fee BPS should be at index 3");
		assert_eq!(NULLIFIER_START_INDEX, 4, "Nullifier should start at index 4");
		assert_eq!(NULLIFIER_END_INDEX, 8, "Nullifier should end at index 8");
		assert_eq!(EXIT_ACCOUNT_1_START_INDEX, 8, "Exit account 1 should start at index 8");
		assert_eq!(EXIT_ACCOUNT_1_END_INDEX, 12, "Exit account 1 should end at index 12");
		assert_eq!(EXIT_ACCOUNT_2_START_INDEX, 12, "Exit account 2 should start at index 12");
		assert_eq!(EXIT_ACCOUNT_2_END_INDEX, 16, "Exit account 2 should end at index 16");
		assert_eq!(BLOCK_HASH_START_INDEX, 16, "Block hash should start at index 16");
		assert_eq!(BLOCK_HASH_END_INDEX, 20, "Block hash should end at index 20");
		assert_eq!(BLOCK_NUMBER_INDEX, 20, "Block number should be at index 20");
	}

	/// Test that constants match expected on-chain configuration
	#[test]
	fn test_constants_match_chain_config() {
		// Volume fee rate must match on-chain VolumeFeeRateBps (4 bps).
		assert_eq!(VOLUME_FEE_BPS, 4, "Volume fee should be 4 bps");

		// Native asset ID should be 0
		assert_eq!(NATIVE_ASSET_ID, 0, "Native asset ID should be 0");

		// Scale down factor should be 10^10 (12 decimals -> 2 decimals)
		assert_eq!(SCALE_DOWN_FACTOR, 10_000_000_000, "Scale down factor should be 10^10");

		// Verify scale down: 1 token with 12 decimals = 10^12 units
		// After quantization: 10^12 / 10^10 = 100 (which is 1.00 in 2 decimal places)
		let one_token_12_decimals: u128 = 1_000_000_000_000;
		let quantized = quantize_funding_amount(one_token_12_decimals).unwrap();
		assert_eq!(quantized, 100, "1 token should quantize to 100 (1.00 with 2 decimals)");
	}

	#[test]
	fn test_volume_fee_bps_constant() {
		// Ensure VOLUME_FEE_BPS matches on-chain VolumeFeeRateBps (4 bps).
		assert_eq!(VOLUME_FEE_BPS, 4);
	}

	#[test]
	fn test_aggregation_config_deserialization_matches_upstream_format() {
		// This test verifies that our local AggregationConfig struct can deserialize
		// the same JSON format that the upstream CircuitBinsConfig produces.
		// If the upstream adds/removes/renames fields, this test will catch it.
		let json = r#"{
			"num_leaf_proofs": 8,
			"num_private_batch_proofs": null
		}"#;

		let config: CircuitBinsConfig = serde_json::from_str(json).unwrap();
		assert_eq!(config.num_leaf_proofs, 8);
		assert_eq!(config.num_private_batch_proofs, None);

		// Legacy config.json files (pre-rename) must still deserialize via the
		// serde alias on the upstream field.
		let legacy_json = r#"{
			"num_leaf_proofs": 8,
			"num_layer0_proofs": 4
		}"#;

		let legacy: CircuitBinsConfig = serde_json::from_str(legacy_json).unwrap();
		assert_eq!(legacy.num_private_batch_proofs, Some(4));
	}

	fn mk_accounts(n: usize) -> Vec<[u8; 32]> {
		(0..n)
			.map(|i| {
				let mut a = [0u8; 32];
				a[0] = (i as u8).wrapping_add(1); // avoid [0;32]
				a
			})
			.collect()
	}

	fn proof_outputs_for_inputs(input_amounts: &[u128], fee_bps: u32) -> Vec<u32> {
		input_amounts
			.iter()
			.map(|&input| {
				let input_quantized = quantize_funding_amount(input).unwrap_or(0);
				compute_output_amount(input_quantized, fee_bps)
			})
			.collect()
	}

	fn total_output_for_inputs(input_amounts: &[u128], fee_bps: u32) -> u64 {
		proof_outputs_for_inputs(input_amounts, fee_bps)
			.into_iter()
			.map(|x| x as u64)
			.sum()
	}

	/// Find some input that yields at least `min_out` quantized output after fee.
	/// Keeps tests robust even if quantization constants change.
	fn find_input_for_min_output(fee_bps: u32, min_out: u32) -> u128 {
		let mut input: u128 = 1;
		for _ in 0..80 {
			let q = quantize_funding_amount(input).unwrap_or(0);
			let out = compute_output_amount(q, fee_bps);
			if out >= min_out {
				return input;
			}
			// grow fast but safely
			input = input.saturating_mul(10);
		}
		panic!("Could not find input producing output >= {}", min_out);
	}

	// --------------------------
	// random_partition tests
	// --------------------------

	#[test]
	fn random_partition_n0() {
		let parts = random_partition(100, 0, 1);
		assert!(parts.is_empty());
	}

	#[test]
	fn random_partition_n1() {
		let total = 12345u128;
		let parts = random_partition(total, 1, 9999);
		assert_eq!(parts, vec![total]);
	}

	#[test]
	fn random_partition_total_less_than_min_total_falls_back_to_equalish() {
		// total < min_per_part * n => fallback path
		let total = 5u128;
		let n = 10usize;
		let min_per_part = 1u128;

		let parts = random_partition(total, n, min_per_part);

		assert_eq!(parts.len(), n);
		assert_eq!(parts.iter().sum::<u128>(), total);

		// fallback behavior: per_part=0, remainder=5, last gets remainder
		for part in parts.iter().take(n - 1) {
			assert_eq!(*part, 0);
		}
		assert_eq!(parts[n - 1], 5);
	}

	#[test]
	fn random_partition_min_achievable_invariants_hold() {
		let total = 100u128;
		let n = 10usize;
		let min_per_part = 3u128;

		for _ in 0..200 {
			let parts = random_partition(total, n, min_per_part);
			assert_eq!(parts.len(), n);
			assert_eq!(parts.iter().sum::<u128>(), total);
			assert!(parts.iter().all(|&p| p >= min_per_part));
		}
	}

	#[test]
	fn random_partition_distributable_zero_all_min() {
		let n = 10usize;
		let min_per_part = 3u128;
		let total = min_per_part * n as u128;

		let parts = random_partition(total, n, min_per_part);

		assert_eq!(parts.len(), n);
		assert_eq!(parts.iter().sum::<u128>(), total);
		assert!(parts.iter().all(|&p| p == min_per_part));
	}

	// --------------------------
	// compute_random_output_assignments tests
	// --------------------------

	#[test]
	fn compute_random_output_assignments_empty_inputs_or_targets() {
		let targets = mk_accounts(3);
		assert!(compute_random_output_assignments(&[], &targets, 0).unwrap().is_empty());

		let inputs = vec![1u128, 2u128, 3u128];
		assert!(compute_random_output_assignments(&inputs, &[], 0).unwrap().is_empty());
	}

	#[test]
	fn compute_random_output_assignments_basic_invariants() {
		let fee_bps = 0u32;

		// ensure non-zero outputs for meaningful checks
		let input = find_input_for_min_output(fee_bps, 5);
		let input_amounts = vec![input, input, input, input, input];
		let targets = mk_accounts(4);

		let assignments =
			compute_random_output_assignments(&input_amounts, &targets, fee_bps).unwrap();
		assert_eq!(assignments.len(), input_amounts.len());

		let proof_outputs = proof_outputs_for_inputs(&input_amounts, fee_bps);

		// per-proof sum matches
		for (i, a) in assignments.iter().enumerate() {
			let per_proof_sum = a.output_amount_1 as u64 + a.output_amount_2 as u64;
			assert_eq!(per_proof_sum, proof_outputs[i] as u64);

			// If an output amount is non-zero, the account must be in targets
			if a.output_amount_1 > 0 {
				assert!(targets.contains(&a.exit_account_1));
			} else {
				// if amount is zero, account can be zero or anything; current impl keeps default
				// [0;32]
			}
			if a.output_amount_2 > 0 {
				assert!(targets.contains(&a.exit_account_2));
				assert_ne!(a.exit_account_2, a.exit_account_1); // should be different if both used
			} else {
				// current impl keeps default [0;32]
				assert_eq!(a.exit_account_2, [0u8; 32]);
			}
		}

		// total sum matches
		let total_assigned: u64 = assignments
			.iter()
			.map(|a| a.output_amount_1 as u64 + a.output_amount_2 as u64)
			.sum();

		let total_expected = total_output_for_inputs(&input_amounts, fee_bps);
		assert_eq!(total_assigned, total_expected);
	}

	#[test]
	fn compute_random_output_assignments_more_targets_than_capacity_still_conserves_funds() {
		// Capacity: each proof can hit at most 2 targets, so distinct-used-targets <= 2 *
		// num_proofs. Set num_targets > 2*num_proofs and ensure total_output >= num_targets so
		// the partition *wants* to give each target >= 1 (though algorithm can't satisfy it).
		let fee_bps = 0u32;
		let num_proofs = 1usize;
		let num_targets = 5usize;

		let input = find_input_for_min_output(fee_bps, 10); // ensure total_output is "big enough"
		let input_amounts = vec![input; num_proofs];
		let targets = mk_accounts(num_targets);

		let assignments =
			compute_random_output_assignments(&input_amounts, &targets, fee_bps).unwrap();
		assert_eq!(assignments.len(), num_proofs);

		// total preserved
		let total_assigned: u64 = assignments
			.iter()
			.map(|a| a.output_amount_1 as u64 + a.output_amount_2 as u64)
			.sum();
		let total_expected = total_output_for_inputs(&input_amounts, fee_bps);
		assert_eq!(total_assigned, total_expected);

		// used targets bounded by 2*num_proofs and thus < num_targets
		let mut used = HashSet::new();
		for a in &assignments {
			if a.output_amount_1 > 0 {
				used.insert(a.exit_account_1);
			}
			if a.output_amount_2 > 0 {
				used.insert(a.exit_account_2);
			}
		}
		assert!(used.len() <= 2 * num_proofs);
		assert!(used.len() < num_targets);
	}

	#[test]
	fn compute_random_output_assignments_total_output_less_than_num_targets_does_not_panic_and_conserves(
	) {
		// This forces random_partition into its fallback branch inside
		// compute_random_output_assignments because min_per_target = 1 and total_output <
		// num_targets.
		let fee_bps = 0u32;

		let num_targets = 50usize;
		let targets = mk_accounts(num_targets);

		// Try to get very small total output: two proofs with output likely >= 1 each,
		// but still far less than 50.
		let input = find_input_for_min_output(fee_bps, 1);
		let input_amounts = vec![input, input];

		let assignments =
			compute_random_output_assignments(&input_amounts, &targets, fee_bps).unwrap();
		assert_eq!(assignments.len(), input_amounts.len());

		let total_assigned: u64 = assignments
			.iter()
			.map(|a| a.output_amount_1 as u64 + a.output_amount_2 as u64)
			.sum();
		let total_expected = total_output_for_inputs(&input_amounts, fee_bps);
		assert_eq!(total_assigned, total_expected);

		// For each assignment: if non-zero amount then account must be in targets.
		for a in &assignments {
			if a.output_amount_1 > 0 {
				assert!(targets.contains(&a.exit_account_1));
			}
			if a.output_amount_2 > 0 {
				assert!(targets.contains(&a.exit_account_2));
				assert_ne!(a.exit_account_2, a.exit_account_1);
			}
		}
	}

	/// Wrapper so `WormholeCommands` can be parsed directly via clap in tests.
	#[derive(clap::Parser, Debug)]
	struct CollectRewardsTestCli {
		#[command(subcommand)]
		cmd: WormholeCommands,
	}

	fn try_parse_collect_rewards(extra_args: &[&str]) -> Result<WormholeCommands, clap::Error> {
		use clap::Parser;
		let mut args = vec!["test", "collect-rewards"];
		args.extend_from_slice(extra_args);
		CollectRewardsTestCli::try_parse_from(args).map(|cli| cli.cmd)
	}

	#[test]
	fn collect_rewards_requires_one_credential() {
		let err = try_parse_collect_rewards(&[]).unwrap_err();
		let s = err.to_string();
		assert!(
			s.contains("--wallet") || s.contains("--mnemonic-file") || s.contains("--secret-file"),
			"expected missing-credential error, got: {s}"
		);
	}

	#[test]
	fn collect_rewards_accepts_each_credential_alone() {
		assert!(try_parse_collect_rewards(&["--wallet", "w"]).is_ok());
		assert!(try_parse_collect_rewards(&["--mnemonic-file", "mnemonic.txt"]).is_ok());
		assert!(try_parse_collect_rewards(&["--secret-file", "secret.hex"]).is_ok());
	}

	#[test]
	fn collect_rewards_credentials_mutually_exclusive() {
		let pairs: &[(&str, &str, &str, &str)] = &[
			("--wallet", "w", "--mnemonic-file", "m"),
			("--wallet", "w", "--secret-file", "s"),
			("--mnemonic-file", "m", "--secret-file", "s"),
		];
		for (a, av, b, bv) in pairs {
			let err = try_parse_collect_rewards(&[a, av, b, bv]).unwrap_err().to_string();
			assert!(
				err.contains("cannot be used with"),
				"expected conflict error for {a} + {b}, got: {err}"
			);
		}
	}

	/// Mnemonic phrases must not be accepted on argv (use --mnemonic-file).
	#[test]
	fn collect_rewards_rejects_mnemonic_cli_argument() {
		let err = try_parse_collect_rewards(&["--mnemonic", "word ".repeat(24).trim()])
			.unwrap_err()
			.to_string();
		assert!(
			err.contains("unexpected argument") || err.contains("--mnemonic"),
			"expected --mnemonic to be rejected, got: {err}"
		);
	}

	/// #160103: wormhole secrets must not be accepted on argv (use --secret-file).
	#[test]
	fn wormhole_rejects_secret_cli_argument() {
		use clap::Parser;

		#[derive(Parser, Debug)]
		#[command(name = "quantus")]
		struct TestCli {
			#[command(subcommand)]
			command: crate::cli::Commands,
		}

		let secret = "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20";
		for args in [
			vec!["quantus", "wormhole", "address", "--secret", secret],
			vec![
				"quantus",
				"wormhole",
				"prove",
				"--secret",
				secret,
				"--amount",
				"1",
				"--exit-account",
				"0x1111111111111111111111111111111111111111111111111111111111111111",
				"--block",
				"0x2222222222222222222222222222222222222222222222222222222222222222",
				"--transfer-count",
				"0",
				"--leaf-index",
				"0",
				"--funding-account",
				"0x3333333333333333333333333333333333333333333333333333333333333333",
			],
			vec!["quantus", "wormhole", "collect-rewards", "--secret", secret],
			vec![
				"quantus",
				"wormhole",
				"check-nullifier",
				"--secret",
				secret,
				"--transfer-counts",
				"0",
			],
		] {
			let result = TestCli::try_parse_from(args.clone());
			assert!(result.is_err(), "wormhole must not accept --secret on argv; args={args:?}");
		}
	}

	fn acct(seed: u8) -> SubxtAccountId {
		SubxtAccountId([seed; 32])
	}

	#[test]
	fn missing_extrinsic_in_proof_verification_block_is_error() {
		// #160033: absent hash must not collapse to success=false / "no ProofVerified".
		let err = require_proof_verification_extrinsic_index(None)
			.expect_err("missing extrinsic must error");
		assert!(
			err.to_string().contains("Could not find submitted extrinsic"),
			"unexpected error: {err}"
		);
		assert_eq!(require_proof_verification_extrinsic_index(Some(2)).unwrap(), 2);
	}

	#[test]
	fn proof_verified_after_extrinsic_failed_stays_unsuccessful() {
		// Vulnerable order-dependent parser set success=true when ProofVerified
		// arrived after ExtrinsicFailed.
		let mut result =
			VerificationResult { success: false, exit_amount: None, error_message: None };
		apply_extrinsic_failed_to_result(&mut result, "Wormhole::InvalidProof".to_string());
		apply_proof_verified_to_result(&mut result, 42);
		assert!(!result.success, "ExtrinsicFailed must dominate later ProofVerified");
		assert_eq!(result.exit_amount, Some(42));
		assert_eq!(result.error_message.as_deref(), Some("Wormhole::InvalidProof"));
	}

	#[test]
	fn extrinsic_failed_after_proof_verified_clears_success() {
		let mut result =
			VerificationResult { success: false, exit_amount: None, error_message: None };
		apply_proof_verified_to_result(&mut result, 99);
		assert!(result.success);
		apply_extrinsic_failed_to_result(&mut result, "dispatch failed".to_string());
		assert!(!result.success, "later ExtrinsicFailed must clear success");
		assert!(result.error_message.is_some());
	}

	#[test]
	fn sdk_event_collection_errors_when_extrinsic_failed_even_if_proof_verified() {
		let transfers = vec![wormhole::events::NativeTransferred {
			from: acct(1),
			to: acct(2),
			amount: 10,
			transfer_count: 1,
			leaf_index: 1,
		}];
		let err = finalize_wormhole_event_collection(
			true,
			Some("Wormhole::InvalidProof".to_string()),
			transfers,
		)
		.expect_err("SDK helpers must not treat failed extrinsics as verified");
		assert!(err.to_string().contains("InvalidProof"));
	}

	#[test]
	fn parse_expected_transfer_events_binds_by_from_and_amount_not_destination_alone() {
		let shared_to = acct(0x42);
		let attacker_from = acct(0xA1);
		let intended_from = acct(0xB2);
		let block_hash = subxt::utils::H256([0xCC; 32]);

		let attacker_event = wormhole::events::NativeTransferred {
			from: attacker_from.clone(),
			to: shared_to.clone(),
			amount: 111,
			transfer_count: 7,
			leaf_index: 70,
		};
		let intended_event = wormhole::events::NativeTransferred {
			from: intended_from.clone(),
			to: shared_to.clone(),
			amount: 999_000,
			transfer_count: 42,
			leaf_index: 420,
		};

		// Destination-only first-match would pick the attacker event. With expected
		// from/amount/transfer_count the intended transfer must be selected instead.
		let expected = [ExpectedTransferEvent {
			wormhole_address: shared_to.clone(),
			funding_account: Some(intended_from.clone()),
			amount: Some(999_000),
			transfer_count: Some(42),
			leaf_index: None,
		}];
		let parsed = parse_expected_transfer_events(
			&[
				wormhole::events::NativeTransferred {
					from: attacker_from.clone(),
					to: shared_to.clone(),
					amount: 111,
					transfer_count: 7,
					leaf_index: 70,
				},
				intended_event,
			],
			&expected,
			block_hash,
		)
		.expect("expected attributes uniquely identify the intended transfer");

		assert_eq!(parsed.len(), 1);
		assert_eq!(parsed[0].funding_account, intended_from);
		assert_eq!(parsed[0].amount, 999_000);
		assert_eq!(parsed[0].transfer_count, 42);
		assert_eq!(parsed[0].leaf_index, 420);
		assert_ne!(parsed[0].funding_account, attacker_from);
		assert_ne!(parsed[0].amount, attacker_event.amount);

		// Destination-only public helper must refuse ambiguous duplicates.
		let ambiguous = parse_transfer_events(
			&[
				attacker_event,
				wormhole::events::NativeTransferred {
					from: intended_from,
					to: shared_to.clone(),
					amount: 999_000,
					transfer_count: 42,
					leaf_index: 420,
				},
			],
			&[shared_to],
			block_hash,
		);
		assert!(
			ambiguous.is_err(),
			"destination-only parse must not accept first-match among duplicate destinations"
		);
		assert!(
			ambiguous.unwrap_err().to_string().contains("Ambiguous"),
			"expected ambiguous-match error"
		);
	}

	#[tokio::test]
	#[serial_test::serial]
	async fn load_multiround_wallet_errors_when_wallet_has_no_mnemonic() {
		let home = tempfile::tempdir().unwrap();
		std::env::set_var("HOME", home.path());

		let wallet_manager = WalletManager::new().unwrap();
		wallet_manager.create_developer_wallet("crystal_alice").await.unwrap();
		let stored = wallet_manager.load_wallet("crystal_alice", "").unwrap();
		assert!(
			stored.mnemonic.is_none(),
			"developer wallet must exercise the no-mnemonic secret path"
		);

		match load_multiround_wallet("crystal_alice", None, None) {
			Ok(_) =>
				panic!("wallet without mnemonic must error instead of generating an ephemeral one"),
			Err(err) => {
				let msg = err.to_string();
				assert!(
					msg.contains("does not contain a mnemonic"),
					"expected mnemonic-required error, got: {msg}"
				);
			},
		}
	}
}