aptos-sdk 0.5.0

A user-friendly, idiomatic Rust SDK for the Aptos blockchain
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
//! End-to-end tests against localnet or testnet.
//!
//! These tests require a running Aptos node and are only compiled when
//! the `e2e` feature is enabled.
//!
//! ## Running the tests
//!
//! ### Option 1: Using the convenience script
//! ```bash
//! ./scripts/run-e2e.sh
//! ```
//!
//! ### Option 2: Manual setup
//! ```bash
//! # In one terminal, start localnet:
//! aptos node run-localnet --with-faucet
//!
//! # In another terminal, run tests:
//! cargo test -p aptos-sdk --features "e2e,full"
//! ```
//!
//! ### Option 3: Using custom node URLs
//! ```bash
//! export APTOS_LOCAL_NODE_URL=http://127.0.0.1:8080/v1
//! export APTOS_LOCAL_FAUCET_URL=http://127.0.0.1:8081
//! cargo test -p aptos-sdk --features "e2e,full"
//! ```
//!
//! ## Test Categories
//!
//! - **`account_tests`**: Account creation, funding, balance queries
//! - **`transfer_tests`**: APT transfers between accounts
//! - **`view_tests`**: View function calls
//! - **`transaction_tests`**: Transaction building, signing, submission
//! - **`multi_signer_tests`**: Multi-agent and fee payer transactions
//! - **`state_tests`**: Resource and state queries
//!
//! Script bytecode is loaded from each Move project: two-signer from
//! `tests/e2e/move/two_signer_transfer/two_signer_transfer.mv`, single-signer from
//! `tests/e2e/move/one_signer_transfer/one_signer_transfer.mv`. If a `.mv` file is
//! missing, the corresponding test fails (panic with compile instructions). Run the
//! compile command inside each project directory:
//! `aptos move compile-script --package-dir <project> --output-file <project>.mv`.

use aptos_sdk::{Aptos, AptosConfig};
use std::env;

/// Gets the configuration for E2E tests.
fn get_test_config() -> AptosConfig {
    if let Ok(node_url) = env::var("APTOS_LOCAL_NODE_URL") {
        AptosConfig::custom(&node_url)
            .unwrap()
            .with_faucet_url(
                &env::var("APTOS_LOCAL_FAUCET_URL")
                    .unwrap_or_else(|_| "http://127.0.0.1:8081".to_string()),
            )
            .unwrap()
    } else {
        AptosConfig::local()
    }
}

/// Helper to wait for transaction finality
async fn wait_for_finality() {
    tokio::time::sleep(std::time::Duration::from_secs(2)).await;
}

// =============================================================================
// Account Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod account_tests {
    use super::*;
    use aptos_sdk::account::Ed25519Account;

    #[tokio::test]
    #[ignore]
    async fn e2e_create_and_fund_account() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Create account
        let account = Ed25519Account::generate();
        println!("Created account: {}", account.address());

        // Fund account
        let txn_hashes = aptos
            .fund_account(account.address(), 100_000_000)
            .await
            .expect("failed to fund account");
        println!("Funded with txns: {txn_hashes:?}");

        wait_for_finality().await;

        // Check balance
        let balance = aptos
            .get_balance(account.address())
            .await
            .expect("failed to get balance");
        assert!(balance > 0, "balance should be > 0");
        println!("Balance: {balance} octas");
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_create_funded_account_helper() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Use helper method
        let account = aptos
            .create_funded_account(50_000_000)
            .await
            .expect("failed to create funded account");

        println!("Created funded account: {}", account.address());

        wait_for_finality().await;

        let balance = aptos
            .get_balance(account.address())
            .await
            .expect("failed to get balance");
        assert!(balance > 0, "balance should be > 0");
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_get_sequence_number() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let account = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create account");

        let seq_num = aptos
            .get_sequence_number(account.address())
            .await
            .expect("failed to get sequence number");

        println!("Sequence number: {seq_num}");
        // New account should have sequence number 0
        assert_eq!(seq_num, 0);
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_account_not_found() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Random unfunded account
        let account = Ed25519Account::generate();

        // Under AIP-42 (implicit accounts) the fullnode reports sequence_number = 0
        // for any address that has never been touched. The two valid outcomes are:
        //   * an explicit "not found" error, or
        //   * sequence_number == 0
        // anything else (a non-zero seq num for a freshly-generated random key) is a bug.
        match aptos.get_sequence_number(account.address()).await {
            Ok(seq) => assert_eq!(
                seq, 0,
                "freshly generated account should have sequence number 0 \
                 (or return not-found), got {seq}"
            ),
            Err(e) => assert!(
                e.is_not_found(),
                "unexpected error for unfunded account (expected a not-found \
                 error or success with seq=0, but got something else): {e}"
            ),
        }

        // get_balance for a fresh address should return 0.
        let balance = aptos
            .get_balance(account.address())
            .await
            .expect("get_balance should succeed for unfunded address (implicit accounts)");
        assert_eq!(balance, 0, "fresh account must have zero balance");

        // account_exists currently maps to `GET /accounts/{addr}` which, under
        // AIP-42 (implicit accounts) on modern Aptos chains, returns 200 for
        // any well-formed address. The helper therefore reports `true` even
        // for never-funded addresses. We assert this is the actual behavior so
        // a regression (e.g., the helper falsely reporting `false` on devnet)
        // would surface immediately, while making the AIP-42 contract explicit
        // in the test name.
        let exists = aptos
            .account_exists(account.address())
            .await
            .expect("account_exists should succeed");
        assert!(
            exists,
            "under AIP-42 implicit accounts the fullnode reports any \
             well-formed address as existing"
        );
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_sequence_number_increments() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let sender = aptos
            .create_funded_account(500_000_000)
            .await
            .expect("failed to create funded sender");

        let start = aptos
            .get_sequence_number(sender.address())
            .await
            .expect("failed to get sequence number");
        assert_eq!(start, 0, "new account must start at sequence number 0");

        // Send two transactions and verify the on-chain sequence number advances.
        for i in 1..=2u64 {
            let recipient = Ed25519Account::generate();
            aptos
                .transfer_apt(&sender, recipient.address(), 1_000)
                .await
                .expect("transfer failed");
            let now = aptos
                .get_sequence_number(sender.address())
                .await
                .expect("failed to get sequence number");
            assert_eq!(
                now, i,
                "sequence number must increment by exactly 1 per submitted transaction"
            );
        }
    }
}

