accumulate-sdk 2.1.0

Accumulate Rust SDK (V2/V3 unified) with DevNet-first flows
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
//! Helper utilities matching Dart SDK convenience features
//!
//! This module provides high-level convenience APIs similar to the Dart SDK:
//! - SmartSigner: Auto-version tracking for transaction signing
//! - TxBody: Factory methods for creating transaction bodies
//! - KeyManager: Key page query and management
//! - QuickStart: Ultra-simple API for rapid development
//! - Polling utilities: Wait for balance, credits, transactions

#![allow(clippy::unwrap_used, clippy::expect_used)]

use crate::client::AccumulateClient;
use crate::json_rpc_client::JsonRpcError;
use crate::AccOptions;
use ed25519_dalek::{SigningKey, Signer};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use url::Url;

// =============================================================================
// KERMIT TESTNET ENDPOINTS
// =============================================================================

/// Kermit public testnet V2 endpoint
pub const KERMIT_V2: &str = "https://kermit.accumulatenetwork.io/v2";
/// Kermit public testnet V3 endpoint
pub const KERMIT_V3: &str = "https://kermit.accumulatenetwork.io/v3";

/// Local DevNet V2 endpoint
pub const DEVNET_V2: &str = "http://127.0.0.1:26660/v2";
/// Local DevNet V3 endpoint
pub const DEVNET_V3: &str = "http://127.0.0.1:26660/v3";

// =============================================================================
// TRANSACTION RESULT
// =============================================================================

/// Result of a transaction submission with wait
#[derive(Debug, Clone)]
pub struct TxResult {
    /// Whether the transaction succeeded
    pub success: bool,
    /// Transaction ID (if successful)
    pub txid: Option<String>,
    /// Error message (if failed)
    pub error: Option<String>,
    /// Raw response data
    pub response: Option<Value>,
}

impl TxResult {
    /// Create a success result
    pub fn ok(txid: String, response: Value) -> Self {
        Self {
            success: true,
            txid: Some(txid),
            error: None,
            response: Some(response),
        }
    }

    /// Create a failure result
    pub fn err(error: String) -> Self {
        Self {
            success: false,
            txid: None,
            error: Some(error),
            response: None,
        }
    }
}

// =============================================================================
// TX BODY HELPERS
// =============================================================================

/// Factory methods for creating transaction bodies (matching Dart SDK TxBody)
#[derive(Debug)]
pub struct TxBody;

impl TxBody {
    /// Create an AddCredits transaction body
    pub fn add_credits(recipient: &str, amount: &str, oracle: u64) -> Value {
        json!({
            "type": "addCredits",
            "recipient": recipient,
            "amount": amount,
            "oracle": oracle
        })
    }

    /// Create a CreateIdentity transaction body
    pub fn create_identity(url: &str, key_book_url: &str, public_key_hash: &str) -> Value {
        json!({
            "type": "createIdentity",
            "url": url,
            "keyBookUrl": key_book_url,
            "keyHash": public_key_hash
        })
    }

    /// Create a CreateTokenAccount transaction body
    pub fn create_token_account(url: &str, token_url: &str) -> Value {
        json!({
            "type": "createTokenAccount",
            "url": url,
            "tokenUrl": token_url
        })
    }

    /// Create a CreateDataAccount transaction body
    pub fn create_data_account(url: &str) -> Value {
        json!({
            "type": "createDataAccount",
            "url": url
        })
    }

    /// Create a CreateToken transaction body
    pub fn create_token(url: &str, symbol: &str, precision: u64, supply_limit: Option<&str>) -> Value {
        let mut body = json!({
            "type": "createToken",
            "url": url,
            "symbol": symbol,
            "precision": precision
        });
        if let Some(limit) = supply_limit {
            body["supplyLimit"] = json!(limit);
        }
        body
    }

    /// Create a SendTokens transaction body for a single recipient
    pub fn send_tokens_single(to_url: &str, amount: &str) -> Value {
        json!({
            "type": "sendTokens",
            "to": [{
                "url": to_url,
                "amount": amount
            }]
        })
    }

    /// Create a SendTokens transaction body for multiple recipients
    pub fn send_tokens_multi(recipients: &[(&str, &str)]) -> Value {
        let to: Vec<Value> = recipients
            .iter()
            .map(|(url, amount)| json!({"url": url, "amount": amount}))
            .collect();
        json!({
            "type": "sendTokens",
            "to": to
        })
    }

    /// Create an IssueTokens transaction body for a single recipient
    pub fn issue_tokens_single(to_url: &str, amount: &str) -> Value {
        json!({
            "type": "issueTokens",
            "to": [{
                "url": to_url,
                "amount": amount
            }]
        })
    }

    /// Create a WriteData transaction body
    /// Data entries are hex-encoded and sent as a DoubleHash data entry
    pub fn write_data(entries: &[&str]) -> Value {
        // Convert each entry to hex string (not nested objects!)
        let entries_hex: Vec<Value> = entries
            .iter()
            .map(|e| Value::String(hex::encode(e.as_bytes())))
            .collect();
        json!({
            "type": "writeData",
            "entry": {
                "type": "doublehash",  // DataEntryType = 3
                "data": entries_hex    // Array of hex strings
            }
        })
    }

    /// Create a WriteData transaction body with hex entries
    pub fn write_data_hex(entries_hex: &[&str]) -> Value {
        // Convert to Value::String (not nested objects!)
        let entries: Vec<Value> = entries_hex
            .iter()
            .map(|e| Value::String((*e).to_string()))
            .collect();
        json!({
            "type": "writeData",
            "entry": {
                "type": "doublehash",  // DataEntryType = 3
                "data": entries        // Array of hex strings
            }
        })
    }

    /// Create a WriteDataTo transaction body with hex entries (entries already hex-encoded)
    pub fn write_data_to_hex(recipient: &str, entries_hex: &[&str]) -> Value {
        let entries: Vec<Value> = entries_hex
            .iter()
            .map(|e| Value::String((*e).to_string()))
            .collect();
        json!({
            "type": "writeDataTo",
            "recipient": recipient,
            "entry": {
                "type": "doublehash",
                "data": entries
            }
        })
    }

    /// Create a CreateKeyPage transaction body
    pub fn create_key_page(key_hashes: &[&[u8]]) -> Value {
        let keys: Vec<Value> = key_hashes
            .iter()
            .map(|h| json!({"keyHash": hex::encode(h)}))
            .collect();
        json!({
            "type": "createKeyPage",
            "keys": keys
        })
    }

    /// Create a CreateKeyBook transaction body
    pub fn create_key_book(url: &str, public_key_hash: &str) -> Value {
        json!({
            "type": "createKeyBook",
            "url": url,
            "publicKeyHash": public_key_hash
        })
    }

    /// Create an UpdateKeyPage transaction body to add a key
    pub fn update_key_page_add_key(key_hash: &[u8]) -> Value {
        json!({
            "type": "updateKeyPage",
            "operation": [{
                "type": "add",
                "entry": {
                    "keyHash": hex::encode(key_hash)
                }
            }]
        })
    }

    /// Create an UpdateKeyPage transaction body to remove a key
    pub fn update_key_page_remove_key(key_hash: &[u8]) -> Value {
        json!({
            "type": "updateKeyPage",
            "operation": [{
                "type": "remove",
                "entry": {
                    "keyHash": hex::encode(key_hash)
                }
            }]
        })
    }

    /// Create an UpdateKeyPage transaction body to set threshold
    pub fn update_key_page_set_threshold(threshold: u64) -> Value {
        json!({
            "type": "updateKeyPage",
            "operation": [{
                "type": "setThreshold",
                "threshold": threshold
            }]
        })
    }

    /// Create a BurnTokens transaction body
    pub fn burn_tokens(amount: &str) -> Value {
        json!({
            "type": "burnTokens",
            "amount": amount
        })
    }

    /// Create a TransferCredits transaction body
    pub fn transfer_credits(to_url: &str, amount: u64) -> Value {
        json!({
            "type": "transferCredits",
            "to": [{
                "url": to_url,
                "amount": amount
            }]
        })
    }

