autonomi-nodejs 0.1.1

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

use autonomi::{AttoTokens, Bytes, Chunk, Multiaddr, Signature};

use napi::bindgen_prelude::*;
use napi_derive::napi;
use tokio::sync::Mutex;

// Convert Rust errors to JavaScript errors
fn map_error<E>(err: E) -> napi::Error
where
    E: std::error::Error,
{
    let mut err_str = String::new();
    err_str.push_str(&format!("{err:?}: {err}\n"));
    let mut source = err.source();
    while let Some(err) = source {
        err_str.push_str(&format!(" Caused by: {err:?}: {err}\n"));
        source = err.source();
    }

    napi::Error::new(Status::GenericFailure, err_str)
}

fn big_int_to_u64(value: BigInt, arg: &str) -> Result<u64> {
    let (_signed, value, losless) = value.get_u64();
    if !losless {
        return Err(napi::Error::new(
            Status::InvalidArg,
            format!("expected `{arg}` to fit in a u64"),
        ));
    }

    Ok(value)
}

fn uint8_array_to_array<const LEN: usize>(value: Uint8Array, arg: &str) -> Result<[u8; LEN]> {
    value.as_ref().try_into().map_err(|_err| {
        napi::Error::new(
            Status::InvalidArg,
            format!(
                "`{arg}` is expected to be a {LEN}-byte array, but is {} bytes long",
                value.len()
            ),
        )
    })
}

/// Represents a client for the Autonomi network.
#[napi]
pub struct Client(autonomi::Client);

#[napi]
impl Client {
    /// Initialize the client with default configuration.
    ///
    /// See `init_with_config`.
    #[napi(factory)]
    pub async fn init() -> Result<Self> {
        let client = autonomi::Client::init().await.map_err(map_error)?;

        Ok(Self(client))
    }

    /// Initialize a client that is configured to be local.
    ///
    /// See `init_with_config`.
    #[napi(factory)]
    pub async fn init_local() -> Result<Self> {
        let client = autonomi::Client::init_local().await.map_err(map_error)?;

        Ok(Self(client))
    }

    /// Initialize a client that is configured to be connected to the alpha network.
    #[napi(factory)]
    pub async fn init_alpha() -> Result<Self> {
        let client = autonomi::Client::init_alpha().await.map_err(map_error)?;

        Ok(Self(client))
    }

    /// Initialize a client that bootstraps from a list of peers.
    ///
    /// If any of the provided peers is a global address, the client will not be local.
    #[napi]
    pub async fn init_with_peers(peers: Vec<String>) -> Result<Self> {
        let peers = peers
            .iter()
            .map(|p| Multiaddr::from_str(p))
            .collect::<std::result::Result<Vec<Multiaddr>, _>>()
            .map_err(map_error)?;

        let client = autonomi::Client::init_with_peers(peers)
            .await
            .map_err(map_error)?;

        Ok(Self(client))
    }

    // /// Initialize the client with the given configuration.
    // ///
    // /// This will block until CLOSE_GROUP_SIZE have been added to the routing table.
    // ///
    // /// See ClientConfig.
    // #[napi]
    // pub async fn init_with_config(config: ClientConfig) -> Result<Self> {
    //     todo!()
    // }

    #[napi]
    pub fn evm_network(&self) -> Network {
        Network(self.0.evm_network().clone())
    }

    // Chunks

    /// Get a chunk from the network.
    #[napi]
    pub async fn chunk_get(&self, addr: &ChunkAddress) -> Result<Buffer> {
        let chunk = self.0.chunk_get(&addr.0).await.map_err(map_error)?;

        Ok(Buffer::from(chunk.value.to_vec()))
    }

    /// Manually upload a chunk to the network.
    ///
    /// It is recommended to use the `data_put` method instead to upload data.
    #[napi]
    pub async fn chunk_put(
        &self,
        data: Buffer,
        payment_option: &PaymentOption,
    ) -> Result<tuple_result::ChunkPut> {
        let chunk = Chunk::new(Bytes::from(data.as_ref().to_vec()));

        let (cost, addr) = self
            .0
            .chunk_put(&chunk, payment_option.0.clone())
            .await
            .map_err(map_error)?;

        Ok(tuple_result::ChunkPut { cost, addr })
    }

    /// Get the cost of a chunk.
    #[napi]
    pub async fn chunk_cost(&self, addr: &ChunkAddress) -> Result</* AttoTokens */ String> {
        let cost = self.0.chunk_cost(&addr.0).await.map_err(map_error)?;

        Ok(cost.to_string())
    }

    // Graph entries

    /// Fetches a GraphEntry from the network.
    #[napi]
    pub async fn graph_entry_get(&self, address: &GraphEntryAddress) -> Result<GraphEntry> {
        let graph_entry = self
            .0
            .graph_entry_get(&address.0)
            .await
            .map_err(map_error)?;

        Ok(GraphEntry(graph_entry))
    }

    /// Check if a graph_entry exists on the network
    #[napi]
    pub async fn graph_entry_check_existance(&self, address: &GraphEntryAddress) -> Result<bool> {
        let exists = self
            .0
            .graph_entry_check_existence(&address.0)
            .await
            .map_err(map_error)?;

        Ok(exists)
    }

    /// Manually puts a GraphEntry to the network.
    #[napi]
    pub async fn graph_entry_put(
        &self,
        entry: &GraphEntry,
        payment_option: &PaymentOption,
    ) -> Result</* (AttoTokens, GraphEntryAddress) */ tuple_result::GraphEntryPut> {
        let (cost, addr) = self
            .0
            .graph_entry_put(entry.0.clone(), payment_option.0.clone())
            .await
            .map_err(map_error)?;

        Ok(tuple_result::GraphEntryPut { cost, addr })
    }

    /// Get the cost to create a GraphEntry
    #[napi]
    pub async fn graph_entry_cost(&self, key: &PublicKey) -> Result</* AttoTokens */ String> {
        self.0
            .graph_entry_cost(&key.0)
            .await
            .map(|c| c.to_string())
            .map_err(map_error)
    }

    // Pointers

    /// Get a pointer from the network
    #[napi]
    pub async fn pointer_get(&self, address: &PointerAddress) -> Result<Pointer> {
        self.0
            .pointer_get(&address.0)
            .await
            .map(Pointer)
            .map_err(map_error)
    }

    /// Check if a pointer exists on the network
    #[napi]
    pub async fn pointer_check_existance(&self, address: &PointerAddress) -> Result<bool> {
        self.0
            .pointer_check_existence(&address.0)
            .await
            .map_err(map_error)
    }

    /// Verify a pointer
    #[napi]
    pub fn pointer_verify(pointer: &Pointer) -> Result<()> {
        autonomi::Client::pointer_verify(&pointer.0).map_err(map_error)
    }

    /// Manually store a pointer on the network
    #[napi]
    pub async fn pointer_put(
        &self,
        pointer: &Pointer,
        payment_option: &PaymentOption,
    ) -> Result</* (AttoTokens, PointerAddress) */ tuple_result::PointerPut> {
        let (cost, addr) = self
            .0
            .pointer_put(pointer.0.clone(), payment_option.0.clone())
            .await
            .map_err(map_error)?;

        Ok(tuple_result::PointerPut { cost, addr })
    }

    /// Create a new pointer on the network.
    ///
    /// Make sure that the owner key is not already used for another pointer as each key is associated with one pointer
    #[napi]
    pub async fn pointer_create(
        &self,
        owner: &SecretKey,
        target: &PointerTarget,
        payment_option: &PaymentOption,
    ) -> Result</* (AttoTokens, PointerAddress) */ tuple_result::PointerPut> {
        let (cost, addr) = self
            .0
            .pointer_create(&owner.0, target.0.clone(), payment_option.0.clone())
            .await
            .map_err(map_error)?;

        Ok(tuple_result::PointerPut { cost, addr })
    }

    /// Update an existing pointer to point to a new target on the network.
    ///
    /// The pointer needs to be created first with Client::pointer_put.
    /// This operation is free as the pointer was already paid for at creation.
    /// Only the latest version of the pointer is kept on the Network,
    /// previous versions will be overwritten and unrecoverable.
    #[napi]
    pub async fn pointer_update(&self, owner: &SecretKey, target: &PointerTarget) -> Result<()> {
        self.0
            .pointer_update(&owner.0, target.0.clone())
            .await
            .map_err(map_error)
    }

    /// Calculate the cost of storing a pointer
    #[napi]
    pub async fn pointer_cost(&self, key: &PublicKey) -> Result</* AttoTokens */ String> {
        let cost = self.0.pointer_cost(&key.0).await.map_err(map_error)?;

        Ok(cost.to_string())
    }

    // Scratchpad

