@fuel-ts/account 0.100.3 → 0.100.4

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 (60) hide show
  1. package/dist/account.d.ts +71 -3
  2. package/dist/account.d.ts.map +1 -1
  3. package/dist/index.global.js +1467 -217
  4. package/dist/index.global.js.map +1 -1
  5. package/dist/index.js +2165 -1005
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +1976 -818
  8. package/dist/index.mjs.map +1 -1
  9. package/dist/predicate/predicate.d.ts +9 -4
  10. package/dist/predicate/predicate.d.ts.map +1 -1
  11. package/dist/providers/__generated__/operations.d.ts +1183 -87
  12. package/dist/providers/__generated__/operations.d.ts.map +1 -1
  13. package/dist/providers/assemble-tx-helpers.d.ts +39 -0
  14. package/dist/providers/assemble-tx-helpers.d.ts.map +1 -0
  15. package/dist/providers/fuel-graphql-subscriber.d.ts +28 -0
  16. package/dist/providers/fuel-graphql-subscriber.d.ts.map +1 -1
  17. package/dist/providers/index.d.ts +1 -0
  18. package/dist/providers/index.d.ts.map +1 -1
  19. package/dist/providers/provider.d.ts +80 -6
  20. package/dist/providers/provider.d.ts.map +1 -1
  21. package/dist/providers/resource.d.ts +4 -1
  22. package/dist/providers/resource.d.ts.map +1 -1
  23. package/dist/providers/transaction-request/helpers.d.ts +3 -3
  24. package/dist/providers/transaction-request/helpers.d.ts.map +1 -1
  25. package/dist/providers/transaction-request/input.d.ts +2 -0
  26. package/dist/providers/transaction-request/input.d.ts.map +1 -1
  27. package/dist/providers/transaction-request/output.d.ts +6 -0
  28. package/dist/providers/transaction-request/output.d.ts.map +1 -1
  29. package/dist/providers/transaction-request/script-transaction-request.d.ts +11 -0
  30. package/dist/providers/transaction-request/script-transaction-request.d.ts.map +1 -1
  31. package/dist/providers/transaction-response/transaction-response.d.ts +38 -11
  32. package/dist/providers/transaction-response/transaction-response.d.ts.map +1 -1
  33. package/dist/providers/transaction-summary/assemble-transaction-summary.d.ts +12 -1
  34. package/dist/providers/transaction-summary/assemble-transaction-summary.d.ts.map +1 -1
  35. package/dist/providers/transaction-summary/get-transaction-summary.d.ts.map +1 -1
  36. package/dist/providers/transaction-summary/status.d.ts +16 -2
  37. package/dist/providers/transaction-summary/status.d.ts.map +1 -1
  38. package/dist/providers/transaction-summary/types.d.ts +85 -4
  39. package/dist/providers/transaction-summary/types.d.ts.map +1 -1
  40. package/dist/providers/utils/handle-gql-error-message.d.ts.map +1 -1
  41. package/dist/providers/utils/index.d.ts +1 -0
  42. package/dist/providers/utils/index.d.ts.map +1 -1
  43. package/dist/providers/utils/parse-graphql-response.d.ts +12 -0
  44. package/dist/providers/utils/parse-graphql-response.d.ts.map +1 -0
  45. package/dist/providers/utils/serialization.d.ts +9 -0
  46. package/dist/providers/utils/serialization.d.ts.map +1 -1
  47. package/dist/test-utils/launchNode.d.ts.map +1 -1
  48. package/dist/test-utils/setup-test-provider-and-wallets.d.ts.map +1 -1
  49. package/dist/test-utils.global.js +1461 -201
  50. package/dist/test-utils.global.js.map +1 -1
  51. package/dist/test-utils.js +2046 -891
  52. package/dist/test-utils.js.map +1 -1
  53. package/dist/test-utils.mjs +1892 -731
  54. package/dist/test-utils.mjs.map +1 -1
  55. package/dist/utils/deployScriptOrPredicate.d.ts.map +1 -1
  56. package/dist/utils/split-coins-into-batches.d.ts +3 -0
  57. package/dist/utils/split-coins-into-batches.d.ts.map +1 -0
  58. package/package.json +15 -15
  59. package/dist/providers/utils/helpers.d.ts +0 -14
  60. package/dist/providers/utils/helpers.d.ts.map +0 -1