    /// Create a BurnCredits transaction body
    pub fn burn_credits(amount: u64) -> Value {
        json!({
            "type": "burnCredits",
            "amount": amount
        })
    }

    /// Create an UpdateKey transaction body (key rotation)
    pub fn update_key(new_key_hash: &str) -> Value {
        json!({
            "type": "updateKey",
            "newKeyHash": new_key_hash
        })
    }

    /// Create a LockAccount transaction body
    pub fn lock_account(height: u64) -> Value {
        json!({
            "type": "lockAccount",
            "height": height
        })
    }

    /// Create an UpdateAccountAuth transaction body
    pub fn update_account_auth(operations: &Value) -> Value {
        json!({
            "type": "updateAccountAuth",
            "operations": operations
        })
    }

    /// Create a WriteDataTo transaction body (write data to a remote data account)
    pub fn write_data_to(recipient: &str, entries: &[&str]) -> Value {
        let entries_hex: Vec<Value> = entries
            .iter()
            .map(|e| Value::String(hex::encode(e.as_bytes())))
            .collect();
        json!({
            "type": "writeDataTo",
            "recipient": recipient,
            "entry": {
                "type": "doublehash",
                "data": entries_hex
            }
        })
    }

    /// Create a generic UpdateKeyPage transaction body with raw operations
    ///
    /// For simple cases, prefer update_key_page_add_key, update_key_page_remove_key,
    /// or update_key_page_set_threshold.
    pub fn update_key_page(operations: &Value) -> Value {
        json!({
            "type": "updateKeyPage",
            "operation": operations
        })
    }
}

// =============================================================================
// KEY PAGE STATE
// =============================================================================

/// Key page state information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyPageState {
    /// Key page URL
    pub url: String,
    /// Current version
    pub version: u64,
    /// Credit balance
    pub credit_balance: u64,
    /// Accept threshold (signatures required)
    pub accept_threshold: u64,
    /// Keys on the page
    pub keys: Vec<KeyEntry>,
}

/// Key entry in a key page
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyEntry {
    /// Public key hash (hex)
    pub key_hash: String,
    /// Delegate (if any)
    pub delegate: Option<String>,
}

// =============================================================================
// HEADER OPTIONS
// =============================================================================

/// Optional transaction header fields for advanced transaction control.
///
/// These fields are included in the transaction envelope submitted to the V3 API.
/// - `memo`: Human-readable memo text
/// - `metadata`: Binary metadata bytes (hex-encoded in the envelope)
/// - `expire`: Transaction expiration time
/// - `hold_until`: Scheduled execution at a specific minor block
/// - `authorities`: Additional signing authorities
#[derive(Debug, Clone, Default)]
pub struct HeaderOptions {
    /// Human-readable memo text
    pub memo: Option<String>,
    /// Binary metadata bytes
    pub metadata: Option<Vec<u8>>,
    /// Transaction expiration options
    pub expire: Option<crate::generated::header::ExpireOptions>,
    /// Hold-until (delayed execution) options
    pub hold_until: Option<crate::generated::header::HoldUntilOptions>,
    /// Additional signing authorities (list of authority URLs)
    pub authorities: Option<Vec<String>>,
}

// =============================================================================
// SMART SIGNER
// =============================================================================

/// Smart signer with auto-version tracking (matching Dart SDK SmartSigner)
#[derive(Debug)]
pub struct SmartSigner<'a> {
    /// Reference to the client
    client: &'a AccumulateClient,
    /// Signing key
    keypair: SigningKey,
    /// Signer URL (key page URL)
    signer_url: String,
    /// Cached version (updated automatically)
    cached_version: u64,
}

impl<'a> SmartSigner<'a> {
    /// Create a new SmartSigner
    pub fn new(client: &'a AccumulateClient, keypair: SigningKey, signer_url: &str) -> Self {
        Self {
            client,
            keypair,
            signer_url: signer_url.to_string(),
            cached_version: 1,
        }
    }

    /// Query and update the cached version
    pub async fn refresh_version(&mut self) -> Result<u64, JsonRpcError> {
        let params = json!({
            "scope": &self.signer_url,
            "query": {"queryType": "default"}
        });

        let result: Value = self.client.v3_client.call_v3("query", params).await?;

        if let Some(account) = result.get("account") {
            if let Some(version) = account.get("version").and_then(|v| v.as_u64()) {
                self.cached_version = version;
                return Ok(version);
            }
        }

        Ok(self.cached_version)
    }

    /// Get the current cached version
    pub fn version(&self) -> u64 {
        self.cached_version
    }

    /// Sign a transaction and return the envelope
    ///
    /// This uses proper binary encoding matching the Go core implementation:
    /// 1. Compute signature metadata hash (binary encoded)
    /// 2. Use that as the transaction initiator
    /// 3. Compute transaction hash using binary encoding
    /// 4. Create signing preimage = SHA256(sigMdHash + txHash)
    /// 5. Sign the preimage
    pub fn sign(&self, principal: &str, body: &Value, memo: Option<&str>) -> Result<Value, JsonRpcError> {
        use crate::codec::signing::{
            compute_ed25519_signature_metadata_hash,
            compute_transaction_hash,
            compute_write_data_body_hash,
            compute_write_data_to_body_hash,
            create_signing_preimage,
            marshal_transaction_header,
            sha256_bytes,
        };

        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|e| JsonRpcError::General(anyhow::anyhow!("Time error: {}", e)))?
            .as_micros() as u64;

        let public_key = self.keypair.verifying_key().to_bytes();

        // Step 1: Compute signature metadata hash
        // This is used as BOTH the transaction initiator AND for signing
        let sig_metadata_hash = compute_ed25519_signature_metadata_hash(
            &public_key,
            &self.signer_url,
            self.cached_version,
            timestamp,
        );
        let initiator_hex = hex::encode(&sig_metadata_hash);

        // Step 2: Marshal header with initiator
        let header_bytes = marshal_transaction_header(
            principal,
            &sig_metadata_hash,
            memo,
            None,
        );

        // Step 3 & 4: Compute transaction hash
        // WriteData/WriteDataTo use special Merkle hash algorithm
        let tx_type = body.get("type").and_then(|t| t.as_str()).unwrap_or("");

        // Helper: extract entries from body.entry.data
        let extract_entries = |body: &Value| -> Vec<String> {
            let mut entries_hex = Vec::new();
            if let Some(entry) = body.get("entry") {
                if let Some(data) = entry.get("data") {
                    if let Some(arr) = data.as_array() {
                        for item in arr {
                            if let Some(s) = item.as_str() {
                                entries_hex.push(s.to_string());
                            }
                        }
                    }
                }
            }
            entries_hex
        };

        let tx_hash = if tx_type == "writeData" {
            let header_hash = sha256_bytes(&header_bytes);
            let entries_hex = extract_entries(body);
            let scratch = body.get("scratch").and_then(|s| s.as_bool()).unwrap_or(false);
            let write_to_state = body.get("writeToState").and_then(|w| w.as_bool()).unwrap_or(false);
            let body_hash = compute_write_data_body_hash(&entries_hex, scratch, write_to_state);
            // txHash = SHA256(SHA256(header) + bodyHash)
            let mut combined = Vec::with_capacity(64);
            combined.extend_from_slice(&header_hash);
            combined.extend_from_slice(&body_hash);
            sha256_bytes(&combined)
        } else if tx_type == "writeDataTo" {
            let header_hash = sha256_bytes(&header_bytes);
            let entries_hex = extract_entries(body);
            let recipient = body.get("recipient").and_then(|r| r.as_str()).unwrap_or("");
            let body_hash = compute_write_data_to_body_hash(recipient, &entries_hex);
            // txHash = SHA256(SHA256(header) + bodyHash)
            let mut combined = Vec::with_capacity(64);
            combined.extend_from_slice(&header_hash);
            combined.extend_from_slice(&body_hash);
            sha256_bytes(&combined)
        } else {
            // Standard: SHA256(SHA256(header) + SHA256(body))
            let body_bytes = marshal_body_to_binary(body)?;
            compute_transaction_hash(&header_bytes, &body_bytes)
        };

