algo_ops 0.2.0

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
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 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;

/// 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>,
}

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,
        }
    }
}

/// 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) {}
}

/// 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,
}

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)
    }

    pub fn new_indexer(config: Option<AlgoChainConfig>) -> Self {
        Self::new(None, None, config)
    }

    pub 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();
        let mut ops = Self {
            passphrase,
            address,
            config,
        };

        // 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
    }

    /// 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).
    pub const RETRYABLE_STATUS_CODES: &'static [u16] = &[408, 425, 429, 502, 503, 504];

    // Returns true if the algonaut error is a retryable transient HTTP error.
    pub fn is_retryable(e: &algonaut::Error) -> bool {
        if let algonaut::Error::Request(req) = e
            && let algonaut::error::RequestErrorDetails::Http { status, .. } = &req.details
        {
            return Self::RETRYABLE_STATUS_CODES.contains(status);
        }
        false
    }

    // Helper: run an algonaut async call and flatten the double-Result, with
    // up to 3 retries (with exponential backoff: 1 s, 2 s, 4 s) on transient
    // HTTP errors (408, 425, 429, 502, 503, 504).
    //
    // Accepts a closure rather than a bare future so the future can be
    // reconstructed on each retry attempt (futures are 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,
    {
        const MAX_RETRIES: u32 = 3;
        const RETRY_BASE_MS: u64 = 1_000;

        let mut attempt = 0u32;
        loop {
            let result = self
                .rt_block_on(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(e) => {
                    let delay = std::time::Duration::from_millis(RETRY_BASE_MS * (1u64 << attempt));
                    tracing::warn!(
                        "algod transient error (attempt {}/{}), retrying in {:?}: {}",
                        attempt + 1,
                        MAX_RETRIES,
                        delay,
                        e
                    );
                    std::thread::sleep(delay);
                    attempt += 1;
                }
                Err(e) => {
                    if attempt >= MAX_RETRIES && Self::is_retryable(&e) {
                        return Err(AlgoError::transient("algod call", &e.to_string()).into());
                    }
                    return Err(anyhow!("{e}"));
                }
            }
        }
    }

    // Helper: run an async future on a fresh current-thread Tokio runtime.
    fn rt_block_on<T: Send>(&self, fut: impl Future<Output = T> + Send) -> Result<T> {
        // If we are already in a tokio runtime, we must avoid nested block_on and
        // the "cannot drop runtime" panic during unwinding/drop.
        if tokio::runtime::Handle::try_current().is_ok() {
            return std::thread::scope(|s| {
                let handle = s.spawn(|| {
                    let rt = tokio::runtime::Builder::new_current_thread()
                        .enable_all()
                        .build()
                        .expect("failed to build temporary tokio runtime");
                    rt.block_on(fut)
                });
                handle
                    .join()
                    .map_err(|_| anyhow!("rt_block_on thread panicked"))
            });
        }

        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|e| anyhow!("failed to build tokio runtime: {e}"))?;
        Ok(rt.block_on(fut))
    }

    // 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 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}"))?;

        let als = match Self::json_get(&v, "apps_local_state", "apps-local-state")
            .and_then(|x| x.as_array())
        {
            Some(a) => a,
            None => return Ok(None),
        };
        for st in als {
            let id = st.get("id").and_then(|x| x.as_u64());
            if id == 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();
                let out = Self::decode_state_entries(&keyvals_vec);
                return Ok(Some(out));
            }
        }
        Ok(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 µ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)
    }

    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`; also `pub` so the reserve-helper
    /// integration tests can exercise the parsing directly.
    pub 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`; also `pub` so the
    /// reserve-helper integration tests can exercise the parsing directly.
    pub 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
    }

    /// 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]
    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>> {
        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);
        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))
    }

    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);
        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))
    }

    pub 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)
    }

    pub 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
        );
        let sk = self.private_key_bytes()?;
        let client = self.algod_client()?;
        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)?;
        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))
    }

    fn build_call_app_tx_inner(
        &self,
        app_id: u64,
        asset_id: Option<u64>,
        foreign_app_ids: &[u64],
        method: Option<&str>,
        args: &[AppArg],
    ) -> Result<algonaut::transaction::transaction::Transaction> {
        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!("failed to fetch application information: {e}"))?;
        let app_info_v = serde_json::to_value(&app_info)
            .map_err(|e| anyhow!("failed to serialize application info: {e}"))?;
        let creator_str = app_info_v
            .get("params")
            .and_then(|p| p.get("creator").and_then(|x| x.as_str()))
            .or_else(|| app_info_v.get("creator").and_then(|x| x.as_str()))
            .ok_or_else(|| anyhow!("application info did not contain creator field"))?;
        let creator = Self::parse_address(creator_str)?;
        let sender = self.require_address()?;

        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}"))?;

        let mut accounts: Vec<algonaut::core::Address> = vec![creator];
        if let Some(sig) = method
            && (sig == "set_allow_static(address,uint64)void"
                || sig == "set_allow_relay(address,uint64)void")
            && let Some(first) = args.first()
            && let AppArg::Bytes(b) = first
            && b.len() == 32
        {
            let mut pk = [0u8; 32];
            pk.copy_from_slice(&b[..32]);
            if let Ok(addr_str) = byte_key_to_address(&pk)
                && let Ok(target) = Self::parse_address(&addr_str)
            {
                accounts.insert(0, target);
            }
        }
        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
        ))
    }
}

/// Application argument type, similar to Kotlin variant handling.
#[derive(Debug, Clone)]
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(),
        }
    }
}

/// 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)
}