@ardrive/turbo-sdk 1.31.1 → 1.32.0

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 (77) hide show
  1. package/README.md +28 -0
  2. package/bundles/web.bundle.min.js +437 -258
  3. package/lib/cjs/cli/commands/uploadFile.js +1 -0
  4. package/lib/cjs/cli/commands/uploadFolder.js +1 -0
  5. package/lib/cjs/cli/options.js +19 -0
  6. package/lib/cjs/cli/utils.js +25 -0
  7. package/lib/cjs/common/factory.js +1 -0
  8. package/lib/cjs/common/payment.js +1 -1
  9. package/lib/cjs/common/token/ario.js +1 -1
  10. package/lib/cjs/common/token/arweave.js +1 -1
  11. package/lib/cjs/common/token/baseEth.js +17 -1
  12. package/lib/cjs/common/token/ethereum.js +13 -4
  13. package/lib/cjs/common/token/kyve.js +1 -1
  14. package/lib/cjs/common/token/solana.js +1 -1
  15. package/lib/cjs/common/turbo.js +3 -1
  16. package/lib/cjs/common/upload.js +124 -6
  17. package/lib/cjs/node/upload.js +2 -1
  18. package/lib/cjs/types.js +20 -1
  19. package/lib/cjs/version.js +1 -1
  20. package/lib/cjs/web/upload.js +2 -2
  21. package/lib/esm/cli/commands/uploadFile.js +2 -1
  22. package/lib/esm/cli/commands/uploadFolder.js +2 -1
  23. package/lib/esm/cli/options.js +19 -0
  24. package/lib/esm/cli/utils.js +25 -1
  25. package/lib/esm/common/factory.js +1 -0
  26. package/lib/esm/common/payment.js +1 -1
  27. package/lib/esm/common/token/ario.js +1 -1
  28. package/lib/esm/common/token/arweave.js +1 -1
  29. package/lib/esm/common/token/baseEth.js +17 -1
  30. package/lib/esm/common/token/ethereum.js +13 -4
  31. package/lib/esm/common/token/kyve.js +1 -1
  32. package/lib/esm/common/token/solana.js +1 -1
  33. package/lib/esm/common/turbo.js +3 -1
  34. package/lib/esm/common/upload.js +124 -6
  35. package/lib/esm/node/upload.js +2 -1
  36. package/lib/esm/types.js +17 -0
  37. package/lib/esm/version.js +1 -1
  38. package/lib/esm/web/upload.js +2 -2
  39. package/lib/types/cli/commands/uploadFile.d.ts.map +1 -1
  40. package/lib/types/cli/commands/uploadFolder.d.ts.map +1 -1
  41. package/lib/types/cli/options.d.ts +43 -0
  42. package/lib/types/cli/options.d.ts.map +1 -1
  43. package/lib/types/cli/types.d.ts +4 -0
  44. package/lib/types/cli/types.d.ts.map +1 -1
  45. package/lib/types/cli/utils.d.ts +4 -1
  46. package/lib/types/cli/utils.d.ts.map +1 -1
  47. package/lib/types/common/factory.d.ts +4 -1
  48. package/lib/types/common/factory.d.ts.map +1 -1
  49. package/lib/types/common/token/ario.d.ts +1 -1
  50. package/lib/types/common/token/ario.d.ts.map +1 -1
  51. package/lib/types/common/token/arweave.d.ts +1 -1
  52. package/lib/types/common/token/arweave.d.ts.map +1 -1
  53. package/lib/types/common/token/baseEth.d.ts +1 -0
  54. package/lib/types/common/token/baseEth.d.ts.map +1 -1
  55. package/lib/types/common/token/ethereum.d.ts +2 -1
  56. package/lib/types/common/token/ethereum.d.ts.map +1 -1
  57. package/lib/types/common/token/kyve.d.ts +1 -1
  58. package/lib/types/common/token/kyve.d.ts.map +1 -1
  59. package/lib/types/common/token/solana.d.ts +1 -1
  60. package/lib/types/common/token/solana.d.ts.map +1 -1
  61. package/lib/types/common/turbo.d.ts +2 -2
  62. package/lib/types/common/turbo.d.ts.map +1 -1
  63. package/lib/types/common/upload.d.ts +16 -3
  64. package/lib/types/common/upload.d.ts.map +1 -1
  65. package/lib/types/node/factory.d.ts +4 -1
  66. package/lib/types/node/factory.d.ts.map +1 -1
  67. package/lib/types/node/upload.d.ts +4 -1
  68. package/lib/types/node/upload.d.ts.map +1 -1
  69. package/lib/types/types.d.ts +19 -4
  70. package/lib/types/types.d.ts.map +1 -1
  71. package/lib/types/version.d.ts +1 -1
  72. package/lib/types/version.d.ts.map +1 -1
  73. package/lib/types/web/factory.d.ts +4 -1
  74. package/lib/types/web/factory.d.ts.map +1 -1
  75. package/lib/types/web/upload.d.ts +4 -1
  76. package/lib/types/web/upload.d.ts.map +1 -1
  77. package/package.json +1 -1
@@ -220860,162 +220860,6 @@ globalThis.arbundles ??= expObj;
220860
220860
  init_dirname();
220861
220861
  init_buffer2();
220862
220862
  init_process2();
