algo_ops 0.9.7

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

// Ensure the algonaut crate is referenced so this module is explicitly implemented with it.
// We keep most calls abstracted for now and will progressively replace stubs with concrete calls.
#[allow(unused_imports)]
use algonaut as _algonaut;

/// An optional outbound rate limit for algod/indexer calls.
///
/// Expresses a token bucket: at most `max_requests` outbound requests are allowed per
/// `per_millis` window, with the allowance refilling continuously (so up to `max_requests`
/// may burst before the steady rate applies). It is `Option`al on [`AlgoChainConfig`] and off
/// by default, so an unset limit leaves the call path unchanged. Plain integer fields (rather
/// than a `Duration`) keep it trivially serializable and settable from a config file.
///
/// This throttles the wrapper's *own* outbound requests to protect a metered endpoint; it does
/// not model the server's limits. A per-second server rate limit (HTTP 429) is still retried
/// with backoff by the call path — see [`AlgoOps::algod_call`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RateLimitConfig {
    /// Maximum requests granted per window; also the burst capacity.
    pub max_requests: u32,
    /// Window length in milliseconds over which `max_requests` tokens refill.
    pub per_millis: u64,
    /// What the limiter does when the bucket is empty. Defaults to [`RateLimitMode::Block`], so a
    /// config that predates this field (or omits it) keeps today's blocking behaviour.
    #[serde(default)]
    pub mode: RateLimitMode,
}

/// What the outbound rate limiter does when the token bucket is empty.
///
/// The default, [`Block`](RateLimitMode::Block), is today's behaviour — no consumer changes. A
/// latency-sensitive caller (e.g. a consensus loop that must not freeze) selects
/// [`Reject`](RateLimitMode::Reject) to be handed the wait and back off on its own terms.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum RateLimitMode {
    /// Sleep the calling thread until the bucket grants a token, then proceed. The request always
    /// eventually goes out; the caller is throttled by blocking.
    #[default]
    Block,
    /// Do not sleep: when the bucket is empty, fail fast with
    /// [`AlgoError::rate_limited`](crate::AlgoError::rate_limited) carrying the wait until the next
    /// token, consuming no token. The caller backs off / serves cached state itself.
    Reject,
}

/// A wall-clock daily request cap aligned to a configurable start-of-day, independent of
/// [`RateLimitConfig`].
///
/// The token bucket ([`RateLimitConfig`]) is a *burst clip* — it bounds the short-term rate but not
/// the total over a day. This bounds the per-day total instead, to stay under a metered provider's
/// per-IP daily request quota (which resets at a provider-defined start-of-day). The two are
/// orthogonal and may both be set: the bucket clips bursts, this caps the daily count.
///
/// It is `Option`al on [`AlgoChainConfig`] and off by default, so an unset budget leaves the call
/// path unchanged. Plain integer fields (rather than a `Duration`/time type) keep it trivially
/// serializable and settable from a config file, mirroring [`RateLimitConfig`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DailyBudgetConfig {
    /// Max requests granted per daily window.
    pub max_requests_per_day: u32,
    /// Start-of-day as a UTC seconds-of-day offset in `[0, 86_400)`: the window is
    /// `[k*86400 + offset, (k+1)*86400 + offset)`. `0` = 00:00 UTC. A consumer parsing a
    /// `HH:MM±TZ` day-start resolves it to this UTC offset before passing it in. A value at or
    /// beyond a full day is reduced modulo 86_400.
    pub day_start_offset_secs: u32,
}

/// Configuration for Algod and Indexer endpoints.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AlgoChainConfig {
    pub client_api_url: String,
    pub client_api_port: u16,
    pub indexer_api_url: String,
    pub indexer_api_port: u16,
    pub token: Option<String>,
    pub token_key: Option<String>,
    pub app_id: Option<u64>,
    pub asset_id: Option<u64>,
    /// Optional outbound rate limit applied to every algod/indexer request. `None` (the
    /// default) leaves calls unthrottled. Set it declaratively here, or at construction with
    /// [`AlgoOps::with_rate_limit`].
    #[serde(default)]
    pub rate_limit: Option<RateLimitConfig>,
    /// Optional wall-clock daily request budget, independent of [`rate_limit`](Self::rate_limit)
    /// (the bucket clips bursts; this caps the per-day total). `None` (the default) leaves the
    /// daily backstop off. Set it declaratively here, or at construction with
    /// [`AlgoOps::with_daily_budget`].
    #[serde(default)]
    pub daily_budget: Option<DailyBudgetConfig>,
}

impl Default for AlgoChainConfig {
    fn default() -> Self {
        // Defaults to localnet configuration matching the Kotlin implementation
        Self {
            client_api_url: "http://localhost".to_string(),
            client_api_port: 4001,
            indexer_api_url: "http://localhost".to_string(),
            indexer_api_port: 8980,
            token: Some(
                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string(),
            ),
            token_key: Some("X-Algo-API-Token".to_string()),
            app_id: None,
            asset_id: None,
            rate_limit: None,
            daily_budget: None,
        }
    }
}

/// Token-bucket limiter backing [`RateLimitConfig`]. Held behind an `Arc<Mutex<_>>` on
/// [`AlgoOps`] so it is shared across clones of a client — cloning must not multiply the
/// allowance against a metered endpoint.
///
/// `pub(crate)` in production; re-exported publicly only under `test-support` so its pure
/// [`poll`](RateLimiter::poll) logic can be unit-tested with injected `Instant`s.
#[cfg_attr(feature = "test-support", visibility::make(pub))]
#[derive(Debug)]
pub(crate) struct RateLimiter {
    /// Maximum tokens (burst capacity).
    capacity: f64,
    /// Tokens currently available; a request consumes one.
    tokens: f64,
    /// Tokens replenished per second.
    refill_per_sec: f64,
    /// When `tokens` was last refilled.
    last_refill: Instant,
}

impl RateLimiter {
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn new(cfg: &RateLimitConfig, now: Instant) -> Self {
        // Clamp to sane minimums so a zero in config cannot divide-by-zero or stall forever.
        let capacity = cfg.max_requests.max(1) as f64;
        let per_secs = (cfg.per_millis.max(1) as f64) / 1000.0;
        Self {
            capacity,
            tokens: capacity,
            refill_per_sec: capacity / per_secs,
            last_refill: now,
        }
    }

    /// Refill for the time elapsed since the last poll, then either consume a token and return
    /// [`Duration::ZERO`] (a request may proceed now) or return how long to wait before the next
    /// token is available. Passing `now` in keeps this pure and unit-testable.
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn poll(&mut self, now: Instant) -> Duration {
        let elapsed = now
            .saturating_duration_since(self.last_refill)
            .as_secs_f64();
        self.tokens = (self.tokens + elapsed * self.refill_per_sec).min(self.capacity);
        self.last_refill = now;
        if self.tokens >= 1.0 {
            self.tokens -= 1.0;
            Duration::ZERO
        } else {
            Duration::from_secs_f64((1.0 - self.tokens) / self.refill_per_sec)
        }
    }
}

/// Lock a `Mutex`, recovering the guard from a poisoned lock rather than panicking: a limiter
/// whose holder panicked mid-update still holds valid state we can keep enforcing with. Shared by
/// the token bucket and the daily budget on the per-request path.
fn lock_recover<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    match m.lock() {
        Ok(g) => g,
        Err(poisoned) => poisoned.into_inner(),
    }
}

/// Wall-clock daily-budget limiter backing [`DailyBudgetConfig`]. Parallel to [`RateLimiter`], but
/// counting per *day* (aligned to a configurable start-of-day) rather than refilling a token bucket
/// — it bounds the total requests in a window, independent of the burst clip.
///
/// Held behind an `Arc<Mutex<_>>` on [`AlgoOps`] so it is shared across clones of a client, like
/// [`RateLimiter`] — cloning must not multiply the daily allowance against a metered endpoint.
///
/// Split **check / record** so a request blocked by the *other* limiter (the token bucket) is not
/// charged here, and vice-versa. `now` is injected (unix seconds) so the pure window logic is
/// unit-testable without the wall clock.
///
/// Two intentional properties: `max == 0` blocks every request (`spent >= max` holds at
/// `spent == 0`), so it reads as "allow none" — a `None` config, not a zero one, means "off". And
/// because the lock is released between `check` and `record`, up to N concurrent requests racing the
/// boundary can admit a few over `max`; that is acceptable for a soft daily backstop set below the
/// provider's hard quota, not an exact semaphore.
///
/// `pub(crate)` in production; re-exported publicly only under `test-support` so its pure logic can
/// be unit-tested with injected clocks (like [`RateLimiter`]).
#[cfg_attr(feature = "test-support", visibility::make(pub))]
#[derive(Debug)]
pub(crate) struct DailyBudget {
    /// Max requests granted per daily window.
    max: u32,
    /// Start-of-day as a UTC seconds-of-day offset in `[0, 86_400)`.
    day_start_offset_secs: u32,
    /// Unix-seconds start of the window `spent` is counted against.
    window_start_unix: u64,
    /// Requests committed against the current window.
    spent: u32,
}

impl DailyBudget {
    /// The start (unix seconds) of the daily window containing `now` for a `day_start_offset_secs`
    /// offset: the greatest `k*86400 + offset <= now`. Uses floor division (`div_euclid`) so a
    /// `now` before the first post-epoch boundary does not underflow. (`86_400` = seconds per day.)
    fn window_start_for(now: u64, offset: u64) -> u64 {
        let k = (now as i64 - offset as i64).div_euclid(86_400);
        (k * 86_400 + offset as i64).max(0) as u64
    }

    /// Roll the window forward (or back) if `now` no longer falls in the current day-long window
    /// `[window_start, window_start + 86_400)`, recomputing the window and zeroing `spent`. A
    /// backward clock jump also recomputes the window rather than trapping `spent` in a stale one.
    fn roll(&mut self, now: u64) {
        let end = self.window_start_unix.saturating_add(86_400);
        if now < self.window_start_unix || now >= end {
            self.window_start_unix = Self::window_start_for(now, self.day_start_offset_secs as u64);
            self.spent = 0;
        }
    }

    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn new(cfg: &DailyBudgetConfig, now_unix_secs: u64, primed_spent: u32) -> Self {
        // Reduce the offset into `[0, 86_400)` so an out-of-range config cannot place the window
        // boundary outside a day.
        let day_start_offset_secs = cfg.day_start_offset_secs % 86_400;
        Self {
            max: cfg.max_requests_per_day,
            day_start_offset_secs,
            window_start_unix: Self::window_start_for(now_unix_secs, day_start_offset_secs as u64),
            spent: primed_spent,
        }
    }

    /// Peek: roll the window if `now` crossed the next day-start (zeroing `spent`), then report
    /// whether a request may proceed. Does **not** consume — see [`record`](Self::record). Returns
    /// `Err(wait)` with the time to the next day-start boundary when the budget is spent.
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn check(&mut self, now_unix_secs: u64) -> Result<(), Duration> {
        self.roll(now_unix_secs);
        if self.spent >= self.max {
            let end = self.window_start_unix.saturating_add(86_400);
            Err(Duration::from_secs(end.saturating_sub(now_unix_secs)))
        } else {
            Ok(())
        }
    }

    /// Commit one request against the current window (call only when the request actually goes
    /// out). Rolls the window first so a commit after a day boundary lands in the new window.
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn record(&mut self, now_unix_secs: u64) {
        self.roll(now_unix_secs);
        self.spent = self.spent.saturating_add(1);
    }
}

/// A snapshot of the daily-budget window for persistence, returned by
/// [`AlgoOps::daily_budget_state`]. A consumer persists `{window_start_unix, spent}` and, on boot,
/// restores `spent` with [`AlgoOps::with_daily_spent`] iff the persisted window still matches the
/// current one — resuming mid-day rather than from zero (a restart does not refill the provider's
/// quota).
#[derive(Debug, Clone, Copy)]
pub struct DailyBudgetState {
    /// Unix-seconds start of the current daily window.
    pub window_start_unix: u64,
    /// Requests committed against the current window.
    pub spent: u32,
    /// The configured per-window maximum.
    pub max: u32,
}

/// Neutral snapshot of the algod suggested transaction parameters, returned by
/// [`AlgoOps::suggested_params`].
///
/// Carries only plain types (no `algonaut` types on the boundary) so a consumer built against
/// a different `algonaut` version can size a payment without a version bump. These are the
/// fields a payment builder needs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AlgoSuggestedParams {
    /// The last committed round the node had seen when it suggested these params.
    pub last_round: u64,
    /// The network minimum transaction fee (not per byte), in microALGOs.
    pub min_fee: u64,
    /// The 32-byte genesis hash of the network.
    pub genesis_hash: [u8; 32],
    /// The genesis id string of the network (e.g. `"testnet-v1.0"`).
    pub genesis_id: String,
}

/// An account's balance and the minimum balance it must keep, both in µALGO — returned by
/// [`AlgoOps::account_funds`]. Plain types only, like [`AlgoSuggestedParams`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct AlgoAccountFunds {
    /// The account's total balance.
    pub amount: u64,
    /// The minimum balance algod requires the account to keep: the base minimum plus a step for
    /// every asset and application it has opted into or created.
    pub min_balance: u64,
}

impl AlgoAccountFunds {
    /// What the account can spend on fees and payments before algod rejects a transaction for
    /// taking it below its minimum: `amount - min_balance`, or zero when it is already below.
    pub fn spendable(&self) -> u64 {
        self.amount.saturating_sub(self.min_balance)
    }
}

// Neutral view of a pending or confirmed transaction. Defined in `blockchain_ops` alongside the
// `TransactionQueryOps` trait it is returned by; re-exported here so `algo_ops::ConfirmedTxn` and
// `crate::ops::ConfirmedTxn` keep resolving.
pub use blockchain_ops::ConfirmedTxn;

/// A confirmed transaction as seen by the incremental cached scanner
/// ([`AlgoOps::fetch_transactions_cached`]).
///
/// Unlike [`ConfirmedTxn`] it also carries the **sender**, so a caller can maintain one shared
/// scan (cached without a server-side sender filter) and restrict senders client-side — collapsing
/// a per-account query fan-out to a single scan. Carries only plain types (no `algonaut` types on
/// the boundary).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ScannedTxn {
    /// The round the transaction was confirmed in (always `> 0` — the scanner drops unconfirmed rows).
    pub confirmed_round: u64,
    /// The transaction's signer address, in standard Algorand address form.
    pub sender: String,
    /// The transaction note, decoded from its on-chain bytes; `None` if it carried no note.
    pub note: Option<Vec<u8>>,
}

/// An account opted into an application, as seen by the incremental cached account scanner
/// ([`AlgoOps::fetch_opted_in_accounts_cached`]).
///
/// The account-scan sibling of [`ScannedTxn`]. Carries the account address plus the account's
/// **decoded local state for the scanned app** — the same `(key, value)` shape
/// [`AlgoOps::local_state_for_account`] returns — so a caller decodes its own local-state field (a
/// membership bit, an endpoint byte-slice) without `algo_ops` knowing the schema. Carries only plain
/// types (no `algonaut` types on the boundary).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ScannedAccount {
    /// The account's address, in standard Algorand address form.
    pub address: String,
    /// The account's local-state key/values for the scanned app, decoded as
    /// [`AlgoOps::local_state_for_account`] decodes them; empty when the app holds no local state for
    /// the account. Since the scan is app-scoped, an account only surfaces here while it is opted in.
    pub local_state: Vec<(String, String)>,
}

/// Optional server-side narrowing for [`AlgoOps::fetch_transactions_cached`], so the incremental
/// fetch stays cheap. Every field is optional; an all-`None` filter scans every transaction.
///
/// This narrows the indexer query; the caller's `ingest` closure is still the client-side truth
/// (e.g. a defensive note-prefix re-check, or a sender restriction applied locally so one cache can
/// serve many senders).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TxnScanFilter {
    /// Restrict to transactions whose note *starts with* these raw bytes (the indexer's
    /// `note-prefix` filter; base64-encoded internally).
    pub note_prefix: Option<Vec<u8>>,
    /// Restrict to transactions signed by this address (indexer address role `sender`).
    pub sender: Option<String>,
    /// Restrict to transactions targeting this application id.
    pub app_id: Option<u64>,
}

impl TxnScanFilter {
    /// Pre-encode the filter once for a scan: note-prefix to base64 (the indexer's `note-prefix`
    /// query parameter), sender to a parsed [`algonaut::core::Address`]. Fails if the sender address
    /// is malformed.
    fn prepare(&self) -> Result<PreparedScanFilter> {
        Ok(PreparedScanFilter {
            note_prefix: self
                .note_prefix
                .as_ref()
                .map(|b| general_purpose::STANDARD.encode(b)),
            address: self
                .sender
                .as_deref()
                .map(AlgoOps::parse_address)
                .transpose()?,
            app_id: self.app_id.map(algonaut::core::AppId),
        })
    }
}

/// A caller-owned incremental scan cache: the last fully-scanned round, the freshness stamp, and the
/// accumulated caller-defined entries.
///
/// Append-only — confirmed transactions are immutable, so (unlike `bingle_core`'s accounts cache)
/// there is no re-lookup/eviction phase: a refresh fetches only rounds past [`last_round`] and pushes
/// the new hits. The cache is caller-owned and passed in (not held inside [`AlgoOps`]), so one process
/// holds one cache per use-case (per note-prefix / per app) and tests can inject prefilled caches.
///
/// Derives `Serialize`/`Deserialize` (when `T` does) so a caller can persist the cache across process
/// restarts and resume the incremental scan from the saved watermark rather than re-bootstrapping the
/// whole history.
///
/// [`last_round`]: TxnScanCache::last_round
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TxnScanCache<T> {
    /// The highest round the cache has scanned through — the indexer's `current-round` at the last
    /// refresh. The next incremental refresh fetches from `last_round + 1`. `0` before any scan.
    pub last_round: u64,
    /// Unix timestamp (seconds) of the last refresh that hit the network; `0` before any scan. Used
    /// to degrade a fresh [`QueryMode::Refresh`] to [`QueryMode::CacheOnly`].
    pub last_updated: u64,
    /// The accumulated caller-defined entries, in scan order (append-only).
    pub entries: Vec<T>,
}

impl<T> TxnScanCache<T> {
    /// An empty cache: no rounds scanned, no freshness stamp, no entries. The first
    /// [`QueryMode::Refresh`] against it performs a full scan.
    pub fn new() -> Self {
        TxnScanCache {
            last_round: 0,
            last_updated: 0,
            entries: Vec::new(),
        }
    }
}

impl<T> Default for TxnScanCache<T> {
    fn default() -> Self {
        TxnScanCache::new()
    }
}

/// A caller-owned incremental scan cache for the accounts opted into an application — the account-scan
/// sibling of [`TxnScanCache`], holding the accumulated account set (keyed by address) plus the
/// `last_round` / `last_updated` watermark.
///
/// Unlike the append-only [`TxnScanCache`] (confirmed transactions are immutable), an account's local
/// state can change, so this is **append-with-revisit**: an incremental refresh discovers which
/// accounts changed past [`last_round`] and re-reads only those, replacing (or, on opt-out, removing)
/// their entry. Entries are therefore keyed by address — `(address, caller entry)` pairs, deduplicated
/// by address — so a revisit updates in place rather than duplicating.
///
/// The cache is caller-owned and passed in (not held inside [`AlgoOps`]), so one process holds one
/// cache per use-case (per app) and tests can inject prefilled caches. Derives
/// `Serialize`/`Deserialize` (when `T` does) so a caller can persist it across restarts and resume the
/// incremental scan from the saved watermark rather than re-bootstrapping the whole set.
///
/// [`last_round`]: AccountScanCache::last_round
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AccountScanCache<T> {
    /// The round the cache has scanned through — the resume point the next incremental refresh
    /// discovers changes *after*. A full scan stamps this at the **minimum** `current-round` across its
    /// pages (not the max): `search_for_accounts` paginates by address over mutable accounts with no
    /// round pinning, so anchoring at the earliest page's round lets the next refresh re-catch any
    /// account changed mid-scan. An incremental refresh advances it to the max `current-round` of the
    /// (immutable, round-ordered) transaction index it scans. `0` before any scan.
    pub last_round: u64,
    /// Unix timestamp (seconds) of the last refresh that hit the network; `0` before any scan. Used
    /// to degrade a fresh [`QueryMode::Refresh`] to [`QueryMode::CacheOnly`].
    pub last_updated: u64,
    /// The accumulated caller-defined entries, each paired with its account address (the dedup key), in
    /// scan order. A `Vec` (not a map) to keep the serialized shape simple and match [`TxnScanCache`];
    /// the incremental refresh upserts/removes by a linear scan, so a use-case holding many thousands
    /// of accounts pays `O(entries)` per changed account on each refresh (fine while the changed set
    /// per poll is small).
    pub entries: Vec<(String, T)>,
}

impl<T> AccountScanCache<T> {
    /// An empty cache: no rounds scanned, no freshness stamp, no entries. The first
    /// [`QueryMode::Refresh`] against it performs a full scan.
    pub fn new() -> Self {
        AccountScanCache {
            last_round: 0,
            last_updated: 0,
            entries: Vec::new(),
        }
    }

    /// Reset the cache to its empty state — drops the accumulated entries and clears the watermark
    /// (`last_round` / `last_updated`) so the next [`QueryMode::Refresh`] re-bootstraps with a full
    /// scan. Equivalent to overwriting with [`AccountScanCache::new`], but as a method a caller can
    /// invoke through a lock guard without naming the field set (so the reset invariant lives with the
    /// type that owns it rather than being re-derived at each call site).
    pub fn clear(&mut self) {
        *self = AccountScanCache::new();
    }
}

impl<T> Default for AccountScanCache<T> {
    fn default() -> Self {
        AccountScanCache::new()
    }
}

/// How [`AlgoOps::fetch_transactions_cached`] should treat the cache on this call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueryMode {
    /// Refresh incrementally: fetch only rounds past the cache watermark, appending the new hits. If
    /// the cache is within its `cache_lifetime_secs` this degrades to [`QueryMode::CacheOnly`] (zero
    /// network); an empty cache does a full scan.
    Refresh,
    /// Never touch the network: run `scan` over whatever the cache already holds.
    CacheOnly,
    /// Discard the cache contents and rebuild it with a full scan from round 0.
    ForceFull,
}

/// One page of a cached transaction scan: the page's confirmed transactions, the next-page token
/// (`None` when the indexer reports no more results), and the indexer's `current-round` (the safe
/// refresh watermark). Returned by the page fetcher that
/// [`AlgoOps::fetch_transactions_cached`] drives; public so the engine can be unit-tested with a
/// stubbed fetcher.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TxnScanPage {
    /// The confirmed, in-scope transactions on this page.
    pub txns: Vec<ScannedTxn>,
    /// The indexer's pagination token for the following page, or `None` at the end of the results.
    pub next_token: Option<String>,
    /// The round at which the indexer computed these results — used as the cache watermark.
    pub current_round: u64,
}

/// One page of a full opted-in-account scan: the page's accounts, the next-page token (`None` at the
/// end of the results), and the indexer's `current-round` (the safe refresh watermark). Returned by
/// the full-scan page fetcher [`AlgoOps::fetch_opted_in_accounts_cached`] drives; public so the engine
/// can be unit-tested with a stubbed fetcher.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccountScanPage {
    /// The opted-in accounts on this page.
    pub accounts: Vec<ScannedAccount>,
    /// The indexer's pagination token for the following page, or `None` at the end of the results.
    pub next_token: Option<String>,
    /// The round at which the indexer computed these results — used as the cache watermark.
    pub current_round: u64,
}

/// One page of the change-discovery scan an incremental account refresh runs: the addresses touched by
/// app transactions past the watermark, the next-page token, and the indexer's `current-round`. The
/// account index has no min-round filter, so an incremental refresh finds *which* accounts to re-read
/// through the app-scoped transaction index instead. Returned by the change-discovery fetcher
/// [`AlgoOps::fetch_opted_in_accounts_cached`] drives; public so the engine can be unit-tested with a
/// stubbed fetcher.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChangedAddressesPage {
    /// The addresses touched by this page's transactions (senders and app-call account references,
    /// including inner transactions) — the accounts whose local state may have changed.
    pub addresses: Vec<String>,
    /// The indexer's pagination token for the following page, or `None` at the end of the results.
    pub next_token: Option<String>,
    /// The round at which the indexer computed these results — used as the cache watermark.
    pub current_round: u64,
}