        // Step 5: Create signing preimage and sign
        let preimage = create_signing_preimage(&sig_metadata_hash, &tx_hash);
        let signature = self.keypair.sign(&preimage);

        // Build transaction JSON (for submission)
        let mut tx = json!({
            "header": {
                "principal": principal,
                "initiator": &initiator_hex
            },
            "body": body
        });

        if let Some(m) = memo {
            tx["header"]["memo"] = json!(m);
        }

        // Build envelope with proper signature document
        // V3 API expects: envelope.signatures[].transactionHash
        let envelope = json!({
            "transaction": [tx],
            "signatures": [{
                "type": "ed25519",
                "publicKey": hex::encode(&public_key),
                "signature": hex::encode(signature.to_bytes()),
                "signer": &self.signer_url,
                "signerVersion": self.cached_version,
                "timestamp": timestamp,
                "transactionHash": hex::encode(&tx_hash)
            }]
        });

        Ok(envelope)
    }

    /// Sign, submit, and wait for transaction confirmation
    pub async fn sign_submit_and_wait(
        &mut self,
        principal: &str,
        body: &Value,
        memo: Option<&str>,
        max_attempts: u32,
    ) -> TxResult {
        // Refresh version before signing
        if let Err(e) = self.refresh_version().await {
            return TxResult::err(format!("Failed to refresh version: {}", e));
        }

        // Sign the transaction
        let envelope = match self.sign(principal, body, memo) {
            Ok(env) => env,
            Err(e) => return TxResult::err(format!("Failed to sign: {}", e)),
        };

        // Submit
        let submit_result: Result<Value, _> = self.client.v3_client.call_v3("submit", json!({
            "envelope": envelope
        })).await;

        let response = match submit_result {
            Ok(resp) => resp,
            Err(e) => return TxResult::err(format!("Submit failed: {}", e)),
        };

        // Extract transaction ID
        let txid = extract_txid(&response);
        if txid.is_none() {
            return TxResult::err("No transaction ID in response".to_string());
        }
        let txid = txid.unwrap();

        // Wait for confirmation
        // Extract just the hash for querying - format: acc://hash@unknown
        let tx_hash = if txid.starts_with("acc://") && txid.contains('@') {
            txid.split('@').next().unwrap_or(&txid).replace("acc://", "")
        } else {
            txid.clone()
        };
        let query_scope = format!("acc://{}@unknown", tx_hash);

        for _attempt in 0..max_attempts {
            tokio::time::sleep(Duration::from_secs(2)).await;

            // Query transaction status
            let query_result: Result<Value, _> = self.client.v3_client.call_v3("query", json!({
                "scope": &query_scope,
                "query": {"queryType": "default"}
            })).await;

            if let Ok(result) = query_result {
                // Check status - can be a String or a Map (matching Dart SDK)
                if let Some(status_value) = result.get("status") {
                    // Case 1: Status is a simple string like "delivered" or "pending"
                    if let Some(status_str) = status_value.as_str() {
                        if status_str == "delivered" {
                            return TxResult::ok(txid, response);
                        }
                        // "pending" - continue waiting
                        continue;
                    }

                    // Case 2: Status is a map with delivered/failed fields
                    if status_value.is_object() {
                        let delivered = status_value.get("delivered")
                            .and_then(|d| d.as_bool())
                            .unwrap_or(false);

                        if delivered {
                            // Check for errors
                            let failed = status_value.get("failed")
                                .and_then(|f| f.as_bool())
                                .unwrap_or(false);

                            if failed {
                                let error_msg = status_value.get("error")
                                    .and_then(|e| {
                                        if let Some(msg) = e.get("message").and_then(|m| m.as_str()) {
                                            Some(msg.to_string())
                                        } else {
                                            e.as_str().map(String::from)
                                        }
                                    })
                                    .unwrap_or_else(|| "Unknown error".to_string());
                                return TxResult::err(error_msg);
                            }

                            return TxResult::ok(txid, response);
                        }
                    }
                }
            }
        }

        TxResult::err(format!("Timeout waiting for delivery: {}", txid))
    }

    /// Add a key to the key page using SmartSigner
    pub async fn add_key(&mut self, public_key: &[u8]) -> TxResult {
        let key_hash = sha256_hash(public_key);
        let body = TxBody::update_key_page_add_key(&key_hash);
        self.sign_submit_and_wait(&self.signer_url.clone(), &body, Some("Add key"), 30).await
    }

    /// Remove a key from the key page using SmartSigner
    pub async fn remove_key(&mut self, public_key_hash: &[u8]) -> TxResult {
        let body = TxBody::update_key_page_remove_key(public_key_hash);
        self.sign_submit_and_wait(&self.signer_url.clone(), &body, Some("Remove key"), 30).await
    }

    /// Set the threshold for the key page
    pub async fn set_threshold(&mut self, threshold: u64) -> TxResult {
        let body = TxBody::update_key_page_set_threshold(threshold);
        self.sign_submit_and_wait(&self.signer_url.clone(), &body, Some("Set threshold"), 30).await
    }

    /// Get public key hash
    #[allow(dead_code)]
    fn public_key_hash(&self) -> [u8; 32] {
        sha256_hash(&self.keypair.verifying_key().to_bytes())
    }

    /// Sign a transaction with full header options and return the envelope.
    ///
    /// Like [`sign`], but accepts a [`HeaderOptions`] struct for specifying
    /// memo, metadata, expire, hold_until, and authorities.
    pub fn sign_with_options(
        &self,
        principal: &str,
        body: &Value,
        options: &HeaderOptions,
    ) -> Result<Value, JsonRpcError> {
        use crate::codec::signing::{
            compute_ed25519_signature_metadata_hash,
            compute_transaction_hash,
            compute_write_data_body_hash,
            compute_write_data_to_body_hash,
            create_signing_preimage,
            marshal_transaction_header_full,
            HeaderBinaryOptions,
            sha256_bytes,
        };

        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|e| JsonRpcError::General(anyhow::anyhow!("Time error: {}", e)))?
            .as_micros() as u64;

        let public_key = self.keypair.verifying_key().to_bytes();

        // Step 1: Compute signature metadata hash
        let sig_metadata_hash = compute_ed25519_signature_metadata_hash(
            &public_key,
            &self.signer_url,
            self.cached_version,
            timestamp,
        );
        let initiator_hex = hex::encode(&sig_metadata_hash);

        // Step 2: Marshal header with initiator, memo, metadata, and extended options
        let memo_ref = options.memo.as_deref();
        let metadata_ref = options.metadata.as_deref();

        // Build extended binary options for fields 5-7
        let has_extended = options.expire.is_some()
            || options.hold_until.is_some()
            || options.authorities.is_some();

        let extended = if has_extended {
            Some(HeaderBinaryOptions {
                expire_at_time: options.expire.as_ref().and_then(|e| e.at_time.map(|t| t as i64)),
                hold_until_minor_block: options.hold_until.as_ref().and_then(|h| h.minor_block),
                authorities: options.authorities.clone(),
            })
        } else {
            None
        };

        let header_bytes = marshal_transaction_header_full(
            principal,
            &sig_metadata_hash,
            memo_ref,
            metadata_ref,
            extended.as_ref(),
        );

        // Step 3 & 4: Compute transaction hash
        let tx_type = body.get("type").and_then(|t| t.as_str()).unwrap_or("");

        // Helper: extract entries from body.entry.data
        let extract_entries = |body: &Value| -> Vec<String> {
            let mut entries_hex = Vec::new();
            if let Some(entry) = body.get("entry") {
                if let Some(data) = entry.get("data") {
                    if let Some(arr) = data.as_array() {
                        for item in arr {
                            if let Some(s) = item.as_str() {
                                entries_hex.push(s.to_string());
                            }
                        }
                    }
                }
            }
            entries_hex
        };

        let tx_hash = if tx_type == "writeData" {
            let header_hash = sha256_bytes(&header_bytes);
            let entries_hex = extract_entries(body);
            let scratch = body.get("scratch").and_then(|s| s.as_bool()).unwrap_or(false);
            let write_to_state = body.get("writeToState").and_then(|w| w.as_bool()).unwrap_or(false);
            let body_hash = compute_write_data_body_hash(&entries_hex, scratch, write_to_state);
            let mut combined = Vec::with_capacity(64);
            combined.extend_from_slice(&header_hash);
            combined.extend_from_slice(&body_hash);
            sha256_bytes(&combined)
        } else if tx_type == "writeDataTo" {
            let header_hash = sha256_bytes(&header_bytes);
            let entries_hex = extract_entries(body);
            let recipient = body.get("recipient").and_then(|r| r.as_str()).unwrap_or("");
            let body_hash = compute_write_data_to_body_hash(recipient, &entries_hex);
            let mut combined = Vec::with_capacity(64);
            combined.extend_from_slice(&header_hash);
            combined.extend_from_slice(&body_hash);
            sha256_bytes(&combined)
        } else {
            let body_bytes = marshal_body_to_binary(body)?;
            compute_transaction_hash(&header_bytes, &body_bytes)
        };

        // Step 5: Create signing preimage and sign
        let preimage = create_signing_preimage(&sig_metadata_hash, &tx_hash);
        let signature = self.keypair.sign(&preimage);

        // Build transaction JSON (for submission)
        let mut tx = json!({
            "header": {
                "principal": principal,
                "initiator": &initiator_hex
            },
            "body": body
        });

        // Add optional header fields
        if let Some(ref m) = options.memo {
            tx["header"]["memo"] = json!(m);
        }
        if let Some(ref md) = options.metadata {
            tx["header"]["metadata"] = json!(hex::encode(md));
        }
        if let Some(ref expire) = options.expire {
            if let Some(at_time) = expire.at_time {
                // V3 API expects atTime as an RFC 3339 / ISO 8601 timestamp string
                let dt = chrono::DateTime::from_timestamp(at_time as i64, 0)
                    .unwrap_or_else(|| chrono::DateTime::from_timestamp(0, 0).unwrap());
                tx["header"]["expire"] = json!({ "atTime": dt.to_rfc3339() });
            }
        }
        if let Some(ref hold) = options.hold_until {
            if let Some(minor_block) = hold.minor_block {
                tx["header"]["holdUntil"] = json!({ "minorBlock": minor_block });
            }
        }
        if let Some(ref auths) = options.authorities {
            tx["header"]["authorities"] = json!(auths);
        }

        // Build envelope
        let envelope = json!({
            "transaction": [tx],
            "signatures": [{
                "type": "ed25519",
                "publicKey": hex::encode(&public_key),
                "signature": hex::encode(signature.to_bytes()),
                "signer": &self.signer_url,
                "signerVersion": self.cached_version,
                "timestamp": timestamp,
                "transactionHash": hex::encode(&tx_hash)
            }]
        });

        Ok(envelope)
    }

    /// Sign, submit, and wait for transaction confirmation with full header options.
    ///
    /// Like [`sign_submit_and_wait`], but accepts a [`HeaderOptions`] struct.
    pub async fn sign_submit_and_wait_with_options(
        &mut self,
        principal: &str,
        body: &Value,
        options: &HeaderOptions,
        max_attempts: u32,
    ) -> TxResult {
        // Refresh version before signing
        if let Err(e) = self.refresh_version().await {
            return TxResult::err(format!("Failed to refresh version: {}", e));
        }

        // Sign the transaction with options
        let envelope = match self.sign_with_options(principal, body, options) {
            Ok(env) => env,
            Err(e) => return TxResult::err(format!("Failed to sign: {}", e)),
        };

        // Submit
        let submit_result: Result<Value, _> = self.client.v3_client.call_v3("submit", json!({
            "envelope": envelope
        })).await;

        let response = match submit_result {
            Ok(resp) => resp,
            Err(e) => return TxResult::err(format!("Submit failed: {}", e)),
        };

        // Extract transaction ID
        let txid = extract_txid(&response);
        if txid.is_none() {
            return TxResult::err("No transaction ID in response".to_string());
        }
        let txid = txid.unwrap();

        // Wait for confirmation
        let tx_hash = if txid.starts_with("acc://") && txid.contains('@') {
            txid.split('@').next().unwrap_or(&txid).replace("acc://", "")
        } else {
            txid.clone()
        };
        let query_scope = format!("acc://{}@unknown", tx_hash);

        for _attempt in 0..max_attempts {
            tokio::time::sleep(Duration::from_secs(2)).await;

            let query_result: Result<Value, _> = self.client.v3_client.call_v3("query", json!({
                "scope": &query_scope,
                "query": {"queryType": "default"}
            })).await;

            if let Ok(result) = query_result {
                if let Some(status_value) = result.get("status") {
                    if let Some(status_str) = status_value.as_str() {
                        if status_str == "delivered" {
                            return TxResult::ok(txid, response);
                        }
                        continue;
                    }
                    if status_value.is_object() {
                        let delivered = status_value.get("delivered")
                            .and_then(|d| d.as_bool())
                            .unwrap_or(false);
                        if delivered {
                            let failed = status_value.get("failed")
                                .and_then(|f| f.as_bool())
                                .unwrap_or(false);
                            if failed {
                                let error_msg = status_value.get("error")
                                    .and_then(|e| {
                                        if let Some(msg) = e.get("message").and_then(|m| m.as_str()) {
                                            Some(msg.to_string())
                                        } else {
                                            e.as_str().map(String::from)
                                        }
                                    })
                                    .unwrap_or_else(|| "Unknown error".to_string());
                                return TxResult::err(error_msg);
                            }
                            return TxResult::ok(txid, response);
                        }
                    }
                }
            }
        }

        TxResult::err(format!("Timeout waiting for delivery: {}", txid))
    }
}