    /// Get Scratchpad from the Network. A Scratchpad is stored at the owner's public key so we can derive the address from it.
    #[napi]
    pub async fn scratchpad_get_from_public_key(
        &self,
        public_key: &PublicKey,
    ) -> Result<Scratchpad> {
        self.0
            .scratchpad_get_from_public_key(&public_key.0)
            .await
            .map(Scratchpad)
            .map_err(map_error)
    }

    /// Get Scratchpad from the Network
    #[napi]
    pub async fn scratchpad_get(&self, address: &ScratchpadAddress) -> Result<Scratchpad> {
        self.0
            .scratchpad_get(&address.0)
            .await
            .map(Scratchpad)
            .map_err(map_error)
    }

    /// Check if a scratchpad exists on the network
    #[napi]
    pub async fn scratchpad_check_existance(&self, address: &ScratchpadAddress) -> Result<bool> {
        self.0
            .scratchpad_check_existence(&address.0)
            .await
            .map_err(map_error)
    }

    /// Verify a scratchpad
    #[napi]
    pub fn scratchpad_verify(scratchpad: &Scratchpad) -> Result<()> {
        autonomi::Client::scratchpad_verify(&scratchpad.0).map_err(map_error)
    }

    /// Manually store a scratchpad on the network
    #[napi]
    pub async fn scratchpad_put(
        &self,
        scratchpad: &Scratchpad,
        payment_option: &PaymentOption,
    ) -> Result</* (AttoTokens, ScratchpadAddress) */ tuple_result::ScratchpadPut> {
        let (cost, addr) = self
            .0
            .scratchpad_put(scratchpad.0.clone(), payment_option.0.clone())
            .await
            .map_err(map_error)?;

        Ok(tuple_result::ScratchpadPut { cost, addr })
    }

    /// Create a new scratchpad to the network.
    ///
    /// Make sure that the owner key is not already used for another scratchpad as each key is associated with one scratchpad. The data will be encrypted with the owner key before being stored on the network. The content type is used to identify the type of data stored in the scratchpad, the choice is up to the caller.
    ///
    /// Returns the cost and the address of the scratchpad.
    #[napi]
    pub async fn scratchpad_create(
        &self,
        owner: &SecretKey,
        content_type: BigInt, // `u64`
        initial_data: Buffer,
        payment_option: &PaymentOption,
    ) -> Result</* (AttoTokens, ScratchpadAddress) */ tuple_result::ScratchpadPut> {
        let content_type = big_int_to_u64(content_type, "content_type")?;

        let (cost, addr) = self
            .0
            .scratchpad_create(
                &owner.0,
                content_type,
                &Bytes::copy_from_slice(&initial_data),
                payment_option.0.clone(),
            )
            .await
            .map_err(map_error)?;

        Ok(tuple_result::ScratchpadPut { cost, addr })
    }

    /// Update an existing scratchpad to the network.
    /// The scratchpad needs to be created first with Client::scratchpad_create.
    /// This operation is free as the scratchpad was already paid for at creation.
    /// Only the latest version of the scratchpad is kept on the Network,
    /// previous versions will be overwritten and unrecoverable.
    #[napi]
    pub async fn scratchpad_update(
        &self,
        owner: &SecretKey,
        content_type: BigInt, // `u64`
        data: Buffer,
    ) -> Result<()> {
        let content_type = big_int_to_u64(content_type, "content_type")?;

        self.0
            .scratchpad_update(&owner.0, content_type, &Bytes::copy_from_slice(&data))
            .await
            .map_err(map_error)
    }

    /// Get the cost of creating a new Scratchpad
    #[napi]
    pub async fn scratchpad_cost(&self, owner: &PublicKey) -> Result</* AttoTokens */ String> {
        let cost = self.0.scratchpad_cost(&owner.0).await.map_err(map_error)?;

        Ok(cost.to_string())
    }

    // Data

    /// Fetch a blob of (private) data from the network
    #[napi]
    pub async fn data_get(&self, data_map: &DataMapChunk) -> Result<Buffer> {
        let data = self.0.data_get(&data_map.0).await.map_err(map_error)?;

        Ok(Buffer::from(data.as_ref()))
    }

    /// Upload a piece of private data to the network. This data will be self-encrypted.
    /// The DataMapChunk is not uploaded to the network, keeping the data private.
    ///
    /// Returns the DataMapChunk containing the map to the encrypted chunks.
    #[napi]
    pub async fn data_put(
        &self,
        data: Buffer,
        payment_option: &PaymentOption,
    ) -> Result</* (AttoTokens, DataMapChunk) */ tuple_result::DataPutResult> {
        let data = Bytes::copy_from_slice(&data);

        let (cost, data_map) = self
            .0
            .data_put(data, payment_option.0.clone())
            .await
            .map_err(map_error)?;

        Ok(tuple_result::DataPutResult { cost, data_map })
    }

    /// Fetch a blob of data from the network
    #[napi]
    pub async fn data_get_public(&self, addr: &DataAddress) -> Result<Buffer> {
        let data = self.0.data_get_public(&addr.0).await.map_err(map_error)?;

        Ok(Buffer::from(data.as_ref()))
    }

    /// Upload a piece of data to the network. This data is publicly accessible.
    ///
    /// Returns the Data Address at which the data was stored.
    #[napi]
    pub async fn data_put_public(
        &self,
        data: Buffer,
        payment_option: &PaymentOption,
    ) -> Result</* (AttoTokens, DataAddress) */ tuple_result::DataPutPublicResult> {
        let data = Bytes::copy_from_slice(&data);

        let (cost, addr) = self
            .0
            .data_put_public(data, payment_option.0.clone())
            .await
            .map_err(map_error)?;

        Ok(tuple_result::DataPutPublicResult { cost, addr })
    }

    /// Get the estimated cost of storing a piece of data.
    #[napi]
    pub async fn data_cost(&self, data: Buffer) -> Result</* AttoTokens */ String> {
        let cost = self
            .0
            .data_cost(Bytes::copy_from_slice(&data))
            .await
            .map_err(map_error)?;

        Ok(cost.to_string())
    }

    // Archives

    /// Fetch a PrivateArchive from the network
    #[napi]
    pub async fn archive_get(&self, addr: &PrivateArchiveDataMap) -> Result<PrivateArchive> {
        let archive = self.0.archive_get(&addr.0).await.map_err(map_error)?;

        Ok(PrivateArchive(archive))
    }

    /// Upload a PrivateArchive to the network
    #[napi]
    pub async fn archive_put(
        &self,
        archive: &PrivateArchive,
        payment_option: &PaymentOption,
    ) -> Result</*(AttoTokens, PrivateArchiveDataMap)*/ tuple_result::ArchivePutResult> {
        let (cost, data_map) = self
            .0
            .archive_put(&archive.0, payment_option.0.clone())
            .await
            .map_err(map_error)?;

        Ok(tuple_result::ArchivePutResult { cost, data_map })
    }

    // <TOPIC>

    /// Fetch an archive from the network
    #[napi]
    pub async fn archive_get_public(&self, addr: &ArchiveAddress) -> Result<PublicArchive> {
        let archive = self
            .0
            .archive_get_public(&addr.0)
            .await
            .map_err(map_error)?;

        Ok(PublicArchive(archive))
    }

    /// Upload an archive to the network
    #[napi]
    pub async fn archive_put_public(
        &self,
        archive: &PublicArchive,
        payment_option: &PaymentOption,
    ) -> Result</* (AttoTokens, ArchiveAddress) */ tuple_result::ArchivePutPublicResult> {
        let (cost, addr) = self
            .0
            .archive_put_public(&archive.0, payment_option.0.clone())
            .await
            .map_err(map_error)?;

        Ok(tuple_result::ArchivePutPublicResult { cost, addr })
    }

    /// Get the cost to upload an archive
    #[napi]
    pub async fn archive_cost(&self, archive: &PublicArchive) -> Result</* AttoTokens */ String> {
        let cost = self
            .0
            .archive_cost(&archive.0.clone())
            .await
            .map_err(map_error)?;

        Ok(cost.to_string())
    }

    // Files

    /// Download a private file from network to local file system
    #[napi]
    pub async fn file_download(
        &self,
        data_map: &DataMapChunk,
        to_dest: /* PathBuf */ String,
    ) -> Result<()> {
        let to_dest = PathBuf::from(to_dest);

        self.0
            .file_download(&data_map.0, to_dest)
            .await
            .map_err(map_error)
    }

    /// Download a private directory from network to local file system
    #[napi]
    pub async fn dir_download(
        &self,
        archive_access: &PrivateArchiveDataMap,
        to_dest: /* PathBuf */ String,
    ) -> Result<()> {
        let to_dest = PathBuf::from(to_dest);

        self.0
            .dir_download(&archive_access.0, to_dest)
            .await
            .map_err(map_error)
    }

    /// Upload the content of all files in a directory to the network.
    /// The directory is recursively walked and each file is uploaded to the network.
    ///
    /// The data maps of these (private) files are not uploaded but returned within
    /// the PrivateArchive return type.

