@ar.io/sdk 3.10.2 → 3.11.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +52 -0
  2. package/bundles/web.bundle.min.js +140 -132
  3. package/lib/cjs/cli/cli.js +137 -122
  4. package/lib/cjs/cli/commands/readCommands.js +6 -0
  5. package/lib/cjs/cli/options.js +12 -0
  6. package/lib/cjs/cli/utils.js +40 -11
  7. package/lib/cjs/common/ant-versions.js +5 -5
  8. package/lib/cjs/common/ant.js +5 -5
  9. package/lib/cjs/common/index.js +2 -0
  10. package/lib/cjs/common/io.js +106 -1
  11. package/lib/cjs/common/turbo.js +208 -0
  12. package/lib/cjs/common/wayfinder/gateways/trusted-gateways.js +106 -0
  13. package/lib/cjs/common/wayfinder/gateways.js +86 -0
  14. package/lib/cjs/common/wayfinder/index.js +44 -0
  15. package/lib/cjs/common/wayfinder/routers/priority.js +29 -0
  16. package/lib/cjs/common/wayfinder/routers/priority.test.js +155 -0
  17. package/lib/cjs/common/wayfinder/routers/random.js +23 -0
  18. package/lib/cjs/common/wayfinder/routers/random.test.js +25 -0
  19. package/lib/cjs/common/wayfinder/routers/simple-cache.js +25 -0
  20. package/lib/cjs/common/wayfinder/routers/simple-cache.test.js +41 -0
  21. package/lib/cjs/common/wayfinder/routers/static.js +14 -0
  22. package/lib/cjs/common/wayfinder/routers/static.test.js +14 -0
  23. package/lib/cjs/common/wayfinder/verification/data-root-verifier.js +139 -0
  24. package/lib/cjs/common/wayfinder/verification/hash-verifier.js +50 -0
  25. package/lib/cjs/common/wayfinder/wayfinder.js +596 -0
  26. package/lib/cjs/common/wayfinder/wayfinder.test.js +500 -0
  27. package/lib/cjs/types/ant.js +12 -1
  28. package/lib/cjs/types/index.js +1 -0
  29. package/lib/cjs/types/io.js +1 -1
  30. package/lib/cjs/types/wayfinder.js +3 -0
  31. package/lib/cjs/utils/ao.js +42 -0
  32. package/lib/cjs/utils/hash.js +56 -0
  33. package/lib/cjs/utils/random.js +30 -0
  34. package/lib/cjs/utils/url.js +28 -0
  35. package/lib/cjs/utils/url.test.js +24 -0
  36. package/lib/cjs/utils/utils.test.js +8 -8
  37. package/lib/cjs/version.js +1 -1
  38. package/lib/cjs/web/index.js +3 -1
  39. package/lib/esm/cli/cli.js +138 -123
  40. package/lib/esm/cli/commands/readCommands.js +5 -0
  41. package/lib/esm/cli/options.js +12 -0
  42. package/lib/esm/cli/utils.js +39 -11
  43. package/lib/esm/common/ant-versions.js +5 -5
  44. package/lib/esm/common/ant.js +5 -5
  45. package/lib/esm/common/index.js +2 -0
  46. package/lib/esm/common/io.js +106 -1
  47. package/lib/esm/common/turbo.js +200 -0
  48. package/lib/esm/common/wayfinder/gateways/trusted-gateways.js +102 -0
  49. package/lib/esm/common/wayfinder/gateways.js +80 -0
  50. package/lib/esm/common/wayfinder/index.js +28 -0
  51. package/lib/esm/common/wayfinder/routers/priority.js +25 -0
  52. package/lib/esm/common/wayfinder/routers/priority.test.js +153 -0
  53. package/lib/esm/common/wayfinder/routers/random.js +19 -0
  54. package/lib/esm/common/wayfinder/routers/random.test.js +23 -0
  55. package/lib/esm/common/wayfinder/routers/simple-cache.js +21 -0
  56. package/lib/esm/common/wayfinder/routers/simple-cache.test.js +39 -0
  57. package/lib/esm/common/wayfinder/routers/static.js +10 -0
  58. package/lib/esm/common/wayfinder/routers/static.test.js +12 -0
  59. package/lib/esm/common/wayfinder/verification/data-root-verifier.js +130 -0
  60. package/lib/esm/common/wayfinder/verification/hash-verifier.js +46 -0
  61. package/lib/esm/common/wayfinder/wayfinder.js +584 -0
  62. package/lib/esm/common/wayfinder/wayfinder.test.js +495 -0
  63. package/lib/esm/types/ant.js +11 -0
  64. package/lib/esm/types/index.js +1 -0
  65. package/lib/esm/types/io.js +1 -1
  66. package/lib/esm/types/wayfinder.js +2 -0
  67. package/lib/esm/utils/ao.js +42 -0
  68. package/lib/esm/utils/hash.js +50 -0
  69. package/lib/esm/utils/random.js +26 -0
  70. package/lib/esm/utils/url.js +24 -0
  71. package/lib/esm/utils/url.test.js +19 -0
  72. package/lib/esm/utils/utils.test.js +1 -1
  73. package/lib/esm/version.js +1 -1
  74. package/lib/esm/web/index.js +1 -1
  75. package/lib/types/cli/commands/antCommands.d.ts +3 -3
  76. package/lib/types/cli/commands/arnsPurchaseCommands.d.ts +1 -1
  77. package/lib/types/cli/commands/gatewayWriteCommands.d.ts +9 -9
  78. package/lib/types/cli/commands/readCommands.d.ts +2 -0
  79. package/lib/types/cli/commands/transfer.d.ts +3 -3
  80. package/lib/types/cli/options.d.ts +9 -0
  81. package/lib/types/cli/types.d.ts +3 -0
  82. package/lib/types/cli/utils.d.ts +4 -0
  83. package/lib/types/common/ant-versions.d.ts +3 -6
  84. package/lib/types/common/index.d.ts +1 -0
  85. package/lib/types/common/io.d.ts +13 -8
  86. package/lib/types/common/turbo.d.ts +62 -0
  87. package/lib/types/common/wayfinder/gateways/trusted-gateways.d.ts +51 -0
  88. package/lib/types/common/wayfinder/gateways.d.ts +53 -0
  89. package/lib/types/common/wayfinder/index.d.ts +23 -0
  90. package/lib/types/common/wayfinder/routers/priority.d.ts +29 -0
  91. package/lib/types/common/wayfinder/routers/priority.test.d.ts +1 -0
  92. package/lib/types/common/wayfinder/routers/random.d.ts +27 -0
  93. package/lib/types/common/wayfinder/routers/random.test.d.ts +1 -0
  94. package/lib/types/common/wayfinder/routers/simple-cache.d.ts +28 -0
  95. package/lib/types/common/wayfinder/routers/simple-cache.test.d.ts +1 -0
  96. package/lib/types/common/wayfinder/routers/static.d.ts +24 -0
  97. package/lib/types/common/wayfinder/routers/static.test.d.ts +1 -0
  98. package/lib/types/common/wayfinder/verification/data-root-verifier.d.ts +31 -0
  99. package/lib/types/common/wayfinder/verification/hash-verifier.d.ts +27 -0
  100. package/lib/types/common/wayfinder/wayfinder.d.ts +265 -0
  101. package/lib/types/common/wayfinder/wayfinder.test.d.ts +1 -0
  102. package/lib/types/types/ant.d.ts +53 -1
  103. package/lib/types/types/common.d.ts +7 -2
  104. package/lib/types/types/index.d.ts +1 -0
  105. package/lib/types/types/io.d.ts +23 -6
  106. package/lib/types/types/wayfinder.d.ts +62 -0
  107. package/lib/types/utils/ao.d.ts +1 -12
  108. package/lib/types/utils/hash.d.ts +4 -0
  109. package/lib/types/utils/random.d.ts +7 -0
  110. package/lib/types/utils/url.d.ts +19 -0
  111. package/lib/types/utils/url.test.d.ts +1 -0
  112. package/lib/types/version.d.ts +1 -1
  113. package/lib/types/web/index.d.ts +1 -1
  114. package/package.json +5 -3