/// Marshal a JSON transaction body to binary format
///
/// This handles different transaction types and converts them to proper binary encoding.
fn marshal_body_to_binary(body: &Value) -> Result<Vec<u8>, JsonRpcError> {
    use crate::codec::signing::{
        marshal_add_credits_body, marshal_send_tokens_body, marshal_create_identity_body,
        marshal_create_token_account_body, marshal_create_data_account_body,
        marshal_write_data_body, marshal_create_token_body, marshal_issue_tokens_body,
        marshal_key_page_operation, marshal_update_key_page_body,
        marshal_create_key_book_body, marshal_create_key_page_body,
        marshal_burn_tokens_body, marshal_update_key_body,
        marshal_burn_credits_body, marshal_transfer_credits_body,
        marshal_write_data_to_body, marshal_lock_account_body,
        marshal_update_account_auth_body,
        tx_types
    };
    use crate::codec::writer::BinaryWriter;

    let tx_type = body.get("type").and_then(|t| t.as_str()).unwrap_or("");

    match tx_type {
        "addCredits" => {
            let recipient = body.get("recipient").and_then(|r| r.as_str()).unwrap_or("");
            let amount_str = body.get("amount").and_then(|a| a.as_str()).unwrap_or("0");
            let amount: u64 = amount_str.parse().unwrap_or(0);
            let oracle = body.get("oracle").and_then(|o| o.as_u64()).unwrap_or(0);
            Ok(marshal_add_credits_body(recipient, amount, oracle))
        }
        "sendTokens" => {
            let to_array = body.get("to").and_then(|t| t.as_array());
            let mut recipients = Vec::new();
            if let Some(to) = to_array {
                for recipient in to {
                    let url = recipient.get("url").and_then(|u| u.as_str()).unwrap_or("");
                    let amount_str = recipient.get("amount").and_then(|a| a.as_str()).unwrap_or("0");
                    let amount: u64 = amount_str.parse().unwrap_or(0);
                    recipients.push((url.to_string(), amount));
                }
            }
            Ok(marshal_send_tokens_body(&recipients))
        }
        "createIdentity" => {
            let url = body.get("url").and_then(|u| u.as_str()).unwrap_or("");
            let key_book_url = body.get("keyBookUrl").and_then(|k| k.as_str()).unwrap_or("");
            // Check both "keyHash" (preferred) and "publicKeyHash" (fallback)
            let key_hash_hex = body.get("keyHash")
                .or_else(|| body.get("publicKeyHash"))
                .and_then(|k| k.as_str())
                .unwrap_or("");
            let key_hash = hex::decode(key_hash_hex).unwrap_or_default();
            Ok(marshal_create_identity_body(url, &key_hash, key_book_url))
        }
        "createTokenAccount" => {
            let url = body.get("url").and_then(|u| u.as_str()).unwrap_or("");
            let token_url = body.get("tokenUrl").and_then(|t| t.as_str()).unwrap_or("");
            Ok(marshal_create_token_account_body(url, token_url))
        }
        "createDataAccount" => {
            let url = body.get("url").and_then(|u| u.as_str()).unwrap_or("");
            Ok(marshal_create_data_account_body(url))
        }
        "writeData" => {
            // Extract entries from nested entry.data structure
            let mut entries_hex = Vec::new();
            if let Some(entry) = body.get("entry") {
                if let Some(data) = entry.get("data") {
                    if let Some(arr) = data.as_array() {
                        for item in arr {
                            if let Some(s) = item.as_str() {
                                entries_hex.push(s.to_string());
                            }
                        }
                    }
                }
            }
            let scratch = body.get("scratch").and_then(|s| s.as_bool()).unwrap_or(false);
            let write_to_state = body.get("writeToState").and_then(|w| w.as_bool()).unwrap_or(false);
            Ok(marshal_write_data_body(&entries_hex, scratch, write_to_state))
        }
        "createToken" => {
            let url = body.get("url").and_then(|u| u.as_str()).unwrap_or("");
            let symbol = body.get("symbol").and_then(|s| s.as_str()).unwrap_or("");
            let precision = body.get("precision").and_then(|p| p.as_u64()).unwrap_or(0);
            let supply_limit = body.get("supplyLimit")
                .and_then(|s| s.as_str())
                .and_then(|s| s.parse::<u64>().ok());
            Ok(marshal_create_token_body(url, symbol, precision, supply_limit))
        }
        "issueTokens" => {
            let to_array = body.get("to").and_then(|t| t.as_array());
            let mut recipients: Vec<(&str, u64)> = Vec::new();
            if let Some(to) = to_array {
                for recipient in to {
                    let url = recipient.get("url").and_then(|u| u.as_str()).unwrap_or("");
                    let amount_str = recipient.get("amount").and_then(|a| a.as_str()).unwrap_or("0");
                    let amount: u64 = amount_str.parse().unwrap_or(0);
                    recipients.push((url, amount));
                }
            }
            Ok(marshal_issue_tokens_body(&recipients))
        }
        "burnTokens" => {
            let amount_str = body.get("amount").and_then(|a| a.as_str()).unwrap_or("0");
            let amount: u64 = amount_str.parse().unwrap_or(0);
            Ok(marshal_burn_tokens_body(amount))
        }
        "createKeyBook" => {
            let url = body.get("url").and_then(|u| u.as_str()).unwrap_or("");
            let key_hash_hex = body.get("publicKeyHash")
                .or_else(|| body.get("keyHash"))
                .and_then(|k| k.as_str())
                .unwrap_or("");
            let key_hash = hex::decode(key_hash_hex).unwrap_or_default();
            Ok(marshal_create_key_book_body(url, &key_hash))
        }
        "createKeyPage" => {
            let keys_array = body.get("keys").and_then(|k| k.as_array());
            let mut key_hashes: Vec<Vec<u8>> = Vec::new();
            if let Some(keys) = keys_array {
                for key in keys {
                    let key_hash_hex = key.get("keyHash")
                        .or_else(|| key.get("publicKeyHash"))
                        .and_then(|k| k.as_str())
                        .unwrap_or("");
                    let key_hash = hex::decode(key_hash_hex).unwrap_or_default();
                    key_hashes.push(key_hash);
                }
            }
            Ok(marshal_create_key_page_body(&key_hashes))
        }
        "updateKey" => {
            let new_key_hash_hex = body.get("newKeyHash")
                .or_else(|| body.get("newKey"))
                .and_then(|k| k.as_str())
                .unwrap_or("");
            let new_key_hash = hex::decode(new_key_hash_hex).unwrap_or_default();
            Ok(marshal_update_key_body(&new_key_hash))
        }
        "updateKeyPage" => {
            // Parse operations array from JSON
            let op_array = body.get("operation").and_then(|o| o.as_array());
            let mut operations: Vec<Vec<u8>> = Vec::new();

            if let Some(ops) = op_array {
                for op in ops {
                    let op_type = op.get("type").and_then(|t| t.as_str()).unwrap_or("");

                    // Extract key hash from entry.keyHash (for add/remove operations)
                    // Go uses "keyHash" field in KeySpecParams
                    let key_hash: Option<Vec<u8>> = op.get("entry")
                        .and_then(|e| e.get("keyHash"))
                        .and_then(|h| h.as_str())
                        .and_then(|hex_str| hex::decode(hex_str).ok());

                    // Extract delegate URL if present
                    let delegate: Option<&str> = op.get("entry")
                        .and_then(|e| e.get("delegate"))
                        .and_then(|d| d.as_str());

                    // Extract old/new key hashes for update operation
                    let old_key_hash: Option<Vec<u8>> = op.get("oldEntry")
                        .and_then(|e| e.get("keyHash"))
                        .and_then(|h| h.as_str())
                        .and_then(|hex_str| hex::decode(hex_str).ok());

                    let new_key_hash: Option<Vec<u8>> = op.get("newEntry")
                        .and_then(|e| e.get("keyHash"))
                        .and_then(|h| h.as_str())
                        .and_then(|hex_str| hex::decode(hex_str).ok());

                    // Extract threshold for setThreshold operation
                    let threshold: Option<u64> = op.get("threshold").and_then(|t| t.as_u64());

                    // Marshal the operation
                    let op_bytes = marshal_key_page_operation(
                        op_type,
                        key_hash.as_deref(),
                        delegate,
                        old_key_hash.as_deref(),
                        new_key_hash.as_deref(),
                        threshold,
                    );
                    operations.push(op_bytes);
                }
            }

            Ok(marshal_update_key_page_body(&operations))
        }
        "burnCredits" => {
            let amount = body.get("amount").and_then(|a| a.as_u64()).unwrap_or(0);
            Ok(marshal_burn_credits_body(amount))
        }
        "transferCredits" => {
            let to_array = body.get("to").and_then(|t| t.as_array());
            let mut recipients: Vec<(&str, u64)> = Vec::new();
            if let Some(to) = to_array {
                for recipient in to {
                    let url = recipient.get("url").and_then(|u| u.as_str()).unwrap_or("");
                    let amount = recipient.get("amount").and_then(|a| a.as_u64()).unwrap_or(0);
                    recipients.push((url, amount));
                }
            }
            Ok(marshal_transfer_credits_body(&recipients))
        }
        "writeDataTo" => {
            let recipient = body.get("recipient").and_then(|r| r.as_str()).unwrap_or("");
            let mut entries_hex = Vec::new();
            if let Some(entry) = body.get("entry") {
                if let Some(data) = entry.get("data") {
                    if let Some(arr) = data.as_array() {
                        for item in arr {
                            if let Some(s) = item.as_str() {
                                entries_hex.push(s.to_string());
                            }
                        }
                    }
                }
            }
            Ok(marshal_write_data_to_body(recipient, &entries_hex))
        }
        "lockAccount" => {
            let height = body.get("height").and_then(|h| h.as_u64()).unwrap_or(0);
            Ok(marshal_lock_account_body(height))
        }
        "updateAccountAuth" => {
            let ops_array = body.get("operations").and_then(|o| o.as_array());
            let mut operations: Vec<(&str, &str)> = Vec::new();
            if let Some(ops) = ops_array {
                for op in ops {
                    let op_type = op.get("type").and_then(|t| t.as_str()).unwrap_or("");
                    let authority = op.get("authority").and_then(|a| a.as_str()).unwrap_or("");
                    operations.push((op_type, authority));
                }
            }
            Ok(marshal_update_account_auth_body(&operations))
        }
        // For other transaction types, fall back to JSON encoding
        // This won't produce correct signatures but allows compilation
        _ => {
            // Create a minimal binary encoding with just the type
            let mut writer = BinaryWriter::new();

            // Map type string to numeric type
            let type_num = match tx_type {
                "createIdentity" => tx_types::CREATE_IDENTITY,
                "createTokenAccount" => tx_types::CREATE_TOKEN_ACCOUNT,
                "createDataAccount" => tx_types::CREATE_DATA_ACCOUNT,
                "writeData" => tx_types::WRITE_DATA,
                "writeDataTo" => tx_types::WRITE_DATA_TO,
                "acmeFaucet" => tx_types::ACME_FAUCET,
                "createToken" => tx_types::CREATE_TOKEN,
                "issueTokens" => tx_types::ISSUE_TOKENS,
                "burnTokens" => tx_types::BURN_TOKENS,
                "createLiteTokenAccount" => tx_types::CREATE_LITE_TOKEN_ACCOUNT,
                "createKeyPage" => tx_types::CREATE_KEY_PAGE,
                "createKeyBook" => tx_types::CREATE_KEY_BOOK,
                "updateKeyPage" => tx_types::UPDATE_KEY_PAGE,
                "updateAccountAuth" => tx_types::UPDATE_ACCOUNT_AUTH,
                "updateKey" => tx_types::UPDATE_KEY,
                "lockAccount" => tx_types::LOCK_ACCOUNT,
                "transferCredits" => tx_types::TRANSFER_CREDITS,
                "burnCredits" => tx_types::BURN_CREDITS,
                _ => 0,
            };

            // Write field 1: Type
            let _ = writer.write_uvarint(1);
            let _ = writer.write_uvarint(type_num);

            // Just return the type encoding - proper implementation needed
            // for each transaction type
            // TODO: Implement full binary encoding for all transaction types
            Ok(writer.into_bytes())
        }
    }
}