    #[napi]
    pub async fn dir_content_upload(
        &self,
        dir_path: /* PathBuf */ String,
        payment_option: &PaymentOption,
    ) -> Result</* (AttoTokens, PrivateArchive) */ tuple_result::DirContentUpload> {
        let dir_path = PathBuf::from(dir_path);

        let (cost, archive) = self
            .0
            .dir_content_upload(dir_path, payment_option.0.clone())
            .await
            .map_err(map_error)?;

        Ok(tuple_result::DirContentUpload { cost, archive })
    }

    /// Same as Client::dir_content_upload but also uploads the archive (privately) to the network.
    ///
    /// Returns the PrivateArchiveDataMap allowing the private archive to be downloaded from the network.
    #[napi]
    pub async fn dir_upload(
        &self,
        dir_path: /* PathBuf */ String,
        payment_option: &PaymentOption,
    ) -> Result</* (AttoTokens, PrivateArchiveDataMap) */ tuple_result::DirUpload> {
        let dir_path = PathBuf::from(dir_path);

        let (cost, data_map) = self
            .0
            .dir_upload(dir_path, payment_option.0.clone())
            .await
            .map_err(map_error)?;

        Ok(tuple_result::DirUpload { cost, data_map })
    }

    /// Upload the content of a private file to the network. Reads file, splits into
    /// chunks, uploads chunks, uploads datamap, returns DataMapChunk (pointing to the datamap)
    #[napi]
    pub async fn file_content_upload(
        &self,
        path: /* PathBuf */ String,
        payment_option: &PaymentOption,
    ) -> Result</* (AttoTokens, DataMapChunk) */ tuple_result::FileContentUpload> {
        let path = PathBuf::from(path);

        let (cost, data_map) = self
            .0
            .file_content_upload(path, payment_option.0.clone())
            .await
            .map_err(map_error)?;

        Ok(tuple_result::FileContentUpload { cost, data_map })
    }

    /// Download file from network to local file system
    #[napi]
    pub async fn file_download_public(
        &self,
        data_addr: &DataAddress,
        to_dest: /* PathBuf */ String,
    ) -> Result<()> {
        let to_dest = PathBuf::from(to_dest);

        self.0
            .file_download_public(&data_addr.0, to_dest)
            .await
            .map_err(map_error)
    }

    /// Download directory from network to local file system
    #[napi]
    pub async fn dir_download_public(
        &self,
        archive_addr: &ArchiveAddress,
        to_dest: /* PathBuf */ String,
    ) -> Result<()> {
        let to_dest = PathBuf::from(to_dest);

        self.0
            .dir_download_public(&archive_addr.0, to_dest)
            .await
            .map_err(map_error)
    }

    /// Upload the content of all files in a directory to the network. The directory is recursively walked and each file is uploaded to the network.
    ///
    /// The data maps of these files are uploaded on the network, making the individual files publicly available.
    ///
    /// This returns, but does not upload (!),the PublicArchive containing the data maps of the uploaded files.
    #[napi]
    pub async fn dir_content_upload_public(
        &self,
        dir_path: /* PathBuf */ String,
        payment_option: &PaymentOption,
    ) -> Result</* (AttoTokens, PublicArchive) */ tuple_result::DirContentUploadPublic> {
        let dir_path = PathBuf::from(dir_path);

        let (cost, archive) = self
            .0
            .dir_content_upload_public(dir_path, payment_option.0.clone())
            .await
            .map_err(map_error)?;

        Ok(tuple_result::DirContentUploadPublic { cost, archive })
    }

    /// Same as Client::dir_content_upload_public but also uploads the archive to the network.
    ///
    /// Returns the ArchiveAddress of the uploaded archive.
    #[napi]
    pub async fn dir_upload_public(
        &self,
        dir_path: /* PathBuf */ String,
        payment_option: &PaymentOption,
    ) -> Result</* (AttoTokens, ArchiveAddress) */ tuple_result::DirUploadPublic> {
        let dir_path = PathBuf::from(dir_path);

        let (cost, addr) = self
            .0
            .dir_upload_public(dir_path, payment_option.0.clone())
            .await
            .map_err(map_error)?;

        Ok(tuple_result::DirUploadPublic { cost, addr })
    }

    /// Upload the content of a file to the network. Reads file, splits into chunks,
    /// uploads chunks, uploads datamap, returns DataAddr (pointing to the datamap)
    #[napi]
    pub async fn file_content_upload_public(
        &self,
        _path: /* PathBuf */ String,
        _payment_option: &PaymentOption,
    ) -> Result</* (AttoTokens, DataAddress) */ tuple_result::FileContentUploadPublic> {
        todo!()
    }

    /// Get the cost to upload a file/dir to the network. quick and dirty implementation, please refactor once files are cleanly implemented
    #[napi]
    pub async fn file_cost(&self, path: /* &PathBuf */ String) -> Result</* AttoTokens */ String> {
        let cost = self
            .0
            .file_cost(&PathBuf::from(path))
            .await
            .map_err(map_error)?;

        Ok(cost.to_string())
    }

    // Vault/user data

    /// Get the user data from the vault
    #[napi]
    pub async fn get_user_data_from_vault(&self, secret_key: &VaultSecretKey) -> Result<UserData> {
        self.0
            .get_user_data_from_vault(&secret_key.0)
            .await
            .map(UserData)
            .map_err(map_error)
    }

    /// Put the user data to the vault
    ///
    /// Returns the total cost of the put operation
    #[napi]
    pub async fn put_user_data_to_vault(
        &self,
        secret_key: &VaultSecretKey,
        payment_option: &PaymentOption,
        user_data: &UserData,
    ) -> Result</* AttoTokens */ String> {
        self.0
            .put_user_data_to_vault(&secret_key.0, payment_option.0.clone(), user_data.0.clone())
            .await
            .map(|c| c.to_string())
            .map_err(map_error)
    }

    /// Retrieves and returns a decrypted vault if one exists.
    ///
    /// Returns the content type of the bytes in the vault.
    #[napi]
    pub async fn fetch_and_decrypt_vault(
        &self,
        secret_key: &VaultSecretKey,
    ) -> Result</* (Bytes, VaultContentType) */ tuple_result::FetchAndDecryptVault> {
        let (data, content_type) = self
            .0
            .fetch_and_decrypt_vault(&secret_key.0)
            .await
            .map_err(map_error)?;

        Ok(tuple_result::FetchAndDecryptVault { data, content_type })
    }

    /// Get the cost of creating a new vault A quick estimation of cost:
    /// num_of_graph_entry * graph_entry_cost + num_of_scratchpad * scratchpad_cost
    #[napi]
    pub async fn vault_cost(
        &self,
        owner: &VaultSecretKey,
        max_size: /* u64 */ BigInt,
    ) -> Result</* AttoTokens */ String> {
        let max_size = big_int_to_u64(max_size, "max_size")?;

        let cost = self
            .0
            .vault_cost(&owner.0.clone(), max_size)
            .await
            .map_err(map_error)?;

        Ok(cost.to_string())
    }

    /// Put data into the client's VaultPacket
    ///
    /// Dynamically expand the vault capacity by paying for more space (Scratchpad) when needed.
    ///
    /// It is recommended to use the hash of the app name or unique identifier as the content type.

    #[napi]
    pub async fn write_bytes_to_vault(
        &self,
        data: Buffer,
        payment_option: &PaymentOption,
        secret_key: &VaultSecretKey,
        content_type: &VaultContentType,
    ) -> Result</* AttoTokens */ String> {
        let data = Bytes::copy_from_slice(&data);

        self.0
            .write_bytes_to_vault(
                data,
                payment_option.0.clone(),
                &secret_key.0,
                content_type.0,
            )
            .await
            .map(|c| c.to_string())
            .map_err(map_error)
    }

    // Registers

    /// Get the register history, starting from the root to the latest entry.
    ///
    /// This returns a RegisterHistory that can be use to get the register values from the history.
    ///
    /// RegisterHistory::next can be used to get the values one by one, from the first to the latest entry.
    /// RegisterHistory::collect can be used to get all the register values from the history from the first to the latest entry.
    #[napi]
    pub fn register_history(&self, addr: &RegisterAddress) -> RegisterHistory {
        let history = self.0.register_history(&addr.0);

        RegisterHistory(Mutex::new(history))
    }

    /// Create a new register key from a SecretKey and a name.
    ///
    /// This derives a new SecretKey from the owner's SecretKey using the name. Note that you will need to keep track of the names you used to create the register key.
    #[napi]
    pub fn register_key_from_name(owner: &SecretKey, name: String) -> SecretKey {
        let key = autonomi::Client::register_key_from_name(&owner.0, &name);
        SecretKey(key)
    }