// =============================================================================
// Transfer Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod transfer_tests {
    use super::*;
    use aptos_sdk::account::Ed25519Account;

    #[tokio::test]
    #[ignore]
    async fn e2e_transfer_apt() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Create and fund sender
        let sender = aptos
            .create_funded_account(200_000_000)
            .await
            .expect("failed to create sender");
        println!("Sender: {}", sender.address());

        // Create recipient
        let recipient = Ed25519Account::generate();
        println!("Recipient: {}", recipient.address());

        // Transfer
        let result = aptos
            .transfer_apt(&sender, recipient.address(), 10_000_000)
            .await
            .expect("failed to transfer");

        let success = result
            .data
            .get("success")
            .and_then(serde_json::Value::as_bool);
        assert_eq!(success, Some(true), "transfer should succeed");
        println!("Transfer successful!");

        wait_for_finality().await;

        // Check recipient balance
        let balance = aptos
            .get_balance(recipient.address())
            .await
            .expect("failed to get balance");
        assert_eq!(
            balance, 10_000_000,
            "recipient should have transferred amount"
        );
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_multiple_transfers() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let sender = aptos
            .create_funded_account(500_000_000)
            .await
            .expect("failed to create sender");

        // Transfer to multiple recipients
        let recipients: Vec<_> = (0..3).map(|_| Ed25519Account::generate()).collect();

        for (i, recipient) in recipients.iter().enumerate() {
            let result = aptos
                .transfer_apt(&sender, recipient.address(), 1_000_000 * (i as u64 + 1))
                .await
                .expect("failed to transfer");

            let success = result
                .data
                .get("success")
                .and_then(serde_json::Value::as_bool);
            assert_eq!(success, Some(true));
            println!("Transfer {} to {} successful", i + 1, recipient.address());
        }

        wait_for_finality().await;

        // Verify balances
        for (i, recipient) in recipients.iter().enumerate() {
            let balance = aptos.get_balance(recipient.address()).await.unwrap_or(0);
            let expected = 1_000_000 * (i as u64 + 1);
            assert_eq!(balance, expected, "recipient {i} balance mismatch");
        }
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_transfer_insufficient_balance() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let sender = aptos
            .create_funded_account(1_000_000)
            .await
            .expect("failed to create sender");

        let recipient = Ed25519Account::generate();

        // Try to transfer more than we have
        let result = aptos
            .transfer_apt(&sender, recipient.address(), 999_999_999_999)
            .await;

        // Should fail (either at simulation or execution)
        assert!(
            result.is_err() || {
                let r = result.unwrap();
                r.data.get("success").and_then(serde_json::Value::as_bool) == Some(false)
            }
        );
    }
}

// =============================================================================
// View Function Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod view_tests {
    use super::*;
    use aptos_sdk::account::Ed25519Account;

    #[tokio::test]
    #[ignore]
    async fn e2e_view_timestamp() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let result = aptos
            .view("0x1::timestamp::now_seconds", vec![], vec![])
            .await
            .expect("failed to call view function");

        assert!(!result.is_empty(), "should return a value");
        println!("Current timestamp: {result:?}");

        // Parse the timestamp
        if let Some(timestamp) = result[0].as_str() {
            let ts: u64 = timestamp.parse().expect("should be a number");
            assert!(ts > 0, "timestamp should be > 0");
        }
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_view_coin_balance() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let funded_amount: u64 = 100_000_000;
        let account = aptos
            .create_funded_account(funded_amount)
            .await
            .expect("failed to create account");

        wait_for_finality().await;

        let result = aptos
            .view(
                "0x1::coin::balance",
                vec!["0x1::aptos_coin::AptosCoin".to_string()],
                vec![serde_json::json!(account.address().to_string())],
            )
            .await
            .expect("failed to call view function");

        assert_eq!(result.len(), 1, "view function should return one value");
        let balance_str = result[0]
            .as_str()
            .expect("balance must be returned as a string");
        let balance_via_view: u64 = balance_str.parse().expect("balance must parse as a u64");

        // Compare against the canonical get_balance helper. The view function
        // and the helper must agree on the balance.
        let balance_via_helper = aptos
            .get_balance(account.address())
            .await
            .expect("get_balance failed");
        assert_eq!(
            balance_via_view, balance_via_helper,
            "view-function balance must match get_balance helper"
        );
        assert!(
            balance_via_view >= funded_amount,
            "balance ({balance_via_view}) must be at least the funded amount ({funded_amount})"
        );
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_view_account_exists() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let account = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create account");

        wait_for_finality().await;

        // Check if account exists
        let result = aptos
            .view(
                "0x1::account::exists_at",
                vec![],
                vec![serde_json::json!(account.address().to_string())],
            )
            .await
            .expect("failed to call view function");

        assert_eq!(result[0], serde_json::json!(true));
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_view_nonexistent_account() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let random_address = Ed25519Account::generate().address();
        println!("Random address: {random_address}");

        let result = aptos
            .view(
                "0x1::account::exists_at",
                vec![],
                vec![serde_json::json!(random_address.to_string())],
            )
            .await
            .expect("failed to call view function");

        println!("Result: {result:?}");
        // Note: Modern Aptos chains use implicit accounts (AIP-42), so all addresses
        // are considered to "exist" with sequence_number=0 until a transaction is made.
        // The view function returns true for all addresses now.
        assert_eq!(result[0], serde_json::json!(true));
    }
}