// =============================================================================
// KEY MANAGER
// =============================================================================

/// Key manager for key page operations (matching Dart SDK KeyManager)
#[derive(Debug)]
pub struct KeyManager<'a> {
    /// Reference to the client
    client: &'a AccumulateClient,
    /// Key page URL
    key_page_url: String,
}

impl<'a> KeyManager<'a> {
    /// Create a new KeyManager
    pub fn new(client: &'a AccumulateClient, key_page_url: &str) -> Self {
        Self {
            client,
            key_page_url: key_page_url.to_string(),
        }
    }

    /// Get the current key page state
    pub async fn get_key_page_state(&self) -> Result<KeyPageState, JsonRpcError> {
        let params = json!({
            "scope": &self.key_page_url,
            "query": {"queryType": "default"}
        });

        let result: Value = self.client.v3_client.call_v3("query", params).await?;

        let account = result.get("account")
            .ok_or_else(|| JsonRpcError::General(anyhow::anyhow!("No account in response")))?;

        let url = account.get("url")
            .and_then(|v| v.as_str())
            .unwrap_or(&self.key_page_url)
            .to_string();

        let version = account.get("version")
            .and_then(|v| v.as_u64())
            .unwrap_or(1);

        let credit_balance = account.get("creditBalance")
            .and_then(|v| v.as_u64())
            .unwrap_or(0);

        let accept_threshold = account.get("acceptThreshold")
            .or_else(|| account.get("threshold"))
            .and_then(|v| v.as_u64())
            .unwrap_or(1);

        let keys: Vec<KeyEntry> = if let Some(keys_arr) = account.get("keys").and_then(|k| k.as_array()) {
            keys_arr.iter().map(|k| {
                let key_hash = k.get("publicKeyHash")
                    .or_else(|| k.get("publicKey"))
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let delegate = k.get("delegate").and_then(|v| v.as_str()).map(String::from);
                KeyEntry { key_hash, delegate }
            }).collect()
        } else {
            vec![]
        };

        Ok(KeyPageState {
            url,
            version,
            credit_balance,
            accept_threshold,
            keys,
        })
    }
}