/// Server-side filter pre-encoded once per scan: the note-prefix as base64 and the sender parsed to
/// an [`algonaut::core::Address`] the indexer call takes by reference.
struct PreparedScanFilter {
    note_prefix: Option<String>,
    address: Option<algonaut::core::Address>,
    app_id: Option<algonaut::core::AppId>,
}

/// Minimal key provider trait analogous to the Kotlin IKeyProvider interface.
pub trait KeyProvider: Send + Sync {
    fn get_id(&self) -> Option<String> {
        None
    }
    fn get_private_key(&self) -> Option<String> {
        None
    }
    fn save_private_key_object(&self, _address: &str, _passphrase: &str) {}
}

/// Which kind of request a retried call makes. It decides which HTTP statuses are retried and
/// names the operation in warnings and errors, so an indexer failure is not reported as algod's.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallKind {
    /// A request to algod: a read, or a transaction submission whose retry the caller decides.
    Algod,
    /// An indexer read (search or lookup). Idempotent, so an HTTP 500 is also retried.
    IndexerRead,
}

impl CallKind {
    /// The operation name used in warnings and in the [`AlgoError`] a failed call returns.
    pub fn operation(self) -> &'static str {
        match self {
            CallKind::Algod => "algod call",
            CallKind::IndexerRead => "indexer search",
        }
    }
}

/// Main operations struct analogous to Kotlin's AlgoOps.
#[derive(Debug, Clone)]
pub struct AlgoOps {
    pub passphrase: Option<String>,
    pub address: Option<String>,
    pub config: AlgoChainConfig,
    /// The live token bucket derived from `config.rate_limit`, or `None` when unthrottled.
    /// Behind an `Arc<Mutex<_>>` so `Clone`d handles share one bucket against the endpoint.
    rate_limiter: Option<Arc<Mutex<RateLimiter>>>,
    /// Total outbound algod/indexer requests issued through this client. Incremented once per real
    /// outbound request in [`algod_call`](Self::algod_call) or [`indexer_call`](Self::indexer_call)
    /// (each page, each retry). Behind an
    /// `Arc<AtomicU64>` so `Clone`d handles share one counter, like `rate_limiter`. Always present
    /// (independent of any rate limit); seeded by [`with_initial_request_count`](Self::with_initial_request_count).
    requests_made: Arc<AtomicU64>,
    /// The live wall-clock daily budget derived from `config.daily_budget`, or `None` when off.
    /// Behind an `Arc<Mutex<_>>` so `Clone`d handles share one daily count against the endpoint.
    daily_budget: Option<Arc<Mutex<DailyBudget>>>,
    /// A ceiling on how long any single algod/indexer call may take before it is cancelled and
    /// surfaced as a timeout error, set by [`with_timeout`](Self::with_timeout). `None` (the default)
    /// leaves calls unbounded — today's behaviour. Applied at the async→sync bridge
    /// ([`rt_block_on`](Self::rt_block_on)) so it bounds **every** call (both the `algonaut` client and
    /// the raw-`reqwest` reads), and cancels a stalled request rather than blocking the caller forever.
    timeout: Option<Duration>,
    /// Each application's creator address, keyed by app id, filled on first lookup by
    /// [`app_creator`](Self::app_creator) (which every app call uses to list the creator as a foreign
    /// account). An app's creator never changes, so an entry never goes stale and has no expiry. Behind
    /// an `Arc<Mutex<_>>` so `Clone`d handles share one cache, like `rate_limiter`.
    app_creators: Arc<Mutex<HashMap<u64, String>>>,
}

impl AlgoOps {
    /// Generate a new Algorand keypair (secure random) and return `(id, passphrase)`.
    ///
    /// - `id` is the Algorand base32 address derived from the public key.
    /// - `passphrase` is the 25-word Algorand mnemonic.
    pub fn generate_keypair() -> (String, String) {
        use ed25519_dalek::SigningKey;
        use rand_core::{OsRng, RngCore};

        // Generate a secure random 32-byte seed
        let mut rng = OsRng;
        let mut sk: [u8; 32] = [0u8; 32];
        rng.fill_bytes(&mut sk);

        // Derive public key and Algorand address
        let signing_key = SigningKey::from_bytes(&sk);
        let verifying_key = signing_key.verifying_key();
        let pk: [u8; 32] = verifying_key.to_bytes();
        let id =
            byte_key_to_address(&pk).expect("failed to derive Algorand address from public key");

        // Encode secret seed as 25-word mnemonic passphrase
        let passphrase =
            algonaut::crypto::mnemonic::from_key(&sk).expect("failed to generate mnemonic");
        (id, passphrase)
    }

    /// Derive the 32-byte ed25519 secret seed for a `passphrase`, accepting either a 25-word
    /// Algorand mnemonic or a legacy base64-encoded secret with a "b64:" prefix (used by tests).
    /// This is the single source of truth for passphrase → seed used by `new`,
    /// `address_from_passphrase`, and `private_key_bytes`.
    pub fn seed_from_passphrase(passphrase: &str) -> Result<[u8; 32]> {
        // Algorand 25-word mnemonic.
        if !passphrase.is_empty()
            && let Ok(key) = algonaut::crypto::mnemonic::to_key(passphrase)
        {
            return key
                .to_vec()
                .as_slice()
                .try_into()
                .map_err(|_| anyhow!("invalid passphrase: derived seed is not 32 bytes"));
        }

        // Legacy base64-encoded secret with a "b64:" prefix.
        if let Some(rest) = passphrase.strip_prefix("b64:") {
            let bytes = general_purpose::STANDARD
                .decode(rest)
                .map_err(|e| anyhow!("invalid passphrase: bad base64 secret ({e})"))?;
            return bytes
                .as_slice()
                .try_into()
                .map_err(|_| anyhow!("invalid passphrase: secret is not 32 bytes"));
        }

        bail!("invalid passphrase: expected a 25-word Algorand mnemonic")
    }

    /// Derive the Algorand address for an existing `passphrase`, without generating a new key.
    /// This is the inverse of `generate_keypair`. Returns an error if `passphrase` is not a valid
    /// Algorand mnemonic (or b64: secret).
    pub fn address_from_passphrase(passphrase: &str) -> Result<String> {
        use ed25519_dalek::SigningKey;

        let sk = Self::seed_from_passphrase(passphrase)?;
        let signing_key = SigningKey::from_bytes(&sk);
        let pk: [u8; 32] = signing_key.verifying_key().to_bytes();
        byte_key_to_address(&pk)
    }

    // Construction is sealed to the crate: consumers go through the
    // `AlgoOps::new_for_algorand` factory (see lib.rs). For indexer-only use,
    // construct with `new_for_algorand(None, None, config)`.
    pub(crate) fn new(
        passphrase: Option<String>,
        address: Option<String>,
        config: Option<AlgoChainConfig>,
    ) -> Self {
        // Use explicit config if provided; else Default (localnet)
        let config = config.unwrap_or_default();
        // Build the live limiter from config so a rate limit set declaratively (deserialized
        // config) is honoured, not only one set via `with_rate_limit`.
        let rate_limiter = config
            .rate_limit
            .as_ref()
            .map(|rl| Arc::new(Mutex::new(RateLimiter::new(rl, Instant::now()))));
        // Build the live daily budget from config so one set declaratively (deserialized config) is
        // honoured, not only one set via `with_daily_budget`. Starts from a fresh (zero-spent)
        // window; a consumer restores a running total with `with_daily_spent`.
        let daily_budget = config
            .daily_budget
            .as_ref()
            .map(|db| Arc::new(Mutex::new(DailyBudget::new(db, Self::now_unix_secs(), 0))));
        let mut ops = Self {
            passphrase,
            address,
            config,
            rate_limiter,
            requests_made: Arc::new(AtomicU64::new(0)),
            daily_budget,
            timeout: None,
            app_creators: Arc::new(Mutex::new(HashMap::new())),
        };

        // If no address was provided but we have a passphrase, derive the address immediately.
        // A malformed passphrase simply leaves the address unset (callers surface the error later).
        if ops.address.is_none()
            && let Some(ref pass) = ops.passphrase
            && let Ok(addr) = Self::address_from_passphrase(pass)
        {
            ops.address = Some(addr);
        }

        ops
    }

    /// Apply an outbound rate limit of at most `max` requests per `per` to every algod and
    /// indexer call this client makes, protecting a metered endpoint from a busy caller.
    ///
    /// A token bucket, so up to `max` requests may burst before the rate settles to `max`/`per`.
    /// Off by default: without this (and without [`AlgoChainConfig::rate_limit`]) the call path is
    /// unchanged. The limit is also recorded in `self.config.rate_limit` so it round-trips through
    /// a serialized config, and is shared across [`Clone`]d handles so cloning does not multiply
    /// the allowance. A builder-style method: `AlgoOps::new_for_algorand(..).with_rate_limit(..)`.
    ///
    /// Uses [`RateLimitMode::Block`] (sleep the caller until a token is free). For the non-blocking
    /// fail-fast behaviour, use [`with_rate_limit_mode`](Self::with_rate_limit_mode).
    pub fn with_rate_limit(self, max: u32, per: Duration) -> Self {
        self.with_rate_limit_mode(max, per, RateLimitMode::Block)
    }

    /// As [`with_rate_limit`](Self::with_rate_limit), but selects the [`RateLimitMode`]: `Block`
    /// sleeps the caller until a token frees; `Reject` fails fast with
    /// [`AlgoError::rate_limited`](crate::AlgoError::rate_limited) (carrying the wait) when the
    /// bucket is empty, so a latency-sensitive caller is never blocked on the rate limit.
    pub fn with_rate_limit_mode(mut self, max: u32, per: Duration, mode: RateLimitMode) -> Self {
        let cfg = RateLimitConfig {
            max_requests: max,
            per_millis: per.as_millis() as u64,
            mode,
        };
        self.rate_limiter = Some(Arc::new(Mutex::new(RateLimiter::new(&cfg, Instant::now()))));
        self.config.rate_limit = Some(cfg);
        self
    }

    /// Bound every algod/indexer call to at most `timeout`: a call that has not completed by then is
    /// cancelled (its in-flight request future is dropped, aborting the socket) and surfaces a timeout
    /// error, rather than blocking the caller indefinitely on a stalled connection.
    ///
    /// Off by default — without this a call waits forever for a hung endpoint, which on a caller's
    /// single-threaded event loop freezes the whole loop. The bound is applied at the async→sync bridge,
    /// so it covers both the `algonaut` client and the raw-`reqwest` reads uniformly. Shared across
    /// [`Clone`]d handles. A builder-style method: `AlgoOps::new_for_algorand(..).with_timeout(..)`.
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Total outbound algod/indexer requests issued through this client (and its clones — the
    /// counter is shared, like the rate limiter). Counts **every** request: each page of a paged
    /// fetch, and each retry. Monotonic; starts from the primed value (default 0, or whatever
    /// [`with_initial_request_count`](Self::with_initial_request_count) seeded).
    pub fn requests_made(&self) -> u64 {
        self.requests_made.load(Ordering::Relaxed)
    }

    /// Seed the request counter's starting value, for a consumer that persists a running total and
    /// must restore it into a freshly built client (config change) or across a process restart — a
    /// counter internal to an instance otherwise resets on both, letting a crash-loop re-spend the
    /// provider's quota. Chainable at construction.
    pub fn with_initial_request_count(self, count: u64) -> Self {
        self.requests_made.store(count, Ordering::Relaxed);
        self
    }

    /// Enable the wall-clock daily request cap. Independent of [`with_rate_limit`](Self::with_rate_limit)
    /// and friends — both may be set (burst clip + daily cap). Rejects with
    /// [`AlgoError::daily_budget_exceeded`](crate::AlgoError::daily_budget_exceeded) once
    /// `max_per_day` requests have gone out in the current window, resetting at the next day-start
    /// (`day_start_offset_secs` UTC seconds-of-day, `0` = 00:00 UTC). Also recorded in
    /// `self.config.daily_budget` so it round-trips through a serialized config, and shared across
    /// [`Clone`]d handles so cloning does not multiply the daily allowance.
    pub fn with_daily_budget(mut self, max_per_day: u32, day_start_offset_secs: u32) -> Self {
        let cfg = DailyBudgetConfig {
            max_requests_per_day: max_per_day,
            day_start_offset_secs,
        };
        self.daily_budget = Some(Arc::new(Mutex::new(DailyBudget::new(
            &cfg,
            Self::now_unix_secs(),
            0,
        ))));
        self.config.daily_budget = Some(cfg);
        self
    }

    /// Seed the current window's spent count — a consumer persisting `{window_start, spent}` restores
    /// it on boot so enforcement resumes mid-day rather than from zero (a restart does not refill the
    /// provider's quota). Pass `0` for a fresh window. A no-op without
    /// [`with_daily_budget`](Self::with_daily_budget) (or a `daily_budget` in the config). Chainable
    /// at construction, after `with_daily_budget`.
    pub fn with_daily_spent(self, spent: u32) -> Self {
        if let Some(daily) = &self.daily_budget {
            lock_recover(daily).spent = spent;
        }
        self
    }

    /// Snapshot the daily budget window for persistence — `{window_start_unix, spent, max}`. `None`
    /// when no daily budget is configured. The window is rolled to the current time first, so a read
    /// after a day boundary reports the fresh (zeroed) window rather than a stale one.
    pub fn daily_budget_state(&self) -> Option<DailyBudgetState> {
        let daily = self.daily_budget.as_ref()?;
        let mut guard = lock_recover(daily);
        guard.roll(Self::now_unix_secs());
        Some(DailyBudgetState {
            window_start_unix: guard.window_start_unix,
            spent: guard.spent,
            max: guard.max,
        })
    }

    /// Apply the optional outbound limiters before a request, then charge the request against them.
    /// A no-op (returns `Ok`) when neither a rate limit nor a daily budget is configured, so the
    /// default call path is unaffected. Sits on the shared async→sync path in
    /// [`algod_call`](Self::algod_call) and [`indexer_call`](Self::indexer_call), so it governs both
    /// algod and indexer requests (including
    /// retries and each page of a paged fetch — every one is a real outbound request against the
    /// quota).
    ///
    /// Enforcement order, so neither limiter is charged for a request the other blocks:
    /// 1. **Daily budget** — [`DailyBudget::check`] peeks (consuming nothing). If the daily budget
    ///    is spent, return [`AlgoError::daily_budget_exceeded`] carrying the wait to the next
    ///    day-start, before the token bucket is touched.
    /// 2. **Token bucket** — [`RateLimitMode::Block`] blocks until a token frees; `Reject` polls
    ///    once and, on an empty bucket, returns [`AlgoError::rate_limited`] carrying the wait without
    ///    sleeping and without consuming a token (so the daily budget below is not charged either).
    /// 3. **Charge** — only once the request will proceed: [`DailyBudget::record`] commits one
    ///    request against the current window, and the cumulative counter increments.
    ///
    /// The daily window is inherently wall-clock, so `now` comes from [`SystemTime::now`] (via
    /// [`now_unix_secs`](Self::now_unix_secs)); a backward clock jump just recomputes the window (see
    /// [`DailyBudget::roll`]). It is read once here so the check and the record agree on the window
    /// even across a day boundary crossed mid-call.
    fn apply_rate_limit(&self, operation: &str) -> Result<()> {
        // Read the wall-clock once, only when a daily budget is configured, so check and record
        // agree on the window.
        let now_secs = self.daily_budget.as_ref().map(|_| Self::now_unix_secs());

        // 1. Daily budget: peek before touching the token bucket. On exhaustion, reject consuming
        //    nothing from either limiter.
        if let Some(daily) = &self.daily_budget {
            let now = now_secs.expect("now read when daily_budget is set");
            let mut guard = lock_recover(daily);
            if let Err(wait) = guard.check(now) {
                let offset = guard.day_start_offset_secs;
                drop(guard);
                return Err(AlgoError::daily_budget_exceeded(wait, offset).into());
            }
        }

        // 2. Token bucket (as before): Block sleeps until a token frees; Reject fails fast on an
        //    empty bucket. A rejection here returns before the daily budget or counter is charged.
        if let Some(limiter) = &self.rate_limiter {
            let reject = matches!(
                self.config.rate_limit.as_ref().map(|c| c.mode),
                Some(RateLimitMode::Reject)
            );
            loop {
                let wait = lock_recover(limiter).poll(Instant::now());
                if wait.is_zero() {
                    break;
                }
                if reject {
                    // Fail fast with the precise wait; no token was consumed (poll only decrements
                    // when it returns zero), so the caller can retry once `wait` has elapsed.
                    return Err(AlgoError::rate_limited(operation, wait).into());
                }
                std::thread::sleep(wait);
            }
        }

        // 3. The request will proceed: charge the daily budget and the cumulative counter, exactly
        //    once per real outbound request.
        if let Some(daily) = &self.daily_budget {
            let now = now_secs.expect("now read when daily_budget is set");
            lock_recover(daily).record(now);
        }
        self.requests_made.fetch_add(1, Ordering::Relaxed);
        Ok(())
    }

    /// Helper to generate a unique note (e.g. for avoiding "transaction already in ledger" errors)
    pub fn unique_note() -> Vec<u8> {
        let mut n = Vec::new();
        n.extend_from_slice(Uuid::new_v4().as_bytes());
        n
    }

    pub fn algod_client(&self) -> Result<algonaut::Algod> {
        // Build base URL including port, e.g., http://localhost:4001
        let url = format!(
            "{}:{}",
            self.config.client_api_url, self.config.client_api_port
        );
        // Per requirement: default the token to empty string for Algod::new calls
        let token = self.config.token.clone().unwrap_or_default();
        algonaut::Algod::new(&url, &token)
            .map_err(|e| anyhow!("failed to construct Algod client: {e}"))
    }

    pub fn indexer_client(&self) -> Result<algonaut::Indexer> {
        let url = format!(
            "{}:{}",
            self.config.indexer_api_url, self.config.indexer_api_port
        );
        let token = self.config.token.clone().unwrap_or_default();
        algonaut::Indexer::new(&url, &token)
            .map_err(|e| anyhow!("failed to construct Indexer client: {e}"))
    }

    // HTTP status codes that warrant a retry (transient/overload errors) on any call.
    // `pub(crate)` in production; re-exported publicly only under `test-support`.
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) const RETRYABLE_STATUS_CODES: &'static [u16] = &[408, 425, 429, 502, 503, 504];

