1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
//! Fullnode REST API client.
use crate::api::response::{
AccountData, AptosResponse, GasEstimation, LedgerInfo, MoveModule, PendingTransaction, Resource,
};
use crate::config::AptosConfig;
use crate::error::{AptosError, AptosResult};
use crate::retry::{RetryConfig, RetryExecutor};
use crate::transaction::simulation::SimulateQueryOptions;
use crate::transaction::types::SignedTransaction;
use crate::types::{AccountAddress, HashValue};
use reqwest::Client;
use reqwest::header::{ACCEPT, CONTENT_TYPE};
use std::sync::Arc;
use std::time::Duration;
use url::Url;
const BCS_CONTENT_TYPE: &str = "application/x.aptos.signed_transaction+bcs";
const BCS_VIEW_CONTENT_TYPE: &str = "application/x-bcs";
const JSON_CONTENT_TYPE: &str = "application/json";
/// Default timeout for waiting for a transaction to be committed.
const DEFAULT_TRANSACTION_WAIT_TIMEOUT_SECS: u64 = 30;
/// Maximum size for error response bodies (8 KB).
///
/// # Security
///
/// This prevents memory exhaustion from malicious servers sending extremely
/// large error response bodies.
const MAX_ERROR_BODY_SIZE: usize = 8 * 1024;
/// Client for the Aptos fullnode REST API.
///
/// The client supports automatic retry with exponential backoff for transient
/// failures. Configure retry behavior via [`AptosConfig::with_retry`].
///
/// # Example
///
/// ```rust,no_run
/// use aptos_sdk::api::FullnodeClient;
/// use aptos_sdk::config::AptosConfig;
/// use aptos_sdk::retry::RetryConfig;
///
/// #[tokio::main]
/// async fn main() -> anyhow::Result<()> {
/// // Default retry configuration
/// let client = FullnodeClient::new(AptosConfig::testnet())?;
///
/// // Aggressive retry for unstable networks
/// let client = FullnodeClient::new(
/// AptosConfig::testnet().with_retry(RetryConfig::aggressive())
/// )?;
///
/// // Disable retry for debugging
/// let client = FullnodeClient::new(
/// AptosConfig::testnet().without_retry()
/// )?;
///
/// let ledger_info = client.get_ledger_info().await?;
/// println!("Ledger version: {:?}", ledger_info.data.version());
/// Ok(())
/// }
/// ```
#[derive(Debug, Clone)]
pub struct FullnodeClient {
config: AptosConfig,
client: Client,
retry_config: Arc<RetryConfig>,
}
impl FullnodeClient {
/// Creates a new fullnode client.
///
/// # TLS Security
///
/// This client uses `reqwest` with its default TLS configuration, which:
/// - Validates server certificates against the system's certificate store
/// - Requires valid TLS certificates for HTTPS connections
/// - Uses secure TLS versions (TLS 1.2+)
///
/// All Aptos network endpoints (mainnet, testnet, devnet) use HTTPS with
/// valid certificates. The local configuration uses HTTP for development.
///
/// For custom deployments requiring custom CA certificates, use the
/// `REQUESTS_CA_BUNDLE` or `SSL_CERT_FILE` environment variables, or
/// configure a custom `reqwest::Client` and use `from_client()`.
///
/// # Errors
///
/// Returns an error if the HTTP client fails to build (e.g., invalid TLS configuration).
pub fn new(config: AptosConfig) -> AptosResult<Self> {
let pool = config.pool_config();
// SECURITY: TLS certificate validation is enabled by default via reqwest.
// The client will reject connections to servers with invalid certificates.
// All production Aptos endpoints use HTTPS with valid certificates.
let mut builder = Client::builder()
.timeout(config.timeout)
.pool_max_idle_per_host(pool.max_idle_per_host.unwrap_or(usize::MAX))
.pool_idle_timeout(pool.idle_timeout)
.tcp_nodelay(pool.tcp_nodelay);
if let Some(keepalive) = pool.tcp_keepalive {
builder = builder.tcp_keepalive(keepalive);
}
let client = builder.build().map_err(AptosError::Http)?;
let retry_config = Arc::new(config.retry_config().clone());
Ok(Self {
config,
client,
retry_config,
})
}
/// Returns the base URL for the fullnode.
pub fn base_url(&self) -> &Url {
self.config.fullnode_url()
}
/// Returns the configuration backing this client.
pub fn config(&self) -> &AptosConfig {
&self.config
}
/// Calls a view function whose arguments are supplied as **BCS-encoded
/// bytes**, returning the JSON-decoded result values.
///
/// This differs from [`view`](Self::view) (which takes JSON arguments) and
/// from [`view_bcs`](Self::view_bcs) (which hex-encodes BCS bytes into the
/// JSON body, and therefore only round-trips correctly for argument types
/// whose hex happens to coincide with their JSON form, e.g. addresses).
///
/// Here the entire request is serialized as an on-wire `ViewRequest`
/// (identical BCS layout to [`crate::transaction::EntryFunction`]) and
/// posted with the `application/x.aptos.view_function+bcs` content type,
/// exactly like the TypeScript SDK's `view`. This is the only reliable way
/// to pass typed arguments such as `Option<String>`, `vector<u8>`, or
/// `String` to a view function. The response is requested as JSON and
/// returned as an array of [`serde_json::Value`], one entry per declared
/// return value.
///
/// # Arguments
///
/// * `function` - Fully qualified function id (e.g. `0x1::coin::balance`).
/// * `type_args` - Type arguments for generic functions.
/// * `args` - Each argument already BCS-encoded (e.g. via
/// `aptos_bcs::to_bytes`).
///
/// # Errors
///
/// Returns an error if the function id is malformed, the request cannot be
/// BCS-serialized, the HTTP request fails, or the API returns an error
/// status code.
pub async fn view_bcs_args(
&self,
function: &str,
type_args: Vec<crate::types::TypeTag>,
args: Vec<Vec<u8>>,
) -> AptosResult<AptosResponse<Vec<serde_json::Value>>> {
// `Content-Type` for a request whose body is a BCS-serialized
// `ViewRequest` (as opposed to `application/x-bcs`, which is an `Accept`
// value asking the node to BCS-encode the *response*).
const BCS_VIEW_REQUEST_CONTENT_TYPE: &str = "application/x.aptos.view_function+bcs";
// A `ViewRequest`/`ViewFunction` is BCS-identical to an `EntryFunction`:
// `module: ModuleId, function: Identifier, ty_args: Vec<TypeTag>,
// args: Vec<Vec<u8>>`. Reusing `EntryFunction` keeps the wire format in
// one place and gives us the function-id parsing for free.
let view_fn =
crate::transaction::EntryFunction::from_function_id(function, type_args, args)?;
let body = aptos_bcs::to_bytes(&view_fn).map_err(AptosError::bcs)?;
let url = self.build_url("view");
let client = self.client.clone();
let retry_config = self.retry_config.clone();
let max_response_size = self.config.pool_config().max_response_size;
let executor = RetryExecutor::from_shared(retry_config);
executor
.execute(|| {
let client = client.clone();
let url = url.clone();
let body = body.clone();
async move {
let response = client
.post(url)
.header(CONTENT_TYPE, BCS_VIEW_REQUEST_CONTENT_TYPE)
.header(ACCEPT, JSON_CONTENT_TYPE)
.body(body)
.send()
.await?;
Self::handle_response_static(response, max_response_size).await
}
})
.await
}
/// Returns the retry configuration.
pub fn retry_config(&self) -> &RetryConfig {
&self.retry_config
}
// === Ledger Info ===
/// Gets the current ledger information.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// or the response cannot be parsed as JSON.
pub async fn get_ledger_info(&self) -> AptosResult<AptosResponse<LedgerInfo>> {
let url = self.build_url("");
self.get_json(url).await
}
// === Account ===
/// Gets account information.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// the response cannot be parsed as JSON, or the account is not found (404).
pub async fn get_account(
&self,
address: AccountAddress,
) -> AptosResult<AptosResponse<AccountData>> {
let url = self.build_url(&format!("accounts/{address}"));
self.get_json(url).await
}
/// Gets the sequence number for an account.
///
/// # Errors
///
/// Returns an error if fetching the account fails, the account is not found (404),
/// or the sequence number cannot be parsed from the account data.
pub async fn get_sequence_number(&self, address: AccountAddress) -> AptosResult<u64> {
let account = self.get_account(address).await?;
account
.data
.sequence_number()
.map_err(|e| AptosError::Internal(format!("failed to parse sequence number: {e}")))
}
/// Gets all resources for an account in a single page (uses the
/// fullnode's default page size; large accounts may be truncated).
///
/// For paginated access on accounts that hold many resources, use
/// [`get_account_resources_paginated`](Self::get_account_resources_paginated).
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// or the response cannot be parsed as JSON.
pub async fn get_account_resources(
&self,
address: AccountAddress,
) -> AptosResult<AptosResponse<Vec<Resource>>> {
self.get_account_resources_paginated(address, None, None)
.await
}
/// Gets resources for an account with explicit pagination cursors.
///
/// * `start` -- opaque cursor token returned by the previous page in
/// the `x-aptos-cursor` header (and surfaced as
/// [`AptosResponse::cursor`](super::response::AptosResponse#field.cursor)).
/// The type is `Option<&str>` rather than `Option<u64>` so opaque
/// non-numeric cursors round-trip losslessly. Pass `None` for the
/// first page; for subsequent pages forward
/// `previous_response.cursor.as_deref()`.
/// * `limit` -- maximum number of resources to return on this page.
/// The fullnode caps this server-side; callers should not assume
/// their requested limit is honored verbatim.
///
/// Matches the TypeScript SDK's `getAccountResources({ start, limit })`.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// or the response cannot be parsed as JSON.
pub async fn get_account_resources_paginated(
&self,
address: AccountAddress,
start: Option<&str>,
limit: Option<u16>,
) -> AptosResult<AptosResponse<Vec<Resource>>> {
let mut url = self.build_url(&format!("accounts/{address}/resources"));
append_start_limit(&mut url, start, limit);
self.get_json(url).await
}
/// Gets a specific resource for an account.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// the response cannot be parsed as JSON, or the resource is not found (404).
pub async fn get_account_resource(
&self,
address: AccountAddress,
resource_type: &str,
) -> AptosResult<AptosResponse<Resource>> {
let url = self.build_url(&format!(
"accounts/{}/resource/{}",
address,
urlencoding::encode(resource_type)
));
self.get_json(url).await
}
/// Gets all modules for an account in a single page (uses the
/// fullnode's default page size; accounts that publish many modules
/// may be truncated).
///
/// For paginated access, use
/// [`get_account_modules_paginated`](Self::get_account_modules_paginated).
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// or the response cannot be parsed as JSON.
pub async fn get_account_modules(
&self,
address: AccountAddress,
) -> AptosResult<AptosResponse<Vec<MoveModule>>> {
self.get_account_modules_paginated(address, None, None)
.await
}
/// Gets modules for an account with explicit pagination cursors.
///
/// See [`get_account_resources_paginated`](Self::get_account_resources_paginated)
/// for `start` / `limit` semantics; they are interpreted the same way
/// by the fullnode.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// or the response cannot be parsed as JSON.
pub async fn get_account_modules_paginated(
&self,
address: AccountAddress,
start: Option<&str>,
limit: Option<u16>,
) -> AptosResult<AptosResponse<Vec<MoveModule>>> {
let mut url = self.build_url(&format!("accounts/{address}/modules"));
append_start_limit(&mut url, start, limit);
self.get_json(url).await
}
/// Gets a specific module for an account.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// the response cannot be parsed as JSON, or the module is not found (404).
pub async fn get_account_module(
&self,
address: AccountAddress,
module_name: &str,
) -> AptosResult<AptosResponse<MoveModule>> {
let url = self.build_url(&format!("accounts/{address}/module/{module_name}"));
self.get_json(url).await
}
// === Balance ===
/// Gets the APT balance for an account in octas.
///
/// # Errors
///
/// Returns an error if the view function call fails, the response cannot be parsed,
/// or the balance value cannot be converted to u64.
pub async fn get_account_balance(&self, address: AccountAddress) -> AptosResult<u64> {
// Use the coin::balance view function which works with both legacy CoinStore
// and the newer Fungible Asset standard
let result = self
.view(
"0x1::coin::balance",
vec!["0x1::aptos_coin::AptosCoin".to_string()],
vec![serde_json::json!(address.to_string())],
)
.await?;
// The view function returns an array with a single string value
let balance_str = result
.data
.first()
.and_then(|v| v.as_str())
.ok_or_else(|| AptosError::Internal("failed to parse balance response".into()))?;
balance_str
.parse()
.map_err(|_| AptosError::Internal("failed to parse balance as u64".into()))
}
// === Transactions ===
/// Submits a signed transaction.
///
/// Note: Transaction submission is automatically retried for transient errors.
/// Duplicate transaction submissions (same hash) are safe and idempotent.
///
/// # Errors
///
/// Returns an error if the transaction cannot be serialized to BCS, the HTTP request fails,
/// the API returns an error status code, or the response cannot be parsed as JSON.
pub async fn submit_transaction(
&self,
signed_txn: &SignedTransaction,
) -> AptosResult<AptosResponse<PendingTransaction>> {
let url = self.build_url("transactions");
let bcs_bytes = signed_txn.to_bcs()?;
let client = self.client.clone();
let retry_config = self.retry_config.clone();
let max_response_size = self.config.pool_config().max_response_size;
let executor = RetryExecutor::from_shared(retry_config);
executor
.execute(|| {
let client = client.clone();
let url = url.clone();
let bcs_bytes = bcs_bytes.clone();
async move {
let response = client
.post(url)
.header(CONTENT_TYPE, BCS_CONTENT_TYPE)
.header(ACCEPT, JSON_CONTENT_TYPE)
.body(bcs_bytes)
.send()
.await?;
Self::handle_response_static(response, max_response_size).await
}
})
.await
}
/// Submits a transaction and waits for it to be committed.
///
/// # Errors
///
/// Returns an error if transaction submission fails, the transaction times out waiting
/// for commitment, the transaction execution fails, or any HTTP/API errors occur.
pub async fn submit_and_wait(
&self,
signed_txn: &SignedTransaction,
timeout: Option<Duration>,
) -> AptosResult<AptosResponse<serde_json::Value>> {
let pending = self.submit_transaction(signed_txn).await?;
self.wait_for_transaction(&pending.data.hash, timeout).await
}
/// Gets a transaction by hash.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// the response cannot be parsed as JSON, or the transaction is not found (404).
pub async fn get_transaction_by_hash(
&self,
hash: &HashValue,
) -> AptosResult<AptosResponse<serde_json::Value>> {
let url = self.build_url(&format!("transactions/by_hash/{hash}"));
self.get_json(url).await
}
/// Gets a committed transaction by its ledger version.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// the response cannot be parsed as JSON, or the transaction is not found (404).
pub async fn get_transaction_by_version(
&self,
version: u64,
) -> AptosResult<AptosResponse<serde_json::Value>> {
let url = self.build_url(&format!("transactions/by_version/{version}"));
self.get_json(url).await
}
/// Lists committed transactions, most-recent first.
///
/// `start` is the ledger version to begin at (defaults to the most recent
/// transactions when `None`); `limit` bounds the page size (the fullnode
/// caps this regardless of the requested value).
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// or the response cannot be parsed as JSON.
pub async fn get_transactions(
&self,
start: Option<u64>,
limit: Option<u16>,
) -> AptosResult<AptosResponse<Vec<serde_json::Value>>> {
let mut url = self.build_url("transactions");
{
let mut query = url.query_pairs_mut();
if let Some(start) = start {
query.append_pair("start", &start.to_string());
}
if let Some(limit) = limit {
query.append_pair("limit", &limit.to_string());
}
}
self.get_json(url).await
}
/// Lists transactions sent by a specific account, ordered by the account's
/// sequence number.
///
/// `start` is the sequence number to begin at (defaults to `0` when `None`);
/// `limit` bounds the page size.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// or the response cannot be parsed as JSON.
pub async fn get_account_transactions(
&self,
address: AccountAddress,
start: Option<u64>,
limit: Option<u16>,
) -> AptosResult<AptosResponse<Vec<serde_json::Value>>> {
let mut url = self.build_url(&format!("accounts/{address}/transactions"));
{
let mut query = url.query_pairs_mut();
if let Some(start) = start {
query.append_pair("start", &start.to_string());
}
if let Some(limit) = limit {
query.append_pair("limit", &limit.to_string());
}
}
self.get_json(url).await
}
/// Waits for a transaction to be committed.
///
/// Uses exponential backoff for polling, starting at 200ms and doubling up to 2s.
///
/// # Errors
///
/// Returns an error if the transaction times out waiting for commitment, the transaction
/// execution fails (`vm_status` indicates failure), or HTTP/API errors occur while polling.
pub async fn wait_for_transaction(
&self,
hash: &HashValue,
timeout: Option<Duration>,
) -> AptosResult<AptosResponse<serde_json::Value>> {
let timeout = timeout.unwrap_or(Duration::from_secs(DEFAULT_TRANSACTION_WAIT_TIMEOUT_SECS));
let start = std::time::Instant::now();
// Exponential backoff: start at 200ms, double each time, max 2s
let initial_interval = Duration::from_millis(200);
let max_interval = Duration::from_secs(2);
let mut current_interval = initial_interval;
loop {
match self.get_transaction_by_hash(hash).await {
Ok(response) => {
// Check if transaction is committed (has version)
if response.data.get("version").is_some() {
// Check success
let success = response
.data
.get("success")
.and_then(serde_json::Value::as_bool);
if success == Some(false) {
let vm_status = response
.data
.get("vm_status")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string();
return Err(AptosError::ExecutionFailed { vm_status });
}
return Ok(response);
}
}
Err(AptosError::Api {
status_code: 404, ..
}) => {
// Transaction not found yet, continue waiting
}
Err(e) => return Err(e),
}
if start.elapsed() >= timeout {
return Err(AptosError::TransactionTimeout {
hash: hash.to_string(),
timeout_secs: timeout.as_secs(),
});
}
tokio::time::sleep(current_interval).await;
// Exponential backoff with cap
current_interval = std::cmp::min(current_interval * 2, max_interval);
}
}
/// Simulates a transaction.
///
/// Delegates to [`simulate_transaction_with_options`](Self::simulate_transaction_with_options) with `None` for options.
///
/// The request body is derived from `signed_txn` after rewriting authenticators for the
/// simulate endpoint (see [`SignedTransaction::for_simulate_endpoint`]).
///
/// # Errors
///
/// Returns an error if the transaction cannot be serialized to BCS, the HTTP request fails,
/// the API returns an error status code, or the response cannot be parsed as JSON.
pub async fn simulate_transaction(
&self,
signed_txn: &SignedTransaction,
) -> AptosResult<AptosResponse<Vec<serde_json::Value>>> {
self.simulate_transaction_with_options(signed_txn, None as Option<SimulateQueryOptions>)
.await
}
/// Simulates a transaction with optional query parameters.
///
/// Pass [`SimulateQueryOptions`] to request gas estimation behavior
/// (e.g. `estimate_gas_unit_price`, `estimate_max_gas_amount`) as query
/// parameters to the `/transactions/simulate` endpoint.
///
/// Authenticators on `signed_txn` are rewritten client-side (via
/// [`SignedTransaction::for_simulate_endpoint`]) before BCS serialization so the
/// fullnode never receives a cryptographically valid signature (which it rejects with
/// HTTP 400).
///
/// # Errors
///
/// Returns an error if the transaction cannot be serialized to BCS, the HTTP request fails,
/// the API returns an error status code, or the response cannot be parsed as JSON.
pub async fn simulate_transaction_with_options(
&self,
signed_txn: &SignedTransaction,
options: impl Into<Option<SimulateQueryOptions>>,
) -> AptosResult<AptosResponse<Vec<serde_json::Value>>> {
let mut url = self.build_url("transactions/simulate");
if let Some(opts) = options.into() {
let mut pairs = url.query_pairs_mut();
if opts.estimate_gas_unit_price {
pairs.append_pair("estimate_gas_unit_price", "true");
}
if opts.estimate_max_gas_amount {
pairs.append_pair("estimate_max_gas_amount", "true");
}
if opts.estimate_prioritized_gas_unit_price {
pairs.append_pair("estimate_prioritized_gas_unit_price", "true");
}
}
let bcs_bytes = signed_txn.for_simulate_endpoint().to_bcs()?;
let client = self.client.clone();
let retry_config = self.retry_config.clone();
let max_response_size = self.config.pool_config().max_response_size;
let executor = RetryExecutor::from_shared(retry_config);
executor
.execute(|| {
let client = client.clone();
let url = url.clone();
let bcs_bytes = bcs_bytes.clone();
async move {
let response = client
.post(url)
.header(CONTENT_TYPE, BCS_CONTENT_TYPE)
.header(ACCEPT, JSON_CONTENT_TYPE)
.body(bcs_bytes)
.send()
.await?;
Self::handle_response_static(response, max_response_size).await
}
})
.await
}
// === Gas ===
/// Gets the current gas estimation.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// or the response cannot be parsed as JSON.
pub async fn estimate_gas_price(&self) -> AptosResult<AptosResponse<GasEstimation>> {
let url = self.build_url("estimate_gas_price");
self.get_json(url).await
}
// === View Functions ===
/// Calls a view function.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// or the response cannot be parsed as JSON.
pub async fn view(
&self,
function: &str,
type_args: Vec<String>,
args: Vec<serde_json::Value>,
) -> AptosResult<AptosResponse<Vec<serde_json::Value>>> {
let url = self.build_url("view");
let body = serde_json::json!({
"function": function,
"type_arguments": type_args,
"arguments": args,
});
let client = self.client.clone();
let retry_config = self.retry_config.clone();
let max_response_size = self.config.pool_config().max_response_size;
let executor = RetryExecutor::from_shared(retry_config);
executor
.execute(|| {
let client = client.clone();
let url = url.clone();
let body = body.clone();
async move {
let response = client
.post(url)
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
.header(ACCEPT, JSON_CONTENT_TYPE)
.json(&body)
.send()
.await?;
Self::handle_response_static(response, max_response_size).await
}
})
.await
}
/// Calls a view function using BCS encoding for both inputs and outputs.
///
/// This method provides lossless serialization by using BCS (Binary Canonical Serialization)
/// instead of JSON, which is important for large integers (u128, u256) and other types
/// where JSON can lose precision.
///
/// # Arguments
///
/// * `function` - The fully qualified function name (e.g., `0x1::coin::balance`)
/// * `type_args` - Type arguments as strings (e.g., `0x1::aptos_coin::AptosCoin`)
/// * `args` - Pre-serialized BCS arguments as byte vectors
///
/// # Returns
///
/// Returns the raw BCS-encoded response bytes, which can be deserialized
/// into the expected return type using `aptos_bcs::from_bytes`.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// or the BCS serialization fails.
pub async fn view_bcs(
&self,
function: &str,
type_args: Vec<String>,
args: Vec<Vec<u8>>,
) -> AptosResult<AptosResponse<Vec<u8>>> {
let url = self.build_url("view");
// Convert BCS args to hex strings for the JSON request body.
// The Aptos API accepts hex-encoded BCS bytes in the arguments array.
let hex_args: Vec<serde_json::Value> = args
.iter()
.map(|bytes| serde_json::json!(const_hex::encode_prefixed(bytes)))
.collect();
let body = serde_json::json!({
"function": function,
"type_arguments": type_args,
"arguments": hex_args,
});
let client = self.client.clone();
let retry_config = self.retry_config.clone();
let max_response_size = self.config.pool_config().max_response_size;
let executor = RetryExecutor::from_shared(retry_config);
executor
.execute(|| {
let client = client.clone();
let url = url.clone();
let body = body.clone();
async move {
let response = client
.post(url)
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
.header(ACCEPT, BCS_VIEW_CONTENT_TYPE)
.json(&body)
.send()
.await?;
// Check for errors before reading body
let status = response.status();
if !status.is_success() {
// SECURITY: Bound error body reads to prevent OOM from
// malicious servers sending huge error responses.
let error_bytes =
crate::config::read_response_bounded(response, MAX_ERROR_BODY_SIZE)
.await
.ok();
let error_text = error_bytes
.and_then(|b| String::from_utf8(b).ok())
.unwrap_or_default();
return Err(AptosError::Api {
status_code: status.as_u16(),
message: Self::truncate_error_body(error_text),
error_code: None,
vm_error_code: None,
});
}
// SECURITY: Stream body with size limit to prevent OOM
// from malicious responses (including chunked encoding).
let bytes =
crate::config::read_response_bounded(response, max_response_size).await?;
Ok(AptosResponse::new(bytes))
}
})
.await
}
// === Tables ===
/// Reads an item from a Move table by its key.
///
/// Table state is not addressable as a normal account resource, so the
/// fullnode exposes a dedicated `POST /tables/{handle}/item` endpoint that
/// takes the table's key/value Move types and the (JSON-encoded) key, and
/// returns the stored value. This mirrors the TypeScript SDK's
/// `getTableItem`.
///
/// # Arguments
///
/// * `handle` - The table handle (the address-like `0x…` identifier of the
/// `Table` on chain, e.g. read from a resource field).
/// * `key_type` - The Move type of the key (e.g. `address`, `u64`,
/// `0x1::string::String`).
/// * `value_type` - The Move type of the stored value.
/// * `key` - The key to look up, encoded as the fullnode expects it in JSON
/// (e.g. `serde_json::json!("0x1")` for an `address` key).
///
/// # Errors
///
/// Returns an error if the request cannot be serialized, the HTTP request
/// fails, the API returns an error status code (including 404 when the key
/// is absent from the table), or the response cannot be parsed as JSON.
pub async fn get_table_item(
&self,
handle: &str,
key_type: &str,
value_type: &str,
key: serde_json::Value,
) -> AptosResult<AptosResponse<serde_json::Value>> {
let url = self.build_url(&format!("tables/{}/item", urlencoding::encode(handle)));
let body = serde_json::json!({
"key_type": key_type,
"value_type": value_type,
"key": key,
});
self.post_json(url, &body).await
}
// === Events ===
/// Gets events emitted from an account by their creation number.
///
/// Each `EventHandle` an account owns has a unique creation number; this
/// endpoint returns the events for one such handle without needing to know
/// the handle's Move struct type (unlike
/// [`get_events_by_event_handle`](Self::get_events_by_event_handle)). Mirrors
/// the TypeScript SDK's `getAccountEventsByCreationNumber`.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// or the response cannot be parsed as JSON.
pub async fn get_events_by_creation_number(
&self,
address: AccountAddress,
creation_number: u64,
start: Option<u64>,
limit: Option<u64>,
) -> AptosResult<AptosResponse<Vec<serde_json::Value>>> {
let mut url = self.build_url(&format!("accounts/{address}/events/{creation_number}"));
{
let mut query = url.query_pairs_mut();
if let Some(start) = start {
query.append_pair("start", &start.to_string());
}
if let Some(limit) = limit {
query.append_pair("limit", &limit.to_string());
}
}
self.get_json(url).await
}
/// Gets events by event handle.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// or the response cannot be parsed as JSON.
pub async fn get_events_by_event_handle(
&self,
address: AccountAddress,
event_handle_struct: &str,
field_name: &str,
start: Option<u64>,
limit: Option<u64>,
) -> AptosResult<AptosResponse<Vec<serde_json::Value>>> {
let mut url = self.build_url(&format!(
"accounts/{}/events/{}/{}",
address,
urlencoding::encode(event_handle_struct),
field_name
));
{
let mut query = url.query_pairs_mut();
if let Some(start) = start {
query.append_pair("start", &start.to_string());
}
if let Some(limit) = limit {
query.append_pair("limit", &limit.to_string());
}
}
self.get_json(url).await
}
// === Blocks ===
/// Gets block by height.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// the response cannot be parsed as JSON, or the block is not found (404).
pub async fn get_block_by_height(
&self,
height: u64,
with_transactions: bool,
) -> AptosResult<AptosResponse<serde_json::Value>> {
let mut url = self.build_url(&format!("blocks/by_height/{height}"));
url.query_pairs_mut()
.append_pair("with_transactions", &with_transactions.to_string());
self.get_json(url).await
}
/// Gets block by version.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error status code,
/// the response cannot be parsed as JSON, or the block is not found (404).
pub async fn get_block_by_version(
&self,
version: u64,
with_transactions: bool,
) -> AptosResult<AptosResponse<serde_json::Value>> {
let mut url = self.build_url(&format!("blocks/by_version/{version}"));
url.query_pairs_mut()
.append_pair("with_transactions", &with_transactions.to_string());
self.get_json(url).await
}
// === Helper Methods ===
fn build_url(&self, path: &str) -> Url {
let mut url = self.config.fullnode_url().clone();
if !path.is_empty() {
// Avoid format! allocations by building the path string manually
let base_path = url.path();
let needs_slash = !base_path.ends_with('/');
let new_len = base_path.len() + path.len() + usize::from(needs_slash);
let mut new_path = String::with_capacity(new_len);
new_path.push_str(base_path);
if needs_slash {
new_path.push('/');
}
new_path.push_str(path);
url.set_path(&new_path);
}
url
}
async fn get_json<T: for<'de> serde::Deserialize<'de>>(
&self,
url: Url,
) -> AptosResult<AptosResponse<T>> {
let client = self.client.clone();
let url_clone = url.clone();
let retry_config = self.retry_config.clone();
let max_response_size = self.config.pool_config().max_response_size;
let executor = RetryExecutor::from_shared(retry_config);
executor
.execute(|| {
let client = client.clone();
let url = url_clone.clone();
async move {
let response = client
.get(url)
.header(ACCEPT, JSON_CONTENT_TYPE)
.send()
.await?;
Self::handle_response_static(response, max_response_size).await
}
})
.await
}
/// Posts a JSON body and deserializes the JSON response.
///
/// Shares the retry/backoff and bounded-response handling with
/// [`get_json`](Self::get_json); used by read endpoints that require a
/// request body (e.g. table-item lookups). Retries are safe because these
/// endpoints are read-only and idempotent.
async fn post_json<B: serde::Serialize, T: for<'de> serde::Deserialize<'de>>(
&self,
url: Url,
body: &B,
) -> AptosResult<AptosResponse<T>> {
let body = serde_json::to_vec(body)?;
let client = self.client.clone();
let retry_config = self.retry_config.clone();
let max_response_size = self.config.pool_config().max_response_size;
let executor = RetryExecutor::from_shared(retry_config);
executor
.execute(|| {
let client = client.clone();
let url = url.clone();
let body = body.clone();
async move {
let response = client
.post(url)
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
.header(ACCEPT, JSON_CONTENT_TYPE)
.body(body)
.send()
.await?;
Self::handle_response_static(response, max_response_size).await
}
})
.await
}
/// Truncates a string to the maximum error body size.
///
/// # Security
///
/// Prevents storing extremely large error messages from malicious servers.
fn truncate_error_body(body: String) -> String {
if body.len() > MAX_ERROR_BODY_SIZE {
// Find the last valid UTF-8 char boundary at or before the limit
let mut end = MAX_ERROR_BODY_SIZE;
while end > 0 && !body.is_char_boundary(end) {
end -= 1;
}
format!(
"{}... [truncated, total: {} bytes]",
&body[..end],
body.len()
)
} else {
body
}
}
/// Handles an HTTP response without retry (for internal use).
///
/// # Security
///
/// This method enforces `max_response_size` on the actual response body,
/// not just the Content-Length header, to prevent memory exhaustion even
/// when the server uses chunked transfer encoding.
async fn handle_response_static<T: for<'de> serde::Deserialize<'de>>(
response: reqwest::Response,
max_response_size: usize,
) -> AptosResult<AptosResponse<T>> {
let status = response.status();
// Extract headers before consuming response body
let ledger_version = response
.headers()
.get("x-aptos-ledger-version")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse().ok());
let ledger_timestamp = response
.headers()
.get("x-aptos-ledger-timestamp")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse().ok());
let epoch = response
.headers()
.get("x-aptos-epoch")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse().ok());
let block_height = response
.headers()
.get("x-aptos-block-height")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse().ok());
let oldest_ledger_version = response
.headers()
.get("x-aptos-oldest-ledger-version")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse().ok());
let cursor = response
.headers()
.get("x-aptos-cursor")
.and_then(|v| v.to_str().ok())
.map(ToString::to_string);
// Extract Retry-After header for rate limiting (before consuming body)
let retry_after_secs = response
.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse().ok());
if status.is_success() {
// SECURITY: Stream body with size limit to prevent OOM
// from malicious responses (including chunked encoding).
let bytes = crate::config::read_response_bounded(response, max_response_size).await?;
let data: T = serde_json::from_slice(&bytes)?;
Ok(AptosResponse {
data,
ledger_version,
ledger_timestamp,
epoch,
block_height,
oldest_ledger_version,
cursor,
})
} else if status.as_u16() == 429 {
// SECURITY: Return specific RateLimited error with Retry-After info
// This allows callers to respect the server's rate limiting
Err(AptosError::RateLimited { retry_after_secs })
} else {
// SECURITY: Bound error body reads to prevent OOM from malicious
// servers sending huge error responses (including chunked encoding).
let error_bytes = crate::config::read_response_bounded(response, MAX_ERROR_BODY_SIZE)
.await
.ok();
let error_text = error_bytes
.and_then(|b| String::from_utf8(b).ok())
.unwrap_or_default();
let error_text = Self::truncate_error_body(error_text);
let body: serde_json::Value = serde_json::from_str(&error_text).unwrap_or_default();
let message = body
.get("message")
.and_then(|v| v.as_str())
.unwrap_or("Unknown error")
.to_string();
let error_code = body
.get("error_code")
.and_then(|v| v.as_str())
.map(ToString::to_string);
let vm_error_code = body
.get("vm_error_code")
.and_then(serde_json::Value::as_u64);
Err(AptosError::api_with_details(
status.as_u16(),
message,
error_code,
vm_error_code,
))
}
}
/// Legacy `handle_response` - delegates to static version.
#[allow(dead_code)]
async fn handle_response<T: for<'de> serde::Deserialize<'de>>(
&self,
response: reqwest::Response,
) -> AptosResult<AptosResponse<T>> {
let max_response_size = self.config.pool_config().max_response_size;
Self::handle_response_static(response, max_response_size).await
}
}
/// Appends `start` and `limit` query parameters to `url` when present.
///
/// Shared by paginated REST endpoints (`/accounts/{addr}/resources`,
/// `/accounts/{addr}/modules`, ...) so the formatting stays consistent.
/// `start` is forwarded verbatim as a string so opaque pagination cursors
/// returned in the `x-aptos-cursor` header round-trip losslessly (the
/// fullnode does not promise numeric cursors).
fn append_start_limit(url: &mut Url, start: Option<&str>, limit: Option<u16>) {
if start.is_none() && limit.is_none() {
return;
}
let mut query = url.query_pairs_mut();
if let Some(start) = start {
query.append_pair("start", start);
}
if let Some(limit) = limit {
query.append_pair("limit", &limit.to_string());
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::transaction::authenticator::{
Ed25519PublicKey, Ed25519Signature, TransactionAuthenticator,
};
use crate::transaction::simulation::SimulateQueryOptions;
use crate::transaction::types::{RawTransaction, SignedTransaction};
use crate::types::ChainId;
use wiremock::{
Mock, MockServer, ResponseTemplate,
matchers::{method, path, path_regex, query_param},
};
#[test]
fn test_build_url() {
let client = FullnodeClient::new(AptosConfig::testnet()).unwrap();
let url = client.build_url("accounts/0x1");
assert!(url.as_str().contains("accounts/0x1"));
}
fn create_mock_client(server: &MockServer) -> FullnodeClient {
// The mock server URL needs to include /v1 since that's part of the base URL
let url = format!("{}/v1", server.uri());
let config = AptosConfig::custom(&url).unwrap().without_retry();
FullnodeClient::new(config).unwrap()
}
/// Creates a minimal `SignedTransaction` for use in `simulate_transaction` tests.
fn create_minimal_signed_transaction() -> SignedTransaction {
use crate::transaction::payload::{EntryFunction, TransactionPayload};
let raw = RawTransaction::new(
AccountAddress::ONE,
0,
TransactionPayload::EntryFunction(
EntryFunction::apt_transfer(AccountAddress::ONE, 0).unwrap(),
),
100_000,
100,
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs()
.saturating_add(600),
ChainId::testnet(),
);
let auth = TransactionAuthenticator::Ed25519 {
public_key: Ed25519PublicKey([0u8; 32]),
signature: Ed25519Signature([0u8; 64]),
};
SignedTransaction::new(raw, auth)
}
fn simulate_response_json() -> serde_json::Value {
serde_json::json!([{
"success": true,
"vm_status": "Executed successfully",
"gas_used": "100",
"max_gas_amount": "200000",
"gas_unit_price": "100",
"hash": "0x1",
"changes": [],
"events": []
}])
}
#[tokio::test]
async fn test_get_ledger_info() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/v1"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"chain_id": 2,
"epoch": "100",
"ledger_version": "12345",
"oldest_ledger_version": "0",
"ledger_timestamp": "1000000",
"node_role": "full_node",
"oldest_block_height": "0",
"block_height": "5000"
})))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let result = client.get_ledger_info().await.unwrap();
assert_eq!(result.data.chain_id, 2);
assert_eq!(result.data.version().unwrap(), 12345);
assert_eq!(result.data.height().unwrap(), 5000);
}
#[tokio::test]
async fn test_get_account() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path_regex(r"^/v1/accounts/0x[0-9a-f]+$"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(serde_json::json!({
"sequence_number": "42",
"authentication_key": "0x0000000000000000000000000000000000000000000000000000000000000001"
}))
.insert_header("x-aptos-ledger-version", "12345"),
)
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let result = client.get_account(AccountAddress::ONE).await.unwrap();
assert_eq!(result.data.sequence_number().unwrap(), 42);
assert_eq!(result.ledger_version, Some(12345));
}
#[tokio::test]
async fn test_get_account_not_found() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path_regex(r"/v1/accounts/0x[0-9a-f]+"))
.respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
"message": "Account not found",
"error_code": "account_not_found"
})))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let result = client.get_account(AccountAddress::ONE).await;
assert!(result.is_err());
let err = result.unwrap_err();
assert!(err.is_not_found());
}
#[tokio::test]
async fn test_get_account_resources() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path_regex(r"/v1/accounts/0x[0-9a-f]+/resources"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
{
"type": "0x1::account::Account",
"data": {"sequence_number": "10"}
},
{
"type": "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>",
"data": {"coin": {"value": "1000000"}}
}
])))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let result = client
.get_account_resources(AccountAddress::ONE)
.await
.unwrap();
assert_eq!(result.data.len(), 2);
assert!(result.data[0].typ.contains("Account"));
}
#[tokio::test]
async fn test_get_account_resource() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path_regex(r"/v1/accounts/0x[0-9a-f]+/resource/.*"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"type": "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>",
"data": {"coin": {"value": "5000000"}}
})))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let result = client
.get_account_resource(
AccountAddress::ONE,
"0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>",
)
.await
.unwrap();
assert!(result.data.typ.contains("CoinStore"));
}
#[tokio::test]
async fn test_get_account_modules() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path_regex(r"/v1/accounts/0x[0-9a-f]+/modules"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
{
"bytecode": "0xabc123",
"abi": {
"address": "0x1",
"name": "coin",
"exposed_functions": [],
"structs": []
}
}
])))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let result = client
.get_account_modules(AccountAddress::ONE)
.await
.unwrap();
assert_eq!(result.data.len(), 1);
assert!(result.data[0].abi.is_some());
}
#[tokio::test]
async fn test_get_account_resources_paginated_sends_start_and_limit() {
let server = MockServer::start().await;
// Verify the SDK forwards both query params verbatim.
Mock::given(method("GET"))
.and(path_regex(r"/v1/accounts/0x[0-9a-f]+/resources"))
.and(query_param("start", "42"))
.and(query_param("limit", "9"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let result = client
.get_account_resources_paginated(AccountAddress::ONE, Some("42"), Some(9))
.await
.unwrap();
assert_eq!(result.data.len(), 0);
}
#[tokio::test]
async fn test_get_account_resources_paginated_round_trips_opaque_cursor() {
// The `x-aptos-cursor` header is opaque (`Option<String>` on
// `AptosResponse`). A caller pulling page N+1 must be able to pass
// page N's cursor verbatim, even when it's not a decimal integer.
let server = MockServer::start().await;
let opaque = "0x0a1b2c3d_state_key_token";
Mock::given(method("GET"))
.and(path_regex(r"/v1/accounts/0x[0-9a-f]+/resources"))
.and(query_param("start", opaque))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
client
.get_account_resources_paginated(AccountAddress::ONE, Some(opaque), None)
.await
.unwrap();
}
#[tokio::test]
async fn test_get_account_resources_no_pagination_omits_query() {
let server = MockServer::start().await;
// When both args are None, no `start`/`limit` query params should
// be appended -- the fullnode default page applies.
Mock::given(method("GET"))
.and(path_regex(r"/v1/accounts/0x[0-9a-f]+/resources$"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
client
.get_account_resources(AccountAddress::ONE)
.await
.unwrap();
}
#[tokio::test]
async fn test_get_account_resources_paginated_sends_start_only() {
// Start without limit: caller is paging from a saved cursor and is
// happy with the fullnode default page size.
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path_regex(r"/v1/accounts/0x[0-9a-f]+/resources"))
.and(query_param("start", "1234"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
client
.get_account_resources_paginated(AccountAddress::ONE, Some("1234"), None)
.await
.unwrap();
}
#[tokio::test]
async fn test_get_account_modules_paginated_sends_start_and_limit() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path_regex(r"/v1/accounts/0x[0-9a-f]+/modules"))
.and(query_param("start", "7"))
.and(query_param("limit", "100"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
client
.get_account_modules_paginated(AccountAddress::ONE, Some("7"), Some(100))
.await
.unwrap();
}
#[tokio::test]
async fn test_get_account_modules_no_pagination_omits_query() {
// Symmetric with the resources variant: no `start` / `limit` query
// params should be appended when both are None.
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path_regex(r"/v1/accounts/0x[0-9a-f]+/modules$"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
client
.get_account_modules(AccountAddress::ONE)
.await
.unwrap();
}
#[tokio::test]
async fn test_get_account_modules_paginated_sends_limit_only() {
let server = MockServer::start().await;
// Only `limit` is sent when `start` is omitted -- caller is fetching
// the first page with a custom page size.
Mock::given(method("GET"))
.and(path_regex(r"/v1/accounts/0x[0-9a-f]+/modules"))
.and(query_param("limit", "25"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
client
.get_account_modules_paginated(AccountAddress::ONE, None, Some(25))
.await
.unwrap();
}
#[tokio::test]
async fn test_estimate_gas_price() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/v1/estimate_gas_price"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"deprioritized_gas_estimate": 50,
"gas_estimate": 100,
"prioritized_gas_estimate": 150
})))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let result = client.estimate_gas_price().await.unwrap();
assert_eq!(result.data.gas_estimate, 100);
assert_eq!(result.data.low(), 50);
assert_eq!(result.data.high(), 150);
}
#[tokio::test]
async fn test_get_transaction_by_hash() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path_regex(r"/v1/transactions/by_hash/0x[0-9a-f]+"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"version": "12345",
"hash": "0x0000000000000000000000000000000000000000000000000000000000000001",
"success": true,
"vm_status": "Executed successfully"
})))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let hash = HashValue::from_hex(
"0x0000000000000000000000000000000000000000000000000000000000000001",
)
.unwrap();
let result = client.get_transaction_by_hash(&hash).await.unwrap();
assert!(
result
.data
.get("success")
.and_then(serde_json::Value::as_bool)
.unwrap()
);
}
#[tokio::test]
async fn test_wait_for_transaction_success() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path_regex(r"/v1/transactions/by_hash/0x[0-9a-f]+"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"type": "user_transaction",
"version": "12345",
"hash": "0x0000000000000000000000000000000000000000000000000000000000000001",
"success": true,
"vm_status": "Executed successfully"
})))
.expect(1..)
.mount(&server)
.await;
let client = create_mock_client(&server);
let hash = HashValue::from_hex(
"0x0000000000000000000000000000000000000000000000000000000000000001",
)
.unwrap();
let result = client
.wait_for_transaction(&hash, Some(Duration::from_secs(5)))
.await
.unwrap();
assert!(
result
.data
.get("success")
.and_then(serde_json::Value::as_bool)
.unwrap()
);
}
#[tokio::test]
async fn test_server_error_retryable() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/v1"))
.respond_with(ResponseTemplate::new(503).set_body_json(serde_json::json!({
"message": "Service temporarily unavailable"
})))
.expect(1)
.mount(&server)
.await;
let url = format!("{}/v1", server.uri());
let config = AptosConfig::custom(&url).unwrap().without_retry();
let client = FullnodeClient::new(config).unwrap();
let result = client.get_ledger_info().await;
assert!(result.is_err());
assert!(result.unwrap_err().is_retryable());
}
#[tokio::test]
async fn test_rate_limited() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/v1"))
.respond_with(
ResponseTemplate::new(429)
.set_body_json(serde_json::json!({
"message": "Rate limited"
}))
.insert_header("retry-after", "30"),
)
.expect(1)
.mount(&server)
.await;
let url = format!("{}/v1", server.uri());
let config = AptosConfig::custom(&url).unwrap().without_retry();
let client = FullnodeClient::new(config).unwrap();
let result = client.get_ledger_info().await;
assert!(result.is_err());
assert!(result.unwrap_err().is_retryable());
}
#[tokio::test]
async fn test_get_block_by_height() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path_regex(r"/v1/blocks/by_height/\d+"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"block_height": "1000",
"block_hash": "0xabc",
"block_timestamp": "1234567890",
"first_version": "100",
"last_version": "200"
})))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let result = client.get_block_by_height(1000, false).await.unwrap();
assert!(result.data.get("block_height").is_some());
}
#[tokio::test]
async fn test_view() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/v1/view"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!(["1000000"])))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let result: AptosResponse<Vec<serde_json::Value>> = client
.view(
"0x1::coin::balance",
vec!["0x1::aptos_coin::AptosCoin".to_string()],
vec![serde_json::json!("0x1")],
)
.await
.unwrap();
assert_eq!(result.data.len(), 1);
}
#[tokio::test]
async fn test_view_bcs_args_posts_bcs_request() {
let server = MockServer::start().await;
// Arguments are real BCS bytes; the request must be sent as a BCS
// `ViewRequest` body (Content-Type application/x.aptos.view_function+bcs),
// not JSON. Pin the exact body bytes to guard the wire format: it must
// equal the BCS of an `EntryFunction`-shaped `ViewRequest`.
let args = vec![aptos_bcs::to_bytes(&AccountAddress::ONE).unwrap()];
let expected_body = aptos_bcs::to_bytes(
&crate::transaction::EntryFunction::from_function_id(
"0x1::coin::balance",
vec![],
args.clone(),
)
.unwrap(),
)
.unwrap();
Mock::given(method("POST"))
.and(path("/v1/view"))
.and(wiremock::matchers::header(
"content-type",
"application/x.aptos.view_function+bcs",
))
.and(wiremock::matchers::body_bytes(expected_body))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!(["1000000"])))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let result = client
.view_bcs_args("0x1::coin::balance", vec![], args)
.await
.unwrap()
.into_inner();
assert_eq!(result.len(), 1);
assert_eq!(result[0].as_str().unwrap(), "1000000");
}
#[tokio::test]
async fn test_simulate_transaction_with_estimate_gas_unit_price() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/v1/transactions/simulate"))
.and(|req: &wiremock::Request| {
req.url
.query()
.is_some_and(|q| q.contains("estimate_gas_unit_price=true"))
})
.respond_with(ResponseTemplate::new(200).set_body_json(simulate_response_json()))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let signed = create_minimal_signed_transaction();
let opts = SimulateQueryOptions::new().estimate_gas_unit_price(true);
let result = client
.simulate_transaction_with_options(&signed, opts)
.await
.unwrap();
assert!(!result.data.is_empty());
}
#[tokio::test]
async fn test_simulate_transaction_with_estimate_max_gas_amount() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/v1/transactions/simulate"))
.and(|req: &wiremock::Request| {
req.url
.query()
.is_some_and(|q| q.contains("estimate_max_gas_amount=true"))
})
.respond_with(ResponseTemplate::new(200).set_body_json(simulate_response_json()))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let signed = create_minimal_signed_transaction();
let opts = SimulateQueryOptions::new().estimate_max_gas_amount(true);
let result = client
.simulate_transaction_with_options(&signed, opts)
.await
.unwrap();
assert!(!result.data.is_empty());
}
#[tokio::test]
async fn test_simulate_transaction_with_estimate_prioritized_gas_unit_price() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/v1/transactions/simulate"))
.and(|req: &wiremock::Request| {
req.url
.query()
.is_some_and(|q| q.contains("estimate_prioritized_gas_unit_price=true"))
})
.respond_with(ResponseTemplate::new(200).set_body_json(simulate_response_json()))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let signed = create_minimal_signed_transaction();
let opts = SimulateQueryOptions::new().estimate_prioritized_gas_unit_price(true);
let result = client
.simulate_transaction_with_options(&signed, opts)
.await
.unwrap();
assert!(!result.data.is_empty());
}
#[tokio::test]
async fn test_simulate_transaction_with_all_options() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/v1/transactions/simulate"))
.and(|req: &wiremock::Request| {
req.url.query().is_some_and(|q| {
q.contains("estimate_gas_unit_price=true")
&& q.contains("estimate_max_gas_amount=true")
&& q.contains("estimate_prioritized_gas_unit_price=true")
})
})
.respond_with(ResponseTemplate::new(200).set_body_json(simulate_response_json()))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let signed = create_minimal_signed_transaction();
let opts = SimulateQueryOptions::new()
.estimate_gas_unit_price(true)
.estimate_max_gas_amount(true)
.estimate_prioritized_gas_unit_price(true);
let result = client
.simulate_transaction_with_options(&signed, opts)
.await
.unwrap();
assert!(!result.data.is_empty());
}
#[tokio::test]
async fn test_simulate_transaction_without_options() {
let server = MockServer::start().await;
// Mock must NOT match if query contains any of the simulate options (so we use path only and expect no query param)
Mock::given(method("POST"))
.and(path("/v1/transactions/simulate"))
.and(|req: &wiremock::Request| {
// URL must not contain the simulate query params when options is None
req.url.query().is_none_or(|q| {
!q.contains("estimate_gas_unit_price=")
&& !q.contains("estimate_max_gas_amount=")
&& !q.contains("estimate_prioritized_gas_unit_price=")
})
})
.respond_with(ResponseTemplate::new(200).set_body_json(simulate_response_json()))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let signed = create_minimal_signed_transaction();
let result = client.simulate_transaction(&signed).await.unwrap();
assert!(!result.data.is_empty());
}
#[tokio::test]
async fn test_get_table_item() {
let server = MockServer::start().await;
// The endpoint is POST /tables/{handle}/item with a JSON body carrying
// the key/value Move types and the key. Pin the body so the wire format
// is guarded.
Mock::given(method("POST"))
.and(path_regex(r"^/v1/tables/0x[0-9a-f]+/item$"))
.and(wiremock::matchers::body_json(serde_json::json!({
"key_type": "address",
"value_type": "u64",
"key": "0x1",
})))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!("42")))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let result = client
.get_table_item(
"0x0000000000000000000000000000000000000000000000000000000000000abc",
"address",
"u64",
serde_json::json!("0x1"),
)
.await
.unwrap();
assert_eq!(result.data, serde_json::json!("42"));
}
#[tokio::test]
async fn test_get_table_item_missing_key_is_404() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path_regex(r"^/v1/tables/0x[0-9a-f]+/item$"))
.respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
"message": "Table item not found",
"error_code": "table_item_not_found"
})))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let err = client
.get_table_item("0xabc", "address", "u64", serde_json::json!("0x2"))
.await
.unwrap_err();
assert!(matches!(
err,
AptosError::Api {
status_code: 404,
..
}
));
}
#[tokio::test]
async fn test_get_transaction_by_version() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/v1/transactions/by_version/100"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"version": "100",
"hash": "0xdead",
"success": true
})))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let result = client.get_transaction_by_version(100).await.unwrap();
assert_eq!(result.data.get("version").unwrap(), "100");
}
#[tokio::test]
async fn test_get_transactions_with_pagination() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/v1/transactions"))
.and(query_param("start", "10"))
.and(query_param("limit", "2"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
{"version": "10"},
{"version": "11"}
])))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let result = client.get_transactions(Some(10), Some(2)).await.unwrap();
assert_eq!(result.data.len(), 2);
}
#[tokio::test]
async fn test_get_account_transactions() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path_regex(r"^/v1/accounts/0x[0-9a-f]+/transactions$"))
.and(query_param("start", "0"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
{"version": "5", "sender": "0x1"}
])))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let result = client
.get_account_transactions(AccountAddress::ONE, Some(0), None)
.await
.unwrap();
assert_eq!(result.data.len(), 1);
}
#[tokio::test]
async fn test_get_events_by_creation_number() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path_regex(r"^/v1/accounts/0x[0-9a-f]+/events/7$"))
.and(query_param("limit", "25"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
{"sequence_number": "0", "type": "0x1::coin::DepositEvent"}
])))
.expect(1)
.mount(&server)
.await;
let client = create_mock_client(&server);
let result = client
.get_events_by_creation_number(AccountAddress::ONE, 7, None, Some(25))
.await
.unwrap();
assert_eq!(result.data.len(), 1);
}
}