// =============================================================================
// POLLING UTILITIES
// =============================================================================

/// Poll for account balance (matching Dart SDK pollForBalance)
pub async fn poll_for_balance(
    client: &AccumulateClient,
    account_url: &str,
    max_attempts: u32,
) -> Option<u64> {
    for i in 0..max_attempts {
        let params = json!({
            "scope": account_url,
            "query": {"queryType": "default"}
        });

        match client.v3_client.call_v3::<Value>("query", params).await {
            Ok(result) => {
                if let Some(account) = result.get("account") {
                    // Try balance as string first
                    if let Some(balance) = account.get("balance").and_then(|b| b.as_str()) {
                        if let Ok(bal) = balance.parse::<u64>() {
                            if bal > 0 {
                                return Some(bal);
                            }
                        }
                    }
                    // Try balance as number
                    if let Some(bal) = account.get("balance").and_then(|b| b.as_u64()) {
                        if bal > 0 {
                            return Some(bal);
                        }
                    }
                }
                println!("  Waiting for balance... (attempt {}/{})", i + 1, max_attempts);
            }
            Err(_) => {
                // Account may not exist yet
                println!("  Account not found yet... (attempt {}/{})", i + 1, max_attempts);
            }
        }

        if i < max_attempts - 1 {
            tokio::time::sleep(Duration::from_secs(2)).await;
        }
    }
    None
}

/// Poll for key page credits (matching Dart SDK pollForKeyPageCredits)
pub async fn poll_for_credits(
    client: &AccumulateClient,
    key_page_url: &str,
    max_attempts: u32,
) -> Option<u64> {
    for i in 0..max_attempts {
        let params = json!({
            "scope": key_page_url,
            "query": {"queryType": "default"}
        });

        if let Ok(result) = client.v3_client.call_v3::<Value>("query", params).await {
            if let Some(account) = result.get("account") {
                if let Some(credits) = account.get("creditBalance").and_then(|c| c.as_u64()) {
                    if credits > 0 {
                        return Some(credits);
                    }
                }
            }
        }

        if i < max_attempts - 1 {
            tokio::time::sleep(Duration::from_secs(2)).await;
        }
    }
    None
}

/// Wait for transaction confirmation
pub async fn wait_for_tx(
    client: &AccumulateClient,
    txid: &str,
    max_attempts: u32,
) -> bool {
    let tx_hash = txid.split('@').next().unwrap_or(txid).replace("acc://", "");

    for _ in 0..max_attempts {
        let params = json!({
            "scope": format!("acc://{}@unknown", tx_hash),
            "query": {"queryType": "default"}
        });

        if let Ok(result) = client.v3_client.call_v3::<Value>("query", params).await {
            if let Some(status) = result.get("status") {
                if status.get("delivered").and_then(|d| d.as_bool()).unwrap_or(false) {
                    return true;
                }
            }
        }

        tokio::time::sleep(Duration::from_secs(2)).await;
    }
    false
}

// =============================================================================
// WALLET STRUCT
// =============================================================================

/// Simple wallet with lite identity and token account
#[derive(Debug, Clone)]
pub struct Wallet {
    /// Lite identity URL
    pub lite_identity: String,
    /// Lite token account URL
    pub lite_token_account: String,
    /// Signing key
    keypair: SigningKey,
}

impl Wallet {
    /// Get the signing key
    pub fn keypair(&self) -> &SigningKey {
        &self.keypair
    }

    /// Get the public key bytes
    pub fn public_key(&self) -> [u8; 32] {
        self.keypair.verifying_key().to_bytes()
    }

