@fuel-ts/account 0.99.0 → 0.100.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 (62) hide show
  1. package/dist/account.d.ts +9 -4
  2. package/dist/account.d.ts.map +1 -1
  3. package/dist/connectors/fuel-connector.d.ts +7 -6
  4. package/dist/connectors/fuel-connector.d.ts.map +1 -1
  5. package/dist/connectors/types/data-type.d.ts +8 -1
  6. package/dist/connectors/types/data-type.d.ts.map +1 -1
  7. package/dist/index.global.js +4116 -3431
  8. package/dist/index.global.js.map +1 -1
  9. package/dist/index.js +970 -562
  10. package/dist/index.js.map +1 -1
  11. package/dist/index.mjs +900 -502
  12. package/dist/index.mjs.map +1 -1
  13. package/dist/mnemonic/mnemonic.d.ts +1 -1
  14. package/dist/providers/__generated__/operations.d.ts +98 -3
  15. package/dist/providers/__generated__/operations.d.ts.map +1 -1
  16. package/dist/providers/coin-quantity.d.ts.map +1 -1
  17. package/dist/providers/message.d.ts.map +1 -1
  18. package/dist/providers/provider.d.ts +75 -11
  19. package/dist/providers/provider.d.ts.map +1 -1
  20. package/dist/providers/resource-cache.d.ts +6 -4
  21. package/dist/providers/resource-cache.d.ts.map +1 -1
  22. package/dist/providers/transaction-request/helpers.d.ts +10 -1
  23. package/dist/providers/transaction-request/helpers.d.ts.map +1 -1
  24. package/dist/providers/transaction-request/transaction-request.d.ts +29 -1
  25. package/dist/providers/transaction-request/transaction-request.d.ts.map +1 -1
  26. package/dist/providers/transaction-response/transaction-response.d.ts.map +1 -1
  27. package/dist/providers/transaction-summary/assemble-transaction-summary-from-serialized.d.ts +7 -0
  28. package/dist/providers/transaction-summary/assemble-transaction-summary-from-serialized.d.ts.map +1 -0
  29. package/dist/providers/transaction-summary/call.d.ts +8 -2
  30. package/dist/providers/transaction-summary/call.d.ts.map +1 -1
  31. package/dist/providers/transaction-summary/get-transaction-summary.d.ts +1 -1
  32. package/dist/providers/transaction-summary/get-transaction-summary.d.ts.map +1 -1
  33. package/dist/providers/transaction-summary/index.d.ts +1 -0
  34. package/dist/providers/transaction-summary/index.d.ts.map +1 -1
  35. package/dist/providers/transaction-summary/operations.d.ts.map +1 -1
  36. package/dist/providers/transaction-summary/receipt.d.ts +3 -2
  37. package/dist/providers/transaction-summary/receipt.d.ts.map +1 -1
  38. package/dist/providers/transaction-summary/types.d.ts +5 -3
  39. package/dist/providers/transaction-summary/types.d.ts.map +1 -1
  40. package/dist/providers/utils/handle-gql-error-message.d.ts +0 -4
  41. package/dist/providers/utils/handle-gql-error-message.d.ts.map +1 -1
  42. package/dist/providers/utils/helpers.d.ts +14 -0
  43. package/dist/providers/utils/helpers.d.ts.map +1 -0
  44. package/dist/providers/utils/index.d.ts +1 -0
  45. package/dist/providers/utils/index.d.ts.map +1 -1
  46. package/dist/providers/utils/receipts.d.ts +4 -3
  47. package/dist/providers/utils/receipts.d.ts.map +1 -1
  48. package/dist/providers/utils/serialization.d.ts +35 -0
  49. package/dist/providers/utils/serialization.d.ts.map +1 -0
  50. package/dist/signer/signer.d.ts +1 -1
  51. package/dist/test-utils.global.js +3839 -3179
  52. package/dist/test-utils.global.js.map +1 -1
  53. package/dist/test-utils.js +895 -537
  54. package/dist/test-utils.js.map +1 -1
  55. package/dist/test-utils.mjs +827 -469
  56. package/dist/test-utils.mjs.map +1 -1
  57. package/dist/utils/formatTransferToContractScriptData.d.ts +3 -3
  58. package/dist/utils/formatTransferToContractScriptData.d.ts.map +1 -1
  59. package/dist/utils/predicate-script-loader-instructions.d.ts +2 -2
  60. package/dist/wallet/base-wallet-unlocked.d.ts +2 -1
  61. package/dist/wallet/base-wallet-unlocked.d.ts.map +1 -1
  62. package/package.json +21 -21
@@ -397,10 +397,9 @@ var coinQuantityfy = (coinQuantityLike) => {
397
397
  assetId = coinQuantityLike.assetId;
398
398
  max = coinQuantityLike.max ?? void 0;
399
399
  }
400
- const bnAmount = bn(amount);
401
400
  return {
402
401
  assetId: hexlify3(assetId),
403
- amount: bnAmount.lt(1) ? bn(1) : bnAmount,
402
+ amount: bn(amount),
404
403
  max: max ? bn(max) : void 0
405
404
  };
406
405
  };
@@ -417,13 +416,12 @@ var addAmountToCoinQuantities = (params) => {
417
416
  };
418
417
 
419
418
  // src/providers/provider.ts
420
- import { Address as Address3 } from "@fuel-ts/address";
419
+ import { Address as Address3, isB256 } from "@fuel-ts/address";
421
420
  import { ErrorCode as ErrorCode16, FuelError as FuelError19 } from "@fuel-ts/errors";
422
- import { BN as BN2, bn as bn17 } from "@fuel-ts/math";
423
- import { InputType as InputType7, InputMessageCoder as InputMessageCoder2, TransactionCoder as TransactionCoder5 } from "@fuel-ts/transactions";
424
- import { arrayify as arrayify13, hexlify as hexlify17, DateTime as DateTime2, isDefined as isDefined2 } from "@fuel-ts/utils";
425
- import { checkFuelCoreVersionCompatibility, versions } from "@fuel-ts/versions";
426
- import { equalBytes } from "@noble/curves/abstract/utils";
421
+ import { bn as bn17 } from "@fuel-ts/math";
422
+ import { InputMessageCoder as InputMessageCoder2, TransactionCoder as TransactionCoder5 } from "@fuel-ts/transactions";
423
+ import { arrayify as arrayify13, hexlify as hexlify18, DateTime as DateTime2, isDefined as isDefined2 } from "@fuel-ts/utils";
424
+ import { checkFuelCoreVersionCompatibility, gte, versions } from "@fuel-ts/versions";
427
425
  import { GraphQLClient } from "graphql-request";
428
426
  import gql2 from "graphql-tag";
429
427
  import { clone as clone8 } from "ramda";
@@ -1035,6 +1033,16 @@ var EstimatePredicatesDocument = gql`
1035
1033
  }
1036
1034
  }
1037
1035
  ${TransactionEstimatePredicatesFragmentDoc}`;
1036
+ var EstimatePredicatesAndGasPriceDocument = gql`
1037
+ query estimatePredicatesAndGasPrice($encodedTransaction: HexString!, $blockHorizon: U32!) {
1038
+ estimatePredicates(tx: $encodedTransaction) {
1039
+ ...transactionEstimatePredicatesFragment
1040
+ }
1041
+ estimateGasPrice(blockHorizon: $blockHorizon) {
1042
+ gasPrice
1043
+ }
1044
+ }
1045
+ ${TransactionEstimatePredicatesFragmentDoc}`;
1038
1046
  var GetLatestBlockDocument = gql`
1039
1047
  query getLatestBlock {
1040
1048
  chain {
@@ -1150,6 +1158,13 @@ var GetBalanceDocument = gql`
1150
1158
  }
1151
1159
  }
1152
1160
  `;
1161
+ var GetBalanceV2Document = gql`
1162
+ query getBalanceV2($owner: Address!, $assetId: AssetId!) {
1163
+ balance(owner: $owner, assetId: $assetId) {
1164
+ amountU128
1165
+ }
1166
+ }
1167
+ `;
1153
1168
  var GetLatestGasPriceDocument = gql`
1154
1169
  query getLatestGasPrice {
1155
1170
  latestGasPrice {
@@ -1182,6 +1197,27 @@ var GetBalancesDocument = gql`
1182
1197
  }
1183
1198
  }
1184
1199
  `;
1200
+ var GetBalancesV2Document = gql`
1201
+ query getBalancesV2($filter: BalanceFilterInput!, $after: String, $before: String, $first: Int, $last: Int) {
1202
+ balances(
1203
+ filter: $filter
1204
+ after: $after
1205
+ before: $before
1206
+ first: $first
1207
+ last: $last
1208
+ ) {
1209
+ pageInfo {
1210
+ ...pageInfoFragment
1211
+ }
1212
+ edges {
1213
+ node {
1214
+ assetId
1215
+ amountU128
1216
+ }
1217
+ }
1218
+ }
1219
+ }
1220
+ ${PageInfoFragmentDoc}`;
1185
1221
  var GetMessagesDocument = gql`
1186
1222
  query getMessages($owner: Address!, $after: String, $before: String, $first: Int, $last: Int) {
1187
1223
  messages(
@@ -1236,6 +1272,15 @@ var GetRelayedTransactionStatusDocument = gql`
1236
1272
  }
1237
1273
  }
1238
1274
  ${RelayedTransactionStatusFragmentDoc}`;
1275
+ var GetAssetDetailsDocument = gql`
1276
+ query getAssetDetails($assetId: AssetId!) {
1277
+ assetDetails(id: $assetId) {
1278
+ subId
1279
+ contractId
1280
+ totalSupply
1281
+ }
1282
+ }
1283
+ `;
1239
1284
  var DryRunDocument = gql`