    // Additional statuses retried only on indexer reads. An indexer read is idempotent, and the
    // Nodely indexer intermittently answers a search with a 500 that succeeds when resent (#121).
    // A 500 from algod (for example on transaction submission) stays non-retryable: the caller
    // decides.
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) const INDEXER_READ_RETRYABLE_STATUS_CODES: &'static [u16] = &[500];

    // Returns true if the algonaut error is a retryable transient HTTP error on an algod call.
    // Only the tests use it; the call path asks `is_retryable_for` with the call's kind.
    #[cfg(feature = "test-support")]
    pub fn is_retryable(e: &algonaut::Error) -> bool {
        Self::is_retryable_for(CallKind::Algod, e)
    }

    // Returns true if the algonaut error is a retryable transient HTTP error for a call of `kind`.
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn is_retryable_for(kind: CallKind, e: &algonaut::Error) -> bool {
        match Self::http_status(e) {
            Some(status) => {
                Self::RETRYABLE_STATUS_CODES.contains(&status)
                    || (kind == CallKind::IndexerRead
                        && Self::INDEXER_READ_RETRYABLE_STATUS_CODES.contains(&status))
            }
            None => false,
        }
    }

    // Extract the HTTP status code from an algonaut error, or `None` for a transport-level
    // failure (timeout, connection refused) that never received an HTTP response. Reads the
    // `RequestErrorDetails::Http` shape; used to decide retries and to surface a typed `AlgoError`
    // carrying the status (e.g. a 403 quota stop) instead of an opaque message string.
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn http_status(e: &algonaut::Error) -> Option<u16> {
        if let algonaut::Error::Request(req) = e
            && let algonaut::error::RequestErrorDetails::Http { status, .. } = &req.details
        {
            return Some(*status);
        }
        None
    }

    /// Run an algonaut algod call: flatten the double-`Result` and retry transient HTTP errors
    /// (408, 425, 429, 502, 503, 504) up to 3 times with exponential backoff (1 s, 2 s, 4 s).
    /// Errors name the operation `algod call`. Use [`indexer_call`](Self::indexer_call) for indexer
    /// reads.
    ///
    /// Takes a closure rather than a bare future so the future can be rebuilt for each attempt
    /// (a future is consumed on first poll).
    pub fn algod_call<T, F, Fut>(&self, make_fut: F) -> Result<T>
    where
        T: Send,
        F: Fn() -> Fut,
        Fut: Future<Output = Result<T, algonaut::Error>> + Send,
    {
        self.call_with_retry(CallKind::Algod, make_fut)
    }

    /// Run an algonaut indexer read as [`algod_call`](Self::algod_call) does, but also retry an
    /// HTTP 500: an indexer read is idempotent, and the indexer can answer a search with a
    /// transient 500 that succeeds when resent. Errors name the operation `indexer search`.
    pub fn indexer_call<T, F, Fut>(&self, make_fut: F) -> Result<T>
    where
        T: Send,
        F: Fn() -> Fut,
        Fut: Future<Output = Result<T, algonaut::Error>> + Send,
    {
        self.call_with_retry(CallKind::IndexerRead, make_fut)
    }

    // The retry loop behind `algod_call` and `indexer_call`; `kind` decides which statuses retry
    // and names the operation in warnings and errors.
    fn call_with_retry<T, F, Fut>(&self, kind: CallKind, make_fut: F) -> Result<T>
    where
        T: Send,
        F: Fn() -> Fut,
        Fut: Future<Output = Result<T, algonaut::Error>> + Send,
    {
        const MAX_RETRIES: u32 = 3;
        const RETRY_BASE_MS: u64 = 1_000;

        let operation = kind.operation();
        let mut attempt = 0u32;
        loop {
            // Throttle every outbound request, retries included: each is a real request against a
            // metered endpoint (and "failed requests count towards quota"). A no-op when unset. In
            // `Reject` mode an empty bucket short-circuits here with `AlgoError::rate_limited`
            // rather than sleeping — and, being surfaced by `?`, does not consume a retry attempt.
            self.apply_rate_limit(operation)?;
            let result = self
                .rt_block_on(operation, make_fut())
                .map_err(|e| anyhow!("runtime error: {e}"))?;

            match result {
                Ok(val) => return Ok(val),
                Err(ref e) if attempt < MAX_RETRIES && Self::is_retryable_for(kind, e) => {
                    let delay = std::time::Duration::from_millis(RETRY_BASE_MS * (1u64 << attempt));
                    tracing::warn!(
                        "{} transient error (attempt {}/{}), retrying in {:?}: {}",
                        operation,
                        attempt + 1,
                        MAX_RETRIES,
                        delay,
                        e
                    );
                    std::thread::sleep(delay);
                    attempt += 1;
                }
                Err(e) => {
                    if attempt >= MAX_RETRIES && Self::is_retryable_for(kind, &e) {
                        return Err(AlgoError::transient(operation, &e.to_string()).into());
                    }
                    // Surface the HTTP status as a typed error so a caller can classify a hard
                    // rejection (e.g. a 403 quota stop) without string-matching the message.
                    if let Some(status) = Self::http_status(&e) {
                        return Err(AlgoError::http(operation, status, &e.to_string()).into());
                    }
                    return Err(anyhow!("{e}"));
                }
            }
        }
    }

    // Helper: run an async future on a fresh current-thread Tokio runtime, bounded by `self.timeout`.
    fn rt_block_on<T: Send>(
        &self,
        operation: &str,
        fut: impl Future<Output = T> + Send,
    ) -> Result<T> {
        let timeout = self.timeout;
        // Build a fresh current-thread runtime and drive `fut` on it. When a timeout is set, race the
        // future against a timer: on elapse the future is dropped, cancelling the in-flight request
        // (aborting its socket) and surfacing a timeout error, so a stalled endpoint cannot block the
        // caller forever. Packaged as one `FnOnce` so it moves either onto a scoped helper thread (when
        // already inside a runtime) or runs inline — the future is consumed by exactly one branch.
        let block = move || -> Result<T> {
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .map_err(|e| anyhow!("failed to build tokio runtime: {e}"))?;
            rt.block_on(async move {
                match timeout {
                    Some(dur) => tokio::time::timeout(dur, fut)
                        .await
                        .map_err(|_| anyhow!("{operation} exceeded timeout of {dur:?}")),
                    None => Ok(fut.await),
                }
            })
        };
        // If we are already in a tokio runtime, we must avoid a nested block_on and the "cannot drop
        // runtime" panic during unwinding/drop — run `block` on a scoped helper thread.
        if tokio::runtime::Handle::try_current().is_ok() {
            std::thread::scope(|s| {
                s.spawn(block)
                    .join()
                    .map_err(|_| anyhow!("rt_block_on thread panicked"))?
            })
        } else {
            block()
        }
    }

    // Helper: parse address string into algonaut Address.
    fn parse_address(addr: &str) -> Result<algonaut::core::Address> {
        use std::str::FromStr;
        algonaut::core::Address::from_str(addr).map_err(|e| anyhow!("invalid address: {e}"))
    }

    // Helper: require self.address and parse it.
    fn require_address(&self) -> Result<algonaut::core::Address> {
        let addr_str = self
            .address
            .as_ref()
            .ok_or_else(|| anyhow!("This operation needs an address"))?;
        Self::parse_address(addr_str)
    }

    pub fn address_str(&self) -> Result<String> {
        self.address
            .as_ref()
            .cloned()
            .ok_or_else(|| anyhow!("This operation needs an address"))
    }

    // Helper: JSON field accessor that supports snake_case and kebab-case alternatives.
    fn json_get<'a>(o: &'a serde_json::Value, k1: &str, k2: &str) -> Option<&'a serde_json::Value> {
        o.get(k1).or_else(|| o.get(k2))
    }

    // Helper: decode TEAL key/value state entries from JSON into vector of (key, value) strings.
    // - Keys are base64-encoded in algod JSON and represent UTF-8 strings: decode to UTF-8.
    // - Byte values (type == 1) may be represented as an array of numbers (bytes) or as a base64 string,
    //   depending on the source struct and serializer. Handle both. Attempt to decode to UTF-8; if not valid,
    //   fall back to a 0x-prefixed hex string for readability.
    fn decode_state_entries(entries: &[serde_json::Value]) -> Vec<(String, String)> {
        let mut kvs: Vec<(String, String)> = Vec::new();
        for entry in entries {
            let key_b64 = match entry.get("key").and_then(|x| x.as_str()) {
                Some(s) => s,
                None => continue,
            };
            let key = match general_purpose::STANDARD.decode(key_b64) {
                Ok(bytes) => String::from_utf8(bytes).unwrap_or_else(|_| key_b64.to_string()),
                Err(_) => key_b64.to_string(),
            };
            let val_obj = match entry.get("value").and_then(|x| x.as_object()) {
                Some(o) => o,
                None => continue,
            };
            let vtype = val_obj.get("type").and_then(|x| x.as_u64()).unwrap_or(0);
            let val = if vtype == 1 {
                // bytes can be an array of numbers or a base64 string
                let bytes_opt = if let Some(arr) = val_obj.get("bytes").and_then(|x| x.as_array()) {
                    // Collect numeric array into bytes
                    let mut buf: Vec<u8> = Vec::with_capacity(arr.len());
                    for n in arr {
                        if let Some(u) = n.as_u64() {
                            buf.push((u & 0xFF) as u8);
                        } else if let Some(i) = n.as_i64()
                            && i >= 0
                        {
                            buf.push(((i as u64) & 0xFF) as u8);
                        }
                    }
                    Some(buf)
                } else if let Some(b64) = val_obj.get("bytes").and_then(|x| x.as_str()) {
                    general_purpose::STANDARD.decode(b64).ok()
                } else {
                    None
                };

                if let Some(bytes) = bytes_opt {
                    match String::from_utf8(bytes.clone()) {
                        Ok(s) => s,
                        Err(_) => {
                            // Fallback: hex string for non-UTF8 bytes
                            let mut hex = String::from("0x");
                            for byte in bytes {
                                hex.push_str(&format!("{:02x}", byte));
                            }
                            hex
                        }
                    }
                } else {
                    String::new()
                }
            } else {
                val_obj
                    .get("uint")
                    .and_then(|x| x.as_u64())
                    .map(|u| u.to_string())
                    .unwrap_or_else(|| "0".to_string())
            };
            kvs.push((key, val));
        }
        kvs
    }

    /// Create a new address, generating an ed25519 keypair. For compatibility with
    /// existing tests, we store the secret key in `passphrase` as a base64-encoded
    /// string with a "b64:" prefix. Note: production code expects an ASCII mnemonic
    /// passphrase to be provided by callers; this storage is only used by tests.
    pub fn create_address(&mut self) -> Result<String> {
        use ed25519_dalek::SigningKey;
        use rand_core::{OsRng, RngCore};

        let mut rng = OsRng;
        let mut sk: [u8; 32] = [0u8; 32];
        rng.fill_bytes(&mut sk);
        let signing_key = SigningKey::from_bytes(&sk);
        let verifying_key = signing_key.verifying_key();
        let pk: [u8; 32] = verifying_key.to_bytes();

        let addr = byte_key_to_address(&pk)?;
        self.address = Some(addr.clone());
        // Store secret key as base64 so we can recover it for signing
        let sk_b64 = general_purpose::STANDARD.encode(sk);
        self.passphrase = Some(format!("b64:{}", sk_b64));
        Ok(addr)
    }

    pub fn public_key_bytes(&self) -> Result<[u8; 32]> {
        let addr = self
            .address
            .as_ref()
            .ok_or_else(|| anyhow!("This operation needs an address"))?;
        address_to_byte_key(addr)
    }

    pub fn private_key_bytes(&self) -> Result<Vec<u8>> {
        let pass = self
            .passphrase
            .as_ref()
            .ok_or_else(|| anyhow!("This operation needs account access"))?;

        // Accepts an ASCII Algorand mnemonic or a legacy "b64:" secret (see seed_from_passphrase).
        Ok(Self::seed_from_passphrase(pass)?.to_vec())
    }

    /// Compute the application (contract) address from app id.
    /// Spec: pubkey = SHA512/256("appID" || app_id_be_u64), then Algorand address from pubkey.
    pub fn contract_address(&self, app_id: u64) -> Result<String> {
        use sha2::{Digest, Sha512_256};
        let mut hasher = Sha512_256::new();
        hasher.update(b"appID");
        hasher.update(app_id.to_be_bytes());
        let pk_bytes: [u8; 32] = hasher.finalize().into();
        byte_key_to_address(&pk_bytes)
    }

    pub fn sign(&self, text: &str) -> Result<String> {
        use ed25519_dalek::{Signer, SigningKey};
        let sk_bytes = self.private_key_bytes()?;
        let sk_arr: [u8; 32] = sk_bytes
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
        let signing_key = SigningKey::from_bytes(&sk_arr);
        let signature = signing_key.sign(text.as_bytes());
        Ok(general_purpose::STANDARD.encode(signature.to_bytes()))
    }

    /// Sign arbitrary bytes with this account's Ed25519 key, returning the raw 64-byte signature.
    ///
    /// This is a plain `Ed25519(sk, message)` over the exact bytes given, with no domain-separation
    /// tag. It differs from [`AlgoOps::sign`] (which base64-encodes the signature for text callers)
    /// and from [`AlgoOps::sign_notify_envelope`] (which prepends Algorand's `"MX"` byte-signing
    /// tag). It is the form a Sidewinder canonical transaction body is signed with: the verifier
    /// re-encodes the same canonical body and checks the signature over those bytes directly, so any
    /// prefix here would make the signature fail to verify.
    pub fn sign_bytes(&self, message: &[u8]) -> Result<[u8; 64]> {
        use ed25519_dalek::{Signer, SigningKey};
        let sk_bytes = self.private_key_bytes()?;
        let sk_arr: [u8; 32] = sk_bytes
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
        let signing_key = SigningKey::from_bytes(&sk_arr);
        Ok(signing_key.sign(message).to_bytes())
    }

    /// Sign the canonical bingle-notify envelope with this account's key.
    ///
    /// Builds the fixed, newline-delimited UTF-8 message (NOT JSON)
    /// `"bingle-notify:v1"\nroute\niss\naudience\nbodyHash\nnonce\nexp`, then signs it with the
    /// Algorand byte-signing scheme — `Ed25519(sk, "MX" || msg)` — which is exactly what
    /// `algosdk.signBytes` produces and `algosdk.verifyBytes` checks. Returns the base64 of the
    /// 64-byte signature.
    ///
    /// `bodyHash` is the lowercase hex SHA-256 of the route-specific body:
    /// - `"register"`: `sha256(utf8(token + "\n" + env))`, with `env` in {"sandbox","production"};
    /// - `"alert"`: `sha256("")` (empty; `token`/`env` are ignored, `audience` is the recipient).
    ///
    /// Source of truth for the contract: bingle_notify/src/lib/verify.ts.
    pub fn sign_notify_envelope(
        &self,
        route: &str,
        iss: &str,
        audience: &str,
        token: &str,
        env: &str,
        nonce: &str,
        exp: i64,
    ) -> Result<String> {
        use ed25519_dalek::{Signer, SigningKey};
        use sha2::{Digest, Sha256};

        // bodyHash: lowercase hex sha256 of the route-specific body.
        let body = match route {
            "register" => format!("{token}\n{env}"),
            "alert" => String::new(),
            other => bail!("unknown notify route: {other}"),
        };
        let body_hash = HEXLOWER.encode(&Sha256::digest(body.as_bytes()));

        // Canonical, newline-delimited message.
        let msg =
            format!("bingle-notify:v1\n{route}\n{iss}\n{audience}\n{body_hash}\n{nonce}\n{exp}");

        // Algorand byte-signing: Ed25519(sk, "MX" || msg).
        let sk_bytes = self.private_key_bytes()?;
        let sk_arr: [u8; 32] = sk_bytes
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
        let signing_key = SigningKey::from_bytes(&sk_arr);
        let mut signed = Vec::with_capacity(2 + msg.len());
        signed.extend_from_slice(b"MX");
        signed.extend_from_slice(msg.as_bytes());
        let signature = signing_key.sign(&signed);
        Ok(general_purpose::STANDARD.encode(signature.to_bytes()))
    }

    pub fn verify(&self, text: &str, sig_b64: &str) -> Result<bool> {
        use ed25519_dalek::{Signature, Verifier, VerifyingKey};
        let sig_bytes = match general_purpose::STANDARD.decode(sig_b64) {
            Ok(b) => b,
            Err(_) => return Ok(false),
        };
        if sig_bytes.len() != 64 {
            return Ok(false);
        }
        let sig_arr: [u8; 64] = match sig_bytes.try_into() {
            Ok(a) => a,
            Err(_) => return Ok(false),
        };
        let signature = Signature::from_bytes(&sig_arr);
        let pk = self.public_key_bytes()?;
        let vk = VerifyingKey::from_bytes(&pk)
            .map_err(|e| anyhow!("invalid verifying key from address: {e}"))?;
        Ok(vk.verify(text.as_bytes(), &signature).is_ok())
    }

    pub fn account_balance(&self) -> Result<Option<f64>> {
        let client = match self.algod_client() {
            Ok(c) => c,
            Err(e) => {
                tracing::error!("[account_balance] Failed to access algod client: {}", e);
                return Err(e);
            }
        };
        let address = match self.require_address() {
            Ok(a) => a,
            Err(e) => {
                tracing::error!("[account_balance] Failed to resolve address: {}", e);
                return Err(e);
            }
        };
        let info = match self.algod_call(|| client.account(&address)) {
            Ok(r) => r,
            Err(e) => {
                if AlgoError::is_host_unreachable(&e) {
                    // Expected during a transient node outage; callers fall back to cached state,
                    // so log at debug to avoid flooding the log while the node is unreachable.
                    tracing::debug!(
                        "[account_balance] account information unreachable for {}: {}",
                        address,
                        e
                    );
                    return Err(
                        AlgoError::unreachable("account_information", &e.to_string()).into(),
                    );
                }
                tracing::error!(
                    "[account_balance] Failed to fetch account information for {}: {}",
                    address,
                    e
                );
                return Err(e);
            }
        };
        // Next log is huge!
        // algo_log!("[account_balance] Retrieved account info for address: {} => {:?}", address, info);
        // amount is in microalgos
        let micro: u64 = info.amount;
        algo_log!(
            "[account_balance] Balance for address {} is {} microalgos",
            address,
            micro
        );
        Ok(Some(micro as f64 / 1_000_000.0))
    }

    pub fn global_state(
        &self,
        maybe_app_id: Option<u64>,
    ) -> Result<Option<Vec<(u64, Vec<(String, String)>)>>> {
        let client = self.algod_client()?;
        let address = self.require_address()?;
        let info = match self.algod_call(|| client.account(&address)) {
            Ok(v) => v,
            Err(e) if AlgoError::is_host_unreachable(&anyhow!(e.to_string())) => {
                return Err(AlgoError::unreachable("account_information", &e.to_string()).into());
            }
            Err(_) => return Ok(None),
        };

        // Convert to json Value for resilient traversal
        let v = serde_json::to_value(&info)
            .map_err(|e| anyhow!("failed to serialize account info: {e}"))?;

        let created =
            match Self::json_get(&v, "created_apps", "created-apps").and_then(|x| x.as_array()) {
                Some(a) => a,
                None => return Ok(Some(vec![])),
            };

        let mut out: Vec<(u64, Vec<(String, String)>)> = Vec::new();
        for app in created {
            let id = match app.get("id").and_then(|x| x.as_u64()) {
                Some(i) => i,
                None => continue,
            };
            if let Some(filter) = maybe_app_id
                && filter != id
            {
                continue;
            }
            let params = match app.get("params").and_then(|x| x.as_object()) {
                Some(p) => p,
                None => continue,
            };
            let params_value = serde_json::Value::Object(params.clone());
            let gs_vec: Vec<serde_json::Value> =
                Self::json_get(&params_value, "global_state", "global-state")
                    .and_then(|x| x.as_array())
                    .cloned()
                    .unwrap_or_default();
            let kvs = Self::decode_state_entries(&gs_vec);
            out.push((id, kvs));
        }
        Ok(Some(out))
    }

    /// Read a single byte-valued global state entry from an arbitrary application (any app id,
    /// not limited to apps created by the sender) and return the raw bytes. Returns None if the
    /// application or the key is absent. Unlike `global_state`, this does not lossily decode the
    /// value to UTF-8, so it is safe for packed binary values.
    pub fn app_global_bytes(&self, app_id: u64, key: &str) -> Result<Option<Vec<u8>>> {
        if app_id == 0 {
            bail!("app_id must be > 0");
        }
        let client = self.algod_client()?;
        let app_info = match self.algod_call(|| client.app(algonaut::core::AppId(app_id))) {
            Ok(v) => v,
            Err(e) if AlgoError::is_host_unreachable(&anyhow!(e.to_string())) => {
                return Err(AlgoError::unreachable("app_information", &e.to_string()).into());
            }
            Err(_) => return Ok(None),
        };
        let v = serde_json::to_value(&app_info)
            .map_err(|e| anyhow!("failed to serialize app info: {e}"))?;
        let params = match Self::json_get(&v, "params", "params").and_then(|x| x.as_object()) {
            Some(p) => serde_json::Value::Object(p.clone()),
            None => return Ok(None),
        };
        let gs: Vec<serde_json::Value> = Self::json_get(&params, "global_state", "global-state")
            .and_then(|x| x.as_array())
            .cloned()
            .unwrap_or_default();
        for entry in &gs {
            let key_b64 = match entry.get("key").and_then(|x| x.as_str()) {
                Some(s) => s,
                None => continue,
            };
            let entry_key = match general_purpose::STANDARD.decode(key_b64) {
                Ok(bytes) => match String::from_utf8(bytes) {
                    Ok(s) => s,
                    Err(_) => continue,
                },
                Err(_) => continue,
            };
            if entry_key != key {
                continue;
            }
            let val_obj = match entry.get("value").and_then(|x| x.as_object()) {
                Some(o) => o,
                None => continue,
            };
            // Byte values (type == 1) may be a numeric array or a base64 string.
            let bytes = if let Some(arr) = val_obj.get("bytes").and_then(|x| x.as_array()) {
                let mut buf: Vec<u8> = Vec::with_capacity(arr.len());
                for n in arr {
                    if let Some(u) = n.as_u64() {
                        buf.push((u & 0xFF) as u8);
                    } else if let Some(i) = n.as_i64()
                        && i >= 0
                    {
                        buf.push(((i as u64) & 0xFF) as u8);
                    }
                }
                Some(buf)
            } else if let Some(b64) = val_obj.get("bytes").and_then(|x| x.as_str()) {
                general_purpose::STANDARD.decode(b64).ok()
            } else {
                None
            };
            return Ok(bytes);
        }
        Ok(None)
    }

    /// Read an app's local-state schema `(num_uints, num_byte_slices)` from application info.
    ///
    /// Generic to any app: these counts drive the minimum-balance increase an account incurs
    /// when it opts in to the app, so callers can size the exact funding an opt-in requires.
    pub fn get_app_local_schema(&self, app_id: u64) -> Result<(u64, u64)> {
        if app_id == 0 {
            bail!("app_id must be > 0");
        }
        let client = self.algod_client()?;
        let app_info = self
            .algod_call(|| client.app(algonaut::core::AppId(app_id)))
            .map_err(|e| anyhow!("application_information failed: {e}"))?;
        let v = serde_json::to_value(&app_info)
            .map_err(|e| anyhow!("failed to serialize application info: {e}"))?;
        let schema = v
            .get("params")
            .and_then(|p| {
                p.get("local-state-schema")
                    .or_else(|| p.get("local_state_schema"))
            })
            .ok_or_else(|| anyhow!("local-state-schema missing for app_id {app_id}"))?;
        let num_uints = schema
            .get("num-uint")
            .or_else(|| schema.get("num_uint"))
            .and_then(|x| x.as_u64())
            .unwrap_or(0);
        let num_byte_slices = schema
            .get("num-byte-slice")
            .or_else(|| schema.get("num_byte_slice"))
            .and_then(|x| x.as_u64())
            .unwrap_or(0);
        Ok((num_uints, num_byte_slices))
    }

    pub fn local_state_for_account(
        &self,
        app_id: u64,
        account_address: &str,
    ) -> Result<Option<Vec<(String, String)>>> {
        let client = self.algod_client()?;
        let address = Self::parse_address(account_address)?;
        let info = match self.algod_call(|| client.account(&address)) {
            Ok(v) => v,
            Err(e) if AlgoError::is_host_unreachable(&anyhow!(e.to_string())) => {
                return Err(AlgoError::unreachable("account_information", &e.to_string()).into());
            }
            Err(_) => return Ok(None),
        };

        algo_log!("Retrieved account info for address: {}", account_address);
        // Next log is huge
        // algo_log!("Account info: {:#?}", info);

        let v = serde_json::to_value(&info)
            .map_err(|e| anyhow!("failed to serialize account info: {e}"))?;

        Ok(Self::decode_app_local_state(&v, app_id))
    }

    /// Decode the local-state key/values an account holds for `app_id`, from the account's serialized
    /// indexer/algod JSON (handling both snake_case and kebab-case field names). `None` when the JSON
    /// carries no local state for that app — i.e. the account is not opted in. Shared by
    /// [`AlgoOps::local_state_for_account`] (algod, single account) and the cached opted-in-account
    /// scanner (indexer, whole app), so both decode local state identically.
    fn decode_app_local_state(
        account_json: &serde_json::Value,
        app_id: u64,
    ) -> Option<Vec<(String, String)>> {
        let als =
            Self::json_get(account_json, "apps_local_state", "apps-local-state")?.as_array()?;
        for st in als {
            if st.get("id").and_then(|x| x.as_u64()) == Some(app_id) {
                let keyvals_vec: Vec<serde_json::Value> =
                    Self::json_get(st, "key_value", "key-value")
                        .and_then(|x| x.as_array())
                        .cloned()
                        .unwrap_or_default();
                return Some(Self::decode_state_entries(&keyvals_vec));
            }
        }
        None
    }

    pub fn send_algo(&self, to_address: &str, amount_algos: f64) -> Result<()> {
        // Validate amount
        if amount_algos <= 0.0 {
            bail!("amount must be positive");
        }
        // Require account access (private key) and valid addresses
        let sk = self.private_key_bytes()?;
        let from = self.require_address()?;
        let to = Self::parse_address(to_address)?; // invalid -> early error

        // Algod client
        let client = self.algod_client()?;

        // Fetch suggested params
        let params = self
            .algod_call(|| client.suggested_params())
            .map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;

        // Build payment transaction
        let micro = (amount_algos * 1_000_000.0).round() as u64;
        let tx = algonaut::transaction::Pay::new(from, to, algonaut::core::MicroAlgos(micro))
            .note(Self::unique_note())
            .build(&params)
            .map_err(|e| anyhow!("failed to build transaction: {e}"))?;

        // Validate secret key length (32 bytes)
        let seed: [u8; 32] = sk
            .as_slice()
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;

        // Sign using algonaut account helper
        let account = algonaut::transaction::account::Account::from_seed(seed);
        let signed_tx = account
            .sign(tx)
            .map_err(|e| anyhow!("failed to sign transaction: {e}"))?;
        let signed = signed_tx
            .to_msg_pack()
            .map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;

        // Submit raw transaction via algod
        let tx_id = self
            .algod_call(|| client.send_raw(&signed))
            .map_err(|e| anyhow!("send_raw failed: {e}"))?
            .tx_id;

        // Wait for confirmation up to a default timeout (e.g., 10 rounds)
        self.wait_for_confirmation(&tx_id, 10)?;
        Ok(())
    }

    pub fn create_asset(&self, name: &str, units_in_issue: u64) -> Result<Option<u64>> {
        // Validate inputs
        if name.trim().is_empty() {
            bail!("asset name must not be empty");
        }
        if units_in_issue == 0 {
            bail!("units_in_issue must be > 0");
        }

        // Require account access and issuer address
        let sk = self.private_key_bytes()?;
        let issuer = self.require_address()?;

        // Algod client and suggested params
        let client = self.algod_client()?;
        let params = self
            .algod_call(|| client.suggested_params())
            .map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;

        // Build CreateAsset transaction: minimal: total=units_in_issue, decimals=0
        // Set manager, reserve, and clawback to issuer so we can later reconfigure if needed
        let tx = algonaut::transaction::CreateAsset::new(issuer, units_in_issue, 0, false)
            .manager(issuer)
            .reserve(issuer)
            .clawback(issuer)
            .note(Self::unique_note())
            .build(&params)
            .map_err(|e| anyhow!("failed to build asset create transaction: {e}"))?;

        // Sign
        let seed: [u8; 32] = sk
            .as_slice()
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
        let account = algonaut::transaction::account::Account::from_seed(seed);
        let signed_tx = account
            .sign(tx)
            .map_err(|e| anyhow!("failed to sign asset create transaction: {e}"))?;
        let signed = signed_tx
            .to_msg_pack()
            .map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;

        // Submit and wait
        let tx_id = self
            .algod_call(|| client.send_raw(&signed))
            .map_err(|e| anyhow!("send_raw failed: {e}"))?
            .tx_id;
        self.wait_for_confirmation(&tx_id, 10)?;

        // Retrieve created asset id from pending transaction info
        let tx_id_obj = algonaut::core::TransactionId::from(tx_id.as_str());
        let info = self
            .algod_call(|| client.pending_transaction(&tx_id_obj))
            .map_err(|e| anyhow!("failed to fetch pending transaction info for asset id: {e}"))?;
        Ok(info.asset_index.or(Some(0)).filter(|id| *id != 0))
    }

    /// Create an ASA with explicit reserve and clawback addresses.
    ///
    /// The caller (`self`) is the ASA manager (the only account that can later reconfigure it).
    /// `reserve_addr` and `clawback_addr` are Algorand address strings. decimals=0.
    pub fn create_asset_configured(
        &self,
        name: &str,
        units_in_issue: u64,
        manager_addr: &str,
        reserve_addr: &str,
        clawback_addr: &str,
        freeze_addr: &str,
    ) -> Result<Option<u64>> {
        if name.trim().is_empty() {
            bail!("asset name must not be empty");
        }
        if units_in_issue == 0 {
            bail!("units_in_issue must be > 0");
        }

        let sk = self.private_key_bytes()?;
        let issuer = self.require_address()?;
        let manager = Self::parse_address(manager_addr)?;
        let reserve = Self::parse_address(reserve_addr)?;
        let clawback = Self::parse_address(clawback_addr)?;
        let freeze = Self::parse_address(freeze_addr)?;

        let client = self.algod_client()?;
        let params = self
            .algod_call(|| client.suggested_params())
            .map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;

        let tx = algonaut::transaction::CreateAsset::new(issuer, units_in_issue, 0, false)
            .manager(manager)
            .reserve(reserve)
            .clawback(clawback)
            .freeze(freeze)
            .note(Self::unique_note())
            .build(&params)
            .map_err(|e| anyhow!("failed to build asset create transaction: {e}"))?;

        let seed: [u8; 32] = sk
            .as_slice()
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
        let account = algonaut::transaction::account::Account::from_seed(seed);
        let signed_tx = account
            .sign(tx)
            .map_err(|e| anyhow!("failed to sign asset create transaction: {e}"))?;
        let signed = signed_tx
            .to_msg_pack()
            .map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;

        let tx_id = self
            .algod_call(|| client.send_raw(&signed))
            .map_err(|e| anyhow!("send_raw failed: {e}"))?
            .tx_id;
        self.wait_for_confirmation(&tx_id, 10)?;

        let tx_id_obj = algonaut::core::TransactionId::from(tx_id.as_str());
        let info = self
            .algod_call(|| client.pending_transaction(&tx_id_obj))
            .map_err(|e| anyhow!("failed to fetch pending transaction info for asset id: {e}"))?;
        Ok(info.asset_index.or(Some(0)).filter(|id| *id != 0))
    }

    /// Create an ASA with the reserve and clawback addresses both set to the application address for `app_id`.
    /// Manager remains the issuer for future reconfiguration; decimals=0.
    pub fn create_asset_with_reserve_app(
        &self,
        name: &str,
        units_in_issue: u64,
        app_id: u64,
    ) -> Result<Option<u64>> {
        if app_id == 0 {
            bail!("app_id must be > 0");
        }
        let app_addr = self.contract_address(app_id)?;
        let issuer_addr = self.address_str()?;
        self.create_asset_configured(
            name,
            units_in_issue,
            &issuer_addr,
            &app_addr,
            &app_addr,
            &issuer_addr,
        )
    }

    /// Check whether `account_address` has opted-in to `asset_id`.
    pub fn is_account_opted_in_to_asset(
        &self,
        account_address: &str,
        asset_id: u64,
    ) -> Result<bool> {
        if asset_id == 0 {
            bail!("asset_id must be > 0");
        }
        let client = self.algod_client()?;
        let address = Self::parse_address(account_address)?;
        let info = match self.algod_call(|| client.account(&address)) {
            Ok(v) => v,
            Err(_) => return Ok(false),
        };
        let v = serde_json::to_value(&info)
            .map_err(|e| anyhow!("failed to serialize account info: {e}"))?;
        let assets_arr = v
            .get("assets")
            .or_else(|| v.get("assets"))
            .and_then(|x| x.as_array())
            .cloned()
            .unwrap_or_default();
        for a in assets_arr {
            let id = a
                .get("asset-id")
                .and_then(|x| x.as_u64())
                .or_else(|| a.get("asset_id").and_then(|x| x.as_u64()))
                .unwrap_or(0);
            if id == asset_id {
                return Ok(true);
            }
        }
        Ok(false)
    }

    /// Returns the holding amount of a specific asset for a given account.
    pub fn asset_holding(&self, account_address: &str, asset_id: u64) -> Result<u64> {
        let client = self.algod_client()?;
        let address = Self::parse_address(account_address)?;
        let info = self
            .algod_call(|| client.account(&address))
            .map_err(|e| anyhow!("failed to fetch account information: {e}"))?;
        let v = serde_json::to_value(&info)
            .map_err(|e| anyhow!("failed to serialize account info: {e}"))?;
        Ok(Self::parse_holding_amount_from_account_value(&v, asset_id))
    }

    /// Returns the balance of any on-chain address (need not be the signer) together with the
    /// minimum balance algod requires it to keep, both in µALGO.
    ///
    /// The minimum grows with each asset or application the account opts into, so the balance
    /// alone cannot tell whether an account can still pay a fee: algod rejects a transaction that
    /// would leave `amount` below `min_balance`. One account read, the same as
    /// [`microalgos_at`](Self::microalgos_at). Same unreachable-node behaviour as
    /// [`round`](Self::round), and a typed [`AlgoError`] (a 403 quota stop, a rate-limit rejection)
    /// is kept intact so a caller polling this can tell those from a transient failure.
    pub fn account_funds(&self, account_address: &str) -> Result<AlgoAccountFunds> {
        let client = self.algod_client()?;
        let address = Self::parse_address(account_address)?;
        let info = match self.algod_call(|| client.account(&address)) {
            Ok(info) => info,
            Err(e) if AlgoError::is_host_unreachable(&e) => {
                return Err(AlgoError::unreachable("account_funds", &e.to_string()).into());
            }
            Err(e) => {
                return Err(AlgoError::contextualize(
                    &format!("failed to fetch account information for {account_address}"),
                    e,
                ));
            }
        };
        Ok(AlgoAccountFunds {
            amount: info.amount,
            min_balance: info.min_balance,
        })
    }

    /// Returns the µALGO balance of any on-chain address (need not be the signer).
    pub fn microalgos_at(&self, account_address: &str) -> Result<u64> {
        let client = self.algod_client()?;
        let address = Self::parse_address(account_address)?;
        let info = self.algod_call(|| client.account(&address)).map_err(|e| {
            anyhow!("failed to fetch account information for {account_address}: {e}")
        })?;
        Ok(info.amount)
    }

    /// Return the last committed round (algod `GET /v2/status` → `last-round`).
    ///
    /// Backs a node's "current round". Routed through `algod_call` for retry + blocking; a
    /// [`AlgoErrorKind::HostUnreachable`](crate::error::AlgoErrorKind::HostUnreachable) error is
    /// surfaced so a consumer can skip while the node is down.
    pub fn round(&self) -> Result<u64> {
        let client = self.algod_client()?;
        let status = match self.algod_call(|| client.status()) {
            Ok(v) => v,
            Err(e) if AlgoError::is_host_unreachable(&e) => {
                return Err(AlgoError::unreachable("node_status", &e.to_string()).into());
            }
            // Keep a typed `AlgoError` (e.g. a 403 quota stop) intact so a caller polling the
            // current round can tell a hard quota rejection from a transient failure.
            Err(e) => return Err(AlgoError::contextualize("failed to get node status", e)),
        };
        Ok(status.last_round.0)
    }

    /// Return the 32-byte VRF block seed for `round` (algod `GET /v2/blocks/{round}` →
    /// `block.seed`). Backs seed-based selection. Same unreachable-node behaviour as [`round`](Self::round).
    ///
    /// The seed is decoded from the block model, so no `algonaut` types cross the boundary.
    pub fn block_seed(&self, round: u64) -> Result<Vec<u8>> {
        // Read only the block header's seed. Fetching the fully-typed block (algonaut `client.block`)
        // decodes its transactions too, and a block that carries a state-proof (`stpf`) transaction —
        // which algonaut cannot decode — fails the whole fetch even though the seed lives in the header
        // (issue #66). So GET the block JSON and deserialize just `block.seed`, ignoring `txns` and every
        // other field, so no transaction is ever decoded.
        let url = format!(
            "{}:{}/v2/blocks/{round}?format=json",
            self.config.client_api_url, self.config.client_api_port
        );
        let token = self.config.token.clone().unwrap_or_default();
        let token_header = self
            .config
            .token_key
            .clone()
            .unwrap_or_else(|| "X-Algo-API-Token".to_string());

        // reuse the async->sync bridge; distinguish an unreachable host (connect/timeout) so the caller's
        // skip-when-down behaviour is preserved, from any other failure.
        let fetched: std::result::Result<String, (bool, String)> =
            self.rt_block_on("algod call", async move {
                let response = reqwest::Client::new()
                    .get(url.as_str())
                    .header(token_header.as_str(), token.as_str())
                    .send()
                    .await
                    .map_err(|e| (e.is_connect() || e.is_timeout(), e.to_string()))?;
                let status = response.status();
                let body = response.text().await.map_err(|e| (false, e.to_string()))?;
                if status.is_success() {
                    Ok(body)
                } else {
                    Err((false, format!("HTTP {status}: {body}")))
                }
            })?;
        let body = fetched.map_err(|(unreachable, message)| {
            if unreachable {
                AlgoError::unreachable("block", &message).into()
            } else {
                anyhow!("failed to fetch block {round}: {message}")
            }
        })?;
        Self::parse_block_header_seed(body.as_bytes(), round)
    }

    /// Extract the 32-byte block seed from an algod `GET /v2/blocks/{round}?format=json` response body,
    /// decoding only `block.seed` and ignoring every other field (including `txns`) — so a state-proof
    /// (`stpf`) or any other transaction algonaut cannot decode is never looked at (issue #66).
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn parse_block_header_seed(body: &[u8], round: u64) -> Result<Vec<u8>> {
        // a minimal view of the block carrying only the header seed; serde ignores fields not declared
        // here (there is no `deny_unknown_fields`), so the transaction list is never decoded.
        #[derive(Deserialize)]
        struct BlockHeaderResponse {
            block: BlockHeaderSeed,
        }
        #[derive(Deserialize)]
        struct BlockHeaderSeed {
            seed: String, // standard base64 of the 32-byte seed
        }

        let parsed: BlockHeaderResponse = serde_json::from_slice(body)
            .map_err(|e| anyhow!("failed to parse block {round} header seed: {e}"))?;
        let seed = general_purpose::STANDARD
            .decode(parsed.block.seed.as_bytes())
            .map_err(|e| anyhow!("block {round} seed is not valid base64: {e}"))?;
        if seed.len() != 32 {
            bail!("block {round} seed is {} bytes, expected 32", seed.len());
        }
        Ok(seed)
    }

    /// Return the suggested transaction params as a neutral [`AlgoSuggestedParams`]
    /// (algod `GET /v2/transactions/params`). Plain types only; same unreachable-node
    /// behaviour as [`round`](Self::round).
    pub fn suggested_params(&self) -> Result<AlgoSuggestedParams> {
        let client = self.algod_client()?;
        let params = match self.algod_call(|| client.suggested_params()) {
            Ok(v) => v,
            Err(e) if AlgoError::is_host_unreachable(&e) => {
                return Err(AlgoError::unreachable("suggested_params", &e.to_string()).into());
            }
            Err(e) => {
                return Err(AlgoError::contextualize(
                    "failed to fetch suggested params",
                    e,
                ));
            }
        };
        Ok(AlgoSuggestedParams {
            last_round: params.last_round.0,
            min_fee: params.min_fee.0,
            genesis_hash: params.genesis_hash.0,
            genesis_id: params.genesis_id,
        })
    }

    /// Submit an already-signed, MessagePack-encoded transaction (algod
    /// `POST /v2/transactions`, raw-transaction broadcast) and return its transaction id.
    ///
    /// The caller builds and signs with its own SDK, so only bytes cross the boundary — this
    /// keeps the primitive independent of `algo_ops`'s `algonaut` version. Routed through
    /// `algod_call` for retry + blocking; surfaces `AlgoError::HostUnreachable` when the node
    /// is down. Unlike the high-level builders, this does not wait for confirmation — poll with
    /// [`confirmed_transaction`](Self::confirmed_transaction) or
    /// [`wait_for_confirmation`](Self::wait_for_confirmation).
    pub fn submit_signed(&self, signed_txn: &[u8]) -> Result<String> {
        if signed_txn.is_empty() {
            bail!("signed_txn must not be empty");
        }
        let client = self.algod_client()?;
        let resp = match self.algod_call(|| client.send_raw(signed_txn)) {
            Ok(v) => v,
            Err(e) if AlgoError::is_host_unreachable(&e) => {
                return Err(AlgoError::unreachable("send_raw", &e.to_string()).into());
            }
            Err(e) => return Err(AlgoError::contextualize("send_raw failed", e)),
        };
        Ok(resp.tx_id)
    }

    /// Read a pending or confirmed transaction (algod `GET /v2/transactions/pending/{txid}`),
    /// exposing the confirmed round and the decoded note as a neutral [`ConfirmedTxn`].
    ///
    /// Returns `Ok(None)` when the node no longer knows the txid (dropped/expired/not yet seen);
    /// while still pending the transaction is known but `confirmed_round == 0`. Backs reading
    /// anchored bytes back from the chain and confirming an anchor landed. Surfaces
    /// `AlgoError::HostUnreachable` when the node is down.
    pub fn confirmed_transaction(&self, txid: &str) -> Result<Option<ConfirmedTxn>> {
        if txid.trim().is_empty() {
            bail!("txid must not be empty");
        }
        let client = self.algod_client()?;
        let tx_id_obj = algonaut::core::TransactionId::from(txid);
        let resp = match self.algod_call(|| client.pending_transaction(&tx_id_obj)) {
            Ok(v) => v,
            Err(e) if AlgoError::is_host_unreachable(&e) => {
                return Err(AlgoError::unreachable("pending_transaction", &e.to_string()).into());
            }
            // A quota/forbidden rejection is a hard stop, not "txn not found": surface it so a
            // poller backs off rather than looping forever on an apparent absent transaction.
            Err(e)
                if e.downcast_ref::<AlgoError>()
                    .is_some_and(AlgoError::is_quota) =>
            {
                return Err(e);
            }
            // The node does not know this txid (404) or a non-fatal read error: report "not
            // found" so callers can poll without special-casing the node's absent-txn response.
            Err(_) => return Ok(None),
        };

        let confirmed_round = resp.confirmed_round.unwrap_or(0);
        // The inner `txn` is an internally-tagged enum whose every variant carries a base64
        // `note`; serialize it and read that field rather than matching all transaction types.
        let note = match &resp.txn.txn {
            Some(txn) => {
                let v = serde_json::to_value(txn)
                    .map_err(|e| anyhow!("failed to serialize pending transaction: {e}"))?;
                v.get("note")
                    .and_then(|x| x.as_str())
                    .and_then(|s| general_purpose::STANDARD.decode(s).ok())
            }
            None => None,
        };
        Ok(Some(ConfirmedTxn {
            confirmed_round,
            note,
        }))
    }

    /// Scan the indexer's note-prefix results for the first confirmed transaction whose note
    /// satisfies `matches`, returned as a neutral [`ConfirmedTxn`], or `Ok(None)` if none does.
    ///
    /// Shared by [`AlgoOps::find_transaction_by_note`] and
    /// [`AlgoOps::find_transaction_by_note_prefix`]. The indexer only supports a note *prefix* filter
    /// (it base64-encodes the raw bytes and matches whole leading bytes — there is no sub-byte
    /// matching), so both callers pass the same `query` bytes as the server-side prefix and narrow the
    /// candidates with `matches`: full-note equality for the exact lookup, `starts_with` for the
    /// prefix lookup.
    ///
    /// Result pages are walked via the indexer's `next` token until a match is found or the results
    /// are exhausted, so the wanted hit is found even when many transactions share `query` as a prefix
    /// and it does not fall on the first page. `query` must be non-empty (an empty prefix matches every
    /// note); the callers enforce that. Surfaces `AlgoError::HostUnreachable` when the indexer is down.
    fn find_confirmed_note_matching(
        &self,
        query: &[u8],
        sender: Option<&str>,
        matches: impl Fn(&[u8]) -> bool,
    ) -> Result<Option<ConfirmedTxn>> {
        let client = self.indexer_client()?;
        // The indexer expects the note-prefix query parameter base64-encoded.
        let note_prefix = general_purpose::STANDARD.encode(query);
        let mut next: Option<String> = None;
        loop {
            let (candidates, next_token) =
                self.confirmed_notes_page(&client, &note_prefix, sender, next.as_deref())?;
            // The server-side filter already restricts to notes starting with `query`; `matches` is
            // the caller's narrowing (exact equality, or a defensive `starts_with` re-check).
            if let Some((confirmed_round, note)) =
                candidates.into_iter().find(|(_, note)| matches(note))
            {
                return Ok(Some(ConfirmedTxn {
                    confirmed_round,
                    note: Some(note),
                }));
            }
            // Advance to the next page, or stop when the indexer reports no more results.
            match next_token {
                Some(token) => next = Some(token),
                None => return Ok(None),
            }
        }
    }

    /// Collect *every* confirmed transaction whose note satisfies `matches` across all indexer
    /// note-prefix result pages, each as a neutral [`ConfirmedTxn`], in the indexer's order.
    ///
    /// The list counterpart of [`AlgoOps::find_confirmed_note_matching`]: same base64 note-prefix
    /// query and the same confirmed-and-`matches` narrowing, but it accumulates all hits instead of
    /// returning the first. Walks all pages via the `next` token so a caller aggregating over the
    /// results (for example the maximum confirmed round) sees matches beyond the first page.
    /// `query` must be non-empty (the callers enforce that). Surfaces `AlgoError::HostUnreachable`
    /// when the indexer is down.
    fn collect_confirmed_notes_matching(
        &self,
        query: &[u8],
        sender: Option<&str>,
        matches: impl Fn(&[u8]) -> bool,
    ) -> Result<Vec<ConfirmedTxn>> {
        let client = self.indexer_client()?;
        let note_prefix = general_purpose::STANDARD.encode(query);
        let mut found = Vec::new();
        let mut next: Option<String> = None;
        loop {
            let (candidates, next_token) =
                self.confirmed_notes_page(&client, &note_prefix, sender, next.as_deref())?;
            found.extend(
                candidates
                    .into_iter()
                    .filter(|(_, note)| matches(note))
                    .map(|(confirmed_round, note)| ConfirmedTxn {
                        confirmed_round,
                        note: Some(note),
                    }),
            );
            match next_token {
                Some(token) => next = Some(token),
                None => return Ok(found),
            }
        }
    }

    /// Fetch one page of the indexer note-prefix search: `note_prefix` (already base64) as the
    /// server-side filter, starting from the `next` pagination token. Returns the page's confirmed,
    /// note-bearing candidates as `(confirmed_round, note)` pairs and the next-page token (`None`
    /// when the indexer reports no more results). Shared by the find-first and collect-all scanners
    /// so the 19-argument `search_for_transactions` call lives in one place. Surfaces
    /// `AlgoError::HostUnreachable` when the indexer is down.
    fn confirmed_notes_page(
        &self,
        client: &algonaut::Indexer,
        note_prefix: &str,
        sender: Option<&str>,
        next: Option<&str>,
    ) -> Result<(Vec<(u64, Vec<u8>)>, Option<String>)> {
        // parse the optional sender filter to an `Address` the indexer call takes by reference; it must
        // outlive the call below.
        let address = sender.map(Self::parse_address).transpose()?;
        // `indexer_call` is the shared async runner (current-thread runtime + retry/backoff) for
        // indexer reads.
        let resp = match self.indexer_call(|| {
            client.search_for_transactions(
                None,              // limit
                next,              // next (pagination token)
                Some(note_prefix), // note_prefix
                None,              // tx_type
                None,              // sig_type
                None,              // transaction_id
                None,              // round
                None,              // min_round
                None,              // max_round
                None,              // asset_id
                None,              // before_time
                None,              // after_time
                None,              // currency_greater_than
                None,              // currency_less_than
                address.as_ref(),  // address — restrict to this signer when a sender filter is set
                // address_role `sender` so an address filter matches the *signer* specifically, not a
                // receiver (an anchor is a self-payment, so both roles hold; being explicit is precise).
                sender.map(|_| "sender"),
                None, // exclude_close_to
                None, // rekey_to
                None, // app_id
            )
        }) {
            Ok(v) => v,
            Err(e) if AlgoError::is_host_unreachable(&e) => {
                return Err(
                    AlgoError::unreachable("search_for_transactions", &e.to_string()).into(),
                );
            }
            Err(e) => return Err(e),
        };

        // Keep only confirmed (`confirmed_round > 0`), note-bearing rows; the caller narrows further
        // with its `matches` predicate.
        let candidates = resp
            .transactions
            .into_iter()
            .filter_map(|txn| {
                let confirmed_round = txn.confirmed_round.filter(|r| *r > 0)?;
                let note = txn.note.map(|b| b.0)?;
                Some((confirmed_round, note))
            })
            .collect();
        let next_token = match resp.next_token {
            Some(token) if !token.is_empty() => Some(token),
            _ => None,
        };
        Ok((candidates, next_token))
    }

    /// Find a confirmed transaction whose note exactly equals `note` (indexer
    /// `GET /v2/transactions?note-prefix=...`), returned as a neutral [`ConfirmedTxn`], or `Ok(None)`.
    ///
    /// The indexer only supports a note *prefix* filter, so this asks for the base64-encoded note as
    /// the prefix and keeps only a candidate whose full note bytes equal `note` — a transaction whose
    /// note merely starts with `note` is rejected. Backs a peer confirming "does a confirmed
    /// transaction with this note exist?" for a transaction it did not submit. Walks all result pages
    /// (see `find_confirmed_note_matching`) so the exact match is found even behind a run of longer
    /// notes sharing it as a prefix; surfaces `AlgoError::HostUnreachable` when the indexer is down.
    pub fn find_transaction_by_note(&self, note: &[u8]) -> Result<Option<ConfirmedTxn>> {
        if note.is_empty() {
            bail!("note must not be empty");
        }
        self.find_confirmed_note_matching(note, None, |candidate| candidate == note)
    }

    /// Find a confirmed transaction whose note exactly equals `note` **and** whose sender is `sender`,
    /// or `Ok(None)`. The sender-authenticated sibling of [`AlgoOps::find_transaction_by_note`]: the
    /// indexer filters server-side on the note prefix and the sender address (role `sender`), so a
    /// caller trusts a note only when it was signed by a known account — an unforgeable check a note a
    /// third party wrote with the same bytes cannot pass. `note` and `sender` must be non-empty.
    pub fn find_transaction_by_note_and_sender(
        &self,
        note: &[u8],
        sender: &str,
    ) -> Result<Option<ConfirmedTxn>> {
        if note.is_empty() {
            bail!("note must not be empty");
        }
        if sender.is_empty() {
            bail!("sender must not be empty");
        }
        self.find_confirmed_note_matching(note, Some(sender), |candidate| candidate == note)
    }

    /// Find a confirmed transaction whose note *starts with* `prefix` — a **byte** prefix, not a bit
    /// prefix — returned as a neutral [`ConfirmedTxn`], or `Ok(None)` when none is found.
    ///
    /// The byte-prefix sibling of [`AlgoOps::find_transaction_by_note`]: same indexer note-prefix
    /// query (the indexer base64-encodes the raw bytes and matches whole leading bytes — there is no
    /// sub-byte matching), but a note *longer* than `prefix` is a valid match, provided its leading
    /// bytes equal `prefix` (a defensive `starts_with` re-check of the server-side match). Callers
    /// wanting a field-aligned prefix must lay the note out on byte boundaries (e.g. sidewinder's
    /// fixed-width 8-byte big-endian anchor round). Walks all result pages (see
    /// `find_confirmed_note_matching`) and surfaces `AlgoError::HostUnreachable` when the indexer is
    /// down.
    ///
    /// This delivers the single-hit "is there *any* confirmed transaction with this note prefix?"
    /// primitive (`is_some()`); returning all matches or the lowest-`confirmed_round` match is
    /// deliberately out of scope.
    pub fn find_transaction_by_note_prefix(&self, prefix: &[u8]) -> Result<Option<ConfirmedTxn>> {
        // An empty prefix would match every note, so reject it (as the exact method rejects an empty
        // note).
        if prefix.is_empty() {
            bail!("prefix must not be empty");
        }
        self.find_confirmed_note_matching(prefix, None, |candidate| candidate.starts_with(prefix))
    }

    /// Find a confirmed transaction whose note *starts with* `prefix` (a **byte** prefix) **and** whose
    /// sender is `sender`, or `Ok(None)`. The sender-authenticated sibling of
    /// [`AlgoOps::find_transaction_by_note_prefix`]: the indexer filters server-side on both the note
    /// prefix and the sender address (role `sender`), so a caller answers "is there any confirmed
    /// transaction with this note prefix *from this signer*?" — e.g. "is round R anchored by a known
    /// node?". `prefix` and `sender` must be non-empty.
    pub fn find_transaction_by_note_prefix_and_sender(
        &self,
        prefix: &[u8],
        sender: &str,
    ) -> Result<Option<ConfirmedTxn>> {
        if prefix.is_empty() {
            bail!("prefix must not be empty");
        }
        if sender.is_empty() {
            bail!("sender must not be empty");
        }
        self.find_confirmed_note_matching(prefix, Some(sender), |candidate| {
            candidate.starts_with(prefix)
        })
    }

    /// Every confirmed transaction whose note *starts with* `prefix` — a **byte** prefix, not a bit
    /// prefix — each as a neutral [`ConfirmedTxn`], in the indexer's result order (this method does
    /// not sort or deduplicate). Returns `Ok(vec![])` when nothing matches.
    ///
    /// The list sibling of [`AlgoOps::find_transaction_by_note_prefix`]: the same indexer note-prefix
    /// query (the indexer base64-encodes the raw bytes and matches whole leading bytes — there is no
    /// sub-byte matching) and the same defensive `starts_with` re-check, but it collects *every*
    /// confirmed match rather than stopping at the first. That lets a caller aggregate over the set —
    /// for sidewinder's cold-start / long-partition rejoin, the maximum round across all anchor
    /// transactions, whose notes are laid out `tag ‖ round_be(8) ‖ root` so every anchor shares the
    /// `tag` prefix. Callers wanting a field-aligned prefix must lay the note out on byte boundaries.
    ///
    /// Walks all indexer result pages (see `collect_confirmed_notes_matching`), so a caller taking a
    /// maximum over the results does not miss matches beyond the first page. `prefix` must be
    /// non-empty (an empty prefix matches every note). Surfaces `AlgoError::HostUnreachable` when the
    /// indexer is down.
    ///
    /// This re-reads the whole matching history on every call. A caller polling the same prefix
    /// repeatedly (an append-only, ever-growing result set) should instead hold a
    /// [`TxnScanCache`] and use [`AlgoOps::fetch_transactions_cached`], which fetches only rounds past
    /// the last scan.
    pub fn find_transactions_by_note_prefix(&self, prefix: &[u8]) -> Result<Vec<ConfirmedTxn>> {
        // An empty prefix would match every note, so reject it (as the single-match method does).
        if prefix.is_empty() {
            bail!("prefix must not be empty");
        }
        self.collect_confirmed_notes_matching(prefix, None, |candidate| {
            candidate.starts_with(prefix)
        })
    }

    /// Every confirmed transaction whose note *starts with* `prefix` (a **byte** prefix) **and** whose
    /// sender is `sender`, in the indexer's result order. The sender-authenticated list sibling of
    /// [`AlgoOps::find_transactions_by_note_prefix`]: the indexer filters server-side on both the note
    /// prefix and the sender address (role `sender`), so a caller aggregates over only a known signer's
    /// transactions — e.g. sidewinder's cold-start rejoin taking the maximum anchor round across the
    /// anchors from *one* enrolled node account (it calls this once per account and unions/maxes).
    /// Returns `Ok(vec![])` when nothing matches. `prefix` and `sender` must be non-empty.
    ///
    /// Like [`AlgoOps::find_transactions_by_note_prefix`], this re-reads the whole matching history
    /// per call and per account; a repeated poll is better served by one shared
    /// [`AlgoOps::fetch_transactions_cached`] over the tag prefix with the sender restriction applied
    /// client-side in `ingest`, collapsing the per-account fan-out to a single incremental scan.
    pub fn find_transactions_by_note_prefix_and_sender(
        &self,
        prefix: &[u8],
        sender: &str,
    ) -> Result<Vec<ConfirmedTxn>> {
        if prefix.is_empty() {
            bail!("prefix must not be empty");
        }
        if sender.is_empty() {
            bail!("sender must not be empty");
        }
        self.collect_confirmed_notes_matching(prefix, Some(sender), |candidate| {
            candidate.starts_with(prefix)
        })
    }

    /// Incrementally refresh a caller-owned [`TxnScanCache`], then read the refreshed entries from it —
    /// the generic, min-round-watermarked counterpart of the whole-history
    /// [`AlgoOps::find_transactions_by_note_prefix`] family.
    ///
    /// Where the `find_transactions_by_note_prefix*` reads re-page the indexer from the beginning of
    /// the chain on every call, this fetches **only** rounds past the cache watermark (via the
    /// indexer's `min_round` parameter), so a long-lived, append-only result set (e.g. anchors sharing
    /// a note-prefix tag) is downloaded once and only extended thereafter. The cache is owned and
    /// passed in by the caller, so one process holds one cache per use-case; **read `cache.entries`
    /// after this returns** to use the refreshed set.
    ///
    /// - `filter` is the optional *server-side* narrowing (note-prefix, sender, app id) that keeps the
    ///   fetch cheap. `ingest` maps each fetched transaction into a cache entry, or `None` to skip — it
    ///   is the *client-side* truth (e.g. a defensive note-prefix re-check, or a sender restriction
    ///   applied locally so one un-sender-filtered cache serves many senders).
    /// - [`QueryMode::Refresh`] within `cache_lifetime_secs` performs **no** network call (it degrades
    ///   to [`QueryMode::CacheOnly`]); a stale `Refresh` fetches only rounds past the watermark; an
    ///   empty cache does a full scan. [`QueryMode::CacheOnly`] never touches the network.
    ///   [`QueryMode::ForceFull`] discards the cache and rebuilds it with a full scan.
    /// - `cache_lifetime_secs` of `None` means no freshness window — a `Refresh` always fetches
    ///   incrementally from the watermark.
    ///
    /// **Locking:** the `cache` mutex is held for the whole refresh — every `fetch_page` network
    /// round-trip — and is released before this returns, so concurrent refreshes of the same cache
    /// serialize (correct for the intended one-poller-per-cache usage). Read the entries with a fresh
    /// lock afterwards; because the refresh and that read take the lock separately, a second writer could
    /// mutate in between — so one poller per cache is assumed.
    ///
    /// Surfaces `AlgoError::HostUnreachable` when the indexer is down. Ported from
    /// `bingle_core::blockchain::algo_bingle::AlgoBingle::indexer_query_opted_in_accounts_sync`,
    /// simplified for immutable (append-only) transactions.
    pub fn fetch_transactions_cached<T>(
        &self,
        cache: &Mutex<TxnScanCache<T>>,
        filter: TxnScanFilter,
        mode: QueryMode,
        cache_lifetime_secs: Option<u64>,
        ingest: impl Fn(&ScannedTxn) -> Option<T>,
    ) -> Result<()> {
        let client = self.indexer_client()?;
        let prepared = filter.prepare()?;
        let now = Self::now_unix_secs();
        Self::fetch_transactions_cached_with(
            cache,
            mode,
            cache_lifetime_secs,
            now,
            ingest,
            |min_round, next| self.fetch_scan_page(&client, &prepared, min_round, next),
        )
    }

    /// The network-free engine behind [`AlgoOps::fetch_transactions_cached`]: the caching / freshness /
    /// watermark logic, with the actual page fetch injected as `fetch_page` and the wall-clock as
    /// `now`. `fetch_page(min_round, next)` returns one [`TxnScanPage`]; `min_round` is `None` for a
    /// full scan and `Some(r)` for an incremental scan from round `r`. Exposed under `test-support` so
    /// the engine is unit-tested with a stubbed, request-counting fetcher (no node required).
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn fetch_transactions_cached_with<T>(
        cache: &Mutex<TxnScanCache<T>>,
        mode: QueryMode,
        cache_lifetime_secs: Option<u64>,
        now: u64,
        ingest: impl Fn(&ScannedTxn) -> Option<T>,
        mut fetch_page: impl FnMut(Option<u64>, Option<&str>) -> Result<TxnScanPage>,
    ) -> Result<()> {
        let mut cache = cache
            .lock()
            .map_err(|_| anyhow!("transaction scan cache mutex poisoned"))?;

        // Decide whether to fetch and, if so, from which round. `Some(min_round)` fetches (`None`
        // inside = full scan, `Some(r)` = incremental from `r`); the outer `None` skips the network.
        let fetch_from: Option<Option<u64>> = match mode {
            QueryMode::CacheOnly => None,
            QueryMode::ForceFull => {
                // Rebuild from scratch: drop the accumulated entries and the watermark, then full scan.
                cache.entries.clear();
                cache.last_round = 0;
                Some(None)
            }
            QueryMode::Refresh => {
                if cache.last_updated == 0 {
                    // Never scanned (a full scan that matched nothing still stamps `last_updated`),
                    // so bootstrap with a full scan.
                    Some(None)
                } else if Self::scan_cache_is_fresh(cache.last_updated, now, cache_lifetime_secs) {
                    // Within the freshness window — degrade to CacheOnly (zero network).
                    None
                } else {
                    // Stale: fetch only rounds strictly past the watermark.
                    Some(Some(cache.last_round + 1))
                }
            }
        };

        if let Some(min_round) = fetch_from {
            // Start the watermark from the existing value so it only ever advances (for a full scan
            // `last_round` was reset to 0 above).
            let mut watermark = cache.last_round;
            let mut next: Option<String> = None;
            loop {
                let page = fetch_page(min_round, next.as_deref())?;
                // Advance the watermark to the greatest `current-round` seen across the pages. This is
                // safe — no round is skipped by the next refresh's `watermark + 1` floor — because the
                // Algorand indexer orders `search_for_transactions` oldest-to-newest by round and the
                // `next` cursor advances monotonically through them: when it is exhausted
                // (`next_token == None`) every matching transaction through the final page's
                // `current-round` has been returned. (`current-round` only grows across sequential
                // requests, so `max` equals the final page's value; taking the max is just robust to
                // any transient non-monotonicity.) If the indexer instead pinned the result set to the
                // first request's round while `current-round` kept climbing per page, `max` could skip
                // the intervening rounds — but that is not this indexer's contract.
                watermark = watermark.max(page.current_round);
                for txn in &page.txns {
                    if let Some(entry) = ingest(txn) {
                        cache.entries.push(entry);
                    }
                }
                match page.next_token {
                    Some(token) => next = Some(token),
                    None => break,
                }
            }
            // The indexer only reports rounds it has indexed, so its `current-round` is a safe
            // watermark: the next incremental refresh resumes at `watermark + 1`.
            cache.last_round = watermark;
            cache.last_updated = now;
        }

        Ok(())
    }

    /// Whether a cache stamped at `last_updated` is still fresh at `now` for `lifetime`. A `None`
    /// lifetime has no freshness window, so the cache is always treated as stale (always refresh).
    fn scan_cache_is_fresh(last_updated: u64, now: u64, lifetime: Option<u64>) -> bool {
        match lifetime {
            Some(secs) => now.saturating_sub(last_updated) < secs,
            None => false,
        }
    }

    /// Current unix time in whole seconds, or `0` if the system clock is before the epoch. A `0` here
    /// (like any `now` at or behind `last_updated`) makes `scan_cache_is_fresh` treat the cache as
    /// *fresh* — so a `Refresh` degrades to `CacheOnly` rather than erroring. That only arises if the
    /// wall clock is set before 1970, so the effect is negligible.
    fn now_unix_secs() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0)
    }

    /// Fetch one page of the incremental scan: the same 19-argument `search_for_transactions` call as
    /// [`AlgoOps::confirmed_notes_page`], but exposing the indexer's `min_round` (for the watermark),
    /// carrying the transaction `sender`, and *not* dropping note-less rows (the caller's `ingest`
    /// decides). Surfaces `AlgoError::HostUnreachable` when the indexer is down.
    fn fetch_scan_page(
        &self,
        client: &algonaut::Indexer,
        filter: &PreparedScanFilter,
        min_round: Option<u64>,
        next: Option<&str>,
    ) -> Result<TxnScanPage> {
        let resp = match self.indexer_call(|| {
            client.search_for_transactions(
                None,                          // limit
                next,                          // next (pagination token)
                filter.note_prefix.as_deref(), // note_prefix
                None,                          // tx_type
                None,                          // sig_type
                None,                          // transaction_id
                None,                          // round
                min_round,                     // min_round — the incremental watermark
                None,                          // max_round
                None,                          // asset_id
                None,                          // before_time
                None,                          // after_time
                None,                          // currency_greater_than
                None,                          // currency_less_than
                filter.address.as_ref(),       // address — restrict to this signer when set
                // address_role `sender` so an address filter matches the *signer*, not a receiver.
                filter.address.as_ref().map(|_| "sender"),
                None,          // exclude_close_to
                None,          // rekey_to
                filter.app_id, // application_id
            )
        }) {
            Ok(v) => v,
            Err(e) if AlgoError::is_host_unreachable(&e) => {
                return Err(
                    AlgoError::unreachable("search_for_transactions", &e.to_string()).into(),
                );
            }
            Err(e) => return Err(e),
        };

        // Keep only confirmed rows (`confirmed_round > 0`); carry the sender and the decoded note
        // (which may be absent — the caller's `ingest` narrows further).
        let txns = resp
            .transactions
            .into_iter()
            .filter_map(|txn| {
                let confirmed_round = txn.confirmed_round.filter(|r| *r > 0)?;
                Some(ScannedTxn {
                    confirmed_round,
                    sender: txn.sender,
                    note: txn.note.map(|b| b.0),
                })
            })
            .collect();
        let next_token = match resp.next_token {
            Some(token) if !token.is_empty() => Some(token),
            _ => None,
        };
        Ok(TxnScanPage {
            txns,
            next_token,
            current_round: resp.current_round,
        })
    }

    /// Incrementally refresh a caller-owned [`AccountScanCache`] of the accounts opted into `app_id`,
    /// leaving the refreshed set in `cache.entries` — the account-scan counterpart of
    /// [`AlgoOps::fetch_transactions_cached`].
    ///
    /// The scan is **app-scoped** (the indexer `application-id` filter), so it hits an index and
    /// cannot degrade into an unbounded scan. `ingest` maps each fetched [`ScannedAccount`] into a
    /// cache entry, or `None` to skip it (so the caller decodes its own local-state field — a
    /// membership bit, an endpoint byte-slice — and can drop accounts that do not match); **read
    /// `cache.entries` after this returns** to use the refreshed `(address, entry)` set.
    ///
    /// - [`QueryMode::Refresh`] within `cache_lifetime_secs` performs **no** network call (it degrades
    ///   to [`QueryMode::CacheOnly`]); an empty cache does a full paged-to-completion scan; a stale
    ///   `Refresh` discovers the accounts changed past the watermark (via the app-scoped transaction
    ///   index, which *does* support a min-round floor) and re-reads only those, replacing or removing
    ///   their entry. [`QueryMode::CacheOnly`] never touches the network. [`QueryMode::ForceFull`]
    ///   discards the cache and rebuilds it with a full scan.
    /// - `cache_lifetime_secs` of `None` means no freshness window — a `Refresh` always refreshes.
    /// - an empty result still stamps `last_updated`, so an all-empty scan is not re-run every poll.
    ///
    /// Every fetched page (each full-scan page, each change-discovery page, each per-account re-read)
    /// is issued through [`indexer_call`](Self::indexer_call), so it counts against the per-request counter
    /// ([`requests_made`](Self::requests_made)).
    ///
    /// **Locking:** the `cache` mutex is held for the whole refresh — every network round-trip — and
    /// released before this returns, so concurrent refreshes of the same cache serialize (correct for
    /// the intended one-poller-per-cache usage). Read the entries with a fresh lock afterwards; because
    /// the refresh and that read take the lock separately, a second writer could mutate in between — so
    /// one poller per cache is assumed.
    ///
    /// Surfaces `AlgoError::HostUnreachable` when the indexer is down. Ported from
    /// `bingle_core::blockchain::algo_bingle::AlgoBingle::indexer_query_opted_in_accounts_sync`,
    /// generalised down so it composes with the cached transaction scan and is reusable outside Bingle.
    pub fn fetch_opted_in_accounts_cached<T>(
        &self,
        app_id: u64,
        cache: &Mutex<AccountScanCache<T>>,
        mode: QueryMode,
        cache_lifetime_secs: Option<u64>,
        ingest: impl Fn(&ScannedAccount) -> Option<T>,
    ) -> Result<()> {
        if app_id == 0 {
            bail!("app_id must be > 0");
        }
        let client = self.indexer_client()?;
        let now = Self::now_unix_secs();
        Self::fetch_opted_in_accounts_cached_with(
            cache,
            mode,
            cache_lifetime_secs,
            now,
            ingest,
            |next| self.fetch_account_page(&client, app_id, next),
            |min_round, next| self.fetch_changed_addresses_page(&client, app_id, min_round, next),
            |address| self.lookup_opted_in_account(&client, app_id, address),
        )
    }

    /// The network-free engine behind [`AlgoOps::fetch_opted_in_accounts_cached`]: the caching /
    /// freshness / watermark / revisit logic, with the three network operations injected and the
    /// wall-clock as `now`. `fetch_full_page(next)` pages a full scan; `fetch_changed(min_round, next)`
    /// pages the change-discovery scan (addresses touched past `min_round`); `lookup_account(address)`
    /// re-reads one account, returning `None` when it is no longer opted in. Exposed under
    /// `test-support` so the engine is unit-tested with a stubbed, request-counting fetcher (no node).
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn fetch_opted_in_accounts_cached_with<T>(
        cache: &Mutex<AccountScanCache<T>>,
        mode: QueryMode,
        cache_lifetime_secs: Option<u64>,
        now: u64,
        ingest: impl Fn(&ScannedAccount) -> Option<T>,
        mut fetch_full_page: impl FnMut(Option<&str>) -> Result<AccountScanPage>,
        mut fetch_changed: impl FnMut(u64, Option<&str>) -> Result<ChangedAddressesPage>,
        mut lookup_account: impl FnMut(&str) -> Result<Option<ScannedAccount>>,
    ) -> Result<()> {
        let mut cache = cache
            .lock()
            .map_err(|_| anyhow!("account scan cache mutex poisoned"))?;

        // Decide the scan kind: `None` = no network (CacheOnly, or a fresh Refresh); `Some(true)` = a
        // full paged scan; `Some(false)` = an incremental change-discovery refresh from the watermark.
        let scan: Option<bool> = match mode {
            QueryMode::CacheOnly => None,
            QueryMode::ForceFull => {
                // Rebuild from scratch: drop the accumulated entries and the watermark, then full scan.
                cache.entries.clear();
                cache.last_round = 0;
                Some(true)
            }
            QueryMode::Refresh => {
                if cache.last_updated == 0 || cache.last_round == 0 {
                    // Never scanned (a full scan that matched nothing still stamps `last_updated`),
                    // so bootstrap with a full scan.
                    Some(true)
                } else if Self::scan_cache_is_fresh(cache.last_updated, now, cache_lifetime_secs) {
                    // Within the freshness window — degrade to CacheOnly (zero network).
                    None
                } else {
                    // Stale: discover and re-read only the accounts changed past the watermark.
                    Some(false)
                }
            }
        };

        match scan {
            // CacheOnly / fresh Refresh: leave the cache exactly as it is.
            None => {}
            // Full scan: page every opted-in account to completion, rebuilding the set.
            Some(true) => {
                cache.entries.clear();
                // Watermark the full scan at the *minimum* `current-round` across its pages (the first
                // page's, since it only grows), NOT the max. `search_for_accounts` paginates by address
                // over *mutable* accounts with no round pinning, so an opt-in / admin bit-set that lands
                // mid-scan on an already-traversed address range is missed by this scan. Anchoring the
                // watermark at the earliest page's round means the next incremental refresh re-discovers
                // (via the transaction index) every account touched from that round on, re-catching the
                // raced change — at the cost of a small re-scan overlap. Taking the max instead would
                // jump `last_round` past the race and lose the account until a `ForceFull`. (The
                // transaction scan can safely take the max because its rows are immutable and ordered by
                // round; account pages are neither.)
                let mut watermark: Option<u64> = None;
                let mut next: Option<String> = None;
                loop {
                    let page = fetch_full_page(next.as_deref())?;
                    watermark = Some(match watermark {
                        Some(w) => w.min(page.current_round),
                        None => page.current_round,
                    });
                    for acct in &page.accounts {
                        if let Some(entry) = ingest(acct) {
                            // A paginated `search_for_accounts` yields each address at most once, so the
                            // rebuilt set needs no dedup — push directly (O(1) per account).
                            cache.entries.push((acct.address.clone(), entry));
                        }
                    }
                    match page.next_token {
                        Some(token) => next = Some(token),
                        None => break,
                    }
                }
                // The loop always fetches at least one page, so `watermark` is always set.
                cache.last_round = watermark.unwrap_or(cache.last_round);
                cache.last_updated = now;
            }
            // Incremental refresh: the account index has no min-round filter, so discover which
            // accounts changed since the watermark via the app-scoped transaction index, then re-read
            // only those (an account's local state can change, so this revisits rather than appends).
            Some(false) => {
                let min_round = cache.last_round + 1;
                // The change-discovery scan runs over the transaction index (immutable rows ordered by
                // round), so the max `current-round` across its pages is a safe watermark — as in the
                // transaction scan.
                let mut watermark = cache.last_round;
                let mut next: Option<String> = None;
                // Accumulate the distinct changed addresses in first-seen order: `seen` gives O(1)
                // dedup, `changed` preserves a deterministic re-read order.
                let mut seen: HashSet<String> = HashSet::new();
                let mut changed: Vec<String> = Vec::new();
                loop {
                    let page = fetch_changed(min_round, next.as_deref())?;
                    watermark = watermark.max(page.current_round);
                    for addr in page.addresses {
                        if seen.insert(addr.clone()) {
                            changed.push(addr);
                        }
                    }
                    match page.next_token {
                        Some(token) => next = Some(token),
                        None => break,
                    }
                }
                // Re-read each changed account: upsert its refreshed entry, or remove it when the
                // account has opted out (`None`) or the caller's `ingest` now rejects it.
                for addr in &changed {
                    match lookup_account(addr)? {
                        Some(acct) => match ingest(&acct) {
                            Some(entry) => {
                                Self::upsert_account_entry(&mut cache.entries, addr, entry)
                            }
                            None => Self::remove_account_entry(&mut cache.entries, addr),
                        },
                        None => Self::remove_account_entry(&mut cache.entries, addr),
                    }
                }
                cache.last_round = watermark;
                cache.last_updated = now;
            }
        }

        Ok(())
    }

    /// Insert `entry` under `address`, replacing any existing entry for that address (the account set
    /// is keyed by address, so a revisit updates in place rather than duplicating). Linear in the
    /// current entry count; only the incremental refresh calls it, once per *changed* account, so the
    /// cost is `O(changed × entries)` per refresh — negligible while the changed set per poll is small.
    /// The full-scan bootstrap pushes directly instead (see above), so it stays `O(entries)`.
    fn upsert_account_entry<T>(entries: &mut Vec<(String, T)>, address: &str, entry: T) {
        if let Some(slot) = entries.iter_mut().find(|(a, _)| a == address) {
            slot.1 = entry;
        } else {
            entries.push((address.to_string(), entry));
        }
    }

    /// Drop the entry for `address`, if any (an account that has opted out or no longer matches).
    fn remove_account_entry<T>(entries: &mut Vec<(String, T)>, address: &str) {
        entries.retain(|(a, _)| a != address);
    }

    /// Fetch one page of a full opted-in-account scan: `search_for_accounts` filtered to `app_id` (the
    /// index-hitting filter), trimming the payload to what the local-state decode needs. Surfaces
    /// `AlgoError::HostUnreachable` when the indexer is down.
    fn fetch_account_page(
        &self,
        client: &algonaut::Indexer,
        app_id: u64,
        next: Option<&str>,
    ) -> Result<AccountScanPage> {
        let resp = match self.indexer_call(|| {
            client.search_for_accounts(
                None,                                // asset_id
                None,                                // limit — the indexer default page size
                next,                                // next (pagination token)
                None,                                // currency_greater_than
                None,                                // include_all
                Self::account_scan_excludes(), // exclude — trim assets/created-* from the payload
                None,                          // currency_less_than
                None,                          // auth_addr
                None,                          // round
                Some(algonaut::core::AppId(app_id)), // app_id — the index-hitting filter
            )
        }) {
            Ok(v) => v,
            Err(e) if AlgoError::is_host_unreachable(&e) => {
                return Err(AlgoError::unreachable("search_for_accounts", &e.to_string()).into());
            }
            Err(e) => return Err(e),
        };

        let mut accounts = Vec::with_capacity(resp.accounts.len());
        for acct in &resp.accounts {
            let v = serde_json::to_value(acct)
                .map_err(|e| anyhow!("failed to serialize account: {e}"))?;
            accounts.push(Self::scanned_account_from(&v, app_id));
        }
        let next_token = match resp.next_token {
            Some(token) if !token.is_empty() => Some(token),
            _ => None,
        };
        Ok(AccountScanPage {
            accounts,
            next_token,
            current_round: resp.current_round,
        })
    }

    /// Fetch one page of the change-discovery scan: `search_for_transactions` filtered to `app_id` with
    /// the `min_round` watermark floor, collecting the addresses each transaction touched (sender,
    /// app-call account references, and inner transactions). Surfaces `AlgoError::HostUnreachable` when
    /// the indexer is down.
    fn fetch_changed_addresses_page(
        &self,
        client: &algonaut::Indexer,
        app_id: u64,
        min_round: u64,
        next: Option<&str>,
    ) -> Result<ChangedAddressesPage> {
        let resp = match self.indexer_call(|| {
            client.search_for_transactions(
                None,                                // limit — the indexer default page size
                next,                                // next (pagination token)
                None,                                // note_prefix
                None,                                // tx_type
                None,                                // sig_type
                None,                                // transaction_id
                None,                                // round
                Some(min_round),                     // min_round — the incremental watermark floor
                None,                                // max_round
                None,                                // asset_id
                None,                                // before_time
                None,                                // after_time
                None,                                // currency_greater_than
                None,                                // currency_less_than
                None,                                // address
                None,                                // address_role
                None,                                // exclude_close_to
                None,                                // rekey_to
                Some(algonaut::core::AppId(app_id)), // application_id — the index-hitting filter
            )
        }) {
            Ok(v) => v,
            Err(e) if AlgoError::is_host_unreachable(&e) => {
                return Err(
                    AlgoError::unreachable("search_for_transactions", &e.to_string()).into(),
                );
            }
            Err(e) => return Err(e),
        };

        let mut addresses = Vec::new();
        for txn in &resp.transactions {
            Self::collect_changed_addresses(txn, &mut addresses);
        }
        let next_token = match resp.next_token {
            Some(token) if !token.is_empty() => Some(token),
            _ => None,
        };
        Ok(ChangedAddressesPage {
            addresses,
            next_token,
            current_round: resp.current_round,
        })
    }

    /// Append every address a transaction touched to `out`: the sender, any accounts referenced by an
    /// application-call transaction (so an admin app-call that sets *another* account's local-state bit
    /// — that account is a foreign account, not the sender — is still discovered), and, recursively,
    /// the same for inner transactions. These are the accounts whose local state a change-discovery
    /// page must re-read. Appends without deduplicating — the engine dedups across the whole scan with a
    /// `HashSet`, so this stays linear in the transaction's address count.
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn collect_changed_addresses(
        txn: &algonaut::model::indexer::Transaction,
        out: &mut Vec<String>,
    ) {
        out.push(txn.sender.clone());
        if let Some(app_txn) = &txn.application_transaction {
            if let Some(accounts) = &app_txn.accounts {
                for addr in accounts {
                    out.push(addr.clone());
                }
            }
        }
        if let Some(inner_txns) = &txn.inner_txns {
            for inner in inner_txns {
                Self::collect_changed_addresses(inner, out);
            }
        }
    }

    /// Re-read one account and return it as a [`ScannedAccount`] **only while it still holds local
    /// state for `app_id`** — `None` once the account has opted out (or was deleted), so the caller
    /// drops it from the cache. A closed account is gone from the indexer's current state, which
    /// answers the lookup with HTTP 404, so that 404 is `None` too: failing here would stop the
    /// watermark advancing and fail every later refresh on the same account. Other errors still
    /// fail the refresh. Surfaces `AlgoError::HostUnreachable` when the indexer is down.
    fn lookup_opted_in_account(
        &self,
        client: &algonaut::Indexer,
        app_id: u64,
        address: &str,
    ) -> Result<Option<ScannedAccount>> {
        let addr = Self::parse_address(address)?;
        let resp = match self.indexer_call(|| {
            client.lookup_account_by_id(&addr, None, None, Self::account_scan_excludes())
        }) {
            Ok(v) => v,
            Err(e)
                if e.downcast_ref::<AlgoError>()
                    .is_some_and(|algo_err| algo_err.status() == Some(404)) =>
            {
                return Ok(None);
            }
            Err(e) if AlgoError::is_host_unreachable(&e) => {
                return Err(AlgoError::unreachable("lookup_account_by_id", &e.to_string()).into());
            }
            Err(e) => return Err(e),
        };

        let acct = *resp.account;
        let v =
            serde_json::to_value(&acct).map_err(|e| anyhow!("failed to serialize account: {e}"))?;
        match Self::decode_app_local_state(&v, app_id) {
            Some(local_state) => Ok(Some(ScannedAccount {
                address: acct.address,
                local_state,
            })),
            None => Ok(None),
        }
    }

    /// Build a [`ScannedAccount`] from an account's serialized indexer JSON: the address plus its
    /// decoded local state for `app_id` (empty when absent). Bakes in no schema — the caller's
    /// `ingest` decodes its own field from `local_state`.
    fn scanned_account_from(account_json: &serde_json::Value, app_id: u64) -> ScannedAccount {
        let address = account_json
            .get("address")
            .and_then(|x| x.as_str())
            .unwrap_or_default()
            .to_string();
        let local_state = Self::decode_app_local_state(account_json, app_id).unwrap_or_default();
        ScannedAccount {
            address,
            local_state,
        }
    }

    /// The indexer `exclude` list for account reads in the opted-in scan: drop the parts of an account
    /// the local-state decode never touches (asset holdings, created apps/assets) to trim the payload,
    /// while keeping `apps-local-state` (the whole point of the scan).
    fn account_scan_excludes() -> Option<Vec<String>> {
        Some(vec![
            "assets".to_string(),
            "created-apps".to_string(),
            "created-assets".to_string(),
        ])
    }

    pub fn set_asset_clawback_to_app(&self, app_id: u64, asset_id: u64) -> Result<()> {
        if app_id == 0 {
            bail!("app_id must be > 0");
        }
        if asset_id == 0 {
            bail!("asset_id must be > 0");
        }

        let client = self.algod_client()?;

        // Identify the caller address (signer)
        let caller = self.require_address()?;

        // Authorization check: the caller must be the asset manager (on-chain authority for UpdateAsset).
        let asset_info = self
            .algod_call(|| client.asset(algonaut::core::AssetId(asset_id)))
            .map_err(|e| anyhow!("failed to fetch asset information: {e}"))?;
        let v_asset = serde_json::to_value(&asset_info)
            .map_err(|e| anyhow!("failed to serialize asset info: {e}"))?;
        let asset_manager_str = v_asset
            .get("params")
            .and_then(|p| p.get("manager").and_then(|x| x.as_str()))
            .ok_or_else(|| anyhow!("asset {} info did not contain manager field", asset_id))?;
        let asset_manager = Self::parse_address(asset_manager_str)?;
        if caller != asset_manager {
            bail!(
                "Only the asset manager ({}) can set asset clawback, but called by {}",
                asset_manager_str,
                caller
            );
        }

        // Fetch application address
        let app_addr_str = self.contract_address(app_id)?;
        let app_addr = Self::parse_address(&app_addr_str)?;

        // Fetch suggested params
        let params = self
            .algod_call(|| client.suggested_params())
            .map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;

        // Manager must sign this transaction; use caller as it is verified to be the manager.
        // Build asset reconfiguration: explicitly keep manager as the caller; set clawback and reserve to app address.
        let tx = algonaut::transaction::builder::UpdateAsset::new(
            caller,
            algonaut::core::AssetId(asset_id),
        )
        .manager(caller)
        .reserve(app_addr)
        .clawback(app_addr)
        .note(Self::unique_note())
        .build(&params)
        .map_err(|e| anyhow!("failed to build asset config transaction: {e}"))?;

        // Sign and submit
        let sk = self.private_key_bytes()?;
        let seed: [u8; 32] = sk
            .as_slice()
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
        let account = algonaut::transaction::account::Account::from_seed(seed);
        let signed_tx = account
            .sign(tx)
            .map_err(|e| anyhow!("failed to sign asset config transaction: {e}"))?;
        let signed = signed_tx
            .to_msg_pack()
            .map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;

        let tx_id = self
            .algod_call(|| client.send_raw(&signed))
            .map_err(|e| anyhow!("send_raw failed: {e}"))?
            .tx_id;

        self.wait_for_confirmation(&tx_id, 10)?;
        algo_log!(
            "Successfully set asset {} clawback and reserve to app address {}",
            asset_id,
            app_addr
        );
        Ok(())
    }

    /// Change an ASA's reserve address using an AssetConfiguration (reconfigure) transaction.
    /// Requires the caller to be the asset creator (manager) to succeed on-chain.
    /// Additionally, after updating the reserve address, transfer the caller's current
    /// holding of the asset to the new reserve address (if any balance is held).
    pub fn change_asset_reserve_address(&self, asset_id: u64, reserve_address: &str) -> Result<()> {
        if asset_id == 0 {
            bail!("asset_id must be > 0");
        }
        // Parse target reserve address early
        let new_reserve = Self::parse_address(reserve_address)
            .map_err(|e| anyhow!("invalid reserve address: {e}"))?;

        // We must sign as the asset manager/creator
        let sk = self.private_key_bytes()?;
        let signer_addr = self.require_address()?;

        // Verify the caller is the asset creator by querying asset information
        let client = self.algod_client()?;
        let asset_info = self
            .algod_call(|| client.asset(algonaut::core::AssetId(asset_id)))
            .map_err(|e| anyhow!("failed to fetch asset information: {e}"))?;
        let v = serde_json::to_value(&asset_info)
            .map_err(|e| anyhow!("failed to serialize asset info: {e}"))?;
        // Try to read creator from params or top-level
        let creator_str = v
            .get("params")
            .and_then(|p| p.get("creator").and_then(|x| x.as_str()))
            .or_else(|| v.get("creator").and_then(|x| x.as_str()))
            .or_else(|| {
                v.get("params").and_then(|p| {
                    p.get("creator-address")
                        .or_else(|| p.get("creator_address"))
                        .and_then(|x| x.as_str())
                })
            })
            .ok_or_else(|| anyhow!("asset info did not contain creator field"))?;
        let caller_str = {
            use std::str::FromStr;
            algonaut::core::Address::from_str(
                self.address
                    .as_ref()
                    .ok_or_else(|| anyhow!("This operation needs an address"))?,
            )
            .map_err(|e| anyhow!("invalid caller address: {e}"))?
            .to_string()
        };
        if creator_str != caller_str {
            bail!("caller must be the asset creator to change the reserve address");
        }

        // Suggested params
        let params = self
            .algod_call(|| client.suggested_params())
            .map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;

        // Build UpdateAsset setting reserve and clawback to the same new address; keep manager unchanged (set to signer to be explicit)
        let tx = algonaut::transaction::builder::UpdateAsset::new(
            signer_addr,
            algonaut::core::AssetId(asset_id),
        )
        .manager(signer_addr)
        .reserve(new_reserve)
        .clawback(new_reserve)
        .note(Self::unique_note())
        .build(&params)
        .map_err(|e| anyhow!("failed to build asset config transaction: {e}"))?;
        algo_log!("[change_asset_reserve_address] tx: {:#?}", tx);

        // Sign and submit
        let seed: [u8; 32] = sk
            .as_slice()
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
        let account = algonaut::transaction::account::Account::from_seed(seed);
        let signed_tx = account
            .sign(tx)
            .map_err(|e| anyhow!("failed to sign asset config transaction: {e}"))?;
        let signed = signed_tx
            .to_msg_pack()
            .map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
        let tx_id = self
            .algod_call(|| client.send_raw(&signed))
            .map_err(|e| anyhow!("send_raw failed: {e}"))?
            .tx_id;
        // Wait for reconfiguration confirmation
        self.wait_for_confirmation(&tx_id, 10)?;

        // After reserve update, transfer creator's current holdings to the new reserve address
        // 1) Determine creator's balance of this asset
        let acct_info = self
            .algod_call(|| client.account(&signer_addr))
            .map_err(|e| anyhow!("failed to fetch creator account information: {e}"))?;
        let va = serde_json::to_value(&acct_info)
            .map_err(|e| anyhow!("failed to serialize creator account info: {e}"))?;
        let mut creator_amount: u64 = 0;
        if let Some(arr) = va.get("assets").and_then(|x| x.as_array()) {
            for holding in arr {
                let id = holding
                    .get("asset-id")
                    .and_then(|x| x.as_u64())
                    .or_else(|| holding.get("asset_id").and_then(|x| x.as_u64()))
                    .unwrap_or(0);
                if id == asset_id {
                    creator_amount = holding.get("amount").and_then(|x| x.as_u64()).unwrap_or(0);
                    break;
                }
            }
        }
        if creator_amount == 0 {
            algo_log!(
                "[change_asset_reserve_address] creator has no balance of asset {}",
                asset_id
            );
            return Ok(()); // nothing to move
        }

        // 2) Ensure the new reserve address is opted-in to receive the asset
        if !self.is_account_opted_in_to_asset(reserve_address, asset_id)? {
            bail!("new reserve address is not opted-in to asset {}", asset_id);
        }

        // 3) Transfer entire balance to the new reserve address
        self.send_asset(asset_id, creator_amount, reserve_address)
    }

    pub fn send_asset(&self, asset_id: u64, amount: u64, to_address: &str) -> Result<()> {
        if asset_id == 0 {
            bail!("asset_id must be > 0");
        }
        if amount == 0 {
            bail!("amount must be > 0");
        }

        // Validate env and addresses
        let sk = self.private_key_bytes()?;
        let from = self.require_address()?;
        let to = Self::parse_address(to_address)?;

        let client = self.algod_client()?;
        let params = self
            .algod_call(|| client.suggested_params())
            .map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;

        // Build asset transfer transaction
        let tx = algonaut::transaction::TransferAsset::new(
            from,
            algonaut::core::AssetId(asset_id),
            amount,
            to,
        )
        .note(Self::unique_note())
        .build(&params)
        .map_err(|e| anyhow!("failed to build asset transfer transaction: {e}"))?;

        algo_log!("[send_asset] tx: {:#?}", tx);

        // Sign and submit
        let seed: [u8; 32] = sk
            .as_slice()
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
        let account = algonaut::transaction::account::Account::from_seed(seed);
        let signed_tx = account
            .sign(tx)
            .map_err(|e| anyhow!("failed to sign asset transfer transaction: {e}"))?;
        let signed = signed_tx
            .to_msg_pack()
            .map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;

        let tx_id = self
            .algod_call(|| client.send_raw(&signed))
            .map_err(|e| anyhow!("send_raw failed: {e}"))?
            .tx_id;

        self.wait_for_confirmation(&tx_id, 10)
    }

    pub fn opt_in_to_asset(&self, asset_id: u64) -> Result<()> {
        if asset_id == 0 {
            bail!("asset_id must be > 0");
        }
        // Ensure we have account access
        let sk = self.private_key_bytes()?;
        let addr = self.require_address()?;

        let client = self.algod_client()?;
        let params = self
            .algod_call(|| client.suggested_params())
            .map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;

        // Opt-in is a zero-amount transfer from self to self
        let tx = algonaut::transaction::TransferAsset::new(
            addr,
            algonaut::core::AssetId(asset_id),
            0,
            addr,
        )
        .note(Self::unique_note())
        .build(&params)
        .map_err(|e| anyhow!("failed to build asset opt-in transaction: {e}"))?;

        let seed: [u8; 32] = sk
            .as_slice()
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
        let account = algonaut::transaction::account::Account::from_seed(seed);
        let signed_tx = account
            .sign(tx)
            .map_err(|e| anyhow!("failed to sign asset opt-in transaction: {e}"))?;
        let signed = signed_tx
            .to_msg_pack()
            .map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;

        let tx_id = self
            .algod_call(|| client.send_raw(&signed))
            .map_err(|e| anyhow!("send_raw failed: {e}"))?
            .tx_id;

        self.wait_for_confirmation(&tx_id, 10)
    }

    /// Extract (creator, reserve) addresses from an asset_information JSON value. Returns None if fields missing.
    ///
    /// Production helper used by `recover_reserve_balance`; `pub(crate)`, and re-exported
    /// publicly under `test-support` so the reserve-helper tests can exercise the parsing.
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn parse_creator_reserve_from_asset_info_value(
        v: &serde_json::Value,
    ) -> Option<(String, String)> {
        let params = v.get("params");
        let creator = params
            .and_then(|p| p.get("creator").and_then(|x| x.as_str()))
            .or_else(|| v.get("creator").and_then(|x| x.as_str()))?;
        let reserve = params.and_then(|p| {
            p.get("reserve").and_then(|x| x.as_str()).or_else(|| {
                p.get("reserve-address")
                    .or_else(|| p.get("reserve_address"))
                    .and_then(|x| x.as_str())
            })
        })?;
        Some((creator.to_string(), reserve.to_string()))
    }

    /// From an account_information JSON value, find the holding amount for the given asset id.
    ///
    /// Production helper used by `asset_holding` / `recover_reserve_balance`; `pub(crate)`, and
    /// re-exported publicly under `test-support` so the reserve-helper tests can exercise it.
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn parse_holding_amount_from_account_value(
        v: &serde_json::Value,
        asset_id: u64,
    ) -> u64 {
        if let Some(arr) = v.get("assets").and_then(|x| x.as_array()) {
            for holding in arr {
                let id = holding
                    .get("asset-id")
                    .and_then(|x| x.as_u64())
                    .or_else(|| holding.get("asset_id").and_then(|x| x.as_u64()))
                    .unwrap_or(0);
                if id == asset_id {
                    return holding.get("amount").and_then(|x| x.as_u64()).unwrap_or(0);
                }
            }
        }
        0
    }

    /// The creator address of `app_id` from its on-chain application parameters. Errors if the app
    /// does not exist / cannot be read.
    ///
    /// Cached per client (shared by `Clone`d handles): an app's creator never changes, so only the
    /// first lookup for an `app_id` reads algod; later ones make no request. A failed lookup is not
    /// cached. One consequence: if the app is deleted after its creator was cached, an app call is
    /// built and submitted and then rejected on chain, rather than failing before submission.
    pub fn app_creator(&self, app_id: u64) -> Result<String> {
        if app_id == 0 {
            bail!("app_id must be > 0");
        }
        if let Some(creator) = self.cached_app_creator(app_id) {
            return Ok(creator);
        }
        let creator = self.fetch_app_creator(app_id)?;
        self.app_creators
            .lock()
            .map_err(|_| anyhow!("app creator cache lock poisoned"))?
            .insert(app_id, creator.clone());
        Ok(creator)
    }

    /// `app_id`'s creator from the per-client cache, or `None` if it has not been looked up yet (or
    /// the cache lock is poisoned, in which case the caller simply re-reads algod).
    fn cached_app_creator(&self, app_id: u64) -> Option<String> {
        self.app_creators.lock().ok()?.get(&app_id).cloned()
    }

    /// Read `app_id`'s creator from algod (one request), bypassing the cache.
    fn fetch_app_creator(&self, app_id: u64) -> Result<String> {
        let client = self.algod_client()?;
        let app_info = self
            .algod_call(|| client.app(algonaut::core::AppId(app_id)))
            .map_err(|e| anyhow!("failed to fetch application {app_id} info: {e}"))?;
        let v = serde_json::to_value(&app_info)
            .map_err(|e| anyhow!("failed to serialize application info: {e}"))?;
        Self::parse_app_creator_from_app_info_value(&v)
            .ok_or_else(|| anyhow!("application {app_id} info did not contain a creator field"))
    }

    /// The clawback address of `asset_id` from its on-chain asset parameters, or `None` when no
    /// clawback is set (absent, empty, or the zero address). Errors if the asset cannot be read.
    pub fn asset_clawback(&self, asset_id: u64) -> Result<Option<String>> {
        if asset_id == 0 {
            bail!("asset_id must be > 0");
        }
        let client = self.algod_client()?;
        let asset_info = self
            .algod_call(|| client.asset(algonaut::core::AssetId(asset_id)))
            .map_err(|e| anyhow!("failed to fetch asset {asset_id} info: {e}"))?;
        let v = serde_json::to_value(&asset_info)
            .map_err(|e| anyhow!("failed to serialize asset info: {e}"))?;
        Ok(Self::parse_clawback_from_asset_info_value(&v))
    }

    /// Extract the creator address from an application_information JSON value (`params.creator`, or a
    /// top-level `creator`). `None` if absent. Pure, so it is unit-tested without a node.
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn parse_app_creator_from_app_info_value(v: &serde_json::Value) -> Option<String> {
        v.get("params")
            .and_then(|p| p.get("creator").and_then(|x| x.as_str()))
            .or_else(|| v.get("creator").and_then(|x| x.as_str()))
            .map(|s| s.to_string())
    }

    /// Extract the clawback address from an asset_information JSON value (`params.clawback`). Returns
    /// `None` when the field is absent or empty — algod omits an unset clawback (`omitempty`), so an
    /// asset with no clawback yields `None`. A caller that needs to reject the all-zero address treats
    /// it as "not the expected controller" by comparison. Pure, so it is unit-tested without a node.
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn parse_clawback_from_asset_info_value(v: &serde_json::Value) -> Option<String> {
        v.get("params")
            .and_then(|p| {
                p.get("clawback")
                    .or_else(|| p.get("clawback-address"))
                    .or_else(|| p.get("clawback_address"))
                    .and_then(|x| x.as_str())
            })
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string())
    }

    /// Transfer the entire reserve balance of an ASA to the creator. The caller must control the reserve address.
    pub fn recover_reserve_balance(&self, asset_id: u64) -> Result<()> {
        if asset_id == 0 {
            bail!("asset_id must be > 0");
        }
        let client = self.algod_client()?;
        // Fetch asset info
        let asset_info = self
            .algod_call(|| client.asset(algonaut::core::AssetId(asset_id)))
            .map_err(|e| anyhow!("failed to fetch asset information: {e}"))?;
        let v = serde_json::to_value(&asset_info)
            .map_err(|e| anyhow!("failed to serialize asset info: {e}"))?;
        let (creator_str, reserve_str) = match Self::parse_creator_reserve_from_asset_info_value(&v)
        {
            Some(t) => t,
            None => {
                return Err(anyhow!(
                    "asset information did not contain creator/reserve fields"
                ));
            }
        };
        // Ensure we are the reserve account
        let caller_addr = self
            .address
            .as_ref()
            .ok_or_else(|| anyhow!("This operation needs an address"))?
            .clone();
        if caller_addr != reserve_str {
            bail!("caller must be the current reserve address to recover the reserve balance");
        }
        // Ensure creator is opted-in to receive the asset
        if !self.is_account_opted_in_to_asset(&creator_str, asset_id)? {
            bail!("creator address is not opted-in to asset {asset_id}");
        }
        // Get reserve account holdings
        let reserve_addr = Self::parse_address(&reserve_str)?;
        let acct_info = self
            .algod_call(|| client.account(&reserve_addr))
            .map_err(|e| anyhow!("failed to fetch reserve account information: {e}"))?;
        let va = serde_json::to_value(&acct_info)
            .map_err(|e| anyhow!("failed to serialize reserve account info: {e}"))?;
        let amount = Self::parse_holding_amount_from_account_value(&va, asset_id);
        if amount == 0 {
            algo_log!("[recover_reserve_balance] reserve has zero balance for asset {asset_id}");
            return Ok(());
        }
        // Transfer to creator
        self.send_asset(asset_id, amount, &creator_str)
    }

    pub fn compile_teal(&self, source: &str) -> Result<Vec<u8>> {
        if source.is_empty() {
            bail!("source must not be empty");
        }
        // If already provided as base64 compiled program, allow it for convenience.
        if let Some(rest) = source.strip_prefix("base64:") {
            let bytes = general_purpose::STANDARD
                .decode(rest)
                .map_err(|e| anyhow!("invalid base64 program: {e}"))?;
            return Ok(bytes);
        }
        let client = self.algod_client()?;
        let resp =
            self.algod_call(|| client.teal_compile(source.as_bytes(), algonaut::SourceMap::Skip))?;
        // The compiled bytes are in the tuple struct directly
        Ok(resp.0)
    }

    // Compute 4-byte ARC-4 method selector from a signature string.
    pub fn arc4_selector(sig: &str) -> [u8; 4] {
        use sha2::{Digest, Sha512_256};
        let mut hasher = Sha512_256::new();
        hasher.update(sig.as_bytes());
        let digest: [u8; 32] = hasher.finalize().into();
        [digest[0], digest[1], digest[2], digest[3]]
    }

    #[inline]
    /// The number of *extra* program pages a create needs for a combined approval+clear program of
    /// `program_size` bytes. The AVM allots 2048 bytes per page (one page included, so no extra pages
    /// up to 2048); each additional started page is one extra page. Exposed under `test-support` so the
    /// page-count arithmetic is unit-tested without a node.
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn required_extra_pages(program_size: usize) -> u32 {
        (program_size.saturating_sub(1) / 2048) as u32
    }

    /// Algorand's maximum number of *extra* program pages for an application (4 pages total,
    /// 2048 bytes each), the ceiling for a create-time page reservation.
    pub(crate) const MAX_EXTRA_PROGRAM_PAGES: u32 = 3;

    /// The number of *extra* program pages a create should request: the minimum needed to fit
    /// `program_size` bytes, but never fewer than `reserve_extra_pages` — spare headroom the caller
    /// locks in at create time so the app can later be updated with a larger program without
    /// migrating (`extra_program_pages` is immutable after create). Clamped to
    /// `MAX_EXTRA_PROGRAM_PAGES`. Each extra page adds 2048 bytes of program budget and 0.1 ALGO to
    /// the creator's minimum balance for the life of the app. Pure, so the sizing is unit-tested
    /// without a node.
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn extra_pages_for(program_size: usize, reserve_extra_pages: u32) -> u32 {
        Self::required_extra_pages(program_size)
            .max(reserve_extra_pages)
            .min(Self::MAX_EXTRA_PROGRAM_PAGES)
    }

    fn estimate_fee_for_programs(
        params: &algonaut::model::algod::SuggestedParams,
        sizes: &[usize],
    ) -> algonaut::core::MicroAlgos {
        let total_size: usize = sizes.iter().copied().sum();
        let per_byte = params.fee; // MicroAlgos per byte
        let min_fee = params.min_fee; // MicroAlgos
        let sized = per_byte * (total_size as u64);
        if sized > min_fee { sized } else { min_fee }
    }

    #[inline]
    fn estimate_fee_for_signed_size(
        params: &algonaut::model::algod::SuggestedParams,
        est_size: u64,
    ) -> algonaut::core::MicroAlgos {
        let per_byte = params.fee; // MicroAlgos
        let min_fee = params.min_fee; // MicroAlgos
        let sized = per_byte * est_size;
        if sized > min_fee { sized } else { min_fee }
    }

    /// Parse the global and local `StateSchema` from an ARC-56 app spec's `state/schema`.
    fn state_schema_from_arc56(
        arc56_json: &str,
    ) -> Result<(
        algonaut::transaction::transaction::StateSchema,
        algonaut::transaction::transaction::StateSchema,
    )> {
        let spec: serde_json::Value = serde_json::from_str(arc56_json)
            .map_err(|e| anyhow!("failed to parse ARC-56 app spec json: {e}"))?;
        let schema = spec
            .get("state")
            .and_then(|s| s.get("schema"))
            .ok_or_else(|| anyhow!("ARC-56 app spec missing state/schema"))?;
        let read = |section: &str, field: &str| -> Result<u64> {
            schema
                .get(section)
                .and_then(|v| v.get(field))
                .and_then(|v| v.as_u64())
                .ok_or_else(|| {
                    anyhow!("ARC-56 app spec missing state/schema/{}/{}", section, field)
                })
        };
        let global = algonaut::transaction::transaction::StateSchema {
            number_ints: read("global", "ints")?,
            number_byteslices: read("global", "bytes")?,
        };
        let local = algonaut::transaction::transaction::StateSchema {
            number_ints: read("local", "ints")?,
            number_byteslices: read("local", "bytes")?,
        };
        Ok((global, local))
    }

    /// Deploy a new Algorand application.
    ///
    /// - `asset_id`: if `Some`, the app is opted into this ASA immediately after creation.
    /// - `method`: ARC-4 method signature to include in the create transaction (e.g.
    ///   `"create(address,address)void"`). Required when the contract uses
    ///   `@abimethod(create="require")`. Pass `None` for bare-create contracts.
    /// - `args`: ABI-encoded arguments for `method`. Must match the method signature.
    /// - `opt_in_method_name`: name of the method on the creator that opts the app in using Teal, signature opt_in(app_id)
    ///   Use `AppArg::Bytes(32-byte pk)` for `address` parameters.
    /// - `arc56_json`: text of the contract's ARC-56 app spec (the `*.arc56.json` that sits
    ///   alongside the TEAL). The global/local state schema is read from its `state/schema`.
    pub fn deploy_app(
        &self,
        approval_program: &[u8],
        clear_state_program: &[u8],
        asset_id: Option<u64>,
        method: Option<&str>,
        args: &[AppArg],
        opt_in_method_name: &str,
        arc56_json: &str,
    ) -> Result<Option<u64>> {
        self.deploy_app_reserving(
            approval_program,
            clear_state_program,
            asset_id,
            method,
            args,
            opt_in_method_name,
            arc56_json,
            0,
        )
    }

    /// Like [`deploy_app`](Self::deploy_app), but reserves at least `reserve_extra_pages` *extra*
    /// program pages at create time so the app can later be updated with a larger program without
    /// migrating (`extra_program_pages` is immutable after create). The actual count is
    /// `max(required_to_fit, reserve_extra_pages)`, clamped to Algorand's maximum of 3 extra pages
    /// (via the `extra_pages_for` helper). Each reserved page adds 0.1 ALGO to the
    /// creator's minimum balance for the life of the app. `reserve_extra_pages = 0` is identical to
    /// [`deploy_app`](Self::deploy_app).
    #[allow(clippy::too_many_arguments)]
    pub fn deploy_app_reserving(
        &self,
        approval_program: &[u8],
        clear_state_program: &[u8],
        asset_id: Option<u64>,
        method: Option<&str>,
        args: &[AppArg],
        opt_in_method_name: &str,
        arc56_json: &str,
        reserve_extra_pages: u32,
    ) -> Result<Option<u64>> {
        if approval_program.is_empty() {
            bail!("approval_program must not be empty");
        }
        if clear_state_program.is_empty() {
            bail!("clear_state_program must not be empty");
        }
        // Ensure we have account access
        let sk = self.private_key_bytes()?;
        let sender = self.require_address()?;

        // Build programs and derive the state schema from the ARC-56 app spec (state/schema)
        // so the allocation stays in sync with the contract rather than being hardcoded.
        let approval = algonaut::core::CompiledTeal(approval_program.to_vec());
        let clear = algonaut::core::CompiledTeal(clear_state_program.to_vec());
        let (gs, ls) = Self::state_schema_from_arc56(arc56_json)?;

        let client = self.algod_client()?;
        let params = self
            .algod_call(|| client.suggested_params())
            .map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;

        // Before building/sending, estimate the cost of the CreateApplication and ensure we have funds
        // Estimate bytes using CompiledTeal.bytes_to_sign per requirement
        let est_prog_size: usize = approval.bytes_to_sign().len() + clear.bytes_to_sign().len();
        let est_fee = Self::estimate_fee_for_programs(&params, &[est_prog_size]);
        let est_fee_micro: u64 = est_fee.0; // microAlgos

        let balance_algos = self
            .account_balance()? // Always validate Option succeeds per guideline
            .ok_or_else(|| anyhow!("Unable to determine account balance from algod; the account may not be funded or node unreachable"))?;
        let balance_micro = (balance_algos * 1_000_000.0).floor() as u64;
        if balance_micro < est_fee_micro {
            let need_algos = est_fee_micro as f64 / 1_000_000.0;
            return Err(anyhow!(
                "Insufficient funds to create application: balance {:.6} ALGO, estimated required fee {:.6} ALGO. Please fund the creator account and retry.",
                balance_algos,
                need_algos
            ));
        }

        // Print estimated fee components and current balance for visibility
        let per_byte = params.fee;
        let min_fee = params.min_fee;
        algo_log!(
            "Preflight: min_fee={} µAlgos, fee_per_byte={} µAlgos/byte, est_prog_size={} bytes, estimated fee: {:.6} ALGO ({} µAlgos); current balance: {:.6} ALGO ({} µAlgos)",
            min_fee.0,
            per_byte.0,
            est_prog_size,
            est_fee_micro as f64 / 1_000_000.0,
            est_fee_micro,
            balance_algos,
            balance_micro
        );

        // Build ABI args for the create method if provided.
        let mut app_args: Vec<Vec<u8>> = Vec::new();
        if let Some(sig) = method {
            app_args.push(Self::arc4_selector(sig).to_vec());
        }
        app_args.extend(args.iter().map(|a| a.to_bytes()));

        // Build create application transaction
        let mut builder =
            algonaut::transaction::CreateApplication::new(sender, approval, clear, gs, ls);
        // The AVM caps a program at 2048 bytes per page; a combined approval+clear larger than one
        // page must request the extra pages at create time (each adds 2048 bytes of budget, and
        // 100_000 microAlgos to the *app account's* minimum balance — not the create fee). Size them
        // to the minimum that fits, but honour any caller-requested reservation of spare pages so a
        // contract that later grows past its current pages can be updated in place rather than
        // migrated (extra_program_pages is immutable after create).
        let extra_pages = Self::extra_pages_for(est_prog_size, reserve_extra_pages);
        if extra_pages > 0 {
            builder = builder.extra_pages(extra_pages);
        }
        if let Some(aid) = asset_id {
            builder = builder.foreign_assets(vec![algonaut::core::AssetId(aid)]);
        }
        if !app_args.is_empty() {
            builder = builder.app_arguments(app_args);
        }
        let tx = builder
            .note(Self::unique_note())
            .build(&params)
            .map_err(|e| anyhow!("failed to build app create transaction: {e}"))?;

        // Sign and submit
        let seed: [u8; 32] = sk
            .as_slice()
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
        let account = algonaut::transaction::account::Account::from_seed(seed);
        let signed_tx = account
            .sign(tx)
            .map_err(|e| anyhow!("failed to sign app create transaction: {e}"))?;
        let signed = signed_tx
            .to_msg_pack()
            .map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;

        let tx_id = self
            .algod_call(|| client.send_raw(&signed))
            .map_err(|e| anyhow!("send_raw failed: {e}"))?
            .tx_id;

        self.wait_for_confirmation(&tx_id, 10)?;

        // Retrieve created application id from pending tx info (robust JSON-based extraction)
        let tx_id_obj = algonaut::core::TransactionId::from(tx_id.as_str());
        let info = self
            .algod_call(|| client.pending_transaction(&tx_id_obj))
            .map_err(|e| anyhow!("failed to fetch pending transaction info for app id: {e}"))?;
        {
            let v = serde_json::to_value(&info)
                .map_err(|e| anyhow!("failed to serialize pending tx info: {e}"))?;
            let app_id = v
                .get("application-index")
                .and_then(|x| x.as_u64())
                .or_else(|| v.get("application_index").and_then(|x| x.as_u64()))
                .unwrap_or(0);

            if app_id != 0 {
                // After successful creation, fund the app account with 3.21 ALGO from the creator
                if let Ok(app_addr) = self.contract_address(app_id) {
                    // Best-effort funding; bubble up error if funding fails
                    self.send_algo(&app_addr, 3.21)?;
                }
                // If an asset id was provided, opt the app address in via the dApp admin method
                if let Some(aid) = asset_id {
                    // Propagate any error from the admin call; ignore returned tx id
                    let _ = self.opt_in_app_to_asset(app_id, aid, opt_in_method_name)?;

                    // Additionally set the reserve and clawback addresses to the application address
                    self.set_asset_clawback_to_app(app_id, aid)?;
                }
            }
            Ok((app_id != 0).then_some(app_id))
        }
    }

    pub fn update_app(
        &self,
        app_id: u64,
        approval_program: &[u8],
        clear_state_program: &[u8],
        asset_id: Option<u64>,
    ) -> Result<Option<u64>> {
        if app_id == 0 {
            bail!("app_id must be > 0");
        }
        if approval_program.is_empty() {
            bail!("approval_program must not be empty");
        }
        if clear_state_program.is_empty() {
            bail!("clear_state_program must not be empty");
        }
        let sk = self.private_key_bytes()?;
        let sender = self.require_address()?;

        let approval = algonaut::core::CompiledTeal(approval_program.to_vec());
        let clear = algonaut::core::CompiledTeal(clear_state_program.to_vec());

        let client = self.algod_client()?;
        let params = self
            .algod_call(|| client.suggested_params())
            .map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;

        // Estimate fee using helper and params
        let est_prog_size: usize = approval.bytes_to_sign().len() + clear.bytes_to_sign().len();
        let est_fee = Self::estimate_fee_for_programs(&params, &[est_prog_size]);
        let per_byte = params.fee;
        let min_fee = params.min_fee;
        algo_log!(
            "Update preflight: min_fee={} µAlgos, fee_per_byte={} µAlgos/byte, est_prog_size={} bytes, estimated fee: {:.6} ALGO ({} µAlgos)",
            min_fee.0,
            per_byte.0,
            est_prog_size,
            est_fee.0 as f64 / 1_000_000.0,
            est_fee.0
        );

        // Note: Application state schemas (global/local) are immutable after creation on Algorand.
        // Do NOT attempt to change schemas in an update; only approval/clear programs (and other updatable
        // fields supported by the protocol) can be changed. Therefore, we build a plain UpdateApplication
        // with the new programs and do not set schemas here.
        let mut builder = algonaut::transaction::builder::UpdateApplication::new(
            sender,
            algonaut::core::AppId(app_id),
            approval,
            clear,
        );
        if let Some(aid) = asset_id {
            builder = builder.foreign_assets(vec![algonaut::core::AssetId(aid)]);
        }
        let tx = builder
            .note(Self::unique_note())
            .build(&params)
            .map_err(|e| anyhow!("failed to build app update transaction: {e}"))?;

        let seed: [u8; 32] = sk
            .as_slice()
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
        let account = algonaut::transaction::account::Account::from_seed(seed);
        let signed_tx = account
            .sign(tx)
            .map_err(|e| anyhow!("failed to sign app update transaction: {e}"))?;
        let signed = signed_tx
            .to_msg_pack()
            .map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;

        let tx_id = self
            .algod_call(|| client.send_raw(&signed))
            .map_err(|e| anyhow!("send_raw failed: {e}"))?
            .tx_id;
        self.wait_for_confirmation(&tx_id, 10)?;
        Ok(Some(app_id))
    }

    /// Call `app_id` (optionally the ARC-4 `method`) with `args` sent as raw bytes, signed by this
    /// client's account; waits for confirmation and returns `(txid, logs)`. The app's creator is
    /// listed as a foreign account; it is looked up once per app and cached (see
    /// [`app_creator`](Self::app_creator)), so repeat calls to the same app make no extra read for it.
    pub fn call_app(
        &self,
        app_id: u64,
        asset_id: Option<u64>,
        method: Option<&str>,
        args: &[AppArg],
    ) -> Result<(String, Vec<Vec<u8>>)> {
        if app_id == 0 {
            bail!("app_id must be > 0");
        }
        // Build tx
        let tx = self.build_call_app_tx(app_id, asset_id, method, args)?;
        algo_log!(
            "[call_app] method={:?} app_id={} asset_id={:?} args_len={}",
            method,
            app_id,
            asset_id,
            args.len()
        );
        algo_log!("[call_app] tx={:?}", tx);
        self.sign_submit_and_fetch_logs(tx)
    }

    /// Explicit synonym for [`call_app`](Self::call_app): every [`AppArg`] is sent as **raw bytes** and the caller is
    /// responsible for any ARC-4 framing — in particular the 2-byte big-endian length prefix a dynamic
    /// `byte[]` / `string` argument needs. This is the historical `call_app` contract; use it when you
    /// pre-frame args yourself, or [`call_app_arc4_args`](Self::call_app_arc4_args) to have the framing done for you.
    pub fn call_app_raw_args(
        &self,
        app_id: u64,
        asset_id: Option<u64>,
        method: Option<&str>,
        args: &[AppArg],
    ) -> Result<(String, Vec<Vec<u8>>)> {
        self.call_app(app_id, asset_id, method, args)
    }

    /// ARC-4-encoding variant of [`call_app`](Self::call_app): **dynamic** ABI arguments (`byte[]`, `string`) are framed
    /// with their 2-byte big-endian length prefix, inferred from `method`'s signature, so the caller passes
    /// the plain payload. Fixed-size ARC-4 args (`address`, `uint64`, `byte[N]`, …) are unchanged. Prefer
    /// this for any method with a dynamic argument — the raw [`call_app`](Self::call_app) / [`call_app_raw_args`](Self::call_app_raw_args) leave the
    /// framing to the caller, and an unframed dynamic arg is rejected by the contract's ABI decode.
    ///
    /// # Errors
    /// Errors if a dynamic argument exceeds the `byte[]`/`string` length field (`u16::MAX`), plus every
    /// error [`call_app`](Self::call_app) can return.
    pub fn call_app_arc4_args(
        &self,
        app_id: u64,
        asset_id: Option<u64>,
        method: Option<&str>,
        args: &[AppArg],
    ) -> Result<(String, Vec<Vec<u8>>)> {
        let framed = arc4_frame_args(method, args)?;
        self.call_app(app_id, asset_id, method, &framed)
    }

    /// Call an application method with explicit foreign accounts.
    ///
    /// Like [`AlgoOps::call_app`], but `extra_accounts` are placed at the front of the transaction's
    /// foreign-accounts array (ahead of the app creator, which is always appended). A method may only
    /// read or write the local state of accounts listed in that array, so pass the account(s) the
    /// method indexes — e.g. an admin setter that writes a *target* account's local state passes that
    /// target here.
    ///
    /// # Errors
    ///
    /// Errors if `app_id` is 0, if any `extra_accounts` entry is not a valid address, or if the call
    /// fails to build, submit, or confirm.
    pub fn call_app_with_accounts(
        &self,
        app_id: u64,
        asset_id: Option<u64>,
        method: Option<&str>,
        args: &[AppArg],
        extra_accounts: &[&str],
    ) -> Result<(String, Vec<Vec<u8>>)> {
        if app_id == 0 {
            bail!("app_id must be > 0");
        }
        let parsed: Vec<algonaut::core::Address> = extra_accounts
            .iter()
            .map(|a| Self::parse_address(a))
            .collect::<Result<_>>()?;
        let tx = self.build_call_app_tx_inner(app_id, asset_id, &[], &parsed, method, args)?;
        algo_log!(
            "[call_app_with_accounts] method={:?} app_id={} extra_accounts={}",
            method,
            app_id,
            extra_accounts.len()
        );
        self.sign_submit_and_fetch_logs(tx)
    }

    /// Sign `tx` with the ops account, submit it, wait for confirmation, and return the transaction
    /// id together with its base64-decoded logs. Shared by the `call_app*` entry points.
    fn sign_submit_and_fetch_logs(
        &self,
        tx: algonaut::transaction::transaction::Transaction,
    ) -> Result<(String, Vec<Vec<u8>>)> {
        let sk = self.private_key_bytes()?;
        let client = self.algod_client()?;
        // Sign, submit, wait
        let seed: [u8; 32] = sk
            .as_slice()
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
        let account = algonaut::transaction::account::Account::from_seed(seed);
        let signed_tx = account
            .sign(tx)
            .map_err(|e| anyhow!("failed to sign app call transaction: {e}"))?;
        let signed = signed_tx
            .to_msg_pack()
            .map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
        let tx_id = self
            .algod_call(|| client.send_raw(&signed))
            .map_err(|e| anyhow!("send_raw failed: {e}"))?
            .tx_id;
        self.wait_for_confirmation(&tx_id, 10)?;
        // Fetch logs
        let tx_id_obj = algonaut::core::TransactionId::from(tx_id.as_str());
        let p = self
            .algod_call(|| client.pending_transaction(&tx_id_obj))
            .map_err(|e| anyhow!("failed to fetch pending transaction info: {e}"))?;
        let v = serde_json::to_value(&p)
            .map_err(|e| anyhow!("failed to serialize pending tx info: {e}"))?;
        let logs_arr = v
            .get("logs")
            .and_then(|x| x.as_array())
            .cloned()
            .unwrap_or_default();
        let mut logs: Vec<Vec<u8>> = Vec::new();
        for l in logs_arr {
            if let Some(s) = l.as_str()
                && let Ok(bytes) = general_purpose::STANDARD.decode(s)
            {
                logs.push(bytes);
            }
        }
        Ok((tx_id, logs))
    }

    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    pub(crate) fn build_call_app_tx(
        &self,
        app_id: u64,
        asset_id: Option<u64>,
        method: Option<&str>,
        args: &[AppArg],
    ) -> Result<algonaut::transaction::transaction::Transaction> {
        self.build_call_app_tx_inner(app_id, asset_id, &[], &[], method, args)
    }

    // No in-crate caller: a `test-support`-only escape hatch for downstream tests.
    #[cfg_attr(feature = "test-support", visibility::make(pub))]
    #[cfg_attr(not(feature = "test-support"), allow(dead_code))]
    pub(crate) fn build_call_app_tx_with_foreign_apps(
        &self,
        app_id: u64,
        asset_id: Option<u64>,
        foreign_app_ids: &[u64],
        method: Option<&str>,
        args: &[AppArg],
    ) -> Result<algonaut::transaction::transaction::Transaction> {
        self.build_call_app_tx_inner(app_id, asset_id, foreign_app_ids, &[], method, args)
    }

    pub fn call_app_with_foreign_app(
        &self,
        app_id: u64,
        foreign_app_id: u64,
        asset_id: Option<u64>,
        method: Option<&str>,
        args: &[AppArg],
    ) -> Result<(String, Vec<Vec<u8>>)> {
        if app_id == 0 {
            bail!("app_id must be > 0");
        }
        if foreign_app_id == 0 {
            bail!("foreign_app_id must be > 0");
        }
        let tx =
            self.build_call_app_tx_inner(app_id, asset_id, &[foreign_app_id], &[], method, args)?;
        algo_log!(
            "[call_app_with_foreign_app] method={:?} app_id={} foreign_app_id={}",
            method,
            app_id,
            foreign_app_id
        );
        self.sign_submit_and_fetch_logs(tx)
    }

    fn build_call_app_tx_inner(
        &self,
        app_id: u64,
        asset_id: Option<u64>,
        foreign_app_ids: &[u64],
        extra_accounts: &[algonaut::core::Address],
        method: Option<&str>,
        args: &[AppArg],
    ) -> Result<algonaut::transaction::transaction::Transaction> {
        if app_id == 0 {
            bail!("app_id must be > 0");
        }
        // the creator goes in the foreign-accounts array; cached per client (#132), so only the first
        // call to an app reads its application information.
        let creator = Self::parse_address(&self.app_creator(app_id)?)?;
        let sender = self.require_address()?;
        let client = self.algod_client()?;

        let mut app_args: Vec<Vec<u8>> = Vec::new();
        if let Some(sig) = method {
            app_args.push(Self::arc4_selector(sig).to_vec());
        }
        app_args.extend(args.iter().map(|a| a.to_bytes()));

        let params = self
            .algod_call(|| client.suggested_params())
            .map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;

        // Foreign accounts array: any caller-supplied accounts first (e.g. the target whose local
        // state an admin method reads/writes), then the app creator. A method can only touch the
        // local state of accounts listed here, so a caller passes the accounts its method indexes via
        // `call_app_with_accounts`; the creator is always appended for methods that reference it.
        let mut accounts: Vec<algonaut::core::Address> =
            Vec::with_capacity(extra_accounts.len() + 1);
        accounts.extend_from_slice(extra_accounts);
        accounts.push(creator);
        let fapps: Vec<algonaut::core::AppId> = foreign_app_ids
            .iter()
            .map(|&id| algonaut::core::AppId(id))
            .collect();
        let make_builder = || {
            let mut b = algonaut::transaction::builder::CallApplication::new(
                sender,
                algonaut::core::AppId(app_id),
            )
            .accounts(accounts.clone())
            .app_arguments(app_args.clone());
            if let Some(aid) = asset_id {
                b = b.foreign_assets(vec![algonaut::core::AssetId(aid)]);
            }
            if !fapps.is_empty() {
                b = b.foreign_apps(fapps.clone());
            }
            b
        };
        let tx_zero_fee = make_builder()
            .fee(algonaut::core::MicroAlgos(0))
            .note(Self::unique_note())
            .build(&params)
            .map_err(|e| anyhow!("failed to build app call transaction for fee estimation: {e}"))?;
        let est_size = tx_zero_fee
            .estimate_basic_sig_size()
            .map_err(|e| anyhow!("failed to estimate signed tx size: {e}"))?;
        let est_fee = Self::estimate_fee_for_signed_size(&params, est_size);
        let tx = make_builder()
            .fee(est_fee)
            .note(Self::unique_note())
            .build(&params)
            .map_err(|e| anyhow!("failed to build app call transaction: {e}"))?;
        Ok(tx)
    }

    pub fn opt_in_app(&self, app_id: u64) -> Result<()> {
        if app_id == 0 {
            bail!("app_id must be > 0");
        }
        // If already opted-in to local state for this app, nothing to do.
        // Always validate that Option succeeds per guidelines.
        let addr_str = self
            .address
            .as_ref()
            .ok_or_else(|| anyhow!("This operation needs an address"))?;
        if let Some(_entries) = self.local_state_for_account(app_id, addr_str)? {
            return Ok(());
        }

        let sender = self.require_address()?;
        let sk = self.private_key_bytes()?;

        let client = self.algod_client()?;
        let params = self
            .algod_call(|| client.suggested_params())
            .map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;

        let tx = algonaut::transaction::builder::OptInApplication::new(
            sender,
            algonaut::core::AppId(app_id),
        )
        .note(Self::unique_note())
        .build(&params)
        .map_err(|e| anyhow!("failed to build app opt-in transaction: {e}"))?;

        let seed: [u8; 32] = sk
            .as_slice()
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
        let account = algonaut::transaction::account::Account::from_seed(seed);
        let signed_tx = account
            .sign(tx)
            .map_err(|e| anyhow!("failed to sign app opt-in transaction: {e}"))?;
        let signed = signed_tx
            .to_msg_pack()
            .map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
        let tx_id = self
            .algod_call(|| client.send_raw(&signed))
            .map_err(|e| anyhow!("send_raw failed: {e}"))?
            .tx_id;
        self.wait_for_confirmation(&tx_id, 10)
    }

    pub fn clear_state_app(&self, app_id: u64) -> Result<()> {
        if app_id == 0 {
            bail!("app_id must be > 0");
        }
        let sender = self.require_address()?;
        let sk = self.private_key_bytes()?;

        let client = self.algod_client()?;
        let params = self
            .algod_call(|| client.suggested_params())
            .map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;

        let tx = algonaut::transaction::builder::ClearApplication::new(
            sender,
            algonaut::core::AppId(app_id),
        )
        .note(Self::unique_note())
        .build(&params)
        .map_err(|e| anyhow!("failed to build app clear transaction: {e}"))?;

        let seed: [u8; 32] = sk
            .as_slice()
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
        let account = algonaut::transaction::account::Account::from_seed(seed);
        let signed_tx = account
            .sign(tx)
            .map_err(|e| anyhow!("failed to sign app clear transaction: {e}"))?;
        let signed = signed_tx
            .to_msg_pack()
            .map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
        let tx_id = self
            .algod_call(|| client.send_raw(&signed))
            .map_err(|e| anyhow!("send_raw failed: {e}"))?
            .tx_id;
        self.wait_for_confirmation(&tx_id, 10)
    }

    pub fn close_out_app(&self, app_id: u64) -> Result<()> {
        if app_id == 0 {
            bail!("app_id must be > 0");
        }
        let sender = self.require_address()?;
        let sk = self.private_key_bytes()?;

        let client = self.algod_client()?;
        let params = self
            .algod_call(|| client.suggested_params())
            .map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;

        let tx = algonaut::transaction::builder::CloseApplication::new(
            sender,
            algonaut::core::AppId(app_id),
        )
        .note(Self::unique_note())
        .build(&params)
        .map_err(|e| anyhow!("failed to build app close-out transaction: {e}"))?;

        let seed: [u8; 32] = sk
            .as_slice()
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
        let account = algonaut::transaction::account::Account::from_seed(seed);
        let signed_tx = account
            .sign(tx)
            .map_err(|e| anyhow!("failed to sign app close-out transaction: {e}"))?;
        let signed = signed_tx
            .to_msg_pack()
            .map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
        let tx_id = self
            .algod_call(|| client.send_raw(&signed))
            .map_err(|e| anyhow!("send_raw failed: {e}"))?
            .tx_id;
        self.wait_for_confirmation(&tx_id, 10)
    }

    pub fn delete_app(&self, app_id: u64) -> Result<()> {
        if app_id == 0 {
            bail!("app_id must be > 0");
        }
        let sender = self.require_address()?;
        let sk = self.private_key_bytes()?;

        let client = self.algod_client()?;
        let params = self
            .algod_call(|| client.suggested_params())
            .map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;

        let tx = algonaut::transaction::builder::DeleteApplication::new(
            sender,
            algonaut::core::AppId(app_id),
        )
        .note(Self::unique_note())
        .build(&params)
        .map_err(|e| anyhow!("failed to build app delete transaction: {e}"))?;

        let seed: [u8; 32] = sk
            .as_slice()
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
        let account = algonaut::transaction::account::Account::from_seed(seed);
        let signed_tx = account
            .sign(tx)
            .map_err(|e| anyhow!("failed to sign app delete transaction: {e}"))?;
        let signed = signed_tx
            .to_msg_pack()
            .map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
        let tx_id = self
            .algod_call(|| client.send_raw(&signed))
            .map_err(|e| anyhow!("send_raw failed: {e}"))?
            .tx_id;
        self.wait_for_confirmation(&tx_id, 10)
    }

    /// Admin method: Opt the application account into the given ASA by a method on the creator
    /// like "opt_(app_id)" which opts the app in using Teal
    /// Returns the transaction id of the app call when an opt-in was required; if the
    /// app was already opted in, returns Ok("") without making a call.
    /// opt_in_method_name must be a method on the creator like "opt_(app_id)" which opts the app in using Teal
    pub fn opt_in_app_to_asset(
        &self,
        app_id: u64,
        asset_id: u64,
        opt_in_method_name: &str,
    ) -> Result<String> {
        tracing::info!("opt_in_app_to_asset: app_id={}", app_id);
        if app_id == 0 {
            bail!("app_id must be > 0");
        }
        if asset_id == 0 {
            bail!("asset_id must be > 0");
        }
        // If the app address already holds the asset, nothing to do
        let app_addr_str = self.contract_address(app_id)?;
        if self.is_account_opted_in_to_asset(&app_addr_str, asset_id)? {
            return Ok(String::new());
        }
        // Call the admin method on the contract; this must be signed by the creator
        let (tx_id, _logs) = self.call_app(
            app_id,
            Some(asset_id),
            Some(opt_in_method_name),
            &[AppArg::Uint(asset_id)],
        )?;
        // Return tx id to signal a call occurred; fetch from tuple index 0
        Ok(tx_id)
    }

    /// Wait for a transaction to be confirmed up to `timeout_rounds` rounds.
    /// Follows the Kotlin logic: poll pending tx info and wait for next rounds.
    pub fn wait_for_confirmation(&self, tx_id: &str, timeout_rounds: u64) -> Result<()> {
        if timeout_rounds == 0 {
            bail!("timeout_rounds must be > 0");
        }
        let client = self.algod_client()?;

        // Get starting round
        let status = self
            .algod_call(|| client.status())
            .map_err(|e| anyhow!("failed to get node status: {e}"))?;
        let start_round = status.last_round.0 + 1;
        let end_round = start_round + timeout_rounds;

        let mut current_round = start_round;
        while current_round < end_round {
            // Check pending transaction info
            let tx_id_obj = algonaut::core::TransactionId::from(tx_id);
            match self.algod_call(|| client.pending_transaction(&tx_id_obj)) {
                Ok(p) => {
                    if let Some(cr) = p.confirmed_round
                        && cr > 0
                    {
                        return Ok(());
                    }
                    if !p.pool_error.is_empty() {
                        bail!("Transaction rejected with pool error: {}", p.pool_error);
                    }
                }
                Err(e) => {
                    if AlgoError::is_host_unreachable(&anyhow!(e.to_string())) {
                        return Err(
                            AlgoError::unreachable("pending_transaction", &e.to_string()).into(),
                        );
                    }
                    // If the node no longer remembers the tx or transient error, continue waiting until timeout
                }
            }

            // Wait for next round
            self.algod_call(|| client.status_after_block(algonaut::core::Round(current_round)))
                .map_err(|e| anyhow!("status_after_block failed: {e}"))?;
            current_round += 1;
        }
        Err(anyhow!(
            "Transaction not confirmed after {} rounds",
            timeout_rounds
        ))
    }

    /// Begin building an atomic transaction group signed and sent by this account.
    ///
    /// Legs are added in order — [`payment`](TransactionGroupBuilder::payment),
    /// [`asset_transfer`](TransactionGroupBuilder::asset_transfer), and
    /// [`call_app`](TransactionGroupBuilder::call_app) — then
    /// [`sign_and_send`](TransactionGroupBuilder::sign_and_send) assigns a shared group id,
    /// signs every leg with this account, broadcasts them atomically, waits for confirmation,
    /// and returns the group's representative transaction id. This keeps `algonaut` group
    /// types out of the public surface, replacing the sealed `build_call_app_tx` escape hatch.
    ///
    /// ```no_run
    /// # use algo_ops::AlgoOps;
    /// # fn f(ops: &AlgoOps, app_address: &str, price_microalgos: u64, app_id: u64, asset_id: u64) -> anyhow::Result<()> {
    /// let tx_id = ops
    ///     .transaction_group()
    ///     .payment(app_address, price_microalgos)          // Pay: ops account -> app_address
    ///     .call_app(app_id, Some("buy_bingle()void"), &[]) // ABI app-call
    ///     .foreign_asset(asset_id)                         // per-leg option, applies to the app-call
    ///     .sign_and_send()?;                               // group id + sign all + broadcast + wait
    /// # let _ = tx_id;
    /// # Ok(())
    /// # }
    /// ```
    pub fn transaction_group(&self) -> TransactionGroupBuilder<'_> {
        TransactionGroupBuilder {
            ops: self,
            legs: Vec::new(),
            error: None,
        }
    }
}