    /// Create a new RegisterValue from bytes, make sure the bytes are not longer than REGISTER_VALUE_SIZE
    #[napi]
    pub fn register_value_from_bytes(bytes: &[u8]) -> Result</* RegisterValue */ Uint8Array> {
        autonomi::Client::register_value_from_bytes(bytes)
            .map(Uint8Array::from)
            .map_err(map_error)
    }

    /// Create a new register with an initial value.
    ///
    /// Note that two payments are required, one for the underlying GraphEntry and one for the crate::Pointer
    #[napi]
    pub async fn register_create(
        &self,
        owner: &SecretKey,
        initial_value: /* RegisterValue */ Uint8Array,
        payment_option: &PaymentOption,
    ) -> Result</* (AttoTokens, RegisterAddress) */ tuple_result::RegisterCreate> {
        let initial_value: [u8; 32] = uint8_array_to_array(initial_value, "initial_value")?;

        let (cost, addr) = self
            .0
            .register_create(&owner.0, initial_value, payment_option.0.clone())
            .await
            .map_err(map_error)?;

        Ok(tuple_result::RegisterCreate { cost, addr })
    }

    /// Update the value of a register.
    ////
    /// The register needs to be created first with autonomi::Client::register_create
    #[napi]
    pub async fn register_update(
        &self,
        owner: &SecretKey,
        new_value: /* RegisterValue */ Uint8Array,
        payment_option: &PaymentOption,
    ) -> Result</* AttoTokens */ String> {
        let new_value: [u8; 32] = uint8_array_to_array(new_value, "new_value")?;
        self.0
            .register_update(&owner.0, new_value, payment_option.0.clone())
            .await
            .map(|c| c.to_string())
            .map_err(map_error)
    }

    /// Get the current value of the register
    #[napi]
    pub async fn register_get(
        &self,
        addr: &RegisterAddress,
    ) -> Result</* RegisterValue */ Uint8Array> {
        self.0
            .register_get(&addr.0)
            .await
            .map(Uint8Array::from)
            .map_err(map_error)
    }

    /// Get the cost of a register operation. Returns the cost of creation if it doesn't exist, else returns the cost of an update
    #[napi]
    pub async fn register_cost(&self, owner: &PublicKey) -> Result</* AttoTokens */ String> {
        let cost = self
            .0
            .register_cost(&owner.0.clone())
            .await
            .map_err(map_error)?;

        Ok(cost.to_string())
    }

    // Quotes

    // /// Get raw quotes from nodes. These quotes do not include actual record prices. You will likely want to use get_store_quotes instead.
    // #[napi]
    // pub async fn get_raw_quotes(
    //     &self,
    //     data_type: DataTypes,
    //     content_addrs: impl Iterator<Item = (XorName, usize)>,
    // ) -> Vec<Result<(XorName, Vec<(PeerId, PaymentQuote)>)>> {
    //     todo!()
    // }

    // ///
    // #[napi]
    // pub async fn get_store_quotes(
    //     &self,
    //     data_type: DataTypes,
    //     content_addrs: impl Iterator<Item = (XorName, usize)>,
    // ) -> Result<StoreQuote> {
    //     todo!()
    // }
}

// These types exists because NAPI-RS does not support returning tuples.
pub mod tuple_result {
    use super::*;

    #[napi]
    pub struct ChunkPut {
        pub(crate) cost: AttoTokens,
        pub(crate) addr: autonomi::ChunkAddress, // Can not be `ChunkAddress` as NAPI-RS expects a reference in that case.
    }
    #[napi]
    impl ChunkPut {
        #[napi(getter)]
        pub fn cost(&self) -> String {
            self.cost.to_string()
        }
        #[napi(getter)]
        pub fn addr(&self) -> ChunkAddress {
            ChunkAddress(self.addr)
        }
    }

    #[napi]
    pub struct GraphEntryPut {
        pub(crate) cost: AttoTokens,
        pub(crate) addr: autonomi::GraphEntryAddress,
    }
    #[napi]
    impl GraphEntryPut {
        #[napi(getter)]
        pub fn cost(&self) -> String {
            self.cost.to_string()
        }
        #[napi(getter)]
        pub fn addr(&self) -> GraphEntryAddress {
            GraphEntryAddress(self.addr)
        }
    }

    #[napi]
    pub struct ScratchpadPut {
        pub(crate) cost: AttoTokens,
        pub(crate) addr: autonomi::ScratchpadAddress,
    }
    #[napi]
    impl ScratchpadPut {
        #[napi(getter)]
        pub fn cost(&self) -> String {
            self.cost.to_string()
        }
        #[napi(getter)]
        pub fn addr(&self) -> ScratchpadAddress {
            ScratchpadAddress(self.addr)
        }
    }

    #[napi]
    pub struct PointerPut {
        pub(crate) cost: AttoTokens,
        pub(crate) addr: autonomi::PointerAddress,
    }
    #[napi]
    impl PointerPut {
        #[napi(getter)]
        pub fn cost(&self) -> String {
            self.cost.to_string()
        }
        #[napi(getter)]
        pub fn addr(&self) -> PointerAddress {
            PointerAddress(self.addr)
        }
    }

    #[napi]
    pub struct DataPutResult {
        pub(crate) cost: AttoTokens,
        pub(crate) data_map: autonomi::data::private::DataMapChunk,
    }
    #[napi]
    impl DataPutResult {
        #[napi(getter)]
        pub fn cost(&self) -> String {
            self.cost.to_string()
        }
        #[napi(getter)]
        pub fn data_map(&self) -> DataMapChunk {
            DataMapChunk(self.data_map.clone())
        }
    }

    #[napi]
    pub struct DataPutPublicResult {
        pub(crate) cost: AttoTokens,
        pub(crate) addr: autonomi::data::DataAddress,
    }
    #[napi]
    impl DataPutPublicResult {
        #[napi(getter)]
        pub fn cost(&self) -> String {
            self.cost.to_string()
        }
        #[napi(getter)]
        pub fn addr(&self) -> DataAddress {
            DataAddress(self.addr)
        }
    }

    #[napi]
    pub struct ArchivePutResult {
        pub(crate) cost: AttoTokens,
        pub(crate) data_map: autonomi::files::archive_private::PrivateArchiveDataMap,
    }
    #[napi]
    impl ArchivePutResult {
        #[napi(getter)]
        pub fn cost(&self) -> String {
            self.cost.to_string()
        }
        #[napi(getter)]
        pub fn data_map(&self) -> PrivateArchiveDataMap {
            PrivateArchiveDataMap(self.data_map.clone())
        }
    }

    #[napi]
    pub struct ArchivePutPublicResult {
        pub(crate) cost: AttoTokens,
        pub(crate) addr: autonomi::data::DataAddress,
    }
    #[napi]
    impl ArchivePutPublicResult {
        #[napi(getter)]
        pub fn cost(&self) -> String {
            self.cost.to_string()
        }
        #[napi(getter)]
        pub fn addr(&self) -> DataAddress {
            DataAddress(self.addr)
        }
    }

    #[napi]
    pub struct DirContentUpload {
        pub(crate) cost: AttoTokens,
        pub(crate) archive: autonomi::files::PrivateArchive,
    }
    #[napi]
    impl DirContentUpload {
        #[napi(getter)]
        pub fn cost(&self) -> String {
            self.cost.to_string()
        }
        #[napi(getter)]
        pub fn archive(&self) -> PrivateArchive {
            PrivateArchive(self.archive.clone())
        }
    }

    #[napi]
    pub struct DirUpload {
        pub(crate) cost: AttoTokens,
        pub(crate) data_map: autonomi::data::private::DataMapChunk,
    }
    #[napi]
    impl DirUpload {
        #[napi(getter)]
        pub fn cost(&self) -> String {
            self.cost.to_string()
        }
        #[napi(getter)]
        pub fn data_map(&self) -> DataMapChunk {
            DataMapChunk(self.data_map.clone())
        }
    }

    #[napi]
    pub struct FileContentUpload {
        pub(crate) cost: AttoTokens,
        pub(crate) data_map: autonomi::data::private::DataMapChunk,
    }
    #[napi]
    impl FileContentUpload {
        #[napi(getter)]
        pub fn cost(&self) -> String {
            self.cost.to_string()
        }
        #[napi(getter)]
        pub fn data_map(&self) -> DataMapChunk {
            DataMapChunk(self.data_map.clone())
        }
    }

    #[napi]
    pub struct DirContentUploadPublic {
        pub(crate) cost: AttoTokens,
        pub(crate) archive: autonomi::files::PublicArchive,
    }
    #[napi]
    impl DirContentUploadPublic {
        #[napi(getter)]
        pub fn cost(&self) -> String {
            self.cost.to_string()
        }
        #[napi(getter)]
        pub fn addr(&self) -> PublicArchive {
            PublicArchive(self.archive.clone())
        }
    }