220863
- var fiatCurrencyTypes = [
220864
- "usd",
220865
- "eur",
220866
- "gbp",
220867
- "cad",
220868
- "aud",
220869
- "jpy",
220870
- "inr",
220871
- "sgd",
220872
- "hkd",
220873
- "brl"
220874
- ];
220875
- function isCurrency(currency) {
220876
- return fiatCurrencyTypes.includes(currency);
220877
- }
220878
- var tokenTypes = [
220879
- "arweave",
220880
- "ario",
220881
- "solana",
220882
- "ethereum",
220883
- "kyve",
220884
- "matic",
220885
- "pol",
220886
- "base-eth"
220887
- ];
220888
- var multipartPendingStatus = [
220889
- "ASSEMBLING",
220890
- "VALIDATING",
220891
- "FINALIZING"
220892
- ];
220893
- var multipartFailedStatus = [
220894
- "UNDERFUNDED",
220895
- "INVALID",
220896
- "APPROVAL_FAILED",
220897
- "REVOKE_FAILED"
220898
- ];
220899
- var multipartFinalizedStatus = ["FINALIZED"];
220900
- var isNodeUploadFolderParams = (p9) => p9.folderPath !== void 0;
220901
- var isWebUploadFolderParams = (p9) => p9.files !== void 0;
220902
- function isKyvePrivateKey(wallet) {
220903
- if (typeof wallet !== "string")
220904
- return false;
220905
- return true;
220906
- }
220907
- function isEthPrivateKey(wallet) {
220908
- if (typeof wallet !== "string")
220909
- return false;
220910
- return wallet.startsWith("0x");
220911
- }
220912
- var isJWK = (wallet) => wallet.kty !== void 0;
220913
- function isSolanaWalletAdapter(walletAdapter) {
220914
- return "publicKey" in walletAdapter && "signMessage" in walletAdapter;
220915
- }
220916
- function isEthereumWalletAdapter(walletAdapter) {
220917
- return "getSigner" in walletAdapter;
220918
- }
220919
- var validChunkingModes = ["force", "disabled", "auto"];
220920
-
220921
- // src/common/logger.ts
220922
- init_dirname();
220923
- init_buffer2();
220924
- init_process2();
220925
- var import_winston = __toESM(require_winston(), 1);
220926
-
220927
- // src/version.ts
220928
- init_dirname();
220929
- init_buffer2();
220930
- init_process2();
220931
- var version21 = "1.31.1-alpha.2";
220932
-
220933
- // src/common/logger.ts
220934
- var TurboWinstonLogger = class _TurboWinstonLogger {
220935
- constructor({
220936
- level = "info",
220937
- logFormat = "simple"
220938
- } = {}) {
220939
- this.silent = false;
220940
- if (level === "none") {
220941
- this.silent = true;
220942
- }
220943
- if (typeof window !== "undefined") {
220944
- this.logger = console;
220945
- } else {
220946
- this.logger = (0, import_winston.createLogger)({
220947
- level,
220948
- silent: this.silent,
220949
- defaultMeta: {
220950
- name: "turbo-sdk",
220951
- version: version21
220952
- },
220953
- format: import_winston.format.combine(import_winston.format.timestamp(), import_winston.format.json()),
220954
- transports: [
220955
- new import_winston.transports.Console({
220956
- format: getLogFormat(logFormat)
220957
- })
220958
- ]
220959
- });
220960
- }
220961
- }
220962
- static {
220963
- this.default = new _TurboWinstonLogger();
220964
- }
220965
- info(message2, ...args) {
220966
- if (this.silent)
220967
- return;
220968
- this.logger.info(message2, ...args);
220969
- }
220970
- warn(message2, ...args) {
220971
- if (this.silent)
220972
- return;
220973
- this.logger.warn(message2, ...args);
220974
- }
220975
- error(message2, ...args) {
220976
- if (this.silent)
220977
- return;
220978
- this.logger.error(message2, ...args);
220979
- }
220980
- debug(message2, ...args) {
220981
- if (this.silent)
220982
- return;
220983
- this.logger.debug(message2, ...args);
220984
- }
220985
- setLogLevel(level) {
220986
- this.silent = level === "none";
220987
- if ("silent" in this.logger) {
220988
- this.logger.silent = level === "none";
220989
- }
220990
- if ("level" in this.logger) {
220991
- this.logger.level = level;
220992
- }
220993
- }
220994
- setLogFormat(logFormat) {
220995
- if ("format" in this.logger) {
220996
- this.logger.format = getLogFormat(logFormat);
220997
- }
220998
- }
220999
- };
221000
- function getLogFormat(logFormat) {
221001
- return import_winston.format.combine(
221002
- (0, import_winston.format)((info) => {
221003
- if (info.stack && info.level !== "error") {
221004
- delete info.stack;
221005
- }
221006
- return info;
221007
- })(),
221008
- import_winston.format.errors({ stack: true }),
221009
- // Ensure errors show a stack trace
221010
- import_winston.format.timestamp(),
221011
- logFormat === "json" ? import_winston.format.json() : import_winston.format.simple()
221012
- );
221013
- }
221014
-
221015
- // src/common/payment.ts
221016
- init_dirname();
221017
- init_buffer2();
221018
- init_process2();
221019
220863
 
221020
220864
  // node_modules/bignumber.js/bignumber.mjs
221021
220865
  init_dirname();
@@ -222493,6 +222337,181 @@ function toFixedPoint(str, e12, z6) {
222493
222337
  }
222494
222338
  var BigNumber2 = clone();
222495
222339
 