/// A single leg of an atomic transaction group. All legs are signed by the ops account.
#[derive(Debug, Clone)]
enum GroupLeg {
    /// `Pay` from the ops account to `to` for `micro_algos` microALGOs.
    Payment { to: String, micro_algos: u64 },
    /// ASA transfer of `amount` base units of `asset_id` from the ops account to `to`.
    AssetTransfer {
        asset_id: u64,
        amount: u64,
        to: String,
    },
    /// ABI app-call on `app_id`, with an optional foreign asset / foreign app.
    AppCall {
        app_id: u64,
        method: Option<String>,
        args: Vec<AppArg>,
        foreign_asset: Option<u64>,
        foreign_app: Option<u64>,
    },
}

/// Fluent builder for an atomic transaction group, created by [`AlgoOps::transaction_group`].
///
/// Every leg is signed by the single ops account (single-signer groups). Per-leg option
/// methods ([`foreign_asset`](Self::foreign_asset) / [`foreign_app`](Self::foreign_app)) apply
/// to the most recently added [`call_app`](Self::call_app) leg. A misuse (e.g. a per-leg option
/// with no preceding app-call, or an empty group) is recorded and surfaced by
/// [`sign_and_send`](Self::sign_and_send) rather than panicking.
#[derive(Debug)]
pub struct TransactionGroupBuilder<'a> {
    ops: &'a AlgoOps,
    legs: Vec<GroupLeg>,
    error: Option<String>,
}