    #[napi]
    pub struct DirUploadPublic {
        pub(crate) cost: AttoTokens,
        pub(crate) addr: autonomi::files::archive_public::ArchiveAddress,
    }
    #[napi]
    impl DirUploadPublic {
        #[napi(getter)]
        pub fn cost(&self) -> String {
            self.cost.to_string()
        }
        #[napi(getter)]
        pub fn addr(&self) -> ArchiveAddress {
            ArchiveAddress(self.addr)
        }
    }

    #[napi]
    pub struct FileContentUploadPublic {
        pub(crate) cost: AttoTokens,
        pub(crate) addr: autonomi::PointerAddress,
    }
    #[napi]
    impl FileContentUploadPublic {
        #[napi(getter)]
        pub fn cost(&self) -> String {
            self.cost.to_string()
        }
        #[napi(getter)]
        pub fn addr(&self) -> PointerAddress {
            PointerAddress(self.addr)
        }
    }

    #[napi]
    pub struct FetchAndDecryptVault {
        pub(crate) data: Bytes,
        pub(crate) content_type: autonomi::vault::VaultContentType,
    }
    #[napi]
    impl FetchAndDecryptVault {
        #[napi(getter)]
        pub fn data(&self) -> Buffer {
            Buffer::from(self.data.as_ref())
        }
        #[napi(getter)]
        pub fn content_type(&self) -> u64 {
            self.content_type
        }
    }

    #[napi]
    pub struct RegisterCreate {
        pub(crate) cost: AttoTokens,
        pub(crate) addr: autonomi::register::RegisterAddress,
    }
    #[napi]
    impl RegisterCreate {
        #[napi(getter)]
        pub fn cost(&self) -> String {
            self.cost.to_string()
        }
        #[napi(getter)]
        pub fn addr(&self) -> RegisterAddress {
            RegisterAddress(self.addr)
        }
    }

    #[napi]
    pub struct GraphEntryDescendant {
        pub(crate) public_key: autonomi::PublicKey,
        pub(crate) content: [u8; 32],
    }
    #[napi]
    impl GraphEntryDescendant {
        #[napi(getter)]
        pub fn public_key(&self) -> PublicKey {
            PublicKey(self.public_key)
        }
        #[napi(getter)]
        pub fn content(&self) -> Uint8Array {
            Uint8Array::from(self.content.as_ref())
        }
    }

    #[napi(object)]
    pub struct ArchiveFile {
        pub path: String,
        pub created: BigInt,
        pub modified: BigInt,
        pub size: BigInt,
        pub extra: Option<String>,
    }
}

/// A 256-bit number, viewed as a point in XOR space.
///
/// This wraps an array of 32 bytes, i. e. a number between 0 and 2<sup>256</sup> - 1.
///
/// XOR space is the space of these numbers, with the [XOR metric][1] as a notion of distance,
/// i. e. the points with IDs `x` and `y` are considered to have distance `x xor y`.
///
/// [1]: https://en.wikipedia.org/wiki/Kademlia#System_details
#[napi]
pub struct XorName(autonomi::XorName);
#[napi]
impl XorName {
    /// Generate a XorName for the given content.
    #[napi(factory)]
    pub fn from_content(content: &[u8]) -> Self {
        Self(autonomi::XorName::from_content_parts(&[content]))
    }

    /// Generate a random XorName
    #[napi(factory)]
    pub fn random() -> Self {
        Self(autonomi::XorName::random(&mut rand::thread_rng()))
    }
}

/// Address of a chunk.
///
/// It is derived from the content of the chunk.
#[napi]
pub struct ChunkAddress(autonomi::ChunkAddress);

#[napi]
impl ChunkAddress {
    /// Creates a new ChunkAddress.
    #[napi(constructor)]
    pub fn new(xor_name: &XorName) -> Self {
        Self(autonomi::ChunkAddress::new(xor_name.0))
    }

    /// Returns the XorName.
    #[napi]
    pub fn xorname(&self) -> XorName {
        XorName(*self.0.xorname())
    }

    /// Returns the hex string representation of the address.
    #[napi]
    pub fn to_hex(&self) -> String {
        self.0.to_hex()
    }

    /// Creates a new ChunkAddress from a hex string.
    #[napi(factory)]
    pub fn from_hex(hex: String) -> Result<Self> {
        let addr = autonomi::ChunkAddress::from_hex(&hex).map_err(map_error)?;

        Ok(Self(addr))
    }
}

/// Address of a `GraphEntry`.
///
/// It is derived from the owner's unique public key
#[napi]
pub struct GraphEntryAddress(autonomi::GraphEntryAddress);

#[napi]
impl GraphEntryAddress {
    /// Creates a new GraphEntryAddress.
    #[napi(constructor)]
    pub fn new(owner: &PublicKey) -> Self {
        Self(autonomi::GraphEntryAddress::new(owner.0))
    }

    /// Return the network name of the scratchpad.
    /// This is used to locate the scratchpad on the network.
    #[napi]
    pub fn xorname(&self) -> XorName {
        XorName(self.0.xorname())
    }

    /// Serialize this `GraphEntryAddress` into a hex-encoded string.
    #[napi]
    pub fn to_hex(&self) -> String {
        self.0.to_hex()
    }

    /// Parse a hex-encoded string into a `GraphEntryAddress`.
    #[napi(factory)]
    pub fn from_hex(hex: String) -> Result<Self> {
        let addr = autonomi::GraphEntryAddress::from_hex(&hex).map_err(map_error)?;

        Ok(Self(addr))
    }
}

#[napi]
pub struct DataAddress(autonomi::data::DataAddress);

#[napi]
impl DataAddress {
    /// Creates a new DataAddress.
    #[napi(constructor)]
    pub fn new(xor_name: &XorName) -> Self {
        Self(autonomi::data::DataAddress::new(xor_name.0))
    }

    /// Returns the XorName.
    #[napi]
    pub fn xorname(&self) -> XorName {
        XorName(*self.0.xorname())
    }

    /// Returns the hex string representation of the address.
    #[napi]
    pub fn to_hex(&self) -> String {
        self.0.to_hex()
    }

    /// Creates a new DataAddress from a hex string.
    #[napi(factory)]
    pub fn from_hex(hex: String) -> Result<Self> {
        autonomi::data::DataAddress::from_hex(&hex)
            .map(Self)
            .map_err(map_error)
    }
}

#[napi]
pub struct ArchiveAddress(autonomi::files::archive_public::ArchiveAddress);

#[napi]
impl ArchiveAddress {
    /// Creates a new ArchiveAddress.
    #[napi(constructor)]
    pub fn new(xor_name: &XorName) -> Self {
        Self(autonomi::files::archive_public::ArchiveAddress::new(
            xor_name.0,
        ))
    }

    /// Returns the XorName.
    #[napi]
    pub fn xorname(&self) -> XorName {
        XorName(*self.0.xorname())
    }

    /// Returns the hex string representation of the address.
    #[napi]
    pub fn to_hex(&self) -> String {
        self.0.to_hex()
    }

    /// Creates a new ArchiveAddress from a hex string.
    #[napi(factory)]
    pub fn from_hex(hex: String) -> Result<Self> {
        autonomi::files::archive_public::ArchiveAddress::from_hex(&hex)
            .map(Self)
            .map_err(map_error)
    }
}

/// A wallet for interacting with the network's payment system
#[napi]
pub struct Wallet(autonomi::Wallet);

#[napi]
impl Wallet {
    /// Convenience function that creates a new Wallet with a random EthereumWallet.
    pub fn new_with_random_wallet(network: autonomi::Network) -> Self {
        Wallet(autonomi::Wallet::new_with_random_wallet(network))
    }

    /// Creates a new Wallet based on the given Ethereum private key. It will fail with Error::PrivateKeyInvalid if private_key is invalid.
    #[napi(factory)]
    pub fn new_from_private_key(network: &Network, private_key: String) -> Result<Self> {
        let wallet = autonomi::Wallet::new_from_private_key(network.0.clone(), &private_key)
            .map_err(map_error)?;

        Ok(Self(wallet))
    }

    /// Returns a string representation of the wallet's address
    #[napi]
    pub fn address(&self) -> String {
        self.0.address().to_string()
    }

    /// Returns the `Network` of this wallet.
    pub fn network(&self) -> Network {
        Network(self.0.network().clone())
    }

    /// Returns the raw balance of payment tokens in the wallet
    #[napi]
    pub async fn balance(&self) -> Result<String> {
        let balance = self.0.balance_of_tokens().await.map_err(map_error)?;

        Ok(balance.to_string())
    }

    /// Returns the current balance of gas tokens in the wallet
    #[napi]
    pub async fn balance_of_gas(&self) -> Result<String> {
        let balance = self.0.balance_of_gas_tokens().await.map_err(map_error)?;

        Ok(balance.to_string())
    }