1240
1285
  mutation dryRun($encodedTransactions: [HexString!]!, $utxoValidation: Boolean, $gasPrice: U64) {
1241
1286
  dryRun(
@@ -1336,6 +1381,9 @@ function getSdk(requester) {
1336
1381
  estimatePredicates(variables, options) {
1337
1382
  return requester(EstimatePredicatesDocument, variables, options);
1338
1383
  },
1384
+ estimatePredicatesAndGasPrice(variables, options) {
1385
+ return requester(EstimatePredicatesAndGasPriceDocument, variables, options);
1386
+ },
1339
1387
  getLatestBlock(variables, options) {
1340
1388
  return requester(GetLatestBlockDocument, variables, options);
1341
1389
  },
@@ -1369,6 +1417,9 @@ function getSdk(requester) {
1369
1417
  getBalance(variables, options) {
1370
1418
  return requester(GetBalanceDocument, variables, options);
1371
1419
  },
1420
+ getBalanceV2(variables, options) {
1421
+ return requester(GetBalanceV2Document, variables, options);
1422
+ },
1372
1423
  getLatestGasPrice(variables, options) {
1373
1424
  return requester(GetLatestGasPriceDocument, variables, options);
1374
1425
  },
@@ -1378,6 +1429,9 @@ function getSdk(requester) {
1378
1429
  getBalances(variables, options) {
1379
1430
  return requester(GetBalancesDocument, variables, options);
1380
1431
  },
1432
+ getBalancesV2(variables, options) {
1433
+ return requester(GetBalancesV2Document, variables, options);
1434
+ },
1381
1435
  getMessages(variables, options) {
1382
1436
  return requester(GetMessagesDocument, variables, options);
1383
1437
  },
@@ -1393,6 +1447,9 @@ function getSdk(requester) {
1393
1447
  getRelayedTransactionStatus(variables, options) {
1394
1448
  return requester(GetRelayedTransactionStatusDocument, variables, options);
1395
1449
  },
1450
+ getAssetDetails(variables, options) {
1451
+ return requester(GetAssetDetailsDocument, variables, options);
1452
+ },
1396
1453
  dryRun(variables, options) {
1397
1454
  return requester(DryRunDocument, variables, options);
1398
1455
  },
@@ -1427,24 +1484,23 @@ import { print } from "graphql";
1427
1484
  // src/providers/utils/handle-gql-error-message.ts
1428
1485
  import { ErrorCode, FuelError as FuelError2 } from "@fuel-ts/errors";
1429
1486
  var mapGqlErrorMessage = (error) => {
1430
- switch (error.message) {
1431
- case "not enough coins to fit the target" /* NOT_ENOUGH_COINS */:
1432
- return new FuelError2(
1433
- ErrorCode.NOT_ENOUGH_FUNDS,
1434
- `The account(s) sending the transaction don't have enough funds to cover the transaction.`,
1435
- {},
1436
- error
1437
- );
1438
- case "max number of coins is reached while trying to fit the target" /* MAX_COINS_REACHED */:
1439
- return new FuelError2(
1440
- ErrorCode.MAX_COINS_REACHED,
1441
- "The account retrieving coins has exceeded the maximum number of coins per asset. Please consider combining your coins into a single UTXO.",
1442
- {},
1443
- error
1444
- );
1445
- default:
1446
- return new FuelError2(ErrorCode.INVALID_REQUEST, error.message, {}, error);
1487
+ if (new RegExp("the target cannot be met due to no coins available or exceeding the \\d+ coin limit." /* NOT_ENOUGH_COINS_MAX_COINS */).test(error.message)) {
1488
+ return new FuelError2(
1489
+ ErrorCode.INSUFFICIENT_FUNDS_OR_MAX_COINS,
1490
+ `Insufficient funds or too many small value coins. Consider combining UTXOs.`,
1491
+ {},
1492
+ error
1493
+ );
1447
1494
  }
1495
+ if (new RegExp("resource was not found in table" /* ASSET_NOT_FOUND */).test(error.message)) {
1496
+ return new FuelError2(
1497
+ ErrorCode.ASSET_NOT_FOUND,
1498
+ `Asset not found for given asset id.`,
1499
+ {},
1500
+ error
1501
+ );
1502
+ }
1503
+ return new FuelError2(ErrorCode.INVALID_REQUEST, error.message, {}, error);
1448
1504
  };
1449
1505
  var mapGqlErrorWithIncompatibleNodeVersion = (error, incompatibleNodeVersionMessage) => {
1450
1506
  if (!incompatibleNodeVersionMessage) {
@@ -1544,74 +1600,16 @@ __publicField(FuelGraphqlSubscriber, "incompatibleNodeVersionMessage", false);
1544
1600
  __publicField(FuelGraphqlSubscriber, "textDecoder", new TextDecoder());
1545
1601
 
1546
1602
  // src/providers/resource-cache.ts
1547
- import { ErrorCode as ErrorCode3, FuelError as FuelError4 } from "@fuel-ts/errors";
1548
- import { hexlify as hexlify4 } from "@fuel-ts/utils";
1549
- var cache = /* @__PURE__ */ new Map();
1550
- var ResourceCache = class {
1551
- ttl;
1552
- constructor(ttl) {
1553
- this.ttl = ttl;
1554
- if (typeof ttl !== "number" || this.ttl <= 0) {
1555
- throw new FuelError4(
1556
- ErrorCode3.INVALID_TTL,
1557
- `Invalid TTL: ${this.ttl}. Use a value greater than zero.`
1558
- );
1559
- }
1560
- }
1561
- // Add resources to the cache
1562
- set(transactionId, resources) {
1563
- const currentTime = Date.now();
1564
- const existingResources = cache.get(transactionId) || {
1565
- utxos: /* @__PURE__ */ new Set(),
1566
- messages: /* @__PURE__ */ new Set(),
1567
- timestamp: currentTime
1568
- };
1569
- resources.utxos.forEach((utxo) => existingResources.utxos.add(hexlify4(utxo)));
1570
- resources.messages.forEach((message) => existingResources.messages.add(hexlify4(message)));
1571
- cache.set(transactionId, existingResources);
1572
- }
1573
- // Remove resources from the cache for a given transaction ID
1574
- unset(transactionId) {
1575
- cache.delete(transactionId);
1576
- }
1577
- // Get all cached resources and remove expired ones
1578
- getActiveData() {
1579
- const allResources = { utxos: [], messages: [] };
1580
- const currentTime = Date.now();
1581
- cache.forEach((resource, transactionId) => {
1582
- if (currentTime - resource.timestamp < this.ttl) {
1583
- allResources.utxos.push(...resource.utxos);
1584
- allResources.messages.push(...resource.messages);
1585
- } else {
1586
- cache.delete(transactionId);
1587
- }
1588
- });
1589
- return allResources;
1590
- }
1591
- // Check if a UTXO ID or message nonce is already cached and not expired
1592
- isCached(key) {
1593
- const currentTime = Date.now();
1594
- for (const [transactionId, resourceData] of cache.entries()) {
1595
- if (currentTime - resourceData.timestamp > this.ttl) {
1596
- cache.delete(transactionId);
1597
- } else if (resourceData.utxos.has(key) || resourceData.messages.has(key)) {
1598
- return true;
1599
- }
1600
- }
1601
- return false;
1602
- }
1603
- clear() {
1604
- cache.clear();
1605
- }
1606
- };
1603
+ import { FuelError as FuelError13, ErrorCode as ErrorCode10 } from "@fuel-ts/errors";
1604
+ import { hexlify as hexlify16 } from "@fuel-ts/utils";
1607
1605
 
1608
1606
  // src/providers/transaction-request/input.ts
1609
1607
  import { BYTES_32 as BYTES_322, UTXO_ID_LEN } from "@fuel-ts/abi-coder";
1610
1608
  import { ZeroBytes32 } from "@fuel-ts/address/configs";
1611
- import { ErrorCode as ErrorCode4, FuelError as FuelError5 } from "@fuel-ts/errors";
1609
+ import { ErrorCode as ErrorCode3, FuelError as FuelError4 } from "@fuel-ts/errors";
1612
1610
  import { bn as bn2, toNumber } from "@fuel-ts/math";
1613
1611
  import { InputType } from "@fuel-ts/transactions";
1614
- import { arrayify as arrayify2, hexlify as hexlify5 } from "@fuel-ts/utils";
1612
+ import { arrayify as arrayify2, hexlify as hexlify4 } from "@fuel-ts/utils";
1615
1613
  var inputify = (value) => {
1616
1614
  const { type } = value;
1617
1615
  switch (value.type) {
@@ -1620,11 +1618,11 @@ var inputify = (value) => {
1620
1618
  const predicateData = arrayify2(value.predicateData ?? "0x");
1621
1619
  return {
1622
1620
  type: InputType.Coin,
1623
- txID: hexlify5(arrayify2(value.id).slice(0, BYTES_322)),
1621
+ txID: hexlify4(arrayify2(value.id).slice(0, BYTES_322)),
1624
1622
  outputIndex: toNumber(arrayify2(value.id).slice(BYTES_322, UTXO_ID_LEN)),
1625
- owner: hexlify5(value.owner),
1623
+ owner: hexlify4(value.owner),
1626
1624
  amount: bn2(value.amount),
1627
- assetId: hexlify5(value.assetId),
1625
+ assetId: hexlify4(value.assetId),
1628
1626
  txPointer: {
1629
1627
  blockHeight: toNumber(arrayify2(value.txPointer).slice(0, 8)),
1630
1628
  txIndex: toNumber(arrayify2(value.txPointer).slice(8, 16))
@@ -1633,8 +1631,8 @@ var inputify = (value) => {
1633
1631
  predicateGasUsed: bn2(value.predicateGasUsed),
1634
1632
  predicateLength: bn2(predicate.length),
1635
1633
  predicateDataLength: bn2(predicateData.length),
1636
- predicate: hexlify5(predicate),
1637
- predicateData: hexlify5(predicateData)
1634
+ predicate: hexlify4(predicate),
1635
+ predicateData: hexlify4(predicateData)
1638
1636
  };
1639
1637
  }
1640
1638
  case InputType.Contract: {
@@ -1648,7 +1646,7 @@ var inputify = (value) => {
1648
1646
  blockHeight: toNumber(arrayify2(value.txPointer).slice(0, 8)),
1649
1647
  txIndex: toNumber(arrayify2(value.txPointer).slice(8, 16))
1650
1648
  },
1651
- contractID: hexlify5(value.contractId)
1649
+ contractID: hexlify4(value.contractId)
1652
1650
  };
1653
1651
  }
1654
1652
  case InputType.Message: {
@@ -1657,23 +1655,23 @@ var inputify = (value) => {
1657
1655
  const data = arrayify2(value.data ?? "0x");
1658
1656
  return {
1659
1657
  type: InputType.Message,
1660
- sender: hexlify5(value.sender),
1661
- recipient: hexlify5(value.recipient),
1658
+ sender: hexlify4(value.sender),
1659
+ recipient: hexlify4(value.recipient),
1662
1660
  amount: bn2(value.amount),
1663
- nonce: hexlify5(value.nonce),
1661
+ nonce: hexlify4(value.nonce),
1664
1662
  witnessIndex: value.witnessIndex,
1665
1663
  predicateGasUsed: bn2(value.predicateGasUsed),
1666
1664
  predicateLength: bn2(predicate.length),
1667
1665
  predicateDataLength: bn2(predicateData.length),
1668
- predicate: hexlify5(predicate),
1669
- predicateData: hexlify5(predicateData),
1670
- data: hexlify5(data),
1666
+ predicate: hexlify4(predicate),
1667
+ predicateData: hexlify4(predicateData),
1668
+ data: hexlify4(data),
1671
1669
  dataLength: data.length
1672
1670
  };
1673
1671
  }
1674
1672
  default: {
1675
- throw new FuelError5(
1676
- ErrorCode4.INVALID_TRANSACTION_INPUT,
1673
+ throw new FuelError4(
1674
+ ErrorCode3.INVALID_TRANSACTION_INPUT,
1677
1675
  `Invalid transaction input type: ${type}.`
1678
1676
  );
1679
1677
  }
@@ -1682,19 +1680,19 @@ var inputify = (value) => {
1682
1680
 
1683
1681
  // src/providers/transaction-request/output.ts
1684
1682
  import { ZeroBytes32 as ZeroBytes322 } from "@fuel-ts/address/configs";
1685
- import { ErrorCode as ErrorCode5, FuelError as FuelError6 } from "@fuel-ts/errors";
1683
+ import { ErrorCode as ErrorCode4, FuelError as FuelError5 } from "@fuel-ts/errors";
1686
1684
  import { bn as bn3 } from "@fuel-ts/math";
1687
1685
  import { OutputType } from "@fuel-ts/transactions";
1688
- import { hexlify as hexlify6 } from "@fuel-ts/utils";
1686
+ import { hexlify as hexlify5 } from "@fuel-ts/utils";
1689
1687
  var outputify = (value) => {
1690
1688
  const { type } = value;
1691
1689
  switch (type) {
1692
1690
  case OutputType.Coin: {
1693
1691
  return {
1694
1692
  type: OutputType.Coin,
1695
- to: hexlify6(value.to),
1693
+ to: hexlify5(value.to),
1696
1694
  amount: bn3(value.amount),
1697
- assetId: hexlify6(value.assetId)
1695
+ assetId: hexlify5(value.assetId)
1698
1696
  };
1699
1697
  }
1700
1698
  case OutputType.Contract: {
@@ -1708,9 +1706,9 @@ var outputify = (value) => {
1708
1706
  case OutputType.Change: {
1709
1707
  return {
1710
1708
  type: OutputType.Change,
1711
- to: hexlify6(value.to),
1709
+ to: hexlify5(value.to),
1712
1710
  amount: bn3(0),
1713
- assetId: hexlify6(value.assetId)
1711
+ assetId: hexlify5(value.assetId)
1714
1712
  };
1715
1713
  }
1716
1714
  case OutputType.Variable: {
@@ -1724,13 +1722,13 @@ var outputify = (value) => {
1724
1722
  case OutputType.ContractCreated: {
1725
1723
  return {
1726
1724
  type: OutputType.ContractCreated,
1727
- contractId: hexlify6(value.contractId),
1728
- stateRoot: hexlify6(value.stateRoot)
1725
+ contractId: hexlify5(value.contractId),
1726
+ stateRoot: hexlify5(value.stateRoot)
1729
1727
  };
1730
1728
  }
1731
1729
  default: {
1732
- throw new FuelError6(
1733
- ErrorCode5.INVALID_TRANSACTION_INPUT,
1730
+ throw new FuelError5(
1731
+ ErrorCode4.INVALID_TRANSACTION_INPUT,
1734
1732
  `Invalid transaction output type: ${type}.`
1735
1733
  );
1736
1734
  }
@@ -1742,7 +1740,7 @@ import { UTXO_ID_LEN as UTXO_ID_LEN2 } from "@fuel-ts/abi-coder";
1742
1740
  import { Address as Address2, addressify } from "@fuel-ts/address";
1743
1741
  import { ZeroBytes32 as ZeroBytes324 } from "@fuel-ts/address/configs";
1744
1742
  import { randomBytes as randomBytes3 } from "@fuel-ts/crypto";
1745
- import { FuelError as FuelError11 } from "@fuel-ts/errors";
1743
+ import { FuelError as FuelError10 } from "@fuel-ts/errors";
1746
1744
  import { bn as bn8 } from "@fuel-ts/math";
1747
1745
  import {
1748
1746
  PolicyType,
@@ -1760,31 +1758,157 @@ var isMessageCoin = (message) => !("data" in message);
1760
1758
  var isCoin = (resource) => "id" in resource;
1761
1759
 
1762
1760
  // src/providers/utils/receipts.ts
1761
+ import { ReceiptType as ReceiptType2 } from "@fuel-ts/transactions";
1762
+ import { FAILED_TRANSFER_TO_ADDRESS_SIGNAL } from "@fuel-ts/transactions/configs";
1763
+
1764
+ // src/providers/utils/serialization.ts
1763
1765
  import { ZeroBytes32 as ZeroBytes323 } from "@fuel-ts/address/configs";
1764
- import { ErrorCode as ErrorCode6, FuelError as FuelError7 } from "@fuel-ts/errors";
1766
+ import { ErrorCode as ErrorCode5, FuelError as FuelError6 } from "@fuel-ts/errors";
1765
1767
  import { bn as bn4 } from "@fuel-ts/math";
1766
1768
  import { getMintedAssetId, InputMessageCoder, ReceiptType } from "@fuel-ts/transactions";
1767
- import { FAILED_TRANSFER_TO_ADDRESS_SIGNAL } from "@fuel-ts/transactions/configs";
1768
- import { arrayify as arrayify3, hexlify as hexlify7 } from "@fuel-ts/utils";
1769
- var doesReceiptHaveMissingOutputVariables = (receipt) => receipt.type === ReceiptType.Revert && receipt.val.toString("hex") === FAILED_TRANSFER_TO_ADDRESS_SIGNAL;
1770
- var doesReceiptHaveMissingContractId = (receipt) => receipt.type === ReceiptType.Panic && receipt.contractId !== "0x0000000000000000000000000000000000000000000000000000000000000000";
1771
- var getReceiptsWithMissingData = (receipts) => receipts.reduce(
1772
- (memo, receipt) => {
1773
- if (doesReceiptHaveMissingOutputVariables(receipt)) {
1774
- memo.missingOutputVariables.push(receipt);
1769
+ import { hexlify as hexlify6, arrayify as arrayify3 } from "@fuel-ts/utils";
1770
+ var deserializeChain = (chain) => {
1771
+ const { name, daHeight, consensusParameters } = chain;
1772
+ const {
1773
+ contractParams,
1774
+ feeParams,
1775
+ predicateParams,
1776
+ scriptParams,
1777
+ txParams,
1778
+ gasCosts,
1779
+ baseAssetId,
1780
+ chainId,
1781
+ version
1782
+ } = consensusParameters;
1783
+ return {
1784
+ name,
1785
+ baseChainHeight: bn4(daHeight),
1786
+ consensusParameters: {
1787
+ version,
1788
+ chainId: bn4(chainId),
1789
+ baseAssetId,
1790
+ feeParameters: {
1791
+ version: feeParams.version,
1792
+ gasPerByte: bn4(feeParams.gasPerByte),
1793
+ gasPriceFactor: bn4(feeParams.gasPriceFactor)
1794
+ },
1795
+ contractParameters: {
1796
+ version: contractParams.version,
1797
+ contractMaxSize: bn4(contractParams.contractMaxSize),
1798
+ maxStorageSlots: bn4(contractParams.maxStorageSlots)
1799
+ },
1800
+ txParameters: {
1801
+ version: txParams.version,
1802
+ maxInputs: bn4(txParams.maxInputs),
1803
+ maxOutputs: bn4(txParams.maxOutputs),
1804
+ maxWitnesses: bn4(txParams.maxWitnesses),
1805
+ maxGasPerTx: bn4(txParams.maxGasPerTx),
1806
+ maxSize: bn4(txParams.maxSize),
1807
+ maxBytecodeSubsections: bn4(txParams.maxBytecodeSubsections)
1808
+ },
1809
+ predicateParameters: {
1810
+ version: predicateParams.version,
1811
+ maxPredicateLength: bn4(predicateParams.maxPredicateLength),
1812
+ maxPredicateDataLength: bn4(predicateParams.maxPredicateDataLength),
1813
+ maxGasPerPredicate: bn4(predicateParams.maxGasPerPredicate),
1814
+ maxMessageDataLength: bn4(predicateParams.maxMessageDataLength)
1815
+ },
1816
+ scriptParameters: {
1817
+ version: scriptParams.version,
1818
+ maxScriptLength: bn4(scriptParams.maxScriptLength),
1819
+ maxScriptDataLength: bn4(scriptParams.maxScriptDataLength)
1820
+ },
1821
+ gasCosts
1775
1822
  }
1776
- if (doesReceiptHaveMissingContractId(receipt)) {
1777
- memo.missingOutputContractIds.push(receipt);
1823
+ };
1824
+ };
1825
+ var serializeChain = (chain) => {
1826
+ const { name, baseChainHeight, consensusParameters } = chain;
1827
+ const {
1828
+ contractParameters,
1829
+ feeParameters,
1830
+ predicateParameters,
1831
+ scriptParameters,
1832
+ txParameters,
1833
+ gasCosts,
1834
+ baseAssetId,
1835
+ chainId,
1836
+ version
1837
+ } = consensusParameters;
1838
+ return {
1839
+ name,
1840
+ daHeight: baseChainHeight.toString(),
1841
+ consensusParameters: {
1842
+ version,
1843
+ chainId: chainId.toString(),
1844
+ baseAssetId,
1845
+ feeParams: {
1846
+ version: feeParameters.version,
1847
+ gasPerByte: feeParameters.gasPerByte.toString(),
1848
+ gasPriceFactor: feeParameters.gasPriceFactor.toString()
1849
+ },
1850
+ contractParams: {
1851
+ version: contractParameters.version,
1852
+ contractMaxSize: contractParameters.contractMaxSize.toString(),
1853
+ maxStorageSlots: contractParameters.maxStorageSlots.toString()
1854
+ },
1855
+ txParams: {
1856
+ version: txParameters.version,
1857
+ maxInputs: txParameters.maxInputs.toString(),
1858
+ maxOutputs: txParameters.maxOutputs.toString(),
1859
+ maxWitnesses: txParameters.maxWitnesses.toString(),
1860
+ maxGasPerTx: txParameters.maxGasPerTx.toString(),
1861
+ maxSize: txParameters.maxSize.toString(),
1862
+ maxBytecodeSubsections: txParameters.maxBytecodeSubsections.toString()
1863
+ },
1864
+ predicateParams: {
1865
+ version: predicateParameters.version,
1866
+ maxPredicateLength: predicateParameters.maxPredicateLength.toString(),
1867
+ maxPredicateDataLength: predicateParameters.maxPredicateDataLength.toString(),
1868
+ maxGasPerPredicate: predicateParameters.maxGasPerPredicate.toString(),
1869
+ maxMessageDataLength: predicateParameters.maxMessageDataLength.toString()
1870
+ },
1871
+ scriptParams: {
1872
+ version: scriptParameters.version,
1873
+ maxScriptLength: scriptParameters.maxScriptLength.toString(),
1874
+ maxScriptDataLength: scriptParameters.maxScriptDataLength.toString()
1875
+ },
1876
+ gasCosts
1778
1877
  }
1779
- return memo;
1780
- },
1781
- {
1782
- missingOutputVariables: [],
1783
- missingOutputContractIds: []
1784
- }
1785
- );
1878
+ };
1879
+ };
1880
+ var deserializeNodeInfo = (nodeInfo) => {
1881
+ const { maxDepth, maxTx, nodeVersion, utxoValidation, vmBacktrace } = nodeInfo;
1882
+ return {
1883
+ maxDepth: bn4(maxDepth),
1884
+ maxTx: bn4(maxTx),
1885
+ nodeVersion,
1886
+ utxoValidation,
1887
+ vmBacktrace
1888
+ };
1889
+ };
1890
+ var serializeNodeInfo = (nodeInfo) => {
1891
+ const { maxDepth, maxTx, nodeVersion, utxoValidation, vmBacktrace } = nodeInfo;
1892
+ return {
1893
+ maxDepth: maxDepth.toString(),
1894
+ maxTx: maxTx.toString(),
1895
+ nodeVersion,
1896
+ utxoValidation,
1897
+ vmBacktrace
1898
+ };
1899
+ };
1900
+ var deserializeProviderCache = (cache2) => ({
1901
+ consensusParametersTimestamp: cache2.consensusParametersTimestamp,
1902
+ chain: deserializeChain(cache2.chain),
1903
+ nodeInfo: deserializeNodeInfo(cache2.nodeInfo)
1904
+ });
1905
+ var serializeProviderCache = async (provider) => ({
1906
+ consensusParametersTimestamp: provider.consensusParametersTimestamp,
1907
+ chain: serializeChain(await provider.getChain()),
1908
+ nodeInfo: serializeNodeInfo(await provider.getNode())
1909
+ });
1786
1910
  var hexOrZero = (hex) => hex || ZeroBytes323;
1787
- function assembleReceiptByType(receipt) {
1911
+ var deserializeReceipt = (receipt) => {
1788
1912
  const { receiptType } = receipt;
1789
1913
  switch (receiptType) {
1790
1914
  case "CALL" /* Call */: {
@@ -1928,7 +2052,7 @@ function assembleReceiptByType(receipt) {
1928
2052
  recipient,
1929
2053
  nonce,
1930
2054
  amount,
1931
- data: hexlify7(data)
2055
+ data: hexlify6(data)
1932
2056
  });
1933
2057
  const receiptMessageOut = {
1934
2058
  type: ReceiptType.MessageOut,
@@ -1974,20 +2098,39 @@ function assembleReceiptByType(receipt) {
1974
2098
  return burnReceipt;
1975
2099
  }
1976
2100
  default:
1977
- throw new FuelError7(ErrorCode6.INVALID_RECEIPT_TYPE, `Invalid receipt type: ${receiptType}.`);
2101
+ throw new FuelError6(ErrorCode5.INVALID_RECEIPT_TYPE, `Invalid receipt type: ${receiptType}.`);
1978
2102
  }
1979
- }
2103
+ };
2104
+
2105
+ // src/providers/utils/receipts.ts
2106
+ var doesReceiptHaveMissingOutputVariables = (receipt) => receipt.type === ReceiptType2.Revert && receipt.val.toString("hex") === FAILED_TRANSFER_TO_ADDRESS_SIGNAL;
2107
+ var doesReceiptHaveMissingContractId = (receipt) => receipt.type === ReceiptType2.Panic && receipt.contractId !== "0x0000000000000000000000000000000000000000000000000000000000000000";
2108
+ var getReceiptsWithMissingData = (receipts) => receipts.reduce(
2109
+ (memo, receipt) => {
2110
+ if (doesReceiptHaveMissingOutputVariables(receipt)) {
2111
+ memo.missingOutputVariables.push(receipt);
2112
+ }
2113
+ if (doesReceiptHaveMissingContractId(receipt)) {
2114
+ memo.missingOutputContractIds.push(receipt);
2115
+ }
2116
+ return memo;
2117
+ },
2118
+ {
2119
+ missingOutputVariables: [],
2120
+ missingOutputContractIds: []
2121
+ }
2122
+ );
1980
2123
 
1981
2124
  // src/providers/utils/block-explorer.ts
1982
- import { ErrorCode as ErrorCode7, FuelError as FuelError8 } from "@fuel-ts/errors";
2125
+ import { ErrorCode as ErrorCode6, FuelError as FuelError7 } from "@fuel-ts/errors";
1983
2126
 
1984
2127
  // src/providers/utils/gas.ts
1985
2128
  import { bn as bn5 } from "@fuel-ts/math";
1986
- import { ReceiptType as ReceiptType2 } from "@fuel-ts/transactions";
2129
+ import { ReceiptType as ReceiptType3 } from "@fuel-ts/transactions";
1987
2130
  import { arrayify as arrayify4 } from "@fuel-ts/utils";
1988
2131
  var getGasUsedFromReceipts = (receipts) => {
1989
2132
  const scriptResult = receipts.filter(
1990
- (receipt) => receipt.type === ReceiptType2.ScriptResult
2133
+ (receipt) => receipt.type === ReceiptType3.ScriptResult
1991
2134
  );
1992
2135
  const gasUsed = scriptResult.reduce((prev, receipt) => prev.add(receipt.gasUsed), bn5(0));
1993
2136
  return gasUsed;
@@ -2120,13 +2263,13 @@ var calculateGasFee = (params) => {
2120
2263
  };
2121
2264
 
2122
2265
  // src/providers/utils/json.ts
2123
- import { hexlify as hexlify8 } from "@fuel-ts/utils";
2266
+ import { hexlify as hexlify7 } from "@fuel-ts/utils";
2124
2267
  import { clone } from "ramda";
2125
2268
  function normalize(object) {
2126
2269
  Object.keys(object).forEach((key) => {
2127
2270
  switch (object[key]?.constructor.name) {
2128
2271
  case "Uint8Array":
2129
- object[key] = hexlify8(object[key]);
2272
+ object[key] = hexlify7(object[key]);
2130
2273
  break;
2131
2274
  case "Array":
2132
2275
  object[key] = normalize(object[key]);
@@ -2151,9 +2294,9 @@ function normalizeJSON(root) {
2151
2294
  }
2152
2295
 
2153
2296
  // src/providers/utils/extract-tx-error.ts
2154
- import { ErrorCode as ErrorCode8, FuelError as FuelError9 } from "@fuel-ts/errors";
2297
+ import { ErrorCode as ErrorCode7, FuelError as FuelError8 } from "@fuel-ts/errors";
2155
2298
  import { bn as bn6 } from "@fuel-ts/math";
2156
- import { ReceiptType as ReceiptType3 } from "@fuel-ts/transactions";
2299
+ import { ReceiptType as ReceiptType4 } from "@fuel-ts/transactions";
2157
2300
  import {
2158
2301
  FAILED_REQUIRE_SIGNAL,
2159
2302
  FAILED_ASSERT_EQ_SIGNAL,
@@ -2172,7 +2315,7 @@ You can read more about this error at:
2172
2315
 
2173
2316
  ${PANIC_DOC_URL}#variant.${statusReason}`;
2174
2317
  }
2175
- return new FuelError9(ErrorCode8.SCRIPT_REVERTED, errorMessage, {
2318
+ return new FuelError8(ErrorCode7.SCRIPT_REVERTED, errorMessage, {
2176
2319
  ...metadata,
2177
2320
  reason: statusReason
2178
2321
  });
@@ -2180,7 +2323,7 @@ ${PANIC_DOC_URL}#variant.${statusReason}`;
2180
2323
  var stringify = (obj) => JSON.stringify(obj, null, 2);
2181
2324
  var assembleRevertError = (receipts, logs, metadata) => {
2182
2325
  let errorMessage = "The transaction reverted with an unknown reason.";
2183
- const revertReceipt = receipts.find(({ type }) => type === ReceiptType3.Revert);
2326
+ const revertReceipt = receipts.find(({ type }) => type === ReceiptType4.Revert);
2184
2327
  let reason = "";
2185
2328
  if (revertReceipt) {
2186
2329
  const reasonHex = bn6(revertReceipt.val).toHex();
@@ -2193,15 +2336,15 @@ var assembleRevertError = (receipts, logs, metadata) => {
2193
2336
  break;
2194
2337
  }
2195
2338
  case FAILED_ASSERT_EQ_SIGNAL: {
2196
- const sufix = logs.length >= 2 ? ` comparing ${stringify(lastLog)} and ${stringify(lastButOneLog)}.` : ".";
2339
+ const suffix = logs.length >= 2 ? ` comparing ${stringify(lastLog)} and ${stringify(lastButOneLog)}.` : ".";
2197
2340
  reason = "assert_eq";
2198
- errorMessage = `The transaction reverted because of an "assert_eq" statement${sufix}`;
2341
+ errorMessage = `The transaction reverted because of an "assert_eq" statement${suffix}`;
2199
2342
  break;
2200
2343
  }
2201
2344
  case FAILED_ASSERT_NE_SIGNAL: {
2202
- const sufix = logs.length >= 2 ? ` comparing ${stringify(lastButOneLog)} and ${stringify(lastLog)}.` : ".";
2345
+ const suffix = logs.length >= 2 ? ` comparing ${stringify(lastButOneLog)} and ${stringify(lastLog)}.` : ".";
2203
2346
  reason = "assert_ne";
2204
- errorMessage = `The transaction reverted because of an "assert_ne" statement${sufix}`;
2347
+ errorMessage = `The transaction reverted because of an "assert_ne" statement${suffix}`;
2205
2348
  break;
2206
2349
  }
2207
2350
  case FAILED_ASSERT_SIGNAL:
@@ -2209,12 +2352,12 @@ var assembleRevertError = (receipts, logs, metadata) => {
2209
2352
  errorMessage = `The transaction reverted because an "assert" statement failed to evaluate to true.`;
2210
2353
  break;
2211
2354
  case FAILED_TRANSFER_TO_ADDRESS_SIGNAL2:
2212
- reason = "MissingOutputChange";
2213
- errorMessage = `The transaction reverted because it's missing an "OutputChange".`;
2355
+ reason = "MissingOutputVariable";
2356
+ errorMessage = `The transaction reverted because it's missing an "OutputVariable".`;
2214
2357
  break;
2215
2358
  default:
2216
- throw new FuelError9(
2217
- ErrorCode8.UNKNOWN,
2359
+ throw new FuelError8(
2360
+ ErrorCode7.UNKNOWN,
2218
2361
  `The transaction reverted with an unknown reason: ${revertReceipt.val}`,
2219
2362
  {
2220
2363
  ...metadata,
@@ -2223,15 +2366,15 @@ var assembleRevertError = (receipts, logs, metadata) => {
2223
2366
  );
2224
2367
  }
2225
2368
  }
2226
- return new FuelError9(ErrorCode8.SCRIPT_REVERTED, errorMessage, {
2369
+ return new FuelError8(ErrorCode7.SCRIPT_REVERTED, errorMessage, {
2227
2370
  ...metadata,
2228
2371
  reason
2229
2372
  });
2230
2373
  };
2231
2374
  var extractTxError = (params) => {
2232
2375
  const { receipts, statusReason, logs } = params;
2233
- const isPanic = receipts.some(({ type }) => type === ReceiptType3.Panic);
2234
- const isRevert = receipts.some(({ type }) => type === ReceiptType3.Revert);
2376
+ const isPanic = receipts.some(({ type }) => type === ReceiptType4.Panic);
2377
+ const isRevert = receipts.some(({ type }) => type === ReceiptType4.Revert);
2235
2378
  const metadata = {
2236
2379
  logs,
2237
2380
  receipts,
@@ -2256,9 +2399,10 @@ var NoWitnessAtIndexError = class extends Error {
2256
2399
  };
2257
2400
 
2258
2401
  // src/providers/transaction-request/helpers.ts
2259
- import { ErrorCode as ErrorCode9, FuelError as FuelError10 } from "@fuel-ts/errors";
2402
+ import { ErrorCode as ErrorCode8, FuelError as FuelError9 } from "@fuel-ts/errors";
2260
2403
  import { bn as bn7 } from "@fuel-ts/math";
2261
2404
  import { InputType as InputType2, OutputType as OutputType2 } from "@fuel-ts/transactions";
2405
+ import { hexlify as hexlify8 } from "@fuel-ts/utils";
2262
2406
  var isRequestInputCoin = (input) => input.type === InputType2.Coin;
2263
2407
  var isRequestInputMessage = (input) => input.type === InputType2.Message;
2264
2408
  var isRequestInputMessageWithoutData = (input) => input.type === InputType2.Message && bn7(input.data).isZero();
@@ -2266,6 +2410,7 @@ var isRequestInputCoinOrMessage = (input) => isRequestInputCoin(input) || isRequ
2266
2410
  var isRequestInputResource = (input) => isRequestInputCoin(input) || isRequestInputMessageWithoutData(input);
2267
2411
  var getRequestInputResourceOwner = (input) => isRequestInputCoin(input) ? input.owner : input.recipient;
2268
2412
  var isRequestInputResourceFromOwner = (input, owner) => getRequestInputResourceOwner(input) === owner.toB256();
2413
+ var isPredicate = (input) => isRequestInputCoinOrMessage(input) && !!input.predicate && hexlify8(input.predicate) !== "0x";
2269
2414
  var getAssetAmountInRequestInputs = (inputs, assetId, baseAsset) => inputs.filter(isRequestInputResource).reduce((acc, input) => {
2270
2415
  if (isRequestInputCoin(input) && input.assetId === assetId) {
2271
2416
  return acc.add(input.amount);
@@ -2313,7 +2458,7 @@ var validateTransactionForAssetBurn = (baseAssetId, transactionRequest, enableAs
2313
2458
  "Add the relevant change outputs to the transaction to avoid burning assets.",
2314
2459
  "Or enable asset burn, upon sending the transaction."
2315
2460
  ].join("\n");
2316
- throw new FuelError10(ErrorCode9.ASSET_BURN_DETECTED, message);
2461
+ throw new FuelError9(ErrorCode8.ASSET_BURN_DETECTED, message);
2317
2462
  };
2318
2463
 
2319
2464
  // src/providers/transaction-request/witness.ts
@@ -2332,6 +2477,8 @@ var BaseTransactionRequest = class {
2332
2477
  tip;
2333
2478
  /** Block until which tx cannot be included */
2334
2479
  maturity;
2480
+ /** The block number after which the transaction is no longer valid. */
2481
+ expiration;
2335
2482
  /** The maximum fee payable by this transaction using BASE_ASSET. */
2336
2483
  maxFee;
2337
2484
  /** The maximum amount of witness data allowed for the transaction */
@@ -2342,6 +2489,12 @@ var BaseTransactionRequest = class {
2342
2489
  outputs = [];
2343
2490
  /** List of witnesses */
2344
2491
  witnesses = [];
2492
+ /**
2493
+ * @hidden
2494
+ *
2495
+ * The current status of the transaction
2496
+ */
2497
+ flag = { state: void 0, transactionId: void 0, summary: void 0 };
2345
2498
  /**
2346
2499
  * Constructor for initializing a base transaction request.
2347
2500
  *
@@ -2350,6 +2503,7 @@ var BaseTransactionRequest = class {
2350
2503
  constructor({
2351
2504
  tip,
2352
2505
  maturity,
2506
+ expiration,
2353
2507
  maxFee,
2354
2508
  witnessLimit,
2355
2509
  inputs,
@@ -2358,6 +2512,7 @@ var BaseTransactionRequest = class {
2358
2512
  } = {}) {
2359
2513
  this.tip = tip ? bn8(tip) : void 0;
2360
2514
  this.maturity = maturity && maturity > 0 ? maturity : void 0;
2515
+ this.expiration = expiration && expiration > 0 ? expiration : void 0;
2361
2516
  this.witnessLimit = isDefined(witnessLimit) ? bn8(witnessLimit) : void 0;
2362
2517
  this.maxFee = bn8(maxFee);
2363
2518
  this.inputs = inputs ?? [];
@@ -2367,7 +2522,7 @@ var BaseTransactionRequest = class {
2367
2522
  static getPolicyMeta(req) {
2368
2523
  let policyTypes = 0;
2369
2524
  const policies = [];
2370
- const { tip, witnessLimit, maturity } = req;
2525
+ const { tip, witnessLimit, maturity, expiration } = req;
2371
2526
  if (bn8(tip).gt(0)) {
2372
2527
  policyTypes += PolicyType.Tip;
2373
2528
  policies.push({ data: bn8(tip), type: PolicyType.Tip });
@@ -2382,6 +2537,10 @@ var BaseTransactionRequest = class {
2382
2537
  }
2383
2538
  policyTypes += PolicyType.MaxFee;
2384
2539
  policies.push({ data: req.maxFee, type: PolicyType.MaxFee });
2540
+ if (expiration && expiration > 0) {
2541
+ policyTypes += PolicyType.Expiration;
2542
+ policies.push({ data: expiration, type: PolicyType.Expiration });
2543
+ }
2385
2544
  return {
2386
2545
  policyTypes,
2387
2546
  policies
@@ -2454,8 +2613,7 @@ var BaseTransactionRequest = class {
2454
2613
  * @returns The index of the created witness.
2455
2614
  */
2456
2615
  addEmptyWitness() {
2457
- this.addWitness(concat2([ZeroBytes324, ZeroBytes324]));
2458
- return this.witnesses.length - 1;
2616
+ return this.addWitness(concat2([ZeroBytes324, ZeroBytes324]));
2459
2617
  }
2460
2618
  /**
2461
2619
  * Updates the witness for a given owner and signature.
@@ -2698,7 +2856,7 @@ var BaseTransactionRequest = class {
2698
2856
  * @hidden
2699
2857
  */
2700
2858
  metadataGas(_gasCosts) {
2701
- throw new FuelError11(FuelError11.CODES.NOT_IMPLEMENTED, "Not implemented");
2859
+ throw new FuelError10(FuelError10.CODES.NOT_IMPLEMENTED, "Not implemented");
2702
2860
  }
2703
2861
  /**
2704
2862
  * @hidden
@@ -2825,6 +2983,21 @@ var BaseTransactionRequest = class {
2825
2983
  byteLength() {
2826
2984
  return this.toTransactionBytes().byteLength;
2827
2985
  }
2986
+ /**
2987
+ * @hidden
2988
+ *
2989
+ * Used internally to update the state of a transaction request.
2990
+ *
2991
+ * @param state - The state to update.
2992
+ */
2993
+ updateState(chainId, state, summary) {
2994
+ if (!state) {
2995
+ this.flag = { state: void 0, transactionId: void 0, summary: void 0 };
2996
+ return;
2997
+ }
2998
+ const transactionId = this.getTransactionId(chainId);
2999
+ this.flag = { state, transactionId, summary };
3000
+ }
2828
3001
  };
2829
3002
 
2830
3003
  // src/providers/transaction-request/blob-transaction-request.ts
@@ -3306,7 +3479,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3306
3479
  };
3307
3480
 
3308
3481
  // src/providers/transaction-request/upgrade-transaction-request.ts
3309
- import { FuelError as FuelError12 } from "@fuel-ts/errors";
3482
+ import { FuelError as FuelError11 } from "@fuel-ts/errors";
3310
3483
  import { hash as hash2 } from "@fuel-ts/hasher";
3311
3484
  import {
3312
3485
  TransactionType as TransactionType5,
@@ -3413,7 +3586,7 @@ var UpgradeTransactionRequest = class extends BaseTransactionRequest {
3413
3586
  }
3414
3587
  };
3415
3588
  } else {
3416
- throw new FuelError12(FuelError12.CODES.NOT_IMPLEMENTED, "Invalid upgrade purpose");
3589
+ throw new FuelError11(FuelError11.CODES.NOT_IMPLEMENTED, "Invalid upgrade purpose");
3417
3590
  }
3418
3591
  return {
3419
3592
  type: TransactionType5.Upgrade,
@@ -3455,7 +3628,7 @@ var UpgradeTransactionRequest = class extends BaseTransactionRequest {
3455
3628
  txBytesSize
3456
3629
  });
3457
3630
  }
3458
- throw new FuelError12(FuelError12.CODES.NOT_IMPLEMENTED, "Invalid upgrade purpose");
3631
+ throw new FuelError11(FuelError11.CODES.NOT_IMPLEMENTED, "Invalid upgrade purpose");
3459
3632
  }
3460
3633
  };
3461
3634
 
@@ -3566,7 +3739,7 @@ var UploadTransactionRequest = class extends BaseTransactionRequest {
3566
3739
  };
3567
3740
 
3568
3741
  // src/providers/transaction-request/utils.ts
3569
- import { ErrorCode as ErrorCode10, FuelError as FuelError13 } from "@fuel-ts/errors";
3742
+ import { ErrorCode as ErrorCode9, FuelError as FuelError12 } from "@fuel-ts/errors";
3570
3743
  import { TransactionType as TransactionType7 } from "@fuel-ts/transactions";
3571
3744
  var transactionRequestify = (obj) => {
3572
3745
  if (obj instanceof ScriptTransactionRequest || obj instanceof CreateTransactionRequest || obj instanceof BlobTransactionRequest || obj instanceof UpgradeTransactionRequest || obj instanceof UploadTransactionRequest) {
@@ -3590,8 +3763,8 @@ var transactionRequestify = (obj) => {
3590
3763
  return UploadTransactionRequest.from(obj);
3591
3764
  }
3592
3765
  default: {
3593
- throw new FuelError13(
3594
- ErrorCode10.UNSUPPORTED_TRANSACTION_TYPE,
3766
+ throw new FuelError12(
3767
+ ErrorCode9.UNSUPPORTED_TRANSACTION_TYPE,
3595
3768
  `Unsupported transaction type: ${type}.`
3596
3769
  );
3597
3770
  }
@@ -3600,6 +3773,97 @@ var transactionRequestify = (obj) => {
3600
3773
  var isTransactionTypeScript = (request) => request.type === TransactionType7.Script;
3601
3774
  var isTransactionTypeCreate = (request) => request.type === TransactionType7.Create;
3602
3775
 
3776
+ // src/providers/resource-cache.ts
3777
+ var cache = /* @__PURE__ */ new Map();
3778
+ var ResourceCache = class {
3779
+ ttl;
3780
+ constructor(ttl) {
3781
+ this.ttl = ttl;
3782
+ if (typeof ttl !== "number" || this.ttl <= 0) {
3783
+ throw new FuelError13(
3784
+ ErrorCode10.INVALID_TTL,
3785
+ `Invalid TTL: ${this.ttl}. Use a value greater than zero.`
3786
+ );
3787
+ }
3788
+ }
3789
+ // Add resources to the cache
3790
+ set(transactionId, inputs) {
3791
+ const transactionResourceCache = this.setupResourcesCache(inputs);
3792
+ cache.set(transactionId, transactionResourceCache);
3793
+ }
3794
+ unset(transactionId) {
3795
+ cache.delete(transactionId);
3796
+ }
3797
+ getActiveData(owner) {
3798
+ const activeData = { utxos: [], messages: [] };
3799
+ const currentTime = Date.now();
3800
+ const expired = [];
3801
+ cache.forEach((resource, transactionId) => {
3802
+ const isActive = currentTime - resource.timestamp < this.ttl;
3803
+ if (isActive) {
3804
+ const resourcesFromOwner = resource.owners.get(owner);
3805
+ if (resourcesFromOwner) {
3806
+ activeData.utxos.push(...resourcesFromOwner.utxos);
3807
+ activeData.messages.push(...resourcesFromOwner.messages);
3808
+ }
3809
+ } else {
3810
+ expired.push(transactionId);
3811
+ }
3812
+ });
3813
+ expired.forEach(this.unset);
3814
+ activeData.utxos.reverse();
3815
+ activeData.messages.reverse();
3816
+ return activeData;
3817
+ }
3818
+ isCached(owner, key) {
3819
+ const currentTime = Date.now();
3820
+ let cached = false;
3821
+ const expired = [];
3822
+ for (const [transactionId, resourceData] of cache.entries()) {
3823
+ const isActive = currentTime - resourceData.timestamp < this.ttl;
3824
+ if (isActive) {
3825
+ const resourcesFromOwner = resourceData.owners.get(owner);
3826
+ if (resourcesFromOwner?.utxos.has(key) || resourcesFromOwner?.messages.has(key)) {
3827
+ cached = true;
3828
+ break;
3829
+ }
3830
+ } else {
3831
+ expired.push(transactionId);
3832
+ }
3833
+ }
3834
+ expired.forEach(this.unset);
3835
+ return cached;
3836
+ }
3837
+ clear() {
3838
+ cache.clear();
3839
+ }
3840
+ setupResourcesCache(inputs) {
3841
+ const currentTime = Date.now();
3842
+ const transactionResourcesCache = {
3843
+ owners: /* @__PURE__ */ new Map(),
3844
+ timestamp: currentTime
3845
+ };
3846
+ inputs.filter(isRequestInputCoinOrMessage).forEach((input) => {
3847
+ const { owner, key, type } = this.extractResourceData(input);
3848
+ if (!transactionResourcesCache.owners.has(owner)) {
3849
+ transactionResourcesCache.owners.set(owner, { utxos: /* @__PURE__ */ new Set(), messages: /* @__PURE__ */ new Set() });
3850
+ }
3851
+ if (type === "utxo") {
3852
+ transactionResourcesCache.owners.get(owner)?.utxos.add(key);
3853
+ } else {
3854
+ transactionResourcesCache.owners.get(owner)?.messages.add(key);
3855
+ }
3856
+ });
3857
+ return transactionResourcesCache;
3858
+ }
3859
+ extractResourceData(input) {
3860
+ if (isRequestInputCoin(input)) {
3861
+ return { owner: hexlify16(input.owner), key: hexlify16(input.id), type: "utxo" };
3862
+ }
3863
+ return { owner: hexlify16(input.recipient), key: hexlify16(input.nonce), type: "message" };
3864
+ }
3865
+ };
3866
+
3603
3867
  // src/providers/transaction-response/transaction-response.ts
3604
3868
  import { ErrorCode as ErrorCode14, FuelError as FuelError17 } from "@fuel-ts/errors";
3605
3869
  import { bn as bn16 } from "@fuel-ts/math";
@@ -3609,7 +3873,7 @@ import { arrayify as arrayify12, assertUnreachable } from "@fuel-ts/utils";
3609
3873
  // src/providers/transaction-summary/assemble-transaction-summary.ts
3610
3874
  import { bn as bn15 } from "@fuel-ts/math";
3611
3875
  import { PolicyType as PolicyType3 } from "@fuel-ts/transactions";
3612
- import { DateTime, hexlify as hexlify16 } from "@fuel-ts/utils";
3876
+ import { DateTime, hexlify as hexlify17 } from "@fuel-ts/utils";
3613
3877
 
3614
3878
  // src/providers/transaction-summary/calculate-tx-fee-for-summary.ts
3615
3879
  import { bn as bn12 } from "@fuel-ts/math";
@@ -3681,40 +3945,7 @@ var calculateTXFeeForSummary = (params) => {
3681
3945
  import { ZeroBytes32 as ZeroBytes329 } from "@fuel-ts/address/configs";
3682
3946
  import { ErrorCode as ErrorCode12, FuelError as FuelError15 } from "@fuel-ts/errors";
3683
3947
  import { bn as bn13 } from "@fuel-ts/math";
3684
- import { ReceiptType as ReceiptType4, TransactionType as TransactionType9 } from "@fuel-ts/transactions";
3685
-
3686
- // src/providers/transaction-summary/call.ts
3687
- import { Interface as Interface2 } from "@fuel-ts/abi-coder";
3688
- var getFunctionCall = ({ abi, receipt }) => {
3689
- const abiInterface = new Interface2(abi);
3690
- const callFunctionSelector = receipt.param1.toHex(8);
3691
- const functionFragment = abiInterface.getFunction(callFunctionSelector);
3692
- const inputs = functionFragment.jsonFn.inputs;
3693
- const encodedArgs = receipt.param2.toHex();
3694
- let argumentsProvided;
3695
- const data = functionFragment.decodeArguments(encodedArgs);
3696
- if (data) {
3697
- argumentsProvided = inputs.reduce((prev, input, index) => {
3698
- const value = data[index];
3699
- const name = input.name;
3700
- if (name) {
3701
- return {
3702
- ...prev,
3703
- // reparse to remove bn
3704
- [name]: JSON.parse(JSON.stringify(value))
3705
- };
3706
- }
3707
- return prev;
3708
- }, {});
3709
- }
3710
- const call = {
3711
- functionSignature: functionFragment.signature,
3712
- functionName: functionFragment.name,
3713
- argumentsProvided,
3714
- ...receipt.amount?.isZero() ? {} : { amount: receipt.amount, assetId: receipt.assetId }
3715
- };
3716
- return call;
3717
- };
3948
+ import { ReceiptType as ReceiptType5, TransactionType as TransactionType9 } from "@fuel-ts/transactions";
3718
3949
 
3719
3950
  // src/providers/transaction-summary/input.ts
3720
3951
  import { ErrorCode as ErrorCode11, FuelError as FuelError14 } from "@fuel-ts/errors";
@@ -3869,10 +4100,10 @@ function isTypeBlob(transactionType) {
3869
4100
  return isType(transactionType, "Blob" /* Blob */);
3870
4101
  }
3871
4102
  function getReceiptsCall(receipts) {
3872
- return getReceiptsByType(receipts, ReceiptType4.Call);
4103
+ return getReceiptsByType(receipts, ReceiptType5.Call);
3873
4104
  }
3874
4105
  function getReceiptsMessageOut(receipts) {
3875
- return getReceiptsByType(receipts, ReceiptType4.MessageOut);
4106
+ return getReceiptsByType(receipts, ReceiptType5.MessageOut);
3876
4107
  }
3877
4108
  function mergeAssets(op1, op2) {
3878
4109
  const assets1 = op1.assetsSent || [];
@@ -3910,7 +4141,11 @@ function mergeOperations(existing, toAdd) {
3910
4141
  return {
3911
4142
  ...existing,
3912
4143
  assetsSent: mergeAssetsSent(existing, toAdd),
3913
- calls: mergeCalls(existing, toAdd)
4144
+ calls: mergeCalls(existing, toAdd),
4145
+ receipts: [
4146
+ ...existing.receipts || [],
4147
+ ...toAdd.receipts?.filter((r) => !existing.receipts?.some((er) => er === r)) || []
4148
+ ]
3914
4149
  };
3915
4150
  }
3916
4151
  function addOperation(operations, toAdd) {
@@ -3947,7 +4182,8 @@ function getWithdrawFromFuelOperations({
3947
4182
  amount: receipt.amount,
3948
4183
  assetId: baseAssetId
3949
4184
  }
3950
- ]
4185
+ ],
4186
+ receipts: [receipt]
3951
4187
  });
3952
4188
  return newWithdrawFromFuelOps;
3953
4189
  }
@@ -3957,19 +4193,12 @@ function getWithdrawFromFuelOperations({
3957
4193
  );
3958
4194
  return withdrawFromFuelOperations;
3959
4195
  }
3960
- function getContractCalls(contractInput, abiMap, receipt, rawPayload, maxInputs) {
4196
+ function getContractCalls(contractInput, abiMap, _receipt, _rawPayload, _maxInputs) {
3961
4197
  const abi = abiMap?.[contractInput.contractID];
3962
4198
  if (!abi) {
3963
4199
  return [];
3964
4200
  }
3965
- return [
3966
- getFunctionCall({
3967
- abi,
3968
- receipt,
3969
- rawPayload,
3970
- maxInputs
3971
- })
3972
- ];
4201
+ return [];
3973
4202
  }
3974
4203
  function getAssetsSent(receipt) {
3975
4204
  return receipt.amount?.isZero() ? void 0 : [
@@ -3999,7 +4228,8 @@ function processCallReceipt(receipt, contractInput, inputs, abiMap, rawPayload,
3999
4228
  address: receipt.to
4000
4229
  },
4001
4230
  assetsSent: getAssetsSent(receipt),
4002
- calls
4231
+ calls,
4232
+ receipts: [receipt]
4003
4233
  }
4004
4234
  ];
4005
4235
  }
@@ -4056,7 +4286,8 @@ function extractTransferOperationFromReceipt(receipt, contractInputs, changeOutp
4056
4286
  assetId: assetId.toString(),
4057
4287
  amount
4058
4288
  }
4059
- ]
4289
+ ],
4290
+ receipts: [receipt]
4060
4291
  };
4061
4292
  }
4062
4293
  function getTransferOperations({
@@ -4101,11 +4332,11 @@ function getTransferOperations({
4101
4332
  });
4102
4333
  const transferReceipts = getReceiptsByType(
4103
4334
  receipts,
4104
- ReceiptType4.Transfer
4335
+ ReceiptType5.Transfer
4105
4336
  );
4106
4337
  const transferOutReceipts = getReceiptsByType(
4107
4338
  receipts,
4108
- ReceiptType4.TransferOut
4339
+ ReceiptType5.TransferOut
4109
4340
  );
4110
4341
  [...transferReceipts, ...transferOutReceipts].forEach((receipt) => {
4111
4342
  const operation = extractTransferOperationFromReceipt(receipt, contractInputs, changeOutputs);
@@ -4189,12 +4420,11 @@ function getOperations({
4189
4420
  }
4190
4421
 
4191
4422
  // src/providers/transaction-summary/receipt.ts
4192
- import { ReceiptType as ReceiptType5 } from "@fuel-ts/transactions";
4193
- var processGqlReceipt = (gqlReceipt) => assembleReceiptByType(gqlReceipt);
4423
+ import { ReceiptType as ReceiptType6 } from "@fuel-ts/transactions";
4194
4424
  var extractMintedAssetsFromReceipts = (receipts) => {
4195
4425
  const mintedAssets = [];
4196
4426
  receipts.forEach((receipt) => {
4197
- if (receipt.type === ReceiptType5.Mint) {
4427
+ if (receipt.type === ReceiptType6.Mint) {
4198
4428
  mintedAssets.push({
4199
4429
  subId: receipt.subId,
4200
4430
  contractId: receipt.contractId,
@@ -4208,7 +4438,7 @@ var extractMintedAssetsFromReceipts = (receipts) => {
4208
4438
  var extractBurnedAssetsFromReceipts = (receipts) => {
4209
4439
  const burnedAssets = [];
4210
4440
  receipts.forEach((receipt) => {
4211
- if (receipt.type === ReceiptType5.Burn) {
4441
+ if (receipt.type === ReceiptType6.Burn) {
4212
4442
  burnedAssets.push({
4213
4443
  subId: receipt.subId,
4214
4444
  contractId: receipt.contractId,
@@ -4305,7 +4535,7 @@ function assembleTransactionSummary(params) {
4305
4535
  baseAssetId
4306
4536
  } = params;
4307
4537
  const gasUsed = getGasUsedFromReceipts(receipts);
4308
- const rawPayload = hexlify16(transactionBytes);
4538
+ const rawPayload = hexlify17(transactionBytes);
4309
4539
  const operations = getOperations({
4310
4540
  transactionType: transaction.type,
4311
4541
  inputs: transaction.inputs || [],
@@ -4367,13 +4597,13 @@ function assembleTransactionSummary(params) {
4367
4597
  }
4368
4598
 
4369
4599
  // src/providers/transaction-response/getDecodedLogs.ts
4370
- import { Interface as Interface3, BigNumberCoder } from "@fuel-ts/abi-coder";
4371
- import { ReceiptType as ReceiptType6 } from "@fuel-ts/transactions";
4600
+ import { Interface as Interface2, BigNumberCoder } from "@fuel-ts/abi-coder";
4601
+ import { ReceiptType as ReceiptType7 } from "@fuel-ts/transactions";
4372
4602
  function getDecodedLogs(receipts, mainAbi, externalAbis = {}) {
4373
4603
  return receipts.reduce((logs, receipt) => {
4374
- if (receipt.type === ReceiptType6.LogData || receipt.type === ReceiptType6.Log) {
4375
- const interfaceToUse = new Interface3(externalAbis[receipt.id] || mainAbi);
4376
- const data = receipt.type === ReceiptType6.Log ? new BigNumberCoder("u64").encode(receipt.ra) : receipt.data;
4604
+ if (receipt.type === ReceiptType7.LogData || receipt.type === ReceiptType7.Log) {
4605
+ const interfaceToUse = new Interface2(externalAbis[receipt.id] || mainAbi);
4606
+ const data = receipt.type === ReceiptType7.Log ? new BigNumberCoder("u64").encode(receipt.ra) : receipt.data;
4377
4607
  const [decodedLog] = interfaceToUse.decodeLog(data, receipt.rb.toString());
4378
4608
  logs.push(decodedLog);
4379
4609
  }
@@ -4495,7 +4725,7 @@ var TransactionResponse = class {
4495
4725
  switch (status?.type) {
4496
4726
  case "SuccessStatus":
4497
4727
  case "FailureStatus":
4498
- return status.receipts.map(processGqlReceipt);
4728
+ return status.receipts.map(deserializeReceipt);
4499
4729
  default:
4500
4730
  return [];
4501
4731
  }
@@ -4619,7 +4849,6 @@ var TransactionResponse = class {
4619
4849
  const { receipts } = transactionResult;
4620
4850
  const status = this.status ?? this.gqlTransaction?.status;
4621
4851
  if (status?.type === "FailureStatus") {
4622
- this.unsetResourceCache();
4623
4852
  const { reason } = status;
4624
4853
  throw extractTxError({
4625
4854
  receipts,
@@ -4636,6 +4865,7 @@ var TransactionResponse = class {
4636
4865
  */
4637
4866
  async waitForResult(contractsAbiMap) {
4638
4867
  await this.waitForStatusChange();
4868
+ this.unsetResourceCache();
4639
4869
  return this.assembleResult(contractsAbiMap);
4640
4870
  }
4641
4871
  /**
@@ -4688,6 +4918,22 @@ function autoRetryFetch(fetchFn, options, retryAttemptNum = 0) {
4688
4918
  };
4689
4919
  }
4690
4920
 
4921
+ // src/providers/utils/helpers.ts
4922
+ var adjustResourcesToExclude = (params) => {
4923
+ const { userInput, cached, maxInputs } = params;
4924
+ const final = { ...userInput };
4925
+ let total = final.utxos.length + final.messages.length;
4926
+ if (total >= maxInputs) {
4927
+ return final;
4928
+ }
4929
+ final.utxos = [...final.utxos, ...cached.utxos.slice(0, maxInputs - total)];
4930
+ total = final.utxos.length + final.messages.length;
4931
+ if (total < maxInputs) {
4932
+ final.messages = [...final.messages, ...cached.messages.slice(0, maxInputs - total)];
4933
+ }
4934
+ return final;
4935
+ };
4936
+
4691
4937
  // src/providers/utils/validate-pagination-args.ts
4692
4938
  import { FuelError as FuelError18, ErrorCode as ErrorCode15 } from "@fuel-ts/errors";
4693
4939
  var validatePaginationArgs = (params) => {
@@ -4727,64 +4973,10 @@ var validatePaginationArgs = (params) => {
4727
4973
  var MAX_RETRIES = 10;
4728
4974
  var RESOURCES_PAGE_SIZE_LIMIT = 512;
4729
4975
  var TRANSACTIONS_PAGE_SIZE_LIMIT = 60;
4976
+ var BALANCES_PAGE_SIZE_LIMIT = 100;
4730
4977
  var BLOCKS_PAGE_SIZE_LIMIT = 5;
4731
4978
  var DEFAULT_RESOURCE_CACHE_TTL = 2e4;
4732
4979
  var GAS_USED_MODIFIER = 1.2;
4733
- var processGqlChain = (chain) => {
4734
- const { name, daHeight, consensusParameters } = chain;
4735
- const {
4736
- contractParams,
4737
- feeParams,
4738
- predicateParams,
4739
- scriptParams,
4740
- txParams,
4741
- gasCosts,
4742
- baseAssetId,
4743
- chainId,
4744
- version
4745
- } = consensusParameters;
4746
- return {
4747
- name,
4748
- baseChainHeight: bn17(daHeight),
4749
- consensusParameters: {
4750
- version,
4751
- chainId: bn17(chainId),
4752
- baseAssetId,
4753
- feeParameters: {
4754
- version: feeParams.version,
4755
- gasPerByte: bn17(feeParams.gasPerByte),
4756
- gasPriceFactor: bn17(feeParams.gasPriceFactor)
4757
- },
4758
- contractParameters: {
4759
- version: contractParams.version,
4760
- contractMaxSize: bn17(contractParams.contractMaxSize),
4761
- maxStorageSlots: bn17(contractParams.maxStorageSlots)
4762
- },
4763
- txParameters: {
4764
- version: txParams.version,
4765
- maxInputs: bn17(txParams.maxInputs),
4766
- maxOutputs: bn17(txParams.maxOutputs),
4767
- maxWitnesses: bn17(txParams.maxWitnesses),
4768
- maxGasPerTx: bn17(txParams.maxGasPerTx),
4769
- maxSize: bn17(txParams.maxSize),
4770
- maxBytecodeSubsections: bn17(txParams.maxBytecodeSubsections)
4771
- },
4772
- predicateParameters: {
4773
- version: predicateParams.version,
4774
- maxPredicateLength: bn17(predicateParams.maxPredicateLength),
4775
- maxPredicateDataLength: bn17(predicateParams.maxPredicateDataLength),
4776
- maxGasPerPredicate: bn17(predicateParams.maxGasPerPredicate),
4777
- maxMessageDataLength: bn17(predicateParams.maxMessageDataLength)
4778
- },
4779
- scriptParameters: {
4780
- version: scriptParams.version,
4781
- maxScriptLength: bn17(scriptParams.maxScriptLength),
4782
- maxScriptDataLength: bn17(scriptParams.maxScriptDataLength)
4783
- },
4784
- gasCosts
4785
- }
4786
- };
4787
- };
4788
4980
  var _cacheInputs, cacheInputs_fn;
4789
4981
  var _Provider = class {
4790
4982
  /**
@@ -4806,13 +4998,19 @@ var _Provider = class {
4806
4998
  /** @hidden */
4807
4999
  __publicField(this, "urlWithoutAuth");
4808
5000
  /** @hidden */
5001
+ __publicField(this, "features", {
5002
+ balancePagination: false,
5003
+ amount128: false
5004
+ });
5005
+ /** @hidden */
4809
5006
  __publicField(this, "consensusParametersTimestamp");
4810
5007
  __publicField(this, "options", {
4811
5008
  timeout: void 0,
4812
5009
  resourceCacheTTL: void 0,
4813
5010
  fetch: void 0,
4814
5011
  retryOptions: void 0,
4815
- headers: void 0
5012
+ headers: void 0,
5013
+ cache: void 0
4816
5014
  });
4817
5015
  const { url: rawUrl, urlWithoutAuth, headers: authHeaders } = _Provider.extractBasicAuth(url);
4818
5016
  this.url = rawUrl;
@@ -4826,7 +5024,13 @@ var _Provider = class {
4826
5024
  headers
4827
5025
  };
4828
5026
  this.operations = this.createOperations();
4829
- const { resourceCacheTTL } = this.options;
5027
+ const { resourceCacheTTL, cache: cache2 } = this.options;
5028
+ if (cache2) {
5029
+ const { consensusParametersTimestamp, chain, nodeInfo } = deserializeProviderCache(cache2);
5030
+ this.consensusParametersTimestamp = consensusParametersTimestamp;
5031
+ _Provider.chainInfoCache[this.urlWithoutAuth] = chain;
5032
+ _Provider.nodeInfoCache[this.urlWithoutAuth] = nodeInfo;
5033
+ }
4830
5034
  if (isDefined2(resourceCacheTTL)) {
4831
5035
  if (resourceCacheTTL !== -1) {
4832
5036
  this.cache = new ResourceCache(resourceCacheTTL);
@@ -4885,7 +5089,8 @@ var _Provider = class {
4885
5089
  * Initialize Provider async stuff
4886
5090
  */
4887
5091
  async init() {
4888
- await this.fetchChainAndNodeInfo();
5092
+ const { nodeInfo } = await this.fetchChainAndNodeInfo();
5093
+ this.setupFeatures(nodeInfo.nodeVersion);
4889
5094
  return this;
4890
5095
  }
4891
5096
  /**
@@ -4956,15 +5161,9 @@ var _Provider = class {
4956
5161
  }
4957
5162
  } catch (_err) {
4958
5163
  const data = await this.operations.getChainAndNodeInfo();
4959
- nodeInfo = {
4960
- maxDepth: bn17(data.nodeInfo.maxDepth),
4961
- maxTx: bn17(data.nodeInfo.maxTx),
4962
- nodeVersion: data.nodeInfo.nodeVersion,
4963
- utxoValidation: data.nodeInfo.utxoValidation,
4964
- vmBacktrace: data.nodeInfo.vmBacktrace
4965
- };
5164
+ nodeInfo = deserializeNodeInfo(data.nodeInfo);
4966
5165
  _Provider.setIncompatibleNodeVersionMessage(nodeInfo);
4967
- chain = processGqlChain(data.chain);
5166
+ chain = deserializeChain(data.chain);
4968
5167
  _Provider.chainInfoCache[this.urlWithoutAuth] = chain;
4969
5168
  _Provider.nodeInfoCache[this.urlWithoutAuth] = nodeInfo;
4970
5169
  this.consensusParametersTimestamp = Date.now();
@@ -5042,6 +5241,15 @@ var _Provider = class {
5042
5241
  });
5043
5242
  return { ...getSdk(executeQuery), ...customOperations(executeQuery) };
5044
5243
  }
5244
+ /**
5245
+ * @hidden
5246
+ */
5247
+ setupFeatures(nodeVersion) {
5248
+ if (gte(nodeVersion, "0.41.0")) {
5249
+ this.features.balancePagination = true;
5250
+ this.features.amount128 = true;
5251
+ }
5252
+ }
5045
5253
  /**
5046
5254
  * Returns the version of the connected node.
5047
5255
  *
@@ -5073,13 +5281,7 @@ var _Provider = class {
5073
5281
  */
5074
5282
  async fetchNode() {
5075
5283
  const { nodeInfo } = await this.operations.getNodeInfo();
5076
- const processedNodeInfo = {
5077
- maxDepth: bn17(nodeInfo.maxDepth),
5078
- maxTx: bn17(nodeInfo.maxTx),
5079
- nodeVersion: nodeInfo.nodeVersion,
5080
- utxoValidation: nodeInfo.utxoValidation,
5081
- vmBacktrace: nodeInfo.vmBacktrace
5082
- };
5284
+ const processedNodeInfo = deserializeNodeInfo(nodeInfo);
5083
5285
  _Provider.nodeInfoCache[this.urlWithoutAuth] = processedNodeInfo;
5084
5286
  return processedNodeInfo;
5085
5287
  }
@@ -5090,7 +5292,7 @@ var _Provider = class {
5090
5292
  */
5091
5293
  async fetchChain() {
5092
5294
  const { chain } = await this.operations.getChain();
5093
- const processedChain = processGqlChain(chain);
5295
+ const processedChain = deserializeChain(chain);
5094
5296
  _Provider.chainInfoCache[this.urlWithoutAuth] = processedChain;
5095
5297
  return processedChain;
5096
5298
  }
@@ -5117,6 +5319,21 @@ var _Provider = class {
5117
5319
  } = all;
5118
5320
  return baseAssetId;
5119
5321
  }
5322
+ /**
5323
+ * Retrieves the details of an asset given its ID.
5324
+ *
5325
+ * @param assetId - The unique identifier of the asset.
5326
+ * @returns A promise that resolves to an object containing the asset details.
5327
+ */
5328
+ async getAssetDetails(assetId) {
5329
+ const { assetDetails } = await this.operations.getAssetDetails({ assetId });
5330
+ const { contractId, subId, totalSupply } = assetDetails;
5331
+ return {
5332
+ subId,
5333
+ contractId,
5334
+ totalSupply: bn17(totalSupply)
5335
+ };
5336
+ }
5120
5337
  /**
5121
5338
  * @hidden
5122
5339
  */
@@ -5160,7 +5377,7 @@ var _Provider = class {
5160
5377
  await this.estimateTxDependencies(transactionRequest);
5161
5378
  }
5162
5379
  await this.validateTransaction(transactionRequest);
5163
- const encodedTransaction = hexlify17(transactionRequest.toTransactionBytes());
5380
+ const encodedTransaction = hexlify18(transactionRequest.toTransactionBytes());
5164
5381
  let abis;
5165
5382
  if (isTransactionTypeScript(transactionRequest)) {
5166
5383
  abis = transactionRequest.abis;
@@ -5185,48 +5402,70 @@ var _Provider = class {
5185
5402
  if (estimateTxDependencies) {
5186
5403
  return this.estimateTxDependencies(transactionRequest);
5187
5404
  }
5188
- const encodedTransaction = hexlify17(transactionRequest.toTransactionBytes());
5405
+ const encodedTransaction = hexlify18(transactionRequest.toTransactionBytes());
5189
5406
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
5190
5407
  encodedTransactions: encodedTransaction,
5191
5408
  utxoValidation: utxoValidation || false
5192
5409
  });
5193
5410
  const [{ receipts: rawReceipts, status: dryRunStatus }] = dryRunStatuses;
5194
- const receipts = rawReceipts.map(processGqlReceipt);
5411
+ const receipts = rawReceipts.map(deserializeReceipt);
5195
5412
  return { receipts, dryRunStatus };
5196
5413
  }
5197
5414
  /**
5198
- * Verifies whether enough gas is available to complete transaction.
5415
+ * Estimates the gas usage for predicates in a transaction request.
5199
5416
  *
5200
5417
  * @template T - The type of the transaction request object.
5201
5418
  *
5202
- * @param transactionRequest - The transaction request object.
5203
- * @returns A promise that resolves to the estimated transaction request object.
5419
+ * @param transactionRequest - The transaction request to estimate predicates for.
5420
+ * @returns A promise that resolves to the updated transaction request with estimated gas usage for predicates.
5204
5421
  */
5205
5422
  async estimatePredicates(transactionRequest) {
5206
- const shouldEstimatePredicates = Boolean(
5207
- transactionRequest.inputs.find(
5208
- (input) => "predicate" in input && input.predicate && !equalBytes(arrayify13(input.predicate), arrayify13("0x")) && new BN2(input.predicateGasUsed).isZero()
5209
- )
5423
+ const shouldEstimatePredicates = transactionRequest.inputs.some(
5424
+ (input) => isPredicate(input) && bn17(input.predicateGasUsed).isZero()
5210
5425
  );
5211
5426
  if (!shouldEstimatePredicates) {
5212
5427
  return transactionRequest;
5213
5428
  }
5214
- const encodedTransaction = hexlify17(transactionRequest.toTransactionBytes());
5429
+ const encodedTransaction = hexlify18(transactionRequest.toTransactionBytes());
5215
5430
  const response = await this.operations.estimatePredicates({
5216
5431
  encodedTransaction
5217
5432
  });
5218
- const {
5219
- estimatePredicates: { inputs }
5220
- } = response;
5221
- if (inputs) {
5222
- inputs.forEach((input, index) => {
5223
- if ("predicateGasUsed" in input && bn17(input.predicateGasUsed).gt(0)) {
5224
- transactionRequest.inputs[index].predicateGasUsed = input.predicateGasUsed;
5225
- }
5226
- });
5227
- }
5433
+ const { estimatePredicates } = response;
5434
+ transactionRequest = this.parseEstimatePredicatesResponse(
5435
+ transactionRequest,
5436
+ estimatePredicates
5437
+ );
5228
5438
  return transactionRequest;
5229
5439
  }
5440
+ /**
5441
+ * Estimates the gas price and predicates for a given transaction request and block horizon.
5442
+ *
5443
+ * @param transactionRequest - The transaction request to estimate predicates and gas price for.
5444
+ * @param blockHorizon - The block horizon to use for gas price estimation.
5445
+ * @returns A promise that resolves to an object containing the updated transaction
5446
+ * request and the estimated gas price.
5447
+ */
5448
+ async estimatePredicatesAndGasPrice(transactionRequest, blockHorizon) {
5449
+ const shouldEstimatePredicates = transactionRequest.inputs.some(
5450
+ (input) => isPredicate(input) && bn17(input.predicateGasUsed).isZero()
5451
+ );
5452
+ if (!shouldEstimatePredicates) {
5453
+ const gasPrice2 = await this.estimateGasPrice(blockHorizon);
5454
+ return { transactionRequest, gasPrice: gasPrice2 };
5455
+ }
5456
+ const {
5457
+ estimateGasPrice: { gasPrice },
5458
+ estimatePredicates
5459
+ } = await this.operations.estimatePredicatesAndGasPrice({
5460
+ blockHorizon: String(blockHorizon),
5461
+ encodedTransaction: hexlify18(transactionRequest.toTransactionBytes())
5462
+ });
5463
+ transactionRequest = this.parseEstimatePredicatesResponse(
5464
+ transactionRequest,
5465
+ estimatePredicates
5466
+ );
5467
+ return { transactionRequest, gasPrice: bn17(gasPrice) };
5468
+ }
5230
5469
  /**
5231
5470
  * Will dryRun a transaction and check for missing dependencies.
5232
5471
  *
@@ -5240,11 +5479,13 @@ var _Provider = class {
5240
5479
  async estimateTxDependencies(transactionRequest, { gasPrice: gasPriceParam } = {}) {
5241
5480
  if (isTransactionTypeCreate(transactionRequest)) {
5242
5481
  return {
5482
+ rawReceipts: [],
5243
5483
  receipts: [],
5244
5484
  outputVariables: 0,
5245
5485
  missingContractIds: []
5246
5486
  };
5247
5487
  }
5488
+ let rawReceipts = [];
5248
5489
  let receipts = [];
5249
5490
  const missingContractIds = [];
5250
5491
  let outputVariables = 0;
@@ -5253,13 +5494,14 @@ var _Provider = class {
5253
5494
  const gasPrice = gasPriceParam ?? await this.estimateGasPrice(10);
5254
5495
  for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
5255
5496
  const {
5256
- dryRun: [{ receipts: rawReceipts, status }]
5497
+ dryRun: [{ receipts: serializedReceipts, status }]
5257
5498
  } = await this.operations.dryRun({
5258
- encodedTransactions: [hexlify17(transactionRequest.toTransactionBytes())],
5499
+ encodedTransactions: [hexlify18(transactionRequest.toTransactionBytes())],
5259
5500
  utxoValidation: false,
5260
5501
  gasPrice: gasPrice.toString()
5261
5502
  });
5262
- receipts = rawReceipts.map(processGqlReceipt);
5503
+ rawReceipts = serializedReceipts;
5504
+ receipts = serializedReceipts.map(deserializeReceipt);
5263
5505
  dryRunStatus = status;
5264
5506
  const { missingOutputVariables, missingOutputContractIds } = getReceiptsWithMissingData(receipts);
5265
5507
  const hasMissingOutputs = missingOutputVariables.length !== 0 || missingOutputContractIds.length !== 0;
@@ -5280,6 +5522,7 @@ var _Provider = class {
5280
5522
  }
5281
5523
  }
5282
5524
  return {
5525
+ rawReceipts,
5283
5526
  receipts,
5284
5527
  outputVariables,
5285
5528
  missingContractIds,
@@ -5298,6 +5541,7 @@ var _Provider = class {
5298
5541
  */
5299
5542
  async estimateMultipleTxDependencies(transactionRequests) {
5300
5543
  const results = transactionRequests.map(() => ({
5544
+ rawReceipts: [],
5301
5545
  receipts: [],
5302
5546
  outputVariables: 0,
5303
5547
  missingContractIds: [],
@@ -5307,7 +5551,7 @@ var _Provider = class {
5307
5551
  const serializedTransactionsMap = /* @__PURE__ */ new Map();
5308
5552
  allRequests.forEach((req, index) => {
5309
5553
  if (isTransactionTypeScript(req)) {
5310
- serializedTransactionsMap.set(index, hexlify17(req.toTransactionBytes()));
5554
+ serializedTransactionsMap.set(index, hexlify18(req.toTransactionBytes()));
5311
5555
  }
5312
5556
  });
5313
5557
  let transactionsToProcess = Array.from(serializedTransactionsMap.keys());
@@ -5325,7 +5569,7 @@ var _Provider = class {
5325
5569
  const requestIdx = transactionsToProcess[i];
5326
5570
  const { receipts: rawReceipts, status } = dryRunResults.dryRun[i];
5327
5571
  const result = results[requestIdx];
5328
- result.receipts = rawReceipts.map(processGqlReceipt);
5572
+ result.receipts = rawReceipts.map(deserializeReceipt);
5329
5573
  result.dryRunStatus = status;
5330
5574
  const { missingOutputVariables, missingOutputContractIds } = getReceiptsWithMissingData(
5331
5575
  result.receipts
@@ -5343,7 +5587,7 @@ var _Provider = class {
5343
5587
  transactionRequest: request
5344
5588
  });
5345
5589
  request.maxFee = maxFee;
5346
- serializedTransactionsMap.set(requestIdx, hexlify17(request.toTransactionBytes()));
5590
+ serializedTransactionsMap.set(requestIdx, hexlify18(request.toTransactionBytes()));
5347
5591
  nextRoundTransactions.push(requestIdx);
5348
5592
  }
5349
5593
  }
@@ -5364,13 +5608,13 @@ var _Provider = class {
5364
5608
  if (estimateTxDependencies) {
5365
5609
  return this.estimateMultipleTxDependencies(transactionRequests);
5366
5610
  }
5367
- const encodedTransactions = transactionRequests.map((tx) => hexlify17(tx.toTransactionBytes()));
5611
+ const encodedTransactions = transactionRequests.map((tx) => hexlify18(tx.toTransactionBytes()));
5368
5612
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
5369
5613
  encodedTransactions,
5370
5614
  utxoValidation: utxoValidation || false
5371
5615
  });
5372
5616
  const results = dryRunStatuses.map(({ receipts: rawReceipts, status }) => {
5373
- const receipts = rawReceipts.map(processGqlReceipt);
5617
+ const receipts = rawReceipts.map(deserializeReceipt);
5374
5618
  return { receipts, dryRunStatus: status };
5375
5619
  });
5376
5620
  return results;
@@ -5464,14 +5708,14 @@ var _Provider = class {
5464
5708
  if (estimateTxDependencies) {
5465
5709
  return this.estimateTxDependencies(transactionRequest);
5466
5710
  }
5467
- const encodedTransactions = [hexlify17(transactionRequest.toTransactionBytes())];
5711
+ const encodedTransactions = [hexlify18(transactionRequest.toTransactionBytes())];
5468
5712
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
5469
5713
  encodedTransactions,
5470
5714
  utxoValidation: true
5471
5715
  });
5472
5716
  const callResult = dryRunStatuses.map((dryRunStatus) => {
5473
5717
  const { id, receipts, status } = dryRunStatus;
5474
- const processedReceipts = receipts.map(processGqlReceipt);
5718
+ const processedReceipts = receipts.map(deserializeReceipt);
5475
5719
  return { id, receipts: processedReceipts, status };
5476
5720
  });
5477
5721
  return { receipts: callResult[0].receipts };
@@ -5502,14 +5746,20 @@ var _Provider = class {
5502
5746
  await signatureCallback(signedRequest);
5503
5747
  addedSignatures = signedRequest.witnesses.length - lengthBefore;
5504
5748
  }
5505
- await this.estimatePredicates(signedRequest);
5749
+ let gasPrice;
5750
+ if (gasPriceParam) {
5751
+ gasPrice = gasPriceParam;
5752
+ await this.estimatePredicates(signedRequest);
5753
+ } else {
5754
+ ({ gasPrice } = await this.estimatePredicatesAndGasPrice(signedRequest, 10));
5755
+ }
5506
5756
  txRequestClone.updatePredicateGasUsed(signedRequest.inputs);
5507
- const gasPrice = gasPriceParam ?? await this.estimateGasPrice(10);
5508
5757
  let { maxFee, maxGas, minFee, minGas, gasLimit } = await this.estimateTxGasAndFee({
5509
5758
  // Fetches and returns a gas price
5510
5759
  transactionRequest: signedRequest,
5511
5760
  gasPrice
5512
5761
  });
5762
+ let rawReceipts = [];
5513
5763
  let receipts = [];
5514
5764
  let dryRunStatus;
5515
5765
  let missingContractIds = [];
@@ -5521,7 +5771,7 @@ var _Provider = class {
5521
5771
  if (signatureCallback) {
5522
5772
  await signatureCallback(txRequestClone);
5523
5773
  }
5524
- ({ receipts, missingContractIds, outputVariables, dryRunStatus } = await this.estimateTxDependencies(txRequestClone, { gasPrice }));
5774
+ ({ rawReceipts, receipts, missingContractIds, outputVariables, dryRunStatus } = await this.estimateTxDependencies(txRequestClone, { gasPrice }));
5525
5775
  if (dryRunStatus && "reason" in dryRunStatus) {
5526
5776
  throw this.extractDryRunError(txRequestClone, receipts, dryRunStatus);
5527
5777
  }
@@ -5534,7 +5784,12 @@ var _Provider = class {
5534
5784
  gasPrice
5535
5785
  }));
5536
5786
  }
5787
+ const transactionSummary = {
5788
+ gasPrice: gasPrice.toString(),
5789
+ receipts: rawReceipts
5790
+ };
5537
5791
  return {
5792
+ rawReceipts,
5538
5793
  receipts,
5539
5794
  gasUsed,
5540
5795
  gasPrice,
@@ -5547,7 +5802,8 @@ var _Provider = class {
5547
5802
  addedSignatures,
5548
5803
  estimatedPredicates: txRequestClone.inputs,
5549
5804
  dryRunStatus,
5550
- updateMaxFee
5805
+ updateMaxFee,
5806
+ transactionSummary
5551
5807
  };
5552
5808
  }
5553
5809
  /**
@@ -5568,7 +5824,7 @@ var _Provider = class {
5568
5824
  paginationLimit: RESOURCES_PAGE_SIZE_LIMIT,
5569
5825
  inputArgs: paginationArgs
5570
5826
  }),
5571
- filter: { owner: ownerAddress.toB256(), assetId: assetId && hexlify17(assetId) }
5827
+ filter: { owner: ownerAddress.toB256(), assetId: assetId && hexlify18(assetId) }
5572
5828
  });
5573
5829
  const coins = edges.map(({ node }) => ({
5574
5830
  id: node.utxoId,
@@ -5593,23 +5849,33 @@ var _Provider = class {
5593
5849
  */
5594
5850
  async getResourcesToSpend(owner, quantities, excludedIds) {
5595
5851
  const ownerAddress = new Address3(owner);
5596
- const excludeInput = {
5597
- messages: excludedIds?.messages?.map((nonce) => hexlify17(nonce)) || [],
5598
- utxos: excludedIds?.utxos?.map((id) => hexlify17(id)) || []
5852
+ let idsToExclude = {
5853
+ messages: excludedIds?.messages?.map((nonce) => hexlify18(nonce)) || [],
5854
+ utxos: excludedIds?.utxos?.map((id) => hexlify18(id)) || []
5599
5855
  };
5600
5856
  if (this.cache) {
5601
- const cached = this.cache.getActiveData();
5602
- excludeInput.messages.push(...cached.messages);
5603
- excludeInput.utxos.push(...cached.utxos);
5857
+ const cached = this.cache.getActiveData(ownerAddress.toB256());
5858
+ if (cached.utxos.length || cached.messages.length) {
5859
+ const {
5860
+ consensusParameters: {
5861
+ txParameters: { maxInputs }
5862
+ }
5863
+ } = await this.getChain();
5864
+ idsToExclude = adjustResourcesToExclude({
5865
+ userInput: idsToExclude,
5866
+ cached,
5867
+ maxInputs: maxInputs.toNumber()
5868
+ });
5869
+ }
5604
5870
  }
5605
5871
  const coinsQuery = {
5606
5872
  owner: ownerAddress.toB256(),
5607
5873
  queryPerAsset: quantities.map(coinQuantityfy).map(({ assetId, amount, max: maxPerAsset }) => ({
5608
- assetId: hexlify17(assetId),
5609
- amount: amount.toString(10),
5874
+ assetId: hexlify18(assetId),
5875
+ amount: (amount.eqn(0) ? bn17(1) : amount).toString(10),
5610
5876
  max: maxPerAsset ? maxPerAsset.toString(10) : void 0
5611
5877
  })),
5612
- excludedIds: excludeInput
5878
+ excludedIds: idsToExclude
5613
5879
  };
5614
5880
  const result = await this.operations.getCoinsToSpend(coinsQuery);
5615
5881
  const coins = result.coinsToSpend.flat().map((coin) => {
@@ -5667,7 +5933,7 @@ var _Provider = class {
5667
5933
  } = await this.operations.getLatestBlock();
5668
5934
  block = latestBlock;
5669
5935
  } else {
5670
- const isblockId = typeof idOrHeight === "string" && idOrHeight.length === 66;
5936
+ const isblockId = typeof idOrHeight === "string" && isB256(idOrHeight);
5671
5937
  const variables = isblockId ? { blockId: idOrHeight } : { height: bn17(idOrHeight).toString(10) };
5672
5938
  const response = await this.operations.getBlock(variables);
5673
5939
  block = response.block;
@@ -5738,8 +6004,10 @@ var _Provider = class {
5738
6004
  variables = { blockHeight: bn17(idOrHeight).toString(10) };
5739
6005
  } else if (idOrHeight === "latest") {
5740
6006
  variables = { blockHeight: (await this.getBlockNumber()).toString() };
5741
- } else {
6007
+ } else if (typeof idOrHeight === "string" && isB256(idOrHeight)) {
5742
6008
  variables = { blockId: idOrHeight };
6009
+ } else {
6010
+ variables = { blockHeight: bn17(idOrHeight).toString() };
5743
6011
  }
5744
6012
  const { block } = await this.operations.getBlockWithTransactions(variables);
5745
6013
  if (!block) {
@@ -5855,7 +6123,7 @@ var _Provider = class {
5855
6123
  async getContractBalance(contractId, assetId) {
5856
6124
  const { contractBalance } = await this.operations.getContractBalance({
5857
6125
  contract: new Address3(contractId).toB256(),
5858
- asset: hexlify17(assetId)
6126
+ asset: hexlify18(assetId)
5859
6127
  });
5860
6128
  return bn17(contractBalance.amount, 10);
5861
6129
  }
@@ -5867,11 +6135,20 @@ var _Provider = class {
5867
6135
  * @returns A promise that resolves to the balance.
5868
6136
  */
5869
6137
  async getBalance(owner, assetId) {
5870
- const { balance } = await this.operations.getBalance({
5871
- owner: new Address3(owner).toB256(),
5872
- assetId: hexlify17(assetId)
6138
+ const ownerStr = new Address3(owner).toB256();
6139
+ const assetIdStr = hexlify18(assetId);
6140
+ if (!this.features.amount128) {
6141
+ const { balance: balance2 } = await this.operations.getBalance({
6142
+ owner: ownerStr,
6143
+ assetId: assetIdStr
6144
+ });
6145
+ return bn17(balance2.amount, 10);
6146
+ }
6147
+ const { balance } = await this.operations.getBalanceV2({
6148
+ owner: ownerStr,
6149
+ assetId: assetIdStr
5873
6150
  });
5874
- return bn17(balance.amount, 10);
6151
+ return bn17(balance.amountU128, 10);
5875
6152
  }
5876
6153
  /**
5877
6154
  * Returns balances for the given owner.
@@ -5880,7 +6157,16 @@ var _Provider = class {
5880
6157
  * @param paginationArgs - Pagination arguments (optional).
5881
6158
  * @returns A promise that resolves to the balances.
5882
6159
  */
5883
- async getBalances(owner) {
6160
+ async getBalances(owner, paginationArgs) {
6161
+ if (!this.features.balancePagination) {
6162
+ return this.getBalancesV1(owner, paginationArgs);
6163
+ }
6164
+ return this.getBalancesV2(owner, paginationArgs);
6165
+ }
6166
+ /**
6167
+ * @hidden
6168
+ */
6169
+ async getBalancesV1(owner, _paginationArgs) {
5884
6170
  const {
5885
6171
  balances: { edges }
5886
6172
  } = await this.operations.getBalances({
@@ -5897,6 +6183,25 @@ var _Provider = class {
5897
6183
  }));
5898
6184
  return { balances };
5899
6185
  }
6186
+ /**
6187
+ * @hidden
6188
+ */
6189
+ async getBalancesV2(owner, paginationArgs) {
6190
+ const {
6191
+ balances: { edges, pageInfo }
6192
+ } = await this.operations.getBalancesV2({
6193
+ ...validatePaginationArgs({
6194
+ inputArgs: paginationArgs,
6195
+ paginationLimit: BALANCES_PAGE_SIZE_LIMIT
6196
+ }),
6197
+ filter: { owner: new Address3(owner).toB256() }
6198
+ });
6199
+ const balances = edges.map(({ node }) => ({
6200
+ assetId: node.assetId,
6201
+ amount: bn17(node.amountU128)
6202
+ }));
6203
+ return { balances, pageInfo };
6204
+ }
5900
6205
  /**
5901
6206
  * Returns message for the given address.
5902
6207
  *
@@ -5963,15 +6268,12 @@ var _Provider = class {
5963
6268
  if (commitBlockHeight) {
5964
6269
  inputObject = {
5965
6270
  ...inputObject,
5966
- // Conver BN into a number string required on the query
5967
- // This should problably be fixed on the fuel client side
6271
+ // Convert BN into a number string required on the query
6272
+ // This should probably be fixed on the fuel client side
5968
6273
  commitBlockHeight: commitBlockHeight.toNumber().toString()
5969
6274
  };
5970
6275
  }
5971
6276
  const result = await this.operations.getMessageProof(inputObject);
5972
- if (!result.messageProof) {
5973
- return null;
5974
- }
5975
6277
  const {
5976
6278
  messageProof,
5977
6279
  messageBlockHeader,
@@ -6080,16 +6382,15 @@ var _Provider = class {
6080
6382
  * @returns A promise that resolves to the result of the check.
6081
6383
  */
6082
6384
  async isUserAccount(id) {
6083
- const { contract, blob, transaction } = await this.operations.isUserAccount({
6084
- blobId: id,
6085
- contractId: id,
6086
- transactionId: id
6087
- });
6088
- if (contract || blob || transaction) {
6089
- return false;
6090
- }
6091
- return true;
6385
+ const type = await this.getAddressType(id);
6386
+ return type === "Account";
6092
6387
  }
6388
+ /**
6389
+ * Determines the type of address based on the provided ID.
6390
+ *
6391
+ * @param id - The ID to be checked.
6392
+ * @returns A promise that resolves to a string indicating the type of address.
6393
+ */
6093
6394
  async getAddressType(id) {
6094
6395
  const { contract, blob, transaction } = await this.operations.isUserAccount({
6095
6396
  blobId: id,
@@ -6105,6 +6406,13 @@ var _Provider = class {
6105
6406
  if (transaction) {
6106
6407
  return "Transaction";
6107
6408
  }
6409
+ try {
6410
+ const asset = await this.getAssetDetails(id);
6411
+ if (asset) {
6412
+ return "Asset";
6413
+ }
6414
+ } catch (e) {
6415
+ }
6108
6416
  return "Account";
6109
6417
  }
6110
6418
  /**
@@ -6179,6 +6487,19 @@ var _Provider = class {
6179
6487
  statusReason: status.reason
6180
6488
  });
6181
6489
  }
6490
+ /**
6491
+ * @hidden
6492
+ */
6493
+ parseEstimatePredicatesResponse(transactionRequest, { inputs }) {
6494
+ if (inputs) {
6495
+ inputs.forEach((input, i) => {
6496
+ if (input && "predicateGasUsed" in input && bn17(input.predicateGasUsed).gt(0)) {
6497
+ transactionRequest.inputs[i].predicateGasUsed = input.predicateGasUsed;
6498
+ }
6499
+ });
6500
+ }
6501
+ return transactionRequest;
6502
+ }
6182
6503
  };
6183
6504
  var Provider = _Provider;
6184
6505
  _cacheInputs = new WeakSet();
@@ -6186,18 +6507,7 @@ cacheInputs_fn = function(inputs, transactionId) {
6186
6507
  if (!this.cache) {
6187
6508
  return;
6188
6509
  }
6189
- const inputsToCache = inputs.reduce(
6190
- (acc, input) => {
6191
- if (input.type === InputType7.Coin) {
6192
- acc.utxos.push(input.id);
6193
- } else if (input.type === InputType7.Message) {
6194
- acc.messages.push(input.nonce);
6195
- }
6196
- return acc;
6197
- },
6198
- { utxos: [], messages: [] }
6199
- );
6200
- this.cache.set(transactionId, inputsToCache);
6510
+ this.cache.set(transactionId, inputs);
6201
6511
  };
6202
6512
  /** @hidden */
6203
6513
  __publicField(Provider, "chainInfoCache", {});
@@ -6212,9 +6522,14 @@ import { bn as bn18 } from "@fuel-ts/math";
6212
6522
  import { TransactionCoder as TransactionCoder6 } from "@fuel-ts/transactions";
6213
6523
  import { arrayify as arrayify14 } from "@fuel-ts/utils";
6214
6524
 
6525
+ // src/providers/transaction-summary/assemble-transaction-summary-from-serialized.ts
6526
+ import { bn as bn19 } from "@fuel-ts/math";
6527
+ import { TransactionCoder as TransactionCoder7 } from "@fuel-ts/transactions";
6528
+ import { arrayify as arrayify15 } from "@fuel-ts/utils";
6529
+
6215
6530
  // src/test-utils/test-asset-id.ts
6216
6531
  import { randomBytes as randomBytes4 } from "@fuel-ts/crypto";
6217
- import { hexlify as hexlify18 } from "@fuel-ts/utils";
6532
+ import { hexlify as hexlify19 } from "@fuel-ts/utils";
6218
6533
  var _TestAssetId = class {
6219
6534
  constructor(value) {
6220
6535
  this.value = value;
@@ -6222,7 +6537,7 @@ var _TestAssetId = class {
6222
6537
  static random(count = 1) {
6223
6538
  const assetIds = [];
6224
6539
  for (let i = 0; i < count; i++) {
6225
- assetIds.push(new _TestAssetId(hexlify18(randomBytes4(32))));
6540
+ assetIds.push(new _TestAssetId(hexlify19(randomBytes4(32))));
6226
6541
  }
6227
6542
  return assetIds;
6228
6543
  }
@@ -6238,21 +6553,21 @@ __publicField(TestAssetId, "B", new _TestAssetId(
6238
6553
  // src/test-utils/wallet-config.ts
6239
6554
  import { randomBytes as randomBytes8 } from "@fuel-ts/crypto";
6240
6555
  import { FuelError as FuelError26 } from "@fuel-ts/errors";
6241
- import { bn as bn21 } from "@fuel-ts/math";
6242
- import { defaultSnapshotConfigs as defaultSnapshotConfigs2, hexlify as hexlify24 } from "@fuel-ts/utils";
6556
+ import { bn as bn22 } from "@fuel-ts/math";
6557
+ import { defaultSnapshotConfigs as defaultSnapshotConfigs2, hexlify as hexlify25 } from "@fuel-ts/utils";
6243
6558
 
6244
6559
  // src/wallet/base-wallet-unlocked.ts
6245
6560
  import { hashMessage } from "@fuel-ts/hasher";
6246
- import { hexlify as hexlify21 } from "@fuel-ts/utils";
6561
+ import { hexlify as hexlify22 } from "@fuel-ts/utils";
6247
6562
 
6248
6563
  // src/account.ts
6249
6564
  import { UTXO_ID_LEN as UTXO_ID_LEN3 } from "@fuel-ts/abi-coder";
6250
6565
  import { Address as Address5 } from "@fuel-ts/address";
6251
6566
  import { randomBytes as randomBytes5 } from "@fuel-ts/crypto";
6252
6567
  import { ErrorCode as ErrorCode18, FuelError as FuelError21 } from "@fuel-ts/errors";
6253
- import { bn as bn19 } from "@fuel-ts/math";
6254
- import { InputType as InputType8 } from "@fuel-ts/transactions";
6255
- import { arrayify as arrayify16, hexlify as hexlify19, isDefined as isDefined3 } from "@fuel-ts/utils";
6568
+ import { bn as bn20 } from "@fuel-ts/math";
6569
+ import { InputType as InputType7 } from "@fuel-ts/transactions";
6570
+ import { arrayify as arrayify17, hexlify as hexlify20, isDefined as isDefined3 } from "@fuel-ts/utils";
6256
6571
  import { clone as clone9 } from "ramda";
6257
6572
 
6258
6573
  // src/providers/utils/merge-quantities.ts
@@ -6276,14 +6591,14 @@ var AbstractAccount = class {
6276
6591
  // src/utils/formatTransferToContractScriptData.ts
6277
6592
  import { ASSET_ID_LEN, BigNumberCoder as BigNumberCoder2, CONTRACT_ID_LEN, WORD_SIZE } from "@fuel-ts/abi-coder";
6278
6593
  import { Address as Address4 } from "@fuel-ts/address";
6279
- import { arrayify as arrayify15, concat as concat4 } from "@fuel-ts/utils";
6594
+ import { arrayify as arrayify16, concat as concat4 } from "@fuel-ts/utils";
6280
6595
  import * as asm from "@fuels/vm-asm";
6281
6596
  var formatTransferToContractScriptData = (transferParams) => {
6282
6597
  const numberCoder = new BigNumberCoder2("u64");
6283
6598
  return transferParams.reduce((acc, transferParam) => {
6284
6599
  const { assetId, amount, contractId } = transferParam;
6285
6600
  const encoded = numberCoder.encode(amount);
6286
- const scriptData = concat4([new Address4(contractId).toBytes(), encoded, arrayify15(assetId)]);
6601
+ const scriptData = concat4([new Address4(contractId).toBytes(), encoded, arrayify16(assetId)]);
6287
6602
  return concat4([acc, scriptData]);
6288
6603
  }, new Uint8Array());
6289
6604
  };
@@ -6427,12 +6742,20 @@ var Account = class extends AbstractAccount {
6427
6742
  * @returns A promise that resolves to the funded transaction request.
6428
6743
  */
6429
6744
  async fund(request, params) {
6430
- const { addedSignatures, estimatedPredicates, requiredQuantities, updateMaxFee, gasPrice } = params;
6745
+ const {
6746
+ addedSignatures,
6747
+ estimatedPredicates,
6748
+ requiredQuantities,
6749
+ updateMaxFee,
6750
+ gasPrice,
6751
+ transactionSummary
6752
+ } = params;
6753
+ const chainId = await this.provider.getChainId();
6431
6754
  const fee = request.maxFee;
6432
6755
  const baseAssetId = await this.provider.getBaseAssetId();
6433
- const requiredInBaseAsset = requiredQuantities.find((quantity) => quantity.assetId === baseAssetId)?.amount || bn19(0);
6756
+ const requiredInBaseAsset = requiredQuantities.find((quantity) => quantity.assetId === baseAssetId)?.amount || bn20(0);
6434
6757
  const requiredQuantitiesWithFee = addAmountToCoinQuantities({
6435
- amount: bn19(fee),
6758
+ amount: bn20(fee),
6436
6759
  assetId: baseAssetId,
6437
6760
  coinQuantities: requiredQuantities
6438
6761
  });
@@ -6440,7 +6763,7 @@ var Account = class extends AbstractAccount {
6440
6763
  requiredQuantitiesWithFee.forEach(({ amount, assetId }) => {
6441
6764
  quantitiesDict[assetId] = {
6442
6765
  required: amount,
6443
- owned: bn19(0)
6766
+ owned: bn20(0)
6444
6767
  };
6445
6768
  });
6446
6769
  request.inputs.filter(isRequestInputResource).forEach((input) => {
@@ -6502,10 +6825,11 @@ var Account = class extends AbstractAccount {
6502
6825
  }
6503
6826
  if (needsToBeFunded) {
6504
6827
  throw new FuelError21(
6505
- ErrorCode18.NOT_ENOUGH_FUNDS,
6828
+ ErrorCode18.INSUFFICIENT_FUNDS_OR_MAX_COINS,
6506
6829
  `The account ${this.address} does not have enough base asset funds to cover the transaction execution.`
6507
6830
  );
6508
6831
  }
6832
+ request.updateState(chainId, "funded", transactionSummary);
6509
6833
  await this.provider.validateTransaction(request);
6510
6834
  request.updatePredicateGasUsed(estimatedPredicates);
6511
6835
  const requestToReestimate = clone9(request);
@@ -6616,9 +6940,9 @@ var Account = class extends AbstractAccount {
6616
6940
  const quantities = [];
6617
6941
  const defaultAssetId = await this.provider.getBaseAssetId();
6618
6942
  const transferParams = contractTransferParams.map((transferParam) => {
6619
- const amount = bn19(transferParam.amount);
6943
+ const amount = bn20(transferParam.amount);
6620
6944
  const contractAddress = new Address5(transferParam.contractId);
6621
- const assetId = transferParam.assetId ? hexlify19(transferParam.assetId) : defaultAssetId;
6945
+ const assetId = transferParam.assetId ? hexlify20(transferParam.assetId) : defaultAssetId;
6622
6946
  if (amount.lte(0)) {
6623
6947
  throw new FuelError21(
6624
6948
  ErrorCode18.INVALID_TRANSFER_AMOUNT,
@@ -6649,21 +6973,21 @@ var Account = class extends AbstractAccount {
6649
6973
  */
6650
6974
  async withdrawToBaseLayer(recipient, amount, txParams = {}) {
6651
6975
  const recipientAddress = new Address5(recipient);
6652
- const recipientDataArray = arrayify16(
6976
+ const recipientDataArray = arrayify17(
6653
6977
  "0x".concat(recipientAddress.toHexString().substring(2).padStart(64, "0"))
6654
6978
  );
6655
- const amountDataArray = arrayify16(
6656
- "0x".concat(bn19(amount).toHex().substring(2).padStart(16, "0"))
6979
+ const amountDataArray = arrayify17(
6980
+ "0x".concat(bn20(amount).toHex().substring(2).padStart(16, "0"))
6657
6981
  );
6658
6982
  const script = new Uint8Array([
6659
- ...arrayify16(withdrawScript.bytes),
6983
+ ...arrayify17(withdrawScript.bytes),
6660
6984
  ...recipientDataArray,
6661
6985
  ...amountDataArray
6662
6986
  ]);
6663
6987
  const params = { script, ...txParams };
6664
6988
  const baseAssetId = await this.provider.getBaseAssetId();
6665
6989
  let request = new ScriptTransactionRequest(params);
6666
- const quantities = [{ amount: bn19(amount), assetId: baseAssetId }];
6990
+ const quantities = [{ amount: bn20(amount), assetId: baseAssetId }];
6667
6991
  const txCost = await this.getTransactionCost(request, { quantities });
6668
6992
  request = this.validateGasLimitAndMaxFee({
6669
6993
  transactionRequest: request,
@@ -6689,9 +7013,9 @@ var Account = class extends AbstractAccount {
6689
7013
  const baseAssetId = await this.provider.getBaseAssetId();
6690
7014
  const coinOutputsQuantities = txRequestClone.getCoinOutputsQuantities();
6691
7015
  const requiredQuantities = mergeQuantities(coinOutputsQuantities, quantities);
6692
- const transactionFeeForDryRun = [{ assetId: baseAssetId, amount: bn19("100000000000000000") }];
7016
+ const transactionFeeForDryRun = [{ assetId: baseAssetId, amount: bn20("100000000000000000") }];
6693
7017
  const findAssetInput = (assetId) => txRequestClone.inputs.find((input) => {
6694
- if (input.type === InputType8.Coin) {
7018
+ if (input.type === InputType7.Coin) {
6695
7019
  return input.assetId === assetId;
6696
7020
  }
6697
7021
  if (isRequestInputMessageWithoutData(input)) {
@@ -6763,16 +7087,28 @@ var Account = class extends AbstractAccount {
6763
7087
  * @param sendTransactionParams - The provider send transaction parameters (optional).
6764
7088
  * @returns A promise that resolves to the transaction response.
6765
7089
  */
6766
- async sendTransaction(transactionRequestLike, { estimateTxDependencies = true, onBeforeSend, skipCustomFee = false } = {}) {
7090
+ async sendTransaction(transactionRequestLike, { estimateTxDependencies = true, ...connectorOptions } = {}) {
7091
+ let transactionRequest = transactionRequestify(transactionRequestLike);
6767
7092
  if (this._connector) {
6768
- return this.provider.getTransactionResponse(
6769
- await this._connector.sendTransaction(this.address.toString(), transactionRequestLike, {
6770
- onBeforeSend,
6771
- skipCustomFee
6772
- })
7093
+ const { onBeforeSend, skipCustomFee = false } = connectorOptions;
7094
+ transactionRequest = await this.prepareTransactionForSend(transactionRequest);
7095
+ const params = {
7096
+ onBeforeSend,
7097
+ skipCustomFee,
7098
+ provider: {
7099
+ url: this.provider.url,
7100
+ cache: await serializeProviderCache(this.provider)
7101
+ },
7102
+ transactionState: transactionRequest.flag.state,
7103
+ transactionSummary: await this.prepareTransactionSummary(transactionRequest)
7104
+ };
7105
+ const transaction = await this._connector.sendTransaction(
7106
+ this.address.toString(),
7107
+ transactionRequest,
7108
+ params
6773
7109
  );
7110
+ return typeof transaction === "string" ? this.provider.getTransactionResponse(transaction) : transaction;
6774
7111
  }
6775
- const transactionRequest = transactionRequestify(transactionRequestLike);
6776
7112
  if (estimateTxDependencies) {
6777
7113
  await this.provider.estimateTxDependencies(transactionRequest);
6778
7114
  }
@@ -6802,16 +7138,38 @@ var Account = class extends AbstractAccount {
6802
7138
  */
6803
7139
  generateFakeResources(coins) {
6804
7140
  return coins.map((coin) => ({
6805
- id: hexlify19(randomBytes5(UTXO_ID_LEN3)),
7141
+ id: hexlify20(randomBytes5(UTXO_ID_LEN3)),
6806
7142
  owner: this.address,
6807
- blockCreated: bn19(1),
6808
- txCreatedIdx: bn19(1),
7143
+ blockCreated: bn20(1),
7144
+ txCreatedIdx: bn20(1),
6809
7145
  ...coin
6810
7146
  }));
6811
7147
  }
7148
+ /** @hidden */
7149
+ async prepareTransactionForSend(request) {
7150
+ const { transactionId } = request.flag;
7151
+ if (!isDefined3(transactionId)) {
7152
+ return request;
7153
+ }
7154
+ const chainId = await this.provider.getChainId();
7155
+ const currentTransactionId = request.getTransactionId(chainId);
7156
+ if (transactionId !== currentTransactionId) {
7157
+ request.updateState(chainId);
7158
+ }
7159
+ return request;
7160
+ }
7161
+ /** @hidden */
7162
+ async prepareTransactionSummary(request) {
7163
+ const chainId = await this.provider.getChainId();
7164
+ return isDefined3(request.flag.summary) ? {
7165
+ ...request.flag.summary,
7166
+ id: request.getTransactionId(chainId),
7167
+ transactionBytes: hexlify20(request.toTransactionBytes())
7168
+ } : void 0;
7169
+ }
6812
7170
  /** @hidden * */
6813
7171
  validateTransferAmount(amount) {
6814
- if (bn19(amount).lte(0)) {
7172
+ if (bn20(amount).lte(0)) {
6815
7173
  throw new FuelError21(
6816
7174
  ErrorCode18.INVALID_TRANSFER_AMOUNT,
6817
7175
  "Transfer amount must be a positive number."
@@ -6872,7 +7230,7 @@ import {
6872
7230
  randomUUID as randomUUID2
6873
7231
  } from "@fuel-ts/crypto";
6874
7232
  import { ErrorCode as ErrorCode19, FuelError as FuelError22 } from "@fuel-ts/errors";
6875
- import { hexlify as hexlify20 } from "@fuel-ts/utils";
7233
+ import { hexlify as hexlify21 } from "@fuel-ts/utils";
6876
7234
  var DEFAULT_KDF_PARAMS_LOG_N = 13;
6877
7235
  var DEFAULT_KDF_PARAMS_R = 8;
6878
7236
  var DEFAULT_KDF_PARAMS_P = 1;
@@ -6954,7 +7312,7 @@ async function decryptKeystoreWallet(jsonWallet, password) {
6954
7312
  );
6955
7313
  }
6956
7314
  const buffer = await decryptJsonWalletData(ciphertextBuffer, key, ivBuffer);
6957
- const privateKey = hexlify20(buffer);
7315
+ const privateKey = hexlify21(buffer);
6958
7316
  return privateKey;
6959
7317
  }
6960
7318
 
@@ -6999,7 +7357,7 @@ var BaseWalletUnlocked = class extends Account {
6999
7357
  */
7000
7358
  async signMessage(message) {
7001
7359
  const signedMessage = await this.signer().sign(hashMessage(message));
7002
- return hexlify21(signedMessage);
7360
+ return hexlify22(signedMessage);
7003
7361
  }
7004
7362
  /**
7005
7363
  * Signs a transaction with the wallet's private key.
@@ -7012,7 +7370,7 @@ var BaseWalletUnlocked = class extends Account {
7012
7370
  const chainId = await this.provider.getChainId();
7013
7371
  const hashedTransaction = transactionRequest.getTransactionId(chainId);
7014
7372
  const signature = await this.signer().sign(hashedTransaction);
7015
- return hexlify21(signature);
7373
+ return hexlify22(signature);
7016
7374
  }
7017
7375
  /**
7018
7376
  * Populates a transaction with the witnesses signature.
@@ -7086,14 +7444,14 @@ __publicField(BaseWalletUnlocked, "defaultPath", "m/44'/1179993420'/0'/0/0");
7086
7444
  import { computeHmac as computeHmac2, ripemd160 } from "@fuel-ts/crypto";
7087
7445
  import { ErrorCode as ErrorCode22, FuelError as FuelError25 } from "@fuel-ts/errors";
7088
7446
  import { sha256 as sha2564 } from "@fuel-ts/hasher";
7089
- import { bn as bn20, toBytes as toBytes2, toHex } from "@fuel-ts/math";
7090
- import { arrayify as arrayify19, hexlify as hexlify23, concat as concat6, dataSlice as dataSlice2, encodeBase58 as encodeBase582, decodeBase58 } from "@fuel-ts/utils";
7447
+ import { bn as bn21, toBytes as toBytes2, toHex } from "@fuel-ts/math";
7448
+ import { arrayify as arrayify20, hexlify as hexlify24, concat as concat6, dataSlice as dataSlice2, encodeBase58 as encodeBase582, decodeBase58 } from "@fuel-ts/utils";
7091
7449
 
7092
7450
  // src/mnemonic/mnemonic.ts
7093
7451
  import { randomBytes as randomBytes7, pbkdf2, computeHmac } from "@fuel-ts/crypto";
7094
7452
  import { ErrorCode as ErrorCode21, FuelError as FuelError24 } from "@fuel-ts/errors";
7095
7453
  import { sha256 as sha2563 } from "@fuel-ts/hasher";
7096
- import { arrayify as arrayify18, hexlify as hexlify22, concat as concat5, dataSlice, encodeBase58, toUtf8Bytes } from "@fuel-ts/utils";
7454
+ import { arrayify as arrayify19, hexlify as hexlify23, concat as concat5, dataSlice, encodeBase58, toUtf8Bytes } from "@fuel-ts/utils";
7097
7455
 
7098
7456
  // src/wordlists/words/english.ts
7099
7457
  var english = [
@@ -9150,7 +9508,7 @@ var english = [
9150
9508
  // src/mnemonic/utils.ts
9151
9509
  import { ErrorCode as ErrorCode20, FuelError as FuelError23 } from "@fuel-ts/errors";
9152
9510
  import { sha256 as sha2562 } from "@fuel-ts/hasher";
9153
- import { arrayify as arrayify17 } from "@fuel-ts/utils";
9511
+ import { arrayify as arrayify18 } from "@fuel-ts/utils";
9154
9512
  function getLowerMask(bits) {
9155
9513
  return (1 << bits) - 1;
9156
9514
  }
@@ -9185,14 +9543,14 @@ function entropyToMnemonicIndices(entropy) {
9185
9543
  }
9186
9544
  }
9187
9545
  const checksumBits = entropy.length / 4;
9188
- const checksum = arrayify17(sha2562(entropy))[0] & getUpperMask(checksumBits);
9546
+ const checksum = arrayify18(sha2562(entropy))[0] & getUpperMask(checksumBits);
9189
9547
  indices[indices.length - 1] <<= checksumBits;
9190
9548
  indices[indices.length - 1] |= checksum >> 8 - checksumBits;
9191
9549
  return indices;
9192
9550
  }
9193
9551
  function mnemonicWordsToEntropy(words, wordlist) {
9194
9552
  const size = Math.ceil(11 * words.length / 8);
9195
- const entropy = arrayify17(new Uint8Array(size));
9553
+ const entropy = arrayify18(new Uint8Array(size));
9196
9554
  let offset = 0;
9197
9555
  for (let i = 0; i < words.length; i += 1) {
9198
9556
  const index = wordlist.indexOf(words[i].normalize("NFKD"));
@@ -9212,7 +9570,7 @@ function mnemonicWordsToEntropy(words, wordlist) {
9212
9570
  const entropyBits = 32 * words.length / 3;
9213
9571
  const checksumBits = words.length / 3;
9214
9572
  const checksumMask = getUpperMask(checksumBits);
9215
- const checksum = arrayify17(sha2562(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
9573
+ const checksum = arrayify18(sha2562(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
9216
9574
  if (checksum !== (entropy[entropy.length - 1] & checksumMask)) {
9217
9575
  throw new FuelError23(
9218
9576
  ErrorCode20.INVALID_CHECKSUM,
@@ -9287,7 +9645,7 @@ var Mnemonic = class {
9287
9645
  static mnemonicToEntropy(phrase, wordlist = english) {
9288
9646
  const words = getWords(phrase);
9289
9647
  assertMnemonic(words);
9290
- return hexlify22(mnemonicWordsToEntropy(words, wordlist));
9648
+ return hexlify23(mnemonicWordsToEntropy(words, wordlist));
9291
9649
  }
9292
9650
  /**
9293
9651
  * @param entropy - Entropy source to the mnemonic phrase.
@@ -9295,7 +9653,7 @@ var Mnemonic = class {
9295
9653
  * @returns 64-byte array contains privateKey and chainCode as described on BIP39
9296
9654
  */
9297
9655
  static entropyToMnemonic(entropy, wordlist = english) {
9298
- const entropyBytes = arrayify18(entropy);
9656
+ const entropyBytes = arrayify19(entropy);
9299
9657
  assertWordList(wordlist);
9300
9658
  assertEntropy(entropyBytes);
9301
9659
  return entropyToMnemonicIndices(entropyBytes).map((i) => wordlist[i]).join(" ");
@@ -9364,14 +9722,14 @@ var Mnemonic = class {
9364
9722
  * @returns 64-byte array contains privateKey and chainCode as described on BIP39
9365
9723
  */
9366
9724
  static masterKeysFromSeed(seed) {
9367
- const seedArray = arrayify18(seed);
9725
+ const seedArray = arrayify19(seed);
9368
9726
  if (seedArray.length < 16 || seedArray.length > 64) {
9369
9727
  throw new FuelError24(
9370
9728
  ErrorCode21.INVALID_SEED,
9371
9729
  `Seed length should be between 16 and 64 bytes, but received ${seedArray.length} bytes.`
9372
9730
  );
9373
9731
  }
9374
- return arrayify18(computeHmac("sha512", MasterSecret, seedArray));
9732
+ return arrayify19(computeHmac("sha512", MasterSecret, seedArray));
9375
9733
  }
9376
9734
  /**
9377
9735
  * Get the extendKey as defined on BIP-32 from the provided seed
@@ -9382,7 +9740,7 @@ var Mnemonic = class {
9382
9740
  */
9383
9741
  static seedToExtendedKey(seed, testnet = false) {
9384
9742
  const masterKey = Mnemonic.masterKeysFromSeed(seed);
9385
- const prefix = arrayify18(testnet ? TestnetPRV : MainnetPRV);
9743
+ const prefix = arrayify19(testnet ? TestnetPRV : MainnetPRV);
9386
9744
  const depth = "0x00";
9387
9745
  const fingerprint = "0x00000000";
9388
9746
  const index = "0x00000000";
@@ -9412,7 +9770,7 @@ var Mnemonic = class {
9412
9770
  * @returns A randomly generated mnemonic
9413
9771
  */
9414
9772
  static generate(size = 32, extraEntropy = "") {
9415
- const entropy = extraEntropy ? sha2563(concat5([randomBytes7(size), arrayify18(extraEntropy)])) : randomBytes7(size);
9773
+ const entropy = extraEntropy ? sha2563(concat5([randomBytes7(size), arrayify19(extraEntropy)])) : randomBytes7(size);
9416
9774
  return Mnemonic.entropyToMnemonic(entropy);
9417
9775
  }
9418
9776
  };
@@ -9420,10 +9778,10 @@ var mnemonic_default = Mnemonic;
9420
9778
 
9421
9779
  // src/hdwallet/hdwallet.ts
9422
9780
  var HARDENED_INDEX = 2147483648;
9423
- var MainnetPRV2 = hexlify23("0x0488ade4");
9424
- var MainnetPUB = hexlify23("0x0488b21e");
9425
- var TestnetPRV2 = hexlify23("0x04358394");
9426
- var TestnetPUB = hexlify23("0x043587cf");
9781
+ var MainnetPRV2 = hexlify24("0x0488ade4");
9782
+ var MainnetPUB = hexlify24("0x0488b21e");
9783
+ var TestnetPRV2 = hexlify24("0x04358394");
9784
+ var TestnetPUB = hexlify24("0x043587cf");
9427
9785
  function base58check(data) {
9428
9786
  return encodeBase582(concat6([data, dataSlice2(sha2564(sha2564(data)), 0, 4)]));
9429
9787
  }
@@ -9434,11 +9792,11 @@ function getExtendedKeyPrefix(isPublic = false, testnet = false) {
9434
9792
  return testnet ? TestnetPRV2 : MainnetPRV2;
9435
9793
  }
9436
9794
  function isPublicExtendedKey(extendedKey) {
9437
- return [MainnetPUB, TestnetPUB].includes(hexlify23(extendedKey.slice(0, 4)));
9795
+ return [MainnetPUB, TestnetPUB].includes(hexlify24(extendedKey.slice(0, 4)));
9438
9796
  }
9439
9797
  function isValidExtendedKey(extendedKey) {
9440
9798
  return [MainnetPRV2, TestnetPRV2, MainnetPUB, TestnetPUB].includes(
9441
- hexlify23(extendedKey.slice(0, 4))
9799
+ hexlify24(extendedKey.slice(0, 4))
9442
9800
  );
9443
9801
  }
9444
9802
  function parsePath(path2, depth = 0) {
@@ -9456,8 +9814,8 @@ function parsePath(path2, depth = 0) {
9456
9814
  var HDWallet = class {
9457
9815
  depth = 0;
9458
9816
  index = 0;
9459
- fingerprint = hexlify23("0x00000000");
9460
- parentFingerprint = hexlify23("0x00000000");
9817
+ fingerprint = hexlify24("0x00000000");
9818
+ parentFingerprint = hexlify24("0x00000000");
9461
9819
  privateKey;
9462
9820
  publicKey;
9463
9821
  chainCode;
@@ -9469,8 +9827,8 @@ var HDWallet = class {
9469
9827
  constructor(config) {
9470
9828
  if (config.privateKey) {
9471
9829
  const signer = new Signer(config.privateKey);
9472
- this.publicKey = hexlify23(signer.compressedPublicKey);
9473
- this.privateKey = hexlify23(config.privateKey);
9830
+ this.publicKey = hexlify24(signer.compressedPublicKey);
9831
+ this.privateKey = hexlify24(config.privateKey);
9474
9832
  } else {
9475
9833
  if (!config.publicKey) {
9476
9834
  throw new FuelError25(
@@ -9478,7 +9836,7 @@ var HDWallet = class {
9478
9836
  "Both public and private Key cannot be missing. At least one should be provided."
9479
9837
  );
9480
9838
  }
9481
- this.publicKey = hexlify23(config.publicKey);
9839
+ this.publicKey = hexlify24(config.publicKey);
9482
9840
  }
9483
9841
  this.parentFingerprint = config.parentFingerprint || this.parentFingerprint;
9484
9842
  this.fingerprint = dataSlice2(ripemd160(sha2564(this.publicKey)), 0, 4);
@@ -9497,9 +9855,9 @@ var HDWallet = class {
9497
9855
  * @returns A new instance of HDWallet on the derived index
9498
9856
  */
9499
9857
  deriveIndex(index) {
9500
- const privateKey = this.privateKey && arrayify19(this.privateKey);
9501
- const publicKey = arrayify19(this.publicKey);
9502
- const chainCode = arrayify19(this.chainCode);
9858
+ const privateKey = this.privateKey && arrayify20(this.privateKey);
9859
+ const publicKey = arrayify20(this.publicKey);
9860
+ const chainCode = arrayify20(this.chainCode);
9503
9861
  const data = new Uint8Array(37);
9504
9862
  if (index & HARDENED_INDEX) {
9505
9863
  if (!privateKey) {
@@ -9510,15 +9868,15 @@ var HDWallet = class {
9510
9868
  }
9511
9869
  data.set(privateKey, 1);
9512
9870
  } else {
9513
- data.set(arrayify19(this.publicKey));
9871
+ data.set(arrayify20(this.publicKey));
9514
9872
  }
9515
9873
  data.set(toBytes2(index, 4), 33);
9516
- const bytes = arrayify19(computeHmac2("sha512", chainCode, data));
9874
+ const bytes = arrayify20(computeHmac2("sha512", chainCode, data));
9517
9875
  const IL = bytes.slice(0, 32);
9518
9876
  const IR = bytes.slice(32);
9519
9877
  if (privateKey) {
9520
9878
  const N = "0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141";
9521
- const ki = bn20(IL).add(privateKey).mod(N).toBytes(32);
9879
+ const ki = bn21(IL).add(privateKey).mod(N).toBytes(32);
9522
9880
  return new HDWallet({
9523
9881
  privateKey: ki,
9524
9882
  chainCode: IR,
@@ -9527,7 +9885,7 @@ var HDWallet = class {
9527
9885
  parentFingerprint: this.fingerprint
9528
9886
  });
9529
9887
  }
9530
- const signer = new Signer(hexlify23(IL));
9888
+ const signer = new Signer(hexlify24(IL));
9531
9889
  const Ki = signer.addPoint(publicKey);
9532
9890
  return new HDWallet({
9533
9891
  publicKey: Ki,
@@ -9562,12 +9920,12 @@ var HDWallet = class {
9562
9920
  );
9563
9921
  }
9564
9922
  const prefix = getExtendedKeyPrefix(this.privateKey == null || isPublic, testnet);
9565
- const depth = hexlify23(Uint8Array.from([this.depth]));
9923
+ const depth = hexlify24(Uint8Array.from([this.depth]));
9566
9924
  const parentFingerprint = this.parentFingerprint;
9567
9925
  const index = toHex(this.index, 4);
9568
9926
  const chainCode = this.chainCode;
9569
9927
  const key = this.privateKey != null && !isPublic ? concat6(["0x00", this.privateKey]) : this.publicKey;
9570
- const extendedKey = arrayify19(concat6([prefix, depth, parentFingerprint, index, chainCode, key]));
9928
+ const extendedKey = arrayify20(concat6([prefix, depth, parentFingerprint, index, chainCode, key]));
9571
9929
  return base58check(extendedKey);
9572
9930
  }
9573
9931
  /**
@@ -9579,13 +9937,13 @@ var HDWallet = class {
9579
9937
  static fromSeed(seed) {
9580
9938
  const masterKey = mnemonic_default.masterKeysFromSeed(seed);
9581
9939
  return new HDWallet({
9582
- chainCode: arrayify19(masterKey.slice(32)),
9583
- privateKey: arrayify19(masterKey.slice(0, 32))
9940
+ chainCode: arrayify20(masterKey.slice(32)),
9941
+ privateKey: arrayify20(masterKey.slice(0, 32))
9584
9942
  });
9585
9943
  }
9586
9944
  static fromExtendedKey(extendedKey) {
9587
- const decoded = hexlify23(toBytes2(decodeBase58(extendedKey)));
9588
- const bytes = arrayify19(decoded);
9945
+ const decoded = hexlify24(toBytes2(decodeBase58(extendedKey)));
9946
+ const bytes = arrayify20(decoded);
9589
9947
  const validChecksum = base58check(bytes.slice(0, 78)) === extendedKey;
9590
9948
  if (bytes.length !== 82 || !isValidExtendedKey(bytes)) {
9591
9949
  throw new FuelError25(ErrorCode22.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
@@ -9594,9 +9952,9 @@ var HDWallet = class {
9594
9952
  throw new FuelError25(ErrorCode22.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
9595
9953
  }
9596
9954
  const depth = bytes[4];
9597
- const parentFingerprint = hexlify23(bytes.slice(5, 9));
9598
- const index = parseInt(hexlify23(bytes.slice(9, 13)).substring(2), 16);
9599
- const chainCode = hexlify23(bytes.slice(13, 45));
9955
+ const parentFingerprint = hexlify24(bytes.slice(5, 9));
9956
+ const index = parseInt(hexlify24(bytes.slice(9, 13)).substring(2), 16);
9957
+ const chainCode = hexlify24(bytes.slice(13, 45));
9600
9958
  const key = bytes.slice(45, 78);
9601
9959
  if (depth === 0 && parentFingerprint !== "0x00000000" || depth === 0 && index !== 0) {
9602
9960
  throw new FuelError25(
@@ -9841,13 +10199,13 @@ var WalletsConfig = class {
9841
10199
  assetIds.forEach((assetId) => {
9842
10200
  for (let index = 0; index < coinsPerAsset; index++) {
9843
10201
  coins.push({
9844
- amount: bn21(amountPerCoin).toString(),
10202
+ amount: bn22(amountPerCoin).toString(),
9845
10203
  asset_id: assetId,
9846
10204
  owner: walletAddress,
9847
10205
  tx_pointer_block_height: 0,
9848
10206
  tx_pointer_tx_idx: 0,
9849
10207
  output_index: 0,
9850
- tx_id: hexlify24(randomBytes8(32))
10208
+ tx_id: hexlify25(randomBytes8(32))
9851
10209
  });
9852
10210
  }
9853
10211
  });
@@ -9878,7 +10236,7 @@ var WalletsConfig = class {
9878
10236
  "Number of coins per asset must be greater than zero."
9879
10237
  );
9880
10238
  }
9881
- if (bn21(amountPerCoin).lt(0)) {
10239
+ if (bn22(amountPerCoin).lt(0)) {
9882
10240
  throw new FuelError26(
9883
10241
  FuelError26.CODES.INVALID_INPUT_PARAMETERS,
9884
10242
  "Amount per coin must be greater than or equal to zero."
@@ -9954,8 +10312,8 @@ async function setupTestProviderAndWallets({
9954
10312
  // src/test-utils/test-message.ts
9955
10313
  import { Address as Address7 } from "@fuel-ts/address";
9956
10314
  import { randomBytes as randomBytes9 } from "@fuel-ts/crypto";
9957
- import { bn as bn22 } from "@fuel-ts/math";
9958
- import { hexlify as hexlify25 } from "@fuel-ts/utils";
10315
+ import { bn as bn23 } from "@fuel-ts/math";
10316
+ import { hexlify as hexlify26 } from "@fuel-ts/utils";
9959
10317
  var TestMessage = class {
9960
10318
  sender;
9961
10319
  recipient;
@@ -9972,7 +10330,7 @@ var TestMessage = class {
9972
10330
  constructor({
9973
10331
  sender = Address7.fromRandom(),
9974
10332
  recipient = Address7.fromRandom(),
9975
- nonce = hexlify25(randomBytes9(32)),
10333
+ nonce = hexlify26(randomBytes9(32)),
9976
10334
  amount = 1e6,
9977
10335
  data = "",
9978
10336
  // Will default to empty data in order to be a spendable message
@@ -9991,7 +10349,7 @@ var TestMessage = class {
9991
10349
  sender: this.sender.toB256(),
9992
10350
  recipient: recipient?.toB256() ?? this.recipient.toB256(),
9993
10351
  nonce: this.nonce,
9994
- amount: bn22(this.amount).toNumber(),
10352
+ amount: bn23(this.amount).toNumber(),
9995
10353
  data,
9996
10354
  da_height: this.da_height
9997
10355
  };