222340
+ // src/types.ts
222341
+ var fiatCurrencyTypes = [
222342
+ "usd",
222343
+ "eur",
222344
+ "gbp",
222345
+ "cad",
222346
+ "aud",
222347
+ "jpy",
222348
+ "inr",
222349
+ "sgd",
222350
+ "hkd",
222351
+ "brl"
222352
+ ];
222353
+ function isCurrency(currency) {
222354
+ return fiatCurrencyTypes.includes(currency);
222355
+ }
222356
+ var tokenTypes = [
222357
+ "arweave",
222358
+ "ario",
222359
+ "solana",
222360
+ "ethereum",
222361
+ "kyve",
222362
+ "matic",
222363
+ "pol",
222364
+ "base-eth"
222365
+ ];
222366
+ var ExistingBalanceFunding = class {
222367
+ };
222368
+ var OnDemandFunding = class {
222369
+ constructor({
222370
+ maxTokenAmount,
222371
+ topUpBufferMultiplier = 1.1
222372
+ }) {
222373
+ if (maxTokenAmount !== void 0 && new BigNumber2(maxTokenAmount).isLessThan(0)) {
222374
+ throw new Error("maxTokenAmount must be non-negative");
222375
+ }
222376
+ this.maxTokenAmount = maxTokenAmount !== void 0 ? new BigNumber2(maxTokenAmount) : void 0;
222377
+ if (topUpBufferMultiplier < 1) {
222378
+ throw new Error("topUpBufferMultiplier must be >= 1");
222379
+ }
222380
+ this.topUpBufferMultiplier = topUpBufferMultiplier;
222381
+ }
222382
+ };
222383
+ var multipartPendingStatus = [
222384
+ "ASSEMBLING",
222385
+ "VALIDATING",
222386
+ "FINALIZING"
222387
+ ];
222388
+ var multipartFailedStatus = [
222389
+ "UNDERFUNDED",
222390
+ "INVALID",
222391
+ "APPROVAL_FAILED",
222392
+ "REVOKE_FAILED"
222393
+ ];
222394
+ var multipartFinalizedStatus = ["FINALIZED"];
222395
+ var isNodeUploadFolderParams = (p9) => p9.folderPath !== void 0;
222396
+ var isWebUploadFolderParams = (p9) => p9.files !== void 0;
222397
+ function isKyvePrivateKey(wallet) {
222398
+ if (typeof wallet !== "string")
222399
+ return false;
222400
+ return true;
222401
+ }
222402
+ function isEthPrivateKey(wallet) {
222403
+ if (typeof wallet !== "string")
222404
+ return false;
222405
+ return wallet.startsWith("0x");
222406
+ }
222407
+ var isJWK = (wallet) => wallet.kty !== void 0;
222408
+ function isSolanaWalletAdapter(walletAdapter) {
222409
+ return "publicKey" in walletAdapter && "signMessage" in walletAdapter;
222410
+ }
222411
+ function isEthereumWalletAdapter(walletAdapter) {
222412
+ return "getSigner" in walletAdapter;
222413
+ }
222414
+ var validChunkingModes = ["force", "disabled", "auto"];
222415
+
222416
+ // src/common/logger.ts
222417
+ init_dirname();
222418
+ init_buffer2();
222419
+ init_process2();
222420
+ var import_winston = __toESM(require_winston(), 1);
222421
+
222422
+ // src/version.ts
222423
+ init_dirname();
222424
+ init_buffer2();
222425
+ init_process2();
222426
+ var version21 = "1.31.1";
222427
+
222428
+ // src/common/logger.ts
222429
+ var TurboWinstonLogger = class _TurboWinstonLogger {
222430
+ constructor({
222431
+ level = "info",
222432
+ logFormat = "simple"
222433
+ } = {}) {
222434
+ this.silent = false;
222435
+ if (level === "none") {
222436
+ this.silent = true;
222437
+ }
222438
+ if (typeof window !== "undefined") {
222439
+ this.logger = console;
222440
+ } else {
222441
+ this.logger = (0, import_winston.createLogger)({
222442
+ level,
222443
+ silent: this.silent,
222444
+ defaultMeta: {
222445
+ name: "turbo-sdk",
222446
+ version: version21
222447
+ },
222448
+ format: import_winston.format.combine(import_winston.format.timestamp(), import_winston.format.json()),
222449
+ transports: [
222450
+ new import_winston.transports.Console({
222451
+ format: getLogFormat(logFormat)
222452
+ })
222453
+ ]
222454
+ });
222455
+ }
222456
+ }
222457
+ static {
222458
+ this.default = new _TurboWinstonLogger();
222459
+ }
222460
+ info(message2, ...args) {
222461
+ if (this.silent)
222462
+ return;
222463
+ this.logger.info(message2, ...args);
222464
+ }
222465
+ warn(message2, ...args) {
222466
+ if (this.silent)
222467
+ return;
222468
+ this.logger.warn(message2, ...args);
222469
+ }
222470
+ error(message2, ...args) {
222471
+ if (this.silent)
222472
+ return;
222473
+ this.logger.error(message2, ...args);
222474
+ }
222475
+ debug(message2, ...args) {
222476
+ if (this.silent)
222477
+ return;
222478
+ this.logger.debug(message2, ...args);
222479
+ }
222480
+ setLogLevel(level) {
222481
+ this.silent = level === "none";
222482
+ if ("silent" in this.logger) {
222483
+ this.logger.silent = level === "none";
222484
+ }
222485
+ if ("level" in this.logger) {
222486
+ this.logger.level = level;
222487
+ }
222488
+ }
222489
+ setLogFormat(logFormat) {
222490
+ if ("format" in this.logger) {
222491
+ this.logger.format = getLogFormat(logFormat);
222492
+ }
222493
+ }
222494
+ };
222495
+ function getLogFormat(logFormat) {
222496
+ return import_winston.format.combine(
222497
+ (0, import_winston.format)((info) => {
222498
+ if (info.stack && info.level !== "error") {
222499
+ delete info.stack;
222500
+ }
222501
+ return info;
222502
+ })(),
222503
+ import_winston.format.errors({ stack: true }),
222504
+ // Ensure errors show a stack trace
222505
+ import_winston.format.timestamp(),
222506
+ logFormat === "json" ? import_winston.format.json() : import_winston.format.simple()
222507
+ );
222508
+ }
222509
+
222510
+ // src/common/payment.ts
222511
+ init_dirname();
222512
+ init_buffer2();
222513
+ init_process2();
222514
+
222496
222515
  // src/utils/axiosClient.ts