    /// Sets the transaction configuration for the wallet.
    #[napi]
    pub fn set_transaction_config(&mut self, config: &TransactionConfig) {
        self.0.set_transaction_config(config.0.clone())
    }
}

/// Transaction configuration for wallets
#[napi]
pub struct TransactionConfig(autonomi::TransactionConfig);

#[napi]
impl TransactionConfig {
    /// Use the current market price for fee per gas. WARNING: This can result in unexpected high gas fees!
    #[napi(factory)]
    pub fn auto() -> Self {
        Self(autonomi::TransactionConfig {
            max_fee_per_gas: autonomi::MaxFeePerGas::Auto,
        })
    }

    /// Use the current market price for fee per gas, but with an upper limit.
    #[napi(factory)]
    pub fn limited_auto(limit: BigInt) -> Result<Self> {
        let (_signed, value, lossless) = limit.get_u128();
        if !lossless {
            return Err(napi::Error::new(
                Status::InvalidArg,
                "expected limit to fit in a u128",
            ));
        }

        Ok(Self(autonomi::TransactionConfig {
            max_fee_per_gas: autonomi::MaxFeePerGas::LimitedAuto(value),
        }))
    }

    /// Use no max fee per gas. WARNING: This can result in unexpected high gas fees!
    #[napi(factory)]
    pub fn unlimited() -> Self {
        Self(autonomi::TransactionConfig {
            max_fee_per_gas: autonomi::MaxFeePerGas::Unlimited,
        })
    }

    /// Use a custom max fee per gas in WEI.
    #[napi(factory)]
    pub fn custom(fee: BigInt) -> Result<Self> {
        let (_signed, value, lossless) = fee.get_u128();
        if !lossless {
            return Err(napi::Error::new(
                Status::InvalidArg,
                "expected fee to fit in a u128",
            ));
        }

        Ok(Self(autonomi::TransactionConfig {
            max_fee_per_gas: autonomi::MaxFeePerGas::Custom(value),
        }))
    }
}

/// Options for making payments on the network
#[napi]
pub struct PaymentOption(autonomi::client::payment::PaymentOption);

#[napi]
impl PaymentOption {
    #[napi(factory)]
    pub fn from_wallet(wallet: &Wallet) -> Self {
        Self(autonomi::client::payment::PaymentOption::from(&wallet.0))
    }

    #[napi(factory)]
    pub fn from_receipt() -> Self {
        unimplemented!()
    }
}

#[napi]
pub struct Network(autonomi::Network);

#[napi]
impl Network {
    #[napi(constructor)]
    pub fn new(local: bool) -> Result<Self> {
        let network = autonomi::Network::new(local).map_err(map_error)?;
        Ok(Self(network))
    }
}

#[napi]
pub struct PublicKey(autonomi::PublicKey);

#[napi]
impl PublicKey {
    /// Returns a byte string representation of the public key.
    #[napi]
    pub fn to_bytes(&self) -> Uint8Array {
        Uint8Array::from(self.0.to_bytes())
    }

    /// Returns the key with the given representation, if valid.
    #[napi(factory)]
    pub fn from_bytes(bytes: Uint8Array) -> Result<Self> {
        let bytes = uint8_array_to_array(bytes, "bytes")?;
        let key = autonomi::PublicKey::from_bytes(bytes).map_err(map_error)?;
        Ok(Self(key))
    }

    /// Returns the hex string representation of the public key.
    #[napi]
    pub fn to_hex(&self) -> String {
        self.0.to_hex()
    }

    /// Creates a new PublicKey from a hex string.
    #[napi(factory)]
    pub fn from_hex(hex: String) -> Result<Self> {
        let key = autonomi::PublicKey::from_hex(&hex).map_err(map_error)?;
        Ok(Self(key))
    }
}

#[napi]
pub struct SecretKey(autonomi::SecretKey);

#[napi]
impl SecretKey {
    /// Generate a random SecretKey
    #[napi(factory)]
    pub fn random() -> Self {
        Self(autonomi::SecretKey::random())
    }

    /// Returns the public key corresponding to this secret key.
    #[napi]
    pub fn public_key(&self) -> PublicKey {
        PublicKey(self.0.public_key())
    }

    /// Converts the secret key to big endian bytes
    #[napi]
    pub fn to_bytes(&self) -> Uint8Array {
        Uint8Array::from(self.0.to_bytes())
    }

    /// Deserialize from big endian bytes
    #[napi(factory)]
    pub fn from_bytes(bytes: Uint8Array) -> Result<Self> {
        let bytes = uint8_array_to_array(bytes, "bytes")?;
        let key = autonomi::SecretKey::from_bytes(bytes).map_err(map_error)?;
        Ok(Self(key))
    }

    /// Returns the hex string representation of the secret key.
    #[napi]
    pub fn to_hex(&self) -> String {
        self.0.to_hex()
    }

    /// Creates a new SecretKey from a hex string.
    #[napi(factory)]
    pub fn from_hex(hex: String) -> Result<Self> {
        let key = autonomi::SecretKey::from_hex(&hex).map_err(map_error)?;
        Ok(Self(key))
    }
}

#[napi]
pub struct GraphEntry(autonomi::GraphEntry);

#[napi]
impl GraphEntry {
    /// Create a new graph entry, signing it with the provided secret key.
    #[napi(constructor)]
    pub fn new(
        owner: &SecretKey,
        parents: Vec<&PublicKey>,
        content: Uint8Array,
        descendants: Vec<(&PublicKey, Uint8Array)>,
    ) -> Result<Self> {
        let content: [u8; 32] = uint8_array_to_array(content, "content")?;

        let parents = parents.iter().map(|p| p.0).collect();

        let descendants = descendants
            .iter()
            .map(|(pk, content)| {
                let content_array: [u8; 32] = uint8_array_to_array(content.clone(), "content")?;
                Ok((pk.0, content_array))
            })
            .collect::<Result<Vec<(autonomi::PublicKey, [u8; 32])>>>()?;

        Ok(Self(autonomi::GraphEntry::new(
            &owner.0,
            parents,
            content,
            descendants,
        )))
    }

    /// Create a new graph entry with the signature already calculated.
    #[napi(factory)]
    pub fn new_with_signature(
        owner: &PublicKey,
        parents: Vec<&PublicKey>,
        content: Uint8Array,
        descendants: Vec<(&PublicKey, Uint8Array)>,
        signature: Uint8Array,
    ) -> Result<Self> {
        let content: [u8; 32] = uint8_array_to_array(content, "content")?;

        let parents = parents.iter().map(|p| p.0).collect();

        let descendants_result: Result<Vec<(autonomi::PublicKey, [u8; 32])>> = descendants
            .iter()
            .map(|(pk, content)| {
                let content_array: [u8; 32] = uint8_array_to_array(content.clone(), "content")?;
                Ok((pk.0, content_array))
            })
            .collect();

        let descendants = descendants_result?;

        let signature = uint8_array_to_array(signature, "signature")?;
        let signature = Signature::from_bytes(signature).map_err(map_error)?;

        Ok(Self(autonomi::GraphEntry::new_with_signature(
            owner.0,
            parents,
            content,
            descendants,
            signature,
        )))
    }

    /// Get the address of the graph entry
    #[napi]
    pub fn address(&self) -> GraphEntryAddress {
        GraphEntryAddress(self.0.address())
    }

    /// Get the owner of the graph entry
    #[napi]
    pub fn owner(&self) -> PublicKey {
        PublicKey(self.0.owner)
    }

    /// Get the parents of the graph entry
    #[napi]
    pub fn parents(&self) -> Vec<PublicKey> {
        self.0.parents.iter().map(|p| PublicKey(*p)).collect()
    }

    /// Get the content of the graph entry
    #[napi]
    pub fn content(&self) -> Buffer {
        Buffer::from(self.0.content.to_vec())
    }

    /// Get the descendants of the graph entry
    #[napi]
    pub fn descendants(&self) -> Vec<tuple_result::GraphEntryDescendant> {
        self.0
            .descendants
            .iter()
            .map(|(pk, data)| tuple_result::GraphEntryDescendant {
                public_key: *pk,
                content: *data,
            })
            .collect()
    }

    /// Get the bytes that were signed for this graph entry
    #[napi]
    pub fn bytes_for_signature(&self) -> Buffer {
        Buffer::from(self.0.bytes_for_signature())
    }

    /// Verifies if the graph entry has a valid signature
    #[napi]
    pub fn verify_signature(&self) -> bool {
        self.0.verify_signature()
    }

    /// Size of the graph entry
    #[napi]
    pub fn size(&self) -> usize {
        self.0.size()
    }

    #[napi(getter)]
    pub fn signature(&self) -> Uint8Array {
        Uint8Array::from(self.0.signature.to_bytes())
    }

    /// Returns true if the graph entry is too big
    #[napi]
    pub fn is_too_big(&self) -> bool {
        self.0.is_too_big()
    }
}