// =============================================================================
// Transaction Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod transaction_tests {
    use super::*;
    use aptos_sdk::account::Ed25519Account;
    use aptos_sdk::transaction::{
        EntryFunction, Script, ScriptArgument, TransactionBuilder, TransactionPayload,
        builder::sign_transaction,
    };

    #[tokio::test]
    #[ignore]
    async fn e2e_script_transfer() {
        let script_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/e2e/move/one_signer_transfer/one_signer_transfer.mv");
        let bytecode = std::fs::read(&script_path).expect(
            "one_signer_transfer.mv not found; run inside tests/e2e/move/one_signer_transfer/: \
             aptos move compile-script --output-file one_signer_transfer.mv",
        );

        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let sender = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create sender");

        let recipient = Ed25519Account::generate().address();
        let amount = 50_000u64;

        let payload = TransactionPayload::Script(Script::new(
            bytecode,
            vec![],
            vec![
                ScriptArgument::Address(recipient),
                ScriptArgument::U64(amount),
            ],
        ));

        let sender_seq = aptos
            .get_sequence_number(sender.address())
            .await
            .expect("failed to get sequence number");
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        let raw_txn = TransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(sender_seq)
            .payload(payload)
            .chain_id(chain_id)
            .max_gas_amount(100_000)
            .gas_unit_price(100)
            .build()
            .expect("failed to build");

        let signed = sign_transaction(&raw_txn, &sender).expect("failed to sign");

        let _result = aptos
            .submit_and_wait(&signed, None)
            .await
            .expect("submit_and_wait should succeed");

        wait_for_finality().await;

        let balance = aptos
            .get_balance(recipient)
            .await
            .expect("failed to get recipient balance");
        assert!(
            balance >= amount,
            "recipient balance {balance} should be >= amount {amount}",
        );
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_build_sign_submit_transaction() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let sender = aptos
            .create_funded_account(500_000_000)
            .await
            .expect("failed to create account");

        let recipient = Ed25519Account::generate();
        let amount: u64 = 1_234_567;

        let payload = EntryFunction::apt_transfer(recipient.address(), amount).unwrap();
        let raw_txn = aptos
            .build_transaction(&sender, payload.into())
            .await
            .expect("failed to build transaction");

        let signed = sign_transaction(&raw_txn, &sender).expect("failed to sign");

        // BCS round-trip: serialize then deserialize the signed transaction.
        let bcs_bytes = signed.to_bcs().expect("failed to serialize");
        assert!(
            !bcs_bytes.is_empty(),
            "BCS serialization must produce bytes"
        );

        let result = aptos
            .submit_and_wait(&signed, None)
            .await
            .expect("failed to submit");

        let success = result
            .data
            .get("success")
            .and_then(serde_json::Value::as_bool);
        assert_eq!(
            success,
            Some(true),
            "transaction should execute successfully, got: {:?}",
            result.data
        );

        wait_for_finality().await;

        // Verify the recipient was credited the *exact* amount.
        let balance = aptos
            .get_balance(recipient.address())
            .await
            .expect("failed to get recipient balance");
        assert_eq!(
            balance, amount,
            "recipient should have received exactly the transferred amount"
        );
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_simulate_transaction() {
        use aptos_sdk::account::Account;
        use aptos_sdk::transaction::authenticator::{Ed25519PublicKey, Ed25519Signature};
        use aptos_sdk::transaction::{SignedTransaction, TransactionAuthenticator};

        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let account = aptos
            .create_funded_account(500_000_000)
            .await
            .expect("failed to create account");

        let payload =
            EntryFunction::apt_transfer(Ed25519Account::generate().address(), 1000).unwrap();

        let raw_txn = aptos
            .build_transaction(&account, payload.into())
            .await
            .expect("failed to build transaction");

        // For simulation, we need to create a transaction with a zeroed signature
        // (the API rejects transactions with valid signatures for simulation)
        let auth = TransactionAuthenticator::Ed25519 {
            public_key: Ed25519PublicKey(account.public_key_bytes().try_into().unwrap()),
            signature: Ed25519Signature([0u8; 64]),
        };
        let signed = SignedTransaction::new(raw_txn, auth);

        // Simulate
        let result = aptos
            .simulate_transaction(&signed)
            .await
            .expect("failed to simulate");

        assert!(!result.data.is_empty(), "simulation should return results");

        let success = result.data[0]
            .get("success")
            .and_then(serde_json::Value::as_bool);
        assert_eq!(success, Some(true), "simulation should succeed");

        let gas_used = result.data[0].get("gas_used").and_then(|v| v.as_str());
        println!("Simulated gas used: {gas_used:?}");
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_get_transaction_by_hash() {
        use aptos_sdk::types::HashValue;

        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let sender = aptos
            .create_funded_account(500_000_000)
            .await
            .expect("failed to create account");

        let result = aptos
            .transfer_apt(&sender, Ed25519Account::generate().address(), 1000)
            .await
            .expect("failed to transfer");

        let hash_str = result
            .data
            .get("hash")
            .and_then(|v| v.as_str())
            .expect("response must include a transaction hash");

        wait_for_finality().await;

        let hash = HashValue::from_hex(hash_str).expect("invalid hash");
        let txn = aptos
            .fullnode()
            .get_transaction_by_hash(&hash)
            .await
            .expect("should be able to get transaction by hash");

        // Verify the looked-up txn matches the one we submitted.
        let looked_up_hash = txn
            .data
            .get("hash")
            .and_then(|v| v.as_str())
            .expect("response must contain hash");
        assert_eq!(looked_up_hash, hash_str);

        let sender_field = txn
            .data
            .get("sender")
            .and_then(|v| v.as_str())
            .expect("transaction must have a sender field");
        // Sender can be returned in short or long form. Compare against both.
        assert!(
            sender_field == sender.address().to_short_string()
                || sender_field == sender.address().to_long_string(),
            "sender mismatch: got {sender_field}, expected {} or {}",
            sender.address().to_short_string(),
            sender.address().to_long_string()
        );

        let success = txn.data.get("success").and_then(serde_json::Value::as_bool);
        assert_eq!(success, Some(true));
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_transaction_expiration() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let account = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create account");

        // Build transaction with very short expiration (already expired)
        let payload =
            EntryFunction::apt_transfer(Ed25519Account::generate().address(), 1000).unwrap();
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        let raw_txn = aptos_sdk::transaction::TransactionBuilder::new()
            .sender(account.address())
            .sequence_number(0)
            .payload(payload.into())
            .chain_id(chain_id)
            .expiration_timestamp_secs(1) // Already expired
            .build()
            .expect("failed to build");

        let signed = sign_transaction(&raw_txn, &account).expect("failed to sign");

        // Submission should fail due to expiration
        let result = aptos.submit_and_wait(&signed, None).await;
        assert!(result.is_err(), "expired transaction should fail");
    }
}

// =============================================================================
// Ledger/Chain Info Tests
// =============================================================================

#[cfg(feature = "ed25519")]
mod ledger_tests {
    use super::*;

    #[tokio::test]
    #[ignore]
    async fn e2e_get_ledger_info() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let ledger_info = aptos
            .ledger_info()
            .await
            .expect("failed to get ledger info");

        println!(
            "Ledger version: {}",
            ledger_info.version().expect("failed to parse version")
        );
        println!(
            "Block height: {}",
            ledger_info.height().expect("failed to parse height")
        );
        println!(
            "Epoch: {}",
            ledger_info.epoch_num().expect("failed to parse epoch")
        );

        assert!(
            ledger_info.version().expect("failed to parse version") > 0,
            "ledger version should be > 0"
        );
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_chain_id_from_ledger() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Just verify we can get ledger info
        let _ledger_info = aptos
            .ledger_info()
            .await
            .expect("failed to get ledger info");

        // Chain ID should be set
        assert!(aptos.chain_id().id() > 0);
        println!("Client chain ID: {}", aptos.chain_id().id());
    }
}