@@ -21,10 +21,12 @@ const constants_js_1 = require("../constants.js");
21
21
  const index_js_1 = require("../types/index.js");
22
22
  const ao_js_1 = require("../utils/ao.js");
23
23
  const arweave_js_1 = require("../utils/arweave.js");
24
+ const ant_js_1 = require("./ant.js");
24
25
  const arweave_js_2 = require("./arweave.js");
25
26
  const ao_process_js_1 = require("./contracts/ao-process.js");
26
27
  const error_js_1 = require("./error.js");
27
28
  const faucet_js_1 = require("./faucet.js");
29
+ const turbo_js_1 = require("./turbo.js");
28
30
  class ARIO {
29
31
  // Implementation
30
32
  static init(config) {
@@ -93,6 +95,7 @@ class ARIOReadable {
93
95
  process;
94
96
  epochSettings;
95
97
  arweave;
98
+ paymentProvider; // TODO: this could be an array/map of payment providers
96
99
  constructor(config) {
97
100
  this.arweave = config?.arweave ?? arweave_js_2.defaultArweave;
98
101
  if (config === undefined || Object.keys(config).length === 0) {
@@ -111,6 +114,9 @@ class ARIOReadable {
111
114
  else {
112
115
  throw new error_js_1.InvalidContractConfigurationError();
113
116
  }
117
+ this.paymentProvider = turbo_js_1.TurboArNSPaymentFactory.init({
118
+ paymentUrl: config?.paymentUrl,
119
+ });
114
120
  }
115
121
  async getInfo() {
116
122
  return this.process.read({
@@ -442,6 +448,20 @@ class ARIOReadable {
442
448
  // TODO: Can overload this function to refine different types of cost details params
443
449
  async getCostDetails({ intent, type, years, name, quantity, fromAddress, fundFrom, }) {
444
450
  const replacedBuyRecordWithBuyName = intent === 'Buy-Record' ? 'Buy-Name' : intent;
451
+ if (fundFrom === 'turbo') {
452
+ const { mARIO, winc } = await this.paymentProvider.getArNSPriceDetails({
453
+ intent: replacedBuyRecordWithBuyName,
454
+ name,
455
+ quantity,
456
+ type,
457
+ years,
458
+ });
459
+ return {
460
+ tokenCost: +mARIO,
461
+ wincQty: winc,
462
+ discounts: [],
463
+ };
464
+ }
445
465
  const allTags = [
446
466
  { name: 'Action', value: 'Cost-Details' },
447
467
  {
@@ -605,11 +625,48 @@ class ARIOReadable {
605
625
  ],
606
626
  });
607
627
  }
628
+ async resolveArNSName({ name, }) {
629
+ const baseName = name.split('_').pop();
630
+ if (baseName === undefined) {
631
+ throw new Error('Invalid name');
632
+ }
633
+ const undername = name === baseName ? '@' : name.replace(`_${baseName}`, '');
634
+ const nameData = await this.getArNSRecord({ name: baseName });
635
+ const ant = ant_js_1.ANT.init({
636
+ process: new ao_process_js_1.AOProcess({
637
+ ao: this.process.ao,
638
+ processId: nameData.processId,
639
+ }),
640
+ });
641
+ const [owner, antRecord] = await Promise.all([
642
+ ant.getOwner(),
643
+ ant.getRecord({ undername }),
644
+ ]);
645
+ if (antRecord === undefined) {
646
+ throw new Error(`Record for ${undername} not found on ANT.`);
647
+ }
648
+ if (antRecord.ttlSeconds === undefined ||
649
+ antRecord.transactionId === undefined) {
650
+ throw new Error(`Invalid record on ANT. Must have ttlSeconds and transactionId. Record: ${JSON.stringify(antRecord)}`);
651
+ }
652
+ return {
653
+ name: name,
654
+ owner: owner,
655
+ txId: antRecord.transactionId,
656
+ ttlSeconds: antRecord.ttlSeconds,
657
+ priority: antRecord.priority,
658
+ // NOTE: we may want return the actual index of the record based on sorting in case ANT tries to set duplicate priority values to get around undername limits
659
+ processId: nameData.processId,
660
+ undernameLimit: nameData.undernameLimit,
661
+ type: nameData.type,
662
+ };
663
+ }
608
664
  }
609
665
  exports.ARIOReadable = ARIOReadable;
610
666
  class ARIOWriteable extends ARIOReadable {
611
667
  signer;
612
- constructor({ signer, ...config }) {
668
+ paymentProvider;
669
+ constructor({ signer, paymentUrl, ...config }) {
613
670
  if (config === undefined) {
614
671
  super({
615
672
  process: new ao_process_js_1.AOProcess({
@@ -621,6 +678,10 @@ class ARIOWriteable extends ARIOReadable {
621
678
  super(config);
622
679
  }
623
680
  this.signer = (0, ao_js_1.createAoSigner)(signer);
681
+ this.paymentProvider = turbo_js_1.TurboArNSPaymentFactory.init({
682
+ signer: (0, turbo_js_1.isTurboArNSSigner)(signer) ? signer : undefined,
683
+ paymentUrl,
684
+ });
624
685
  }
625
686
  async transfer({ target, qty, }, options) {
626
687
  const { tags = [] } = options || {};
@@ -895,6 +956,18 @@ class ARIOWriteable extends ARIOReadable {
895
956
  });
896
957
  }
897
958
  async buyRecord(params, options) {
959
+ if (params.fundFrom === 'turbo') {
960
+ if (!(this.paymentProvider instanceof turbo_js_1.TurboArNSPaymentProviderAuthenticated)) {
961
+ throw new Error('Turbo funding is not supported for this payment provider');
962
+ }
963
+ return this.paymentProvider.initiateArNSPurchase({
964
+ intent: 'Buy-Name',
965
+ name: params.name,
966
+ years: params.years,
967
+ type: params.type,
968
+ processId: params.processId,
969
+ });
970
+ }
898
971
  const { tags = [] } = options || {};
899
972
  const allTags = [
900
973
  ...tags,
@@ -919,6 +992,15 @@ class ARIOWriteable extends ARIOReadable {
919
992
  * @returns {Promise<AoMessageResult>} The result of the upgrade
920
993
  */
921
994
  async upgradeRecord(params, options) {
995
+ if (params.fundFrom === 'turbo') {
996
+ if (!(this.paymentProvider instanceof turbo_js_1.TurboArNSPaymentProviderAuthenticated)) {
997
+ throw new Error('Turbo funding is not supported for this payment provider');
998
+ }
999
+ return this.paymentProvider.initiateArNSPurchase({
1000
+ intent: 'Upgrade-Name',
1001
+ name: params.name,
1002
+ });
1003
+ }
922
1004
  const { tags = [] } = options || {};
923
1005
  const allTags = [
924
1006
  ...tags,
@@ -941,6 +1023,16 @@ class ARIOWriteable extends ARIOReadable {
941
1023
  * @returns {Promise<AoMessageResult>} The result of the extension
942
1024
  */
943
1025
  async extendLease(params, options) {
1026
+ if (params.fundFrom === 'turbo') {
1027
+ if (!(this.paymentProvider instanceof turbo_js_1.TurboArNSPaymentProviderAuthenticated)) {
1028
+ throw new Error('Turbo funding is not supported for this payment provider');
1029
+ }
1030
+ return this.paymentProvider.initiateArNSPurchase({
1031
+ intent: 'Extend-Lease',
1032
+ name: params.name,
1033
+ years: params.years,
1034
+ });
1035
+ }
944
1036
  const { tags = [] } = options || {};
945
1037
  const allTags = [
946
1038
  ...tags,
@@ -955,6 +1047,16 @@ class ARIOWriteable extends ARIOReadable {
955
1047
  });
956
1048
  }
957
1049
  async increaseUndernameLimit(params, options) {
1050
+ if (params.fundFrom === 'turbo') {
1051
+ if (!(this.paymentProvider instanceof turbo_js_1.TurboArNSPaymentProviderAuthenticated)) {
1052
+ throw new Error('Turbo funding is not supported for this payment provider');
1053
+ }
1054
+ return this.paymentProvider.initiateArNSPurchase({
1055
+ intent: 'Increase-Undername-Limit',
1056
+ quantity: params.increaseCount,
1057
+ name: params.name,
1058
+ });
1059
+ }
958
1060
  const { tags = [] } = options || {};
959
1061
  const allTags = [
960
1062
  ...tags,
@@ -991,6 +1093,9 @@ class ARIOWriteable extends ARIOReadable {
991
1093
  });
992
1094
  }
993
1095
  async requestPrimaryName(params, options) {
1096
+ if (params.fundFrom === 'turbo') {
1097
+ throw new Error('Turbo funding is not yet supported for primary name requests');
1098
+ }
994
1099
  const { tags = [] } = options || {};
995
1100
  const allTags = [
996
1101
  ...tags,
@@ -0,0 +1,208 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TurboArNSPaymentProviderAuthenticated = exports.TurboArNSPaymentProviderUnauthenticated = exports.TurboArNSPaymentFactory = void 0;
4
+ exports.signedRequestHeadersFromSigner = signedRequestHeadersFromSigner;
5
+ exports.isTurboArNSSigner = isTurboArNSSigner;
6
+ /**
7
+ * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
8
+ *
9
+ * Licensed under the Apache License, Version 2.0 (the "License");
10
+ * you may not use this file except in compliance with the License.
11
+ * You may obtain a copy of the License at
12
+ *
13
+ * http://www.apache.org/licenses/LICENSE-2.0
14
+ *
15
+ * Unless required by applicable law or agreed to in writing, software
16
+ * distributed under the License is distributed on an "AS IS" BASIS,
17
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ * See the License for the specific language governing permissions and
19
+ * limitations under the License.
20
+ */
21
+ const arbundles_1 = require("@dha-team/arbundles");
22
+ const uuid_1 = require("uuid");
23
+ const token_js_1 = require("../types/token.js");
24
+ const base64_js_1 = require("../utils/base64.js");
25
+ const http_client_js_1 = require("../utils/http-client.js");
26
+ const url_js_1 = require("../utils/url.js");
27
+ const logger_js_1 = require("./logger.js");
28
+ async function signedRequestHeadersFromSigner({ signer, nonce = (0, uuid_1.v4)(), }) {
29
+ let signature = undefined;
30
+ let publicKey = undefined;
31
+ const signatureType = isWanderArweaveBrowserSigner(signer)
32
+ ? arbundles_1.SignatureConfig.ARWEAVE
33
+ : signer.signatureType;
34
+ // equivalent to window.arweaveWallet
35
+ if (isWanderArweaveBrowserSigner(signer)) {
36
+ signature = (0, base64_js_1.toB64Url)(Buffer.from(await signer.signMessage(Uint8Array.from(Buffer.from(nonce)))));
37
+ }
38
+ else if (signer instanceof arbundles_1.ArconnectSigner) {
39
+ signature = (0, base64_js_1.toB64Url)(Buffer.from(await signer['signer'].signMessage(Uint8Array.from(Buffer.from(nonce)))));
40
+ }
41
+ else if (signer instanceof arbundles_1.ArweaveSigner ||
42
+ signer instanceof arbundles_1.EthereumSigner ||
43
+ signer instanceof arbundles_1.InjectedEthereumSigner) {
44
+ if ('setPublicKey' in signer && signer['publicKey'] === undefined) {
45
+ await signer.setPublicKey();
46
+ }
47
+ signature = (0, base64_js_1.toB64Url)(Buffer.from(await signer.sign(Uint8Array.from(Buffer.from(nonce)))));
48
+ }
49
+ switch (signatureType) {
50
+ case arbundles_1.SignatureConfig.ARWEAVE:
51
+ if (isWanderArweaveBrowserSigner(signer)) {
52
+ publicKey = await signer.getActivePublicKey();
53
+ }
54
+ else if ('setPublicKey' in signer) {
55
+ await signer.setPublicKey();
56
+ publicKey = (0, base64_js_1.toB64Url)(signer.publicKey);
57
+ }
58
+ break;
59
+ case arbundles_1.SignatureConfig.ETHEREUM:
60
+ if ('publicKey' in signer) {
61
+ publicKey = '0x' + signer.publicKey.toString('hex');
62
+ }
63
+ else {
64
+ throw new Error('Public key not found');
65
+ }
66
+ break;
67
+ // TODO: solana sig support
68
+ // case SignatureConfig.SOLANA:
69
+ // case SignatureConfig.ED25519:
70
+ default:
71
+ throw new Error(`Unsupported signer type for signing requests: ${signatureType}`);
72
+ }
73
+ if (publicKey === undefined || signature === undefined) {
74
+ throw new Error('Public key or signature not found');
75
+ }
76
+ return {
77
+ 'x-public-key': publicKey,
78
+ 'x-nonce': nonce,
79
+ 'x-signature': signature,
80
+ 'x-signature-type': signatureType,
81
+ };
82
+ }
83
+ class TurboArNSPaymentFactory {
84
+ static init(config) {
85
+ const { signer, paymentUrl, axios, logger } = config ?? {};
86
+ if (signer !== undefined) {
87
+ return new TurboArNSPaymentProviderAuthenticated({
88
+ signer,
89
+ paymentUrl,
90
+ axios,
91
+ logger,
92
+ });
93
+ }
94
+ return new TurboArNSPaymentProviderUnauthenticated({
95
+ paymentUrl,
96
+ axios,
97
+ logger,
98
+ });
99
+ }
100
+ }
101
+ exports.TurboArNSPaymentFactory = TurboArNSPaymentFactory;
102
+ // Base class for unauthenticated operations
103
+ class TurboArNSPaymentProviderUnauthenticated {
104
+ paymentUrl;
105
+ axios;
106
+ logger;
107
+ constructor({ paymentUrl = 'https://payment.ardrive.io', axios = (0, http_client_js_1.createAxiosInstance)(), logger = logger_js_1.Logger.default, }) {
108
+ this.paymentUrl = paymentUrl;
109
+ this.axios = axios;
110
+ this.logger = logger;
111
+ }
112
+ async getArNSPriceDetails({ intent, name, quantity, type, years, }) {
113
+ const url = (0, url_js_1.urlWithSearchParams)({
114
+ baseUrl: `${this.paymentUrl}/v1/arns/price/${intent}/${name}`,
115
+ params: {
116
+ increaseQty: quantity,
117
+ type,
118
+ years,
119
+ },
120
+ });
121
+ const { data, status } = await this.axios.get(url);
122
+ this.logger.debug('getArNSPriceDetails', {
123
+ intent,
124
+ name,
125
+ quantity,
126
+ type,
127
+ years,
128
+ data,
129
+ status,
130
+ });
131
+ if (status !== 200) {
132
+ throw new Error('Failed to get ArNS purchase price ' + JSON.stringify(data));
133
+ }
134
+ if (!data.winc || !data.mARIO) {
135
+ throw new Error('Invalid response from Turbo ' + JSON.stringify(data));
136
+ }
137
+ return {
138
+ winc: data.winc,
139
+ mARIO: new token_js_1.mARIOToken(+data.mARIO),
140
+ };
141
+ }
142
+ async getPrice(params) {
143
+ const { winc } = await this.getArNSPriceDetails(params);
144
+ return +winc;
145
+ }
146
+ }
147
+ exports.TurboArNSPaymentProviderUnauthenticated = TurboArNSPaymentProviderUnauthenticated;
148
+ // Class for authenticated operations, extending the base class
149
+ class TurboArNSPaymentProviderAuthenticated extends TurboArNSPaymentProviderUnauthenticated {
150
+ signer;
151
+ constructor({ signer, ...restConfig }) {
152
+ super(restConfig); // Pass unauthenticated config to base class+
153
+ if (!isTurboArNSSigner(signer)) {
154
+ throw new Error('Signer must be a TurboArNSSigner');
155
+ }
156
+ this.signer = signer;
157
+ }
158
+ async initiateArNSPurchase({ intent, name, quantity, type, processId, years, }) {
159
+ // Signer check is implicitly handled by requiring it in the constructor
160
+ const url = (0, url_js_1.urlWithSearchParams)({
161
+ baseUrl: `${this.paymentUrl}/v1/arns/purchase/${intent}/${name}`,
162
+ params: {
163
+ increaseQty: quantity,
164
+ processId,
165
+ type,
166
+ years,
167
+ },
168
+ });
169
+ const headers = await signedRequestHeadersFromSigner({
170
+ signer: this.signer,
171
+ });
172
+ const { data, status } = await this.axios.post(url, null, {
173
+ headers,
174
+ });
175
+ this.logger.debug('Initiated ArNS purchase', {
176
+ intent,
177
+ name,
178
+ quantity,
179
+ processId,
180
+ type,
181
+ years,
182
+ data,
183
+ status,
184
+ });
185
+ if (status !== 200) {
186
+ throw new Error('Failed to initiate ArNS purchase ' + JSON.stringify(data));
187
+ }
188
+ return {
189
+ id: data.arioWriteResult.id,
190
+ result: data.purchaseReceipt,
191
+ };
192
+ }
193
+ }
194
+ exports.TurboArNSPaymentProviderAuthenticated = TurboArNSPaymentProviderAuthenticated;
195
+ function isWanderArweaveBrowserSigner(signer) {
196
+ return (typeof signer === 'object' &&
197
+ signer !== null &&
198
+ 'signMessage' in signer &&
199
+ 'getActivePublicKey' in signer);
200
+ }
201
+ function isTurboArNSSigner(signer) {
202
+ const isWanderWallet = isWanderArweaveBrowserSigner(signer);
203
+ const isSigner = signer instanceof arbundles_1.EthereumSigner ||
204
+ signer instanceof arbundles_1.InjectedEthereumSigner ||
205
+ signer instanceof arbundles_1.ArweaveSigner ||
206
+ signer instanceof arbundles_1.ArconnectSigner;
207
+ return isWanderWallet || isSigner;
208
+ }
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TrustedGatewaysHashProvider = void 0;
4
+ const arioGatewayHeaders = {
5
+ digest: 'x-ar-io-digest',
6
+ verified: 'x-ar-io-verified',
7
+ txId: 'x-arns-resolved-tx-id',
8
+ processId: 'x-arns-resolved-process-id',
9
+ };
10
+ class TrustedGatewaysHashProvider {
11
+ gatewaysProvider;
12
+ constructor({ gatewaysProvider,
13
+ // TODO: add threshold for allowed hash difference (i.e. by count or ratio of total gateways checked)
14
+ }) {
15
+ this.gatewaysProvider = gatewaysProvider;
16
+ }
17
+ /**
18
+ * Gets the digest for a given txId from all trusted gateways and ensures they all match.
19
+ * @param txId - The txId to get the digest for.
20
+ * @returns The digest for the given txId.
21
+ */
22
+ async getHash({ txId, }) {
23
+ // get the hash from every gateway, and ensure they all match
24
+ const hashSet = new Set();
25
+ const hashResults = [];
26
+ const gateways = await this.gatewaysProvider.getGateways();
27
+ const hashes = await Promise.all(gateways.map(async (gateway) => {
28
+ const response = await fetch(`${gateway.toString()}${txId}`, {
29
+ method: 'HEAD',
30
+ redirect: 'follow',
31
+ });
32
+ if (!response.ok) {
33
+ // skip this gateway
34
+ return undefined;
35
+ }
36
+ const txIdHash = response.headers.get(arioGatewayHeaders.digest);
37
+ if (txIdHash === null || txIdHash === undefined) {
38
+ // skip this gateway
39
+ return undefined;
40
+ }
41
+ hashResults.push({
42
+ gateway: gateway.hostname,
43
+ txIdHash,
44
+ });
45
+ return txIdHash;
46
+ }));
47
+ for (const hash of hashes) {
48
+ if (hash !== undefined) {
49
+ hashSet.add(hash);
50
+ }
51
+ }
52
+ if (hashSet.size === 0) {
53
+ throw new Error(`No trusted gateways returned a hash for txId ${txId}`);
54
+ }
55
+ if (hashSet.size > 1) {
56
+ throw new Error(`Failed to get consistent hash from all trusted gateways. ${JSON.stringify(hashResults)}`);
57
+ }
58
+ return { hash: hashResults[0].txIdHash, algorithm: 'sha256' };
59
+ }
60
+ /**
61
+ * Get the data root for a given txId from all trusted gateways and ensure they all match.
62
+ * @param txId - The txId to get the data root for.
63
+ * @returns The data root for the given txId.
64
+ */
65
+ async getDataRoot({ txId }) {
66
+ const dataRootSet = new Set();
67
+ const dataRootResults = [];
68
+ const gateways = await this.gatewaysProvider.getGateways();
69
+ const dataRoots = await Promise.all(gateways.map(async (gateway) => {
70
+ const response = await fetch(`${gateway.toString()}tx/${txId}/data_root`);
71
+ if (!response.ok) {
72
+ // skip this gateway
73
+ return undefined;
74
+ }
75
+ const dataRoot = await response.text();
76
+ dataRootResults.push({
77
+ gateway: gateway.hostname,
78
+ dataRoot,
79
+ });
80
+ return dataRoot;
81
+ }));
82
+ for (const dataRoot of dataRoots) {
83
+ if (dataRoot !== undefined) {
84
+ dataRootSet.add(dataRoot);
85
+ }
86
+ }
87
+ if (dataRootSet.size > 1) {
88
+ throw new Error(`Failed to get consistent data root from all trusted gateways. ${JSON.stringify(dataRootResults)}`);
89
+ }
90
+ return dataRootSet.values().next().value;
91
+ }
92
+ }
93
+ exports.TrustedGatewaysHashProvider = TrustedGatewaysHashProvider;
94
+ // client could check hashes of data items, match expected hash
95
+ // if the gateway has the hash and they've verified it, you can trust the data item and offset
96
+ // you would be only trusting the gateway that it is a valid bundle
97
+ // you can request the offset from the gateway to verify the id
98
+ /**
99
+ * Note from @djwhitt
100
+ *
101
+ * Calculating data roots this way is fine, but it may not reproduce the original data root.
102
+ * We could also implement a data root verifier that pulls all the chunks, checks that they
103
+ * reproduce the expected data root, and then compares the concatenated chunk data to the
104
+ * original data retrieved. That would take a while, but it should be able to verify any L1
105
+ * data where we can find the chunks.
106
+ */
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SimpleCacheGatewaysProvider = exports.StaticGatewaysProvider = exports.NetworkGatewaysProvider = void 0;
4
+ class NetworkGatewaysProvider {
5
+ ario;
6
+ sortBy;
7
+ sortOrder;
8
+ limit;
9
+ filter;
10
+ constructor({ ario, sortBy = 'operatorStake', sortOrder = 'desc', limit = 1000, filter = (g) => g.status === 'joined', }) {
11
+ this.ario = ario;
12
+ this.sortBy = sortBy;
13
+ this.sortOrder = sortOrder;
14
+ this.limit = limit;
15
+ this.filter = filter;
16
+ }
17
+ async getGateways() {
18
+ let cursor;
19
+ let attempts = 0;
20
+ const gateways = [];
21
+ do {
22
+ try {
23
+ const { items: newGateways = [], nextCursor } = await this.ario.getGateways({
24
+ limit: 1000,
25
+ cursor,
26
+ sortBy: this.sortBy,
27
+ sortOrder: this.sortOrder,
28
+ });
29
+ gateways.push(...newGateways);
30
+ cursor = nextCursor;
31
+ attempts = 0; // reset attempts if we get a new cursor
32
+ }
33
+ catch (error) {
34
+ console.error('Error fetching gateways', {
35
+ cursor,
36
+ attempts,
37
+ error,
38
+ });
39
+ attempts++;
40
+ }
41
+ } while (cursor !== undefined && attempts < 3);
42
+ // filter out any gateways that are not joined
43
+ const filteredGateways = gateways.filter(this.filter).slice(0, this.limit);
44
+ return filteredGateways.map((g) => new URL(`${g.settings.protocol}://${g.settings.fqdn}:${g.settings.port}`));
45
+ }
46
+ }
47
+ exports.NetworkGatewaysProvider = NetworkGatewaysProvider;
48
+ class StaticGatewaysProvider {
49
+ gateways;
50
+ constructor({ gateways }) {
51
+ this.gateways = gateways.map((g) => new URL(g));
52
+ }
53
+ async getGateways() {
54
+ return this.gateways;
55
+ }
56
+ }
57
+ exports.StaticGatewaysProvider = StaticGatewaysProvider;
58
+ class SimpleCacheGatewaysProvider {
59
+ gatewaysProvider;
60
+ ttlSeconds;
61
+ lastUpdated;
62
+ gatewaysCache;
63
+ constructor({ gatewaysProvider, ttlSeconds = 5 * 60, // 5 minutes
64
+ }) {
65
+ this.gatewaysCache = [];
66
+ this.gatewaysProvider = gatewaysProvider;
67
+ this.ttlSeconds = ttlSeconds;
68
+ }
69
+ async getGateways() {
70
+ const now = Date.now();
71
+ if (this.gatewaysCache.length === 0 ||
72
+ now - this.lastUpdated > this.ttlSeconds * 1000) {
73
+ try {
74
+ // preserve the cache if the fetch fails
75
+ const allGateways = await this.gatewaysProvider.getGateways();
76
+ this.gatewaysCache = allGateways;
77
+ this.lastUpdated = now;
78
+ }
79
+ catch (error) {
80
+ console.error('Error fetching gateways', error);
81
+ }
82
+ }
83
+ return this.gatewaysCache;
84
+ }
85
+ }
86
+ exports.SimpleCacheGatewaysProvider = SimpleCacheGatewaysProvider;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ /**
18
+ * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
19
+ *
20
+ * Licensed under the Apache License, Version 2.0 (the "License");
21
+ * you may not use this file except in compliance with the License.
22
+ * You may obtain a copy of the License at
23
+ *
24
+ * http://www.apache.org/licenses/LICENSE-2.0
25
+ *
26
+ * Unless required by applicable law or agreed to in writing, software
27
+ * distributed under the License is distributed on an "AS IS" BASIS,
28
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29
+ * See the License for the specific language governing permissions and
30
+ * limitations under the License.
31
+ */
32
+ __exportStar(require("./wayfinder.js"), exports);
33
+ // routers
34
+ __exportStar(require("./routers/random.js"), exports);
35
+ __exportStar(require("./routers/priority.js"), exports);
36
+ __exportStar(require("./routers/static.js"), exports);
37
+ // gateways providers
38
+ __exportStar(require("./gateways.js"), exports);
39
+ // trusted gateways
40
+ __exportStar(require("./gateways/trusted-gateways.js"), exports);
41
+ // hash providers
42
+ __exportStar(require("./verification/data-root-verifier.js"), exports);
43
+ __exportStar(require("./verification/hash-verifier.js"), exports);
44
+ // TODO: signature verification
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PriorityGatewayRouter = void 0;
4
+ const random_js_1 = require("../../../utils/random.js");
5
+ const gateways_js_1 = require("../gateways.js");
6
+ // TODO: one of N where N are in the last time window have met certain performance thresholds
7
+ // TODO: look at bitorrent routing protocols for inspiration
8
+ // TODO: router that looks at local stats/metrics and adjusts based on those
9
+ class PriorityGatewayRouter {
10
+ name = 'priority';
11
+ gatewaysProvider;
12
+ constructor({ ario, sortBy, sortOrder, limit, }) {
13
+ this.gatewaysProvider = new gateways_js_1.NetworkGatewaysProvider({
14
+ ario,
15
+ sortBy,
16
+ sortOrder,
17
+ limit,
18
+ });
19
+ }
20
+ async getTargetGateway() {
21
+ const gateways = await this.gatewaysProvider.getGateways();
22
+ const targetGateway = gateways[(0, random_js_1.randomInt)(0, gateways.length)];
23
+ if (targetGateway === undefined) {
24
+ throw new Error('No target gateway found');
25
+ }
26
+ return targetGateway;
27
+ }
28
+ }
29
+ exports.PriorityGatewayRouter = PriorityGatewayRouter;