#[napi]
pub struct Pointer(autonomi::Pointer);

#[napi]
impl Pointer {
    /// Create a new pointer, signing it with the provided secret key.
    /// This pointer would be stored on the network at the provided key's public key.
    /// There can only be one pointer at a time at the same address (one per key).
    #[napi(constructor)]
    pub fn new(owner: &SecretKey, counter: BigInt, target: &PointerTarget) -> Result<Self> {
        let counter = big_int_to_u64(counter, "counter")?;
        Ok(Pointer(autonomi::Pointer::new(
            &owner.0,
            counter,
            target.0.clone(),
        )))
    }

    /// Get the address of the pointer
    #[napi]
    pub fn address(&self) -> PointerAddress {
        PointerAddress(self.0.address())
    }

    /// Get the owner of the pointer
    #[napi]
    pub fn owner(&self) -> PublicKey {
        PublicKey(*self.0.owner())
    }

    /// Get the target of the pointer
    #[napi]
    pub fn target(&self) -> PointerTarget {
        PointerTarget(self.0.target().clone())
    }

    /// Get the bytes that were signed for this pointer
    #[napi]
    pub fn bytes_for_signature(&self) -> Buffer {
        Buffer::from(self.0.bytes_for_signature())
    }

    /// Get the xorname of the pointer target
    #[napi]
    pub fn xorname(&self) -> XorName {
        XorName(self.0.xorname())
    }

    /// Get the counter of the pointer, the higher the counter, the more recent the pointer is
    /// Similarly to counter CRDTs only the latest version (highest counter) of the pointer is kept on the network
    #[napi]
    pub fn counter(&self) -> u64 {
        self.0.counter()
    }

    /// Verifies if the pointer has a valid signature
    #[napi]
    pub fn verify_signature(&self) -> bool {
        self.0.verify_signature()
    }

    /// Size of the pointer
    #[napi]
    pub fn size() -> usize {
        autonomi::Pointer::size()
    }
}

#[napi]
pub struct PointerTarget(autonomi::pointer::PointerTarget);

#[napi]
impl PointerTarget {
    /// Returns the xorname of the target
    #[napi]
    pub fn xorname(&self) -> XorName {
        XorName(self.0.xorname())
    }

    /// Returns the hex string representation of the target
    #[napi]
    pub fn to_hex(&self) -> String {
        self.0.to_hex()
    }

    /// Creates a new PointerTarget from a ChunkAddress
    #[napi(factory, js_name = "ChunkAddress")]
    pub fn from_chunk_address(addr: &ChunkAddress) -> Self {
        Self(autonomi::pointer::PointerTarget::ChunkAddress(addr.0))
    }

    /// Creates a new PointerTarget from a GraphEntryAddress
    #[napi(factory, js_name = "GraphEntryAddress")]
    pub fn from_graph_entry_address(addr: &GraphEntryAddress) -> Self {
        Self(autonomi::pointer::PointerTarget::GraphEntryAddress(addr.0))
    }

    /// Creates a new PointerTarget from a PointerAddress
    #[napi(factory, js_name = "PointerAddress")]
    pub fn from_pointer_address(addr: &PointerAddress) -> Self {
        Self(autonomi::pointer::PointerTarget::PointerAddress(addr.0))
    }

    /// Creates a new PointerTarget from a ScratchpadAddress
    #[napi(factory, js_name = "ScratchpadAddress")]
    pub fn from_scratchpad_address(addr: &ScratchpadAddress) -> Self {
        Self(autonomi::pointer::PointerTarget::ScratchpadAddress(addr.0))
    }
}

#[napi]
pub struct PointerAddress(autonomi::PointerAddress);

#[napi]
impl PointerAddress {
    /// Creates a new PointerAddress.
    #[napi(constructor)]
    pub fn new(owner: &PublicKey) -> Self {
        Self(autonomi::PointerAddress::new(owner.0))
    }

    /// Return the network name of the pointer.
    /// This is used to locate the pointer on the network.
    #[napi]
    pub fn xorname(&self) -> XorName {
        XorName(self.0.xorname())
    }

    /// Return the owner.
    #[napi]
    pub fn owner(&self) -> PublicKey {
        PublicKey(*self.0.owner())
    }

    /// Serialize this PointerAddress into a hex-encoded string.
    #[napi]
    pub fn to_hex(&self) -> String {
        self.0.to_hex()
    }

    /// Parse a hex-encoded string into a PointerAddress.
    #[napi(factory)]
    pub fn from_hex(hex: String) -> Result<Self> {
        let addr = autonomi::PointerAddress::from_hex(&hex).map_err(map_error)?;
        Ok(Self(addr))
    }
}

#[napi]
pub struct Scratchpad(autonomi::Scratchpad);

#[napi]
impl Scratchpad {
    /// Create a new scratchpad, signing it with the provided secret key.
    #[napi(constructor)]
    pub fn new(
        owner: &SecretKey,
        data_encoding: BigInt, // `u64`
        data: Buffer,
        counter: BigInt, // `u64`
    ) -> Result<Self> {
        let data_encoding = big_int_to_u64(data_encoding, "data_encoding")?;
        let counter = big_int_to_u64(counter, "counter")?;
        let data = Bytes::copy_from_slice(&data);

        Ok(Self(autonomi::Scratchpad::new(
            &owner.0,
            data_encoding,
            &data,
            counter,
        )))
    }

    /// Get the address of the scratchpad
    #[napi]
    pub fn address(&self) -> ScratchpadAddress {
        ScratchpadAddress(*self.0.address())
    }

    /// Get the owner of the scratchpad
    #[napi]
    pub fn owner(&self) -> PublicKey {
        PublicKey(*self.0.owner())
    }

    /// Get the data encoding (content type) of the scratchpad
    #[napi]
    pub fn data_encoding(&self) -> u64 {
        self.0.data_encoding()
    }

    /// Decrypt the data of the scratchpad
    #[napi]
    pub fn decrypt_data(&self, key: &SecretKey) -> Result<Buffer> {
        let data = self.0.decrypt_data(&key.0).map_err(map_error)?;
        Ok(Buffer::from(data.to_vec()))
    }

    /// Get the counter of the scratchpad
    #[napi]
    pub fn counter(&self) -> u64 {
        self.0.counter()
    }

    /// Verify the signature of the scratchpad
    #[napi]
    pub fn verify_signature(&self) -> bool {
        self.0.verify_signature()
    }
}

#[napi]
pub struct ScratchpadAddress(autonomi::ScratchpadAddress);

#[napi]
impl ScratchpadAddress {
    /// Creates a new ScratchpadAddress.
    #[napi(constructor)]
    pub fn new(owner: &PublicKey) -> Self {
        Self(autonomi::ScratchpadAddress::new(owner.0))
    }

    /// Return the network name of the scratchpad.
    /// This is used to locate the scratchpad on the network.
    #[napi]
    pub fn xorname(&self) -> XorName {
        XorName(self.0.xorname())
    }

    /// Return the owner.
    #[napi]
    pub fn owner(&self) -> PublicKey {
        PublicKey(*self.0.owner())
    }

    /// Serialize this ScratchpadAddress into a hex-encoded string.
    #[napi]
    pub fn to_hex(&self) -> String {
        self.0.to_hex()
    }

    /// Parse a hex-encoded string into a ScratchpadAddress.
    #[napi(factory)]
    pub fn from_hex(hex: String) -> Result<Self> {
        let addr = autonomi::ScratchpadAddress::from_hex(&hex).map_err(map_error)?;
        Ok(Self(addr))
    }
}

#[napi]
pub struct DataMapChunk(autonomi::data::private::DataMapChunk);

#[napi]
pub struct PrivateArchiveDataMap(autonomi::files::archive_private::PrivateArchiveDataMap);

#[napi]
impl PrivateArchiveDataMap {
    /// Serialize this PrivateArchiveDataMap into a hex-encoded string.
    #[napi]
    pub fn to_hex(&self) -> String {
        self.0.to_hex()
    }

    /// Parse a hex-encoded string into a PrivateArchiveDataMap.
    #[napi(factory)]
    pub fn from_hex(hex: String) -> Result<Self> {
        let data_map = autonomi::files::archive_private::PrivateArchiveDataMap::from_hex(&hex)
            .map_err(map_error)?;
        Ok(Self(data_map))
    }
}

#[napi]
pub struct PrivateArchive(autonomi::files::PrivateArchive);

#[napi]
impl PrivateArchive {
    /// Create a new empty local archive
    #[napi(constructor)]
    #[allow(clippy::new_without_default, reason = "`Default` not useful")]
    pub fn new() -> Self {
        Self(autonomi::files::PrivateArchive::new())
    }

    /// Add a file to a local archive
    #[napi]
    pub fn add_file(&mut self, path: String, data_map: &DataMapChunk, metadata: &Metadata) {
        self.0
            .add_file(PathBuf::from(path), data_map.0.clone(), metadata.0.clone());
    }