// =============================================================================
// Multi-Signer Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod multi_signer_tests {
    use super::*;
    use aptos_sdk::account::{Account, Ed25519Account};
    use aptos_sdk::transaction::{
        EntryFunction, Script, ScriptArgument, TransactionBuilder, TransactionPayload,
        builder::{sign_fee_payer_transaction, sign_multi_agent_transaction},
        types::{FeePayerRawTransaction, MultiAgentRawTransaction},
    };

    #[tokio::test]
    #[ignore]
    async fn e2e_fee_payer_transaction() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Sender has just enough APT to pay the transfer itself (no gas budget).
        let sender = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create sender");

        // Fee payer covers the gas.
        let fee_payer = aptos
            .create_funded_account(500_000_000)
            .await
            .expect("failed to create fee payer");

        let recipient = Ed25519Account::generate();
        let transfer_amount: u64 = 500;

        let payload = EntryFunction::apt_transfer(recipient.address(), transfer_amount).unwrap();

        let sender_seq = aptos
            .get_sequence_number(sender.address())
            .await
            .expect("failed to get sender seq");
        let fee_payer_balance_before = aptos
            .get_balance(fee_payer.address())
            .await
            .expect("failed to read fee payer balance");
        let sender_balance_before = aptos
            .get_balance(sender.address())
            .await
            .expect("failed to read sender balance");
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        let raw_txn = TransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(sender_seq)
            .payload(payload.into())
            .chain_id(chain_id)
            .max_gas_amount(2_000_000)
            .gas_unit_price(100)
            .build()
            .expect("failed to build");

        let fee_payer_txn = FeePayerRawTransaction {
            raw_txn,
            secondary_signer_addresses: vec![],
            fee_payer_address: fee_payer.address(),
        };

        let signed = sign_fee_payer_transaction(&fee_payer_txn, &sender, &[], &fee_payer)
            .expect("failed to sign");

        let result = aptos
            .submit_and_wait(&signed, None)
            .await
            .expect("fee-payer transaction must be accepted by devnet");

        let success = result
            .data
            .get("success")
            .and_then(serde_json::Value::as_bool);
        assert_eq!(
            success,
            Some(true),
            "fee-payer transaction must succeed: {:?}",
            result.data
        );

        wait_for_finality().await;

        // Recipient must have received exactly the transferred amount.
        let recipient_balance = aptos
            .get_balance(recipient.address())
            .await
            .expect("failed to get recipient balance");
        assert_eq!(recipient_balance, transfer_amount);

        // Sender balance must drop by exactly the transferred amount (no gas).
        let sender_balance_after = aptos
            .get_balance(sender.address())
            .await
            .expect("failed to get sender balance");
        assert_eq!(
            sender_balance_after,
            sender_balance_before - transfer_amount,
            "sender should have paid only the transfer amount, not gas"
        );

        // Fee payer should have decreased -- but by *less* than the gas budget.
        let fee_payer_balance_after = aptos
            .get_balance(fee_payer.address())
            .await
            .expect("failed to get fee payer balance");
        assert!(
            fee_payer_balance_after < fee_payer_balance_before,
            "fee payer must have paid gas"
        );
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_multi_agent_transaction() {
        let script_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/e2e/move/two_signer_transfer/two_signer_transfer.mv");
        let two_signer_bytecode = std::fs::read(&script_path).expect(
            "two_signer_transfer.mv not found; run inside tests/e2e/move/two_signer_transfer/: \
             aptos move compile-script --output-file two_signer_transfer.mv",
        );

        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let sender = aptos
            .create_funded_account(500_000_000)
            .await
            .expect("failed to create sender");
        let secondary = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create secondary");

        // Two-signer script: VM expects sender + secondary (matches multi-agent tx).
        let recipient = Ed25519Account::generate().address();
        let amount = 1000u64;
        let payload = TransactionPayload::Script(Script::new(
            two_signer_bytecode,
            vec![],
            vec![
                ScriptArgument::Address(recipient),
                ScriptArgument::U64(amount),
            ],
        ));

        let sender_seq = aptos
            .get_sequence_number(sender.address())
            .await
            .expect("failed to get sender seq");
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        let raw_txn = TransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(sender_seq)
            .payload(payload)
            .chain_id(chain_id)
            .max_gas_amount(2_000_000)
            .gas_unit_price(100)
            .build()
            .expect("failed to build");

        let multi_agent_txn = MultiAgentRawTransaction {
            raw_txn,
            secondary_signer_addresses: vec![secondary.address()],
        };

        let secondary_ref: &dyn Account = &secondary;
        let signed = sign_multi_agent_transaction(&multi_agent_txn, &sender, &[secondary_ref])
            .expect("failed to sign");

        // BCS round-trip must succeed.
        let bytes = signed.to_bcs().expect("BCS serialization should succeed");
        assert!(!bytes.is_empty());

        let result = aptos
            .submit_and_wait(&signed, None)
            .await
            .expect("submit_and_wait should succeed");
        let success = result
            .data
            .get("success")
            .and_then(serde_json::Value::as_bool);
        assert_eq!(
            success,
            Some(true),
            "multi-agent two-signer transfer should succeed: {:?}",
            result.data
        );
    }

    /// Simulate a multi-agent transaction (no signatures) then sign and submit.
    #[tokio::test]
    #[ignore]
    async fn e2e_simulate_multi_agent_then_submit() {
        let script_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/e2e/move/two_signer_transfer/two_signer_transfer.mv");
        let two_signer_bytecode = std::fs::read(&script_path).expect(
            "two_signer_transfer.mv not found; run inside tests/e2e/move/two_signer_transfer/: \
             aptos move compile-script --output-file two_signer_transfer.mv",
        );

        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let sender = aptos
            .create_funded_account(200_000_000)
            .await
            .expect("failed to create sender");
        let secondary = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create secondary");

        // Use a two-signer script so the VM expects 2 signers (matches multi-agent tx).
        let recipient = Ed25519Account::generate().address();
        let amount = 1000u64;
        let payload = TransactionPayload::Script(Script::new(
            two_signer_bytecode,
            vec![],
            vec![
                ScriptArgument::Address(recipient),
                ScriptArgument::U64(amount),
            ],
        ));

        let sender_seq = aptos
            .get_sequence_number(sender.address())
            .await
            .unwrap_or(0);
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        let raw_txn = TransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(sender_seq)
            .payload(payload)
            .chain_id(chain_id)
            .max_gas_amount(100_000)
            .gas_unit_price(100)
            .build()
            .expect("failed to build");

        let multi_agent_txn = MultiAgentRawTransaction {
            raw_txn,
            secondary_signer_addresses: vec![secondary.address()],
        };

        // Simulate first (no signatures required)
        let sim_result = aptos
            .simulate_multi_agent(&multi_agent_txn, None)
            .await
            .expect("simulate_multi_agent should succeed");
        assert!(
            sim_result.success(),
            "simulation must succeed before submit (vm_status={})",
            sim_result.vm_status()
        );
        println!(
            "Simulation success: {}, gas_used: {}",
            sim_result.success(),
            sim_result.gas_used()
        );

        // Then sign and submit
        let secondary_ref: &dyn Account = &secondary;
        let signed = sign_multi_agent_transaction(&multi_agent_txn, &sender, &[secondary_ref])
            .expect("failed to sign");
        aptos
            .submit_and_wait(&signed, None)
            .await
            .expect("submit_and_wait should succeed");
    }

    /// Simulate a fee-payer transaction (no signatures) then sign and submit.
    #[tokio::test]
    #[ignore]
    async fn e2e_simulate_fee_payer_then_submit() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let sender = aptos
            .create_funded_account(1_000)
            .await
            .expect("failed to create sender");
        let fee_payer = aptos
            .create_funded_account(500_000_000)
            .await
            .expect("failed to create fee payer");
        let recipient = Ed25519Account::generate();

        let payload = EntryFunction::apt_transfer(recipient.address(), 500).unwrap();
        let sender_seq = aptos
            .get_sequence_number(sender.address())
            .await
            .unwrap_or(0);
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        let raw_txn = TransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(sender_seq)
            .payload(payload.into())
            .chain_id(chain_id)
            .max_gas_amount(100_000)
            .gas_unit_price(100)
            .build()
            .expect("failed to build");

        let fee_payer_txn = FeePayerRawTransaction {
            raw_txn,
            secondary_signer_addresses: vec![],
            fee_payer_address: fee_payer.address(),
        };

        // Simulate first (no signatures required)
        let sim_result = aptos
            .simulate_fee_payer(&fee_payer_txn, None)
            .await
            .expect("simulate_fee_payer should succeed");
        assert!(
            sim_result.success(),
            "simulation must succeed before submit (vm_status={})",
            sim_result.vm_status()
        );
        println!(
            "Simulation success: {}, gas_used: {}",
            sim_result.success(),
            sim_result.gas_used()
        );

        // Then sign and submit
        let signed = sign_fee_payer_transaction(&fee_payer_txn, &sender, &[], &fee_payer)
            .expect("failed to sign");
        aptos
            .submit_and_wait(&signed, None)
            .await
            .expect("submit_and_wait should succeed");
    }
}

