@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
@@ -13,6 +13,7 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
+ import { EthereumSigner } from '@dha-team/arbundles';
16
17
  import { connect } from '@permaweb/aoconnect';
17
18
  import { program } from 'commander';
18
19
  import { readFileSync } from 'fs';
@@ -77,7 +78,7 @@ export function arioProcessIdFromOptions({ arioProcessId, devnet, testnet, }) {
77
78
  }
78
79
  return ARIO_MAINNET_PROCESS_ID;
79
80
  }
80
- function jwkFromOptions({ privateKey, walletFile, }) {
81
+ function walletFromOptions({ privateKey, walletFile, }) {
81
82
  if (privateKey !== undefined) {
82
83
  return JSON.parse(privateKey);
83
84
  }
@@ -87,7 +88,7 @@ function jwkFromOptions({ privateKey, walletFile, }) {
87
88
  return undefined;
88
89
  }
89
90
  export function requiredJwkFromOptions(options) {
90
- const jwk = jwkFromOptions(options);
91
+ const jwk = walletFromOptions(options);
91
92
  if (jwk === undefined) {
92
93
  throw new Error('No JWK provided for signing!\nPlease provide a stringified JWK with `--private-key` or the file path of a jwk.json file with `--wallet-file`');
93
94
  }
@@ -115,15 +116,39 @@ function aoProcessFromOptions(options) {
115
116
  }
116
117
  export function readARIOFromOptions(options) {
117
118
  setLoggerIfDebug(options);
119
+ console.log('options', {
120
+ cuUrl: 'https://cu.ardrive.io', // default to ardrive cu for ARIO process
121
+ ...options,
122
+ });
118
123
  return ARIO.init({
119
- process: aoProcessFromOptions(options),
124
+ process: aoProcessFromOptions({
125
+ cuUrl: 'https://cu.ardrive.io', // default to ardrive cu for ARIO process
126
+ ...options,
127
+ }),
128
+ paymentUrl: options.paymentUrl,
120
129
  });
121
130
  }
122
- export function requiredContractSignerFromOptions(options) {
131
+ export function contractSignerFromOptions(options) {
132
+ const wallet = walletFromOptions(options);
133
+ if (wallet === undefined) {
134
+ return undefined;
135
+ }
136
+ const token = options.token ?? 'arweave';
137
+ if (token === 'ethereum') {
138
+ const signer = new EthereumSigner(wallet);
139
+ // For EthereumSigner, we need to convert the JWK to a string
140
+ return { signer, signerAddress: signer.publicKey.toString('hex') };
141
+ }
123
142
  // TODO: Support other wallet types
124
- const jwk = requiredJwkFromOptions(options);
125
- const signer = new ArweaveSigner(jwk);
126
- return { signer, signerAddress: jwkToAddress(jwk) };
143
+ const signer = new ArweaveSigner(wallet);
144
+ return { signer, signerAddress: jwkToAddress(wallet) };
145
+ }
146
+ export function requiredContractSignerFromOptions(options) {
147
+ const contractSigner = contractSignerFromOptions(options);
148
+ if (contractSigner === undefined) {
149
+ throw new Error('No signer provided for signing!\nPlease provide a stringified JWK or Ethereum private key with `--private-key` or the file path of an arweave.jwk.json or eth.private.key.txt file with `--wallet-file`');
150
+ }
151
+ return contractSigner;
127
152
  }
128
153
  export function requiredAoSignerFromOptions(options) {
129
154
  return createAoSigner(requiredContractSignerFromOptions(options).signer);
@@ -135,6 +160,7 @@ export function writeARIOFromOptions(options) {
135
160
  ario: ARIO.init({
136
161
  process: aoProcessFromOptions(options),
137
162
  signer,
163
+ paymentUrl: options.paymentUrl,
138
164
  }),
139
165
  signerAddress,
140
166
  };
@@ -155,10 +181,9 @@ export function addressFromOptions(options) {
155
181
  if (options.address !== undefined) {
156
182
  return options.address;
157
183
  }
158
- // TODO: Support other wallet types
159
- const jwk = jwkFromOptions(options);
160
- if (jwk !== undefined) {
161
- return jwkToAddress(jwk);
184
+ const signer = contractSignerFromOptions(options);
185
+ if (signer !== undefined) {
186
+ return signer.signerAddress;
162
187
  }
163
188
  return undefined;
164
189
  }
@@ -281,6 +306,9 @@ export function requiredMARIOFromOptions(options, key) {
281
306
  return new ARIOToken(+options[key]).toMARIO();
282
307
  }
283
308
  export async function assertEnoughBalanceForArNSPurchase({ ario, address, costDetailsParams, }) {
309
+ if (costDetailsParams.fundFrom === 'turbo') {
310
+ return;
311
+ }
284
312
  const costDetails = await ario.getCostDetails(costDetailsParams);
285
313
  if (costDetails.fundingPlan) {
286
314
  if (costDetails.fundingPlan.shortfall > 0) {
@@ -70,14 +70,14 @@ export class ANTVersionsWritable extends ANTVersionsReadable {
70
70
  super(config);
71
71
  this.signer = createAoSigner(signer);
72
72
  }
73
- async addVersion(params, { tags }) {
73
+ async addVersion({ version, moduleId, luaSourceId, notes, }, { tags }) {
74
74
  return this.process.send({
75
75
  tags: pruneTags([
76
76
  { name: 'Action', value: 'Add-Version' },
77
- { name: 'Version', value: params.version },
78
- { name: 'Module-Id', value: params.moduleId },
79
- { name: 'Lua-Source-Id', value: params.luaSourceId },
80
- { name: 'Notes', value: params.notes },
77
+ { name: 'Version', value: version },
78
+ { name: 'Module-Id', value: moduleId },
79
+ { name: 'Lua-Source-Id', value: luaSourceId },
80
+ { name: 'Notes', value: notes },
81
81
  ...(tags ?? []),
82
82
  ]),
83
83
  signer: this.signer,
@@ -89,12 +89,12 @@ export class AoANTReadable {
89
89
  * ```
90
90
  */
91
91
  async getRecord({ undername }, { strict } = { strict: this.strict }) {
92
- const tags = [
93
- { name: 'Sub-Domain', value: undername },
94
- { name: 'Action', value: 'Record' },
95
- ];
92
+ // TODO: use sortedANTRecords to get priority on all records, even if ANT does not have a priority set
96
93
  const record = await this.process.read({
97
- tags,
94
+ tags: [
95
+ { name: 'Action', value: 'Record' },
96
+ { name: 'Sub-Domain', value: undername },
97
+ ],
98
98
  });
99
99
  if (strict)
100
100
  parseSchemaResult(AntRecordSchema.passthrough(), record);
@@ -22,3 +22,5 @@ export * from './faucet.js';
22
22
  // ao
23
23
  export * from './io.js';
24
24
  export * from './contracts/ao-process.js';
25
+ // wayfinder
26
+ export * from './wayfinder/index.js';
@@ -18,10 +18,12 @@ import { ARIO_MAINNET_PROCESS_ID, ARIO_TESTNET_PROCESS_ID, } from '../constants.
18
18
  import { isProcessConfiguration, isProcessIdConfiguration, } from '../types/index.js';
19
19
  import { createAoSigner } from '../utils/ao.js';
20
20
  import { getEpochDataFromGqlWithCUFallback, paginationParamsToTags, pruneTags, removeEligibleRewardsFromEpochData, sortAndPaginateEpochDataIntoEligibleDistributions, } from '../utils/arweave.js';
21
+ import { ANT } from './ant.js';
21
22
  import { defaultArweave } from './arweave.js';
22
23
  import { AOProcess } from './contracts/ao-process.js';
23
24
  import { InvalidContractConfigurationError } from './error.js';
24
25
  import { createFaucet } from './faucet.js';
26
+ import { TurboArNSPaymentFactory, TurboArNSPaymentProviderAuthenticated, isTurboArNSSigner, } from './turbo.js';
25
27
  export class ARIO {
26
28
  // Implementation
27
29
  static init(config) {
@@ -89,6 +91,7 @@ export class ARIOReadable {
89
91
  process;
90
92
  epochSettings;
91
93
  arweave;
94
+ paymentProvider; // TODO: this could be an array/map of payment providers
92
95
  constructor(config) {
93
96
  this.arweave = config?.arweave ?? defaultArweave;
94
97
  if (config === undefined || Object.keys(config).length === 0) {
@@ -107,6 +110,9 @@ export class ARIOReadable {
107
110
  else {
108
111
  throw new InvalidContractConfigurationError();
109
112
  }
113
+ this.paymentProvider = TurboArNSPaymentFactory.init({
114
+ paymentUrl: config?.paymentUrl,
115
+ });
110
116
  }
111
117
  async getInfo() {
112
118
  return this.process.read({
@@ -438,6 +444,20 @@ export class ARIOReadable {
438
444
  // TODO: Can overload this function to refine different types of cost details params
439
445
  async getCostDetails({ intent, type, years, name, quantity, fromAddress, fundFrom, }) {
440
446
  const replacedBuyRecordWithBuyName = intent === 'Buy-Record' ? 'Buy-Name' : intent;
447
+ if (fundFrom === 'turbo') {
448
+ const { mARIO, winc } = await this.paymentProvider.getArNSPriceDetails({
449
+ intent: replacedBuyRecordWithBuyName,
450
+ name,
451
+ quantity,
452
+ type,
453
+ years,
454
+ });
455
+ return {
456
+ tokenCost: +mARIO,
457
+ wincQty: winc,
458
+ discounts: [],
459
+ };
460
+ }
441
461
  const allTags = [
442
462
  { name: 'Action', value: 'Cost-Details' },
443
463
  {
@@ -601,10 +621,47 @@ export class ARIOReadable {
601
621
  ],
602
622
  });
603
623
  }
624
+ async resolveArNSName({ name, }) {
625
+ const baseName = name.split('_').pop();
626
+ if (baseName === undefined) {
627
+ throw new Error('Invalid name');
628
+ }
629
+ const undername = name === baseName ? '@' : name.replace(`_${baseName}`, '');
630
+ const nameData = await this.getArNSRecord({ name: baseName });
631
+ const ant = ANT.init({
632
+ process: new AOProcess({
633
+ ao: this.process.ao,
634
+ processId: nameData.processId,
635
+ }),
636
+ });
637
+ const [owner, antRecord] = await Promise.all([
638
+ ant.getOwner(),
639
+ ant.getRecord({ undername }),
640
+ ]);
641
+ if (antRecord === undefined) {
642
+ throw new Error(`Record for ${undername} not found on ANT.`);
643
+ }
644
+ if (antRecord.ttlSeconds === undefined ||
645
+ antRecord.transactionId === undefined) {
646
+ throw new Error(`Invalid record on ANT. Must have ttlSeconds and transactionId. Record: ${JSON.stringify(antRecord)}`);
647
+ }
648
+ return {
649
+ name: name,
650
+ owner: owner,
651
+ txId: antRecord.transactionId,
652
+ ttlSeconds: antRecord.ttlSeconds,
653
+ priority: antRecord.priority,
654
+ // 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
655
+ processId: nameData.processId,
656
+ undernameLimit: nameData.undernameLimit,
657
+ type: nameData.type,
658
+ };
659
+ }
604
660
  }
605
661
  export class ARIOWriteable extends ARIOReadable {
606
662
  signer;
607
- constructor({ signer, ...config }) {
663
+ paymentProvider;
664
+ constructor({ signer, paymentUrl, ...config }) {
608
665
  if (config === undefined) {
609
666
  super({
610
667
  process: new AOProcess({
@@ -616,6 +673,10 @@ export class ARIOWriteable extends ARIOReadable {
616
673
  super(config);
617
674
  }
618
675
  this.signer = createAoSigner(signer);
676
+ this.paymentProvider = TurboArNSPaymentFactory.init({
677
+ signer: isTurboArNSSigner(signer) ? signer : undefined,
678
+ paymentUrl,
679
+ });
619
680
  }
620
681
  async transfer({ target, qty, }, options) {
621
682
  const { tags = [] } = options || {};
@@ -890,6 +951,18 @@ export class ARIOWriteable extends ARIOReadable {
890
951
  });
891
952
  }
892
953
  async buyRecord(params, options) {
954
+ if (params.fundFrom === 'turbo') {
955
+ if (!(this.paymentProvider instanceof TurboArNSPaymentProviderAuthenticated)) {
956
+ throw new Error('Turbo funding is not supported for this payment provider');
957
+ }
958
+ return this.paymentProvider.initiateArNSPurchase({
959
+ intent: 'Buy-Name',
960
+ name: params.name,
961
+ years: params.years,
962
+ type: params.type,
963
+ processId: params.processId,
964
+ });
965
+ }
893
966
  const { tags = [] } = options || {};
894
967
  const allTags = [
895
968
  ...tags,
@@ -914,6 +987,15 @@ export class ARIOWriteable extends ARIOReadable {
914
987
  * @returns {Promise<AoMessageResult>} The result of the upgrade
915
988
  */
916
989
  async upgradeRecord(params, options) {
990
+ if (params.fundFrom === 'turbo') {
991
+ if (!(this.paymentProvider instanceof TurboArNSPaymentProviderAuthenticated)) {
992
+ throw new Error('Turbo funding is not supported for this payment provider');
993
+ }
994
+ return this.paymentProvider.initiateArNSPurchase({
995
+ intent: 'Upgrade-Name',
996
+ name: params.name,
997
+ });
998
+ }
917
999
  const { tags = [] } = options || {};
918
1000
  const allTags = [
919
1001
  ...tags,
@@ -936,6 +1018,16 @@ export class ARIOWriteable extends ARIOReadable {
936
1018
  * @returns {Promise<AoMessageResult>} The result of the extension
937
1019
  */
938
1020
  async extendLease(params, options) {
1021
+ if (params.fundFrom === 'turbo') {
1022
+ if (!(this.paymentProvider instanceof TurboArNSPaymentProviderAuthenticated)) {
1023
+ throw new Error('Turbo funding is not supported for this payment provider');
1024
+ }
1025
+ return this.paymentProvider.initiateArNSPurchase({
1026
+ intent: 'Extend-Lease',
1027
+ name: params.name,
1028
+ years: params.years,
1029
+ });
1030
+ }
939
1031
  const { tags = [] } = options || {};
940
1032
  const allTags = [
941
1033
  ...tags,
@@ -950,6 +1042,16 @@ export class ARIOWriteable extends ARIOReadable {
950
1042
  });
951
1043
  }
952
1044
  async increaseUndernameLimit(params, options) {
1045
+ if (params.fundFrom === 'turbo') {
1046
+ if (!(this.paymentProvider instanceof TurboArNSPaymentProviderAuthenticated)) {
1047
+ throw new Error('Turbo funding is not supported for this payment provider');
1048
+ }
1049
+ return this.paymentProvider.initiateArNSPurchase({
1050
+ intent: 'Increase-Undername-Limit',
1051
+ quantity: params.increaseCount,
1052
+ name: params.name,
1053
+ });
1054
+ }
953
1055
  const { tags = [] } = options || {};
954
1056
  const allTags = [
955
1057
  ...tags,
@@ -986,6 +1088,9 @@ export class ARIOWriteable extends ARIOReadable {
986
1088
  });
987
1089
  }
988
1090
  async requestPrimaryName(params, options) {
1091
+ if (params.fundFrom === 'turbo') {
1092
+ throw new Error('Turbo funding is not yet supported for primary name requests');
1093
+ }
989
1094
  const { tags = [] } = options || {};
990
1095
  const allTags = [
991
1096
  ...tags,
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { ArconnectSigner, ArweaveSigner, EthereumSigner, InjectedEthereumSigner, SignatureConfig, } from '@dha-team/arbundles';
17
+ import { v4 as uuidv4 } from 'uuid';
18
+ import { mARIOToken } from '../types/token.js';
19
+ import { toB64Url } from '../utils/base64.js';
20
+ import { createAxiosInstance } from '../utils/http-client.js';
21
+ import { urlWithSearchParams } from '../utils/url.js';
22
+ import { Logger } from './logger.js';
23
+ export async function signedRequestHeadersFromSigner({ signer, nonce = uuidv4(), }) {
24
+ let signature = undefined;
25
+ let publicKey = undefined;
26
+ const signatureType = isWanderArweaveBrowserSigner(signer)
27
+ ? SignatureConfig.ARWEAVE
28
+ : signer.signatureType;
29
+ // equivalent to window.arweaveWallet
30
+ if (isWanderArweaveBrowserSigner(signer)) {
31
+ signature = toB64Url(Buffer.from(await signer.signMessage(Uint8Array.from(Buffer.from(nonce)))));
32
+ }
33
+ else if (signer instanceof ArconnectSigner) {
34
+ signature = toB64Url(Buffer.from(await signer['signer'].signMessage(Uint8Array.from(Buffer.from(nonce)))));
35
+ }
36
+ else if (signer instanceof ArweaveSigner ||
37
+ signer instanceof EthereumSigner ||
38
+ signer instanceof InjectedEthereumSigner) {
39
+ if ('setPublicKey' in signer && signer['publicKey'] === undefined) {
40
+ await signer.setPublicKey();
41
+ }
42
+ signature = toB64Url(Buffer.from(await signer.sign(Uint8Array.from(Buffer.from(nonce)))));
43
+ }
44
+ switch (signatureType) {
45
+ case SignatureConfig.ARWEAVE:
46
+ if (isWanderArweaveBrowserSigner(signer)) {
47
+ publicKey = await signer.getActivePublicKey();
48
+ }
49
+ else if ('setPublicKey' in signer) {
50
+ await signer.setPublicKey();
51
+ publicKey = toB64Url(signer.publicKey);
52
+ }
53
+ break;
54
+ case SignatureConfig.ETHEREUM:
55
+ if ('publicKey' in signer) {
56
+ publicKey = '0x' + signer.publicKey.toString('hex');
57
+ }
58
+ else {
59
+ throw new Error('Public key not found');
60
+ }
61
+ break;
62
+ // TODO: solana sig support
63
+ // case SignatureConfig.SOLANA:
64
+ // case SignatureConfig.ED25519:
65
+ default:
66
+ throw new Error(`Unsupported signer type for signing requests: ${signatureType}`);
67
+ }
68
+ if (publicKey === undefined || signature === undefined) {
69
+ throw new Error('Public key or signature not found');
70
+ }
71
+ return {
72
+ 'x-public-key': publicKey,
73
+ 'x-nonce': nonce,
74
+ 'x-signature': signature,
75
+ 'x-signature-type': signatureType,
76
+ };
77
+ }
78
+ export class TurboArNSPaymentFactory {
79
+ static init(config) {
80
+ const { signer, paymentUrl, axios, logger } = config ?? {};
81
+ if (signer !== undefined) {
82
+ return new TurboArNSPaymentProviderAuthenticated({
83
+ signer,
84
+ paymentUrl,
85
+ axios,
86
+ logger,
87
+ });
88
+ }
89
+ return new TurboArNSPaymentProviderUnauthenticated({
90
+ paymentUrl,
91
+ axios,
92
+ logger,
93
+ });
94
+ }
95
+ }
96
+ // Base class for unauthenticated operations
97
+ export class TurboArNSPaymentProviderUnauthenticated {
98
+ paymentUrl;
99
+ axios;
100
+ logger;
101
+ constructor({ paymentUrl = 'https://payment.ardrive.io', axios = createAxiosInstance(), logger = Logger.default, }) {
102
+ this.paymentUrl = paymentUrl;
103
+ this.axios = axios;
104
+ this.logger = logger;
105
+ }
106
+ async getArNSPriceDetails({ intent, name, quantity, type, years, }) {
107
+ const url = urlWithSearchParams({
108
+ baseUrl: `${this.paymentUrl}/v1/arns/price/${intent}/${name}`,
109
+ params: {
110
+ increaseQty: quantity,
111
+ type,
112
+ years,
113
+ },
114
+ });
115
+ const { data, status } = await this.axios.get(url);
116
+ this.logger.debug('getArNSPriceDetails', {
117
+ intent,
118
+ name,
119
+ quantity,
120
+ type,
121
+ years,
122
+ data,
123
+ status,
124
+ });
125
+ if (status !== 200) {
126
+ throw new Error('Failed to get ArNS purchase price ' + JSON.stringify(data));
127
+ }
128
+ if (!data.winc || !data.mARIO) {
129
+ throw new Error('Invalid response from Turbo ' + JSON.stringify(data));
130
+ }
131
+ return {
132
+ winc: data.winc,
133
+ mARIO: new mARIOToken(+data.mARIO),
134
+ };
135
+ }
136
+ async getPrice(params) {
137
+ const { winc } = await this.getArNSPriceDetails(params);
138
+ return +winc;
139
+ }
140
+ }
141
+ // Class for authenticated operations, extending the base class
142
+ export class TurboArNSPaymentProviderAuthenticated extends TurboArNSPaymentProviderUnauthenticated {
143
+ signer;
144
+ constructor({ signer, ...restConfig }) {
145
+ super(restConfig); // Pass unauthenticated config to base class+
146
+ if (!isTurboArNSSigner(signer)) {
147
+ throw new Error('Signer must be a TurboArNSSigner');
148
+ }
149
+ this.signer = signer;
150
+ }
151
+ async initiateArNSPurchase({ intent, name, quantity, type, processId, years, }) {
152
+ // Signer check is implicitly handled by requiring it in the constructor
153
+ const url = urlWithSearchParams({
154
+ baseUrl: `${this.paymentUrl}/v1/arns/purchase/${intent}/${name}`,
155
+ params: {
156
+ increaseQty: quantity,
157
+ processId,
158
+ type,
159
+ years,
160
+ },
161
+ });
162
+ const headers = await signedRequestHeadersFromSigner({
163
+ signer: this.signer,
164
+ });
165
+ const { data, status } = await this.axios.post(url, null, {
166
+ headers,
167
+ });
168
+ this.logger.debug('Initiated ArNS purchase', {
169
+ intent,
170
+ name,
171
+ quantity,
172
+ processId,
173
+ type,
174
+ years,
175
+ data,
176
+ status,
177
+ });
178
+ if (status !== 200) {
179
+ throw new Error('Failed to initiate ArNS purchase ' + JSON.stringify(data));
180
+ }
181
+ return {
182
+ id: data.arioWriteResult.id,
183
+ result: data.purchaseReceipt,
184
+ };
185
+ }
186
+ }
187
+ function isWanderArweaveBrowserSigner(signer) {
188
+ return (typeof signer === 'object' &&
189
+ signer !== null &&
190
+ 'signMessage' in signer &&
191
+ 'getActivePublicKey' in signer);
192
+ }
193
+ export function isTurboArNSSigner(signer) {
194
+ const isWanderWallet = isWanderArweaveBrowserSigner(signer);
195
+ const isSigner = signer instanceof EthereumSigner ||
196
+ signer instanceof InjectedEthereumSigner ||
197
+ signer instanceof ArweaveSigner ||
198
+ signer instanceof ArconnectSigner;
199
+ return isWanderWallet || isSigner;
200
+ }
@@ -0,0 +1,102 @@
1
+ const arioGatewayHeaders = {
2
+ digest: 'x-ar-io-digest',
3
+ verified: 'x-ar-io-verified',
4
+ txId: 'x-arns-resolved-tx-id',
5
+ processId: 'x-arns-resolved-process-id',
6
+ };
7
+ export class TrustedGatewaysHashProvider {
8
+ gatewaysProvider;
9
+ constructor({ gatewaysProvider,
10
+ // TODO: add threshold for allowed hash difference (i.e. by count or ratio of total gateways checked)
11
+ }) {
12
+ this.gatewaysProvider = gatewaysProvider;
13
+ }
14
+ /**
15
+ * Gets the digest for a given txId from all trusted gateways and ensures they all match.
16
+ * @param txId - The txId to get the digest for.
17
+ * @returns The digest for the given txId.
18
+ */
19
+ async getHash({ txId, }) {
20
+ // get the hash from every gateway, and ensure they all match
21
+ const hashSet = new Set();
22
+ const hashResults = [];
23
+ const gateways = await this.gatewaysProvider.getGateways();
24
+ const hashes = await Promise.all(gateways.map(async (gateway) => {
25
+ const response = await fetch(`${gateway.toString()}${txId}`, {
26
+ method: 'HEAD',
27
+ redirect: 'follow',
28
+ });
29
+ if (!response.ok) {
30
+ // skip this gateway
31
+ return undefined;
32
+ }
33
+ const txIdHash = response.headers.get(arioGatewayHeaders.digest);
34
+ if (txIdHash === null || txIdHash === undefined) {
35
+ // skip this gateway
36
+ return undefined;
37
+ }
38
+ hashResults.push({
39
+ gateway: gateway.hostname,
40
+ txIdHash,
41
+ });
42
+ return txIdHash;
43
+ }));
44
+ for (const hash of hashes) {
45
+ if (hash !== undefined) {
46
+ hashSet.add(hash);
47
+ }
48
+ }
49
+ if (hashSet.size === 0) {
50
+ throw new Error(`No trusted gateways returned a hash for txId ${txId}`);
51
+ }
52
+ if (hashSet.size > 1) {
53
+ throw new Error(`Failed to get consistent hash from all trusted gateways. ${JSON.stringify(hashResults)}`);
54
+ }
55
+ return { hash: hashResults[0].txIdHash, algorithm: 'sha256' };
56
+ }
57
+ /**
58
+ * Get the data root for a given txId from all trusted gateways and ensure they all match.
59
+ * @param txId - The txId to get the data root for.
60
+ * @returns The data root for the given txId.
61
+ */
62
+ async getDataRoot({ txId }) {
63
+ const dataRootSet = new Set();
64
+ const dataRootResults = [];
65
+ const gateways = await this.gatewaysProvider.getGateways();
66
+ const dataRoots = await Promise.all(gateways.map(async (gateway) => {
67
+ const response = await fetch(`${gateway.toString()}tx/${txId}/data_root`);
68
+ if (!response.ok) {
69
+ // skip this gateway
70
+ return undefined;
71
+ }
72
+ const dataRoot = await response.text();
73
+ dataRootResults.push({
74
+ gateway: gateway.hostname,
75
+ dataRoot,
76
+ });
77
+ return dataRoot;
78
+ }));
79
+ for (const dataRoot of dataRoots) {
80
+ if (dataRoot !== undefined) {
81
+ dataRootSet.add(dataRoot);
82
+ }
83
+ }
84
+ if (dataRootSet.size > 1) {
85
+ throw new Error(`Failed to get consistent data root from all trusted gateways. ${JSON.stringify(dataRootResults)}`);
86
+ }
87
+ return dataRootSet.values().next().value;
88
+ }
89
+ }
90
+ // client could check hashes of data items, match expected hash
91
+ // if the gateway has the hash and they've verified it, you can trust the data item and offset
92
+ // you would be only trusting the gateway that it is a valid bundle
93
+ // you can request the offset from the gateway to verify the id
94
+ /**
95
+ * Note from @djwhitt
96
+ *
97
+ * Calculating data roots this way is fine, but it may not reproduce the original data root.
98
+ * We could also implement a data root verifier that pulls all the chunks, checks that they
99
+ * reproduce the expected data root, and then compares the concatenated chunk data to the
100
+ * original data retrieved. That would take a while, but it should be able to verify any L1
101
+ * data where we can find the chunks.
102
+ */