    /// Rename a file in an archive
    #[napi]
    pub fn rename_file(&mut self, old_path: String, new_path: String) -> Result<()> {
        self.0
            .rename_file(&PathBuf::from(old_path), &PathBuf::from(new_path))
            .map_err(map_error)
    }

    /// List all files in the archive with their metadata
    #[napi]
    pub fn files(&self) -> Vec<tuple_result::ArchiveFile> {
        self.0
            .files()
            .into_iter()
            .map(|(path, meta)| tuple_result::ArchiveFile {
                path: path.to_string_lossy().to_string(),
                created: BigInt::from(meta.created),
                modified: BigInt::from(meta.modified),
                size: BigInt::from(meta.size),
                extra: meta.extra.clone(),
            })
            .collect()
    }

    /// List all data maps of the files in the archive
    #[napi]
    pub fn data_maps(&self) -> Vec<DataMapChunk> {
        self.0.data_maps().into_iter().map(DataMapChunk).collect()
    }

    /// Convert the archive to bytes
    #[napi]
    pub fn to_bytes(&self) -> Result<Buffer> {
        let bytes = self.0.to_bytes().map_err(|e| {
            napi::Error::new(
                Status::GenericFailure,
                format!("Failed to serialize archive: {e:?}"),
            )
        })?;

        Ok(Buffer::from(bytes.to_vec()))
    }

    /// Create an archive from bytes
    #[napi(factory)]
    pub fn from_bytes(data: Buffer) -> Result<Self> {
        let bytes = Bytes::from(data.as_ref().to_vec());
        let archive = autonomi::files::PrivateArchive::from_bytes(bytes).map_err(|e| {
            napi::Error::new(
                Status::GenericFailure,
                format!("Failed to deserialize archive: {e:?}"),
            )
        })?;

        Ok(Self(archive))
    }

    /// Merge with another archive
    #[napi]
    pub fn merge(&mut self, other: &PrivateArchive) {
        self.0.merge(&other.0);
    }
}

#[napi]
pub struct VaultSecretKey(autonomi::vault::VaultSecretKey);

#[napi]
pub struct UserData(autonomi::vault::UserData);

#[napi]
pub struct VaultContentType(autonomi::vault::VaultContentType);

/// File metadata
#[napi]
pub struct Metadata(autonomi::files::Metadata);

#[napi]
impl Metadata {
    /// Create a new metadata struct with the current time as uploaded, created and modified.
    #[napi(factory)]
    pub fn new_with_size(size: BigInt) -> Result<Self> {
        let size = big_int_to_u64(size, "size")?;
        Ok(Self(autonomi::files::Metadata::new_with_size(size)))
    }

    /// Create new metadata with all custom fields
    #[napi(factory)]
    pub fn with_custom_fields(
        created: BigInt,
        modified: BigInt,
        size: BigInt,
        extra: Option<String>,
    ) -> Result<Self> {
        let created = big_int_to_u64(created, "created")?;
        let modified = big_int_to_u64(modified, "modified")?;
        let size = big_int_to_u64(size, "size")?;

        Ok(Self(autonomi::files::Metadata {
            created,
            modified,
            size,
            extra,
        }))
    }

    /// Create a new empty metadata struct with zeros
    #[napi(factory)]
    pub fn empty() -> Self {
        Self(autonomi::files::Metadata::empty())
    }

    /// Get the creation timestamp
    #[napi(getter)]
    pub fn created(&self) -> u64 {
        self.0.created
    }

    /// Get the modification timestamp
    #[napi(getter)]
    pub fn modified(&self) -> u64 {
        self.0.modified
    }

    /// Get the file size
    #[napi(getter)]
    pub fn size(&self) -> u64 {
        self.0.size
    }

    /// Get the extra metadata
    #[napi(getter)]
    pub fn extra(&self) -> Option<String> {
        self.0.extra.clone()
    }
}

#[napi]
pub struct RegisterAddress(autonomi::register::RegisterAddress);

#[napi]
impl RegisterAddress {
    /// Creates a new RegisterAddress.
    #[napi(constructor)]
    pub fn new(owner: &PublicKey) -> Self {
        Self(autonomi::register::RegisterAddress::new(owner.0))
    }

    /// Get the owner of the register
    #[napi]
    pub fn owner(&self) -> PublicKey {
        PublicKey(self.0.owner())
    }

    /// Get the underlying graph root address
    #[napi]
    pub fn to_underlying_graph_root(&self) -> GraphEntryAddress {
        GraphEntryAddress(self.0.to_underlying_graph_root())
    }

    /// Get the underlying head pointer address
    #[napi]
    pub fn to_underlying_head_pointer(&self) -> PointerAddress {
        PointerAddress(self.0.to_underlying_head_pointer())
    }

    /// Serialize this RegisterAddress into a hex-encoded string.
    #[napi]
    pub fn to_hex(&self) -> String {
        self.0.to_hex()
    }

    /// Parse a hex-encoded string into a RegisterAddress.
    #[napi(factory)]
    pub fn from_hex(hex: String) -> Result<Self> {
        let addr = autonomi::register::RegisterAddress::from_hex(&hex).map_err(map_error)?;
        Ok(Self(addr))
    }
}

#[napi]
pub struct RegisterHistory(Mutex<autonomi::register::RegisterHistory>);

#[napi]
impl RegisterHistory {
    // Somehow without this stub, NAPI-RS fails to create this object with an error:
    // error: `Failed to get constructor of class`
    #[allow(clippy::new_without_default, reason = "`Default` not useful")]
    #[napi(constructor)]
    pub fn new() -> Self {
        unimplemented!()
    }

    /// Fetch and go to the next register value from the history.
    ///
    /// Returns null when we reached the end.
    #[napi]
    pub async fn next(&self) -> Result<Option<Uint8Array>> {
        self.0
            .lock()
            .await
            .next()
            .await
            .map(|v| v.map(Uint8Array::from))
            .map_err(map_error)
    }

    /// Get all the register values from the history, starting from the first to the latest entry
    #[napi]
    pub async fn collect(&self) -> Result<Vec<Uint8Array>> {
        let values = self.0.lock().await.collect().await.map_err(map_error)?;
        let values = values.into_iter().map(Uint8Array::from).collect();
        Ok(values)
    }
}

#[napi]
pub struct PublicArchive(autonomi::files::PublicArchive);

#[napi]
impl PublicArchive {
    /// Create a new empty local archive
    #[napi(constructor)]
    #[allow(clippy::new_without_default, reason = "`Default` not useful")]
    pub fn new() -> Self {
        Self(autonomi::files::PublicArchive::new())
    }

    /// Add a file to a local archive
    #[napi]
    pub fn add_file(&mut self, path: String, data_addr: &DataAddress, metadata: &Metadata) {
        self.0
            .add_file(PathBuf::from(path), data_addr.0, metadata.0.clone());
    }

    /// Rename a file in an archive
    #[napi]
    pub fn rename_file(&mut self, old_path: String, new_path: String) -> Result<()> {
        self.0
            .rename_file(&PathBuf::from(old_path), &PathBuf::from(new_path))
            .map_err(map_error)
    }

    /// List all files in the archive with their metadata
    #[napi]
    pub fn files(&self) -> Vec<tuple_result::ArchiveFile> {
        self.0
            .files()
            .into_iter()
            .map(|(path, meta)| tuple_result::ArchiveFile {
                path: path.to_string_lossy().to_string(),
                created: BigInt::from(meta.created),
                modified: BigInt::from(meta.modified),
                size: BigInt::from(meta.size),
                extra: meta.extra.clone(),
            })
            .collect()
    }

    /// List all data addresses of the files in the archive
    #[napi]
    pub fn addresses(&self) -> Vec<DataAddress> {
        self.0.addresses().into_iter().map(DataAddress).collect()
    }

    /// Convert the archive to bytes
    #[napi]
    pub fn to_bytes(&self) -> Result<Buffer> {
        let bytes = self.0.to_bytes().map_err(|e| {
            napi::Error::new(
                Status::GenericFailure,
                format!("Failed to serialize archive: {e:?}"),
            )
        })?;

        Ok(Buffer::from(bytes.to_vec()))
    }

    /// Create an archive from bytes
    #[napi(factory)]
    pub fn from_bytes(data: Buffer) -> Result<Self> {
        let bytes = Bytes::from(data.as_ref().to_vec());
        let archive = autonomi::files::PublicArchive::from_bytes(bytes).map_err(|e| {
            napi::Error::new(
                Status::GenericFailure,
                format!("Failed to deserialize archive: {e:?}"),
            )
        })?;

        Ok(Self(archive))
    }

    /// Merge with another archive
    #[napi]
    pub fn merge(&mut self, other: &PublicArchive) {
        self.0.merge(&other.0);
    }
}