    /// Get the public key hash
    pub fn public_key_hash(&self) -> [u8; 32] {
        sha256_hash(&self.public_key())
    }
}

// =============================================================================
// ADI INFO STRUCT
// =============================================================================

/// ADI (Accumulate Digital Identity) information
#[derive(Debug, Clone)]
pub struct AdiInfo {
    /// ADI URL
    pub url: String,
    /// Key book URL
    pub key_book_url: String,
    /// Key page URL
    pub key_page_url: String,
    /// ADI signing key
    keypair: SigningKey,
}

impl AdiInfo {
    /// Get the signing key
    pub fn keypair(&self) -> &SigningKey {
        &self.keypair
    }

    /// Get the public key bytes
    pub fn public_key(&self) -> [u8; 32] {
        self.keypair.verifying_key().to_bytes()
    }
}

// =============================================================================
// KEY PAGE INFO
// =============================================================================

/// Key page information for QuickStart API
#[derive(Debug, Clone)]
pub struct KeyPageInfo {
    /// Credit balance
    pub credits: u64,
    /// Current version
    pub version: u64,
    /// Accept threshold
    pub threshold: u64,
    /// Number of keys
    pub key_count: usize,
}

// =============================================================================
// QUICKSTART API
// =============================================================================

/// Ultra-simple API for rapid development (matching Dart SDK QuickStart)
#[derive(Debug)]
pub struct QuickStart {
    /// The underlying client
    client: AccumulateClient,
}

impl QuickStart {
    /// Connect to local DevNet
    pub async fn devnet() -> Result<Self, JsonRpcError> {
        let v2_url = Url::parse(DEVNET_V2).map_err(|e| {
            JsonRpcError::General(anyhow::anyhow!("Invalid URL: {}", e))
        })?;
        let v3_url = Url::parse(DEVNET_V3).map_err(|e| {
            JsonRpcError::General(anyhow::anyhow!("Invalid URL: {}", e))
        })?;

        let client = AccumulateClient::new_with_options(v2_url, v3_url, AccOptions::default()).await?;
        Ok(Self { client })
    }

    /// Connect to Kermit testnet
    pub async fn kermit() -> Result<Self, JsonRpcError> {
        let v2_url = Url::parse(KERMIT_V2).map_err(|e| {
            JsonRpcError::General(anyhow::anyhow!("Invalid URL: {}", e))
        })?;
        let v3_url = Url::parse(KERMIT_V3).map_err(|e| {
            JsonRpcError::General(anyhow::anyhow!("Invalid URL: {}", e))
        })?;

        let client = AccumulateClient::new_with_options(v2_url, v3_url, AccOptions::default()).await?;
        Ok(Self { client })
    }

    /// Connect to custom endpoints
    pub async fn custom(v2_endpoint: &str, v3_endpoint: &str) -> Result<Self, JsonRpcError> {
        let v2_url = Url::parse(v2_endpoint).map_err(|e| {
            JsonRpcError::General(anyhow::anyhow!("Invalid V2 URL: {}", e))
        })?;
        let v3_url = Url::parse(v3_endpoint).map_err(|e| {
            JsonRpcError::General(anyhow::anyhow!("Invalid V3 URL: {}", e))
        })?;

        let client = AccumulateClient::new_with_options(v2_url, v3_url, AccOptions::default()).await?;
        Ok(Self { client })
    }

    /// Get the underlying client
    pub fn client(&self) -> &AccumulateClient {
        &self.client
    }

    /// Create a new wallet with lite identity and token account
    pub fn create_wallet(&self) -> Wallet {
        let keypair = AccumulateClient::generate_keypair();
        let public_key = keypair.verifying_key().to_bytes();

        // Derive lite identity URL
        let lite_identity = derive_lite_identity_url(&public_key);
        let lite_token_account = format!("{}/ACME", lite_identity);

        Wallet {
            lite_identity,
            lite_token_account,
            keypair,
        }
    }

    /// Fund wallet from faucet (multiple requests) using V3 API
    pub async fn fund_wallet(&self, wallet: &Wallet, times: u32) -> Result<(), JsonRpcError> {
        for i in 0..times {
            let params = json!({"account": &wallet.lite_token_account});
            match self.client.v3_client.call_v3::<Value>("faucet", params).await {
                Ok(response) => {
                    let txid = response.get("transactionHash")
                        .or_else(|| response.get("txid"))
                        .and_then(|v| v.as_str())
                        .unwrap_or("submitted");
                    println!("  Faucet {}/{}: {}", i + 1, times, txid);
                }
                Err(e) => {
                    println!("  Faucet {}/{} failed: {}", i + 1, times, e);
                }
            }
            if i < times - 1 {
                tokio::time::sleep(Duration::from_secs(2)).await;
            }
        }

        // Wait for faucet transactions to process
        println!("  Waiting for faucet to process...");
        tokio::time::sleep(Duration::from_secs(10)).await;

        // Poll for balance to confirm account is available
        let balance = poll_for_balance(&self.client, &wallet.lite_token_account, 30).await;
        if balance.is_none() || balance == Some(0) {
            println!("  Warning: Account balance not confirmed yet");
        }

        Ok(())
    }

    /// Get account balance (polls up to 30 times)
    pub async fn get_balance(&self, wallet: &Wallet) -> Option<u64> {
        poll_for_balance(&self.client, &wallet.lite_token_account, 30).await
    }

    /// Get oracle price from network status
    pub async fn get_oracle_price(&self) -> Result<u64, JsonRpcError> {
        let result: Value = self.client.v3_client.call_v3("network-status", json!({})).await?;

        result.get("oracle")
            .and_then(|o| o.get("price"))
            .and_then(|p| p.as_u64())
            .ok_or_else(|| JsonRpcError::General(anyhow::anyhow!("Oracle price not found")))
    }

    /// Calculate ACME amount for desired credits
    pub fn calculate_credits_amount(credits: u64, oracle: u64) -> u64 {
        // credits * 10^10 / oracle
        (credits as u128 * 10_000_000_000u128 / oracle as u128) as u64
    }

    /// Set up an ADI (handles all the complexity)
    pub async fn setup_adi(&self, wallet: &Wallet, adi_name: &str) -> Result<AdiInfo, JsonRpcError> {
        let adi_keypair = AccumulateClient::generate_keypair();
        let adi_public_key = adi_keypair.verifying_key().to_bytes();
        let adi_key_hash = sha256_hash(&adi_public_key);

        let identity_url = format!("acc://{}.acme", adi_name);
        let book_url = format!("{}/book", identity_url);
        let key_page_url = format!("{}/1", book_url);

        // First, add credits to lite identity
        let oracle = self.get_oracle_price().await?;
        let credits_amount = Self::calculate_credits_amount(1000, oracle);

        let mut signer = SmartSigner::new(&self.client, wallet.keypair.clone(), &wallet.lite_identity);

        // Add credits to lite identity
        let add_credits_body = TxBody::add_credits(
            &wallet.lite_identity,
            &credits_amount.to_string(),
            oracle,
        );

        let result = signer.sign_submit_and_wait(
            &wallet.lite_token_account,
            &add_credits_body,
            Some("Add credits to lite identity"),
            30,
        ).await;

        if !result.success {
            return Err(JsonRpcError::General(anyhow::anyhow!(
                "Failed to add credits: {:?}", result.error
            )));
        }

        // Create ADI
        let create_adi_body = TxBody::create_identity(
            &identity_url,
            &book_url,
            &hex::encode(adi_key_hash),
        );

        let result = signer.sign_submit_and_wait(
            &wallet.lite_token_account,
            &create_adi_body,
            Some("Create ADI"),
            30,
        ).await;

        if !result.success {
            return Err(JsonRpcError::General(anyhow::anyhow!(
                "Failed to create ADI: {:?}", result.error
            )));
        }

        Ok(AdiInfo {
            url: identity_url,
            key_book_url: book_url,
            key_page_url,
            keypair: adi_keypair,
        })
    }