222497
222516
  init_dirname();
222498
222517
  init_buffer2();
@@ -262493,7 +262512,7 @@ var ARIOToken = class {
262493
262512
  });
262494
262513
  return { id: txId, target, reward: "0" };
262495
262514
  }
262496
- async pollForTxBeingAvailable() {
262515
+ async pollTxAvailability() {
262497
262516
  return sleep(this.pollingOptions.initialBackoffMs);
262498
262517
  }
262499
262518
  };
@@ -262621,9 +262640,7 @@ var ArweaveToken = class {
262621
262640
  await this.submitTx(tx);
262622
262641
  return { id: id3, target, reward: tx.reward };
262623
262642
  }
262624
- async pollForTxBeingAvailable({
262625
- txId
262626
- }) {
262643
+ async pollTxAvailability({ txId }) {
262627
262644
  const { maxAttempts, pollingIntervalMs, initialBackoffMs } = this.pollingOptions;
262628
262645
  this.logger.debug("Polling for transaction...", { txId });
262629
262646
  await sleep(initialBackoffMs);
@@ -262734,17 +262751,24 @@ var EthereumToken = class {
262734
262751
  target
262735
262752
  };
262736
262753
  }
262737
- async pollForTxBeingAvailable({
262738
- txId
262739
- }) {
262754
+ async getTxAvailability(txId) {
262755
+ const tx = await this.rpcProvider.getTransaction(txId);
262756
+ if (tx) {
262757
+ this.logger.debug("Transaction is available on chain", { txId, tx });
262758
+ return true;
262759
+ }
262760
+ this.logger.debug("Transaction not yet available on chain", { txId });
262761
+ return false;
262762
+ }
262763
+ async pollTxAvailability({ txId }) {
262740
262764
  await new Promise(
262741
262765
  (resolve3) => setTimeout(resolve3, this.pollingOptions.initialBackoffMs)
262742
262766
  );
262743
262767
  let attempts = 0;
262744
262768
  while (attempts < this.pollingOptions.maxAttempts) {
262745
262769
  try {
262746
- const tx = await this.rpcProvider.getTransaction(txId);
262747
- if (tx) {
262770
+ const txIsAvailable = await this.getTxAvailability(txId);
262771
+ if (txIsAvailable) {
262748
262772
  return;
262749
262773
  }
262750
262774
  } catch (e12) {
@@ -262755,7 +262779,7 @@ var EthereumToken = class {
262755
262779
  );
262756
262780
  attempts++;
262757
262781
  }
262758
- throw new Error("Transaction not found after polling!");
262782
+ throw new Error(`Transaction ${txId} not found after polling!`);
262759
262783
  }
262760
262784
  };
262761
262785
 
@@ -262765,7 +262789,7 @@ var BaseEthToken = class extends EthereumToken {
262765
262789
  logger: logger19,
262766
262790
  gatewayUrl = defaultProdGatewayUrls["base-eth"],
262767
262791
  pollingOptions = {
262768
- initialBackoffMs: 1e3,
262792
+ initialBackoffMs: 2500,
262769
262793
  maxAttempts: 10,
262770
262794
  pollingIntervalMs: 2500
262771
262795
  }
@@ -262776,6 +262800,22 @@ var BaseEthToken = class extends EthereumToken {
262776
262800
  pollingOptions
262777
262801
  });
262778
262802
  }
262803
+ async getTxAvailability(txId) {
262804
+ const tx = await this.rpcProvider.getTransactionReceipt(txId);
262805
+ if (tx) {
262806
+ const confirmations = await tx.confirmations();
262807
+ if (confirmations >= 1) {
262808
+ this.logger.debug("Transaction is available on chain", {
262809
+ txId,
262810
+ tx,
262811
+ confirmations
262812
+ });
262813
+ return true;
262814
+ }
262815
+ }
262816
+ this.logger.debug("Transaction not yet available on chain", { txId, tx });
262817
+ return false;
262818
+ }
262779
262819
  };
262780
262820
 
262781
262821
  // src/common/token/kyve.ts
@@ -262825,9 +262865,7 @@ var KyveToken = class {
262825
262865
  });
262826
262866
  return { id: txHash, target };
262827
262867
  }