@@ -228,6 +228,7 @@ var launchNode = /* @__PURE__ */ __name(async ({
228
228
  const poaInstant = poaInstantFlagValue === "true" || poaInstantFlagValue === void 0;
229
229
  const nativeExecutorVersion = getFlagValueFromArgs(args, "--native-executor-version") || "0";
230
230
  const minGasPrice = getFlagValueFromArgs(args, "--min-gas-price") || "1";
231
+ const startingGasPrice = getFlagValueFromArgs(args, "--starting-gas-price") || "1";
231
232
  const graphQLStartSubstring = "Binding GraphQL provider to";
232
233
  const command = fuelCorePath || "fuel-core";
233
234
  const ipToUse = ip || "0.0.0.0";
@@ -269,6 +270,7 @@ var launchNode = /* @__PURE__ */ __name(async ({
269
270
  ["--port", portToUse],
270
271
  useInMemoryDb ? ["--db-type", "in-memory"] : ["--db-path", tempDir],
271
272
  ["--min-gas-price", minGasPrice],
273
+ ["--starting-gas-price", startingGasPrice],
272
274
  poaInstant ? ["--poa-instant", "true"] : [],
273
275
  ["--native-executor-version", nativeExecutorVersion],
274
276
  ["--consensus-key", consensusKey],
@@ -404,10 +406,10 @@ var addAmountToCoinQuantities = /* @__PURE__ */ __name((params) => {
404
406
 
405
407
  // src/providers/provider.ts
406
408
  import { Address as Address3, isB256 } from "@fuel-ts/address";
407
- import { ErrorCode as ErrorCode16, FuelError as FuelError19 } from "@fuel-ts/errors";
408
- import { bn as bn17 } from "@fuel-ts/math";
409
- import { InputMessageCoder as InputMessageCoder2, TransactionCoder as TransactionCoder5 } from "@fuel-ts/transactions";
410
- import { arrayify as arrayify13, hexlify as hexlify18, DateTime as DateTime2, isDefined as isDefined2 } from "@fuel-ts/utils";
409
+ import { ErrorCode as ErrorCode17, FuelError as FuelError20 } from "@fuel-ts/errors";
410
+ import { bn as bn18 } from "@fuel-ts/math";
411
+ import { InputMessageCoder as InputMessageCoder2, TransactionCoder as TransactionCoder6, TransactionType as TransactionType11 } from "@fuel-ts/transactions";
412
+ import { arrayify as arrayify13, hexlify as hexlify19, DateTime as DateTime2, isDefined as isDefined3, sleep as sleep2 } from "@fuel-ts/utils";
411
413
  import { checkFuelCoreVersionCompatibility, versions } from "@fuel-ts/versions";
412
414
  import { GraphQLClient } from "graphql-request";
413
415
  import gql2 from "graphql-tag";
@@ -415,6 +417,83 @@ import { clone as clone8 } from "ramda";
415
417
 
416
418
  // src/providers/__generated__/operations.ts
417
419
  import gql from "graphql-tag";
420
+ var InputCoinFragmentDoc = gql`
421
+ fragment InputCoinFragment on InputCoin {
422
+ type: __typename
423
+ utxoId
424
+ owner
425
+ amount
426
+ assetId
427
+ txPointer
428
+ coinWitnessIndex: witnessIndex
429
+ predicateGasUsed
430
+ predicate
431
+ predicateData
432
+ }
433
+ `;
434
+ var InputMessageFragmentDoc = gql`
435
+ fragment InputMessageFragment on InputMessage {
436
+ type: __typename
437
+ sender
438
+ recipient
439
+ amount
440
+ nonce
441
+ messageWitnessIndex: witnessIndex
442
+ predicateGasUsed
443
+ data
444
+ predicate
445
+ predicateData
446
+ }
447
+ `;
448
+ var InputContractFragmentDoc = gql`
449
+ fragment InputContractFragment on InputContract {
450
+ type: __typename
451
+ utxoId
452
+ balanceRoot
453
+ stateRoot
454
+ txPointer
455
+ contractId
456
+ }
457
+ `;
458
+ var OutputCoinFragmentDoc = gql`
459
+ fragment OutputCoinFragment on CoinOutput {
460
+ type: __typename
461
+ to
462
+ amount
463
+ assetId
464
+ }
465
+ `;
466
+ var OutputContractFragmentDoc = gql`
467
+ fragment OutputContractFragment on ContractOutput {
468
+ type: __typename
469
+ inputIndex
470
+ balanceRoot
471
+ stateRoot
472
+ }
473
+ `;
474
+ var OutputChangeFragmentDoc = gql`
475
+ fragment OutputChangeFragment on ChangeOutput {
476
+ type: __typename
477
+ to
478
+ amount
479
+ assetId
480
+ }
481
+ `;
482
+ var OutputVariableFragmentDoc = gql`
483
+ fragment OutputVariableFragment on VariableOutput {
484
+ type: __typename
485
+ to
486
+ amount
487
+ assetId
488
+ }
489
+ `;
490
+ var OutputContractCreatedFragmentDoc = gql`
491
+ fragment OutputContractCreatedFragment on ContractCreated {
492
+ type: __typename
493
+ contract
494
+ stateRoot
495
+ }
496
+ `;
418
497
  var SubmittedStatusFragmentDoc = gql`
419
498
  fragment SubmittedStatusFragment on SubmittedStatus {
420
499
  type: __typename
@@ -543,6 +622,87 @@ var SqueezedOutStatusFragmentDoc = gql`
543
622
  reason
544
623
  }
545
624
  `;
625
+ var PreconfirmationSuccessStatusFragmentDoc = gql`
626
+ fragment PreconfirmationSuccessStatusFragment on PreconfirmationSuccessStatus {
627
+ type: __typename
628
+ totalGas
629
+ totalFee
630
+ resolvedOutputs {
631
+ utxoId
632
+ output {
633
+ type: __typename
634
+ ... on CoinOutput {
635
+ to
636
+ amount
637
+ assetId
638
+ }
639
+ ... on ContractOutput {
640
+ inputIndex
641
+ balanceRoot
642
+ stateRoot
643
+ }
644
+ ... on ChangeOutput {
645
+ to
646
+ amount
647
+ assetId
648
+ }
649
+ ... on VariableOutput {
650
+ to
651
+ amount
652
+ assetId
653
+ }
654
+ ... on ContractCreated {
655
+ contract
656
+ stateRoot
657
+ }
658
+ }
659
+ }
660
+ preconfirmationReceipts: receipts {
661
+ ...receiptFragment
662
+ }
663
+ }
664
+ ${ReceiptFragmentDoc}`;
665
+ var PreconfirmationFailureStatusFragmentDoc = gql`
666
+ fragment PreconfirmationFailureStatusFragment on PreconfirmationFailureStatus {
667
+ type: __typename
668
+ reason
669
+ totalGas
670
+ totalFee
671
+ resolvedOutputs {
672
+ utxoId
673
+ output {
674
+ type: __typename
675
+ ... on CoinOutput {
676
+ to
677
+ amount
678
+ assetId
679
+ }
680
+ ... on ContractOutput {
681
+ inputIndex
682
+ balanceRoot
683
+ stateRoot
684
+ }
685
+ ... on ChangeOutput {
686
+ to
687
+ amount
688
+ assetId
689
+ }
690
+ ... on VariableOutput {
691
+ to
692
+ amount
693
+ assetId
694
+ }
695
+ ... on ContractCreated {
696
+ contract
697
+ stateRoot
698
+ }
699
+ }
700
+ }
701
+ preconfirmationReceipts: receipts {
702
+ ...receiptFragment
703
+ }
704
+ }
705
+ ${ReceiptFragmentDoc}`;
546
706
  var TransactionStatusSubscriptionFragmentDoc = gql`
547
707
  fragment transactionStatusSubscriptionFragment on TransactionStatus {
548
708
  ... on SubmittedStatus {
@@ -563,12 +723,20 @@ var TransactionStatusSubscriptionFragmentDoc = gql`
563
723
  ... on SqueezedOutStatus {
564
724
  ...SqueezedOutStatusFragment
565
725
  }
726
+ ... on PreconfirmationSuccessStatus {
727
+ ...PreconfirmationSuccessStatusFragment
728
+ }
729
+ ... on PreconfirmationFailureStatus {
730
+ ...PreconfirmationFailureStatusFragment
731
+ }
566
732
  }
567
733
  ${SubmittedStatusFragmentDoc}
568
734
  ${SuccessStatusWithBlockIdFragmentDoc}
569
735
  ${MalleableTransactionFieldsFragmentDoc}
570
736
  ${FailureStatusWithBlockIdFragmentDoc}
571
- ${SqueezedOutStatusFragmentDoc}`;
737
+ ${SqueezedOutStatusFragmentDoc}
738
+ ${PreconfirmationSuccessStatusFragmentDoc}
739
+ ${PreconfirmationFailureStatusFragmentDoc}`;
572
740
  var TransactionStatusFragmentDoc = gql`
573
741
  fragment transactionStatusFragment on TransactionStatus {
574
742
  ... on SubmittedStatus {
@@ -620,6 +788,23 @@ var TransactionEstimatePredicatesFragmentDoc = gql`
620
788
  }
621
789
  }
622
790
  ${InputEstimatePredicatesFragmentDoc}`;
791
+ var DryRunFailureAssembleTxFragmentDoc = gql`
792
+ fragment dryRunFailureAssembleTxFragment on DryRunFailureStatus {
793
+ type: __typename
794
+ reason
795
+ receipts {
796
+ ...receiptFragment
797
+ }
798
+ }
799
+ ${ReceiptFragmentDoc}`;
800
+ var DryRunSuccessAssembleTxFragmentDoc = gql`
801
+ fragment dryRunSuccessAssembleTxFragment on DryRunSuccessStatus {
802
+ type: __typename
803
+ receipts {
804
+ ...receiptFragment
805
+ }
806
+ }
807
+ ${ReceiptFragmentDoc}`;
623
808
  var DryRunFailureStatusFragmentDoc = gql`
624
809
  fragment dryRunFailureStatusFragment on DryRunFailureStatus {
625
810
  type: __typename
@@ -976,13 +1161,21 @@ var GetTransactionWithReceiptsDocument = gql`
976
1161
  ... on SqueezedOutStatus {
977
1162
  ...SqueezedOutStatusFragment
978
1163
  }
1164
+ ... on PreconfirmationSuccessStatus {
1165
+ ...PreconfirmationSuccessStatusFragment
1166
+ }
1167
+ ... on PreconfirmationFailureStatus {
1168
+ ...PreconfirmationFailureStatusFragment
1169
+ }
979
1170
  }
980
1171
  }
981
1172
  }
982
1173
  ${SubmittedStatusFragmentDoc}
983
1174
  ${SuccessStatusWithBlockIdFragmentDoc}
984
1175
  ${FailureStatusWithBlockIdFragmentDoc}
985
- ${SqueezedOutStatusFragmentDoc}`;
1176
+ ${SqueezedOutStatusFragmentDoc}
1177
+ ${PreconfirmationSuccessStatusFragmentDoc}
1178
+ ${PreconfirmationFailureStatusFragmentDoc}`;
986
1179
  var GetTransactionsDocument = gql`
987
1180
  query getTransactions($after: String, $before: String, $first: Int, $last: Int) {
988
1181
  transactions(after: $after, before: $before, first: $first, last: $last) {
@@ -1273,6 +1466,77 @@ var GetAssetDetailsDocument = gql`
1273
1466
  }
1274
1467
  }
1275
1468
  `;
1469
+ var AssembleTxDocument = gql`
1470
+ query assembleTx($tx: HexString!, $blockHorizon: U32!, $requiredBalances: [RequiredBalance!]!, $feeAddressIndex: U16!, $excludeInput: ExcludeInput, $estimatePredicates: Boolean, $reserveGas: U64) {
1471
+ assembleTx(
1472
+ tx: $tx
1473
+ blockHorizon: $blockHorizon
1474
+ requiredBalances: $requiredBalances
1475
+ feeAddressIndex: $feeAddressIndex
1476
+ excludeInput: $excludeInput
1477
+ estimatePredicates: $estimatePredicates
1478
+ reserveGas: $reserveGas
1479
+ ) {
1480
+ transaction {
1481
+ id
1482
+ inputs {
1483
+ ... on InputCoin {
1484
+ ...InputCoinFragment
1485
+ }
1486
+ ... on InputContract {
1487
+ ...InputContractFragment
1488
+ }
1489
+ ... on InputMessage {
1490
+ ...InputMessageFragment
1491
+ }
1492
+ }
1493
+ outputs {
1494
+ ... on CoinOutput {
1495
+ ...OutputCoinFragment
1496
+ }
1497
+ ... on ContractOutput {
1498
+ ...OutputContractFragment
1499
+ }
1500
+ ... on ChangeOutput {
1501
+ ...OutputChangeFragment
1502
+ }
1503
+ ... on VariableOutput {
1504
+ ...OutputVariableFragment
1505
+ }
1506
+ ... on ContractCreated {
1507
+ ...OutputContractCreatedFragment
1508
+ }
1509
+ }
1510
+ policies {
1511
+ tip
1512
+ witnessLimit
1513
+ maturity
1514
+ maxFee
1515
+ }
1516
+ witnesses
1517
+ scriptGasLimit
1518
+ }
1519
+ status {
1520
+ ... on DryRunFailureStatus {
1521
+ ...dryRunFailureAssembleTxFragment
1522
+ }
1523
+ ... on DryRunSuccessStatus {
1524
+ ...dryRunSuccessAssembleTxFragment
1525
+ }
1526
+ }
1527
+ gasPrice
1528
+ }
1529
+ }
1530
+ ${InputCoinFragmentDoc}
1531
+ ${InputContractFragmentDoc}
1532
+ ${InputMessageFragmentDoc}
1533
+ ${OutputCoinFragmentDoc}
1534
+ ${OutputContractFragmentDoc}
1535
+ ${OutputChangeFragmentDoc}
1536
+ ${OutputVariableFragmentDoc}
1537
+ ${OutputContractCreatedFragmentDoc}
1538
+ ${DryRunFailureAssembleTxFragmentDoc}
1539
+ ${DryRunSuccessAssembleTxFragmentDoc}`;
1276
1540
  var DryRunDocument = gql`
1277
1541
  mutation dryRun($encodedTransactions: [HexString!]!, $utxoValidation: Boolean, $gasPrice: U64) {
1278
1542
  dryRun(
@@ -1331,15 +1595,22 @@ var GetConsensusParametersVersionDocument = gql`
1331
1595
  }
1332
1596
  `;
1333
1597
  var SubmitAndAwaitStatusDocument = gql`
1334
- subscription submitAndAwaitStatus($encodedTransaction: HexString!) {
1335
- submitAndAwaitStatus(tx: $encodedTransaction) {
1598
+ subscription submitAndAwaitStatus($encodedTransaction: HexString!, $estimatePredicates: Boolean, $includePreConfirmation: Boolean) {
1599
+ submitAndAwaitStatus(
1600
+ tx: $encodedTransaction
1601
+ estimatePredicates: $estimatePredicates
1602
+ includePreconfirmation: $includePreConfirmation
1603
+ ) {
1336
1604
  ...transactionStatusSubscriptionFragment
1337
1605
  }
1338
1606
  }
1339
1607
  ${TransactionStatusSubscriptionFragmentDoc}`;
1340
1608
  var StatusChangeDocument = gql`
1341
- subscription statusChange($transactionId: TransactionId!) {
1342
- statusChange(id: $transactionId) {
1609
+ subscription statusChange($transactionId: TransactionId!, $includePreConfirmation: Boolean) {
1610
+ statusChange(
1611
+ id: $transactionId
1612
+ includePreconfirmation: $includePreConfirmation
1613
+ ) {
1343
1614
  ...transactionStatusSubscriptionFragment
1344
1615
  }
1345
1616
  }
@@ -1442,6 +1713,9 @@ function getSdk(requester) {
1442
1713
  getAssetDetails(variables, options) {
1443
1714
  return requester(GetAssetDetailsDocument, variables, options);
1444
1715
  },
1716
+ assembleTx(variables, options) {
1717
+ return requester(AssembleTxDocument, variables, options);
1718
+ },
1445
1719
  dryRun(variables, options) {
1446
1720
  return requester(DryRunDocument, variables, options);
1447
1721
  },
@@ -1470,36 +1744,123 @@ function getSdk(requester) {
1470
1744
  }
1471
1745
  __name(getSdk, "getSdk");
1472
1746
 
1747
+ // src/providers/assemble-tx-helpers.ts
1748
+ import { FuelError as FuelError2, ErrorCode } from "@fuel-ts/errors";
1749
+ import { bn as bn2 } from "@fuel-ts/math";
1750
+ import { TransactionType } from "@fuel-ts/transactions";
1751
+ import { hexlify as hexlify4, isDefined } from "@fuel-ts/utils";
1752
+ var resolveAccountForAssembleTxParams = /* @__PURE__ */ __name((account) => {
1753
+ const assembleTxAccount = {};
1754
+ const accountIsPredicate = "bytes" in account;
1755
+ if (accountIsPredicate) {
1756
+ assembleTxAccount.predicate = {
1757
+ predicate: hexlify4(account.bytes),
1758
+ predicateAddress: account.address.toB256(),
1759
+ predicateData: hexlify4(account.getPredicateData())
1760
+ };
1761
+ } else {
1762
+ assembleTxAccount.address = account.address.toB256();
1763
+ }
1764
+ return assembleTxAccount;
1765
+ }, "resolveAccountForAssembleTxParams");
1766
+ var setAndValidateGasAndFeeForAssembledTx = /* @__PURE__ */ __name(async (params) => {
1767
+ const { gasPrice, transactionRequest, setGasLimit, setMaxFee, provider } = params;
1768
+ const gasLimitSpecified = isDefined(setGasLimit);
1769
+ const maxFeeSpecified = isDefined(setMaxFee);
1770
+ const isScriptTx = transactionRequest.type === TransactionType.Script;
1771
+ if (gasLimitSpecified && isScriptTx) {
1772
+ const requiredGasLimit = transactionRequest.gasLimit;
1773
+ if (bn2(setGasLimit).lt(bn2(requiredGasLimit))) {
1774
+ throw new FuelError2(
1775
+ ErrorCode.GAS_LIMIT_TOO_LOW,
1776
+ `Gas limit '${setGasLimit}' is lower than the required: '${requiredGasLimit}'.`
1777
+ );
1778
+ }
1779
+ transactionRequest.gasLimit = bn2(setGasLimit);
1780
+ }
1781
+ if (maxFeeSpecified) {
1782
+ const requiredMaxFee = transactionRequest.maxFee;
1783
+ if (bn2(setMaxFee).lt(requiredMaxFee)) {
1784
+ throw new FuelError2(
1785
+ ErrorCode.MAX_FEE_TOO_LOW,
1786
+ `Max fee '${setMaxFee}' is lower than the required: '${requiredMaxFee}'.`
1787
+ );
1788
+ }
1789
+ transactionRequest.maxFee = bn2(setMaxFee);
1790
+ }
1791
+ if (gasLimitSpecified && !maxFeeSpecified) {
1792
+ const { maxFee: feeForGasPrice } = await provider.estimateTxGasAndFee({
1793
+ transactionRequest,
1794
+ gasPrice
1795
+ });
1796
+ transactionRequest.maxFee = feeForGasPrice;
1797
+ }
1798
+ return transactionRequest;
1799
+ }, "setAndValidateGasAndFeeForAssembledTx");
1800
+
1473
1801
  // src/providers/fuel-graphql-subscriber.ts
1474
- import { ErrorCode as ErrorCode2, FuelError as FuelError3 } from "@fuel-ts/errors";
1802
+ import { ErrorCode as ErrorCode3, FuelError as FuelError4 } from "@fuel-ts/errors";
1475
1803
  import { print } from "graphql";
1476
1804
 
1477
1805
  // src/providers/utils/handle-gql-error-message.ts
1478
- import { ErrorCode, FuelError as FuelError2 } from "@fuel-ts/errors";
1806
+ import { ErrorCode as ErrorCode2, FuelError as FuelError3 } from "@fuel-ts/errors";
1807
+ var gqlErrorMessage = {
1808
+ RPC_CONSISTENCY: /The required fuel block height is higher than the current block height. Required: \d+, Current: \d+/,
1809
+ NOT_ENOUGH_COINS_MAX_COINS: /the target cannot be met due to no coins available or exceeding the \d+ coin limit./,
1810
+ ASSET_NOT_FOUND: /resource was not found in table/,
1811
+ MULTIPLE_CHANGE_POLICIES: /The asset ([a-fA-F0-9]{64}) has multiple change policies/,
1812
+ DUPLICATE_CHANGE_OUTPUT_ACCOUNT: /required balances contain duplicate \(asset, account\) pair/,
1813
+ INSUFFICIENT_FEE_AMOUNT: /InsufficientFeeAmount { expected: (\d+), provided: (\d+) }/
1814
+ };
1479
1815
  var mapGqlErrorMessage = /* @__PURE__ */ __name((error) => {
1480
- 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)) {
1481
- return new FuelError2(
1482
- ErrorCode.INSUFFICIENT_FUNDS_OR_MAX_COINS,
1816
+ if (gqlErrorMessage.NOT_ENOUGH_COINS_MAX_COINS.test(error.message)) {
1817
+ return new FuelError3(
1818
+ ErrorCode2.INSUFFICIENT_FUNDS_OR_MAX_COINS,
1483
1819
  `Insufficient funds or too many small value coins. Consider combining UTXOs.`,
1484
1820
  {},
1485
1821
  error
1486
1822
  );
1487
1823
  }
1488
- if (new RegExp("resource was not found in table" /* ASSET_NOT_FOUND */).test(error.message)) {
1489
- return new FuelError2(
1490
- ErrorCode.ASSET_NOT_FOUND,
1824
+ if (gqlErrorMessage.MULTIPLE_CHANGE_POLICIES.test(error.message)) {
1825
+ const match = error.message.match(/asset ([a-fA-F0-9]{64})/);
1826
+ const assetId = match?.[1] || "";
1827
+ return new FuelError3(
1828
+ ErrorCode2.CHANGE_OUTPUT_COLLISION,
1829
+ `OutputChange address for asset 0x${assetId} differs between transaction request and assembleTx parameters.`,
1830
+ {},
1831
+ error
1832
+ );
1833
+ }
1834
+ if (gqlErrorMessage.DUPLICATE_CHANGE_OUTPUT_ACCOUNT.test(error.message)) {
1835
+ return new FuelError3(
1836
+ ErrorCode2.DUPLICATE_CHANGE_OUTPUT_ACCOUNT,
1837
+ `The parameter 'accountCoinQuantities' of assembleTx contains duplicate entries for the same assetId with different 'changeOutputAccount'.`,
1838
+ {},
1839
+ error
1840
+ );
1841
+ }
1842
+ if (gqlErrorMessage.ASSET_NOT_FOUND.test(error.message)) {
1843
+ return new FuelError3(
1844
+ ErrorCode2.ASSET_NOT_FOUND,
1491
1845
  `Asset not found for given asset id.`,
1492
1846
  {},
1493
1847
  error
1494
1848
  );
1495
1849
  }
1496
- return new FuelError2(ErrorCode.INVALID_REQUEST, error.message, {}, error);
1850
+ if (gqlErrorMessage.RPC_CONSISTENCY.test(error.message)) {
1851
+ return new FuelError3(ErrorCode2.RPC_CONSISTENCY, error.message, {}, error);
1852
+ }
1853
+ if (gqlErrorMessage.INSUFFICIENT_FEE_AMOUNT.test(error.message)) {
1854
+ const match = error.message.match(gqlErrorMessage.INSUFFICIENT_FEE_AMOUNT);
1855
+ return new FuelError3(ErrorCode2.FUNDS_TOO_LOW, match?.[0] || error.message, {}, error);
1856
+ }
1857
+ return new FuelError3(ErrorCode2.INVALID_REQUEST, error.message, {}, error);
1497
1858
  }, "mapGqlErrorMessage");
1498
1859
  var mapGqlErrorWithIncompatibleNodeVersion = /* @__PURE__ */ __name((error, incompatibleNodeVersionMessage) => {
1499
1860
  if (!incompatibleNodeVersionMessage) {
1500
1861
  return error;
1501
1862
  }
1502
- return new FuelError2(
1863
+ return new FuelError3(
1503
1864
  error.code,
1504
1865
  `${error.message}
1505
1866
 
@@ -1518,15 +1879,16 @@ var assertGqlResponseHasNoErrors = /* @__PURE__ */ __name((errors, incompatibleN
1518
1879
  }
1519
1880
  const errorMessage = mappedErrors.map((err) => err.message).join("\n");
1520
1881
  throw mapGqlErrorWithIncompatibleNodeVersion(
1521
- new FuelError2(ErrorCode.INVALID_REQUEST, errorMessage, {}, mappedErrors),
1882
+ new FuelError3(ErrorCode2.INVALID_REQUEST, errorMessage, {}, mappedErrors),
1522
1883
  incompatibleNodeVersionMessage
1523
1884
  );
1524
1885
  }, "assertGqlResponseHasNoErrors");
1525
1886
 
1526
1887
  // src/providers/fuel-graphql-subscriber.ts
1527
1888
  var FuelGraphqlSubscriber = class _FuelGraphqlSubscriber {
1528
- constructor(stream) {
1889
+ constructor(stream, onEvent) {
1529
1890
  this.stream = stream;
1891
+ this.onEvent = onEvent;
1530
1892
  }
1531
1893
  static {
1532
1894
  __name(this, "FuelGraphqlSubscriber");
@@ -1534,12 +1896,13 @@ var FuelGraphqlSubscriber = class _FuelGraphqlSubscriber {
1534
1896
  static incompatibleNodeVersionMessage = false;
1535
1897
  static textDecoder = new TextDecoder();
1536
1898
  static async create(options) {
1537
- const { url, query, variables, fetchFn } = options;
1899
+ const { url, query, variables, fetchFn, operationName, onEvent } = options;
1538
1900
  const response = await fetchFn(`${url}-sub`, {
1539
1901
  method: "POST",
1540
1902
  body: JSON.stringify({
1541
1903
  query: print(query),
1542
- variables
1904
+ variables,
1905
+ operationName
1543
1906
  }),
1544
1907
  headers: {
1545
1908
  "Content-Type": "application/json",
@@ -1548,39 +1911,71 @@ var FuelGraphqlSubscriber = class _FuelGraphqlSubscriber {
1548
1911
  });
1549
1912
  const [errorReader, resultReader] = response.body.tee().map((stream) => stream.getReader());
1550
1913
  await new _FuelGraphqlSubscriber(errorReader).next();
1551
- return new _FuelGraphqlSubscriber(resultReader);
1914
+ return new _FuelGraphqlSubscriber(resultReader, onEvent);
1552
1915
  }
1553
- events = [];
1554
- parsingLeftover = "";
1555
- async next() {
1916
+ /**
1917
+ * This method will take a stream reader and parse the event from the stream.
1918
+ *
1919
+ * @param reader - The reader of the SSE stream
1920
+ * @param parsingLeftover - The leftover string from parsing the previous event
1921
+ * @returns The event parsed as a full GraphQL response, whether the stream is done and the leftover string after parsing
1922
+ */
1923
+ static async readEvent(reader, parsingLeftover = "") {
1924
+ let text = parsingLeftover;
1925
+ const regex = /data:.*\n\n/g;
1556
1926
  while (true) {
1557
- if (this.events.length > 0) {
1558
- const { data, errors } = this.events.shift();
1559
- assertGqlResponseHasNoErrors(errors, _FuelGraphqlSubscriber.incompatibleNodeVersionMessage);
1560
- return { value: data, done: false };
1561
- }
1562
- const { value, done } = await this.stream.read();
1563
- if (done) {
1564
- return { value, done };
1565
- }
1566
- const decoded = _FuelGraphqlSubscriber.textDecoder.decode(value).replace(":keep-alive-text\n\n", "");
1567
- if (decoded === "") {
1568
- continue;
1569
- }
1570
- const text = `${this.parsingLeftover}${decoded}`;
1571
- const regex = /data:.*\n\n/g;
1572
1927
  const matches = [...text.matchAll(regex)].flatMap((match) => match);
1573
- matches.forEach((match) => {
1928
+ if (matches.length > 0) {
1574
1929
  try {
1575
- this.events.push(JSON.parse(match.replace(/^data:/, "")));
1930
+ const event = JSON.parse(matches[0].replace(/^data:/, ""));
1931
+ return {
1932
+ event,
1933
+ done: false,
1934
+ parsingLeftover: text.replace(matches[0], "")
1935
+ };
1576
1936
  } catch (e) {
1577
- throw new FuelError3(
1578
- ErrorCode2.STREAM_PARSING_ERROR,
1937
+ throw new FuelError4(
1938
+ ErrorCode3.STREAM_PARSING_ERROR,
1579
1939
  `Error while parsing stream data response: ${text}`
1580
1940
  );
1581
1941
  }
1582
- });
1583
- this.parsingLeftover = text.replace(matches.join(), "");
1942
+ }
1943
+ const { value, done } = await reader.read();
1944
+ if (done) {
1945
+ return { event: void 0, done, parsingLeftover: "" };
1946
+ }
1947
+ const decoded = _FuelGraphqlSubscriber.textDecoder.decode(value).replace(":keep-alive-text\n\n", "");
1948
+ text += decoded;
1949
+ }
1950
+ }
1951
+ events = [];
1952
+ parsingLeftover = "";
1953
+ /**
1954
+ * Gets automatically called when iterating in a `for-await-of` loop.
1955
+ * It can also be called manually.
1956
+ *
1957
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/next
1958
+ */
1959
+ async next() {
1960
+ while (true) {
1961
+ const nextEvent = this.events.shift();
1962
+ if (nextEvent) {
1963
+ this.onEvent?.(nextEvent);
1964
+ assertGqlResponseHasNoErrors(
1965
+ nextEvent.errors,
1966
+ _FuelGraphqlSubscriber.incompatibleNodeVersionMessage
1967
+ );
1968
+ return { value: nextEvent.data, done: false };
1969
+ }
1970
+ const { event, done, parsingLeftover } = await _FuelGraphqlSubscriber.readEvent(
1971
+ this.stream,
1972
+ this.parsingLeftover
1973
+ );
1974
+ this.parsingLeftover = parsingLeftover;
1975
+ if (done) {
1976
+ return { value: void 0, done: true };
1977
+ }
1978
+ this.events.push(event);
1584
1979
  }
1585
1980
  }
1586
1981
  /**
@@ -1595,16 +1990,16 @@ var FuelGraphqlSubscriber = class _FuelGraphqlSubscriber {
1595
1990
  };
1596
1991
 
1597
1992
  // src/providers/resource-cache.ts
1598
- import { FuelError as FuelError13, ErrorCode as ErrorCode10 } from "@fuel-ts/errors";
1599
- import { hexlify as hexlify16 } from "@fuel-ts/utils";
1993
+ import { FuelError as FuelError14, ErrorCode as ErrorCode11 } from "@fuel-ts/errors";
1994
+ import { hexlify as hexlify17 } from "@fuel-ts/utils";
1600
1995
 
1601
1996
  // src/providers/transaction-request/input.ts
1602
1997
  import { BYTES_32 as BYTES_322, UTXO_ID_LEN } from "@fuel-ts/abi-coder";
1603
1998
  import { ZeroBytes32 } from "@fuel-ts/address/configs";
1604
- import { ErrorCode as ErrorCode3, FuelError as FuelError4 } from "@fuel-ts/errors";
1605
- import { bn as bn2, toNumber } from "@fuel-ts/math";
1999
+ import { ErrorCode as ErrorCode4, FuelError as FuelError5 } from "@fuel-ts/errors";
2000
+ import { bn as bn3, toNumber } from "@fuel-ts/math";
1606
2001
  import { InputType } from "@fuel-ts/transactions";
1607
- import { arrayify as arrayify2, hexlify as hexlify4 } from "@fuel-ts/utils";
2002
+ import { arrayify as arrayify2, hexlify as hexlify5 } from "@fuel-ts/utils";
1608
2003
  var inputify = /* @__PURE__ */ __name((value) => {
1609
2004
  const { type } = value;
1610
2005
  switch (value.type) {
@@ -1613,27 +2008,27 @@ var inputify = /* @__PURE__ */ __name((value) => {
1613
2008
  const predicateData = arrayify2(value.predicateData ?? "0x");
1614
2009
  return {
1615
2010
  type: InputType.Coin,
1616
- txID: hexlify4(arrayify2(value.id).slice(0, BYTES_322)),
2011
+ txID: hexlify5(arrayify2(value.id).slice(0, BYTES_322)),
1617
2012
  outputIndex: toNumber(arrayify2(value.id).slice(BYTES_322, UTXO_ID_LEN)),
1618
- owner: hexlify4(value.owner),
1619
- amount: bn2(value.amount),
1620
- assetId: hexlify4(value.assetId),
2013
+ owner: hexlify5(value.owner),
2014
+ amount: bn3(value.amount),
2015
+ assetId: hexlify5(value.assetId),
1621
2016
  txPointer: {
1622
2017
  blockHeight: toNumber(arrayify2(value.txPointer).slice(0, 8)),
1623
2018
  txIndex: toNumber(arrayify2(value.txPointer).slice(8, 16))
1624
2019
  },
1625
2020
  witnessIndex: value.witnessIndex,
1626
- predicateGasUsed: bn2(value.predicateGasUsed),
1627
- predicateLength: bn2(predicate.length),
1628
- predicateDataLength: bn2(predicateData.length),
1629
- predicate: hexlify4(predicate),
1630
- predicateData: hexlify4(predicateData)
2021
+ predicateGasUsed: bn3(value.predicateGasUsed),
2022
+ predicateLength: bn3(predicate.length),
2023
+ predicateDataLength: bn3(predicateData.length),
2024
+ predicate: hexlify5(predicate),
2025
+ predicateData: hexlify5(predicateData)
1631
2026
  };
1632
2027
  }
1633
2028
  case InputType.Contract: {
1634
2029
  return {
1635
2030
  type: InputType.Contract,
1636
- txID: ZeroBytes32,
2031
+ txID: hexlify5(value.txID || ZeroBytes32),
1637
2032
  outputIndex: 0,
1638
2033
  balanceRoot: ZeroBytes32,
1639
2034
  stateRoot: ZeroBytes32,
@@ -1641,7 +2036,7 @@ var inputify = /* @__PURE__ */ __name((value) => {
1641
2036
  blockHeight: toNumber(arrayify2(value.txPointer).slice(0, 8)),
1642
2037
  txIndex: toNumber(arrayify2(value.txPointer).slice(8, 16))
1643
2038
  },
1644
- contractID: hexlify4(value.contractId)
2039
+ contractID: hexlify5(value.contractId)
1645
2040
  };
1646
2041
  }
1647
2042
  case InputType.Message: {
@@ -1650,23 +2045,23 @@ var inputify = /* @__PURE__ */ __name((value) => {
1650
2045
  const data = arrayify2(value.data ?? "0x");
1651
2046
  return {
1652
2047
  type: InputType.Message,
1653
- sender: hexlify4(value.sender),
1654
- recipient: hexlify4(value.recipient),
1655
- amount: bn2(value.amount),
1656
- nonce: hexlify4(value.nonce),
2048
+ sender: hexlify5(value.sender),
2049
+ recipient: hexlify5(value.recipient),
2050
+ amount: bn3(value.amount),
2051
+ nonce: hexlify5(value.nonce),
1657
2052
  witnessIndex: value.witnessIndex,
1658
- predicateGasUsed: bn2(value.predicateGasUsed),
1659
- predicateLength: bn2(predicate.length),
1660
- predicateDataLength: bn2(predicateData.length),
1661
- predicate: hexlify4(predicate),
1662
- predicateData: hexlify4(predicateData),
1663
- data: hexlify4(data),
2053
+ predicateGasUsed: bn3(value.predicateGasUsed),
2054
+ predicateLength: bn3(predicate.length),
2055
+ predicateDataLength: bn3(predicateData.length),
2056
+ predicate: hexlify5(predicate),
2057
+ predicateData: hexlify5(predicateData),
2058
+ data: hexlify5(data),
1664
2059
  dataLength: data.length
1665
2060
  };
1666
2061
  }
1667
2062
  default: {
1668
- throw new FuelError4(
1669
- ErrorCode3.INVALID_TRANSACTION_INPUT,
2063
+ throw new FuelError5(
2064
+ ErrorCode4.INVALID_TRANSACTION_INPUT,
1670
2065
  `Invalid transaction input type: ${type}.`
1671
2066
  );
1672
2067
  }
@@ -1675,19 +2070,19 @@ var inputify = /* @__PURE__ */ __name((value) => {
1675
2070
 
1676
2071
  // src/providers/transaction-request/output.ts
1677
2072
  import { ZeroBytes32 as ZeroBytes322 } from "@fuel-ts/address/configs";
1678
- import { ErrorCode as ErrorCode4, FuelError as FuelError5 } from "@fuel-ts/errors";
1679
- import { bn as bn3 } from "@fuel-ts/math";
2073
+ import { ErrorCode as ErrorCode5, FuelError as FuelError6 } from "@fuel-ts/errors";
2074
+ import { bn as bn4 } from "@fuel-ts/math";
1680
2075
  import { OutputType } from "@fuel-ts/transactions";
1681
- import { hexlify as hexlify5 } from "@fuel-ts/utils";
2076
+ import { hexlify as hexlify6 } from "@fuel-ts/utils";
1682
2077
  var outputify = /* @__PURE__ */ __name((value) => {
1683
2078
  const { type } = value;
1684
2079
  switch (type) {
1685
2080
  case OutputType.Coin: {
1686
2081
  return {
1687
2082
  type: OutputType.Coin,
1688
- to: hexlify5(value.to),
1689
- amount: bn3(value.amount),
1690
- assetId: hexlify5(value.assetId)
2083
+ to: hexlify6(value.to),
2084
+ amount: bn4(value.amount),
2085
+ assetId: hexlify6(value.assetId)
1691
2086
  };
1692
2087
  }
1693
2088
  case OutputType.Contract: {
@@ -1701,29 +2096,29 @@ var outputify = /* @__PURE__ */ __name((value) => {
1701
2096
  case OutputType.Change: {
1702
2097
  return {
1703
2098
  type: OutputType.Change,
1704
- to: hexlify5(value.to),
1705
- amount: bn3(0),
1706
- assetId: hexlify5(value.assetId)
2099
+ to: hexlify6(value.to),
2100
+ amount: bn4(0),
2101
+ assetId: hexlify6(value.assetId)
1707
2102
  };
1708
2103
  }
1709
2104
  case OutputType.Variable: {
1710
2105
  return {
1711
2106
  type: OutputType.Variable,
1712
- to: ZeroBytes322,
1713
- amount: bn3(0),
1714
- assetId: ZeroBytes322
2107
+ to: hexlify6(value.to || ZeroBytes322),
2108
+ amount: bn4(value.amount),
2109
+ assetId: hexlify6(value.assetId || ZeroBytes322)
1715
2110
  };
1716
2111
  }
1717
2112
  case OutputType.ContractCreated: {
1718
2113
  return {
1719
2114
  type: OutputType.ContractCreated,
1720
- contractId: hexlify5(value.contractId),
1721
- stateRoot: hexlify5(value.stateRoot)
2115
+ contractId: hexlify6(value.contractId),
2116
+ stateRoot: hexlify6(value.stateRoot)
1722
2117
  };
1723
2118
  }
1724
2119
  default: {
1725
- throw new FuelError5(
1726
- ErrorCode4.INVALID_TRANSACTION_INPUT,
2120
+ throw new FuelError6(
2121
+ ErrorCode5.INVALID_TRANSACTION_INPUT,
1727
2122
  `Invalid transaction output type: ${type}.`
1728
2123
  );
1729
2124
  }
@@ -1735,16 +2130,16 @@ import { UTXO_ID_LEN as UTXO_ID_LEN2 } from "@fuel-ts/abi-coder";
1735
2130
  import { Address as Address2, addressify } from "@fuel-ts/address";
1736
2131
  import { ZeroBytes32 as ZeroBytes324 } from "@fuel-ts/address/configs";
1737
2132
  import { randomBytes as randomBytes3 } from "@fuel-ts/crypto";
1738
- import { FuelError as FuelError10 } from "@fuel-ts/errors";
1739
- import { bn as bn8 } from "@fuel-ts/math";
2133
+ import { FuelError as FuelError11 } from "@fuel-ts/errors";
2134
+ import { bn as bn9 } from "@fuel-ts/math";
1740
2135
  import {
1741
2136
  PolicyType,
1742
2137
  TransactionCoder,
1743
- InputType as InputType3,
1744
- OutputType as OutputType3,
1745
- TransactionType
2138
+ InputType as InputType4,
2139
+ OutputType as OutputType4,
2140
+ TransactionType as TransactionType2
1746
2141
  } from "@fuel-ts/transactions";
1747
- import { concat as concat2, hexlify as hexlify10, isDefined } from "@fuel-ts/utils";
2142
+ import { concat as concat2, hexlify as hexlify11, isDefined as isDefined2 } from "@fuel-ts/utils";
1748
2143
 
1749
2144
  // src/providers/message.ts
1750
2145
  var isMessageCoin = /* @__PURE__ */ __name((message) => !("data" in message), "isMessageCoin");
@@ -1758,10 +2153,16 @@ import { FAILED_TRANSFER_TO_ADDRESS_SIGNAL } from "@fuel-ts/transactions/configs
1758
2153
 
1759
2154
  // src/providers/utils/serialization.ts
1760
2155
  import { ZeroBytes32 as ZeroBytes323 } from "@fuel-ts/address/configs";
1761
- import { ErrorCode as ErrorCode5, FuelError as FuelError6 } from "@fuel-ts/errors";
1762
- import { bn as bn4 } from "@fuel-ts/math";
1763
- import { getMintedAssetId, InputMessageCoder, ReceiptType } from "@fuel-ts/transactions";
1764
- import { hexlify as hexlify6, arrayify as arrayify3 } from "@fuel-ts/utils";
2156
+ import { ErrorCode as ErrorCode6, FuelError as FuelError7 } from "@fuel-ts/errors";
2157
+ import { bn as bn5 } from "@fuel-ts/math";
2158
+ import {
2159
+ getMintedAssetId,
2160
+ InputMessageCoder,
2161
+ InputType as InputType2,
2162
+ OutputType as OutputType2,
2163
+ ReceiptType
2164
+ } from "@fuel-ts/transactions";
2165
+ import { hexlify as hexlify7, arrayify as arrayify3, assertUnreachable } from "@fuel-ts/utils";
1765
2166
  var deserializeChain = /* @__PURE__ */ __name((chain) => {
1766
2167
  const { name, daHeight, consensusParameters } = chain;
1767
2168
  const {
@@ -1777,41 +2178,41 @@ var deserializeChain = /* @__PURE__ */ __name((chain) => {
1777
2178
  } = consensusParameters;
1778
2179
  return {
1779
2180
  name,
1780
- baseChainHeight: bn4(daHeight),
2181
+ baseChainHeight: bn5(daHeight),
1781
2182
  consensusParameters: {
1782
2183
  version,
1783
- chainId: bn4(chainId),
2184
+ chainId: bn5(chainId),
1784
2185
  baseAssetId,
1785
2186
  feeParameters: {
1786
2187
  version: feeParams.version,
1787
- gasPerByte: bn4(feeParams.gasPerByte),
1788
- gasPriceFactor: bn4(feeParams.gasPriceFactor)
2188
+ gasPerByte: bn5(feeParams.gasPerByte),
2189
+ gasPriceFactor: bn5(feeParams.gasPriceFactor)
1789
2190
  },
1790
2191
  contractParameters: {
1791
2192
  version: contractParams.version,
1792
- contractMaxSize: bn4(contractParams.contractMaxSize),
1793
- maxStorageSlots: bn4(contractParams.maxStorageSlots)
2193
+ contractMaxSize: bn5(contractParams.contractMaxSize),
2194
+ maxStorageSlots: bn5(contractParams.maxStorageSlots)
1794
2195
  },
1795
2196
  txParameters: {
1796
2197
  version: txParams.version,
1797
- maxInputs: bn4(txParams.maxInputs),
1798
- maxOutputs: bn4(txParams.maxOutputs),
1799
- maxWitnesses: bn4(txParams.maxWitnesses),
1800
- maxGasPerTx: bn4(txParams.maxGasPerTx),
1801
- maxSize: bn4(txParams.maxSize),
1802
- maxBytecodeSubsections: bn4(txParams.maxBytecodeSubsections)
2198
+ maxInputs: bn5(txParams.maxInputs),
2199
+ maxOutputs: bn5(txParams.maxOutputs),
2200
+ maxWitnesses: bn5(txParams.maxWitnesses),
2201
+ maxGasPerTx: bn5(txParams.maxGasPerTx),
2202
+ maxSize: bn5(txParams.maxSize),
2203
+ maxBytecodeSubsections: bn5(txParams.maxBytecodeSubsections)
1803
2204
  },
1804
2205
  predicateParameters: {
1805
2206
  version: predicateParams.version,
1806
- maxPredicateLength: bn4(predicateParams.maxPredicateLength),
1807
- maxPredicateDataLength: bn4(predicateParams.maxPredicateDataLength),
1808
- maxGasPerPredicate: bn4(predicateParams.maxGasPerPredicate),
1809
- maxMessageDataLength: bn4(predicateParams.maxMessageDataLength)
2207
+ maxPredicateLength: bn5(predicateParams.maxPredicateLength),
2208
+ maxPredicateDataLength: bn5(predicateParams.maxPredicateDataLength),
2209
+ maxGasPerPredicate: bn5(predicateParams.maxGasPerPredicate),
2210
+ maxMessageDataLength: bn5(predicateParams.maxMessageDataLength)
1810
2211
  },
1811
2212
  scriptParameters: {
1812
2213
  version: scriptParams.version,
1813
- maxScriptLength: bn4(scriptParams.maxScriptLength),
1814
- maxScriptDataLength: bn4(scriptParams.maxScriptDataLength)
2214
+ maxScriptLength: bn5(scriptParams.maxScriptLength),
2215
+ maxScriptDataLength: bn5(scriptParams.maxScriptDataLength)
1815
2216
  },
1816
2217
  gasCosts
1817
2218
  }
@@ -1875,8 +2276,8 @@ var serializeChain = /* @__PURE__ */ __name((chain) => {
1875
2276
  var deserializeNodeInfo = /* @__PURE__ */ __name((nodeInfo) => {
1876
2277
  const { maxDepth, maxTx, nodeVersion, utxoValidation, vmBacktrace, indexation } = nodeInfo;
1877
2278
  return {
1878
- maxDepth: bn4(maxDepth),
1879
- maxTx: bn4(maxTx),
2279
+ maxDepth: bn5(maxDepth),
2280
+ maxTx: bn5(maxTx),
1880
2281
  nodeVersion,
1881
2282
  utxoValidation,
1882
2283
  vmBacktrace,
@@ -1914,13 +2315,13 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1914
2315
  type: ReceiptType.Call,
1915
2316
  id,
1916
2317
  to: hexOrZero(receipt?.to),
1917
- amount: bn4(receipt.amount),
2318
+ amount: bn5(receipt.amount),
1918
2319
  assetId: hexOrZero(receipt.assetId),
1919
- gas: bn4(receipt.gas),
1920
- param1: bn4(receipt.param1),
1921
- param2: bn4(receipt.param2),
1922
- pc: bn4(receipt.pc),
1923
- is: bn4(receipt.is)
2320
+ gas: bn5(receipt.gas),
2321
+ param1: bn5(receipt.param1),
2322
+ param2: bn5(receipt.param2),
2323
+ pc: bn5(receipt.pc),
2324
+ is: bn5(receipt.is)
1924
2325
  };
1925
2326
  return callReceipt;
1926
2327
  }
@@ -1928,9 +2329,9 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1928
2329
  const returnReceipt = {
1929
2330
  type: ReceiptType.Return,
1930
2331
  id: hexOrZero(receipt.id || receipt.contractId),
1931
- val: bn4(receipt.val),
1932
- pc: bn4(receipt.pc),
1933
- is: bn4(receipt.is)
2332
+ val: bn5(receipt.val),
2333
+ pc: bn5(receipt.pc),
2334
+ is: bn5(receipt.is)
1934
2335
  };
1935
2336
  return returnReceipt;
1936
2337
  }
@@ -1938,12 +2339,12 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1938
2339
  const returnDataReceipt = {
1939
2340
  type: ReceiptType.ReturnData,
1940
2341
  id: hexOrZero(receipt.id || receipt.contractId),
1941
- ptr: bn4(receipt.ptr),
1942
- len: bn4(receipt.len),
2342
+ ptr: bn5(receipt.ptr),
2343
+ len: bn5(receipt.len),
1943
2344
  digest: hexOrZero(receipt.digest),
1944
- pc: bn4(receipt.pc),
2345
+ pc: bn5(receipt.pc),
1945
2346
  data: hexOrZero(receipt.data),
1946
- is: bn4(receipt.is)
2347
+ is: bn5(receipt.is)
1947
2348
  };
1948
2349
  return returnDataReceipt;
1949
2350
  }
@@ -1951,9 +2352,9 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1951
2352
  const panicReceipt = {
1952
2353
  type: ReceiptType.Panic,
1953
2354
  id: hexOrZero(receipt.id),
1954
- reason: bn4(receipt.reason),
1955
- pc: bn4(receipt.pc),
1956
- is: bn4(receipt.is),
2355
+ reason: bn5(receipt.reason),
2356
+ pc: bn5(receipt.pc),
2357
+ is: bn5(receipt.is),
1957
2358
  contractId: hexOrZero(receipt.contractId)
1958
2359
  };
1959
2360
  return panicReceipt;
@@ -1962,17 +2363,17 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1962
2363
  const revertReceipt = {
1963
2364
  type: ReceiptType.Revert,
1964
2365
  id: hexOrZero(receipt.id || receipt.contractId),
1965
- val: bn4(receipt.ra),
1966
- pc: bn4(receipt.pc),
1967
- is: bn4(receipt.is)
2366
+ val: bn5(receipt.ra),
2367
+ pc: bn5(receipt.pc),
2368
+ is: bn5(receipt.is)
1968
2369
  };
1969
2370
  return revertReceipt;
1970
2371
  }
1971
2372
  case "LOG" /* Log */: {
1972
- const ra = bn4(receipt.ra);
1973
- const rb = bn4(receipt.rb);
1974
- const rc = bn4(receipt.rc);
1975
- const rd = bn4(receipt.rd);
2373
+ const ra = bn5(receipt.ra);
2374
+ const rb = bn5(receipt.rb);
2375
+ const rc = bn5(receipt.rc);
2376
+ const rd = bn5(receipt.rd);
1976
2377
  const logReceipt = {
1977
2378
  type: ReceiptType.Log,
1978
2379
  id: hexOrZero(receipt.id || receipt.contractId),
@@ -1980,25 +2381,25 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1980
2381
  rb,
1981
2382
  rc,
1982
2383
  rd,
1983
- pc: bn4(receipt.pc),
1984
- is: bn4(receipt.is)
2384
+ pc: bn5(receipt.pc),
2385
+ is: bn5(receipt.is)
1985
2386
  };
1986
2387
  return logReceipt;
1987
2388
  }
1988
2389
  case "LOG_DATA" /* LogData */: {
1989
- const ra = bn4(receipt.ra);
1990
- const rb = bn4(receipt.rb);
2390
+ const ra = bn5(receipt.ra);
2391
+ const rb = bn5(receipt.rb);
1991
2392
  const logDataReceipt = {
1992
2393
  type: ReceiptType.LogData,
1993
2394
  id: hexOrZero(receipt.id || receipt.contractId),
1994
2395
  ra,
1995
2396
  rb,
1996
- ptr: bn4(receipt.ptr),
1997
- len: bn4(receipt.len),
2397
+ ptr: bn5(receipt.ptr),
2398
+ len: bn5(receipt.len),
1998
2399
  digest: hexOrZero(receipt.digest),
1999
- pc: bn4(receipt.pc),
2400
+ pc: bn5(receipt.pc),
2000
2401
  data: hexOrZero(receipt.data),
2001
- is: bn4(receipt.is)
2402
+ is: bn5(receipt.is)
2002
2403
  };
2003
2404
  return logDataReceipt;
2004
2405
  }
@@ -2008,10 +2409,10 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
2008
2409
  type: ReceiptType.Transfer,
2009
2410
  id,
2010
2411
  to: hexOrZero(receipt.toAddress || receipt?.to),
2011
- amount: bn4(receipt.amount),
2412
+ amount: bn5(receipt.amount),
2012
2413
  assetId: hexOrZero(receipt.assetId),
2013
- pc: bn4(receipt.pc),
2014
- is: bn4(receipt.is)
2414
+ pc: bn5(receipt.pc),
2415
+ is: bn5(receipt.is)
2015
2416
  };
2016
2417
  return transferReceipt;
2017
2418
  }
@@ -2021,18 +2422,18 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
2021
2422
  type: ReceiptType.TransferOut,
2022
2423
  id,
2023
2424
  to: hexOrZero(receipt.toAddress || receipt.to),
2024
- amount: bn4(receipt.amount),
2425
+ amount: bn5(receipt.amount),
2025
2426
  assetId: hexOrZero(receipt.assetId),
2026
- pc: bn4(receipt.pc),
2027
- is: bn4(receipt.is)
2427
+ pc: bn5(receipt.pc),
2428
+ is: bn5(receipt.is)
2028
2429
  };
2029
2430
  return transferOutReceipt;
2030
2431
  }
2031
2432
  case "SCRIPT_RESULT" /* ScriptResult */: {
2032
2433
  const scriptResultReceipt = {
2033
2434
  type: ReceiptType.ScriptResult,
2034
- result: bn4(receipt.result),
2035
- gasUsed: bn4(receipt.gasUsed)
2435
+ result: bn5(receipt.result),
2436
+ gasUsed: bn5(receipt.gasUsed)
2036
2437
  };
2037
2438
  return scriptResultReceipt;
2038
2439
  }
@@ -2040,16 +2441,16 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
2040
2441
  const sender = hexOrZero(receipt.sender);
2041
2442
  const recipient = hexOrZero(receipt.recipient);
2042
2443
  const nonce = hexOrZero(receipt.nonce);
2043
- const amount = bn4(receipt.amount);
2444
+ const amount = bn5(receipt.amount);
2044
2445
  const data = receipt.data ? arrayify3(receipt.data) : Uint8Array.from([]);
2045
2446
  const digest = hexOrZero(receipt.digest);
2046
- const len = bn4(receipt.len).toNumber();
2447
+ const len = bn5(receipt.len).toNumber();
2047
2448
  const messageId = InputMessageCoder.getMessageId({
2048
2449
  sender,
2049
2450
  recipient,
2050
2451
  nonce,
2051
2452
  amount,
2052
- data: hexlify6(data)
2453
+ data: hexlify7(data)
2053
2454
  });
2054
2455
  const receiptMessageOut = {
2055
2456
  type: ReceiptType.MessageOut,
@@ -2073,9 +2474,9 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
2073
2474
  subId,
2074
2475
  contractId,
2075
2476
  assetId,
2076
- val: bn4(receipt.val),
2077
- pc: bn4(receipt.pc),
2078
- is: bn4(receipt.is)
2477
+ val: bn5(receipt.val),
2478
+ pc: bn5(receipt.pc),
2479
+ is: bn5(receipt.is)
2079
2480
  };
2080
2481
  return mintReceipt;
2081
2482
  }
@@ -2088,16 +2489,151 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
2088
2489
  subId,
2089
2490
  contractId,
2090
2491
  assetId,
2091
- val: bn4(receipt.val),
2092
- pc: bn4(receipt.pc),
2093
- is: bn4(receipt.is)
2492
+ val: bn5(receipt.val),
2493
+ pc: bn5(receipt.pc),
2494
+ is: bn5(receipt.is)
2094
2495
  };
2095
2496
  return burnReceipt;
2096
2497
  }
2097
2498
  default:
2098
- throw new FuelError6(ErrorCode5.INVALID_RECEIPT_TYPE, `Invalid receipt type: ${receiptType}.`);
2499
+ throw new FuelError7(ErrorCode6.INVALID_RECEIPT_TYPE, `Invalid receipt type: ${receiptType}.`);
2099
2500
  }
2100
2501
  }, "deserializeReceipt");
2502
+ var deserializeInput = /* @__PURE__ */ __name((input) => {
2503
+ let parsedInput;
2504
+ switch (input.type) {
2505
+ case "InputCoin":
2506
+ parsedInput = {
2507
+ type: InputType2.Coin,
2508
+ id: input.utxoId,
2509
+ amount: bn5(input.amount),
2510
+ assetId: input.assetId,
2511
+ owner: input.owner,
2512
+ txPointer: `0x${input.txPointer}`,
2513
+ witnessIndex: Number(input.coinWitnessIndex),
2514
+ predicate: input.predicate,
2515
+ predicateData: input.predicateData,
2516
+ predicateGasUsed: bn5(input.predicateGasUsed)
2517
+ };
2518
+ break;
2519
+ case "InputMessage":
2520
+ parsedInput = {
2521
+ type: InputType2.Message,
2522
+ nonce: input.nonce,
2523
+ amount: bn5(input.amount),
2524
+ recipient: input.recipient,
2525
+ sender: input.sender,
2526
+ data: input.data,
2527
+ witnessIndex: Number(input.messageWitnessIndex),
2528
+ predicate: input.predicate,
2529
+ predicateData: input.predicateData,
2530
+ predicateGasUsed: bn5(input.predicateGasUsed)
2531
+ };
2532
+ break;
2533
+ case "InputContract":
2534
+ parsedInput = {
2535
+ type: InputType2.Contract,
2536
+ contractId: input.contractId,
2537
+ txPointer: `0x${input.txPointer}`,
2538
+ txID: hexlify7(arrayify3(input.utxoId).slice(0, 32))
2539
+ };
2540
+ break;
2541
+ default:
2542
+ assertUnreachable(input);
2543
+ }
2544
+ return parsedInput;
2545
+ }, "deserializeInput");
2546
+ var deserializeOutput = /* @__PURE__ */ __name((output) => {
2547
+ let parsedOutput;
2548
+ switch (output.type) {
2549
+ case "CoinOutput":
2550
+ parsedOutput = {
2551
+ type: OutputType2.Coin,
2552
+ amount: bn5(output.amount),
2553
+ assetId: output.assetId,
2554
+ to: output.to
2555
+ };
2556
+ break;
2557
+ case "ContractOutput":
2558
+ parsedOutput = {
2559
+ type: OutputType2.Contract,
2560
+ inputIndex: Number(output.inputIndex)
2561
+ };
2562
+ break;
2563
+ case "ChangeOutput":
2564
+ parsedOutput = {
2565
+ type: OutputType2.Change,
2566
+ assetId: output.assetId,
2567
+ to: output.to
2568
+ };
2569
+ break;
2570
+ case "ContractCreated":
2571
+ parsedOutput = {
2572
+ type: OutputType2.ContractCreated,
2573
+ stateRoot: output.stateRoot,
2574
+ contractId: output.contract
2575
+ };
2576
+ break;
2577
+ case "VariableOutput":
2578
+ parsedOutput = {
2579
+ type: OutputType2.Variable,
2580
+ amount: bn5(output.amount),
2581
+ assetId: output.assetId,
2582
+ to: output.to
2583
+ };
2584
+ break;
2585
+ default:
2586
+ assertUnreachable(output);
2587
+ }
2588
+ return parsedOutput;
2589
+ }, "deserializeOutput");
2590
+ var deserializeProcessedTxOutput = /* @__PURE__ */ __name((output) => {
2591
+ let parsedOutput;
2592
+ switch (output.type) {
2593
+ case "CoinOutput":
2594
+ parsedOutput = {
2595
+ type: OutputType2.Coin,
2596
+ amount: bn5(output.amount),
2597
+ assetId: output.assetId,
2598
+ to: output.to
2599
+ };
2600
+ break;
2601
+ case "ContractOutput":
2602
+ parsedOutput = {
2603
+ type: OutputType2.Contract,
2604
+ inputIndex: Number(output.inputIndex),
2605
+ balanceRoot: output.balanceRoot,
2606
+ stateRoot: output.stateRoot
2607
+ };
2608
+ break;
2609
+ case "ChangeOutput":
2610
+ parsedOutput = {
2611
+ type: OutputType2.Change,
2612
+ assetId: output.assetId,
2613
+ to: output.to,
2614
+ amount: bn5(output.amount)
2615
+ };
2616
+ break;
2617
+ case "ContractCreated":
2618
+ parsedOutput = {
2619
+ type: OutputType2.ContractCreated,
2620
+ stateRoot: output.stateRoot,
2621
+ contractId: output.contract
2622
+ };
2623
+ break;
2624
+ case "VariableOutput":
2625
+ parsedOutput = {
2626
+ type: OutputType2.Variable,
2627
+ amount: bn5(output.amount),
2628
+ assetId: output.assetId,
2629
+ to: output.to
2630
+ };
2631
+ break;
2632
+ default:
2633
+ assertUnreachable(output);
2634
+ }
2635
+ return parsedOutput;
2636
+ }, "deserializeProcessedTxOutput");
2101
2637
 
2102
2638
  // src/providers/utils/receipts.ts
2103
2639
  var doesReceiptHaveMissingOutputVariables = /* @__PURE__ */ __name((receipt) => receipt.type === ReceiptType2.Revert && receipt.val.toString("hex") === FAILED_TRANSFER_TO_ADDRESS_SIGNAL, "doesReceiptHaveMissingOutputVariables");
@@ -2119,26 +2655,26 @@ var getReceiptsWithMissingData = /* @__PURE__ */ __name((receipts) => receipts.r
2119
2655
  ), "getReceiptsWithMissingData");
2120
2656
 
2121
2657
  // src/providers/utils/block-explorer.ts
2122
- import { ErrorCode as ErrorCode6, FuelError as FuelError7 } from "@fuel-ts/errors";
2658
+ import { ErrorCode as ErrorCode7, FuelError as FuelError8 } from "@fuel-ts/errors";
2123
2659
 
2124
2660
  // src/providers/utils/gas.ts
2125
- import { bn as bn5 } from "@fuel-ts/math";
2661
+ import { bn as bn6 } from "@fuel-ts/math";
2126
2662
  import { ReceiptType as ReceiptType3 } from "@fuel-ts/transactions";
2127
2663
  import { arrayify as arrayify4 } from "@fuel-ts/utils";
2128
2664
  var getGasUsedFromReceipts = /* @__PURE__ */ __name((receipts) => {
2129
2665
  const scriptResult = receipts.filter(
2130
2666
  (receipt) => receipt.type === ReceiptType3.ScriptResult
2131
2667
  );
2132
- const gasUsed = scriptResult.reduce((prev, receipt) => prev.add(receipt.gasUsed), bn5(0));
2668
+ const gasUsed = scriptResult.reduce((prev, receipt) => prev.add(receipt.gasUsed), bn6(0));
2133
2669
  return gasUsed;
2134
2670
  }, "getGasUsedFromReceipts");
2135
2671
  function resolveGasDependentCosts(byteSize, gasDependentCost) {
2136
- const base = bn5(gasDependentCost.base);
2137
- let dependentValue = bn5(0);
2672
+ const base = bn6(gasDependentCost.base);
2673
+ let dependentValue = bn6(0);
2138
2674
  if ("unitsPerGas" in gasDependentCost) {
2139
- dependentValue = bn5(byteSize).div(bn5(gasDependentCost.unitsPerGas));
2675
+ dependentValue = bn6(byteSize).div(bn6(gasDependentCost.unitsPerGas));
2140
2676
  } else {
2141
- dependentValue = bn5(byteSize).mul(bn5(gasDependentCost.gasPerUnit));
2677
+ dependentValue = bn6(byteSize).mul(bn6(gasDependentCost.gasPerUnit));
2142
2678
  }
2143
2679
  return base.add(dependentValue);
2144
2680
  }
@@ -2162,18 +2698,18 @@ function gasUsedByInputs(inputs, txBytesSize, gasCosts) {
2162
2698
  const totalGas = chargeableInputs.reduce((total, input) => {
2163
2699
  if ("predicate" in input && input.predicate && input.predicate !== "0x") {
2164
2700
  return total.add(
2165
- vmInitializationCost.add(resolveGasDependentCosts(arrayify4(input.predicate).length, gasCosts.contractRoot)).add(bn5(input.predicateGasUsed))
2701
+ vmInitializationCost.add(resolveGasDependentCosts(arrayify4(input.predicate).length, gasCosts.contractRoot)).add(bn6(input.predicateGasUsed))
2166
2702
  );
2167
2703
  }
2168
2704
  return total.add(gasCosts.ecr1);
2169
- }, bn5(0));
2705
+ }, bn6(0));
2170
2706
  return totalGas;
2171
2707
  }
2172
2708
  __name(gasUsedByInputs, "gasUsedByInputs");
2173
2709
  function getMinGas(params) {
2174
2710
  const { gasCosts, gasPerByte, inputs, metadataGas, txBytesSize } = params;
2175
2711
  const vmInitGas = resolveGasDependentCosts(txBytesSize, gasCosts.vmInitialization);
2176
- const bytesGas = bn5(txBytesSize).mul(gasPerByte);
2712
+ const bytesGas = bn6(txBytesSize).mul(gasPerByte);
2177
2713
  const inputsGas = gasUsedByInputs(inputs, txBytesSize, gasCosts);
2178
2714
  const minGas = vmInitGas.add(bytesGas).add(inputsGas).add(metadataGas).maxU64();
2179
2715
  return minGas;
@@ -2185,12 +2721,12 @@ function getMaxGas(params) {
2185
2721
  witnessesLength,
2186
2722
  witnessLimit,
2187
2723
  minGas,
2188
- gasLimit = bn5(0),
2724
+ gasLimit = bn6(0),
2189
2725
  maxGasPerTx
2190
2726
  } = params;
2191
- let remainingAllowedWitnessGas = bn5(0);
2727
+ let remainingAllowedWitnessGas = bn6(0);
2192
2728
  if (witnessLimit?.gt(0) && witnessLimit.gte(witnessesLength)) {
2193
- remainingAllowedWitnessGas = bn5(witnessLimit).sub(witnessesLength).mul(gasPerByte);
2729
+ remainingAllowedWitnessGas = bn6(witnessLimit).sub(witnessesLength).mul(gasPerByte);
2194
2730
  }
2195
2731
  const maxGas = remainingAllowedWitnessGas.add(minGas).add(gasLimit);
2196
2732
  return maxGas.gte(maxGasPerTx) ? maxGasPerTx : maxGas;
@@ -2205,7 +2741,7 @@ function calculateMetadataGasForTxCreate({
2205
2741
  const contractRootGas = resolveGasDependentCosts(contractBytesSize, gasCosts.contractRoot);
2206
2742
  const stateRootGas = resolveGasDependentCosts(stateRootSize, gasCosts.stateRoot);
2207
2743
  const txIdGas = resolveGasDependentCosts(txBytesSize, gasCosts.s256);
2208
- const contractIdInputSize = bn5(4 + 32 + 32 + 32);
2744
+ const contractIdInputSize = bn6(4 + 32 + 32 + 32);
2209
2745
  const contractIdGas = resolveGasDependentCosts(contractIdInputSize, gasCosts.s256);
2210
2746
  const metadataGas = contractRootGas.add(stateRootGas).add(txIdGas).add(contractIdGas);
2211
2747
  return metadataGas.maxU64();
@@ -2260,23 +2796,23 @@ function calculateMinGasForTxUpload({
2260
2796
  baseMinGas,
2261
2797
  subsectionSize
2262
2798
  }) {
2263
- const additionalStoragePerByte = bn5(gasCosts.newStoragePerByte).mul(subsectionSize);
2264
- return bn5(baseMinGas).add(additionalStoragePerByte);
2799
+ const additionalStoragePerByte = bn6(gasCosts.newStoragePerByte).mul(subsectionSize);
2800
+ return bn6(baseMinGas).add(additionalStoragePerByte);
2265
2801
  }
2266
2802
  __name(calculateMinGasForTxUpload, "calculateMinGasForTxUpload");
2267
2803
  var calculateGasFee = /* @__PURE__ */ __name((params) => {
2268
2804
  const { gas, gasPrice, priceFactor, tip } = params;
2269
- return gas.mul(gasPrice).div(priceFactor).add(bn5(tip));
2805
+ return gas.mul(gasPrice).div(priceFactor).add(bn6(tip));
2270
2806
  }, "calculateGasFee");
2271
2807
 
2272
2808
  // src/providers/utils/json.ts
2273
- import { hexlify as hexlify7 } from "@fuel-ts/utils";
2809
+ import { hexlify as hexlify8 } from "@fuel-ts/utils";
2274
2810
  import { clone } from "ramda";
2275
2811
  function normalize(object) {
2276
2812
  Object.keys(object).forEach((key) => {
2277
2813
  switch (object[key]?.constructor.name) {
2278
2814
  case "Uint8Array":
2279
- object[key] = hexlify7(object[key]);
2815
+ object[key] = hexlify8(object[key]);
2280
2816
  break;
2281
2817
  case "Array":
2282
2818
  object[key] = normalize(object[key]);
@@ -2303,8 +2839,8 @@ function normalizeJSON(root) {
2303
2839
  __name(normalizeJSON, "normalizeJSON");
2304
2840
 
2305
2841
  // src/providers/utils/extract-tx-error.ts
2306
- import { ErrorCode as ErrorCode7, FuelError as FuelError8 } from "@fuel-ts/errors";
2307
- import { bn as bn6 } from "@fuel-ts/math";
2842
+ import { ErrorCode as ErrorCode8, FuelError as FuelError9 } from "@fuel-ts/errors";
2843
+ import { bn as bn7 } from "@fuel-ts/math";
2308
2844
  import { ReceiptType as ReceiptType4 } from "@fuel-ts/transactions";
2309
2845
  import {
2310
2846
  FAILED_REQUIRE_SIGNAL,
@@ -2324,7 +2860,7 @@ You can read more about this error at:
2324
2860
 
2325
2861
  ${PANIC_DOC_URL}#variant.${statusReason}`;
2326
2862
  }
2327
- return new FuelError8(ErrorCode7.SCRIPT_REVERTED, errorMessage, {
2863
+ return new FuelError9(ErrorCode8.SCRIPT_REVERTED, errorMessage, {
2328
2864
  ...metadata,
2329
2865
  reason: statusReason
2330
2866
  });
@@ -2335,7 +2871,7 @@ var assembleRevertError = /* @__PURE__ */ __name((receipts, logs, metadata) => {
2335
2871
  const revertReceipt = receipts.find(({ type }) => type === ReceiptType4.Revert);
2336
2872
  let reason = "";
2337
2873
  if (revertReceipt) {
2338
- const reasonHex = bn6(revertReceipt.val).toHex();
2874
+ const reasonHex = bn7(revertReceipt.val).toHex();
2339
2875
  const lastLog = logs[logs.length - 1];
2340
2876
  const lastButOneLog = logs[logs.length - 2];
2341
2877
  switch (reasonHex) {
@@ -2365,8 +2901,8 @@ var assembleRevertError = /* @__PURE__ */ __name((receipts, logs, metadata) => {
2365
2901
  errorMessage = `The transaction reverted because it's missing an "OutputVariable".`;
2366
2902
  break;
2367
2903
  default:
2368
- throw new FuelError8(
2369
- ErrorCode7.UNKNOWN,
2904
+ throw new FuelError9(
2905
+ ErrorCode8.UNKNOWN,
2370
2906
  `The transaction reverted with an unknown reason: ${revertReceipt.val}`,
2371
2907
  {
2372
2908
  ...metadata,
@@ -2375,7 +2911,7 @@ var assembleRevertError = /* @__PURE__ */ __name((receipts, logs, metadata) => {
2375
2911
  );
2376
2912
  }
2377
2913
  }
2378
- return new FuelError8(ErrorCode7.SCRIPT_REVERTED, errorMessage, {
2914
+ return new FuelError9(ErrorCode8.SCRIPT_REVERTED, errorMessage, {
2379
2915
  ...metadata,
2380
2916
  reason
2381
2917
  });
@@ -2398,6 +2934,21 @@ var extractTxError = /* @__PURE__ */ __name((params) => {
2398
2934
  return assembleRevertError(receipts, logs, metadata);
2399
2935
  }, "extractTxError");
2400
2936
 
2937
+ // src/providers/utils/merge-quantities.ts
2938
+ var mergeQuantities = /* @__PURE__ */ __name((...coinQuantities) => {
2939
+ const resultMap = {};
2940
+ function addToMap({ amount, assetId }) {
2941
+ if (resultMap[assetId]) {
2942
+ resultMap[assetId] = resultMap[assetId].add(amount);
2943
+ } else {
2944
+ resultMap[assetId] = amount;
2945
+ }
2946
+ }
2947
+ __name(addToMap, "addToMap");
2948
+ coinQuantities.forEach((arr) => arr.forEach(addToMap));
2949
+ return Object.entries(resultMap).map(([assetId, amount]) => ({ assetId, amount }));
2950
+ }, "mergeQuantities");
2951
+
2401
2952
  // src/providers/transaction-request/errors.ts
2402
2953
  var NoWitnessAtIndexError = class extends Error {
2403
2954
  constructor(index) {
@@ -2412,18 +2963,18 @@ var NoWitnessAtIndexError = class extends Error {
2412
2963
  };
2413
2964
 
2414
2965
  // src/providers/transaction-request/helpers.ts
2415
- import { ErrorCode as ErrorCode8, FuelError as FuelError9 } from "@fuel-ts/errors";
2416
- import { bn as bn7 } from "@fuel-ts/math";
2417
- import { InputType as InputType2, OutputType as OutputType2 } from "@fuel-ts/transactions";
2418
- import { hexlify as hexlify8 } from "@fuel-ts/utils";
2419
- var isRequestInputCoin = /* @__PURE__ */ __name((input) => input.type === InputType2.Coin, "isRequestInputCoin");
2420
- var isRequestInputMessage = /* @__PURE__ */ __name((input) => input.type === InputType2.Message, "isRequestInputMessage");
2421
- var isRequestInputMessageWithoutData = /* @__PURE__ */ __name((input) => input.type === InputType2.Message && bn7(input.data).isZero(), "isRequestInputMessageWithoutData");
2966
+ import { ErrorCode as ErrorCode9, FuelError as FuelError10 } from "@fuel-ts/errors";
2967
+ import { bn as bn8 } from "@fuel-ts/math";
2968
+ import { InputType as InputType3, OutputType as OutputType3 } from "@fuel-ts/transactions";
2969
+ import { hexlify as hexlify9 } from "@fuel-ts/utils";
2970
+ var isRequestInputCoin = /* @__PURE__ */ __name((input) => input.type === InputType3.Coin, "isRequestInputCoin");
2971
+ var isRequestInputMessage = /* @__PURE__ */ __name((input) => input.type === InputType3.Message, "isRequestInputMessage");
2972
+ var isRequestInputMessageWithoutData = /* @__PURE__ */ __name((input) => input.type === InputType3.Message && bn8(input.data).isZero(), "isRequestInputMessageWithoutData");
2422
2973
  var isRequestInputCoinOrMessage = /* @__PURE__ */ __name((input) => isRequestInputCoin(input) || isRequestInputMessage(input), "isRequestInputCoinOrMessage");
2423
2974
  var isRequestInputResource = /* @__PURE__ */ __name((input) => isRequestInputCoin(input) || isRequestInputMessageWithoutData(input), "isRequestInputResource");
2424
2975
  var getRequestInputResourceOwner = /* @__PURE__ */ __name((input) => isRequestInputCoin(input) ? input.owner : input.recipient, "getRequestInputResourceOwner");
2425
2976
  var isRequestInputResourceFromOwner = /* @__PURE__ */ __name((input, owner) => getRequestInputResourceOwner(input) === owner.toB256(), "isRequestInputResourceFromOwner");
2426
- var isPredicate = /* @__PURE__ */ __name((input) => isRequestInputCoinOrMessage(input) && !!input.predicate && hexlify8(input.predicate) !== "0x", "isPredicate");
2977
+ var isPredicate = /* @__PURE__ */ __name((input) => isRequestInputCoinOrMessage(input) && !!input.predicate && hexlify9(input.predicate) !== "0x", "isPredicate");
2427
2978
  var getAssetAmountInRequestInputs = /* @__PURE__ */ __name((inputs, assetId, baseAsset) => inputs.filter(isRequestInputResource).reduce((acc, input) => {
2428
2979
  if (isRequestInputCoin(input) && input.assetId === assetId) {
2429
2980
  return acc.add(input.amount);
@@ -2432,7 +2983,7 @@ var getAssetAmountInRequestInputs = /* @__PURE__ */ __name((inputs, assetId, bas
2432
2983
  return acc.add(input.amount);
2433
2984
  }
2434
2985
  return acc;
2435
- }, bn7(0)), "getAssetAmountInRequestInputs");
2986
+ }, bn8(0)), "getAssetAmountInRequestInputs");
2436
2987
  var cacheRequestInputsResourcesFromOwner = /* @__PURE__ */ __name((inputs, owner) => inputs.reduce(
2437
2988
  (acc, input) => {
2438
2989
  if (isRequestInputCoin(input) && input.owner === owner.toB256()) {
@@ -2450,11 +3001,11 @@ var cacheRequestInputsResourcesFromOwner = /* @__PURE__ */ __name((inputs, owner
2450
3001
  var getBurnableAssetCount = /* @__PURE__ */ __name((baseAssetId, transactionRequest) => {
2451
3002
  const { inputs, outputs } = transactionRequest;
2452
3003
  const coinInputs = new Set(inputs.filter(isRequestInputCoin).map((input) => input.assetId));
2453
- if (inputs.some((i) => isRequestInputMessage(i) && bn7(i.amount).gt(0))) {
3004
+ if (inputs.some((i) => isRequestInputMessage(i) && bn8(i.amount).gt(0))) {
2454
3005
  coinInputs.add(baseAssetId);
2455
3006
  }
2456
3007
  const changeOutputs = new Set(
2457
- outputs.filter((output) => output.type === OutputType2.Change).map((output) => output.assetId)
3008
+ outputs.filter((output) => output.type === OutputType3.Change).map((output) => output.assetId)
2458
3009
  );
2459
3010
  const difference = new Set([...coinInputs].filter((x) => !changeOutputs.has(x)));
2460
3011
  return difference.size;
@@ -2471,15 +3022,15 @@ var validateTransactionForAssetBurn = /* @__PURE__ */ __name((baseAssetId, trans
2471
3022
  "Add the relevant change outputs to the transaction to avoid burning assets.",
2472
3023
  "Or enable asset burn, upon sending the transaction."
2473
3024
  ].join("\n");
2474
- throw new FuelError9(ErrorCode8.ASSET_BURN_DETECTED, message);
3025
+ throw new FuelError10(ErrorCode9.ASSET_BURN_DETECTED, message);
2475
3026
  }, "validateTransactionForAssetBurn");
2476
3027
 
2477
3028
  // src/providers/transaction-request/witness.ts
2478
- import { arrayify as arrayify5, hexlify as hexlify9 } from "@fuel-ts/utils";
3029
+ import { arrayify as arrayify5, hexlify as hexlify10 } from "@fuel-ts/utils";
2479
3030
  var witnessify = /* @__PURE__ */ __name((value) => {
2480
3031
  const data = arrayify5(value);
2481
3032
  return {
2482
- data: hexlify9(data),
3033
+ data: hexlify10(data),
2483
3034
  dataLength: data.length
2484
3035
  };
2485
3036
  }, "witnessify");
@@ -2526,11 +3077,11 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2526
3077
  outputs,
2527
3078
  witnesses
2528
3079
  } = {}) {
2529
- this.tip = tip ? bn8(tip) : void 0;
3080
+ this.tip = tip ? bn9(tip) : void 0;
2530
3081
  this.maturity = maturity && maturity > 0 ? maturity : void 0;
2531
3082
  this.expiration = expiration && expiration > 0 ? expiration : void 0;
2532
- this.witnessLimit = isDefined(witnessLimit) ? bn8(witnessLimit) : void 0;
2533
- this.maxFee = bn8(maxFee);
3083
+ this.witnessLimit = isDefined2(witnessLimit) ? bn9(witnessLimit) : void 0;
3084
+ this.maxFee = bn9(maxFee);
2534
3085
  this.inputs = inputs ?? [];
2535
3086
  this.outputs = outputs ?? [];
2536
3087
  this.witnesses = witnesses ?? [];
@@ -2539,13 +3090,13 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2539
3090
  let policyTypes = 0;
2540
3091
  const policies = [];
2541
3092
  const { tip, witnessLimit, maturity, expiration } = req;
2542
- if (bn8(tip).gt(0)) {
3093
+ if (bn9(tip).gt(0)) {
2543
3094
  policyTypes += PolicyType.Tip;
2544
- policies.push({ data: bn8(tip), type: PolicyType.Tip });
3095
+ policies.push({ data: bn9(tip), type: PolicyType.Tip });
2545
3096
  }
2546
- if (isDefined(witnessLimit) && bn8(witnessLimit).gte(0)) {
3097
+ if (isDefined2(witnessLimit) && bn9(witnessLimit).gte(0)) {
2547
3098
  policyTypes += PolicyType.WitnessLimit;
2548
- policies.push({ data: bn8(witnessLimit), type: PolicyType.WitnessLimit });
3099
+ policies.push({ data: bn9(witnessLimit), type: PolicyType.WitnessLimit });
2549
3100
  }
2550
3101
  if (maturity && maturity > 0) {
2551
3102
  policyTypes += PolicyType.Maturity;
@@ -2679,7 +3230,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2679
3230
  */
2680
3231
  getCoinInputs() {
2681
3232
  return this.inputs.filter(
2682
- (input) => input.type === InputType3.Coin
3233
+ (input) => input.type === InputType4.Coin
2683
3234
  );
2684
3235
  }
2685
3236
  /**
@@ -2689,7 +3240,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2689
3240
  */
2690
3241
  getCoinOutputs() {
2691
3242
  return this.outputs.filter(
2692
- (output) => output.type === OutputType3.Coin
3243
+ (output) => output.type === OutputType4.Coin
2693
3244
  );
2694
3245
  }
2695
3246
  /**
@@ -2699,7 +3250,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2699
3250
  */
2700
3251
  getChangeOutputs() {
2701
3252
  return this.outputs.filter(
2702
- (output) => output.type === OutputType3.Change
3253
+ (output) => output.type === OutputType4.Change
2703
3254
  );
2704
3255
  }
2705
3256
  /**
@@ -2711,10 +3262,10 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2711
3262
  const ownerAddress = addressify(owner);
2712
3263
  const found = this.inputs.find((input) => {
2713
3264
  switch (input.type) {
2714
- case InputType3.Coin:
2715
- return hexlify10(input.owner) === ownerAddress.toB256();
2716
- case InputType3.Message:
2717
- return hexlify10(input.recipient) === ownerAddress.toB256();
3265
+ case InputType4.Coin:
3266
+ return hexlify11(input.owner) === ownerAddress.toB256();
3267
+ case InputType4.Message:
3268
+ return hexlify11(input.recipient) === ownerAddress.toB256();
2718
3269
  default:
2719
3270
  return false;
2720
3271
  }
@@ -2740,7 +3291,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2740
3291
  }
2741
3292
  const input = {
2742
3293
  id,
2743
- type: InputType3.Coin,
3294
+ type: InputType4.Coin,
2744
3295
  owner: owner.toB256(),
2745
3296
  amount,
2746
3297
  assetId,
@@ -2771,7 +3322,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2771
3322
  }
2772
3323
  const input = {
2773
3324
  nonce,
2774
- type: InputType3.Message,
3325
+ type: InputType4.Message,
2775
3326
  sender: sender.toB256(),
2776
3327
  recipient: recipient.toB256(),
2777
3328
  data: isMessageCoin(message) ? "0x" : message.data,
@@ -2820,7 +3371,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2820
3371
  */
2821
3372
  addCoinOutput(to, amount, assetId) {
2822
3373
  this.pushOutput({
2823
- type: OutputType3.Coin,
3374
+ type: OutputType4.Coin,
2824
3375
  to: addressify(to).toB256(),
2825
3376
  amount,
2826
3377
  assetId
@@ -2836,7 +3387,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2836
3387
  addCoinOutputs(to, quantities) {
2837
3388
  quantities.map(coinQuantityfy).forEach((quantity) => {
2838
3389
  this.pushOutput({
2839
- type: OutputType3.Coin,
3390
+ type: OutputType4.Coin,
2840
3391
  to: addressify(to).toB256(),
2841
3392
  amount: quantity.amount,
2842
3393
  assetId: quantity.assetId
@@ -2852,11 +3403,11 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2852
3403
  */
2853
3404
  addChangeOutput(to, assetId) {
2854
3405
  const changeOutput = this.getChangeOutputs().find(
2855
- (output) => hexlify10(output.assetId) === assetId
3406
+ (output) => hexlify11(output.assetId) === assetId
2856
3407
  );
2857
3408
  if (!changeOutput) {
2858
3409
  this.pushOutput({
2859
- type: OutputType3.Change,
3410
+ type: OutputType4.Change,
2860
3411
  to: addressify(to).toB256(),
2861
3412
  assetId
2862
3413
  });
@@ -2872,7 +3423,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2872
3423
  * @hidden
2873
3424
  */
2874
3425
  metadataGas(_gasCosts) {
2875
- throw new FuelError10(FuelError10.CODES.NOT_IMPLEMENTED, "Not implemented");
3426
+ throw new FuelError11(FuelError11.CODES.NOT_IMPLEMENTED, "Not implemented");
2876
3427
  }
2877
3428
  /**
2878
3429
  * @hidden
@@ -2929,25 +3480,25 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2929
3480
  const assetInput = findAssetInput(assetId);
2930
3481
  let usedQuantity = quantity;
2931
3482
  if (assetId === baseAssetId) {
2932
- usedQuantity = bn8("1000000000000000000");
3483
+ usedQuantity = bn9("1000000000000000000");
2933
3484
  }
2934
3485
  if (assetInput && "assetId" in assetInput) {
2935
- assetInput.id = hexlify10(randomBytes3(UTXO_ID_LEN2));
3486
+ assetInput.id = hexlify11(randomBytes3(UTXO_ID_LEN2));
2936
3487
  assetInput.amount = usedQuantity;
2937
3488
  } else {
2938
3489
  this.addResources([
2939
3490
  {
2940
- id: hexlify10(randomBytes3(UTXO_ID_LEN2)),
3491
+ id: hexlify11(randomBytes3(UTXO_ID_LEN2)),
2941
3492
  amount: usedQuantity,
2942
3493
  assetId,
2943
3494
  owner: resourcesOwner || Address2.fromRandom(),
2944
- blockCreated: bn8(1),
2945
- txCreatedIdx: bn8(1)
3495
+ blockCreated: bn9(1),
3496
+ txCreatedIdx: bn9(1)
2946
3497
  }
2947
3498
  ]);
2948
3499
  }
2949
3500
  }, "updateAssetInput");
2950
- updateAssetInput(baseAssetId, bn8(1e11));
3501
+ updateAssetInput(baseAssetId, bn9(1e11));
2951
3502
  quantities.forEach((q) => updateAssetInput(q.assetId, q.amount));
2952
3503
  return this;
2953
3504
  }
@@ -2959,7 +3510,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2959
3510
  */
2960
3511
  getCoinOutputsQuantities() {
2961
3512
  const coinsQuantities = this.getCoinOutputs().map(({ amount, assetId }) => ({
2962
- amount: bn8(amount),
3513
+ amount: bn9(amount),
2963
3514
  assetId: assetId.toString()
2964
3515
  }));
2965
3516
  return coinsQuantities;
@@ -2991,7 +3542,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2991
3542
  const correspondingInput = inputsToExtractGasUsed.find(
2992
3543
  (x) => isRequestInputResourceFromOwner(x, new Address2(String(owner)))
2993
3544
  );
2994
- if (correspondingInput && "predicateGasUsed" in correspondingInput && bn8(correspondingInput.predicateGasUsed).gt(0)) {
3545
+ if (correspondingInput && "predicateGasUsed" in correspondingInput && bn9(correspondingInput.predicateGasUsed).gt(0)) {
2995
3546
  i.predicateGasUsed = correspondingInput.predicateGasUsed;
2996
3547
  }
2997
3548
  });
@@ -3022,34 +3573,34 @@ import { clone as clone3 } from "ramda";
3022
3573
  // src/providers/transaction-request/hash-transaction.ts
3023
3574
  import { ZeroBytes32 as ZeroBytes325 } from "@fuel-ts/address/configs";
3024
3575
  import { uint64ToBytesBE, sha256 } from "@fuel-ts/hasher";
3025
- import { bn as bn9 } from "@fuel-ts/math";
3026
- import { TransactionType as TransactionType2, InputType as InputType4, OutputType as OutputType4, TransactionCoder as TransactionCoder2 } from "@fuel-ts/transactions";
3576
+ import { bn as bn10 } from "@fuel-ts/math";
3577
+ import { TransactionType as TransactionType3, InputType as InputType5, OutputType as OutputType5, TransactionCoder as TransactionCoder2 } from "@fuel-ts/transactions";
3027
3578
  import { concat as concat3 } from "@fuel-ts/utils";
3028
3579
  import { clone as clone2 } from "ramda";
3029
3580
  function hashTransaction(transactionRequest, chainId) {
3030
3581
  const transaction = transactionRequest.toTransaction();
3031
- if (transaction.type === TransactionType2.Script) {
3582
+ if (transaction.type === TransactionType3.Script) {
3032
3583
  transaction.receiptsRoot = ZeroBytes325;
3033
3584
  }
3034
3585
  transaction.inputs = transaction.inputs.map((input) => {
3035
3586
  const inputClone = clone2(input);
3036
3587
  switch (inputClone.type) {
3037
3588
  // Zero out on signing: txPointer, predicateGasUsed
3038
- case InputType4.Coin: {
3589
+ case InputType5.Coin: {
3039
3590
  inputClone.txPointer = {
3040
3591
  blockHeight: 0,
3041
3592
  txIndex: 0
3042
3593
  };
3043
- inputClone.predicateGasUsed = bn9(0);
3594
+ inputClone.predicateGasUsed = bn10(0);
3044
3595
  return inputClone;
3045
3596
  }
3046
3597
  // Zero out on signing: predicateGasUsed
3047
- case InputType4.Message: {
3048
- inputClone.predicateGasUsed = bn9(0);
3598
+ case InputType5.Message: {
3599
+ inputClone.predicateGasUsed = bn10(0);
3049
3600
  return inputClone;
3050
3601
  }
3051
3602
  // Zero out on signing: txID, outputIndex, balanceRoot, stateRoot, and txPointer
3052
- case InputType4.Contract: {
3603
+ case InputType5.Contract: {
3053
3604
  inputClone.txPointer = {
3054
3605
  blockHeight: 0,
3055
3606
  txIndex: 0
@@ -3068,20 +3619,20 @@ function hashTransaction(transactionRequest, chainId) {
3068
3619
  const outputClone = clone2(output);
3069
3620
  switch (outputClone.type) {
3070
3621
  // Zero out on signing: balanceRoot, stateRoot
3071
- case OutputType4.Contract: {
3622
+ case OutputType5.Contract: {
3072
3623
  outputClone.balanceRoot = ZeroBytes325;
3073
3624
  outputClone.stateRoot = ZeroBytes325;
3074
3625
  return outputClone;
3075
3626
  }
3076
3627
  // Zero out on signing: amount
3077
- case OutputType4.Change: {
3078
- outputClone.amount = bn9(0);
3628
+ case OutputType5.Change: {
3629
+ outputClone.amount = bn10(0);
3079
3630
  return outputClone;
3080
3631
  }
3081
3632
  // Zero out on signing: amount, to and assetId
3082
- case OutputType4.Variable: {
3633
+ case OutputType5.Variable: {
3083
3634
  outputClone.to = ZeroBytes325;
3084
- outputClone.amount = bn9(0);
3635
+ outputClone.amount = bn10(0);
3085
3636
  outputClone.assetId = ZeroBytes325;
3086
3637
  return outputClone;
3087
3638
  }
@@ -3106,7 +3657,7 @@ var BlobTransactionRequest = class extends BaseTransactionRequest {
3106
3657
  return new this(clone3(obj));
3107
3658
  }
3108
3659
  /** Type of the transaction */
3109
- type = TransactionType.Blob;
3660
+ type = TransactionType2.Blob;
3110
3661
  /** Blob ID */
3111
3662
  blobId;
3112
3663
  /** Witness index of the bytecode to create */
@@ -3130,7 +3681,7 @@ var BlobTransactionRequest = class extends BaseTransactionRequest {
3130
3681
  const baseTransaction = this.getBaseTransaction();
3131
3682
  const { witnessIndex, blobId } = this;
3132
3683
  return {
3133
- type: TransactionType.Blob,
3684
+ type: TransactionType2.Blob,
3134
3685
  ...baseTransaction,
3135
3686
  blobId,
3136
3687
  witnessIndex
@@ -3163,13 +3714,13 @@ var BlobTransactionRequest = class extends BaseTransactionRequest {
3163
3714
 
3164
3715
  // src/providers/transaction-request/create-transaction-request.ts
3165
3716
  import { ZeroBytes32 as ZeroBytes326 } from "@fuel-ts/address/configs";
3166
- import { bn as bn10 } from "@fuel-ts/math";
3167
- import { TransactionType as TransactionType3, OutputType as OutputType5 } from "@fuel-ts/transactions";
3168
- import { arrayify as arrayify7, hexlify as hexlify12 } from "@fuel-ts/utils";
3717
+ import { bn as bn11 } from "@fuel-ts/math";
3718
+ import { TransactionType as TransactionType4, OutputType as OutputType6 } from "@fuel-ts/transactions";
3719
+ import { arrayify as arrayify7, hexlify as hexlify13 } from "@fuel-ts/utils";
3169
3720
  import { clone as clone4 } from "ramda";
3170
3721
 
3171
3722
  // src/providers/transaction-request/storage-slot.ts
3172
- import { arrayify as arrayify6, hexlify as hexlify11 } from "@fuel-ts/utils";
3723
+ import { arrayify as arrayify6, hexlify as hexlify12 } from "@fuel-ts/utils";
3173
3724
  var getStorageValue = /* @__PURE__ */ __name((value) => {
3174
3725
  const v = new Uint8Array(32);
3175
3726
  v.set(arrayify6(value));
@@ -3186,8 +3737,8 @@ var storageSlotify = /* @__PURE__ */ __name((storageSlot) => {
3186
3737
  value = storageSlot.value;
3187
3738
  }
3188
3739
  return {
3189
- key: hexlify11(key),
3190
- value: hexlify11(getStorageValue(value))
3740
+ key: hexlify12(key),
3741
+ value: hexlify12(getStorageValue(value))
3191
3742
  };
3192
3743
  }, "storageSlotify");
3193
3744
 
@@ -3200,7 +3751,7 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3200
3751
  return new this(clone4(obj));
3201
3752
  }
3202
3753
  /** Type of the transaction */
3203
- type = TransactionType3.Create;
3754
+ type = TransactionType4.Create;
3204
3755
  /** Witness index of contract bytecode to create */
3205
3756
  bytecodeWitnessIndex;
3206
3757
  /** Salt */
@@ -3215,7 +3766,7 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3215
3766
  constructor({ bytecodeWitnessIndex, salt, storageSlots, ...rest }) {
3216
3767
  super(rest);
3217
3768
  this.bytecodeWitnessIndex = bytecodeWitnessIndex ?? 0;
3218
- this.salt = hexlify12(salt ?? ZeroBytes326);
3769
+ this.salt = hexlify13(salt ?? ZeroBytes326);
3219
3770
  this.storageSlots = [...storageSlots ?? []];
3220
3771
  }
3221
3772
  /**
@@ -3228,11 +3779,11 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3228
3779
  const bytecodeWitnessIndex = this.bytecodeWitnessIndex;
3229
3780
  const storageSlots = this.storageSlots?.map(storageSlotify) ?? [];
3230
3781
  return {
3231
- type: TransactionType3.Create,
3782
+ type: TransactionType4.Create,
3232
3783
  ...baseTransaction,
3233
3784
  bytecodeWitnessIndex,
3234
- storageSlotsCount: bn10(storageSlots.length),
3235
- salt: this.salt ? hexlify12(this.salt) : ZeroBytes326,
3785
+ storageSlotsCount: bn11(storageSlots.length),
3786
+ salt: this.salt ? hexlify13(this.salt) : ZeroBytes326,
3236
3787
  storageSlots
3237
3788
  };
3238
3789
  }
@@ -3243,7 +3794,7 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3243
3794
  */
3244
3795
  getContractCreatedOutputs() {
3245
3796
  return this.outputs.filter(
3246
- (output) => output.type === OutputType5.ContractCreated
3797
+ (output) => output.type === OutputType6.ContractCreated
3247
3798
  );
3248
3799
  }
3249
3800
  /**
@@ -3264,14 +3815,14 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3264
3815
  */
3265
3816
  addContractCreatedOutput(contractId, stateRoot) {
3266
3817
  this.pushOutput({
3267
- type: OutputType5.ContractCreated,
3818
+ type: OutputType6.ContractCreated,
3268
3819
  contractId,
3269
3820
  stateRoot
3270
3821
  });
3271
3822
  }
3272
3823
  metadataGas(gasCosts) {
3273
3824
  return calculateMetadataGasForTxCreate({
3274
- contractBytesSize: bn10(arrayify7(this.witnesses[this.bytecodeWitnessIndex] || "0x").length),
3825
+ contractBytesSize: bn11(arrayify7(this.witnesses[this.bytecodeWitnessIndex] || "0x").length),
3275
3826
  gasCosts,
3276
3827
  stateRootSize: this.storageSlots.length,
3277
3828
  txBytesSize: this.byteSize()
@@ -3283,9 +3834,9 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3283
3834
  import { Interface } from "@fuel-ts/abi-coder";
3284
3835
  import { addressify as addressify2 } from "@fuel-ts/address";
3285
3836
  import { ZeroBytes32 as ZeroBytes327 } from "@fuel-ts/address/configs";
3286
- import { bn as bn11 } from "@fuel-ts/math";
3287
- import { InputType as InputType5, OutputType as OutputType6, TransactionType as TransactionType4 } from "@fuel-ts/transactions";
3288
- import { arrayify as arrayify9, hexlify as hexlify13 } from "@fuel-ts/utils";
3837
+ import { bn as bn12 } from "@fuel-ts/math";
3838
+ import { InputType as InputType6, OutputType as OutputType7, TransactionType as TransactionType5 } from "@fuel-ts/transactions";
3839
+ import { arrayify as arrayify9, hexlify as hexlify14 } from "@fuel-ts/utils";
3289
3840
  import { clone as clone5 } from "ramda";
3290
3841
 
3291
3842
  // src/providers/transaction-request/scripts.ts
@@ -3323,7 +3874,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3323
3874
  return new this(clone5(obj));
3324
3875
  }
3325
3876
  /** Type of the transaction */
3326
- type = TransactionType4.Script;
3877
+ type = TransactionType5.Script;
3327
3878
  /** Gas limit for transaction */
3328
3879
  gasLimit;
3329
3880
  /** Script to execute */
@@ -3338,7 +3889,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3338
3889
  */
3339
3890
  constructor({ script, scriptData, gasLimit, ...rest } = {}) {
3340
3891
  super(rest);
3341
- this.gasLimit = bn11(gasLimit);
3892
+ this.gasLimit = bn12(gasLimit);
3342
3893
  this.script = arrayify9(script ?? returnZeroScript.bytes);
3343
3894
  this.scriptData = arrayify9(scriptData ?? returnZeroScript.encodeScriptData());
3344
3895
  this.abis = rest.abis;
@@ -3349,6 +3900,9 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3349
3900
  * @param account - The account to fund the transaction.
3350
3901
  * @param params - The parameters for the transaction cost.
3351
3902
  * @returns The current instance of the `ScriptTransactionRequest` funded.
3903
+ *
3904
+ * @deprecated Use `provider.assembleTx` instead.
3905
+ * Check the migration guide https://docs.fuel.network/guide/assembling-transactions/migration-guide.html for more information.
3352
3906
  */
3353
3907
  async estimateAndFund(account, { signatureCallback, quantities = [] } = {}) {
3354
3908
  const txCost = await account.getTransactionCost(this, { signatureCallback, quantities });
@@ -3366,14 +3920,14 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3366
3920
  const script = arrayify9(this.script ?? "0x");
3367
3921
  const scriptData = arrayify9(this.scriptData ?? "0x");
3368
3922
  return {
3369
- type: TransactionType4.Script,
3923
+ type: TransactionType5.Script,
3370
3924
  scriptGasLimit: this.gasLimit,
3371
3925
  ...super.getBaseTransaction(),
3372
- scriptLength: bn11(script.length),
3373
- scriptDataLength: bn11(scriptData.length),
3926
+ scriptLength: bn12(script.length),
3927
+ scriptDataLength: bn12(scriptData.length),
3374
3928
  receiptsRoot: ZeroBytes327,
3375
- script: hexlify13(script),
3376
- scriptData: hexlify13(scriptData)
3929
+ script: hexlify14(script),
3930
+ scriptData: hexlify14(scriptData)
3377
3931
  };
3378
3932
  }
3379
3933
  /**
@@ -3383,7 +3937,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3383
3937
  */
3384
3938
  getContractInputs() {
3385
3939
  return this.inputs.filter(
3386
- (input) => input.type === InputType5.Contract
3940
+ (input) => input.type === InputType6.Contract
3387
3941
  );
3388
3942
  }
3389
3943
  /**
@@ -3393,7 +3947,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3393
3947
  */
3394
3948
  getContractOutputs() {
3395
3949
  return this.outputs.filter(
3396
- (output) => output.type === OutputType6.Contract
3950
+ (output) => output.type === OutputType7.Contract
3397
3951
  );
3398
3952
  }
3399
3953
  /**
@@ -3403,7 +3957,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3403
3957
  */
3404
3958
  getVariableOutputs() {
3405
3959
  return this.outputs.filter(
3406
- (output) => output.type === OutputType6.Variable
3960
+ (output) => output.type === OutputType7.Variable
3407
3961
  );
3408
3962
  }
3409
3963
  /**
@@ -3426,12 +3980,27 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3426
3980
  let outputsNumber = numberOfVariables;
3427
3981
  while (outputsNumber) {
3428
3982
  this.pushOutput({
3429
- type: OutputType6.Variable
3983
+ type: OutputType7.Variable
3430
3984
  });
3431
3985
  outputsNumber -= 1;
3432
3986
  }
3433
3987
  return this.outputs.length - 1;
3434
3988
  }
3989
+ /**
3990
+ * Adds a variable output to the transaction request.
3991
+ *
3992
+ * @param to - The recipient address as a BytesLike object. Defaults to ZeroBytes32 if not provided.
3993
+ * @param amount - The amount to be transferred as a BigNumberish object. Defaults to 0 if not provided.
3994
+ * @param assetId - The asset ID as a BytesLike object. Defaults to ZeroBytes32 if not provided.
3995
+ */
3996
+ addVariableOutput(to, amount, assetId) {
3997
+ this.pushOutput({
3998
+ type: OutputType7.Variable,
3999
+ to,
4000
+ amount,
4001
+ assetId
4002
+ });
4003
+ }
3435
4004
  /**
3436
4005
  * Calculates the maximum gas for the transaction.
3437
4006
  *
@@ -3470,12 +4039,12 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3470
4039
  return this;
3471
4040
  }
3472
4041
  const inputIndex = super.pushInput({
3473
- type: InputType5.Contract,
4042
+ type: InputType6.Contract,
3474
4043
  contractId: contractAddress.toB256(),
3475
4044
  txPointer: "0x00000000000000000000000000000000"
3476
4045
  });
3477
4046
  this.pushOutput({
3478
- type: OutputType6.Contract,
4047
+ type: OutputType7.Contract,
3479
4048
  inputIndex
3480
4049
  });
3481
4050
  return this;
@@ -3511,13 +4080,13 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3511
4080
  };
3512
4081
 
3513
4082
  // src/providers/transaction-request/upgrade-transaction-request.ts
3514
- import { FuelError as FuelError11 } from "@fuel-ts/errors";
4083
+ import { FuelError as FuelError12 } from "@fuel-ts/errors";
3515
4084
  import { hash as hash2 } from "@fuel-ts/hasher";
3516
4085
  import {
3517
- TransactionType as TransactionType5,
4086
+ TransactionType as TransactionType6,
3518
4087
  UpgradePurposeTypeEnum
3519
4088
  } from "@fuel-ts/transactions";
3520
- import { hexlify as hexlify14 } from "@fuel-ts/utils";
4089
+ import { hexlify as hexlify15 } from "@fuel-ts/utils";
3521
4090
  import { clone as clone6 } from "ramda";
3522
4091
  var UpgradeTransactionRequest = class _UpgradeTransactionRequest extends BaseTransactionRequest {
3523
4092
  static {
@@ -3530,7 +4099,7 @@ var UpgradeTransactionRequest = class _UpgradeTransactionRequest extends BaseTra
3530
4099
  return new this(clone6(obj));
3531
4100
  }
3532
4101
  /** The type of transaction */
3533
- type = TransactionType5.Upgrade;
4102
+ type = TransactionType6.Upgrade;
3534
4103
  /** The upgrade purpose */
3535
4104
  upgradePurpose;
3536
4105
  /** Witness index of consensus */
@@ -3577,7 +4146,7 @@ var UpgradeTransactionRequest = class _UpgradeTransactionRequest extends BaseTra
3577
4146
  addStateTransitionUpgradePurpose(bytecodeRoot) {
3578
4147
  this.upgradePurpose = {
3579
4148
  type: UpgradePurposeTypeEnum.StateTransition,
3580
- data: hexlify14(bytecodeRoot)
4149
+ data: hexlify15(bytecodeRoot)
3581
4150
  };
3582
4151
  return this;
3583
4152
  }
@@ -3617,14 +4186,14 @@ var UpgradeTransactionRequest = class _UpgradeTransactionRequest extends BaseTra
3617
4186
  upgradePurpose = {
3618
4187
  type: UpgradePurposeTypeEnum.StateTransition,
3619
4188
  data: {
3620
- bytecodeRoot: hexlify14(this.upgradePurpose.data)
4189
+ bytecodeRoot: hexlify15(this.upgradePurpose.data)
3621
4190
  }
3622
4191
  };
3623
4192
  } else {
3624
- throw new FuelError11(FuelError11.CODES.NOT_IMPLEMENTED, "Invalid upgrade purpose");
4193
+ throw new FuelError12(FuelError12.CODES.NOT_IMPLEMENTED, "Invalid upgrade purpose");
3625
4194
  }
3626
4195
  return {
3627
- type: TransactionType5.Upgrade,
4196
+ type: TransactionType6.Upgrade,
3628
4197
  ...super.getBaseTransaction(),
3629
4198
  upgradePurpose
3630
4199
  };
@@ -3663,14 +4232,14 @@ var UpgradeTransactionRequest = class _UpgradeTransactionRequest extends BaseTra
3663
4232
  txBytesSize
3664
4233
  });
3665
4234
  }
3666
- throw new FuelError11(FuelError11.CODES.NOT_IMPLEMENTED, "Invalid upgrade purpose");
4235
+ throw new FuelError12(FuelError12.CODES.NOT_IMPLEMENTED, "Invalid upgrade purpose");
3667
4236
  }
3668
4237
  };
3669
4238
 
3670
4239
  // src/providers/transaction-request/upload-transaction-request.ts
3671
4240
  import { ZeroBytes32 as ZeroBytes328 } from "@fuel-ts/address/configs";
3672
- import { TransactionType as TransactionType6 } from "@fuel-ts/transactions";
3673
- import { arrayify as arrayify10, hexlify as hexlify15 } from "@fuel-ts/utils";
4241
+ import { TransactionType as TransactionType7 } from "@fuel-ts/transactions";
4242
+ import { arrayify as arrayify10, hexlify as hexlify16 } from "@fuel-ts/utils";
3674
4243
  import { clone as clone7 } from "ramda";
3675
4244
  var UploadTransactionRequest = class _UploadTransactionRequest extends BaseTransactionRequest {
3676
4245
  static {
@@ -3683,7 +4252,7 @@ var UploadTransactionRequest = class _UploadTransactionRequest extends BaseTrans
3683
4252
  return new this(clone7(obj));
3684
4253
  }
3685
4254
  /** Type of the transaction */
3686
- type = TransactionType6.Upload;
4255
+ type = TransactionType7.Upload;
3687
4256
  /** The witness index of the subsection of the bytecode. */
3688
4257
  witnessIndex;
3689
4258
  /** The subsection data. */
@@ -3732,12 +4301,12 @@ var UploadTransactionRequest = class _UploadTransactionRequest extends BaseTrans
3732
4301
  const baseTransaction = this.getBaseTransaction();
3733
4302
  const { subsectionIndex, subsectionsNumber, root, proofSet } = this.subsection;
3734
4303
  return {
3735
- type: TransactionType6.Upload,
4304
+ type: TransactionType7.Upload,
3736
4305
  ...baseTransaction,
3737
4306
  subsectionIndex,
3738
4307
  subsectionsNumber,
3739
- root: hexlify15(root),
3740
- proofSet: proofSet.map(hexlify15),
4308
+ root: hexlify16(root),
4309
+ proofSet: proofSet.map(hexlify16),
3741
4310
  witnessIndex: this.witnessIndex,
3742
4311
  proofSetCount: proofSet.length
3743
4312
  };
@@ -3777,39 +4346,39 @@ var UploadTransactionRequest = class _UploadTransactionRequest extends BaseTrans
3777
4346
  };
3778
4347
 
3779
4348
  // src/providers/transaction-request/utils.ts
3780
- import { ErrorCode as ErrorCode9, FuelError as FuelError12 } from "@fuel-ts/errors";
3781
- import { TransactionType as TransactionType7 } from "@fuel-ts/transactions";
4349
+ import { ErrorCode as ErrorCode10, FuelError as FuelError13 } from "@fuel-ts/errors";
4350
+ import { TransactionType as TransactionType8 } from "@fuel-ts/transactions";
3782
4351
  var transactionRequestify = /* @__PURE__ */ __name((obj) => {
3783
4352
  if (obj instanceof ScriptTransactionRequest || obj instanceof CreateTransactionRequest || obj instanceof BlobTransactionRequest || obj instanceof UpgradeTransactionRequest || obj instanceof UploadTransactionRequest) {
3784
4353
  return obj;
3785
4354
  }
3786
4355
  const { type } = obj;
3787
4356
  switch (obj.type) {
3788
- case TransactionType7.Script: {
4357
+ case TransactionType8.Script: {
3789
4358
  return ScriptTransactionRequest.from(obj);
3790
4359
  }
3791
- case TransactionType7.Create: {
4360
+ case TransactionType8.Create: {
3792
4361
  return CreateTransactionRequest.from(obj);
3793
4362
  }
3794
- case TransactionType7.Blob: {
4363
+ case TransactionType8.Blob: {
3795
4364
  return BlobTransactionRequest.from(obj);
3796
4365
  }
3797
- case TransactionType7.Upgrade: {
4366
+ case TransactionType8.Upgrade: {
3798
4367
  return UpgradeTransactionRequest.from(obj);
3799
4368
  }
3800
- case TransactionType7.Upload: {
4369
+ case TransactionType8.Upload: {
3801
4370
  return UploadTransactionRequest.from(obj);
3802
4371
  }
3803
4372
  default: {
3804
- throw new FuelError12(
3805
- ErrorCode9.UNSUPPORTED_TRANSACTION_TYPE,
4373
+ throw new FuelError13(
4374
+ ErrorCode10.UNSUPPORTED_TRANSACTION_TYPE,
3806
4375
  `Unsupported transaction type: ${type}.`
3807
4376
  );
3808
4377
  }
3809
4378
  }
3810
4379
  }, "transactionRequestify");
3811
- var isTransactionTypeScript = /* @__PURE__ */ __name((request) => request.type === TransactionType7.Script, "isTransactionTypeScript");
3812
- var isTransactionTypeCreate = /* @__PURE__ */ __name((request) => request.type === TransactionType7.Create, "isTransactionTypeCreate");
4380
+ var isTransactionTypeScript = /* @__PURE__ */ __name((request) => request.type === TransactionType8.Script, "isTransactionTypeScript");
4381
+ var isTransactionTypeCreate = /* @__PURE__ */ __name((request) => request.type === TransactionType8.Create, "isTransactionTypeCreate");
3813
4382
 
3814
4383
  // src/providers/resource-cache.ts
3815
4384
  var cache = /* @__PURE__ */ new Map();
@@ -3821,8 +4390,8 @@ var ResourceCache = class {
3821
4390
  constructor(ttl) {
3822
4391
  this.ttl = ttl;
3823
4392
  if (typeof ttl !== "number" || this.ttl <= 0) {
3824
- throw new FuelError13(
3825
- ErrorCode10.INVALID_TTL,
4393
+ throw new FuelError14(
4394
+ ErrorCode11.INVALID_TTL,
3826
4395
  `Invalid TTL: ${this.ttl}. Use a value greater than zero.`
3827
4396
  );
3828
4397
  }
@@ -3899,26 +4468,26 @@ var ResourceCache = class {
3899
4468
  }
3900
4469
  extractResourceData(input) {
3901
4470
  if (isRequestInputCoin(input)) {
3902
- return { owner: hexlify16(input.owner), key: hexlify16(input.id), type: "utxo" };
4471
+ return { owner: hexlify17(input.owner), key: hexlify17(input.id), type: "utxo" };
3903
4472
  }
3904
- return { owner: hexlify16(input.recipient), key: hexlify16(input.nonce), type: "message" };
4473
+ return { owner: hexlify17(input.recipient), key: hexlify17(input.nonce), type: "message" };
3905
4474
  }
3906
4475
  };
3907
4476
 
3908
4477
  // src/providers/transaction-response/transaction-response.ts
3909
- import { ErrorCode as ErrorCode14, FuelError as FuelError17 } from "@fuel-ts/errors";
3910
- import { bn as bn16 } from "@fuel-ts/math";
3911
- import { OutputType as OutputType8, TransactionCoder as TransactionCoder4, TxPointerCoder } from "@fuel-ts/transactions";
3912
- import { arrayify as arrayify12, assertUnreachable } from "@fuel-ts/utils";
4478
+ import { ErrorCode as ErrorCode15, FuelError as FuelError18 } from "@fuel-ts/errors";
4479
+ import { bn as bn17 } from "@fuel-ts/math";
4480
+ import { TransactionCoder as TransactionCoder5, TxPointerCoder } from "@fuel-ts/transactions";
4481
+ import { arrayify as arrayify12 } from "@fuel-ts/utils";
3913
4482
 
3914
4483
  // src/providers/transaction-summary/assemble-transaction-summary.ts
3915
- import { bn as bn15 } from "@fuel-ts/math";
3916
- import { PolicyType as PolicyType3 } from "@fuel-ts/transactions";
3917
- import { DateTime, hexlify as hexlify17 } from "@fuel-ts/utils";
4484
+ import { bn as bn16 } from "@fuel-ts/math";
4485
+ import { PolicyType as PolicyType3, TransactionCoder as TransactionCoder4 } from "@fuel-ts/transactions";
4486
+ import { DateTime, hexlify as hexlify18 } from "@fuel-ts/utils";
3918
4487
 
3919
4488
  // src/providers/transaction-summary/calculate-tx-fee-for-summary.ts
3920
- import { bn as bn12 } from "@fuel-ts/math";
3921
- import { PolicyType as PolicyType2, TransactionCoder as TransactionCoder3, TransactionType as TransactionType8 } from "@fuel-ts/transactions";
4489
+ import { bn as bn13 } from "@fuel-ts/math";
4490
+ import { PolicyType as PolicyType2, TransactionCoder as TransactionCoder3, TransactionType as TransactionType9 } from "@fuel-ts/transactions";
3922
4491
  import { arrayify as arrayify11 } from "@fuel-ts/utils";
3923
4492
  var calculateTXFeeForSummary = /* @__PURE__ */ __name((params) => {
3924
4493
  const {
@@ -3927,19 +4496,19 @@ var calculateTXFeeForSummary = /* @__PURE__ */ __name((params) => {
3927
4496
  tip,
3928
4497
  consensusParameters: { gasCosts, feeParams, maxGasPerTx }
3929
4498
  } = params;
3930
- const gasPerByte = bn12(feeParams.gasPerByte);
3931
- const gasPriceFactor = bn12(feeParams.gasPriceFactor);
4499
+ const gasPerByte = bn13(feeParams.gasPerByte);
4500
+ const gasPriceFactor = bn13(feeParams.gasPriceFactor);
3932
4501
  const transactionBytes = arrayify11(rawPayload);
3933
4502
  const [transaction] = new TransactionCoder3().decode(transactionBytes, 0);
3934
4503
  const { type, witnesses, inputs, policies } = transaction;
3935
- let metadataGas = bn12(0);
3936
- let gasLimit = bn12(0);
3937
- if (type !== TransactionType8.Create && type !== TransactionType8.Script) {
3938
- return bn12(0);
4504
+ let metadataGas = bn13(0);
4505
+ let gasLimit = bn13(0);
4506
+ if (type !== TransactionType9.Create && type !== TransactionType9.Script) {
4507
+ return bn13(0);
3939
4508
  }
3940
- if (type === TransactionType8.Create) {
4509
+ if (type === TransactionType9.Create) {
3941
4510
  const { bytecodeWitnessIndex, storageSlots } = transaction;
3942
- const contractBytesSize = bn12(arrayify11(witnesses[bytecodeWitnessIndex].data).length);
4511
+ const contractBytesSize = bn13(arrayify11(witnesses[bytecodeWitnessIndex].data).length);
3943
4512
  metadataGas = calculateMetadataGasForTxCreate({
3944
4513
  contractBytesSize,
3945
4514
  gasCosts,
@@ -3958,7 +4527,7 @@ var calculateTXFeeForSummary = /* @__PURE__ */ __name((params) => {
3958
4527
  }
3959
4528
  const minGas = getMinGas({
3960
4529
  gasCosts,
3961
- gasPerByte: bn12(gasPerByte),
4530
+ gasPerByte: bn13(gasPerByte),
3962
4531
  inputs,
3963
4532
  metadataGas,
3964
4533
  txBytesSize: transactionBytes.length
@@ -3984,14 +4553,14 @@ var calculateTXFeeForSummary = /* @__PURE__ */ __name((params) => {
3984
4553
 
3985
4554
  // src/providers/transaction-summary/operations.ts
3986
4555
  import { ZeroBytes32 as ZeroBytes329 } from "@fuel-ts/address/configs";
3987
- import { ErrorCode as ErrorCode12, FuelError as FuelError15 } from "@fuel-ts/errors";
3988
- import { bn as bn13 } from "@fuel-ts/math";
3989
- import { ReceiptType as ReceiptType5, TransactionType as TransactionType9 } from "@fuel-ts/transactions";
4556
+ import { ErrorCode as ErrorCode13, FuelError as FuelError16 } from "@fuel-ts/errors";
4557
+ import { bn as bn14 } from "@fuel-ts/math";
4558
+ import { ReceiptType as ReceiptType5, TransactionType as TransactionType10 } from "@fuel-ts/transactions";
3990
4559
 
3991
4560
  // src/providers/transaction-summary/input.ts
3992
- import { ErrorCode as ErrorCode11, FuelError as FuelError14 } from "@fuel-ts/errors";
4561
+ import { ErrorCode as ErrorCode12, FuelError as FuelError15 } from "@fuel-ts/errors";
3993
4562
  import { BN } from "@fuel-ts/math";
3994
- import { InputType as InputType6 } from "@fuel-ts/transactions";
4563
+ import { InputType as InputType7 } from "@fuel-ts/transactions";
3995
4564
  function getInputsByTypes(inputs, types) {
3996
4565
  return inputs.filter((i) => types.includes(i.type));
3997
4566
  }
@@ -4001,23 +4570,23 @@ function getInputsByType(inputs, type) {
4001
4570
  }
4002
4571
  __name(getInputsByType, "getInputsByType");
4003
4572
  function getInputsCoin(inputs) {
4004
- return getInputsByType(inputs, InputType6.Coin);
4573
+ return getInputsByType(inputs, InputType7.Coin);
4005
4574
  }
4006
4575
  __name(getInputsCoin, "getInputsCoin");
4007
4576
  function getInputsMessage(inputs) {
4008
- return getInputsByType(inputs, InputType6.Message);
4577
+ return getInputsByType(inputs, InputType7.Message);
4009
4578
  }
4010
4579
  __name(getInputsMessage, "getInputsMessage");
4011
4580
  function getInputsCoinAndMessage(inputs) {
4012
- return getInputsByTypes(inputs, [InputType6.Coin, InputType6.Message]);
4581
+ return getInputsByTypes(inputs, [InputType7.Coin, InputType7.Message]);
4013
4582
  }
4014
4583
  __name(getInputsCoinAndMessage, "getInputsCoinAndMessage");
4015
4584
  function isInputCoin(input) {
4016
- return input.type === InputType6.Coin;
4585
+ return input.type === InputType7.Coin;
4017
4586
  }
4018
4587
  __name(isInputCoin, "isInputCoin");
4019
4588
  function getInputsContract(inputs) {
4020
- return getInputsByType(inputs, InputType6.Contract);
4589
+ return getInputsByType(inputs, InputType7.Contract);
4021
4590
  }
4022
4591
  __name(getInputsContract, "getInputsContract");
4023
4592
  function findCoinInput(inputs, assetId) {
@@ -4068,9 +4637,9 @@ function getInputContractFromIndex(inputs, inputIndex) {
4068
4637
  if (!contractInput) {
4069
4638
  return void 0;
4070
4639
  }
4071
- if (contractInput.type !== InputType6.Contract) {
4072
- throw new FuelError14(
4073
- ErrorCode11.INVALID_TRANSACTION_INPUT,
4640
+ if (contractInput.type !== InputType7.Contract) {
4641
+ throw new FuelError15(
4642
+ ErrorCode12.INVALID_TRANSACTION_INPUT,
4074
4643
  `Contract input should be of type 'contract'.`
4075
4644
  );
4076
4645
  }
@@ -4078,10 +4647,10 @@ function getInputContractFromIndex(inputs, inputIndex) {
4078
4647
  }
4079
4648
  __name(getInputContractFromIndex, "getInputContractFromIndex");
4080
4649
  function getInputAccountAddress(input) {
4081
- if (input.type === InputType6.Coin) {
4650
+ if (input.type === InputType7.Coin) {
4082
4651
  return input.owner.toString();
4083
4652
  }
4084
- if (input.type === InputType6.Message) {
4653
+ if (input.type === InputType7.Message) {
4085
4654
  return input.recipient.toString();
4086
4655
  }
4087
4656
  return "";
@@ -4089,25 +4658,25 @@ function getInputAccountAddress(input) {
4089
4658
  __name(getInputAccountAddress, "getInputAccountAddress");
4090
4659
 
4091
4660
  // src/providers/transaction-summary/output.ts
4092
- import { OutputType as OutputType7 } from "@fuel-ts/transactions";
4661
+ import { OutputType as OutputType8 } from "@fuel-ts/transactions";
4093
4662
  function getOutputsByType(outputs, type) {
4094
4663
  return outputs.filter((o) => o.type === type);
4095
4664
  }
4096
4665
  __name(getOutputsByType, "getOutputsByType");
4097
4666
  function getOutputsContractCreated(outputs) {
4098
- return getOutputsByType(outputs, OutputType7.ContractCreated);
4667
+ return getOutputsByType(outputs, OutputType8.ContractCreated);
4099
4668
  }
4100
4669
  __name(getOutputsContractCreated, "getOutputsContractCreated");
4101
4670
  function getOutputsCoin(outputs) {
4102
- return getOutputsByType(outputs, OutputType7.Coin);
4671
+ return getOutputsByType(outputs, OutputType8.Coin);
4103
4672
  }
4104
4673
  __name(getOutputsCoin, "getOutputsCoin");
4105
4674
  function getOutputsChange(outputs) {
4106
- return getOutputsByType(outputs, OutputType7.Change);
4675
+ return getOutputsByType(outputs, OutputType8.Change);
4107
4676
  }
4108
4677
  __name(getOutputsChange, "getOutputsChange");
4109
4678
  function getOutputsContract(outputs) {
4110
- return getOutputsByType(outputs, OutputType7.Contract);
4679
+ return getOutputsByType(outputs, OutputType8.Contract);
4111
4680
  }
4112
4681
  __name(getOutputsContract, "getOutputsContract");
4113
4682
 
@@ -4118,21 +4687,21 @@ function getReceiptsByType(receipts, type) {
4118
4687
  __name(getReceiptsByType, "getReceiptsByType");
4119
4688
  function getTransactionTypeName(transactionType) {
4120
4689
  switch (transactionType) {
4121
- case TransactionType9.Mint:
4690
+ case TransactionType10.Mint:
4122
4691
  return "Mint" /* Mint */;
4123
- case TransactionType9.Create:
4692
+ case TransactionType10.Create:
4124
4693
  return "Create" /* Create */;
4125
- case TransactionType9.Script:
4694
+ case TransactionType10.Script:
4126
4695
  return "Script" /* Script */;
4127
- case TransactionType9.Blob:
4696
+ case TransactionType10.Blob:
4128
4697
  return "Blob" /* Blob */;
4129
- case TransactionType9.Upgrade:
4698
+ case TransactionType10.Upgrade:
4130
4699
  return "Upgrade" /* Upgrade */;
4131
- case TransactionType9.Upload:
4700
+ case TransactionType10.Upload:
4132
4701
  return "Upload" /* Upload */;
4133
4702
  default:
4134
- throw new FuelError15(
4135
- ErrorCode12.UNSUPPORTED_TRANSACTION_TYPE,
4703
+ throw new FuelError16(
4704
+ ErrorCode13.UNSUPPORTED_TRANSACTION_TYPE,
4136
4705
  `Unsupported transaction type: ${transactionType}.`
4137
4706
  );
4138
4707
  }
@@ -4185,7 +4754,7 @@ function mergeAssets(op1, op2) {
4185
4754
  assets2.forEach((asset) => {
4186
4755
  const existingAsset = assetMap.get(asset.assetId);
4187
4756
  if (existingAsset) {
4188
- existingAsset.amount = bn13(existingAsset.amount).add(asset.amount);
4757
+ existingAsset.amount = bn14(existingAsset.amount).add(asset.amount);
4189
4758
  } else {
4190
4759
  assetMap.set(asset.assetId, { ...asset });
4191
4760
  }
@@ -4537,8 +5106,8 @@ var extractBurnedAssetsFromReceipts = /* @__PURE__ */ __name((receipts) => {
4537
5106
  }, "extractBurnedAssetsFromReceipts");
4538
5107
 
4539
5108
  // src/providers/transaction-summary/status.ts
4540
- import { ErrorCode as ErrorCode13, FuelError as FuelError16 } from "@fuel-ts/errors";
4541
- import { bn as bn14 } from "@fuel-ts/math";
5109
+ import { ErrorCode as ErrorCode14, FuelError as FuelError17 } from "@fuel-ts/errors";
5110
+ import { bn as bn15 } from "@fuel-ts/math";
4542
5111
  var getTransactionStatusName = /* @__PURE__ */ __name((gqlStatus) => {
4543
5112
  switch (gqlStatus) {
4544
5113
  case "FailureStatus":
@@ -4549,22 +5118,41 @@ var getTransactionStatusName = /* @__PURE__ */ __name((gqlStatus) => {
4549
5118
  return "submitted" /* submitted */;
4550
5119
  case "SqueezedOutStatus":
4551
5120
  return "squeezedout" /* squeezedout */;
5121
+ case "PreconfirmationSuccessStatus":
5122
+ return "preconfirmationSuccess" /* preconfirmationSuccess */;
5123
+ case "PreconfirmationFailureStatus":
5124
+ return "preconfirmationFailure" /* preconfirmationFailure */;
4552
5125
  default:
4553
- throw new FuelError16(
4554
- ErrorCode13.INVALID_TRANSACTION_STATUS,
5126
+ throw new FuelError17(
5127
+ ErrorCode14.INVALID_TRANSACTION_STATUS,
4555
5128
  `Invalid transaction status: ${gqlStatus}.`
4556
5129
  );
4557
5130
  }
4558
5131
  }, "getTransactionStatusName");
5132
+ var extractResolvedOutputs = /* @__PURE__ */ __name((serializedOutputs) => {
5133
+ const resolvedOutputs = [];
5134
+ serializedOutputs?.forEach(
5135
+ ({ utxoId, output }) => resolvedOutputs.push({
5136
+ utxoId,
5137
+ output: deserializeProcessedTxOutput(output)
5138
+ })
5139
+ );
5140
+ return resolvedOutputs;
5141
+ }, "extractResolvedOutputs");
4559
5142
  var processGraphqlStatus = /* @__PURE__ */ __name((gqlTransactionStatus) => {
4560
5143
  let time;
4561
5144
  let blockId;
4562
5145
  let status;
4563
5146
  let totalFee;
4564
5147
  let totalGas;
5148
+ let receipts;
5149
+ let resolvedOutputs = [];
5150
+ let errorReason;
4565
5151
  let isStatusFailure = false;
4566
5152
  let isStatusSuccess = false;
4567
5153
  let isStatusPending = false;
5154
+ let isStatusPreConfirmationSuccess = false;
5155
+ let isStatusPreConfirmationFailure = false;
4568
5156
  if (gqlTransactionStatus?.type) {
4569
5157
  status = getTransactionStatusName(gqlTransactionStatus.type);
4570
5158
  switch (gqlTransactionStatus.type) {
@@ -4572,20 +5160,37 @@ var processGraphqlStatus = /* @__PURE__ */ __name((gqlTransactionStatus) => {
4572
5160
  time = gqlTransactionStatus.time;
4573
5161
  blockId = gqlTransactionStatus.block?.id;
4574
5162
  isStatusSuccess = true;
4575
- totalFee = bn14(gqlTransactionStatus.totalFee);
4576
- totalGas = bn14(gqlTransactionStatus.totalGas);
5163
+ receipts = gqlTransactionStatus.receipts?.map(deserializeReceipt);
5164
+ totalFee = bn15(gqlTransactionStatus.totalFee);
5165
+ totalGas = bn15(gqlTransactionStatus.totalGas);
4577
5166
  break;
4578
5167
  case "FailureStatus":
4579
5168
  time = gqlTransactionStatus.time;
4580
5169
  blockId = gqlTransactionStatus.block?.id;
4581
5170
  isStatusFailure = true;
4582
- totalFee = bn14(gqlTransactionStatus.totalFee);
4583
- totalGas = bn14(gqlTransactionStatus.totalGas);
5171
+ totalFee = bn15(gqlTransactionStatus.totalFee);
5172
+ receipts = gqlTransactionStatus.receipts?.map(deserializeReceipt);
5173
+ totalGas = bn15(gqlTransactionStatus.totalGas);
4584
5174
  break;
4585
5175
  case "SubmittedStatus":
4586
5176
  time = gqlTransactionStatus.time;
4587
5177
  isStatusPending = true;
4588
5178
  break;
5179
+ case "PreconfirmationSuccessStatus":
5180
+ isStatusPreConfirmationSuccess = true;
5181
+ totalFee = bn15(gqlTransactionStatus.totalFee);
5182
+ totalGas = bn15(gqlTransactionStatus.totalGas);
5183
+ receipts = gqlTransactionStatus.preconfirmationReceipts?.map(deserializeReceipt);
5184
+ resolvedOutputs = extractResolvedOutputs(gqlTransactionStatus.resolvedOutputs);
5185
+ break;
5186
+ case "PreconfirmationFailureStatus":
5187
+ isStatusPreConfirmationFailure = true;
5188
+ totalFee = bn15(gqlTransactionStatus.totalFee);
5189
+ totalGas = bn15(gqlTransactionStatus.totalGas);
5190
+ receipts = gqlTransactionStatus.preconfirmationReceipts?.map(deserializeReceipt);
5191
+ resolvedOutputs = extractResolvedOutputs(gqlTransactionStatus.resolvedOutputs);
5192
+ errorReason = gqlTransactionStatus.reason;
5193
+ break;
4589
5194
  default:
4590
5195
  }
4591
5196
  }
@@ -4595,13 +5200,18 @@ var processGraphqlStatus = /* @__PURE__ */ __name((gqlTransactionStatus) => {
4595
5200
  status,
4596
5201
  totalFee,
4597
5202
  totalGas,
5203
+ receipts,
4598
5204
  isStatusFailure,
4599
5205
  isStatusSuccess,
4600
- isStatusPending
5206
+ isStatusPending,
5207
+ isStatusPreConfirmationSuccess,
5208
+ isStatusPreConfirmationFailure,
5209
+ resolvedOutputs,
5210
+ errorReason
4601
5211
  };
4602
5212
  return processedGraphqlStatus;
4603
5213
  }, "processGraphqlStatus");
4604
- var getTotalFeeFromStatus = /* @__PURE__ */ __name((status) => status && "totalFee" in status ? bn14(status.totalFee) : void 0, "getTotalFeeFromStatus");
5214
+ var getTotalFeeFromStatus = /* @__PURE__ */ __name((status) => status && "totalFee" in status ? bn15(status.totalFee) : void 0, "getTotalFeeFromStatus");
4605
5215
 
4606
5216
  // src/providers/transaction-summary/assemble-transaction-summary.ts
4607
5217
  function assembleTransactionSummary(params) {
@@ -4621,7 +5231,7 @@ function assembleTransactionSummary(params) {
4621
5231
  baseAssetId
4622
5232
  } = params;
4623
5233
  const gasUsed = getGasUsedFromReceipts(receipts);
4624
- const rawPayload = hexlify17(transactionBytes);
5234
+ const rawPayload = hexlify18(transactionBytes);
4625
5235
  const operations = getOperations({
4626
5236
  transactionType: transaction.type,
4627
5237
  inputs: transaction.inputs || [],
@@ -4633,7 +5243,7 @@ function assembleTransactionSummary(params) {
4633
5243
  baseAssetId
4634
5244
  });
4635
5245
  const typeName = getTransactionTypeName(transaction.type);
4636
- const tip = bn15(transaction.policies?.find((policy) => policy.type === PolicyType3.Tip)?.data);
5246
+ const tip = bn16(transaction.policies?.find((policy) => policy.type === PolicyType3.Tip)?.data);
4637
5247
  const { isStatusFailure, isStatusPending, isStatusSuccess, blockId, status, time, totalFee } = processGraphqlStatus(gqlTransactionStatus);
4638
5248
  const fee = totalFee ?? calculateTXFeeForSummary({
4639
5249
  gasPrice,
@@ -4682,6 +5292,81 @@ function assembleTransactionSummary(params) {
4682
5292
  return transactionSummary;
4683
5293
  }
4684
5294
  __name(assembleTransactionSummary, "assembleTransactionSummary");
5295
+ function assemblePreConfirmationTransactionSummary(params) {
5296
+ const { id, gqlTransactionStatus, transactionRequest, baseAssetId, maxInputs, abiMap } = params;
5297
+ let type;
5298
+ let operations;
5299
+ let gasUsed;
5300
+ let tip;
5301
+ let transaction;
5302
+ let mintedAssets;
5303
+ let burnedAssets;
5304
+ const {
5305
+ isStatusFailure,
5306
+ isStatusSuccess,
5307
+ isStatusPending,
5308
+ status,
5309
+ receipts,
5310
+ resolvedOutputs,
5311
+ errorReason,
5312
+ totalFee,
5313
+ isStatusPreConfirmationFailure,
5314
+ isStatusPreConfirmationSuccess
5315
+ } = processGraphqlStatus(gqlTransactionStatus);
5316
+ if (receipts) {
5317
+ gasUsed = getGasUsedFromReceipts(receipts);
5318
+ mintedAssets = extractMintedAssetsFromReceipts(receipts);
5319
+ burnedAssets = extractBurnedAssetsFromReceipts(receipts);
5320
+ }
5321
+ if (transactionRequest) {
5322
+ transaction = transactionRequest.toTransaction();
5323
+ type = getTransactionTypeName(transaction.type);
5324
+ tip = bn16(transaction.policies?.find((policy) => policy.type === PolicyType3.Tip)?.data);
5325
+ if (receipts) {
5326
+ const rawPayload = hexlify18(new TransactionCoder4().encode(transaction));
5327
+ operations = getOperations({
5328
+ transactionType: transaction.type,
5329
+ inputs: transaction.inputs || [],
5330
+ outputs: transaction.outputs || [],
5331
+ receipts,
5332
+ rawPayload,
5333
+ abiMap,
5334
+ maxInputs,
5335
+ baseAssetId
5336
+ });
5337
+ }
5338
+ }
5339
+ const transactionSummary = {
5340
+ id,
5341
+ fee: totalFee,
5342
+ type,
5343
+ status,
5344
+ receipts,
5345
+ gasUsed,
5346
+ tip,
5347
+ isStatusPreConfirmationFailure,
5348
+ isStatusPreConfirmationSuccess,
5349
+ isStatusFailure,
5350
+ isStatusSuccess,
5351
+ isStatusPending,
5352
+ ...transaction && {
5353
+ isTypeMint: isTypeMint(transaction.type),
5354
+ isTypeCreate: isTypeCreate(transaction.type),
5355
+ isTypeScript: isTypeScript(transaction.type),
5356
+ isTypeUpgrade: isTypeUpgrade(transaction.type),
5357
+ isTypeUpload: isTypeUpload(transaction.type),
5358
+ isTypeBlob: isTypeBlob(transaction.type)
5359
+ },
5360
+ mintedAssets,
5361
+ burnedAssets,
5362
+ resolvedOutputs,
5363
+ errorReason,
5364
+ transaction,
5365
+ operations
5366
+ };
5367
+ return transactionSummary;
5368
+ }
5369
+ __name(assemblePreConfirmationTransactionSummary, "assemblePreConfirmationTransactionSummary");
4685
5370
 
4686
5371
  // src/providers/transaction-response/getAllDecodedLogs.ts
4687
5372
  import { Interface as Interface2, BigNumberCoder } from "@fuel-ts/abi-coder";
@@ -4717,37 +5402,6 @@ function getAllDecodedLogs(opts) {
4717
5402
  __name(getAllDecodedLogs, "getAllDecodedLogs");
4718
5403
 
4719
5404
  // src/providers/transaction-response/transaction-response.ts
4720
- function mapGqlOutputsToTxOutputs(outputs) {
4721
- return outputs.map((o) => {
4722
- const obj = "amount" in o ? { ...o, amount: bn16(o.amount) } : o;
4723
- switch (obj.type) {
4724
- case "CoinOutput":
4725
- return { ...obj, type: OutputType8.Coin };
4726
- case "ContractOutput":
4727
- return {
4728
- ...obj,
4729
- type: OutputType8.Contract,
4730
- inputIndex: parseInt(obj.inputIndex, 10)
4731
- };
4732
- case "ChangeOutput":
4733
- return {
4734
- ...obj,
4735
- type: OutputType8.Change
4736
- };
4737
- case "VariableOutput":
4738
- return { ...obj, type: OutputType8.Variable };
4739
- case "ContractCreated":
4740
- return {
4741
- ...obj,
4742
- type: OutputType8.ContractCreated,
4743
- contractId: obj.contract
4744
- };
4745
- default:
4746
- return assertUnreachable(obj);
4747
- }
4748
- });
4749
- }
4750
- __name(mapGqlOutputsToTxOutputs, "mapGqlOutputsToTxOutputs");
4751
5405
  var TransactionResponse = class _TransactionResponse {
4752
5406
  /**
4753
5407
  * Constructor for `TransactionResponse`.
@@ -4757,11 +5411,16 @@ var TransactionResponse = class _TransactionResponse {
4757
5411
  */
4758
5412
  constructor(tx, provider, chainId, abis, submitTxSubscription) {
4759
5413
  this.submitTxSubscription = submitTxSubscription;
4760
- this.id = typeof tx === "string" ? tx : tx.getTransactionId(chainId);
5414
+ if (typeof tx === "string") {
5415
+ this.id = tx;
5416
+ } else {
5417
+ this.id = tx.getTransactionId(chainId);
5418
+ this.request = tx;
5419
+ }
4761
5420
  this.provider = provider;
4762
5421
  this.abis = abis;
4763
- this.request = typeof tx === "string" ? void 0 : tx;
4764
5422
  this.waitForResult = this.waitForResult.bind(this);
5423
+ this.waitForPreConfirmation = this.waitForPreConfirmation.bind(this);
4765
5424
  }
4766
5425
  static {
4767
5426
  __name(this, "TransactionResponse");
@@ -4771,12 +5430,15 @@ var TransactionResponse = class _TransactionResponse {
4771
5430
  /** Current provider */
4772
5431
  provider;
4773
5432
  /** Gas used on the transaction */
4774
- gasUsed = bn16(0);
5433
+ gasUsed = bn17(0);
4775
5434
  /** The graphql Transaction with receipts object. */
4776
5435
  gqlTransaction;
4777
5436
  request;
4778
5437
  status;
4779
5438
  abis;
5439
+ waitingForStreamData = false;
5440
+ statusResolvers = /* @__PURE__ */ new Map();
5441
+ preConfirmationStatus;
4780
5442
  /**
4781
5443
  * Async constructor for `TransactionResponse`. This method can be used to create
4782
5444
  * an instance of `TransactionResponse` and wait for the transaction to be fetched
@@ -4808,29 +5470,38 @@ var TransactionResponse = class _TransactionResponse {
4808
5470
  }
4809
5471
  return input;
4810
5472
  });
4811
- tx.outputs = mapGqlOutputsToTxOutputs(status.transaction.outputs);
4812
- if ("receiptsRoot" in status.transaction) {
5473
+ tx.outputs = status.transaction.outputs.map(deserializeProcessedTxOutput);
5474
+ if (status.transaction.receiptsRoot) {
4813
5475
  tx.receiptsRoot = status.transaction.receiptsRoot;
4814
5476
  }
4815
5477
  }
4816
5478
  }
4817
5479
  async getTransaction() {
4818
5480
  if (this.request) {
4819
- const tx = this.request.toTransaction();
4820
- this.applyMalleableSubscriptionFields(tx);
5481
+ const tx2 = this.request.toTransaction();
5482
+ this.applyMalleableSubscriptionFields(tx2);
4821
5483
  return {
4822
- tx,
5484
+ tx: tx2,
4823
5485
  bytes: this.request.toTransactionBytes()
4824
5486
  };
4825
5487
  }
4826
5488
  const gqlTransaction = this.gqlTransaction ?? await this.fetch();
5489
+ const { rawPayload } = gqlTransaction;
5490
+ const bytes = arrayify12(rawPayload);
5491
+ const [tx] = new TransactionCoder5().decode(bytes, 0);
4827
5492
  return {
4828
- tx: this.decodeTransaction(gqlTransaction),
4829
- bytes: arrayify12(gqlTransaction.rawPayload)
5493
+ tx,
5494
+ bytes
4830
5495
  };
4831
5496
  }
5497
+ /**
5498
+ *
5499
+ * NOTE: This method is only called within `getTransactionSummary`, which is invoked after `getTransaction`.
5500
+ * Since `getTransaction` only resolves once the transaction has been processed,
5501
+ * the status at this point is guaranteed to be either `SuccessStatus` or `FailureStatus`.
5502
+ */
4832
5503
  getReceipts() {
4833
- const status = this.status ?? this.gqlTransaction?.status;
5504
+ const status = this.getTransactionStatus();
4834
5505
  switch (status?.type) {
4835
5506
  case "SuccessStatus":
4836
5507
  case "FailureStatus":
@@ -4863,18 +5534,6 @@ var TransactionResponse = class _TransactionResponse {
4863
5534
  this.gqlTransaction = response.transaction;
4864
5535
  return response.transaction;
4865
5536
  }
4866
- /**
4867
- * Decode the raw payload of the transaction.
4868
- *
4869
- * @param transactionWithReceipts - The transaction with receipts object.
4870
- * @returns The decoded transaction.
4871
- */
4872
- decodeTransaction(transactionWithReceipts) {
4873
- return new TransactionCoder4().decode(
4874
- arrayify12(transactionWithReceipts.rawPayload),
4875
- 0
4876
- )?.[0];
4877
- }
4878
5537
  /**
4879
5538
  * Retrieves the TransactionSummary. If the `gqlTransaction` is not set, it will
4880
5539
  * fetch it from the provider
@@ -4885,8 +5544,9 @@ var TransactionResponse = class _TransactionResponse {
4885
5544
  async getTransactionSummary(contractsAbiMap) {
4886
5545
  const { tx: transaction, bytes: transactionBytes } = await this.getTransaction();
4887
5546
  const { gasPerByte, gasPriceFactor, gasCosts, maxGasPerTx } = await this.provider.getGasConfig();
4888
- const totalFee = getTotalFeeFromStatus(this.status ?? this.gqlTransaction?.status);
4889
- const gasPrice = totalFee ? bn16(0) : await this.provider.getLatestGasPrice();
5547
+ const transactionStatus = this.getTransactionStatus();
5548
+ const totalFee = getTotalFeeFromStatus(transactionStatus);
5549
+ const gasPrice = totalFee ? bn17(0) : await this.provider.getLatestGasPrice();
4890
5550
  const maxInputs = (await this.provider.getChain()).consensusParameters.txParameters.maxInputs;
4891
5551
  const baseAssetId = await this.provider.getBaseAssetId();
4892
5552
  const transactionSummary = assembleTransactionSummary({
@@ -4894,7 +5554,7 @@ var TransactionResponse = class _TransactionResponse {
4894
5554
  receipts: this.getReceipts(),
4895
5555
  transaction,
4896
5556
  transactionBytes,
4897
- gqlTransactionStatus: this.status ?? this.gqlTransaction?.status,
5557
+ gqlTransactionStatus: transactionStatus,
4898
5558
  gasPerByte,
4899
5559
  gasPriceFactor,
4900
5560
  abiMap: contractsAbiMap,
@@ -4906,29 +5566,92 @@ var TransactionResponse = class _TransactionResponse {
4906
5566
  });
4907
5567
  return transactionSummary;
4908
5568
  }
5569
+ async getPreConfirmationTransactionSummary(contractsAbiMap) {
5570
+ const baseAssetId = await this.provider.getBaseAssetId();
5571
+ const maxInputs = (await this.provider.getChain()).consensusParameters.txParameters.maxInputs;
5572
+ const transactionSummary = assemblePreConfirmationTransactionSummary({
5573
+ id: this.id,
5574
+ gqlTransactionStatus: this.preConfirmationStatus || this.status,
5575
+ baseAssetId,
5576
+ maxInputs,
5577
+ abiMap: contractsAbiMap,
5578
+ transactionRequest: this.request
5579
+ });
5580
+ return transactionSummary;
5581
+ }
5582
+ resolveStatus(type) {
5583
+ const resolvers = this.statusResolvers.get(type) || [];
5584
+ resolvers.forEach((resolve) => resolve());
5585
+ this.statusResolvers.delete(type);
5586
+ }
5587
+ async waitForStatus(type) {
5588
+ return new Promise((resolve, reject) => {
5589
+ const resolvers = this.statusResolvers.get(type) || [];
5590
+ resolvers.push(() => {
5591
+ resolve();
5592
+ });
5593
+ this.statusResolvers.set(type, resolvers);
5594
+ this.waitForStatusChange().catch(reject);
5595
+ });
5596
+ }
5597
+ /**
5598
+ * Waits for the status change of the transaction.
5599
+ * If the transaction is already in a final state, it will return immediately.
5600
+ * If the transaction is not in a final state, it will wait for the status change.
5601
+ * If we are already subscribed to the status change, it will return immediately.
5602
+ */
4909
5603
  async waitForStatusChange() {
4910
- const status = this.gqlTransaction?.status?.type;
4911
- if (status && status !== "SubmittedStatus") {
5604
+ const type = this.status?.type;
5605
+ if (type && (type === "FailureStatus" || type === "SuccessStatus")) {
5606
+ this.resolveStatus("preConfirmation");
5607
+ this.resolveStatus("confirmation");
4912
5608
  return;
4913
5609
  }
5610
+ if (this.waitingForStreamData) {
5611
+ return;
5612
+ }
5613
+ this.waitingForStreamData = true;
4914
5614
  const subscription = this.submitTxSubscription ?? await this.provider.operations.statusChange({
4915
- transactionId: this.id
5615
+ transactionId: this.id,
5616
+ includePreConfirmation: true
4916
5617
  });
4917
5618
  for await (const sub of subscription) {
4918
5619
  const statusChange = "statusChange" in sub ? sub.statusChange : sub.submitAndAwaitStatus;
4919
5620
  this.status = statusChange;
4920
5621
  if (statusChange.type === "SqueezedOutStatus") {
4921
- this.unsetResourceCache();
4922
- throw new FuelError17(
4923
- ErrorCode14.TRANSACTION_SQUEEZED_OUT,
5622
+ throw new FuelError18(
5623
+ ErrorCode15.TRANSACTION_SQUEEZED_OUT,
4924
5624
  `Transaction Squeezed Out with reason: ${statusChange.reason}`
4925
5625
  );
4926
5626
  }
4927
- if (statusChange.type !== "SubmittedStatus") {
5627
+ if (statusChange.type === "PreconfirmationSuccessStatus" || statusChange.type === "PreconfirmationFailureStatus") {
5628
+ this.preConfirmationStatus = statusChange;
5629
+ this.resolveStatus("preConfirmation");
5630
+ }
5631
+ if (statusChange.type === "SuccessStatus" || statusChange.type === "FailureStatus") {
5632
+ this.resolveStatus("confirmation");
5633
+ this.resolveStatus("preConfirmation");
5634
+ this.waitingForStreamData = false;
4928
5635
  break;
4929
5636
  }
4930
5637
  }
4931
5638
  }
5639
+ async waitForConfirmationStatuses() {
5640
+ try {
5641
+ await this.waitForStatus("confirmation");
5642
+ } catch (error) {
5643
+ this.unsetResourceCache();
5644
+ throw error;
5645
+ }
5646
+ }
5647
+ async waitForPreConfirmationStatuses() {
5648
+ try {
5649
+ await this.waitForStatus("preConfirmation");
5650
+ } catch (error) {
5651
+ this.unsetResourceCache();
5652
+ throw error;
5653
+ }
5654
+ }
4932
5655
  /**
4933
5656
  * Assembles the result of a transaction by retrieving the transaction summary,
4934
5657
  * decoding logs (if available), and handling transaction failure.
@@ -4957,7 +5680,7 @@ var TransactionResponse = class _TransactionResponse {
4957
5680
  transactionResult.groupedLogs = groupedLogs;
4958
5681
  }
4959
5682
  const { receipts } = transactionResult;
4960
- const status = this.status ?? this.gqlTransaction?.status;
5683
+ const status = this.getTransactionStatus();
4961
5684
  if (status?.type === "FailureStatus") {
4962
5685
  const { reason } = status;
4963
5686
  throw extractTxError({
@@ -4969,16 +5692,46 @@ var TransactionResponse = class _TransactionResponse {
4969
5692
  }
4970
5693
  return transactionResult;
4971
5694
  }
5695
+ async assemblePreConfirmationResult(contractsAbiMap) {
5696
+ const transactionSummary = await this.getPreConfirmationTransactionSummary(contractsAbiMap);
5697
+ const transactionResult = {
5698
+ ...transactionSummary,
5699
+ logs: [],
5700
+ groupedLogs: {}
5701
+ };
5702
+ let { logs, groupedLogs } = { logs: [], groupedLogs: {} };
5703
+ if (this.abis && transactionSummary.receipts) {
5704
+ ({ logs, groupedLogs } = getAllDecodedLogs({
5705
+ receipts: transactionSummary.receipts,
5706
+ mainAbi: this.abis.main,
5707
+ externalAbis: this.abis.otherContractsAbis
5708
+ }));
5709
+ transactionResult.logs = logs;
5710
+ transactionResult.groupedLogs = groupedLogs;
5711
+ }
5712
+ return transactionResult;
5713
+ }
4972
5714
  /**
4973
5715
  * Waits for transaction to complete and returns the result.
4974
5716
  *
4975
5717
  * @returns The completed transaction result
4976
5718
  */
4977
5719
  async waitForResult(contractsAbiMap) {
4978
- await this.waitForStatusChange();
5720
+ await this.waitForConfirmationStatuses();
4979
5721
  this.unsetResourceCache();
4980
5722
  return this.assembleResult(contractsAbiMap);
4981
5723
  }
5724
+ /**
5725
+ * Waits for the transaction's pre-confirmation and returns the result.
5726
+ *
5727
+ * @param contractsAbiMap - The contracts ABI map.
5728
+ * @returns The pre-confirmed transaction result
5729
+ */
5730
+ async waitForPreConfirmation(contractsAbiMap) {
5731
+ await this.waitForPreConfirmationStatuses();
5732
+ this.unsetResourceCache();
5733
+ return this.assemblePreConfirmationResult(contractsAbiMap);
5734
+ }
4982
5735
  /**
4983
5736
  * Waits for transaction to complete and returns the result.
4984
5737
  *
@@ -4990,6 +5743,9 @@ var TransactionResponse = class _TransactionResponse {
4990
5743
  unsetResourceCache() {
4991
5744
  this.provider.cache?.unset(this.id);
4992
5745
  }
5746
+ getTransactionStatus() {
5747
+ return this.status ?? this.gqlTransaction?.status;
5748
+ }
4993
5749
  };
4994
5750
 
4995
5751
  // src/providers/transaction-response/getDecodedLogs.ts
@@ -5036,48 +5792,49 @@ function autoRetryFetch(fetchFn, options, retryAttemptNum = 0) {
5036
5792
  }
5037
5793
  __name(autoRetryFetch, "autoRetryFetch");
5038
5794
 
5039
- // src/providers/utils/helpers.ts
5040
- var adjustResourcesToExclude = /* @__PURE__ */ __name((params) => {
5041
- const { userInput, cached, maxInputs } = params;
5042
- const final = { ...userInput };
5043
- let total = final.utxos.length + final.messages.length;
5044
- if (total >= maxInputs) {
5045
- return final;
5046
- }
5047
- final.utxos = [...final.utxos, ...cached.utxos.slice(0, maxInputs - total)];
5048
- total = final.utxos.length + final.messages.length;
5049
- if (total < maxInputs) {
5050
- final.messages = [...final.messages, ...cached.messages.slice(0, maxInputs - total)];
5795
+ // src/providers/utils/parse-graphql-response.ts
5796
+ var parseGraphqlResponse = /* @__PURE__ */ __name(async (options) => {
5797
+ const { response, isSubscription } = options;
5798
+ let extensions;
5799
+ const responseClone = response.clone();
5800
+ if (isSubscription) {
5801
+ const reader = responseClone.body?.getReader();
5802
+ const { event } = await FuelGraphqlSubscriber.readEvent(reader);
5803
+ extensions = event?.extensions;
5804
+ } else {
5805
+ extensions = (await responseClone.json()).extensions;
5051
5806
  }
5052
- return final;
5053
- }, "adjustResourcesToExclude");
5807
+ return {
5808
+ extensions
5809
+ };
5810
+ }, "parseGraphqlResponse");
5054
5811
 
5055
5812
  // src/providers/utils/validate-pagination-args.ts
5056
- import { FuelError as FuelError18, ErrorCode as ErrorCode15 } from "@fuel-ts/errors";
5813
+ import { FuelError as FuelError19, ErrorCode as ErrorCode16 } from "@fuel-ts/errors";
5057
5814
  var validatePaginationArgs = /* @__PURE__ */ __name((params) => {
5058
5815
  const { paginationLimit, inputArgs = {} } = params;
5059
5816
  const { first, last, after, before } = inputArgs;
5060
5817
  if (after && before) {
5061
- throw new FuelError18(
5062
- ErrorCode15.INVALID_INPUT_PARAMETERS,
5818
+ throw new FuelError19(
5819
+ ErrorCode16.INVALID_INPUT_PARAMETERS,
5063
5820
  'Pagination arguments "after" and "before" cannot be used together'
5064
5821
  );
5065
5822
  }
5066
5823
  if ((first || 0) > paginationLimit || (last || 0) > paginationLimit) {
5067
- throw new FuelError18(
5068
- ErrorCode15.INVALID_INPUT_PARAMETERS,
5824
+ throw new FuelError19(
5825
+ ErrorCode16.INVALID_INPUT_PARAMETERS,
5069
5826
  `Pagination limit for this query cannot exceed ${paginationLimit} items`
5070
5827
  );
5071
5828
  }
5072
5829
  if (first && before) {
5073
- throw new FuelError18(
5074
- ErrorCode15.INVALID_INPUT_PARAMETERS,
5830
+ throw new FuelError19(
5831
+ ErrorCode16.INVALID_INPUT_PARAMETERS,
5075
5832
  'The use of pagination argument "first" with "before" is not supported'
5076
5833
  );
5077
5834
  }
5078
5835
  if (last && after) {
5079
- throw new FuelError18(
5080
- ErrorCode15.INVALID_INPUT_PARAMETERS,
5836
+ throw new FuelError19(
5837
+ ErrorCode16.INVALID_INPUT_PARAMETERS,
5081
5838
  'The use of pagination argument "last" with "after" is not supported'
5082
5839
  );
5083
5840
  }
@@ -5096,22 +5853,48 @@ var NON_PAGINATED_BALANCES_SIZE = 1e4;
5096
5853
  var BLOCKS_PAGE_SIZE_LIMIT = 5;
5097
5854
  var DEFAULT_RESOURCE_CACHE_TTL = 2e4;
5098
5855
  var GAS_USED_MODIFIER = 1.2;
5856
+ var WRITE_OPERATIONS = [
5857
+ "submit",
5858
+ "submitAndAwaitStatus",
5859
+ "produceBlocks"
5860
+ ];
5099
5861
  var Provider = class _Provider {
5100
5862
  static {
5101
5863
  __name(this, "Provider");
5102
5864
  }
5103
5865
  operations;
5104
5866
  cache;
5105
- /** @hidden */
5106
- static clearChainAndNodeCaches() {
5867
+ /**
5868
+ * @hidden
5869
+ * @param url - If provided, clears cache only for given url
5870
+ */
5871
+ static clearChainAndNodeCaches(url) {
5872
+ if (url) {
5873
+ delete _Provider.inflightFetchChainAndNodeInfoRequests[url];
5874
+ delete _Provider.chainInfoCache[url];
5875
+ delete _Provider.nodeInfoCache[url];
5876
+ delete _Provider.currentBlockHeightCache[url];
5877
+ return;
5878
+ }
5107
5879
  _Provider.inflightFetchChainAndNodeInfoRequests = {};
5108
5880
  _Provider.nodeInfoCache = {};
5109
5881
  _Provider.chainInfoCache = {};
5882
+ _Provider.currentBlockHeightCache = {};
5110
5883
  }
5111
5884
  /** @hidden */
5112
5885
  url;
5113
5886
  /** @hidden */
5114
5887
  urlWithoutAuth;
5888
+ /**
5889
+ * Governs whether to include the required block height in the request body
5890
+ * for block-sensitive operations like when submitting a transaction.
5891
+ *
5892
+ * This ensures that the operation is executed at the correct block height,
5893
+ * regardless of which node in the network the request is routed to.
5894
+ *
5895
+ * `true` by default.
5896
+ */
5897
+ static ENABLE_RPC_CONSISTENCY = true;
5115
5898
  /** @hidden */
5116
5899
  static inflightFetchChainAndNodeInfoRequests = {};
5117
5900
  /** @hidden */
@@ -5119,6 +5902,8 @@ var Provider = class _Provider {
5119
5902
  /** @hidden */
5120
5903
  static nodeInfoCache = {};
5121
5904
  /** @hidden */
5905
+ static currentBlockHeightCache = {};
5906
+ /** @hidden */
5122
5907
  static incompatibleNodeVersionMessage = "";
5123
5908
  /** @hidden */
5124
5909
  consensusParametersTimestamp;
@@ -5130,6 +5915,18 @@ var Provider = class _Provider {
5130
5915
  headers: void 0,
5131
5916
  cache: void 0
5132
5917
  };
5918
+ static extractOperationName(body) {
5919
+ return body?.toString().match(/"operationName":"(.+)"/)?.[1];
5920
+ }
5921
+ static isWriteOperation(body) {
5922
+ return WRITE_OPERATIONS.includes(this.extractOperationName(body));
5923
+ }
5924
+ static normalizeUrl(url) {
5925
+ return url.replace(/-sub$/, "");
5926
+ }
5927
+ static hasWriteOperationHappened(url) {
5928
+ return isDefined3(_Provider.currentBlockHeightCache[this.normalizeUrl(url)]);
5929
+ }
5133
5930
  /**
5134
5931
  * @hidden
5135
5932
  */
@@ -5147,9 +5944,57 @@ var Provider = class _Provider {
5147
5944
  if (options.requestMiddleware) {
5148
5945
  fullRequest = await options.requestMiddleware(fullRequest);
5149
5946
  }
5150
- return options.fetch ? options.fetch(url, fullRequest, options) : fetch(url, fullRequest);
5947
+ if (_Provider.ENABLE_RPC_CONSISTENCY && _Provider.hasWriteOperationHappened(url)) {
5948
+ _Provider.applyBlockHeight(fullRequest, url);
5949
+ }
5950
+ return _Provider.fetchAndProcessBlockHeight(url, fullRequest, options);
5151
5951
  }, retryOptions);
5152
5952
  }
5953
+ static applyBlockHeight(request, url) {
5954
+ const normalizedUrl = this.normalizeUrl(url);
5955
+ const currentBlockHeight = _Provider.currentBlockHeightCache[normalizedUrl] ?? 0;
5956
+ request.body = request.body?.toString().replace(/}$/, `,"extensions":{"required_fuel_block_height":${currentBlockHeight}}}`);
5957
+ }
5958
+ static async fetchAndProcessBlockHeight(url, request, options) {
5959
+ const fetchFn = /* @__PURE__ */ __name(() => options.fetch ? options.fetch(url, request, options) : fetch(url, request), "fetchFn");
5960
+ const isWriteOperation = _Provider.isWriteOperation(request.body);
5961
+ if (isWriteOperation && !_Provider.hasWriteOperationHappened(url)) {
5962
+ _Provider.currentBlockHeightCache[_Provider.normalizeUrl(url)] = 0;
5963
+ }
5964
+ let response = await fetchFn();
5965
+ if (!_Provider.ENABLE_RPC_CONSISTENCY) {
5966
+ return response;
5967
+ }
5968
+ const retryOptions = {
5969
+ maxRetries: 5,
5970
+ baseDelay: 500
5971
+ };
5972
+ for (let retriesLeft = retryOptions.maxRetries; retriesLeft > 0; --retriesLeft) {
5973
+ const { extensions } = await parseGraphqlResponse({
5974
+ response,
5975
+ isSubscription: url.endsWith("-sub")
5976
+ });
5977
+ _Provider.setCurrentBlockHeight(url, extensions?.current_fuel_block_height);
5978
+ if (!extensions?.fuel_block_height_precondition_failed) {
5979
+ break;
5980
+ }
5981
+ const retryAttempt = retryOptions.maxRetries - retriesLeft + 1;
5982
+ const sleepTime = getWaitDelay(retryOptions, retryAttempt);
5983
+ await sleep2(sleepTime);
5984
+ response = await fetchFn();
5985
+ }
5986
+ return response;
5987
+ }
5988
+ static setCurrentBlockHeight(url, height) {
5989
+ const writeOperationHappened = _Provider.hasWriteOperationHappened(url);
5990
+ if (!isDefined3(height) || !writeOperationHappened) {
5991
+ return;
5992
+ }
5993
+ const normalizedUrl = _Provider.normalizeUrl(url);
5994
+ if (height > _Provider.currentBlockHeightCache[normalizedUrl]) {
5995
+ _Provider.currentBlockHeightCache[normalizedUrl] = height;
5996
+ }
5997
+ }
5153
5998
  /**
5154
5999
  * Constructor to initialize a Provider.
5155
6000
  *
@@ -5177,7 +6022,7 @@ var Provider = class _Provider {
5177
6022
  _Provider.chainInfoCache[this.urlWithoutAuth] = chain;
5178
6023
  _Provider.nodeInfoCache[this.urlWithoutAuth] = nodeInfo;
5179
6024
  }
5180
- if (isDefined2(resourceCacheTTL)) {
6025
+ if (isDefined3(resourceCacheTTL)) {
5181
6026
  if (resourceCacheTTL !== -1) {
5182
6027
  this.cache = new ResourceCache(resourceCacheTTL);
5183
6028
  } else {
@@ -5192,7 +6037,7 @@ var Provider = class _Provider {
5192
6037
  try {
5193
6038
  parsedUrl = new URL(url);
5194
6039
  } catch (error) {
5195
- throw new FuelError19(FuelError19.CODES.INVALID_URL, "Invalid URL provided.", { url }, error);
6040
+ throw new FuelError20(FuelError20.CODES.INVALID_URL, "Invalid URL provided.", { url }, error);
5196
6041
  }
5197
6042
  const username = parsedUrl.username;
5198
6043
  const password = parsedUrl.password;
@@ -5235,6 +6080,7 @@ var Provider = class _Provider {
5235
6080
  * Returns some helpful parameters related to gas fees.
5236
6081
  */
5237
6082
  async getGasConfig() {
6083
+ await this.init();
5238
6084
  const {
5239
6085
  txParameters: { maxGasPerTx },
5240
6086
  predicateParameters: { maxGasPerPredicate },
@@ -5297,8 +6143,8 @@ var Provider = class _Provider {
5297
6143
  this.consensusParametersTimestamp = data.consensusParametersTimestamp;
5298
6144
  return data;
5299
6145
  }).catch((err) => {
5300
- const error = new FuelError19(
5301
- FuelError19.CODES.CONNECTION_REFUSED,
6146
+ const error = new FuelError20(
6147
+ FuelError20.CODES.CONNECTION_REFUSED,
5302
6148
  "Unable to fetch chain and node info from the network",
5303
6149
  { url: this.urlWithoutAuth },
5304
6150
  err
@@ -5359,7 +6205,14 @@ var Provider = class _Provider {
5359
6205
  url: this.urlWithoutAuth,
5360
6206
  query,
5361
6207
  fetchFn: /* @__PURE__ */ __name((url, requestInit) => fetchFn(url, requestInit, this.options), "fetchFn"),
5362
- variables: vars
6208
+ variables: vars,
6209
+ operationName: opDefinition.name.value,
6210
+ onEvent: /* @__PURE__ */ __name((event) => {
6211
+ _Provider.setCurrentBlockHeight(
6212
+ this.urlWithoutAuth,
6213
+ event.extensions?.current_fuel_block_height
6214
+ );
6215
+ }, "onEvent")
5363
6216
  });
5364
6217
  }
5365
6218
  return gqlClient.request(query, vars);
@@ -5407,7 +6260,7 @@ var Provider = class _Provider {
5407
6260
  latestBlock: { height }
5408
6261
  }
5409
6262
  } = await this.operations.getLatestBlockHeight();
5410
- return bn17(height);
6263
+ return bn18(height);
5411
6264
  }
5412
6265
  /**
5413
6266
  * Returns the node information for the current provider network.
@@ -5463,8 +6316,8 @@ var Provider = class _Provider {
5463
6316
  async getAssetDetails(assetId) {
5464
6317
  const { assetMetadata } = await this.getNodeFeatures();
5465
6318
  if (!assetMetadata) {
5466
- throw new FuelError19(
5467
- ErrorCode16.UNSUPPORTED_FEATURE,
6319
+ throw new FuelError20(
6320
+ ErrorCode17.UNSUPPORTED_FEATURE,
5468
6321
  "The current node does not supports fetching asset details"
5469
6322
  );
5470
6323
  }
@@ -5473,7 +6326,7 @@ var Provider = class _Provider {
5473
6326
  return {
5474
6327
  subId,
5475
6328
  contractId,
5476
- totalSupply: bn17(totalSupply)
6329
+ totalSupply: bn18(totalSupply)
5477
6330
  };
5478
6331
  }
5479
6332
  /**
@@ -5494,15 +6347,15 @@ var Provider = class _Provider {
5494
6347
  txParameters: { maxInputs, maxOutputs }
5495
6348
  }
5496
6349
  } = await this.getChain();
5497
- if (bn17(tx.inputs.length).gt(maxInputs)) {
5498
- throw new FuelError19(
5499
- ErrorCode16.MAX_INPUTS_EXCEEDED,
6350
+ if (bn18(tx.inputs.length).gt(maxInputs)) {
6351
+ throw new FuelError20(
6352
+ ErrorCode17.MAX_INPUTS_EXCEEDED,
5500
6353
  `The transaction exceeds the maximum allowed number of inputs. Tx inputs: ${tx.inputs.length}, max inputs: ${maxInputs}`
5501
6354
  );
5502
6355
  }
5503
- if (bn17(tx.outputs.length).gt(maxOutputs)) {
5504
- throw new FuelError19(
5505
- ErrorCode16.MAX_OUTPUTS_EXCEEDED,
6356
+ if (bn18(tx.outputs.length).gt(maxOutputs)) {
6357
+ throw new FuelError20(
6358
+ ErrorCode17.MAX_OUTPUTS_EXCEEDED,
5506
6359
  `The transaction exceeds the maximum allowed number of outputs. Tx outputs: ${tx.outputs.length}, max outputs: ${maxOutputs}`
5507
6360
  );
5508
6361
  }
@@ -5517,7 +6370,11 @@ var Provider = class _Provider {
5517
6370
  * @param sendTransactionParams - The provider send transaction parameters (optional).
5518
6371
  * @returns A promise that resolves to the transaction response object.
5519
6372
  */
5520
- async sendTransaction(transactionRequestLike, { estimateTxDependencies = true, enableAssetBurn } = {}) {
6373
+ async sendTransaction(transactionRequestLike, {
6374
+ enableAssetBurn,
6375
+ estimateTxDependencies = true,
6376
+ includePreConfirmation: _includePreConfirmation = true
6377
+ } = {}) {
5521
6378
  const transactionRequest = transactionRequestify(transactionRequestLike);
5522
6379
  validateTransactionForAssetBurn(
5523
6380
  await this.getBaseAssetId(),
@@ -5528,12 +6385,15 @@ var Provider = class _Provider {
5528
6385
  await this.estimateTxDependencies(transactionRequest);
5529
6386
  }
5530
6387
  await this.validateTransaction(transactionRequest);
5531
- const encodedTransaction = hexlify18(transactionRequest.toTransactionBytes());
6388
+ const encodedTransaction = hexlify19(transactionRequest.toTransactionBytes());
5532
6389
  let abis;
5533
6390
  if (isTransactionTypeScript(transactionRequest)) {
5534
6391
  abis = transactionRequest.abis;
5535
6392
  }
5536
- const subscription = await this.operations.submitAndAwaitStatus({ encodedTransaction });
6393
+ const subscription = await this.operations.submitAndAwaitStatus({
6394
+ encodedTransaction,
6395
+ includePreConfirmation: true
6396
+ });
5537
6397
  this.#cacheInputs(
5538
6398
  transactionRequest.inputs,
5539
6399
  transactionRequest.getTransactionId(await this.getChainId())
@@ -5556,7 +6416,7 @@ var Provider = class _Provider {
5556
6416
  if (estimateTxDependencies) {
5557
6417
  return this.estimateTxDependencies(transactionRequest);
5558
6418
  }
5559
- const encodedTransaction = hexlify18(transactionRequest.toTransactionBytes());
6419
+ const encodedTransaction = hexlify19(transactionRequest.toTransactionBytes());
5560
6420
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
5561
6421
  encodedTransactions: encodedTransaction,
5562
6422
  utxoValidation: utxoValidation || false
@@ -5575,12 +6435,12 @@ var Provider = class _Provider {
5575
6435
  */
5576
6436
  async estimatePredicates(transactionRequest) {
5577
6437
  const shouldEstimatePredicates = transactionRequest.inputs.some(
5578
- (input) => isPredicate(input) && bn17(input.predicateGasUsed).isZero()
6438
+ (input) => isPredicate(input) && bn18(input.predicateGasUsed).isZero()
5579
6439
  );
5580
6440
  if (!shouldEstimatePredicates) {
5581
6441
  return transactionRequest;
5582
6442
  }
5583
- const encodedTransaction = hexlify18(transactionRequest.toTransactionBytes());
6443
+ const encodedTransaction = hexlify19(transactionRequest.toTransactionBytes());
5584
6444
  const response = await this.operations.estimatePredicates({
5585
6445
  encodedTransaction
5586
6446
  });
@@ -5601,7 +6461,7 @@ var Provider = class _Provider {
5601
6461
  */
5602
6462
  async estimatePredicatesAndGasPrice(transactionRequest, blockHorizon) {
5603
6463
  const shouldEstimatePredicates = transactionRequest.inputs.some(
5604
- (input) => isPredicate(input) && bn17(input.predicateGasUsed).isZero()
6464
+ (input) => isPredicate(input) && bn18(input.predicateGasUsed).isZero()
5605
6465
  );
5606
6466
  if (!shouldEstimatePredicates) {
5607
6467
  const gasPrice2 = await this.estimateGasPrice(blockHorizon);
@@ -5612,13 +6472,13 @@ var Provider = class _Provider {
5612
6472
  estimatePredicates
5613
6473
  } = await this.operations.estimatePredicatesAndGasPrice({
5614
6474
  blockHorizon: String(blockHorizon),
5615
- encodedTransaction: hexlify18(transactionRequest.toTransactionBytes())
6475
+ encodedTransaction: hexlify19(transactionRequest.toTransactionBytes())
5616
6476
  });
5617
6477
  transactionRequest = this.parseEstimatePredicatesResponse(
5618
6478
  transactionRequest,
5619
6479
  estimatePredicates
5620
6480
  );
5621
- return { transactionRequest, gasPrice: bn17(gasPrice) };
6481
+ return { transactionRequest, gasPrice: bn18(gasPrice) };
5622
6482
  }
5623
6483
  /**
5624
6484
  * Will dryRun a transaction and check for missing dependencies.
@@ -5650,7 +6510,7 @@ var Provider = class _Provider {
5650
6510
  const {
5651
6511
  dryRun: [{ receipts: serializedReceipts, status }]
5652
6512
  } = await this.operations.dryRun({
5653
- encodedTransactions: [hexlify18(transactionRequest.toTransactionBytes())],
6513
+ encodedTransactions: [hexlify19(transactionRequest.toTransactionBytes())],
5654
6514
  utxoValidation: false,
5655
6515
  gasPrice: gasPrice.toString()
5656
6516
  });
@@ -5705,7 +6565,7 @@ var Provider = class _Provider {
5705
6565
  const serializedTransactionsMap = /* @__PURE__ */ new Map();
5706
6566
  allRequests.forEach((req, index) => {
5707
6567
  if (isTransactionTypeScript(req)) {
5708
- serializedTransactionsMap.set(index, hexlify18(req.toTransactionBytes()));
6568
+ serializedTransactionsMap.set(index, hexlify19(req.toTransactionBytes()));
5709
6569
  }
5710
6570
  });
5711
6571
  let transactionsToProcess = Array.from(serializedTransactionsMap.keys());
@@ -5741,7 +6601,7 @@ var Provider = class _Provider {
5741
6601
  transactionRequest: request
5742
6602
  });
5743
6603
  request.maxFee = maxFee;
5744
- serializedTransactionsMap.set(requestIdx, hexlify18(request.toTransactionBytes()));
6604
+ serializedTransactionsMap.set(requestIdx, hexlify19(request.toTransactionBytes()));
5745
6605
  nextRoundTransactions.push(requestIdx);
5746
6606
  }
5747
6607
  }
@@ -5762,7 +6622,7 @@ var Provider = class _Provider {
5762
6622
  if (estimateTxDependencies) {
5763
6623
  return this.estimateMultipleTxDependencies(transactionRequests);
5764
6624
  }
5765
- const encodedTransactions = transactionRequests.map((tx) => hexlify18(tx.toTransactionBytes()));
6625
+ const encodedTransactions = transactionRequests.map((tx) => hexlify19(tx.toTransactionBytes()));
5766
6626
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
5767
6627
  encodedTransactions,
5768
6628
  utxoValidation: utxoValidation || false
@@ -5810,16 +6670,16 @@ var Provider = class _Provider {
5810
6670
  const chainInfo = await this.getChain();
5811
6671
  const { gasPriceFactor, maxGasPerTx } = await this.getGasConfig();
5812
6672
  const minGas = transactionRequest.calculateMinGas(chainInfo);
5813
- if (!isDefined2(gasPrice)) {
6673
+ if (!isDefined3(gasPrice)) {
5814
6674
  gasPrice = await this.estimateGasPrice(10);
5815
6675
  }
5816
6676
  const minFee = calculateGasFee({
5817
- gasPrice: bn17(gasPrice),
6677
+ gasPrice: bn18(gasPrice),
5818
6678
  gas: minGas,
5819
6679
  priceFactor: gasPriceFactor,
5820
6680
  tip: transactionRequest.tip
5821
6681
  }).add(1);
5822
- let gasLimit = bn17(0);
6682
+ let gasLimit = bn18(0);
5823
6683
  if (isTransactionTypeScript(transactionRequest)) {
5824
6684
  gasLimit = transactionRequest.gasLimit;
5825
6685
  if (transactionRequest.gasLimit.eq(0)) {
@@ -5832,7 +6692,7 @@ var Provider = class _Provider {
5832
6692
  }
5833
6693
  const maxGas = transactionRequest.calculateMaxGas(chainInfo, minGas);
5834
6694
  const maxFee = calculateGasFee({
5835
- gasPrice: bn17(gasPrice),
6695
+ gasPrice: bn18(gasPrice),
5836
6696
  gas: maxGas,
5837
6697
  priceFactor: gasPriceFactor,
5838
6698
  tip: transactionRequest.tip
@@ -5862,7 +6722,7 @@ var Provider = class _Provider {
5862
6722
  if (estimateTxDependencies) {
5863
6723
  return this.estimateTxDependencies(transactionRequest);
5864
6724
  }
5865
- const encodedTransactions = [hexlify18(transactionRequest.toTransactionBytes())];
6725
+ const encodedTransactions = [hexlify19(transactionRequest.toTransactionBytes())];
5866
6726
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
5867
6727
  encodedTransactions,
5868
6728
  utxoValidation: true
@@ -5885,13 +6745,16 @@ var Provider = class _Provider {
5885
6745
  * @param transactionCostParams - The transaction cost parameters (optional).
5886
6746
  *
5887
6747
  * @returns A promise that resolves to the transaction cost object.
6748
+ *
6749
+ * @deprecated Use provider.assembleTx instead
6750
+ * Check the migration guide https://docs.fuel.network/guide/assembling-transactions/migration-guide.html for more information.
5888
6751
  */
5889
6752
  async getTransactionCost(transactionRequestLike, { signatureCallback, gasPrice: gasPriceParam } = {}) {
5890
6753
  const txRequestClone = clone8(transactionRequestify(transactionRequestLike));
5891
6754
  const updateMaxFee = txRequestClone.maxFee.eq(0);
5892
6755
  const isScriptTransaction = isTransactionTypeScript(txRequestClone);
5893
6756
  if (isScriptTransaction) {
5894
- txRequestClone.gasLimit = bn17(0);
6757
+ txRequestClone.gasLimit = bn18(0);
5895
6758
  }
5896
6759
  const signedRequest = clone8(txRequestClone);
5897
6760
  let addedSignatures = 0;
@@ -5918,7 +6781,7 @@ var Provider = class _Provider {
5918
6781
  let dryRunStatus;
5919
6782
  let missingContractIds = [];
5920
6783
  let outputVariables = 0;
5921
- let gasUsed = bn17(0);
6784
+ let gasUsed = bn18(0);
5922
6785
  txRequestClone.maxFee = maxFee;
5923
6786
  if (isScriptTransaction) {
5924
6787
  txRequestClone.gasLimit = gasLimit;
@@ -5927,11 +6790,11 @@ var Provider = class _Provider {
5927
6790
  }
5928
6791
  ({ rawReceipts, receipts, missingContractIds, outputVariables, dryRunStatus } = await this.estimateTxDependencies(txRequestClone, { gasPrice }));
5929
6792
  if (dryRunStatus && "reason" in dryRunStatus) {
5930
- throw this.extractDryRunError(txRequestClone, receipts, dryRunStatus);
6793
+ throw this.extractDryRunError(txRequestClone, receipts, dryRunStatus.reason);
5931
6794
  }
5932
6795
  const { maxGasPerTx } = await this.getGasConfig();
5933
6796
  const pristineGasUsed = getGasUsedFromReceipts(receipts);
5934
- gasUsed = bn17(pristineGasUsed.muln(GAS_USED_MODIFIER)).max(maxGasPerTx.sub(minGas));
6797
+ gasUsed = bn18(pristineGasUsed.muln(GAS_USED_MODIFIER)).max(maxGasPerTx.sub(minGas));
5935
6798
  txRequestClone.gasLimit = gasUsed;
5936
6799
  ({ maxFee, maxGas, minFee, minGas } = await this.estimateTxGasAndFee({
5937
6800
  transactionRequest: txRequestClone,
@@ -5960,6 +6823,102 @@ var Provider = class _Provider {
5960
6823
  transactionSummary
5961
6824
  };
5962
6825
  }
6826
+ /**
6827
+ * Assembles a transaction by completely estimating and funding it.
6828
+ *
6829
+ * @param params - Parameters used to assemble the transaction.
6830
+ *
6831
+ * @returns The assembled transaction request, estimated gas price, and receipts
6832
+ */
6833
+ async assembleTx(params) {
6834
+ const {
6835
+ request,
6836
+ reserveGas,
6837
+ resourcesIdsToIgnore,
6838
+ feePayerAccount,
6839
+ blockHorizon = 10,
6840
+ estimatePredicates = true,
6841
+ accountCoinQuantities = []
6842
+ } = params;
6843
+ const allAddresses = /* @__PURE__ */ new Set();
6844
+ const baseAssetId = await this.getBaseAssetId();
6845
+ let feePayerIndex = -1;
6846
+ let baseAssetChange;
6847
+ const requiredBalances = accountCoinQuantities.map((quantity, index) => {
6848
+ const { amount, assetId, account = feePayerAccount, changeOutputAccount } = quantity;
6849
+ const changeAccountAddress = changeOutputAccount ? changeOutputAccount.address.toB256() : account.address.toB256();
6850
+ allAddresses.add(account.address.toB256());
6851
+ const changePolicy = {
6852
+ change: changeAccountAddress
6853
+ };
6854
+ if (assetId === baseAssetId) {
6855
+ baseAssetChange = changePolicy.change;
6856
+ }
6857
+ if (account.address.equals(feePayerAccount.address)) {
6858
+ feePayerIndex = index;
6859
+ }
6860
+ const requiredBalance = {
6861
+ account: resolveAccountForAssembleTxParams(account),
6862
+ amount: bn18(amount).toString(10),
6863
+ assetId,
6864
+ changePolicy
6865
+ };
6866
+ return requiredBalance;
6867
+ });
6868
+ if (feePayerIndex === -1) {
6869
+ allAddresses.add(feePayerAccount.address.toB256());
6870
+ const newLength = requiredBalances.push({
6871
+ account: resolveAccountForAssembleTxParams(feePayerAccount),
6872
+ amount: bn18(0).toString(10),
6873
+ // Since the correct fee amount cannot be determined yet, we can use 0
6874
+ assetId: baseAssetId,
6875
+ changePolicy: {
6876
+ change: baseAssetChange || feePayerAccount.address.toB256()
6877
+ }
6878
+ });
6879
+ feePayerIndex = newLength - 1;
6880
+ }
6881
+ const excludeInput = await this.adjustResourcesToIgnoreForAddresses(
6882
+ Array.from(allAddresses),
6883
+ resourcesIdsToIgnore
6884
+ );
6885
+ const {
6886
+ assembleTx: { status, transaction: gqlTransaction, gasPrice }
6887
+ } = await this.operations.assembleTx({
6888
+ tx: hexlify19(request.toTransactionBytes()),
6889
+ blockHorizon: String(blockHorizon),
6890
+ feeAddressIndex: String(feePayerIndex),
6891
+ requiredBalances,
6892
+ estimatePredicates,
6893
+ excludeInput,
6894
+ reserveGas: reserveGas ? reserveGas.toString(10) : void 0
6895
+ });
6896
+ if (status.type === "DryRunFailureStatus") {
6897
+ const parsedReceipts = status.receipts.map(deserializeReceipt);
6898
+ throw this.extractDryRunError(request, parsedReceipts, status.reason);
6899
+ }
6900
+ request.witnesses = gqlTransaction.witnesses || request.witnesses;
6901
+ request.inputs = gqlTransaction.inputs?.map(deserializeInput) || request.inputs;
6902
+ request.outputs = gqlTransaction.outputs?.map(deserializeOutput) || request.outputs;
6903
+ if (gqlTransaction.policies?.maxFee) {
6904
+ request.maxFee = bn18(gqlTransaction.policies.maxFee);
6905
+ }
6906
+ if (gqlTransaction.scriptGasLimit) {
6907
+ request.gasLimit = bn18(gqlTransaction.scriptGasLimit);
6908
+ }
6909
+ const rawReceipts = status.receipts;
6910
+ const chainId = await this.getChainId();
6911
+ request.updateState(chainId, "funded", {
6912
+ gasPrice: gasPrice.toString(),
6913
+ receipts: rawReceipts
6914
+ });
6915
+ return {
6916
+ assembledRequest: request,
6917
+ gasPrice: bn18(gasPrice),
6918
+ receipts: status.receipts.map(deserializeReceipt),
6919
+ rawReceipts
6920
+ };
6921
+ }
5963
6922
  /**
5964
6923
  * Returns coins for the given owner.
5965
6924
  *
@@ -5978,15 +6937,15 @@ var Provider = class _Provider {
5978
6937
  paginationLimit: RESOURCES_PAGE_SIZE_LIMIT,
5979
6938
  inputArgs: paginationArgs
5980
6939
  }),
5981
- filter: { owner: ownerAddress.toB256(), assetId: assetId && hexlify18(assetId) }
6940
+ filter: { owner: ownerAddress.toB256(), assetId: assetId && hexlify19(assetId) }
5982
6941
  });
5983
6942
  const coins = edges.map(({ node }) => ({
5984
6943
  id: node.utxoId,
5985
6944
  assetId: node.assetId,
5986
- amount: bn17(node.amount),
6945
+ amount: bn18(node.amount),
5987
6946
  owner: ownerAddress,
5988
- blockCreated: bn17(node.blockCreated),
5989
- txCreatedIdx: bn17(node.txCreatedIdx)
6947
+ blockCreated: bn18(node.blockCreated),
6948
+ txCreatedIdx: bn18(node.txCreatedIdx)
5990
6949
  }));
5991
6950
  return {
5992
6951
  coins,
@@ -5998,47 +6957,32 @@ var Provider = class _Provider {
5998
6957
  *
5999
6958
  * @param owner - The address to get resources for.
6000
6959
  * @param quantities - The coin quantities to get.
6001
- * @param excludedIds - IDs of excluded resources from the selection (optional).
6960
+ * @param resourcesIdsToIgnore - IDs of excluded resources from the selection (optional).
6002
6961
  * @returns A promise that resolves to the resources.
6003
6962
  */
6004
- async getResourcesToSpend(owner, quantities, excludedIds) {
6963
+ async getResourcesToSpend(owner, quantities, resourcesIdsToIgnore) {
6005
6964
  const ownerAddress = new Address3(owner);
6006
- let idsToExclude = {
6007
- messages: excludedIds?.messages?.map((nonce) => hexlify18(nonce)) || [],
6008
- utxos: excludedIds?.utxos?.map((id) => hexlify18(id)) || []
6009
- };
6010
- if (this.cache) {
6011
- const cached = this.cache.getActiveData(ownerAddress.toB256());
6012
- if (cached.utxos.length || cached.messages.length) {
6013
- const {
6014
- consensusParameters: {
6015
- txParameters: { maxInputs }
6016
- }
6017
- } = await this.getChain();
6018
- idsToExclude = adjustResourcesToExclude({
6019
- userInput: idsToExclude,
6020
- cached,
6021
- maxInputs: maxInputs.toNumber()
6022
- });
6023
- }
6024
- }
6965
+ const excludedIds = await this.adjustResourcesToIgnoreForAddresses(
6966
+ [ownerAddress.b256Address],
6967
+ resourcesIdsToIgnore
6968
+ );
6025
6969
  const coinsQuery = {
6026
6970
  owner: ownerAddress.toB256(),
6027
6971
  queryPerAsset: quantities.map(coinQuantityfy).map(({ assetId, amount, max: maxPerAsset }) => ({
6028
- assetId: hexlify18(assetId),
6029
- amount: (amount.eqn(0) ? bn17(1) : amount).toString(10),
6972
+ assetId: hexlify19(assetId),
6973
+ amount: (amount.eqn(0) ? bn18(1) : amount).toString(10),
6030
6974
  max: maxPerAsset ? maxPerAsset.toString(10) : void 0
6031
6975
  })),
6032
- excludedIds: idsToExclude
6976
+ excludedIds
6033
6977
  };
6034
6978
  const result = await this.operations.getCoinsToSpend(coinsQuery);
6035
6979
  const coins = result.coinsToSpend.flat().map((coin) => {
6036
6980
  switch (coin.type) {
6037
6981
  case "MessageCoin":
6038
6982
  return {
6039
- amount: bn17(coin.amount),
6983
+ amount: bn18(coin.amount),
6040
6984
  assetId: coin.assetId,
6041
- daHeight: bn17(coin.daHeight),
6985
+ daHeight: bn18(coin.daHeight),
6042
6986
  sender: new Address3(coin.sender),
6043
6987
  recipient: new Address3(coin.recipient),
6044
6988
  nonce: coin.nonce
@@ -6046,11 +6990,11 @@ var Provider = class _Provider {
6046
6990
  case "Coin":
6047
6991
  return {
6048
6992
  id: coin.utxoId,
6049
- amount: bn17(coin.amount),
6993
+ amount: bn18(coin.amount),
6050
6994
  assetId: coin.assetId,
6051
6995
  owner: ownerAddress,
6052
- blockCreated: bn17(coin.blockCreated),
6053
- txCreatedIdx: bn17(coin.txCreatedIdx)
6996
+ blockCreated: bn18(coin.blockCreated),
6997
+ txCreatedIdx: bn18(coin.txCreatedIdx)
6054
6998
  };
6055
6999
  default:
6056
7000
  return null;
@@ -6088,7 +7032,7 @@ var Provider = class _Provider {
6088
7032
  block = latestBlock;
6089
7033
  } else {
6090
7034
  const isblockId = typeof idOrHeight === "string" && isB256(idOrHeight);
6091
- const variables = isblockId ? { blockId: idOrHeight } : { height: bn17(idOrHeight).toString(10) };
7035
+ const variables = isblockId ? { blockId: idOrHeight } : { height: bn18(idOrHeight).toString(10) };
6092
7036
  const response = await this.operations.getBlock(variables);
6093
7037
  block = response.block;
6094
7038
  }
@@ -6098,11 +7042,11 @@ var Provider = class _Provider {
6098
7042
  const { header, height, id, transactions } = block;
6099
7043
  return {
6100
7044
  id,
6101
- height: bn17(height),
7045
+ height: bn18(height),
6102
7046
  time: header.time,
6103
7047
  header: {
6104
7048
  applicationHash: header.applicationHash,
6105
- daHeight: bn17(header.daHeight),
7049
+ daHeight: bn18(header.daHeight),
6106
7050
  eventInboxRoot: header.eventInboxRoot,
6107
7051
  messageOutboxRoot: header.messageOutboxRoot,
6108
7052
  prevRoot: header.prevRoot,
@@ -6130,11 +7074,11 @@ var Provider = class _Provider {
6130
7074
  });
6131
7075
  const blocks = edges.map(({ node: block }) => ({
6132
7076
  id: block.id,
6133
- height: bn17(block.height),
7077
+ height: bn18(block.height),
6134
7078
  time: block.header.time,
6135
7079
  header: {
6136
7080
  applicationHash: block.header.applicationHash,
6137
- daHeight: bn17(block.header.daHeight),
7081
+ daHeight: bn18(block.header.daHeight),
6138
7082
  eventInboxRoot: block.header.eventInboxRoot,
6139
7083
  messageOutboxRoot: block.header.messageOutboxRoot,
6140
7084
  prevRoot: block.header.prevRoot,
@@ -6155,13 +7099,13 @@ var Provider = class _Provider {
6155
7099
  async getBlockWithTransactions(idOrHeight) {
6156
7100
  let variables;
6157
7101
  if (typeof idOrHeight === "number") {
6158
- variables = { blockHeight: bn17(idOrHeight).toString(10) };
7102
+ variables = { blockHeight: bn18(idOrHeight).toString(10) };
6159
7103
  } else if (idOrHeight === "latest") {
6160
7104
  variables = { blockHeight: (await this.getBlockNumber()).toString() };
6161
7105
  } else if (typeof idOrHeight === "string" && isB256(idOrHeight)) {
6162
7106
  variables = { blockId: idOrHeight };
6163
7107
  } else {
6164
- variables = { blockHeight: bn17(idOrHeight).toString() };
7108
+ variables = { blockHeight: bn18(idOrHeight).toString() };
6165
7109
  }
6166
7110
  const { block } = await this.operations.getBlockWithTransactions(variables);
6167
7111
  if (!block) {
@@ -6169,11 +7113,11 @@ var Provider = class _Provider {
6169
7113
  }
6170
7114
  return {
6171
7115
  id: block.id,
6172
- height: bn17(block.height, 10),
7116
+ height: bn18(block.height, 10),
6173
7117
  time: block.header.time,
6174
7118
  header: {
6175
7119
  applicationHash: block.header.applicationHash,
6176
- daHeight: bn17(block.header.daHeight),
7120
+ daHeight: bn18(block.header.daHeight),
6177
7121
  eventInboxRoot: block.header.eventInboxRoot,
6178
7122
  messageOutboxRoot: block.header.messageOutboxRoot,
6179
7123
  prevRoot: block.header.prevRoot,
@@ -6183,7 +7127,7 @@ var Provider = class _Provider {
6183
7127
  },
6184
7128
  transactionIds: block.transactions.map((tx) => tx.id),
6185
7129
  transactions: block.transactions.map(
6186
- (tx) => new TransactionCoder5().decode(arrayify13(tx.rawPayload), 0)?.[0]
7130
+ (tx) => new TransactionCoder6().decode(arrayify13(tx.rawPayload), 0)?.[0]
6187
7131
  )
6188
7132
  };
6189
7133
  }
@@ -6199,12 +7143,12 @@ var Provider = class _Provider {
6199
7143
  return null;
6200
7144
  }
6201
7145
  try {
6202
- return new TransactionCoder5().decode(
7146
+ return new TransactionCoder6().decode(
6203
7147
  arrayify13(transaction.rawPayload),
6204
7148
  0
6205
7149
  )?.[0];
6206
7150
  } catch (error) {
6207
- if (error instanceof FuelError19 && error.code === ErrorCode16.UNSUPPORTED_TRANSACTION_TYPE) {
7151
+ if (error instanceof FuelError20 && error.code === ErrorCode17.UNSUPPORTED_TRANSACTION_TYPE) {
6208
7152
  console.warn("Unsupported transaction type encountered");
6209
7153
  return null;
6210
7154
  }
@@ -6225,12 +7169,12 @@ var Provider = class _Provider {
6225
7169
  paginationLimit: TRANSACTIONS_PAGE_SIZE_LIMIT
6226
7170
  })
6227
7171
  });
6228
- const coder = new TransactionCoder5();
7172
+ const coder = new TransactionCoder6();
6229
7173
  const transactions = edges.map(({ node: { rawPayload } }) => {
6230
7174
  try {
6231
7175
  return coder.decode(arrayify13(rawPayload), 0)[0];
6232
7176
  } catch (error) {
6233
- if (error instanceof FuelError19 && error.code === ErrorCode16.UNSUPPORTED_TRANSACTION_TYPE) {
7177
+ if (error instanceof FuelError20 && error.code === ErrorCode17.UNSUPPORTED_TRANSACTION_TYPE) {
6234
7178
  console.warn("Unsupported transaction type encountered");
6235
7179
  return null;
6236
7180
  }
@@ -6277,9 +7221,9 @@ var Provider = class _Provider {
6277
7221
  async getContractBalance(contractId, assetId) {
6278
7222
  const { contractBalance } = await this.operations.getContractBalance({
6279
7223
  contract: new Address3(contractId).toB256(),
6280
- asset: hexlify18(assetId)
7224
+ asset: hexlify19(assetId)
6281
7225
  });
6282
- return bn17(contractBalance.amount, 10);
7226
+ return bn18(contractBalance.amount, 10);
6283
7227
  }
6284
7228
  /**
6285
7229
  * Returns the balance for the given owner for the given asset ID.
@@ -6291,9 +7235,9 @@ var Provider = class _Provider {
6291
7235
  async getBalance(owner, assetId) {
6292
7236
  const { balance } = await this.operations.getBalanceV2({
6293
7237
  owner: new Address3(owner).toB256(),
6294
- assetId: hexlify18(assetId)
7238
+ assetId: hexlify19(assetId)
6295
7239
  });
6296
- return bn17(balance.amountU128, 10);
7240
+ return bn18(balance.amountU128, 10);
6297
7241
  }
6298
7242
  /**
6299
7243
  * Returns balances for the given owner.
@@ -6320,7 +7264,7 @@ var Provider = class _Provider {
6320
7264
  });
6321
7265
  const balances = edges.map(({ node }) => ({
6322
7266
  assetId: node.assetId,
6323
- amount: bn17(node.amountU128)
7267
+ amount: bn18(node.amountU128)
6324
7268
  }));
6325
7269
  return {
6326
7270
  balances,
@@ -6349,15 +7293,15 @@ var Provider = class _Provider {
6349
7293
  sender: node.sender,
6350
7294
  recipient: node.recipient,
6351
7295
  nonce: node.nonce,
6352
- amount: bn17(node.amount),
7296
+ amount: bn18(node.amount),
6353
7297
  data: node.data
6354
7298
  }),
6355
7299
  sender: new Address3(node.sender),
6356
7300
  recipient: new Address3(node.recipient),
6357
7301
  nonce: node.nonce,
6358
- amount: bn17(node.amount),
7302
+ amount: bn18(node.amount),
6359
7303
  data: InputMessageCoder2.decodeData(node.data),
6360
- daHeight: bn17(node.daHeight)
7304
+ daHeight: bn18(node.daHeight)
6361
7305
  }));
6362
7306
  return {
6363
7307
  messages,
@@ -6379,8 +7323,8 @@ var Provider = class _Provider {
6379
7323
  nonce
6380
7324
  };
6381
7325
  if (commitBlockId && commitBlockHeight) {
6382
- throw new FuelError19(
6383
- ErrorCode16.INVALID_INPUT_PARAMETERS,
7326
+ throw new FuelError20(
7327
+ ErrorCode17.INVALID_INPUT_PARAMETERS,
6384
7328
  "commitBlockId and commitBlockHeight cannot be used together"
6385
7329
  );
6386
7330
  }
@@ -6411,19 +7355,19 @@ var Provider = class _Provider {
6411
7355
  } = result.messageProof;
6412
7356
  return {
6413
7357
  messageProof: {
6414
- proofIndex: bn17(messageProof.proofIndex),
7358
+ proofIndex: bn18(messageProof.proofIndex),
6415
7359
  proofSet: messageProof.proofSet
6416
7360
  },
6417
7361
  blockProof: {
6418
- proofIndex: bn17(blockProof.proofIndex),
7362
+ proofIndex: bn18(blockProof.proofIndex),
6419
7363
  proofSet: blockProof.proofSet
6420
7364
  },
6421
7365
  messageBlockHeader: {
6422
7366
  id: messageBlockHeader.id,
6423
- daHeight: bn17(messageBlockHeader.daHeight),
7367
+ daHeight: bn18(messageBlockHeader.daHeight),
6424
7368
  transactionsCount: Number(messageBlockHeader.transactionsCount),
6425
7369
  transactionsRoot: messageBlockHeader.transactionsRoot,
6426
- height: bn17(messageBlockHeader.height),
7370
+ height: bn18(messageBlockHeader.height),
6427
7371
  prevRoot: messageBlockHeader.prevRoot,
6428
7372
  time: messageBlockHeader.time,
6429
7373
  applicationHash: messageBlockHeader.applicationHash,
@@ -6435,10 +7379,10 @@ var Provider = class _Provider {
6435
7379
  },
6436
7380
  commitBlockHeader: {
6437
7381
  id: commitBlockHeader.id,
6438
- daHeight: bn17(commitBlockHeader.daHeight),
7382
+ daHeight: bn18(commitBlockHeader.daHeight),
6439
7383
  transactionsCount: Number(commitBlockHeader.transactionsCount),
6440
7384
  transactionsRoot: commitBlockHeader.transactionsRoot,
6441
- height: bn17(commitBlockHeader.height),
7385
+ height: bn18(commitBlockHeader.height),
6442
7386
  prevRoot: commitBlockHeader.prevRoot,
6443
7387
  time: commitBlockHeader.time,
6444
7388
  applicationHash: commitBlockHeader.applicationHash,
@@ -6451,7 +7395,7 @@ var Provider = class _Provider {
6451
7395
  sender: new Address3(sender),
6452
7396
  recipient: new Address3(recipient),
6453
7397
  nonce,
6454
- amount: bn17(amount),
7398
+ amount: bn18(amount),
6455
7399
  data
6456
7400
  };
6457
7401
  }
@@ -6462,7 +7406,7 @@ var Provider = class _Provider {
6462
7406
  */
6463
7407
  async getLatestGasPrice() {
6464
7408
  const { latestGasPrice } = await this.operations.getLatestGasPrice();
6465
- return bn17(latestGasPrice.gasPrice);
7409
+ return bn18(latestGasPrice.gasPrice);
6466
7410
  }
6467
7411
  /**
6468
7412
  * Returns the estimate gas price for the given block horizon.
@@ -6474,7 +7418,7 @@ var Provider = class _Provider {
6474
7418
  const { estimateGasPrice } = await this.operations.estimateGasPrice({
6475
7419
  blockHorizon: String(blockHorizon)
6476
7420
  });
6477
- return bn17(estimateGasPrice.gasPrice);
7421
+ return bn18(estimateGasPrice.gasPrice);
6478
7422
  }
6479
7423
  /**
6480
7424
  * Returns Message Proof for given transaction id and the message id from MessageOut receipt.
@@ -6495,10 +7439,10 @@ var Provider = class _Provider {
6495
7439
  */
6496
7440
  async produceBlocks(amount, startTime) {
6497
7441
  const { produceBlocks: latestBlockHeight } = await this.operations.produceBlocks({
6498
- blocksToProduce: bn17(amount).toString(10),
7442
+ blocksToProduce: bn18(amount).toString(10),
6499
7443
  startTimestamp: startTime ? DateTime2.fromUnixMilliseconds(startTime).toTai64() : void 0
6500
7444
  });
6501
- return bn17(latestBlockHeight);
7445
+ return bn18(latestBlockHeight);
6502
7446
  }
6503
7447
  /**
6504
7448
  * Check if the given ID is an account.
@@ -6566,15 +7510,15 @@ var Provider = class _Provider {
6566
7510
  sender: rawMessage.sender,
6567
7511
  recipient: rawMessage.recipient,
6568
7512
  nonce,
6569
- amount: bn17(rawMessage.amount),
7513
+ amount: bn18(rawMessage.amount),
6570
7514
  data: rawMessage.data
6571
7515
  }),
6572
7516
  sender: new Address3(rawMessage.sender),
6573
7517
  recipient: new Address3(rawMessage.recipient),
6574
7518
  nonce,
6575
- amount: bn17(rawMessage.amount),
7519
+ amount: bn18(rawMessage.amount),
6576
7520
  data: InputMessageCoder2.decodeData(rawMessage.data),
6577
- daHeight: bn17(rawMessage.daHeight)
7521
+ daHeight: bn18(rawMessage.daHeight)
6578
7522
  };
6579
7523
  return message;
6580
7524
  }
@@ -6596,11 +7540,10 @@ var Provider = class _Provider {
6596
7540
  /**
6597
7541
  * @hidden
6598
7542
  */
6599
- extractDryRunError(transactionRequest, receipts, dryRunStatus) {
6600
- const status = dryRunStatus;
7543
+ extractDryRunError(transactionRequest, receipts, reason) {
6601
7544
  let logs = [];
6602
7545
  let groupedLogs = {};
6603
- if (transactionRequest.abis) {
7546
+ if (transactionRequest.type === TransactionType11.Script && transactionRequest.abis) {
6604
7547
  ({ logs, groupedLogs } = getAllDecodedLogs({
6605
7548
  receipts,
6606
7549
  mainAbi: transactionRequest.abis.main,
@@ -6611,7 +7554,7 @@ var Provider = class _Provider {
6611
7554
  logs,
6612
7555
  groupedLogs,
6613
7556
  receipts,
6614
- statusReason: status.reason
7557
+ statusReason: reason
6615
7558
  });
6616
7559
  }
6617
7560
  /**
@@ -6631,29 +7574,68 @@ var Provider = class _Provider {
6631
7574
  parseEstimatePredicatesResponse(transactionRequest, { inputs }) {
6632
7575
  if (inputs) {
6633
7576
  inputs.forEach((input, i) => {
6634
- if (input && "predicateGasUsed" in input && bn17(input.predicateGasUsed).gt(0)) {
7577
+ if (input && "predicateGasUsed" in input && bn18(input.predicateGasUsed).gt(0)) {
6635
7578
  transactionRequest.inputs[i].predicateGasUsed = input.predicateGasUsed;
6636
7579
  }
6637
7580
  });
6638
7581
  }
6639
7582
  return transactionRequest;
6640
7583
  }
7584
+ /**
7585
+ * @hidden
7586
+ *
7587
+ * This helper adjusts the resources to be excluded for a given set of addresses.
7588
+ * Supporting multiple addresses is important because of the `assembleTx` method,
7589
+ * which may be invoked with different addresses. It handles both messages and UTXOs,
7590
+ * ensuring the total number of inputs does not exceed the maximum allowed by the chain's
7591
+ * consensus parameters. The resources specified in the `resourcesIdsToIgnore` parameter have priority
7592
+ * over those retrieved from the cache.
7593
+ */
7594
+ async adjustResourcesToIgnoreForAddresses(addresses, resourcesIdsToIgnore) {
7595
+ const final = {
7596
+ messages: resourcesIdsToIgnore?.messages?.map((nonce) => hexlify19(nonce)) || [],
7597
+ utxos: resourcesIdsToIgnore?.utxos?.map((id) => hexlify19(id)) || []
7598
+ };
7599
+ if (this.cache) {
7600
+ const cache2 = this.cache;
7601
+ const allCached = addresses.map((address) => cache2.getActiveData(address));
7602
+ const {
7603
+ consensusParameters: {
7604
+ txParameters: { maxInputs: maxInputsBn }
7605
+ }
7606
+ } = await this.getChain();
7607
+ const maxInputs = maxInputsBn.toNumber();
7608
+ for (let i = 0; i < allCached.length; i++) {
7609
+ let total = final.utxos.length + final.messages.length;
7610
+ if (total >= maxInputs) {
7611
+ break;
7612
+ }
7613
+ final.utxos = [...final.utxos, ...allCached[i].utxos.slice(0, maxInputs - total)];
7614
+ total = final.utxos.length + final.messages.length;
7615
+ if (total >= maxInputs) {
7616
+ break;
7617
+ }
7618
+ final.messages = [...final.messages, ...allCached[i].messages.slice(0, maxInputs - total)];
7619
+ }
7620
+ }
7621
+ return final;
7622
+ }
6641
7623
  };
6642
7624
 
6643
7625
  // src/providers/transaction-summary/get-transaction-summary.ts
6644
- import { ErrorCode as ErrorCode17, FuelError as FuelError20 } from "@fuel-ts/errors";
6645
- import { bn as bn18 } from "@fuel-ts/math";
6646
- import { TransactionCoder as TransactionCoder6 } from "@fuel-ts/transactions";
7626
+ import { ErrorCode as ErrorCode18, FuelError as FuelError21 } from "@fuel-ts/errors";
7627
+ import { bn as bn19 } from "@fuel-ts/math";
7628
+ import { TransactionCoder as TransactionCoder7 } from "@fuel-ts/transactions";
6647
7629
  import { arrayify as arrayify14 } from "@fuel-ts/utils";
6648
7630
 
6649
7631
  // src/providers/transaction-summary/assemble-transaction-summary-from-serialized.ts
6650
- import { bn as bn19 } from "@fuel-ts/math";
6651
- import { TransactionCoder as TransactionCoder7 } from "@fuel-ts/transactions";
7632
+ import { bn as bn20 } from "@fuel-ts/math";
7633
+ import { TransactionCoder as TransactionCoder8 } from "@fuel-ts/transactions";
6652
7634
  import { arrayify as arrayify15 } from "@fuel-ts/utils";
6653
7635
 
6654
7636
  // src/test-utils/test-asset-id.ts
6655
7637
  import { randomBytes as randomBytes4 } from "@fuel-ts/crypto";
6656
- import { hexlify as hexlify19 } from "@fuel-ts/utils";
7638
+ import { hexlify as hexlify20 } from "@fuel-ts/utils";
6657
7639
  var TestAssetId = class _TestAssetId {
6658
7640
  constructor(value) {
6659
7641
  this.value = value;
@@ -6670,7 +7652,7 @@ var TestAssetId = class _TestAssetId {
6670
7652
  static random(count = 1) {
6671
7653
  const assetIds = [];
6672
7654
  for (let i = 0; i < count; i++) {
6673
- assetIds.push(new _TestAssetId(hexlify19(randomBytes4(32))));
7655
+ assetIds.push(new _TestAssetId(hexlify20(randomBytes4(32))));
6674
7656
  }
6675
7657
  return assetIds;
6676
7658
  }
@@ -6678,39 +7660,24 @@ var TestAssetId = class _TestAssetId {
6678
7660
 
6679
7661
  // src/test-utils/wallet-config.ts
6680
7662
  import { randomBytes as randomBytes8 } from "@fuel-ts/crypto";
6681
- import { FuelError as FuelError26 } from "@fuel-ts/errors";
6682
- import { bn as bn22 } from "@fuel-ts/math";
6683
- import { defaultSnapshotConfigs as defaultSnapshotConfigs2, hexlify as hexlify25 } from "@fuel-ts/utils";
7663
+ import { FuelError as FuelError27 } from "@fuel-ts/errors";
7664
+ import { bn as bn23 } from "@fuel-ts/math";
7665
+ import { defaultSnapshotConfigs as defaultSnapshotConfigs2, hexlify as hexlify26 } from "@fuel-ts/utils";
6684
7666
 
6685
7667
  // src/wallet/base-wallet-unlocked.ts
6686
7668
  import { hashMessage } from "@fuel-ts/hasher";
6687
- import { hexlify as hexlify22 } from "@fuel-ts/utils";
7669
+ import { hexlify as hexlify23 } from "@fuel-ts/utils";
6688
7670
 
6689
7671
  // src/account.ts
6690
7672
  import { UTXO_ID_LEN as UTXO_ID_LEN3 } from "@fuel-ts/abi-coder";
6691
7673
  import { Address as Address5 } from "@fuel-ts/address";
6692
7674
  import { randomBytes as randomBytes5 } from "@fuel-ts/crypto";
6693
- import { ErrorCode as ErrorCode18, FuelError as FuelError21 } from "@fuel-ts/errors";
6694
- import { bn as bn20 } from "@fuel-ts/math";
6695
- import { InputType as InputType7 } from "@fuel-ts/transactions";
6696
- import { arrayify as arrayify17, hexlify as hexlify20, isDefined as isDefined3 } from "@fuel-ts/utils";
7675
+ import { ErrorCode as ErrorCode19, FuelError as FuelError22 } from "@fuel-ts/errors";
7676
+ import { bn as bn21 } from "@fuel-ts/math";
7677
+ import { InputType as InputType8, OutputType as OutputType9 } from "@fuel-ts/transactions";
7678
+ import { arrayify as arrayify17, hexlify as hexlify21, isDefined as isDefined4 } from "@fuel-ts/utils";
6697
7679
  import { clone as clone9 } from "ramda";
6698
7680
 
6699
- // src/providers/utils/merge-quantities.ts
6700
- var mergeQuantities = /* @__PURE__ */ __name((...coinQuantities) => {
6701
- const resultMap = {};
6702
- function addToMap({ amount, assetId }) {
6703
- if (resultMap[assetId]) {
6704
- resultMap[assetId] = resultMap[assetId].add(amount);
6705
- } else {
6706
- resultMap[assetId] = amount;
6707
- }
6708
- }
6709
- __name(addToMap, "addToMap");
6710
- coinQuantities.forEach((arr) => arr.forEach(addToMap));
6711
- return Object.entries(resultMap).map(([assetId, amount]) => ({ assetId, amount }));
6712
- }, "mergeQuantities");
6713
-
6714
7681
  // src/types.ts
6715
7682
  var AbstractAccount = class {
6716
7683
  static {
@@ -6758,6 +7725,18 @@ var assembleTransferToContractScript = /* @__PURE__ */ __name(async (transferPar
6758
7725
  return { script, scriptData };
6759
7726
  }, "assembleTransferToContractScript");
6760
7727
 
7728
+ // src/utils/split-coins-into-batches.ts
7729
+ var splitCoinsIntoBatches = /* @__PURE__ */ __name((coins, maxBatchLength) => {
7730
+ const batchesNum = Math.ceil(coins.length / maxBatchLength);
7731
+ const batches = [];
7732
+ for (let i = 0; i < batchesNum; i += 1) {
7733
+ const batchStart = i * maxBatchLength;
7734
+ const batchEnd = (i + 1) * maxBatchLength;
7735
+ batches.push(coins.slice(batchStart, batchEnd));
7736
+ }
7737
+ return batches;
7738
+ }, "splitCoinsIntoBatches");
7739
+
6761
7740
  // src/account.ts
6762
7741
  var MAX_FUNDING_ATTEMPTS = 5;
6763
7742
  var Account = class extends AbstractAccount {
@@ -6798,7 +7777,7 @@ var Account = class extends AbstractAccount {
6798
7777
  */
6799
7778
  get provider() {
6800
7779
  if (!this._provider) {
6801
- throw new FuelError21(ErrorCode18.MISSING_PROVIDER, "Provider not set");
7780
+ throw new FuelError22(ErrorCode19.MISSING_PROVIDER, "Provider not set");
6802
7781
  }
6803
7782
  return this._provider;
6804
7783
  }
@@ -6824,11 +7803,11 @@ var Account = class extends AbstractAccount {
6824
7803
  * Retrieves resources satisfying the spend query for the account.
6825
7804
  *
6826
7805
  * @param quantities - Quantities of resources to be obtained.
6827
- * @param excludedIds - IDs of resources to be excluded from the query (optional).
7806
+ * @param resourcesIdsToIgnore - IDs of resources to be excluded from the query (optional).
6828
7807
  * @returns A promise that resolves to an array of Resources.
6829
7808
  */
6830
- async getResourcesToSpend(quantities, excludedIds) {
6831
- return this.provider.getResourcesToSpend(this.address, quantities, excludedIds);
7809
+ async getResourcesToSpend(quantities, resourcesIdsToIgnore) {
7810
+ return this.provider.getResourcesToSpend(this.address, quantities, resourcesIdsToIgnore);
6832
7811
  }
6833
7812
  /**
6834
7813
  * Retrieves coins owned by the account.
@@ -6873,6 +7852,9 @@ var Account = class extends AbstractAccount {
6873
7852
  * @param request - The transaction request to fund.
6874
7853
  * @param params - The estimated transaction parameters.
6875
7854
  * @returns A promise that resolves to the funded transaction request.
7855
+ *
7856
+ * @deprecated Use provider.assembleTx instead
7857
+ * Check the migration guide https://docs.fuel.network/guide/assembling-transactions/migration-guide.html for more information.
6876
7858
  */
6877
7859
  async fund(request, params) {
6878
7860
  const {
@@ -6886,9 +7868,9 @@ var Account = class extends AbstractAccount {
6886
7868
  const chainId = await this.provider.getChainId();
6887
7869
  const fee = request.maxFee;
6888
7870
  const baseAssetId = await this.provider.getBaseAssetId();
6889
- const requiredInBaseAsset = requiredQuantities.find((quantity) => quantity.assetId === baseAssetId)?.amount || bn20(0);
7871
+ const requiredInBaseAsset = requiredQuantities.find((quantity) => quantity.assetId === baseAssetId)?.amount || bn21(0);
6890
7872
  const requiredQuantitiesWithFee = addAmountToCoinQuantities({
6891
- amount: bn20(fee),
7873
+ amount: bn21(fee),
6892
7874
  assetId: baseAssetId,
6893
7875
  coinQuantities: requiredQuantities
6894
7876
  });
@@ -6896,7 +7878,7 @@ var Account = class extends AbstractAccount {
6896
7878
  requiredQuantitiesWithFee.forEach(({ amount, assetId }) => {
6897
7879
  quantitiesDict[assetId] = {
6898
7880
  required: amount,
6899
- owned: bn20(0)
7881
+ owned: bn21(0)
6900
7882
  };
6901
7883
  });
6902
7884
  request.inputs.filter(isRequestInputResource).forEach((input) => {
@@ -6957,8 +7939,8 @@ var Account = class extends AbstractAccount {
6957
7939
  fundingAttempts += 1;
6958
7940
  }
6959
7941
  if (needsToBeFunded) {
6960
- throw new FuelError21(
6961
- ErrorCode18.INSUFFICIENT_FUNDS_OR_MAX_COINS,
7942
+ throw new FuelError22(
7943
+ ErrorCode19.INSUFFICIENT_FUNDS_OR_MAX_COINS,
6962
7944
  `The account ${this.address} does not have enough base asset funds to cover the transaction execution.`
6963
7945
  );
6964
7946
  }
@@ -6995,7 +7977,14 @@ var Account = class extends AbstractAccount {
6995
7977
  amount,
6996
7978
  assetId: assetId || await this.provider.getBaseAssetId()
6997
7979
  });
6998
- request = await this.estimateAndFundTransaction(request, txParams);
7980
+ const { gasPrice, transactionRequest } = await this.assembleTx(request);
7981
+ request = await setAndValidateGasAndFeeForAssembledTx({
7982
+ gasPrice,
7983
+ provider: this.provider,
7984
+ transactionRequest,
7985
+ setGasLimit: txParams?.gasLimit,
7986
+ setMaxFee: txParams?.maxFee
7987
+ });
6999
7988
  return request;
7000
7989
  }
7001
7990
  /**
@@ -7021,7 +8010,14 @@ var Account = class extends AbstractAccount {
7021
8010
  async batchTransfer(transferParams, txParams = {}) {
7022
8011
  let request = new ScriptTransactionRequest(txParams);
7023
8012
  request = this.addBatchTransfer(request, transferParams);
7024
- request = await this.estimateAndFundTransaction(request, txParams);
8013
+ const { gasPrice, transactionRequest } = await this.assembleTx(request);
8014
+ request = await setAndValidateGasAndFeeForAssembledTx({
8015
+ gasPrice,
8016
+ provider: this.provider,
8017
+ transactionRequest,
8018
+ setGasLimit: txParams?.gasLimit,
8019
+ setMaxFee: txParams?.maxFee
8020
+ });
7025
8021
  return this.sendTransaction(request, { estimateTxDependencies: false });
7026
8022
  }
7027
8023
  /**
@@ -7073,12 +8069,12 @@ var Account = class extends AbstractAccount {
7073
8069
  const quantities = [];
7074
8070
  const defaultAssetId = await this.provider.getBaseAssetId();
7075
8071
  const transferParams = contractTransferParams.map((transferParam) => {
7076
- const amount = bn20(transferParam.amount);
8072
+ const amount = bn21(transferParam.amount);
7077
8073
  const contractAddress = new Address5(transferParam.contractId);
7078
- const assetId = transferParam.assetId ? hexlify20(transferParam.assetId) : defaultAssetId;
8074
+ const assetId = transferParam.assetId ? hexlify21(transferParam.assetId) : defaultAssetId;
7079
8075
  if (amount.lte(0)) {
7080
- throw new FuelError21(
7081
- ErrorCode18.INVALID_TRANSFER_AMOUNT,
8076
+ throw new FuelError22(
8077
+ ErrorCode19.INVALID_TRANSFER_AMOUNT,
7082
8078
  "Transfer amount must be a positive number."
7083
8079
  );
7084
8080
  }
@@ -7093,7 +8089,14 @@ var Account = class extends AbstractAccount {
7093
8089
  const { script, scriptData } = await assembleTransferToContractScript(transferParams);
7094
8090
  request.script = script;
7095
8091
  request.scriptData = scriptData;
7096
- request = await this.estimateAndFundTransaction(request, txParams, { quantities });
8092
+ const { gasPrice, transactionRequest } = await this.assembleTx(request, quantities);
8093
+ request = await setAndValidateGasAndFeeForAssembledTx({
8094
+ gasPrice,
8095
+ provider: this.provider,
8096
+ transactionRequest,
8097
+ setGasLimit: txParams?.gasLimit,
8098
+ setMaxFee: txParams?.maxFee
8099
+ });
7097
8100
  return this.sendTransaction(request);
7098
8101
  }
7099
8102
  /**
@@ -7110,7 +8113,7 @@ var Account = class extends AbstractAccount {
7110
8113
  "0x".concat(recipientAddress.toHexString().substring(2).padStart(64, "0"))
7111
8114
  );
7112
8115
  const amountDataArray = arrayify17(
7113
- "0x".concat(bn20(amount).toHex().substring(2).padStart(16, "0"))
8116
+ "0x".concat(bn21(amount).toHex().substring(2).padStart(16, "0"))
7114
8117
  );
7115
8118
  const script = new Uint8Array([
7116
8119
  ...arrayify17(withdrawScript.bytes),
@@ -7120,17 +8123,145 @@ var Account = class extends AbstractAccount {
7120
8123
  const params = { script, ...txParams };
7121
8124
  const baseAssetId = await this.provider.getBaseAssetId();
7122
8125
  let request = new ScriptTransactionRequest(params);
7123
- const quantities = [{ amount: bn20(amount), assetId: baseAssetId }];
7124
- const txCost = await this.getTransactionCost(request, { quantities });
7125
- request = this.validateGasLimitAndMaxFee({
7126
- transactionRequest: request,
7127
- gasUsed: txCost.gasUsed,
7128
- maxFee: txCost.maxFee,
7129
- txParams
8126
+ const quantities = [{ amount: bn21(amount), assetId: baseAssetId }];
8127
+ const { gasPrice, transactionRequest } = await this.assembleTx(request, quantities);
8128
+ request = await setAndValidateGasAndFeeForAssembledTx({
8129
+ gasPrice,
8130
+ provider: this.provider,
8131
+ transactionRequest,
8132
+ setGasLimit: txParams?.gasLimit,
8133
+ setMaxFee: txParams?.maxFee
7130
8134
  });
7131
- await this.fund(request, txCost);
7132
8135
  return this.sendTransaction(request);
7133
8136
  }
8137
+ /**
8138
+ * Consolidates base asset UTXOs into fewer, larger ones.
8139
+ *
8140
+ * Retrieves a limited number of base asset coins (as defined by `Provider.RESOURCES_PAGE_SIZE_LIMIT`),
8141
+ * assembles consolidation transactions, and submits them to the network.
8142
+ *
8143
+ * Note: This method currently supports only the base asset.
8144
+ *
8145
+ * @param params - The parameters for coin consolidation, including the asset ID, mode, and output number.
8146
+ * @returns A promise that resolves to the response of the submitted transactions.
8147
+ * @throws Will throw an error if the asset is not a base asset as non-base asset consolidation is not implemented.
8148
+ */
8149
+ async consolidateCoins(params) {
8150
+ const { assetId } = params;
8151
+ const { coins } = await this.getCoins(assetId);
8152
+ const baseAssetId = await this.provider.getBaseAssetId();
8153
+ const isBaseAsset = baseAssetId === assetId;
8154
+ let submitAll;
8155
+ const consolidationParams = {
8156
+ coins,
8157
+ mode: params.mode,
8158
+ outputNum: params.outputNum
8159
+ };
8160
+ if (isBaseAsset) {
8161
+ ({ submitAll } = await this.assembleBaseAssetConsolidationTxs(consolidationParams));
8162
+ } else {
8163
+ throw new FuelError22(
8164
+ ErrorCode19.UNSUPPORTED_FEATURE,
8165
+ "Consolidation for non-base assets is not supported yet."
8166
+ );
8167
+ }
8168
+ return submitAll();
8169
+ }
8170
+ /**
8171
+ * Assembles transactions for consolidating base asset coins into fewer UTXOs.
8172
+ *
8173
+ * This method splits the provided coins into batches and creates transaction requests
8174
+ * to consolidate them. It calculates the necessary fee and sets up the transactions
8175
+ * to be submitted either in parallel (default) or sequentially.
8176
+ *
8177
+ * @param params - The parameters for assembling base asset consolidation transactions.
8178
+ *
8179
+ * @returns An object containing the assembled transactions, the total fee cost, and a callback to submit all transactions.
8180
+ */
8181
+ async assembleBaseAssetConsolidationTxs(params) {
8182
+ const { coins, mode = "parallel", outputNum = 1 } = params;
8183
+ const baseAssetId = await this.provider.getBaseAssetId();
8184
+ this.validateConsolidationTxsCoins(coins, baseAssetId);
8185
+ const chainInfo = await this.provider.getChain();
8186
+ const maxInputsNumber = chainInfo.consensusParameters.txParameters.maxInputs.toNumber();
8187
+ let totalFeeCost = bn21(0);
8188
+ const txs = [];
8189
+ const coinsBatches = splitCoinsIntoBatches(coins, maxInputsNumber);
8190
+ const gasPrice = await this.provider.estimateGasPrice(10);
8191
+ const consolidateMoreThanOneCoin = outputNum > 1;
8192
+ coinsBatches.filter((batch) => batch.length > 1).forEach((coinBatch) => {
8193
+ const request = new ScriptTransactionRequest({
8194
+ script: "0x"
8195
+ });
8196
+ request.addResources(coinBatch);
8197
+ if (consolidateMoreThanOneCoin) {
8198
+ Array.from({ length: outputNum - 1 }).forEach(() => {
8199
+ request.addCoinOutput(this.address, 0, baseAssetId);
8200
+ });
8201
+ }
8202
+ const minGas = request.calculateMinGas(chainInfo);
8203
+ const fee = calculateGasFee({
8204
+ gasPrice,
8205
+ gas: minGas,
8206
+ priceFactor: chainInfo.consensusParameters.feeParameters.gasPriceFactor,
8207
+ tip: request.tip
8208
+ });
8209
+ request.maxFee = fee;
8210
+ if (consolidateMoreThanOneCoin) {
8211
+ const total = request.inputs.filter(isRequestInputCoin).reduce((acc, input) => acc.add(input.amount), bn21(0));
8212
+ const amountPerNewUtxo = total.div(outputNum + 1);
8213
+ request.outputs.forEach((output) => {
8214
+ if (output.type === OutputType9.Coin) {
8215
+ output.amount = amountPerNewUtxo;
8216
+ }
8217
+ });
8218
+ }
8219
+ totalFeeCost = totalFeeCost.add(fee);
8220
+ txs.push(request);
8221
+ });
8222
+ const submitAll = this.prepareSubmitAll({ txs, mode });
8223
+ return { txs, totalFeeCost, submitAll };
8224
+ }
8225
+ /**
8226
+ * Prepares a function to submit all transactions either sequentially or in parallel.
8227
+ *
8228
+ * @param params - The parameters for preparing the submitAll callback.
8229
+ *
8230
+ * @returns A callback that, when called, submits all transactions and returns their results and any errors encountered.
8231
+ */
8232
+ prepareSubmitAll = /* @__PURE__ */ __name((params) => {
8233
+ const { txs, mode = "sequential" } = params;
8234
+ return async () => {
8235
+ const txResponses = [];
8236
+ const errors = [];
8237
+ if (mode === "sequential") {
8238
+ for (const tx of txs) {
8239
+ try {
8240
+ const submit = await this.sendTransaction(tx);
8241
+ const response = await submit.waitForResult();
8242
+ txResponses.push(response);
8243
+ } catch (error) {
8244
+ errors.push(error);
8245
+ }
8246
+ }
8247
+ } else {
8248
+ const results = await Promise.allSettled(
8249
+ txs.map(async (tx) => {
8250
+ const submit = await this.sendTransaction(tx);
8251
+ return submit.waitForResult();
8252
+ })
8253
+ );
8254
+ results.forEach((result) => {
8255
+ if (result.status === "fulfilled") {
8256
+ txResponses.push(result.value);
8257
+ } else {
8258
+ errors.push(result.reason);
8259
+ }
8260
+ });
8261
+ }
8262
+ return { txResponses, errors };
8263
+ };
8264
+ }, "prepareSubmitAll");
7134
8265
  /**
7135
8266
  * Returns a transaction cost to enable user
7136
8267
  * to set gasLimit and also reserve balance amounts
@@ -7140,15 +8271,18 @@ var Account = class extends AbstractAccount {
7140
8271
  * @param transactionCostParams - The transaction cost parameters (optional).
7141
8272
  *
7142
8273
  * @returns A promise that resolves to the transaction cost object.
8274
+ *
8275
+ * @deprecated Use provider.assembleTx instead
8276
+ * Check the migration guide https://docs.fuel.network/guide/assembling-transactions/migration-guide.html for more information.
7143
8277
  */
7144
8278
  async getTransactionCost(transactionRequestLike, { signatureCallback, quantities = [], gasPrice } = {}) {
7145
8279
  const txRequestClone = clone9(transactionRequestify(transactionRequestLike));
7146
8280
  const baseAssetId = await this.provider.getBaseAssetId();
7147
8281
  const coinOutputsQuantities = txRequestClone.getCoinOutputsQuantities();
7148
8282
  const requiredQuantities = mergeQuantities(coinOutputsQuantities, quantities);
7149
- const transactionFeeForDryRun = [{ assetId: baseAssetId, amount: bn20("100000000000000000") }];
8283
+ const transactionFeeForDryRun = [{ assetId: baseAssetId, amount: bn21("100000000000000000") }];
7150
8284
  const findAssetInput = /* @__PURE__ */ __name((assetId) => txRequestClone.inputs.find((input) => {
7151
- if (input.type === InputType7.Coin) {
8285
+ if (input.type === InputType8.Coin) {
7152
8286
  return input.assetId === assetId;
7153
8287
  }
7154
8288
  if (isRequestInputMessageWithoutData(input)) {
@@ -7194,7 +8328,7 @@ var Account = class extends AbstractAccount {
7194
8328
  */
7195
8329
  async signMessage(message) {
7196
8330
  if (!this._connector) {
7197
- throw new FuelError21(ErrorCode18.MISSING_CONNECTOR, "A connector is required to sign messages.");
8331
+ throw new FuelError22(ErrorCode19.MISSING_CONNECTOR, "A connector is required to sign messages.");
7198
8332
  }
7199
8333
  return this._connector.signMessage(this.address.toString(), message);
7200
8334
  }
@@ -7206,8 +8340,8 @@ var Account = class extends AbstractAccount {
7206
8340
  */
7207
8341
  async signTransaction(transactionRequestLike) {
7208
8342
  if (!this._connector) {
7209
- throw new FuelError21(
7210
- ErrorCode18.MISSING_CONNECTOR,
8343
+ throw new FuelError22(
8344
+ ErrorCode19.MISSING_CONNECTOR,
7211
8345
  "A connector is required to sign transactions."
7212
8346
  );
7213
8347
  }
@@ -7271,17 +8405,17 @@ var Account = class extends AbstractAccount {
7271
8405
  */
7272
8406
  generateFakeResources(coins) {
7273
8407
  return coins.map((coin) => ({
7274
- id: hexlify20(randomBytes5(UTXO_ID_LEN3)),
8408
+ id: hexlify21(randomBytes5(UTXO_ID_LEN3)),
7275
8409
  owner: this.address,
7276
- blockCreated: bn20(1),
7277
- txCreatedIdx: bn20(1),
8410
+ blockCreated: bn21(1),
8411
+ txCreatedIdx: bn21(1),
7278
8412
  ...coin
7279
8413
  }));
7280
8414
  }
7281
8415
  /** @hidden */
7282
8416
  async prepareTransactionForSend(request) {
7283
8417
  const { transactionId } = request.flag;
7284
- if (!isDefined3(transactionId)) {
8418
+ if (!isDefined4(transactionId)) {
7285
8419
  return request;
7286
8420
  }
7287
8421
  const chainId = await this.provider.getChainId();
@@ -7294,17 +8428,29 @@ var Account = class extends AbstractAccount {
7294
8428
  /** @hidden */
7295
8429
  async prepareTransactionSummary(request) {
7296
8430
  const chainId = await this.provider.getChainId();
7297
- return isDefined3(request.flag.summary) ? {
8431
+ return isDefined4(request.flag.summary) ? {
7298
8432
  ...request.flag.summary,
7299
8433
  id: request.getTransactionId(chainId),
7300
- transactionBytes: hexlify20(request.toTransactionBytes())
8434
+ transactionBytes: hexlify21(request.toTransactionBytes())
7301
8435
  } : void 0;
7302
8436
  }
7303
8437
  /** @hidden * */
8438
+ async assembleTx(transactionRequest, quantities = []) {
8439
+ const outputQuantities = transactionRequest.outputs.filter((o) => o.type === OutputType9.Coin).map(({ amount, assetId }) => ({ assetId: String(assetId), amount: bn21(amount) }));
8440
+ transactionRequest.gasLimit = bn21(0);
8441
+ transactionRequest.maxFee = bn21(0);
8442
+ const { assembledRequest, gasPrice } = await this.provider.assembleTx({
8443
+ request: transactionRequest,
8444
+ accountCoinQuantities: mergeQuantities(outputQuantities, quantities),
8445
+ feePayerAccount: this
8446
+ });
8447
+ return { transactionRequest: assembledRequest, gasPrice };
8448
+ }
8449
+ /** @hidden * */
7304
8450
  validateTransferAmount(amount) {
7305
- if (bn20(amount).lte(0)) {
7306
- throw new FuelError21(
7307
- ErrorCode18.INVALID_TRANSFER_AMOUNT,
8451
+ if (bn21(amount).lte(0)) {
8452
+ throw new FuelError22(
8453
+ ErrorCode19.INVALID_TRANSFER_AMOUNT,
7308
8454
  "Transfer amount must be a positive number."
7309
8455
  );
7310
8456
  }
@@ -7330,24 +8476,36 @@ var Account = class extends AbstractAccount {
7330
8476
  txParams: { gasLimit: setGasLimit, maxFee: setMaxFee }
7331
8477
  }) {
7332
8478
  const request = transactionRequestify(transactionRequest);
7333
- if (!isDefined3(setGasLimit)) {
8479
+ if (!isDefined4(setGasLimit)) {
7334
8480
  request.gasLimit = gasUsed;
7335
8481
  } else if (gasUsed.gt(setGasLimit)) {
7336
- throw new FuelError21(
7337
- ErrorCode18.GAS_LIMIT_TOO_LOW,
8482
+ throw new FuelError22(
8483
+ ErrorCode19.GAS_LIMIT_TOO_LOW,
7338
8484
  `Gas limit '${setGasLimit}' is lower than the required: '${gasUsed}'.`
7339
8485
  );
7340
8486
  }
7341
- if (!isDefined3(setMaxFee)) {
8487
+ if (!isDefined4(setMaxFee)) {
7342
8488
  request.maxFee = maxFee;
7343
8489
  } else if (maxFee.gt(setMaxFee)) {
7344
- throw new FuelError21(
7345
- ErrorCode18.MAX_FEE_TOO_LOW,
8490
+ throw new FuelError22(
8491
+ ErrorCode19.MAX_FEE_TOO_LOW,
7346
8492
  `Max fee '${setMaxFee}' is lower than the required: '${maxFee}'.`
7347
8493
  );
7348
8494
  }
7349
8495
  return request;
7350
8496
  }
8497
+ /** @hidden * */
8498
+ validateConsolidationTxsCoins(coins, assetId) {
8499
+ if (coins.length <= 1) {
8500
+ throw new FuelError22(ErrorCode19.NO_COINS_TO_CONSOLIDATE, "No coins to consolidate.");
8501
+ }
8502
+ if (!coins.every((c) => c.assetId === assetId)) {
8503
+ throw new FuelError22(
8504
+ ErrorCode19.COINS_ASSET_ID_MISMATCH,
8505
+ "All coins to consolidate must be from the same asset id."
8506
+ );
8507
+ }
8508
+ }
7351
8509
  };
7352
8510
 
7353
8511
  // src/wallet/keystore-wallet.ts
@@ -7362,8 +8520,8 @@ import {
7362
8520
  encryptJsonWalletData,
7363
8521
  randomUUID as randomUUID2
7364
8522
  } from "@fuel-ts/crypto";
7365
- import { ErrorCode as ErrorCode19, FuelError as FuelError22 } from "@fuel-ts/errors";
7366
- import { hexlify as hexlify21 } from "@fuel-ts/utils";
8523
+ import { ErrorCode as ErrorCode20, FuelError as FuelError23 } from "@fuel-ts/errors";
8524
+ import { hexlify as hexlify22 } from "@fuel-ts/utils";
7367
8525
  var DEFAULT_KDF_PARAMS_LOG_N = 13;
7368
8526
  var DEFAULT_KDF_PARAMS_R = 8;
7369
8527
  var DEFAULT_KDF_PARAMS_P = 1;
@@ -7440,13 +8598,13 @@ async function decryptKeystoreWallet(jsonWallet, password) {
7440
8598
  const macHashUint8Array = keccak256(data);
7441
8599
  const macHash = stringFromBuffer(macHashUint8Array, "hex");
7442
8600
  if (mac !== macHash) {
7443
- throw new FuelError22(
7444
- ErrorCode19.INVALID_PASSWORD,
8601
+ throw new FuelError23(
8602
+ ErrorCode20.INVALID_PASSWORD,
7445
8603
  "Failed to decrypt the keystore wallet, the provided password is incorrect."
7446
8604
  );
7447
8605
  }
7448
8606
  const buffer = await decryptJsonWalletData(ciphertextBuffer, key, ivBuffer);
7449
- const privateKey = hexlify21(buffer);
8607
+ const privateKey = hexlify22(buffer);
7450
8608
  return privateKey;
7451
8609
  }
7452
8610
  __name(decryptKeystoreWallet, "decryptKeystoreWallet");
@@ -7499,7 +8657,7 @@ var BaseWalletUnlocked = class extends Account {
7499
8657
  */
7500
8658
  async signMessage(message) {
7501
8659
  const signedMessage = await this.signer().sign(hashMessage(message));
7502
- return hexlify22(signedMessage);
8660
+ return hexlify23(signedMessage);
7503
8661
  }
7504
8662
  /**
7505
8663
  * Signs a transaction with the wallet's private key.
@@ -7512,7 +8670,7 @@ var BaseWalletUnlocked = class extends Account {
7512
8670
  const chainId = await this.provider.getChainId();
7513
8671
  const hashedTransaction = transactionRequest.getTransactionId(chainId);
7514
8672
  const signature = await this.signer().sign(hashedTransaction);
7515
- return hexlify22(signature);
8673
+ return hexlify23(signature);
7516
8674
  }
7517
8675
  /**
7518
8676
  * Populates a transaction with the witnesses signature.
@@ -7580,16 +8738,16 @@ var BaseWalletUnlocked = class extends Account {
7580
8738
 
7581
8739
  // src/hdwallet/hdwallet.ts
7582
8740
  import { computeHmac as computeHmac2, ripemd160 } from "@fuel-ts/crypto";
7583
- import { ErrorCode as ErrorCode22, FuelError as FuelError25 } from "@fuel-ts/errors";
8741
+ import { ErrorCode as ErrorCode23, FuelError as FuelError26 } from "@fuel-ts/errors";
7584
8742
  import { sha256 as sha2564 } from "@fuel-ts/hasher";
7585
- import { bn as bn21, toBytes as toBytes2, toHex } from "@fuel-ts/math";
7586
- import { arrayify as arrayify20, hexlify as hexlify24, concat as concat6, dataSlice as dataSlice2, encodeBase58 as encodeBase582, decodeBase58 } from "@fuel-ts/utils";
8743
+ import { bn as bn22, toBytes as toBytes2, toHex } from "@fuel-ts/math";
8744
+ import { arrayify as arrayify20, hexlify as hexlify25, concat as concat6, dataSlice as dataSlice2, encodeBase58 as encodeBase582, decodeBase58 } from "@fuel-ts/utils";
7587
8745
 
7588
8746
  // src/mnemonic/mnemonic.ts
7589
8747
  import { randomBytes as randomBytes7, pbkdf2, computeHmac } from "@fuel-ts/crypto";
7590
- import { ErrorCode as ErrorCode21, FuelError as FuelError24 } from "@fuel-ts/errors";
8748
+ import { ErrorCode as ErrorCode22, FuelError as FuelError25 } from "@fuel-ts/errors";
7591
8749
  import { sha256 as sha2563 } from "@fuel-ts/hasher";
7592
- import { arrayify as arrayify19, hexlify as hexlify23, concat as concat5, dataSlice, encodeBase58, toUtf8Bytes } from "@fuel-ts/utils";
8750
+ import { arrayify as arrayify19, hexlify as hexlify24, concat as concat5, dataSlice, encodeBase58, toUtf8Bytes } from "@fuel-ts/utils";
7593
8751
 
7594
8752
  // src/wordlists/words/english.ts
7595
8753
  var english = [
@@ -9644,7 +10802,7 @@ var english = [
9644
10802
  ];
9645
10803
 
9646
10804
  // src/mnemonic/utils.ts
9647
- import { ErrorCode as ErrorCode20, FuelError as FuelError23 } from "@fuel-ts/errors";
10805
+ import { ErrorCode as ErrorCode21, FuelError as FuelError24 } from "@fuel-ts/errors";
9648
10806
  import { sha256 as sha2562 } from "@fuel-ts/hasher";
9649
10807
  import { arrayify as arrayify18 } from "@fuel-ts/utils";
9650
10808
  function getLowerMask(bits) {
@@ -9698,8 +10856,8 @@ function mnemonicWordsToEntropy(words, wordlist) {
9698
10856
  for (let i = 0; i < words.length; i += 1) {
9699
10857
  const index = wordlist.indexOf(words[i].normalize("NFKD"));
9700
10858
  if (index === -1) {
9701
- throw new FuelError23(
9702
- ErrorCode20.INVALID_MNEMONIC,
10859
+ throw new FuelError24(
10860
+ ErrorCode21.INVALID_MNEMONIC,
9703
10861
  `Invalid mnemonic: the word '${words[i]}' is not found in the provided wordlist.`
9704
10862
  );
9705
10863
  }
@@ -9715,8 +10873,8 @@ function mnemonicWordsToEntropy(words, wordlist) {
9715
10873
  const checksumMask = getUpperMask(checksumBits);
9716
10874
  const checksum = arrayify18(sha2562(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
9717
10875
  if (checksum !== (entropy[entropy.length - 1] & checksumMask)) {
9718
- throw new FuelError23(
9719
- ErrorCode20.INVALID_CHECKSUM,
10876
+ throw new FuelError24(
10877
+ ErrorCode21.INVALID_CHECKSUM,
9720
10878
  "Checksum validation failed for the provided mnemonic."
9721
10879
  );
9722
10880
  }
@@ -9731,8 +10889,8 @@ var TestnetPRV = "0x04358394";
9731
10889
  var MNEMONIC_SIZES = [12, 15, 18, 21, 24];
9732
10890
  function assertWordList(wordlist) {
9733
10891
  if (wordlist.length !== 2048) {
9734
- throw new FuelError24(
9735
- ErrorCode21.INVALID_WORD_LIST,
10892
+ throw new FuelError25(
10893
+ ErrorCode22.INVALID_WORD_LIST,
9736
10894
  `Expected word list length of 2048, but got ${wordlist.length}.`
9737
10895
  );
9738
10896
  }
@@ -9740,8 +10898,8 @@ function assertWordList(wordlist) {
9740
10898
  __name(assertWordList, "assertWordList");
9741
10899
  function assertEntropy(entropy) {
9742
10900
  if (entropy.length % 4 !== 0 || entropy.length < 16 || entropy.length > 32) {
9743
- throw new FuelError24(
9744
- ErrorCode21.INVALID_ENTROPY,
10901
+ throw new FuelError25(
10902
+ ErrorCode22.INVALID_ENTROPY,
9745
10903
  `Entropy should be between 16 and 32 bytes and a multiple of 4, but got ${entropy.length} bytes.`
9746
10904
  );
9747
10905
  }
@@ -9752,7 +10910,7 @@ function assertMnemonic(words) {
9752
10910
  const errorMsg = `Invalid mnemonic size. Expected one of [${MNEMONIC_SIZES.join(
9753
10911
  ", "
9754
10912
  )}] words, but got ${words.length}.`;
9755
- throw new FuelError24(ErrorCode21.INVALID_MNEMONIC, errorMsg);
10913
+ throw new FuelError25(ErrorCode22.INVALID_MNEMONIC, errorMsg);
9756
10914
  }
9757
10915
  }
9758
10916
  __name(assertMnemonic, "assertMnemonic");
@@ -9795,7 +10953,7 @@ var Mnemonic = class _Mnemonic {
9795
10953
  static mnemonicToEntropy(phrase, wordlist = english) {
9796
10954
  const words = getWords(phrase);
9797
10955
  assertMnemonic(words);
9798
- return hexlify23(mnemonicWordsToEntropy(words, wordlist));
10956
+ return hexlify24(mnemonicWordsToEntropy(words, wordlist));
9799
10957
  }
9800
10958
  /**
9801
10959
  * @param entropy - Entropy source to the mnemonic phrase.
@@ -9874,8 +11032,8 @@ var Mnemonic = class _Mnemonic {
9874
11032
  static masterKeysFromSeed(seed) {
9875
11033
  const seedArray = arrayify19(seed);
9876
11034
  if (seedArray.length < 16 || seedArray.length > 64) {
9877
- throw new FuelError24(
9878
- ErrorCode21.INVALID_SEED,
11035
+ throw new FuelError25(
11036
+ ErrorCode22.INVALID_SEED,
9879
11037
  `Seed length should be between 16 and 64 bytes, but received ${seedArray.length} bytes.`
9880
11038
  );
9881
11039
  }
@@ -9928,10 +11086,10 @@ var mnemonic_default = Mnemonic;
9928
11086
 
9929
11087
  // src/hdwallet/hdwallet.ts
9930
11088
  var HARDENED_INDEX = 2147483648;
9931
- var MainnetPRV2 = hexlify24("0x0488ade4");
9932
- var MainnetPUB = hexlify24("0x0488b21e");
9933
- var TestnetPRV2 = hexlify24("0x04358394");
9934
- var TestnetPUB = hexlify24("0x043587cf");
11089
+ var MainnetPRV2 = hexlify25("0x0488ade4");
11090
+ var MainnetPUB = hexlify25("0x0488b21e");
11091
+ var TestnetPRV2 = hexlify25("0x04358394");
11092
+ var TestnetPUB = hexlify25("0x043587cf");
9935
11093
  function base58check(data) {
9936
11094
  return encodeBase582(concat6([data, dataSlice2(sha2564(sha2564(data)), 0, 4)]));
9937
11095
  }
@@ -9944,19 +11102,19 @@ function getExtendedKeyPrefix(isPublic = false, testnet = false) {
9944
11102
  }
9945
11103
  __name(getExtendedKeyPrefix, "getExtendedKeyPrefix");
9946
11104
  function isPublicExtendedKey(extendedKey) {
9947
- return [MainnetPUB, TestnetPUB].includes(hexlify24(extendedKey.slice(0, 4)));
11105
+ return [MainnetPUB, TestnetPUB].includes(hexlify25(extendedKey.slice(0, 4)));
9948
11106
  }
9949
11107
  __name(isPublicExtendedKey, "isPublicExtendedKey");
9950
11108
  function isValidExtendedKey(extendedKey) {
9951
11109
  return [MainnetPRV2, TestnetPRV2, MainnetPUB, TestnetPUB].includes(
9952
- hexlify24(extendedKey.slice(0, 4))
11110
+ hexlify25(extendedKey.slice(0, 4))
9953
11111
  );
9954
11112
  }
9955
11113
  __name(isValidExtendedKey, "isValidExtendedKey");
9956
11114
  function parsePath(path2, depth = 0) {
9957
11115
  const components = path2.split("/");
9958
11116
  if (components.length === 0 || components[0] === "m" && depth !== 0) {
9959
- throw new FuelError25(ErrorCode22.HD_WALLET_ERROR, `invalid path - ${path2}`);
11117
+ throw new FuelError26(ErrorCode23.HD_WALLET_ERROR, `invalid path - ${path2}`);
9960
11118
  }
9961
11119
  if (components[0] === "m") {
9962
11120
  components.shift();
@@ -9972,8 +11130,8 @@ var HDWallet = class _HDWallet {
9972
11130
  }
9973
11131
  depth = 0;
9974
11132
  index = 0;
9975
- fingerprint = hexlify24("0x00000000");
9976
- parentFingerprint = hexlify24("0x00000000");
11133
+ fingerprint = hexlify25("0x00000000");
11134
+ parentFingerprint = hexlify25("0x00000000");
9977
11135
  privateKey;
9978
11136
  publicKey;
9979
11137
  chainCode;
@@ -9985,16 +11143,16 @@ var HDWallet = class _HDWallet {
9985
11143
  constructor(config) {
9986
11144
  if (config.privateKey) {
9987
11145
  const signer = new Signer(config.privateKey);
9988
- this.publicKey = hexlify24(signer.compressedPublicKey);
9989
- this.privateKey = hexlify24(config.privateKey);
11146
+ this.publicKey = hexlify25(signer.compressedPublicKey);
11147
+ this.privateKey = hexlify25(config.privateKey);
9990
11148
  } else {
9991
11149
  if (!config.publicKey) {
9992
- throw new FuelError25(
9993
- ErrorCode22.HD_WALLET_ERROR,
11150
+ throw new FuelError26(
11151
+ ErrorCode23.HD_WALLET_ERROR,
9994
11152
  "Both public and private Key cannot be missing. At least one should be provided."
9995
11153
  );
9996
11154
  }
9997
- this.publicKey = hexlify24(config.publicKey);
11155
+ this.publicKey = hexlify25(config.publicKey);
9998
11156
  }
9999
11157
  this.parentFingerprint = config.parentFingerprint || this.parentFingerprint;
10000
11158
  this.fingerprint = dataSlice2(ripemd160(sha2564(this.publicKey)), 0, 4);
@@ -10019,8 +11177,8 @@ var HDWallet = class _HDWallet {
10019
11177
  const data = new Uint8Array(37);
10020
11178
  if (index & HARDENED_INDEX) {
10021
11179
  if (!privateKey) {
10022
- throw new FuelError25(
10023
- ErrorCode22.HD_WALLET_ERROR,
11180
+ throw new FuelError26(
11181
+ ErrorCode23.HD_WALLET_ERROR,
10024
11182
  "Cannot derive a hardened index without a private Key."
10025
11183
  );
10026
11184
  }
@@ -10034,7 +11192,7 @@ var HDWallet = class _HDWallet {
10034
11192
  const IR = bytes.slice(32);
10035
11193
  if (privateKey) {
10036
11194
  const N = "0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141";
10037
- const ki = bn21(IL).add(privateKey).mod(N).toBytes(32);
11195
+ const ki = bn22(IL).add(privateKey).mod(N).toBytes(32);
10038
11196
  return new _HDWallet({
10039
11197
  privateKey: ki,
10040
11198
  chainCode: IR,
@@ -10043,7 +11201,7 @@ var HDWallet = class _HDWallet {
10043
11201
  parentFingerprint: this.fingerprint
10044
11202
  });
10045
11203
  }
10046
- const signer = new Signer(hexlify24(IL));
11204
+ const signer = new Signer(hexlify25(IL));
10047
11205
  const Ki = signer.addPoint(publicKey);
10048
11206
  return new _HDWallet({
10049
11207
  publicKey: Ki,
@@ -10072,13 +11230,13 @@ var HDWallet = class _HDWallet {
10072
11230
  */
10073
11231
  toExtendedKey(isPublic = false, testnet = false) {
10074
11232
  if (this.depth >= 256) {
10075
- throw new FuelError25(
10076
- ErrorCode22.HD_WALLET_ERROR,
11233
+ throw new FuelError26(
11234
+ ErrorCode23.HD_WALLET_ERROR,
10077
11235
  `Exceeded max depth of 255. Current depth: ${this.depth}.`
10078
11236
  );
10079
11237
  }
10080
11238
  const prefix = getExtendedKeyPrefix(this.privateKey == null || isPublic, testnet);
10081
- const depth = hexlify24(Uint8Array.from([this.depth]));
11239
+ const depth = hexlify25(Uint8Array.from([this.depth]));
10082
11240
  const parentFingerprint = this.parentFingerprint;
10083
11241
  const index = toHex(this.index, 4);
10084
11242
  const chainCode = this.chainCode;
@@ -10100,29 +11258,29 @@ var HDWallet = class _HDWallet {
10100
11258
  });
10101
11259
  }
10102
11260
  static fromExtendedKey(extendedKey) {
10103
- const decoded = hexlify24(toBytes2(decodeBase58(extendedKey)));
11261
+ const decoded = hexlify25(toBytes2(decodeBase58(extendedKey)));
10104
11262
  const bytes = arrayify20(decoded);
10105
11263
  const validChecksum = base58check(bytes.slice(0, 78)) === extendedKey;
10106
11264
  if (bytes.length !== 82 || !isValidExtendedKey(bytes)) {
10107
- throw new FuelError25(ErrorCode22.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
11265
+ throw new FuelError26(ErrorCode23.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
10108
11266
  }
10109
11267
  if (!validChecksum) {
10110
- throw new FuelError25(ErrorCode22.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
11268
+ throw new FuelError26(ErrorCode23.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
10111
11269
  }
10112
11270
  const depth = bytes[4];
10113
- const parentFingerprint = hexlify24(bytes.slice(5, 9));
10114
- const index = parseInt(hexlify24(bytes.slice(9, 13)).substring(2), 16);
10115
- const chainCode = hexlify24(bytes.slice(13, 45));
11271
+ const parentFingerprint = hexlify25(bytes.slice(5, 9));
11272
+ const index = parseInt(hexlify25(bytes.slice(9, 13)).substring(2), 16);
11273
+ const chainCode = hexlify25(bytes.slice(13, 45));
10116
11274
  const key = bytes.slice(45, 78);
10117
11275
  if (depth === 0 && parentFingerprint !== "0x00000000" || depth === 0 && index !== 0) {
10118
- throw new FuelError25(
10119
- ErrorCode22.HD_WALLET_ERROR,
11276
+ throw new FuelError26(
11277
+ ErrorCode23.HD_WALLET_ERROR,
10120
11278
  "Inconsistency detected: Depth is zero but fingerprint/index is non-zero."
10121
11279
  );
10122
11280
  }
10123
11281
  if (isPublicExtendedKey(bytes)) {
10124
11282
  if (key[0] !== 3) {
10125
- throw new FuelError25(ErrorCode22.HD_WALLET_ERROR, "Invalid public extended key.");
11283
+ throw new FuelError26(ErrorCode23.HD_WALLET_ERROR, "Invalid public extended key.");
10126
11284
  }
10127
11285
  return new _HDWallet({
10128
11286
  publicKey: key,
@@ -10133,7 +11291,7 @@ var HDWallet = class _HDWallet {
10133
11291
  });
10134
11292
  }
10135
11293
  if (key[0] !== 0) {
10136
- throw new FuelError25(ErrorCode22.HD_WALLET_ERROR, "Invalid private extended key.");
11294
+ throw new FuelError26(ErrorCode23.HD_WALLET_ERROR, "Invalid private extended key.");
10137
11295
  }
10138
11296
  return new _HDWallet({
10139
11297
  privateKey: key.slice(1),
@@ -10369,13 +11527,13 @@ var WalletsConfig = class _WalletsConfig {
10369
11527
  assetIds.forEach((assetId) => {
10370
11528
  for (let index = 0; index < coinsPerAsset; index++) {
10371
11529
  coins.push({
10372
- amount: bn22(amountPerCoin).toString(),
11530
+ amount: bn23(amountPerCoin).toString(),
10373
11531
  asset_id: assetId,
10374
11532
  owner: walletAddress,
10375
11533
  tx_pointer_block_height: 0,
10376
11534
  tx_pointer_tx_idx: 0,
10377
11535
  output_index: 0,
10378
- tx_id: hexlify25(randomBytes8(32))
11536
+ tx_id: hexlify26(randomBytes8(32))
10379
11537
  });
10380
11538
  }
10381
11539
  });
@@ -10389,26 +11547,26 @@ var WalletsConfig = class _WalletsConfig {
10389
11547
  amountPerCoin
10390
11548
  }) {
10391
11549
  if (Array.isArray(wallets) && wallets.length === 0 || typeof wallets === "number" && wallets <= 0) {
10392
- throw new FuelError26(
10393
- FuelError26.CODES.INVALID_INPUT_PARAMETERS,
11550
+ throw new FuelError27(
11551
+ FuelError27.CODES.INVALID_INPUT_PARAMETERS,
10394
11552
  "Number of wallets must be greater than zero."
10395
11553
  );
10396
11554
  }
10397
11555
  if (Array.isArray(assets) && assets.length === 0 || typeof assets === "number" && assets <= 0) {
10398
- throw new FuelError26(
10399
- FuelError26.CODES.INVALID_INPUT_PARAMETERS,
11556
+ throw new FuelError27(
11557
+ FuelError27.CODES.INVALID_INPUT_PARAMETERS,
10400
11558
  "Number of assets per wallet must be greater than zero."
10401
11559
  );
10402
11560
  }
10403
11561
  if (coinsPerAsset <= 0) {
10404
- throw new FuelError26(
10405
- FuelError26.CODES.INVALID_INPUT_PARAMETERS,
11562
+ throw new FuelError27(
11563
+ FuelError27.CODES.INVALID_INPUT_PARAMETERS,
10406
11564
  "Number of coins per asset must be greater than zero."
10407
11565
  );
10408
11566
  }
10409
- if (bn22(amountPerCoin).lt(0)) {
10410
- throw new FuelError26(
10411
- FuelError26.CODES.INVALID_INPUT_PARAMETERS,
11567
+ if (bn23(amountPerCoin).lt(0)) {
11568
+ throw new FuelError27(
11569
+ FuelError27.CODES.INVALID_INPUT_PARAMETERS,
10412
11570
  "Amount per coin must be greater than or equal to zero."
10413
11571
  );
10414
11572
  }
@@ -10446,23 +11604,26 @@ async function setupTestProviderAndWallets({
10446
11604
  ),
10447
11605
  port: nodeOptions.port || "0"
10448
11606
  };
10449
- let cleanup;
11607
+ let killNode;
10450
11608
  let url;
10451
11609
  if (launchNodeServerPort) {
10452
11610
  const serverUrl = `http://localhost:${launchNodeServerPort}`;
10453
11611
  url = await (await fetch(serverUrl, { method: "POST", body: JSON.stringify(launchNodeOptions) })).text();
10454
- cleanup = /* @__PURE__ */ __name(() => {
11612
+ killNode = /* @__PURE__ */ __name(() => {
10455
11613
  fetch(`${serverUrl}/cleanup/${url}`);
10456
- }, "cleanup");
11614
+ }, "killNode");
10457
11615
  } else {
10458
11616
  const settings = await launchNode(launchNodeOptions);
10459
11617
  url = settings.url;
10460
- cleanup = settings.cleanup;
11618
+ killNode = settings.cleanup;
10461
11619
  }
11620
+ const cleanup = /* @__PURE__ */ __name(() => {
11621
+ Provider.clearChainAndNodeCaches(url);
11622
+ killNode();
11623
+ }, "cleanup");
10462
11624
  let provider;
10463
11625
  try {
10464
11626
  provider = new Provider(url, providerOptions);
10465
- await provider.init();
10466
11627
  } catch (err) {
10467
11628
  cleanup();
10468
11629
  throw err;
@@ -10483,8 +11644,8 @@ __name(setupTestProviderAndWallets, "setupTestProviderAndWallets");
10483
11644
  // src/test-utils/test-message.ts
10484
11645
  import { Address as Address7 } from "@fuel-ts/address";
10485
11646
  import { randomBytes as randomBytes9 } from "@fuel-ts/crypto";
10486
- import { bn as bn23 } from "@fuel-ts/math";
10487
- import { hexlify as hexlify26 } from "@fuel-ts/utils";
11647
+ import { bn as bn24 } from "@fuel-ts/math";
11648
+ import { hexlify as hexlify27 } from "@fuel-ts/utils";
10488
11649
  var TestMessage = class {
10489
11650
  static {
10490
11651
  __name(this, "TestMessage");
@@ -10504,7 +11665,7 @@ var TestMessage = class {
10504
11665
  constructor({
10505
11666
  sender = Address7.fromRandom(),
10506
11667
  recipient = Address7.fromRandom(),
10507
- nonce = hexlify26(randomBytes9(32)),
11668
+ nonce = hexlify27(randomBytes9(32)),
10508
11669
  amount = 1e6,
10509
11670
  data = "",
10510
11671
  // Will default to empty data in order to be a spendable message
@@ -10523,7 +11684,7 @@ var TestMessage = class {
10523
11684
  sender: this.sender.toB256(),
10524
11685
  recipient: recipient?.toB256() ?? this.recipient.toB256(),
10525
11686
  nonce: this.nonce,
10526
- amount: bn23(this.amount).toNumber(),
11687
+ amount: bn24(this.amount).toNumber(),
10527
11688
  data,
10528
11689
  da_height: this.da_height
10529
11690
  };