    /// Buy credits for ADI key page (auto-fetches oracle)
    pub async fn buy_credits_for_adi(&self, wallet: &Wallet, adi: &AdiInfo, credits: u64) -> Result<TxResult, JsonRpcError> {
        let oracle = self.get_oracle_price().await?;
        let amount = Self::calculate_credits_amount(credits, oracle);

        let mut signer = SmartSigner::new(&self.client, wallet.keypair.clone(), &wallet.lite_identity);

        let body = TxBody::add_credits(&adi.key_page_url, &amount.to_string(), oracle);

        Ok(signer.sign_submit_and_wait(
            &wallet.lite_token_account,
            &body,
            Some("Buy credits for ADI"),
            30,
        ).await)
    }

    /// Get key page information
    pub async fn get_key_page_info(&self, key_page_url: &str) -> Option<KeyPageInfo> {
        let manager = KeyManager::new(&self.client, key_page_url);
        match manager.get_key_page_state().await {
            Ok(state) => Some(KeyPageInfo {
                credits: state.credit_balance,
                version: state.version,
                threshold: state.accept_threshold,
                key_count: state.keys.len(),
            }),
            Err(_) => None,
        }
    }

    /// Create a token account under an ADI
    pub async fn create_token_account(&self, adi: &AdiInfo, account_name: &str) -> Result<TxResult, JsonRpcError> {
        let account_url = format!("{}/{}", adi.url, account_name);
        let mut signer = SmartSigner::new(&self.client, adi.keypair.clone(), &adi.key_page_url);

        let body = TxBody::create_token_account(&account_url, "acc://ACME");

        Ok(signer.sign_submit_and_wait(
            &adi.url,
            &body,
            Some("Create token account"),
            30,
        ).await)
    }

    /// Create a data account under an ADI
    pub async fn create_data_account(&self, adi: &AdiInfo, account_name: &str) -> Result<TxResult, JsonRpcError> {
        let account_url = format!("{}/{}", adi.url, account_name);
        let mut signer = SmartSigner::new(&self.client, adi.keypair.clone(), &adi.key_page_url);

        let body = TxBody::create_data_account(&account_url);

        Ok(signer.sign_submit_and_wait(
            &adi.url,
            &body,
            Some("Create data account"),
            30,
        ).await)
    }

    /// Write data to a data account
    pub async fn write_data(&self, adi: &AdiInfo, account_name: &str, entries: &[&str]) -> Result<TxResult, JsonRpcError> {
        let account_url = format!("{}/{}", adi.url, account_name);
        let mut signer = SmartSigner::new(&self.client, adi.keypair.clone(), &adi.key_page_url);

        let body = TxBody::write_data(entries);

        Ok(signer.sign_submit_and_wait(
            &account_url,
            &body,
            Some("Write data"),
            30,
        ).await)
    }

    /// Add a key to the ADI's key page
    pub async fn add_key_to_adi(&self, adi: &AdiInfo, new_keypair: &SigningKey) -> Result<TxResult, JsonRpcError> {
        let mut signer = SmartSigner::new(&self.client, adi.keypair.clone(), &adi.key_page_url);
        Ok(signer.add_key(&new_keypair.verifying_key().to_bytes()).await)
    }

    /// Set multi-sig threshold for the ADI's key page
    pub async fn set_multi_sig_threshold(&self, adi: &AdiInfo, threshold: u64) -> Result<TxResult, JsonRpcError> {
        let mut signer = SmartSigner::new(&self.client, adi.keypair.clone(), &adi.key_page_url);
        Ok(signer.set_threshold(threshold).await)
    }

    /// Close the client (for cleanup)
    pub fn close(&self) {
        // HTTP client cleanup is automatic in Rust
    }
}

// =============================================================================
// UTILITY FUNCTIONS
// =============================================================================

/// Derive lite identity URL from public key
///
/// Format: acc://[40 hex key hash][8 hex checksum]
/// - Key hash: SHA256(publicKey)[0..20] as hex (40 chars)
/// - Checksum: SHA256(keyHashHex)[28..32] as hex (8 chars)
///
/// Note: Lite addresses do NOT have .acme suffix!
pub fn derive_lite_identity_url(public_key: &[u8; 32]) -> String {
    // Get first 20 bytes of SHA256(publicKey)
    let hash = sha256_hash(public_key);
    let key_hash_20 = &hash[0..20];

    // Convert to hex string
    let key_hash_hex = hex::encode(key_hash_20);

    // Compute checksum: SHA256(keyHashHex)[28..32]
    let checksum_full = sha256_hash(key_hash_hex.as_bytes());
    let checksum_hex = hex::encode(&checksum_full[28..32]);

    // Format: acc://[keyHash][checksum]
    format!("acc://{}{}", key_hash_hex, checksum_hex)
}

/// Derive lite token account URL from public key
///
/// Format: acc://[40 hex key hash][8 hex checksum]/ACME
pub fn derive_lite_token_account_url(public_key: &[u8; 32]) -> String {
    let lite_identity = derive_lite_identity_url(public_key);
    format!("{}/ACME", lite_identity)
}

/// SHA-256 hash helper
pub fn sha256_hash(data: &[u8]) -> [u8; 32] {
    let mut hasher = Sha256::new();
    hasher.update(data);
    hasher.finalize().into()
}

/// Extract transaction ID from submit response
///
/// The V3 API returns a List with two entries:
/// - [0] = transaction result with txID like acc://hash@account/path
/// - [1] = signature result with txID like acc://hash@account
///
/// We prefer the second entry (signature tx) which doesn't have path suffix.
fn extract_txid(response: &Value) -> Option<String> {
    // Try array format first - this is the V3 format
    if let Some(arr) = response.as_array() {
        // Prefer second entry (signature tx) if available
        if arr.len() > 1 {
            if let Some(status) = arr[1].get("status") {
                if let Some(txid) = status.get("txID").and_then(|t| t.as_str()) {
                    return Some(txid.to_string());
                }
            }
        }
        // Fall back to first entry
        if let Some(first) = arr.first() {
            if let Some(status) = first.get("status") {
                if let Some(txid) = status.get("txID").and_then(|t| t.as_str()) {
                    return Some(txid.to_string());
                }
            }
        }
    }

    // Try direct format
    response.get("txid")
        .or_else(|| response.get("transactionHash"))
        .and_then(|t| t.as_str())
        .map(String::from)
}

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

    #[test]
    fn test_derive_lite_identity_url() {
        let public_key = [1u8; 32];
        let url = derive_lite_identity_url(&public_key);
        assert!(url.starts_with("acc://"));
        // Lite URLs do NOT have .acme suffix - they have 40 hex chars + 8 hex checksum
        assert!(!url.ends_with(".acme"));
        // Format: acc://[40 hex][8 hex checksum]
        let path = url.strip_prefix("acc://").unwrap();
        assert_eq!(path.len(), 48); // 40 + 8 hex chars
    }

    #[test]
    fn test_tx_body_add_credits() {
        let body = TxBody::add_credits("acc://test.acme/credits", "1000000", 5000);
        assert_eq!(body["type"], "addCredits");
        assert_eq!(body["recipient"], "acc://test.acme/credits");
    }

    #[test]
    fn test_tx_body_send_tokens() {
        let body = TxBody::send_tokens_single("acc://bob.acme/tokens", "100");
        assert_eq!(body["type"], "sendTokens");
    }

    #[test]
    fn test_tx_body_create_identity() {
        let body = TxBody::create_identity(
            "acc://test.acme",
            "acc://test.acme/book",
            "0123456789abcdef",
        );
        assert_eq!(body["type"], "createIdentity");
        assert_eq!(body["url"], "acc://test.acme");
    }

    #[test]
    fn test_wallet_creation() {
        let keypair = AccumulateClient::generate_keypair();
        let public_key = keypair.verifying_key().to_bytes();
        let lite_identity = derive_lite_identity_url(&public_key);
        let lite_token_account = derive_lite_token_account_url(&public_key);

        assert!(lite_identity.starts_with("acc://"));
        assert!(lite_token_account.contains("/ACME"));
    }
}