impl<'a> TransactionGroupBuilder<'a> {
    // Record the first misuse; later calls keep the original message.
    fn set_error(&mut self, msg: impl Into<String>) {
        if self.error.is_none() {
            self.error = Some(msg.into());
        }
    }

    /// Add a payment leg: `Pay` from the ops account to `to_address` for `micro_algos` microALGOs.
    pub fn payment(mut self, to_address: &str, micro_algos: u64) -> Self {
        self.legs.push(GroupLeg::Payment {
            to: to_address.to_string(),
            micro_algos,
        });
        self
    }

    /// Add an asset-transfer leg: move `amount` base units of `asset_id` from the ops account
    /// to `to_address`.
    pub fn asset_transfer(mut self, asset_id: u64, amount: u64, to_address: &str) -> Self {
        self.legs.push(GroupLeg::AssetTransfer {
            asset_id,
            amount,
            to: to_address.to_string(),
        });
        self
    }

    /// Add an ABI app-call leg on `app_id` with the given `method` signature and `args`.
    /// Attach an optional foreign asset / foreign app with [`foreign_asset`](Self::foreign_asset)
    /// / [`foreign_app`](Self::foreign_app) immediately after this call.
    pub fn call_app(mut self, app_id: u64, method: Option<&str>, args: &[AppArg]) -> Self {
        if app_id == 0 {
            self.set_error("call_app() requires app_id > 0");
        }
        self.legs.push(GroupLeg::AppCall {
            app_id,
            method: method.map(|s| s.to_string()),
            args: args.to_vec(),
            foreign_asset: None,
            foreign_app: None,
        });
        self
    }