262828
- async pollForTxBeingAvailable({
262829
- txId
262830
- }) {
262868
+ async pollTxAvailability({ txId }) {
262831
262869
  const { maxAttempts, pollingIntervalMs, initialBackoffMs } = this.pollingOptions;
262832
262870
  this.logger.debug("Polling for transaction...", {
262833
262871
  txId,
@@ -273642,9 +273680,7 @@ var SolanaToken = class {
273642
273680
  "finalized"
273643
273681
  );
273644
273682
  }
273645
- async pollForTxBeingAvailable({
273646
- txId
273647
- }) {
273683
+ async pollTxAvailability({ txId }) {
273648
273684
  const { maxAttempts, pollingIntervalMs, initialBackoffMs } = this.pollingOptions;
273649
273685
  this.logger.debug("Polling for transaction...", {
273650
273686
  txId,
@@ -274021,7 +274057,7 @@ var TurboAuthenticatedPaymentService = class extends TurboUnauthenticatedPayment
274021
274057
  });
274022
274058
  const txId = fundTx.id;
274023
274059
  try {
274024
- await this.tokenTools.pollForTxBeingAvailable({ txId });
274060
+ await this.tokenTools.pollTxAvailability({ txId });
274025
274061
  } catch (e12) {
274026
274062
  this.logger.error(
274027
274063
  `Failed to poll for transaction being available from ${this.token} gateway... Attempting to submit fund tx to Turbo...`,
@@ -274809,6 +274845,77 @@ function combineAbortSignals(signals) {
274809
274845
  return controller.signal;
274810
274846
  }
274811
274847
 
274848
+ // src/common/index.ts
274849
+ init_dirname();
274850
+ init_buffer2();
274851
+ init_process2();
274852
+
274853
+ // src/common/currency.ts
274854
+ init_dirname();
274855
+ init_buffer2();
274856
+ init_process2();
274857
+ var ZeroDecimalCurrency = class {
274858
+ constructor(amt, type4) {
274859
+ this.amt = amt;
274860
+ this.type = type4;
274861
+ if (amt < 0) {
274862
+ throw new ProvidedInputError(
274863
+ `${type4} currency amount cannot be negative`
274864
+ );
274865
+ }
274866
+ this.assertDecimalPlaces(amt);
274867
+ }
274868
+ assertDecimalPlaces(a8) {
274869
+ if (a8 % 1 !== 0) {
274870
+ throw new ProvidedInputError(
274871
+ `${this.type} currency amount must have zero decimal places`
274872
+ );
274873
+ }
274874
+ }
274875
+ get amount() {
274876
+ return this.amt;
274877
+ }
274878
+ };
274879
+ var TwoDecimalCurrency = class extends ZeroDecimalCurrency {
274880
+ constructor(a8, type4) {
274881
+ super(a8, type4);
274882
+ this.a = a8;
274883
+ this.type = type4;
274884
+ }
274885
+ assertDecimalPlaces(a8) {
274886
+ if (a8 * 100 % 1 !== 0) {
274887
+ throw new ProvidedInputError(
274888
+ `${this.type} currency amount must have two decimal places`
274889
+ );
274890
+ }
274891
+ }
274892
+ get amount() {
274893
+ return this.a * 100;
274894
+ }
274895
+ };
274896
+ var USD = (usd) => new TwoDecimalCurrency(usd, "usd");
274897
+ var EUR = (eur) => new TwoDecimalCurrency(eur, "eur");
274898
+ var GBP = (gbp) => new TwoDecimalCurrency(gbp, "gbp");
274899
+ var CAD = (cad) => new TwoDecimalCurrency(cad, "cad");
274900
+ var AUD = (aud) => new TwoDecimalCurrency(aud, "aud");
274901
+ var INR = (inr) => new TwoDecimalCurrency(inr, "inr");
274902
+ var SGD = (sgd) => new TwoDecimalCurrency(sgd, "sgd");
274903
+ var HKD = (hkd) => new TwoDecimalCurrency(hkd, "hkd");
274904
+ var BRL = (brl) => new TwoDecimalCurrency(brl, "brl");
274905
+ var JPY = (jpy) => new ZeroDecimalCurrency(jpy, "jpy");
274906
+ var currencyMap = {
274907
+ usd: USD,
274908
+ eur: EUR,
274909
+ gbp: GBP,
274910
+ cad: CAD,
274911
+ aud: AUD,
274912
+ inr: INR,
274913
+ sgd: SGD,
274914
+ hkd: HKD,
274915
+ brl: BRL,
274916
+ jpy: JPY
274917
+ };
274918
+
274812
274919
  // src/common/upload.ts
274813
274920
  function isTurboUploadFileWithStreamFactoryParams(params) {
274814
274921
  return "fileStreamFactory" in params;
@@ -274881,10 +274988,13 @@ var TurboAuthenticatedBaseUploadService = class extends TurboUnauthenticatedUplo
274881
274988
  retryConfig,
274882
274989
  signer,
274883
274990
  logger: logger19,
274884
- token
274991
+ token,
274992
+ paymentService
274885
274993
  }) {
274886
274994
  super({ url, retryConfig, logger: logger19, token });
274995
+ this.enabledOnDemandTokens = ["ario", "solana", "base-eth"];
274887
274996
  this.signer = signer;
274997
+ this.paymentService = paymentService;
274888
274998
  }
274889
274999
  /**
274890
275000
  * Signs and uploads raw data to the Turbo Upload Service.
@@ -274896,7 +275006,9 @@ var TurboAuthenticatedBaseUploadService = class extends TurboUnauthenticatedUplo
274896
275006
  events,
274897
275007
  chunkByteCount,
274898
275008
  chunkingMode,
274899
- maxChunkConcurrency
275009
+ maxChunkConcurrency,
275010
+ fundingMode,
275011
+ maxFinalizeMs
274900
275012
  }) {
274901
275013
  if (isBlob2(data)) {
274902
275014
  const streamFactory = () => data.stream();
@@ -274906,7 +275018,12 @@ var TurboAuthenticatedBaseUploadService = class extends TurboUnauthenticatedUplo
274906
275018
  fileSizeFactory: sizeFactory,
274907
275019
  signal,
274908
275020
  dataItemOpts,
274909
- events
275021
+ events,
275022
+ chunkByteCount,
275023
+ chunkingMode,
275024
+ maxChunkConcurrency,
275025
+ fundingMode,
275026
+ maxFinalizeMs
274910
275027
  });
274911
275028
  }
274912
275029
  const dataBuffer = (() => {
@@ -274925,7 +275042,9 @@ var TurboAuthenticatedBaseUploadService = class extends TurboUnauthenticatedUplo
274925
275042
  events,
274926
275043
  chunkByteCount,
274927
275044
  chunkingMode,
274928
- maxChunkConcurrency
275045
+ maxChunkConcurrency,
275046
+ fundingMode,
275047
+ maxFinalizeMs
274929
275048
  });
274930
275049
  }
274931
275050
  resolveUploadFileConfig(params) {
@@ -274950,13 +275069,21 @@ var TurboAuthenticatedBaseUploadService = class extends TurboUnauthenticatedUplo
274950
275069
  };
274951
275070
  }
274952
275071
  async uploadFile(params) {
274953
- const { signal, dataItemOpts, events, fileStreamFactory, fileSizeFactory } = this.resolveUploadFileConfig(params);
275072
+ const {
275073
+ signal,
275074
+ dataItemOpts,
275075
+ events,
275076
+ fileStreamFactory,
275077
+ fileSizeFactory,
275078
+ fundingMode = new ExistingBalanceFunding()
275079
+ } = this.resolveUploadFileConfig(params);
274954
275080
  let retries = 0;
274955
275081
  const maxRetries = this.retryConfig.retries ?? 3;
274956
275082
  const retryDelay = this.retryConfig.retryDelay ?? ((retryNumber) => retryNumber * 1e3);
274957
275083
  let lastError = void 0;
274958
275084
  let lastStatusCode = void 0;
274959
275085
  const emitter = new TurboEventEmitter(events);
275086
+ let cryptoFundResult;
274960
275087
  while (retries < maxRetries) {
274961
275088
  if (signal?.aborted) {
274962
275089
  throw new CanceledError2();
@@ -274967,6 +275094,13 @@ var TurboAuthenticatedBaseUploadService = class extends TurboUnauthenticatedUplo
274967
275094
  dataItemOpts,
274968
275095
  emitter
274969
275096
  });
275097
+ if (fundingMode instanceof OnDemandFunding && cryptoFundResult === void 0) {
275098
+ const totalByteCount = dataItemSizeFactory();
275099
+ cryptoFundResult = await this.onDemand({
275100
+ totalByteCount,
275101
+ onDemandFunding: fundingMode
275102
+ });
275103
+ }
274970
275104
  try {
274971
275105
  const { chunkByteCount, maxChunkConcurrency } = params;
274972
275106
  const chunkedUploader = new ChunkedUploader({
@@ -274987,7 +275121,7 @@ var TurboAuthenticatedBaseUploadService = class extends TurboUnauthenticatedUplo
274987
275121
  signal,
274988
275122
  events
274989
275123
  });
274990
- return response2;
275124
+ return { ...response2, cryptoFundResult };
274991
275125
  }
274992
275126
  const response = await this.uploadSignedDataItem({
274993
275127
  dataItemStreamFactory,
@@ -274996,7 +275130,7 @@ var TurboAuthenticatedBaseUploadService = class extends TurboUnauthenticatedUplo
274996
275130
  signal,
274997
275131
  events
274998
275132
  });
274999
- return response;
275133
+ return { ...response, cryptoFundResult };
275000
275134
  } catch (error) {
275001
275135
  lastError = error;
275002
275136
  if (error instanceof FailedRequestError) {
@@ -275089,6 +275223,7 @@ ${lastError instanceof Error ? lastError.message : lastError}`;
275089
275223
  maxChunkConcurrency,
275090
275224
  chunkByteCount,
275091
275225
  chunkingMode,
275226
+ fundingMode = new ExistingBalanceFunding(),
275092
275227
  maxFinalizeMs
275093
275228
  } = params;
275094
275229
  const { disableManifest, indexFile, fallbackFile } = manifestOptions;
@@ -275133,6 +275268,16 @@ ${lastError instanceof Error ? lastError.message : lastError}`;
275133
275268
  };
275134
275269
  const files = await this.getFiles(params);
275135
275270
  const limit = pLimit(maxConcurrentUploads);
275271
+ let cryptoFundResult;
275272
+ if (fundingMode instanceof OnDemandFunding) {
275273
+ const totalByteCount = files.reduce((acc, file) => {
275274
+ return acc + this.getFileSize(file) + 1200;
275275
+ }, 0);
275276
+ cryptoFundResult = await this.onDemand({
275277
+ totalByteCount,
275278
+ onDemandFunding: fundingMode
275279
+ });
275280
+ }
275136
275281
  await Promise.all(files.map((file) => limit(() => uploadFile(file))));
275137
275282
  this.logger.debug("Finished uploading files", {
275138
275283
  numFiles: files.length,
@@ -275170,7 +275315,8 @@ ${lastError instanceof Error ? lastError.message : lastError}`;
275170
275315
  return {
275171
275316
  ...response,
275172
275317
  manifest,
275173
- manifestResponse
275318
+ manifestResponse,
275319
+ cryptoFundResult
275174
275320
  };
275175
275321
  }
275176
275322
  async shareCredits({
@@ -275235,6 +275381,102 @@ ${lastError instanceof Error ? lastError.message : lastError}`;
275235
275381
  }
275236
275382
  return revokedApprovals;
275237
275383
  }
275384
+ /**
275385
+ * Triggers an upload that will top-up the wallet with Credits for the amount before uploading.
275386
+ * First, it calculates the expected cost of the upload. Next, it checks the wallet for existing
275387
+ * balance. If the balance is insufficient, it will attempt the top-up with the wallet in the specified `token`
275388
+ * and await for the balance to be credited.
275389
+ * Note: Only `ario`, `solana`, and `base-eth` tokens are currently supported for on-demand uploads.
275390
+ */
275391
+ async onDemand({
275392
+ totalByteCount,
275393
+ onDemandFunding
275394
+ }) {
275395
+ const { maxTokenAmount, topUpBufferMultiplier } = onDemandFunding;
275396
+ const currentBalance = await this.paymentService.getBalance();
275397
+ const wincPriceForOneGiB = (await this.paymentService.getUploadCosts({
275398
+ bytes: [2 ** 30]
275399
+ }))[0].winc;
275400
+ const expectedWincPrice = new BigNumber2(wincPriceForOneGiB).multipliedBy(totalByteCount).dividedBy(2 ** 30).toFixed(0, BigNumber2.ROUND_UP);
275401
+ if (BigNumber2(currentBalance.effectiveBalance).isGreaterThanOrEqualTo(
275402
+ expectedWincPrice
275403
+ )) {
275404
+ this.logger.debug("Sufficient balance for on demand upload", {
275405
+ currentBalance,
275406
+ expectedWincPrice
275407
+ });
275408
+ return void 0;
275409
+ }
275410
+ this.logger.debug("Insufficient balance for on demand upload", {
275411
+ currentBalance,
275412
+ expectedWincPrice
275413
+ });
275414
+ if (!this.enabledOnDemandTokens.includes(this.token)) {
275415
+ throw new Error(
275416
+ `On-demand uploads are not supported for token: ${this.token}`
275417
+ );
275418
+ }
275419
+ const topUpWincAmount = BigNumber2(expectedWincPrice).minus(currentBalance.effectiveBalance).multipliedBy(topUpBufferMultiplier).toFixed(0, BigNumber2.ROUND_UP);
275420
+ const wincPriceForOneToken = (await this.paymentService.getWincForToken({
275421
+ tokenAmount: tokenToBaseMap[this.token](1)
275422
+ })).winc;
275423
+ const topUpTokenAmount = new BigNumber2(topUpWincAmount).dividedBy(wincPriceForOneToken).multipliedBy(tokenToBaseMap[this.token](1)).toFixed(0, BigNumber2.ROUND_UP);
275424
+ if (maxTokenAmount !== void 0) {
275425
+ if (new BigNumber2(topUpTokenAmount).isGreaterThan(maxTokenAmount)) {
275426
+ throw new Error(
275427
+ `Top up token amount ${new BigNumber2(topUpTokenAmount).div(
275428
+ exponentMap[this.token]
275429
+ )} is greater than the maximum allowed amount of ${maxTokenAmount}`
275430
+ );
275431
+ }
275432
+ }
275433
+ this.logger.debug(
275434
+ `Topping up wallet with ${topUpTokenAmount} ${this.token} for ${topUpWincAmount} winc`
275435
+ );
275436
+ const topUpResponse = await this.paymentService.topUpWithTokens({
275437
+ tokenAmount: topUpTokenAmount
275438
+ });
275439
+ this.logger.debug("Top up transaction submitted", { topUpResponse });
275440
+ const pollingOptions = {
275441
+ pollIntervalMs: 3 * 1e3,
275442
+ // poll every 3 seconds
275443
+ timeoutMs: 120 * 1e3
275444
+ // wait up to 2 minutes
275445
+ };
275446
+ let tries = 1;
275447
+ const maxTries = Math.ceil(pollingOptions.timeoutMs / pollingOptions.pollIntervalMs) - 1;
275448
+ while (topUpResponse.status !== "confirmed" && tries < maxTries) {
275449
+ this.logger.debug("Tx not yet confirmed, waiting to poll again", {
275450
+ tries,
275451
+ maxTries
275452
+ });
275453
+ await sleep(pollingOptions.pollIntervalMs);
275454
+ tries++;
275455
+ try {
275456
+ const submitFundResult = await this.paymentService.submitFundTransaction({
275457
+ txId: topUpResponse.id
275458
+ });
275459
+ if (submitFundResult.status === "confirmed") {
275460
+ this.logger.debug(
275461
+ "Top-up transaction confirmed and balance updated",
275462
+ { submitFundResult }
275463
+ );
275464
+ topUpResponse.status = "confirmed";
275465
+ break;
275466
+ }
275467
+ } catch (error) {
275468
+ this.logger.warn("Error fetching fund transaction during polling", {
275469
+ message: error instanceof Error ? error.message : error
275470
+ });
275471
+ }
275472
+ }
275473
+ if (tries >= maxTries) {
275474
+ this.logger.warn(
275475
+ "Timed out waiting for fund tx to confirm after top-up. Will continue to attempt upload but it may fail if balance is insufficient."
275476
+ );
275477
+ }
275478
+ return topUpResponse;
275479
+ }
275238
275480
  };
275239
275481
 
275240
275482
  // src/common/turbo.ts
@@ -275416,7 +275658,9 @@ var TurboAuthenticatedClient = class extends TurboUnauthenticatedClient {
275416
275658
  events,
275417
275659
  chunkByteCount,
275418
275660
  chunkingMode,
275419
- maxChunkConcurrency
275661
+ maxChunkConcurrency,
275662
+ maxFinalizeMs,
275663
+ fundingMode
275420
275664
  }) {
275421
275665
  return this.uploadService.upload({
275422
275666
  data,
@@ -275425,7 +275669,9 @@ var TurboAuthenticatedClient = class extends TurboUnauthenticatedClient {
275425
275669
  events,
275426
275670
  chunkByteCount,
275427
275671
  chunkingMode,
275428
- maxChunkConcurrency
275672
+ maxChunkConcurrency,
275673
+ fundingMode,
275674
+ maxFinalizeMs
275429
275675
  });
275430
275676
  }
275431
275677
  uploadFile(params) {
@@ -275565,7 +275811,8 @@ var TurboBaseFactory = class {
275565
275811
  ...uploadServiceConfig,
275566
275812
  signer: turboSigner,
275567
275813
  logger: logger19,
275568
- token
275814
+ token,
275815
+ paymentService
275569
275816
  });
275570
275817
  return new TurboAuthenticatedClient({
275571
275818
  uploadService,
@@ -275978,9 +276225,10 @@ var TurboAuthenticatedUploadService = class extends TurboAuthenticatedBaseUpload
275978
276225
  retryConfig,
275979
276226
  signer,
275980
276227
  logger: logger19,
275981
- token
276228
+ token,
276229
+ paymentService
275982
276230
  }) {
275983
- super({ url, retryConfig, logger: logger19, token, signer });
276231
+ super({ url, retryConfig, logger: logger19, token, signer, paymentService });
275984
276232
  }
275985
276233
  getFiles(params) {
275986
276234
  if (!isWebUploadFolderParams(params)) {
@@ -276066,77 +276314,6 @@ var TurboFactory = class _TurboFactory extends TurboBaseFactory {
276066
276314
  });
276067
276315
  }
276068
276316
  };
276069
-
276070
- // src/common/index.ts
276071
- init_dirname();
276072
- init_buffer2();
276073
- init_process2();
276074
-
276075
- // src/common/currency.ts
276076
- init_dirname();
276077
- init_buffer2();
276078
- init_process2();
276079
- var ZeroDecimalCurrency = class {
276080
- constructor(amt, type4) {
276081
- this.amt = amt;
276082
- this.type = type4;
276083
- if (amt < 0) {
276084
- throw new ProvidedInputError(
276085
- `${type4} currency amount cannot be negative`
276086
- );
276087
- }
276088
- this.assertDecimalPlaces(amt);
276089
- }
276090
- assertDecimalPlaces(a8) {
276091
- if (a8 % 1 !== 0) {
276092
- throw new ProvidedInputError(
276093
- `${this.type} currency amount must have zero decimal places`
276094
- );
276095
- }
276096
- }
276097
- get amount() {
276098
- return this.amt;
276099
- }
276100
- };
276101
- var TwoDecimalCurrency = class extends ZeroDecimalCurrency {
276102
- constructor(a8, type4) {
276103
- super(a8, type4);
276104
- this.a = a8;
276105
- this.type = type4;
276106
- }
276107
- assertDecimalPlaces(a8) {
276108
- if (a8 * 100 % 1 !== 0) {
276109
- throw new ProvidedInputError(
276110
- `${this.type} currency amount must have two decimal places`
276111
- );
276112
- }
276113
- }
276114
- get amount() {
276115
- return this.a * 100;
276116
- }
276117
- };
276118
- var USD = (usd) => new TwoDecimalCurrency(usd, "usd");
276119
- var EUR = (eur) => new TwoDecimalCurrency(eur, "eur");
276120
- var GBP = (gbp) => new TwoDecimalCurrency(gbp, "gbp");
276121
- var CAD = (cad) => new TwoDecimalCurrency(cad, "cad");
276122
- var AUD = (aud) => new TwoDecimalCurrency(aud, "aud");
276123
- var INR = (inr) => new TwoDecimalCurrency(inr, "inr");
276124
- var SGD = (sgd) => new TwoDecimalCurrency(sgd, "sgd");
276125
- var HKD = (hkd) => new TwoDecimalCurrency(hkd, "hkd");
276126
- var BRL = (brl) => new TwoDecimalCurrency(brl, "brl");
276127
- var JPY = (jpy) => new ZeroDecimalCurrency(jpy, "jpy");
276128
- var currencyMap = {
276129
- usd: USD,
276130
- eur: EUR,
276131
- gbp: GBP,
276132
- cad: CAD,
276133
- aud: AUD,
276134
- inr: INR,
276135
- sgd: SGD,
276136
- hkd: HKD,
276137
- brl: BRL,
276138
- jpy: JPY
276139
- };
276140
276317
  export {
276141
276318
  ARIOToTokenAmount,
276142
276319
  ARIOToken,
@@ -276152,6 +276329,7 @@ export {
276152
276329
  EUR,
276153
276330
  EthereumSigner,
276154
276331
  EthereumToken,
276332
+ ExistingBalanceFunding,
276155
276333
  GBP,
276156
276334
  HKD,
276157
276335
  HexSolanaSigner2 as HexSolanaSigner,
@@ -276159,6 +276337,7 @@ export {
276159
276337
  JPY,
276160
276338
  KYVEToTokenAmount,
276161
276339
  KyveToken,
276340
+ OnDemandFunding,
276162
276341
  POLToTokenAmount,
276163
276342
  PolygonToken,
276164
276343
  SGD,