// =============================================================================
// Multi-Key Account Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "secp256k1", feature = "faucet"))]
mod multi_key_e2e_tests {
    use super::*;
    use aptos_sdk::account::{AnyPrivateKey, MultiKeyAccount};
    use aptos_sdk::crypto::{Ed25519PrivateKey, Secp256k1PrivateKey};
    use aptos_sdk::transaction::{EntryFunction, TransactionBuilder, builder::sign_transaction};

    #[tokio::test]
    #[ignore]
    async fn e2e_multi_key_account_transfer() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // 2-of-3 multi-key account: two Ed25519 keys and one Secp256k1 key.
        let ed_key1 = Ed25519PrivateKey::generate();
        let secp_key = Secp256k1PrivateKey::generate();
        let ed_key2 = Ed25519PrivateKey::generate();

        let keys = vec![
            AnyPrivateKey::ed25519(ed_key1),
            AnyPrivateKey::secp256k1(secp_key),
            AnyPrivateKey::ed25519(ed_key2),
        ];
        let multi_key_account = MultiKeyAccount::new(keys, 2).unwrap();

        aptos
            .fund_account(multi_key_account.address(), 500_000_000)
            .await
            .expect("failed to fund multi-key account");

        wait_for_finality().await;

        let balance_before = aptos
            .get_balance(multi_key_account.address())
            .await
            .expect("failed to get multi-key balance");
        assert!(
            balance_before >= 500_000_000,
            "multi-key account should be funded to at least 500M octas"
        );