    /// Explicit synonym for [`call_app`](Self::call_app): every [`AppArg`] goes on the wire as **raw
    /// bytes** and the caller does any ARC-4 framing (the 2-byte length prefix a dynamic `byte[]` /
    /// `string` argument needs). Mirrors [`AlgoOps::call_app_raw_args`].
    pub fn call_app_raw_args(self, app_id: u64, method: Option<&str>, args: &[AppArg]) -> Self {
        self.call_app(app_id, method, args)
    }

    /// ARC-4-encoding variant of [`call_app`](Self::call_app): **dynamic** ABI arguments (`byte[]`,
    /// `string`) are framed with their 2-byte big-endian length prefix, inferred from `method`'s
    /// signature, so the caller passes the plain payload; fixed-size args are unchanged. Mirrors
    /// [`AlgoOps::call_app_arc4_args`]. A dynamic argument longer than `u16::MAX` is recorded as a
    /// builder error, so [`sign_and_send`](Self::sign_and_send) fails before any network I/O and
    /// nothing in the group is submitted. Per-leg options ([`foreign_asset`](Self::foreign_asset),
    /// [`foreign_app`](Self::foreign_app)) apply to this leg as to a `call_app` leg.
    pub fn call_app_arc4_args(
        mut self,
        app_id: u64,
        method: Option<&str>,
        args: &[AppArg],
    ) -> Self {
        match arc4_frame_args(method, args) {
            Ok(framed_args) => self.call_app(app_id, method, &framed_args),
            Err(error) => {
                self.set_error(format!("call_app_arc4_args(): {error}"));
                // still add the leg, so a following foreign_asset()/foreign_app() attaches to it
                // rather than reporting a second, misleading misuse.
                self.call_app(app_id, method, args)
            }
        }
    }

    /// Attach a foreign asset to the most recently added [`call_app`](Self::call_app) leg.
    pub fn foreign_asset(mut self, asset_id: u64) -> Self {
        match self.legs.last_mut() {
            Some(GroupLeg::AppCall { foreign_asset, .. }) => *foreign_asset = Some(asset_id),
            _ => self.set_error("foreign_asset() must follow a call_app() leg"),
        }
        self
    }

    /// Attach a foreign app to the most recently added [`call_app`](Self::call_app) leg.
    pub fn foreign_app(mut self, foreign_app_id: u64) -> Self {
        match self.legs.last_mut() {
            Some(GroupLeg::AppCall { foreign_app, .. }) => *foreign_app = Some(foreign_app_id),
            _ => self.set_error("foreign_app() must follow a call_app() leg"),
        }
        self
    }

    /// Assign a shared group id to every leg, sign each with the ops account, broadcast the group
    /// atomically, wait for confirmation, and return the group's representative transaction id.
    ///
    /// Fails (before any network I/O) if a builder misuse was recorded or if no legs were added.
    pub fn sign_and_send(self) -> Result<String> {
        if let Some(err) = self.error {
            bail!("{err}");
        }
        if self.legs.is_empty() {
            bail!("transaction group must contain at least one transaction");
        }

        let ops = self.ops;
        let sk = ops.private_key_bytes()?;
        let seed: [u8; 32] = sk
            .as_slice()
            .try_into()
            .map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
        let sender = ops.require_address()?;
        let client = ops.algod_client()?;
        let params = ops
            .algod_call(|| client.suggested_params())
            .map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;

        // Build each leg into an unsigned transaction, preserving order.
        let mut txns: Vec<algonaut::transaction::transaction::Transaction> =
            Vec::with_capacity(self.legs.len());
        for leg in &self.legs {
            let tx = match leg {
                GroupLeg::Payment { to, micro_algos } => {
                    let to_addr = AlgoOps::parse_address(to)?;
                    algonaut::transaction::Pay::new(
                        sender,
                        to_addr,
                        algonaut::core::MicroAlgos(*micro_algos),
                    )
                    .note(AlgoOps::unique_note())
                    .build(&params)
                    .map_err(|e| anyhow!("failed to build payment transaction: {e}"))?
                }
                GroupLeg::AssetTransfer {
                    asset_id,
                    amount,
                    to,
                } => {
                    let to_addr = AlgoOps::parse_address(to)?;
                    algonaut::transaction::TransferAsset::new(
                        sender,
                        algonaut::core::AssetId(*asset_id),
                        *amount,
                        to_addr,
                    )
                    .note(AlgoOps::unique_note())
                    .build(&params)
                    .map_err(|e| anyhow!("failed to build asset transfer transaction: {e}"))?
                }
                GroupLeg::AppCall {
                    app_id,
                    method,
                    args,
                    foreign_asset,
                    foreign_app,
                } => {
                    let fapps: Vec<u64> = foreign_app.iter().copied().collect();
                    ops.build_call_app_tx_inner(
                        *app_id,
                        *foreign_asset,
                        &fapps,
                        &[],
                        method.as_deref(),
                        args,
                    )?
                }
            };
            txns.push(tx);
        }

        // Assign the shared group id across all legs.
        let group = algonaut::transaction::group::TransactionGroup::try_from(txns)
            .map_err(|e| anyhow!("failed to assign group id: {e}"))?;

        // Sign every leg with the ops account.
        let account = algonaut::transaction::account::Account::from_seed(seed);
        let mut signed: Vec<algonaut::transaction::SignedTransaction> = Vec::new();
        for tx in group.into_transactions() {
            let stx = account
                .sign(tx)
                .map_err(|e| anyhow!("failed to sign grouped transaction: {e}"))?;
            signed.push(stx);
        }

        // Broadcast the group atomically and wait for confirmation.
        let tx_id = ops
            .algod_call(|| client.send_transactions(&signed))
            .map_err(|e| anyhow!("failed to broadcast transaction group: {e}"))?
            .tx_id;
        ops.wait_for_confirmation(&tx_id, 10)?;
        Ok(tx_id)
    }
}