        let recipient = aptos_sdk::account::Ed25519Account::generate();
        let transfer_amount: u64 = 1_000_000;
        let payload = EntryFunction::apt_transfer(recipient.address(), transfer_amount).unwrap();

        let seq = aptos
            .get_sequence_number(multi_key_account.address())
            .await
            .expect("failed to get seq");
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        let raw_txn = TransactionBuilder::new()
            .sender(multi_key_account.address())
            .sequence_number(seq)
            .payload(payload.into())
            .chain_id(chain_id)
            .max_gas_amount(2_000_000)
            .gas_unit_price(100)
            .build()
            .expect("failed to build");

        let signed =
            sign_transaction(&raw_txn, &multi_key_account).expect("failed to sign with multi-key");

        let result = aptos
            .submit_and_wait(&signed, None)
            .await
            .expect("multi-key transaction must be accepted");

        let success = result
            .data
            .get("success")
            .and_then(serde_json::Value::as_bool);
        assert_eq!(
            success,
            Some(true),
            "multi-key transaction must succeed: {:?}",
            result.data
        );

        wait_for_finality().await;

        let recipient_balance = aptos
            .get_balance(recipient.address())
            .await
            .expect("failed to get recipient balance");
        assert_eq!(
            recipient_balance, transfer_amount,
            "recipient should have received exactly the transferred amount"
        );
    }
}

// =============================================================================
// Resource/State Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod state_tests {
    use super::*;

    #[tokio::test]
    #[ignore]
    async fn e2e_get_account_resource_after_first_txn() {
        use aptos_sdk::account::Ed25519Account;

        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Under AIP-42 (implicit accounts) an address that has only been
        // *funded* via the faucet does not yet have a `0x1::account::Account`
        // resource on chain -- the resource is materialised the first time
        // *that account itself* submits a transaction. Drive at least one
        // transfer from this account so the Account resource exists, then
        // assert it parses and that the sequence_number it reports is 1.
        let sender = aptos
            .create_funded_account(500_000_000)
            .await
            .expect("failed to create account");
        let recipient = Ed25519Account::generate();
        aptos
            .transfer_apt(&sender, recipient.address(), 1_000)
            .await
            .expect("first transfer should succeed");

        wait_for_finality().await;

        let resource = aptos
            .fullnode()
            .get_account_resource(sender.address(), "0x1::account::Account")
            .await
            .expect("0x1::account::Account resource must exist after first txn");

        assert_eq!(resource.data.typ, "0x1::account::Account");
        let seq_str = resource
            .data
            .data
            .get("sequence_number")
            .and_then(|v| v.as_str())
            .expect("Account resource must have sequence_number");
        let seq: u64 = seq_str.parse().expect("sequence_number must be numeric");
        assert_eq!(
            seq, 1,
            "after exactly one transfer the on-chain sequence number must be 1"
        );
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_get_resources_for_funded_account() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let funded_amount: u64 = 100_000_000;
        let account = aptos
            .create_funded_account(funded_amount)
            .await
            .expect("failed to create account");

        wait_for_finality().await;

        // Modern Aptos APT balances live in fungible-store object resources,
        // not in `0x1::coin::CoinStore`. Use the canonical `get_balance`
        // helper and assert it matches the funded amount.
        let balance = aptos
            .get_balance(account.address())
            .await
            .expect("failed to read balance");
        assert!(
            balance >= funded_amount,
            "balance ({balance}) must be at least the funded amount ({funded_amount})"
        );

        // We do NOT assert that `get_account_resources` is non-empty. Under
        // AIP-42 a pure-faucet-funded address may have *no* directly-owned
        // resources (its balance is held in a fungible store object
        // referenced indirectly), so the call is exercised for its
        // network/serialization path only.
        let _ = aptos
            .fullnode()
            .get_account_resources(account.address())
            .await
            .expect("listing resources should not error");
    }
}

// =============================================================================
// SingleKey Account Tests (real transfer flow)
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod single_key_tests {
    use super::*;
    use aptos_sdk::account::{Ed25519Account, Ed25519SingleKeyAccount};
    use aptos_sdk::transaction::{EntryFunction, TransactionBuilder, builder::sign_transaction};

    #[tokio::test]
    #[ignore]
    async fn e2e_single_key_account_transfer() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // SingleKey accounts derive a different address than legacy Ed25519.
        let sender = Ed25519SingleKeyAccount::generate();

        aptos
            .fund_account(sender.address(), 500_000_000)
            .await
            .expect("failed to fund single-key account");
        wait_for_finality().await;

        let recipient = Ed25519Account::generate();
        let amount: u64 = 2_500_000;
        let payload = EntryFunction::apt_transfer(recipient.address(), amount).unwrap();

        let seq = aptos
            .get_sequence_number(sender.address())
            .await
            .expect("failed to get seq");
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        let raw_txn = TransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(seq)
            .payload(payload.into())
            .chain_id(chain_id)
            .max_gas_amount(2_000_000)
            .gas_unit_price(100)
            .build()
            .expect("failed to build");

        let signed = sign_transaction(&raw_txn, &sender).expect("failed to sign");
        let result = aptos
            .submit_and_wait(&signed, None)
            .await
            .expect("transaction submission failed");

        let success = result
            .data
            .get("success")
            .and_then(serde_json::Value::as_bool);
        assert_eq!(success, Some(true), "transaction must succeed");

        wait_for_finality().await;

        let recipient_balance = aptos
            .get_balance(recipient.address())
            .await
            .expect("failed to get recipient balance");
        assert_eq!(recipient_balance, amount);
    }
}

// =============================================================================
// Secp256k1 Account Tests (real transfer flow)
// =============================================================================

#[cfg(all(feature = "secp256k1", feature = "faucet"))]
mod secp256k1_tests {
    use super::*;
    use aptos_sdk::account::{Ed25519Account, Secp256k1Account};
    use aptos_sdk::transaction::{EntryFunction, TransactionBuilder, builder::sign_transaction};

    #[tokio::test]
    #[ignore]
    async fn e2e_secp256k1_account_transfer() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let sender = Secp256k1Account::generate();
        aptos
            .fund_account(sender.address(), 500_000_000)
            .await
            .expect("failed to fund secp256k1 account");
        wait_for_finality().await;