/// Application argument type, similar to Kotlin variant handling.
///
/// This is the Algorand application-arguments / Application Binary Interface (ABI) convention, which
/// the Sidewinder client also packs operation arguments with (see `sidewinder_ops`): each argument
/// is encoded on its own — a `Uint` as 8 big-endian bytes (an Algorand Request for Comments 4,
/// ARC-4, `uint64`), and `Bytes` / `Utf8` as their raw bytes (the argument boundary carries the
/// length, so no length prefix is added).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AppArg {
    Bytes(Vec<u8>),
    Utf8(String),
    Uint(u64),
}

impl AppArg {
    pub fn to_bytes(&self) -> Vec<u8> {
        match self {
            AppArg::Bytes(b) => b.clone(),
            AppArg::Utf8(s) => s.as_bytes().to_vec(),
            AppArg::Uint(v) => v.to_be_bytes().to_vec(),
        }
    }
}

/// Split an ABI method signature's **top-level** argument types.
/// `"foo(byte[],uint64)void"` -> `["byte[]", "uint64"]`; `"foo()void"` -> `[]`. Respects nesting so a
/// tuple/array's inner commas are not split (`"foo((uint64,byte[]),address)"` -> `["(uint64,byte[])","address"]`).
/// Returns `None` if there is no argument list. Used to decide which args need ARC-4 dynamic framing.
fn abi_arg_types(sig: &str) -> Option<Vec<String>> {
    let open = sig.find('(')?;
    let mut depth = 0i32;
    let mut start = 0usize;
    let mut inner: Option<&str> = None;
    for (i, c) in sig.char_indices().skip_while(|(i, _)| *i < open) {
        match c {
            '(' => {
                depth += 1;
                if depth == 1 {
                    start = i + 1;
                }
            }
            ')' => {
                depth -= 1;
                if depth == 0 {
                    inner = Some(&sig[start..i]);
                    break;
                }
            }
            _ => {}
        }
    }
    let inner = inner?;
    if inner.trim().is_empty() {
        return Some(Vec::new());
    }
    let mut out = Vec::new();
    let mut d = 0i32;
    let mut seg = 0usize;
    for (i, c) in inner.char_indices() {
        match c {
            '(' | '[' => d += 1,
            ')' | ']' => d -= 1,
            ',' if d == 0 => {
                out.push(inner[seg..i].trim().to_string());
                seg = i + 1;
            }
            _ => {}
        }
    }
    out.push(inner[seg..].trim().to_string());
    Some(out)
}

/// ARC-4-frame `args` for `method`: a `byte[]` / `string` argument (dynamic ARC-4 types) is wrapped with
/// its 2-byte big-endian length prefix; every other argument is passed through unchanged (fixed-size ARC-4
/// types are already their own wire form, and an argument whose type can't be determined is left as-is —
/// the raw contract). Used by [`AlgoOps::call_app_arc4_args`] and
/// [`TransactionGroupBuilder::call_app_arc4_args`].
///
/// Private in production; re-exported publicly only under `test-support` so the framing rules can be
/// unit-tested without a node.
#[cfg_attr(feature = "test-support", visibility::make(pub))]
fn arc4_frame_args(method: Option<&str>, args: &[AppArg]) -> Result<Vec<AppArg>> {
    let types = method.and_then(abi_arg_types);
    args.iter()
        .enumerate()
        .map(|(i, arg)| {
            let ty = types.as_ref().and_then(|t| t.get(i)).map(String::as_str);
            match ty {
                Some("byte[]") | Some("string") => {
                    let raw = arg.to_bytes();
                    let len = u16::try_from(raw.len()).map_err(|_| {
                        anyhow!(
                            "ARC-4 byte[]/string argument {i} is {} bytes, over the u16 length limit",
                            raw.len()
                        )
                    })?;
                    let mut framed = Vec::with_capacity(2 + raw.len());
                    framed.extend_from_slice(&len.to_be_bytes());
                    framed.extend_from_slice(&raw);
                    Ok(AppArg::Bytes(framed))
                }
                _ => Ok(arg.clone()),
            }
        })
        .collect()
}

/// Decode first 32 bytes of an Algorand address' base32 to get the public key.
pub fn address_to_byte_key(address: &str) -> Result<[u8; 32]> {
    // Algorand addresses use RFC4648 base32 without padding and include checksum.
    let decoded = BASE32_NOPAD
        .decode(address.as_bytes())
        .map_err(|e| anyhow!("Invalid base32 address: {e}"))?;
    if decoded.len() < 32 {
        bail!("Decoded address is shorter than 32 bytes");
    }
    let mut pk = [0u8; 32];
    pk.copy_from_slice(&decoded[..32]);
    Ok(pk)
}

/// Build an Algorand address from a 32-byte public key.
pub fn byte_key_to_address(byte_public_key: &[u8; 32]) -> Result<String> {
    use sha2::{Digest, Sha512_256};
    // Compute checksum: SHA512/256 over public key, take last 4 bytes
    let mut hasher = Sha512_256::new();

    hasher.update(byte_public_key);
    let hash = hasher.finalize();
    let checksum = &hash[hash.len() - 4..];

    let mut addr_bytes = [0u8; 36];
    addr_bytes[..32].copy_from_slice(byte_public_key);
    addr_bytes[32..].copy_from_slice(checksum);

    let addr = BASE32_NOPAD.encode(&addr_bytes);
    Ok(addr)
}