        let recipient = Ed25519Account::generate();
        let amount: u64 = 3_141_592;
        let payload = EntryFunction::apt_transfer(recipient.address(), amount).unwrap();

        let seq = aptos
            .get_sequence_number(sender.address())
            .await
            .expect("failed to get seq");
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        let raw_txn = TransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(seq)
            .payload(payload.into())
            .chain_id(chain_id)
            .max_gas_amount(2_000_000)
            .gas_unit_price(100)
            .build()
            .expect("failed to build");

        let signed = sign_transaction(&raw_txn, &sender).expect("failed to sign");
        let result = aptos
            .submit_and_wait(&signed, None)
            .await
            .expect("transaction submission failed");

        let success = result
            .data
            .get("success")
            .and_then(serde_json::Value::as_bool);
        assert_eq!(success, Some(true), "secp256k1 transfer must succeed");

        wait_for_finality().await;

        let balance = aptos
            .get_balance(recipient.address())
            .await
            .expect("failed to get recipient balance");
        assert_eq!(balance, amount);
    }
}

// =============================================================================
// WebAuthn / Passkey Account Tests (real transfer flow with synthetic
// PartialAuthenticatorAssertionResponse)
//
// On current Aptos networks the on-chain `AnySignature` variant at index 2
// is `WebAuthn { signature: PartialAuthenticatorAssertionResponse }`, not a
// bare Secp256r1Ecdsa signature. The SDK ships a `WebAuthnAccount` wrapper
// that wraps a P-256 key in the WebAuthn envelope (rpIdHash +
// authenticator_data + client_data_json + canonical low-S signature) so the
// chain accepts the resulting transaction.
//
// This test exercises that path end-to-end against devnet: fund a
// WebAuthn-derived address, submit a real APT transfer signed by the
// WebAuthn account, and verify the recipient is credited exactly the
// transferred amount.
// =============================================================================

#[cfg(all(feature = "secp256r1", feature = "faucet"))]
mod webauthn_tests {
    use super::*;
    use aptos_sdk::account::WebAuthnAccount;
    use aptos_sdk::transaction::{EntryFunction, TransactionBuilder, builder::sign_transaction};

    #[tokio::test]
    #[ignore]
    async fn e2e_webauthn_account_transfer() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let sender = WebAuthnAccount::generate();
        aptos
            .fund_account(sender.address(), 500_000_000)
            .await
            .expect("failed to fund WebAuthn account");
        wait_for_finality().await;

        #[cfg(feature = "ed25519")]
        let recipient = aptos_sdk::account::Ed25519Account::generate();
        #[cfg(not(feature = "ed25519"))]
        let recipient = WebAuthnAccount::generate();

        let amount: u64 = 2_718_281;
        let payload = EntryFunction::apt_transfer(recipient.address(), amount).unwrap();

        let seq = aptos
            .get_sequence_number(sender.address())
            .await
            .expect("failed to get seq");
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        let raw_txn = TransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(seq)
            .payload(payload.into())
            .chain_id(chain_id)
            .max_gas_amount(2_000_000)
            .gas_unit_price(100)
            .build()
            .expect("failed to build");

        let signed = sign_transaction(&raw_txn, &sender).expect("failed to sign");
        let result = aptos
            .submit_and_wait(&signed, None)
            .await
            .expect("WebAuthn transaction submission must succeed on devnet");

        let success = result
            .data
            .get("success")
            .and_then(serde_json::Value::as_bool);
        assert_eq!(
            success,
            Some(true),
            "WebAuthn transaction must execute successfully on devnet: {:?}",
            result.data
        );

        wait_for_finality().await;

        let recipient_balance = aptos
            .get_balance(recipient.address())
            .await
            .expect("failed to get recipient balance");
        assert_eq!(
            recipient_balance, amount,
            "recipient must receive exactly the transferred amount"
        );
    }
}

// =============================================================================
// MultiEd25519 Account Tests (real on-chain flow)
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod multi_ed25519_tests {
    use super::*;
    use aptos_sdk::account::{Ed25519Account, MultiEd25519Account};
    use aptos_sdk::crypto::Ed25519PrivateKey;
    use aptos_sdk::transaction::{EntryFunction, TransactionBuilder, builder::sign_transaction};

    #[tokio::test]
    #[ignore]
    async fn e2e_multi_ed25519_transfer() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let keys: Vec<_> = (0..3).map(|_| Ed25519PrivateKey::generate()).collect();
        let account = MultiEd25519Account::new(keys, 2).unwrap();

        aptos
            .fund_account(account.address(), 500_000_000)
            .await
            .expect("failed to fund multi-ed25519 account");
        wait_for_finality().await;

        let recipient = Ed25519Account::generate();
        let amount: u64 = 4_096_000;
        let payload = EntryFunction::apt_transfer(recipient.address(), amount).unwrap();

        let seq = aptos
            .get_sequence_number(account.address())
            .await
            .expect("failed to get seq");
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        let raw_txn = TransactionBuilder::new()
            .sender(account.address())
            .sequence_number(seq)
            .payload(payload.into())
            .chain_id(chain_id)
            .max_gas_amount(2_000_000)
            .gas_unit_price(100)
            .build()
            .expect("failed to build");

        let signed = sign_transaction(&raw_txn, &account).expect("failed to sign");
        let result = aptos
            .submit_and_wait(&signed, None)
            .await
            .expect("multi-ed25519 transaction submission failed");

        let success = result
            .data
            .get("success")
            .and_then(serde_json::Value::as_bool);
        assert_eq!(success, Some(true), "multi-ed25519 transfer must succeed");

        wait_for_finality().await;

        let balance = aptos
            .get_balance(recipient.address())
            .await
            .expect("failed to get recipient balance");
        assert_eq!(balance, amount);
    }
}

// =============================================================================
// Batch Transaction Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod batch_tests {
    use super::*;
    use aptos_sdk::account::Ed25519Account;
    use aptos_sdk::transaction::{InputEntryFunctionData, TransactionBatchBuilder};

    #[tokio::test]
    #[ignore]
    async fn e2e_batch_build_and_submit() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Fund well above the gas budget for 2 transactions (~400M octas).
        let sender = aptos
            .create_funded_account(1_000_000_000)
            .await
            .expect("failed to create sender");

        let recipient1 = Ed25519Account::generate();
        let recipient2 = Ed25519Account::generate();
        let amount1: u64 = 7_777_777;
        let amount2: u64 = 8_888_888;

        wait_for_finality().await;

        let seq_num = aptos
            .fullnode()
            .get_sequence_number(sender.address())
            .await
            .expect("failed to get seq num");
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        let payload1 = InputEntryFunctionData::transfer_apt(recipient1.address(), amount1)
            .expect("failed to build payload 1");
        let payload2 = InputEntryFunctionData::transfer_apt(recipient2.address(), amount2)
            .expect("failed to build payload 2");

        let batch = TransactionBatchBuilder::new()
            .sender(sender.address())
            .starting_sequence_number(seq_num)
            .chain_id(chain_id)
            .add_payload(payload1)
            .add_payload(payload2)
            .build_and_sign(&sender)
            .expect("failed to build batch");
        assert_eq!(batch.len(), 2);

        let txns = batch.transactions();
        // Sequence numbers must be strictly increasing and dense.
        assert_eq!(txns[0].raw_txn.sequence_number, seq_num);
        assert_eq!(txns[1].raw_txn.sequence_number, seq_num + 1);

        // Submit each transaction in the batch and wait for both to finalize.
        for txn in txns {
            aptos
                .submit_and_wait(txn, None)
                .await
                .expect("batch transaction must succeed");
        }

        wait_for_finality().await;

        // Recipients should have exactly the funded amounts.
        let balance1 = aptos
            .get_balance(recipient1.address())
            .await
            .expect("failed to read recipient1 balance");
        let balance2 = aptos
            .get_balance(recipient2.address())
            .await
            .expect("failed to read recipient2 balance");
        assert_eq!(balance1, amount1);
        assert_eq!(balance2, amount2);

        // Sender sequence number must have advanced by 2.
        let new_seq = aptos
            .get_sequence_number(sender.address())
            .await
            .expect("failed to read seq");
        assert_eq!(new_seq, seq_num + 2);
    }
}

// =============================================================================
// Additional Balance Tests
// =============================================================================

// =============================================================================
// Gas Estimation Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod gas_tests {
    use super::*;
    use aptos_sdk::account::Ed25519Account;
    use aptos_sdk::transaction::EntryFunction;

    #[tokio::test]
    #[ignore]
    async fn e2e_estimate_gas_for_transfer() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let sender = aptos
            .create_funded_account(500_000_000)
            .await
            .expect("failed to create sender");
        let recipient = Ed25519Account::generate();

        let payload = EntryFunction::apt_transfer(recipient.address(), 1_000)
            .expect("failed to build payload");

        let gas_used = aptos
            .estimate_gas(&sender, payload.into())
            .await
            .expect("estimate_gas must succeed");

        // Sanity bounds: a basic APT transfer is on the order of a few hundred to
        // a few thousand gas units on devnet. We bound very loosely to avoid
        // flakiness with on-chain gas schedule changes.
        assert!(gas_used > 0, "gas_used must be positive");
        assert!(
            gas_used < 1_000_000,
            "gas_used ({gas_used}) is wildly higher than expected for an APT transfer"
        );
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_estimate_gas_price() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let estimate = aptos
            .fullnode()
            .estimate_gas_price()
            .await
            .expect("estimate_gas_price must succeed");

        assert!(
            estimate.data.gas_estimate > 0,
            "gas_estimate must be positive"
        );
    }
}

// =============================================================================
// Sponsored (Fee Payer) Builder Helper Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod sponsored_builder_tests {
    use super::*;
    use aptos_sdk::account::Ed25519Account;
    use aptos_sdk::transaction::{EntryFunction, SponsoredTransactionBuilder};

    #[tokio::test]
    #[ignore]
    async fn e2e_sponsored_builder_real_transfer() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Sender has just the transfer amount; sponsor covers gas.
        let sender = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create sender");
        let sponsor = aptos
            .create_funded_account(500_000_000)
            .await
            .expect("failed to create sponsor");
        let recipient = Ed25519Account::generate();

        let sender_seq = aptos
            .get_sequence_number(sender.address())
            .await
            .expect("failed to get sender seq");
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        let amount: u64 = 12_345;
        let payload = EntryFunction::apt_transfer(recipient.address(), amount).unwrap();

        let signed = SponsoredTransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(sender_seq)
            .fee_payer(sponsor.address())
            .payload(payload.into())
            .chain_id(chain_id)
            .max_gas_amount(2_000_000)
            .gas_unit_price(100)
            .build_and_sign(&sender, &[], &sponsor)
            .expect("failed to build+sign sponsored transaction");

        let result = aptos
            .submit_and_wait(&signed, None)
            .await
            .expect("sponsored transaction submission failed");

        let success = result
            .data
            .get("success")
            .and_then(serde_json::Value::as_bool);
        assert_eq!(success, Some(true), "sponsored transaction must succeed");

        wait_for_finality().await;

        let recipient_balance = aptos
            .get_balance(recipient.address())
            .await
            .expect("failed to get recipient balance");
        assert_eq!(recipient_balance, amount);
    }
}

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod balance_tests {
    use super::*;
    use aptos_sdk::account::Ed25519Account;

    #[tokio::test]
    #[ignore]
    async fn e2e_balance_multiple_accounts() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Create multiple accounts
        let accounts: Vec<_> = (0..3).map(|_| Ed25519Account::generate()).collect();

        // Fund all accounts
        for account in &accounts {
            aptos
                .fund_account(account.address(), 50_000_000)
                .await
                .expect("failed to fund account");
        }

        wait_for_finality().await;

        // Check all balances
        for (i, account) in accounts.iter().enumerate() {
            let balance = aptos
                .get_balance(account.address())
                .await
                .expect("failed to get balance");
            assert!(
                balance >= 50_000_000,
                "Account {i} should have at least 50M octas"
            );
            println!("Account {i}: {balance} octas");
        }
    }
}