@fuel-ts/account 0.100.3 → 0.100.5

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 (67) hide show
  1. package/dist/account.d.ts +71 -3
  2. package/dist/account.d.ts.map +1 -1
  3. package/dist/connectors/fuel-connector.d.ts +3 -3
  4. package/dist/connectors/fuel-connector.d.ts.map +1 -1
  5. package/dist/index.global.js +1506 -221
  6. package/dist/index.global.js.map +1 -1
  7. package/dist/index.js +2222 -1027
  8. package/dist/index.js.map +1 -1
  9. package/dist/index.mjs +2021 -828
  10. package/dist/index.mjs.map +1 -1
  11. package/dist/predicate/predicate.d.ts +9 -4
  12. package/dist/predicate/predicate.d.ts.map +1 -1
  13. package/dist/providers/__generated__/operations.d.ts +1187 -76
  14. package/dist/providers/__generated__/operations.d.ts.map +1 -1
  15. package/dist/providers/assemble-tx-helpers.d.ts +39 -0
  16. package/dist/providers/assemble-tx-helpers.d.ts.map +1 -0
  17. package/dist/providers/fuel-graphql-subscriber.d.ts +28 -0
  18. package/dist/providers/fuel-graphql-subscriber.d.ts.map +1 -1
  19. package/dist/providers/index.d.ts +1 -0
  20. package/dist/providers/index.d.ts.map +1 -1
  21. package/dist/providers/provider.d.ts +85 -6
  22. package/dist/providers/provider.d.ts.map +1 -1
  23. package/dist/providers/resource.d.ts +4 -1
  24. package/dist/providers/resource.d.ts.map +1 -1
  25. package/dist/providers/transaction-request/helpers.d.ts +3 -3
  26. package/dist/providers/transaction-request/helpers.d.ts.map +1 -1
  27. package/dist/providers/transaction-request/input.d.ts +2 -0
  28. package/dist/providers/transaction-request/input.d.ts.map +1 -1
  29. package/dist/providers/transaction-request/output.d.ts +6 -0
  30. package/dist/providers/transaction-request/output.d.ts.map +1 -1
  31. package/dist/providers/transaction-request/script-transaction-request.d.ts +11 -0
  32. package/dist/providers/transaction-request/script-transaction-request.d.ts.map +1 -1
  33. package/dist/providers/transaction-request/transaction-request.d.ts +3 -3
  34. package/dist/providers/transaction-request/transaction-request.d.ts.map +1 -1
  35. package/dist/providers/transaction-response/getAllDecodedLogs.d.ts.map +1 -1
  36. package/dist/providers/transaction-response/transaction-response.d.ts +54 -15
  37. package/dist/providers/transaction-response/transaction-response.d.ts.map +1 -1
  38. package/dist/providers/transaction-summary/assemble-transaction-summary.d.ts +12 -1
  39. package/dist/providers/transaction-summary/assemble-transaction-summary.d.ts.map +1 -1
  40. package/dist/providers/transaction-summary/get-transaction-summary.d.ts.map +1 -1
  41. package/dist/providers/transaction-summary/status.d.ts +16 -2
  42. package/dist/providers/transaction-summary/status.d.ts.map +1 -1
  43. package/dist/providers/transaction-summary/types.d.ts +85 -4
  44. package/dist/providers/transaction-summary/types.d.ts.map +1 -1
  45. package/dist/providers/utils/handle-gql-error-message.d.ts.map +1 -1
  46. package/dist/providers/utils/index.d.ts +1 -0
  47. package/dist/providers/utils/index.d.ts.map +1 -1
  48. package/dist/providers/utils/parse-graphql-response.d.ts +12 -0
  49. package/dist/providers/utils/parse-graphql-response.d.ts.map +1 -0
  50. package/dist/providers/utils/serialization.d.ts +9 -0
  51. package/dist/providers/utils/serialization.d.ts.map +1 -1
  52. package/dist/providers/utils/transaction-response-serialization.d.ts +8 -0
  53. package/dist/providers/utils/transaction-response-serialization.d.ts.map +1 -0
  54. package/dist/test-utils/launchNode.d.ts.map +1 -1
  55. package/dist/test-utils/setup-test-provider-and-wallets.d.ts.map +1 -1
  56. package/dist/test-utils.global.js +1500 -205
  57. package/dist/test-utils.global.js.map +1 -1
  58. package/dist/test-utils.js +2091 -901
  59. package/dist/test-utils.js.map +1 -1
  60. package/dist/test-utils.mjs +1938 -742
  61. package/dist/test-utils.mjs.map +1 -1
  62. package/dist/utils/deployScriptOrPredicate.d.ts.map +1 -1
  63. package/dist/utils/split-coins-into-batches.d.ts +3 -0
  64. package/dist/utils/split-coins-into-batches.d.ts.map +1 -0
  65. package/package.json +15 -15
  66. package/dist/providers/utils/helpers.d.ts +0 -14
  67. 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
@@ -880,6 +1065,11 @@ var ChainInfoFragmentDoc = gql`
880
1065
  consensusParameters {
881
1066
  ...consensusParametersFragment
882
1067
  }
1068
+ latestBlock {
1069
+ header {
1070
+ consensusParametersVersion
1071
+ }
1072
+ }
883
1073
  }
884
1074
  ${ConsensusParametersFragmentDoc}`;
885
1075
  var ContractBalanceFragmentDoc = gql`
@@ -976,13 +1166,21 @@ var GetTransactionWithReceiptsDocument = gql`
976
1166
  ... on SqueezedOutStatus {
977
1167
  ...SqueezedOutStatusFragment
978
1168
  }
1169
+ ... on PreconfirmationSuccessStatus {
1170
+ ...PreconfirmationSuccessStatusFragment
1171
+ }
1172
+ ... on PreconfirmationFailureStatus {
1173
+ ...PreconfirmationFailureStatusFragment
1174
+ }
979
1175
  }
980
1176
  }
981
1177
  }
982
1178
  ${SubmittedStatusFragmentDoc}
983
1179
  ${SuccessStatusWithBlockIdFragmentDoc}
984
1180
  ${FailureStatusWithBlockIdFragmentDoc}
985
- ${SqueezedOutStatusFragmentDoc}`;
1181
+ ${SqueezedOutStatusFragmentDoc}
1182
+ ${PreconfirmationSuccessStatusFragmentDoc}
1183
+ ${PreconfirmationFailureStatusFragmentDoc}`;
986
1184
  var GetTransactionsDocument = gql`
987
1185
  query getTransactions($after: String, $before: String, $first: Int, $last: Int) {
988
1186
  transactions(after: $after, before: $before, first: $first, last: $last) {
@@ -1273,8 +1471,79 @@ var GetAssetDetailsDocument = gql`
1273
1471
  }
1274
1472
  }
1275
1473
  `;
1474
+ var AssembleTxDocument = gql`
1475
+ query assembleTx($tx: HexString!, $blockHorizon: U32!, $requiredBalances: [RequiredBalance!]!, $feeAddressIndex: U16!, $excludeInput: ExcludeInput, $estimatePredicates: Boolean, $reserveGas: U64) {
1476
+ assembleTx(
1477
+ tx: $tx
1478
+ blockHorizon: $blockHorizon
1479
+ requiredBalances: $requiredBalances
1480
+ feeAddressIndex: $feeAddressIndex
1481
+ excludeInput: $excludeInput
1482
+ estimatePredicates: $estimatePredicates
1483
+ reserveGas: $reserveGas
1484
+ ) {
1485
+ transaction {
1486
+ id
1487
+ inputs {
1488
+ ... on InputCoin {
1489
+ ...InputCoinFragment
1490
+ }
1491
+ ... on InputContract {
1492
+ ...InputContractFragment
1493
+ }
1494
+ ... on InputMessage {
1495
+ ...InputMessageFragment
1496
+ }
1497
+ }
1498
+ outputs {
1499
+ ... on CoinOutput {
1500
+ ...OutputCoinFragment
1501
+ }
1502
+ ... on ContractOutput {
1503
+ ...OutputContractFragment
1504
+ }
1505
+ ... on ChangeOutput {
1506
+ ...OutputChangeFragment
1507
+ }
1508
+ ... on VariableOutput {
1509
+ ...OutputVariableFragment
1510
+ }
1511
+ ... on ContractCreated {
1512
+ ...OutputContractCreatedFragment
1513
+ }
1514
+ }
1515
+ policies {
1516
+ tip
1517
+ witnessLimit
1518
+ maturity
1519
+ maxFee
1520
+ }
1521
+ witnesses
1522
+ scriptGasLimit
1523
+ }
1524
+ status {
1525
+ ... on DryRunFailureStatus {
1526
+ ...dryRunFailureAssembleTxFragment
1527
+ }
1528
+ ... on DryRunSuccessStatus {
1529
+ ...dryRunSuccessAssembleTxFragment
1530
+ }
1531
+ }
1532
+ gasPrice
1533
+ }
1534
+ }
1535
+ ${InputCoinFragmentDoc}
1536
+ ${InputContractFragmentDoc}
1537
+ ${InputMessageFragmentDoc}
1538
+ ${OutputCoinFragmentDoc}
1539
+ ${OutputContractFragmentDoc}
1540
+ ${OutputChangeFragmentDoc}
1541
+ ${OutputVariableFragmentDoc}
1542
+ ${OutputContractCreatedFragmentDoc}
1543
+ ${DryRunFailureAssembleTxFragmentDoc}
1544
+ ${DryRunSuccessAssembleTxFragmentDoc}`;
1276
1545
  var DryRunDocument = gql`
1277
- mutation dryRun($encodedTransactions: [HexString!]!, $utxoValidation: Boolean, $gasPrice: U64) {
1546
+ query dryRun($encodedTransactions: [HexString!]!, $utxoValidation: Boolean, $gasPrice: U64) {
1278
1547
  dryRun(
1279
1548
  txs: $encodedTransactions
1280
1549
  utxoValidation: $utxoValidation
@@ -1331,15 +1600,22 @@ var GetConsensusParametersVersionDocument = gql`
1331
1600
  }
1332
1601
  `;
1333
1602
  var SubmitAndAwaitStatusDocument = gql`
1334
- subscription submitAndAwaitStatus($encodedTransaction: HexString!) {
1335
- submitAndAwaitStatus(tx: $encodedTransaction) {
1603
+ subscription submitAndAwaitStatus($encodedTransaction: HexString!, $estimatePredicates: Boolean, $includePreConfirmation: Boolean) {
1604
+ submitAndAwaitStatus(
1605
+ tx: $encodedTransaction
1606
+ estimatePredicates: $estimatePredicates
1607
+ includePreconfirmation: $includePreConfirmation
1608
+ ) {
1336
1609
  ...transactionStatusSubscriptionFragment
1337
1610
  }
1338
1611
  }
1339
1612
  ${TransactionStatusSubscriptionFragmentDoc}`;
1340
1613
  var StatusChangeDocument = gql`
1341
- subscription statusChange($transactionId: TransactionId!) {
1342
- statusChange(id: $transactionId) {
1614
+ subscription statusChange($transactionId: TransactionId!, $includePreConfirmation: Boolean) {
1615
+ statusChange(
1616
+ id: $transactionId
1617
+ includePreconfirmation: $includePreConfirmation
1618
+ ) {
1343
1619
  ...transactionStatusSubscriptionFragment
1344
1620
  }
1345
1621
  }
@@ -1442,6 +1718,9 @@ function getSdk(requester) {
1442
1718
  getAssetDetails(variables, options) {
1443
1719
  return requester(GetAssetDetailsDocument, variables, options);
1444
1720
  },
1721
+ assembleTx(variables, options) {
1722
+ return requester(AssembleTxDocument, variables, options);
1723
+ },
1445
1724
  dryRun(variables, options) {
1446
1725
  return requester(DryRunDocument, variables, options);
1447
1726
  },
@@ -1470,36 +1749,123 @@ function getSdk(requester) {
1470
1749
  }
1471
1750
  __name(getSdk, "getSdk");
1472
1751
 
1752
+ // src/providers/assemble-tx-helpers.ts
1753
+ import { FuelError as FuelError2, ErrorCode } from "@fuel-ts/errors";
1754
+ import { bn as bn2 } from "@fuel-ts/math";
1755
+ import { TransactionType } from "@fuel-ts/transactions";
1756
+ import { hexlify as hexlify4, isDefined } from "@fuel-ts/utils";
1757
+ var resolveAccountForAssembleTxParams = /* @__PURE__ */ __name((account) => {
1758
+ const assembleTxAccount = {};
1759
+ const accountIsPredicate = "bytes" in account;
1760
+ if (accountIsPredicate) {
1761
+ assembleTxAccount.predicate = {
1762
+ predicate: hexlify4(account.bytes),
1763
+ predicateAddress: account.address.toB256(),
1764
+ predicateData: hexlify4(account.getPredicateData())
1765
+ };
1766
+ } else {
1767
+ assembleTxAccount.address = account.address.toB256();
1768
+ }
1769
+ return assembleTxAccount;
1770
+ }, "resolveAccountForAssembleTxParams");
1771
+ var setAndValidateGasAndFeeForAssembledTx = /* @__PURE__ */ __name(async (params) => {
1772
+ const { gasPrice, transactionRequest, setGasLimit, setMaxFee, provider } = params;
1773
+ const gasLimitSpecified = isDefined(setGasLimit);
1774
+ const maxFeeSpecified = isDefined(setMaxFee);
1775
+ const isScriptTx = transactionRequest.type === TransactionType.Script;
1776
+ if (gasLimitSpecified && isScriptTx) {
1777
+ const requiredGasLimit = transactionRequest.gasLimit;
1778
+ if (bn2(setGasLimit).lt(bn2(requiredGasLimit))) {
1779
+ throw new FuelError2(
1780
+ ErrorCode.GAS_LIMIT_TOO_LOW,
1781
+ `Gas limit '${setGasLimit}' is lower than the required: '${requiredGasLimit}'.`
1782
+ );
1783
+ }
1784
+ transactionRequest.gasLimit = bn2(setGasLimit);
1785
+ }
1786
+ if (maxFeeSpecified) {
1787
+ const requiredMaxFee = transactionRequest.maxFee;
1788
+ if (bn2(setMaxFee).lt(requiredMaxFee)) {
1789
+ throw new FuelError2(
1790
+ ErrorCode.MAX_FEE_TOO_LOW,
1791
+ `Max fee '${setMaxFee}' is lower than the required: '${requiredMaxFee}'.`
1792
+ );
1793
+ }
1794
+ transactionRequest.maxFee = bn2(setMaxFee);
1795
+ }
1796
+ if (gasLimitSpecified && !maxFeeSpecified) {
1797
+ const { maxFee: feeForGasPrice } = await provider.estimateTxGasAndFee({
1798
+ transactionRequest,
1799
+ gasPrice
1800
+ });
1801
+ transactionRequest.maxFee = feeForGasPrice;
1802
+ }
1803
+ return transactionRequest;
1804
+ }, "setAndValidateGasAndFeeForAssembledTx");
1805
+
1473
1806
  // src/providers/fuel-graphql-subscriber.ts
1474
- import { ErrorCode as ErrorCode2, FuelError as FuelError3 } from "@fuel-ts/errors";
1807
+ import { ErrorCode as ErrorCode3, FuelError as FuelError4 } from "@fuel-ts/errors";
1475
1808
  import { print } from "graphql";
1476
1809
 
1477
1810
  // src/providers/utils/handle-gql-error-message.ts
1478
- import { ErrorCode, FuelError as FuelError2 } from "@fuel-ts/errors";
1811
+ import { ErrorCode as ErrorCode2, FuelError as FuelError3 } from "@fuel-ts/errors";
1812
+ var gqlErrorMessage = {
1813
+ RPC_CONSISTENCY: /The required fuel block height is higher than the current block height. Required: \d+, Current: \d+/,
1814
+ NOT_ENOUGH_COINS_MAX_COINS: /the target cannot be met due to no coins available or exceeding the \d+ coin limit./,
1815
+ ASSET_NOT_FOUND: /resource was not found in table/,
1816
+ MULTIPLE_CHANGE_POLICIES: /The asset ([a-fA-F0-9]{64}) has multiple change policies/,
1817
+ DUPLICATE_CHANGE_OUTPUT_ACCOUNT: /required balances contain duplicate \(asset, account\) pair/,
1818
+ INSUFFICIENT_FEE_AMOUNT: /InsufficientFeeAmount { expected: (\d+), provided: (\d+) }/
1819
+ };
1479
1820
  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,
1821
+ if (gqlErrorMessage.NOT_ENOUGH_COINS_MAX_COINS.test(error.message)) {
1822
+ return new FuelError3(
1823
+ ErrorCode2.INSUFFICIENT_FUNDS_OR_MAX_COINS,
1483
1824
  `Insufficient funds or too many small value coins. Consider combining UTXOs.`,
1484
1825
  {},
1485
1826
  error
1486
1827
  );
1487
1828
  }
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,
1829
+ if (gqlErrorMessage.MULTIPLE_CHANGE_POLICIES.test(error.message)) {
1830
+ const match = error.message.match(/asset ([a-fA-F0-9]{64})/);
1831
+ const assetId = match?.[1] || "";
1832
+ return new FuelError3(
1833
+ ErrorCode2.CHANGE_OUTPUT_COLLISION,
1834
+ `OutputChange address for asset 0x${assetId} differs between transaction request and assembleTx parameters.`,
1835
+ {},
1836
+ error
1837
+ );
1838
+ }
1839
+ if (gqlErrorMessage.DUPLICATE_CHANGE_OUTPUT_ACCOUNT.test(error.message)) {
1840
+ return new FuelError3(
1841
+ ErrorCode2.DUPLICATE_CHANGE_OUTPUT_ACCOUNT,
1842
+ `The parameter 'accountCoinQuantities' of assembleTx contains duplicate entries for the same assetId with different 'changeOutputAccount'.`,
1843
+ {},
1844
+ error
1845
+ );
1846
+ }
1847
+ if (gqlErrorMessage.ASSET_NOT_FOUND.test(error.message)) {
1848
+ return new FuelError3(
1849
+ ErrorCode2.ASSET_NOT_FOUND,
1491
1850
  `Asset not found for given asset id.`,
1492
1851
  {},
1493
1852
  error
1494
1853
  );
1495
1854
  }
1496
- return new FuelError2(ErrorCode.INVALID_REQUEST, error.message, {}, error);
1855
+ if (gqlErrorMessage.RPC_CONSISTENCY.test(error.message)) {
1856
+ return new FuelError3(ErrorCode2.RPC_CONSISTENCY, error.message, {}, error);
1857
+ }
1858
+ if (gqlErrorMessage.INSUFFICIENT_FEE_AMOUNT.test(error.message)) {
1859
+ const match = error.message.match(gqlErrorMessage.INSUFFICIENT_FEE_AMOUNT);
1860
+ return new FuelError3(ErrorCode2.FUNDS_TOO_LOW, match?.[0] || error.message, {}, error);
1861
+ }
1862
+ return new FuelError3(ErrorCode2.INVALID_REQUEST, error.message, {}, error);
1497
1863
  }, "mapGqlErrorMessage");
1498
1864
  var mapGqlErrorWithIncompatibleNodeVersion = /* @__PURE__ */ __name((error, incompatibleNodeVersionMessage) => {
1499
1865
  if (!incompatibleNodeVersionMessage) {
1500
1866
  return error;
1501
1867
  }
1502
- return new FuelError2(
1868
+ return new FuelError3(
1503
1869
  error.code,
1504
1870
  `${error.message}
1505
1871
 
@@ -1518,15 +1884,16 @@ var assertGqlResponseHasNoErrors = /* @__PURE__ */ __name((errors, incompatibleN
1518
1884
  }
1519
1885
  const errorMessage = mappedErrors.map((err) => err.message).join("\n");
1520
1886
  throw mapGqlErrorWithIncompatibleNodeVersion(
1521
- new FuelError2(ErrorCode.INVALID_REQUEST, errorMessage, {}, mappedErrors),
1887
+ new FuelError3(ErrorCode2.INVALID_REQUEST, errorMessage, {}, mappedErrors),
1522
1888
  incompatibleNodeVersionMessage
1523
1889
  );
1524
1890
  }, "assertGqlResponseHasNoErrors");
1525
1891
 
1526
1892
  // src/providers/fuel-graphql-subscriber.ts
1527
1893
  var FuelGraphqlSubscriber = class _FuelGraphqlSubscriber {
1528
- constructor(stream) {
1894
+ constructor(stream, onEvent) {
1529
1895
  this.stream = stream;
1896
+ this.onEvent = onEvent;
1530
1897
  }
1531
1898
  static {
1532
1899
  __name(this, "FuelGraphqlSubscriber");
@@ -1534,12 +1901,13 @@ var FuelGraphqlSubscriber = class _FuelGraphqlSubscriber {
1534
1901
  static incompatibleNodeVersionMessage = false;
1535
1902
  static textDecoder = new TextDecoder();
1536
1903
  static async create(options) {
1537
- const { url, query, variables, fetchFn } = options;
1904
+ const { url, query, variables, fetchFn, operationName, onEvent } = options;
1538
1905
  const response = await fetchFn(`${url}-sub`, {
1539
1906
  method: "POST",
1540
1907
  body: JSON.stringify({
1541
1908
  query: print(query),
1542
- variables
1909
+ variables,
1910
+ operationName
1543
1911
  }),
1544
1912
  headers: {
1545
1913
  "Content-Type": "application/json",
@@ -1548,39 +1916,71 @@ var FuelGraphqlSubscriber = class _FuelGraphqlSubscriber {
1548
1916
  });
1549
1917
  const [errorReader, resultReader] = response.body.tee().map((stream) => stream.getReader());
1550
1918
  await new _FuelGraphqlSubscriber(errorReader).next();
1551
- return new _FuelGraphqlSubscriber(resultReader);
1919
+ return new _FuelGraphqlSubscriber(resultReader, onEvent);
1552
1920
  }
1553
- events = [];
1554
- parsingLeftover = "";
1555
- async next() {
1921
+ /**
1922
+ * This method will take a stream reader and parse the event from the stream.
1923
+ *
1924
+ * @param reader - The reader of the SSE stream
1925
+ * @param parsingLeftover - The leftover string from parsing the previous event
1926
+ * @returns The event parsed as a full GraphQL response, whether the stream is done and the leftover string after parsing
1927
+ */
1928
+ static async readEvent(reader, parsingLeftover = "") {
1929
+ let text = parsingLeftover;
1930
+ const regex = /data:.*\n\n/g;
1556
1931
  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
1932
  const matches = [...text.matchAll(regex)].flatMap((match) => match);
1573
- matches.forEach((match) => {
1933
+ if (matches.length > 0) {
1574
1934
  try {
1575
- this.events.push(JSON.parse(match.replace(/^data:/, "")));
1935
+ const event = JSON.parse(matches[0].replace(/^data:/, ""));
1936
+ return {
1937
+ event,
1938
+ done: false,
1939
+ parsingLeftover: text.replace(matches[0], "")
1940
+ };
1576
1941
  } catch (e) {
1577
- throw new FuelError3(
1578
- ErrorCode2.STREAM_PARSING_ERROR,
1942
+ throw new FuelError4(
1943
+ ErrorCode3.STREAM_PARSING_ERROR,
1579
1944
  `Error while parsing stream data response: ${text}`
1580
1945
  );
1581
1946
  }
1582
- });
1583
- this.parsingLeftover = text.replace(matches.join(), "");
1947
+ }
1948
+ const { value, done } = await reader.read();
1949
+ if (done) {
1950
+ return { event: void 0, done, parsingLeftover: "" };
1951
+ }
1952
+ const decoded = _FuelGraphqlSubscriber.textDecoder.decode(value).replace(":keep-alive-text\n\n", "");
1953
+ text += decoded;
1954
+ }
1955
+ }
1956
+ events = [];
1957
+ parsingLeftover = "";
1958
+ /**
1959
+ * Gets automatically called when iterating in a `for-await-of` loop.
1960
+ * It can also be called manually.
1961
+ *
1962
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/next
1963
+ */
1964
+ async next() {
1965
+ while (true) {
1966
+ const nextEvent = this.events.shift();
1967
+ if (nextEvent) {
1968
+ this.onEvent?.(nextEvent);
1969
+ assertGqlResponseHasNoErrors(
1970
+ nextEvent.errors,
1971
+ _FuelGraphqlSubscriber.incompatibleNodeVersionMessage
1972
+ );
1973
+ return { value: nextEvent.data, done: false };
1974
+ }
1975
+ const { event, done, parsingLeftover } = await _FuelGraphqlSubscriber.readEvent(
1976
+ this.stream,
1977
+ this.parsingLeftover
1978
+ );
1979
+ this.parsingLeftover = parsingLeftover;
1980
+ if (done) {
1981
+ return { value: void 0, done: true };
1982
+ }
1983
+ this.events.push(event);
1584
1984
  }
1585
1985
  }
1586
1986
  /**
@@ -1595,16 +1995,16 @@ var FuelGraphqlSubscriber = class _FuelGraphqlSubscriber {
1595
1995
  };
1596
1996
 
1597
1997
  // 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";
1998
+ import { FuelError as FuelError14, ErrorCode as ErrorCode11 } from "@fuel-ts/errors";
1999
+ import { hexlify as hexlify17 } from "@fuel-ts/utils";
1600
2000
 
1601
2001
  // src/providers/transaction-request/input.ts
1602
2002
  import { BYTES_32 as BYTES_322, UTXO_ID_LEN } from "@fuel-ts/abi-coder";
1603
2003
  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";
2004
+ import { ErrorCode as ErrorCode4, FuelError as FuelError5 } from "@fuel-ts/errors";
2005
+ import { bn as bn3, toNumber } from "@fuel-ts/math";
1606
2006
  import { InputType } from "@fuel-ts/transactions";
1607
- import { arrayify as arrayify2, hexlify as hexlify4 } from "@fuel-ts/utils";
2007
+ import { arrayify as arrayify2, hexlify as hexlify5 } from "@fuel-ts/utils";
1608
2008
  var inputify = /* @__PURE__ */ __name((value) => {
1609
2009
  const { type } = value;
1610
2010
  switch (value.type) {
@@ -1613,27 +2013,27 @@ var inputify = /* @__PURE__ */ __name((value) => {
1613
2013
  const predicateData = arrayify2(value.predicateData ?? "0x");
1614
2014
  return {
1615
2015
  type: InputType.Coin,
1616
- txID: hexlify4(arrayify2(value.id).slice(0, BYTES_322)),
2016
+ txID: hexlify5(arrayify2(value.id).slice(0, BYTES_322)),
1617
2017
  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),
2018
+ owner: hexlify5(value.owner),
2019
+ amount: bn3(value.amount),
2020
+ assetId: hexlify5(value.assetId),
1621
2021
  txPointer: {
1622
2022
  blockHeight: toNumber(arrayify2(value.txPointer).slice(0, 8)),
1623
2023
  txIndex: toNumber(arrayify2(value.txPointer).slice(8, 16))
1624
2024
  },
1625
2025
  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)
2026
+ predicateGasUsed: bn3(value.predicateGasUsed),
2027
+ predicateLength: bn3(predicate.length),
2028
+ predicateDataLength: bn3(predicateData.length),
2029
+ predicate: hexlify5(predicate),
2030
+ predicateData: hexlify5(predicateData)
1631
2031
  };
1632
2032
  }
1633
2033
  case InputType.Contract: {
1634
2034
  return {
1635
2035
  type: InputType.Contract,
1636
- txID: ZeroBytes32,
2036
+ txID: hexlify5(value.txID || ZeroBytes32),
1637
2037
  outputIndex: 0,
1638
2038
  balanceRoot: ZeroBytes32,
1639
2039
  stateRoot: ZeroBytes32,
@@ -1641,7 +2041,7 @@ var inputify = /* @__PURE__ */ __name((value) => {
1641
2041
  blockHeight: toNumber(arrayify2(value.txPointer).slice(0, 8)),
1642
2042
  txIndex: toNumber(arrayify2(value.txPointer).slice(8, 16))
1643
2043
  },
1644
- contractID: hexlify4(value.contractId)
2044
+ contractID: hexlify5(value.contractId)
1645
2045
  };
1646
2046
  }
1647
2047
  case InputType.Message: {
@@ -1650,23 +2050,23 @@ var inputify = /* @__PURE__ */ __name((value) => {
1650
2050
  const data = arrayify2(value.data ?? "0x");
1651
2051
  return {
1652
2052
  type: InputType.Message,
1653
- sender: hexlify4(value.sender),
1654
- recipient: hexlify4(value.recipient),
1655
- amount: bn2(value.amount),
1656
- nonce: hexlify4(value.nonce),
2053
+ sender: hexlify5(value.sender),
2054
+ recipient: hexlify5(value.recipient),
2055
+ amount: bn3(value.amount),
2056
+ nonce: hexlify5(value.nonce),
1657
2057
  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),
2058
+ predicateGasUsed: bn3(value.predicateGasUsed),
2059
+ predicateLength: bn3(predicate.length),
2060
+ predicateDataLength: bn3(predicateData.length),
2061
+ predicate: hexlify5(predicate),
2062
+ predicateData: hexlify5(predicateData),
2063
+ data: hexlify5(data),
1664
2064
  dataLength: data.length
1665
2065
  };
1666
2066
  }
1667
2067
  default: {
1668
- throw new FuelError4(
1669
- ErrorCode3.INVALID_TRANSACTION_INPUT,
2068
+ throw new FuelError5(
2069
+ ErrorCode4.INVALID_TRANSACTION_INPUT,
1670
2070
  `Invalid transaction input type: ${type}.`
1671
2071
  );
1672
2072
  }
@@ -1675,19 +2075,19 @@ var inputify = /* @__PURE__ */ __name((value) => {
1675
2075
 
1676
2076
  // src/providers/transaction-request/output.ts
1677
2077
  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";
2078
+ import { ErrorCode as ErrorCode5, FuelError as FuelError6 } from "@fuel-ts/errors";
2079
+ import { bn as bn4 } from "@fuel-ts/math";
1680
2080
  import { OutputType } from "@fuel-ts/transactions";
1681
- import { hexlify as hexlify5 } from "@fuel-ts/utils";
2081
+ import { hexlify as hexlify6 } from "@fuel-ts/utils";
1682
2082
  var outputify = /* @__PURE__ */ __name((value) => {
1683
2083
  const { type } = value;
1684
2084
  switch (type) {
1685
2085
  case OutputType.Coin: {
1686
2086
  return {
1687
2087
  type: OutputType.Coin,
1688
- to: hexlify5(value.to),
1689
- amount: bn3(value.amount),
1690
- assetId: hexlify5(value.assetId)
2088
+ to: hexlify6(value.to),
2089
+ amount: bn4(value.amount),
2090
+ assetId: hexlify6(value.assetId)
1691
2091
  };
1692
2092
  }
1693
2093
  case OutputType.Contract: {
@@ -1701,29 +2101,29 @@ var outputify = /* @__PURE__ */ __name((value) => {
1701
2101
  case OutputType.Change: {
1702
2102
  return {
1703
2103
  type: OutputType.Change,
1704
- to: hexlify5(value.to),
1705
- amount: bn3(0),
1706
- assetId: hexlify5(value.assetId)
2104
+ to: hexlify6(value.to),
2105
+ amount: bn4(0),
2106
+ assetId: hexlify6(value.assetId)
1707
2107
  };
1708
2108
  }
1709
2109
  case OutputType.Variable: {
1710
2110
  return {
1711
2111
  type: OutputType.Variable,
1712
- to: ZeroBytes322,
1713
- amount: bn3(0),
1714
- assetId: ZeroBytes322
2112
+ to: hexlify6(value.to || ZeroBytes322),
2113
+ amount: bn4(value.amount),
2114
+ assetId: hexlify6(value.assetId || ZeroBytes322)
1715
2115
  };
1716
2116
  }
1717
2117
  case OutputType.ContractCreated: {
1718
2118
  return {
1719
2119
  type: OutputType.ContractCreated,
1720
- contractId: hexlify5(value.contractId),
1721
- stateRoot: hexlify5(value.stateRoot)
2120
+ contractId: hexlify6(value.contractId),
2121
+ stateRoot: hexlify6(value.stateRoot)
1722
2122
  };
1723
2123
  }
1724
2124
  default: {
1725
- throw new FuelError5(
1726
- ErrorCode4.INVALID_TRANSACTION_INPUT,
2125
+ throw new FuelError6(
2126
+ ErrorCode5.INVALID_TRANSACTION_INPUT,
1727
2127
  `Invalid transaction output type: ${type}.`
1728
2128
  );
1729
2129
  }
@@ -1735,16 +2135,16 @@ import { UTXO_ID_LEN as UTXO_ID_LEN2 } from "@fuel-ts/abi-coder";
1735
2135
  import { Address as Address2, addressify } from "@fuel-ts/address";
1736
2136
  import { ZeroBytes32 as ZeroBytes324 } from "@fuel-ts/address/configs";
1737
2137
  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";
2138
+ import { FuelError as FuelError11 } from "@fuel-ts/errors";
2139
+ import { bn as bn9 } from "@fuel-ts/math";
1740
2140
  import {
1741
2141
  PolicyType,
1742
2142
  TransactionCoder,
1743
- InputType as InputType3,
1744
- OutputType as OutputType3,
1745
- TransactionType
2143
+ InputType as InputType4,
2144
+ OutputType as OutputType4,
2145
+ TransactionType as TransactionType2
1746
2146
  } from "@fuel-ts/transactions";
1747
- import { concat as concat2, hexlify as hexlify10, isDefined } from "@fuel-ts/utils";
2147
+ import { concat as concat2, hexlify as hexlify11, isDefined as isDefined2 } from "@fuel-ts/utils";
1748
2148
 
1749
2149
  // src/providers/message.ts
1750
2150
  var isMessageCoin = /* @__PURE__ */ __name((message) => !("data" in message), "isMessageCoin");
@@ -1758,12 +2158,18 @@ import { FAILED_TRANSFER_TO_ADDRESS_SIGNAL } from "@fuel-ts/transactions/configs
1758
2158
 
1759
2159
  // src/providers/utils/serialization.ts
1760
2160
  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";
2161
+ import { ErrorCode as ErrorCode6, FuelError as FuelError7 } from "@fuel-ts/errors";
2162
+ import { bn as bn5 } from "@fuel-ts/math";
2163
+ import {
2164
+ getMintedAssetId,
2165
+ InputMessageCoder,
2166
+ InputType as InputType2,
2167
+ OutputType as OutputType2,
2168
+ ReceiptType
2169
+ } from "@fuel-ts/transactions";
2170
+ import { hexlify as hexlify7, arrayify as arrayify3, assertUnreachable } from "@fuel-ts/utils";
1765
2171
  var deserializeChain = /* @__PURE__ */ __name((chain) => {
1766
- const { name, daHeight, consensusParameters } = chain;
2172
+ const { name, daHeight, consensusParameters, latestBlock } = chain;
1767
2173
  const {
1768
2174
  contractParams,
1769
2175
  feeParams,
@@ -1777,48 +2183,49 @@ var deserializeChain = /* @__PURE__ */ __name((chain) => {
1777
2183
  } = consensusParameters;
1778
2184
  return {
1779
2185
  name,
1780
- baseChainHeight: bn4(daHeight),
2186
+ baseChainHeight: bn5(daHeight),
1781
2187
  consensusParameters: {
1782
2188
  version,
1783
- chainId: bn4(chainId),
2189
+ chainId: bn5(chainId),
1784
2190
  baseAssetId,
1785
2191
  feeParameters: {
1786
2192
  version: feeParams.version,
1787
- gasPerByte: bn4(feeParams.gasPerByte),
1788
- gasPriceFactor: bn4(feeParams.gasPriceFactor)
2193
+ gasPerByte: bn5(feeParams.gasPerByte),
2194
+ gasPriceFactor: bn5(feeParams.gasPriceFactor)
1789
2195
  },
1790
2196
  contractParameters: {
1791
2197
  version: contractParams.version,
1792
- contractMaxSize: bn4(contractParams.contractMaxSize),
1793
- maxStorageSlots: bn4(contractParams.maxStorageSlots)
2198
+ contractMaxSize: bn5(contractParams.contractMaxSize),
2199
+ maxStorageSlots: bn5(contractParams.maxStorageSlots)
1794
2200
  },
1795
2201
  txParameters: {
1796
2202
  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)
2203
+ maxInputs: bn5(txParams.maxInputs),
2204
+ maxOutputs: bn5(txParams.maxOutputs),
2205
+ maxWitnesses: bn5(txParams.maxWitnesses),
2206
+ maxGasPerTx: bn5(txParams.maxGasPerTx),
2207
+ maxSize: bn5(txParams.maxSize),
2208
+ maxBytecodeSubsections: bn5(txParams.maxBytecodeSubsections)
1803
2209
  },
1804
2210
  predicateParameters: {
1805
2211
  version: predicateParams.version,
1806
- maxPredicateLength: bn4(predicateParams.maxPredicateLength),
1807
- maxPredicateDataLength: bn4(predicateParams.maxPredicateDataLength),
1808
- maxGasPerPredicate: bn4(predicateParams.maxGasPerPredicate),
1809
- maxMessageDataLength: bn4(predicateParams.maxMessageDataLength)
2212
+ maxPredicateLength: bn5(predicateParams.maxPredicateLength),
2213
+ maxPredicateDataLength: bn5(predicateParams.maxPredicateDataLength),
2214
+ maxGasPerPredicate: bn5(predicateParams.maxGasPerPredicate),
2215
+ maxMessageDataLength: bn5(predicateParams.maxMessageDataLength)
1810
2216
  },
1811
2217
  scriptParameters: {
1812
2218
  version: scriptParams.version,
1813
- maxScriptLength: bn4(scriptParams.maxScriptLength),
1814
- maxScriptDataLength: bn4(scriptParams.maxScriptDataLength)
2219
+ maxScriptLength: bn5(scriptParams.maxScriptLength),
2220
+ maxScriptDataLength: bn5(scriptParams.maxScriptDataLength)
1815
2221
  },
1816
2222
  gasCosts
1817
- }
2223
+ },
2224
+ latestBlock
1818
2225
  };
1819
2226
  }, "deserializeChain");
1820
2227
  var serializeChain = /* @__PURE__ */ __name((chain) => {
1821
- const { name, baseChainHeight, consensusParameters } = chain;
2228
+ const { name, baseChainHeight, consensusParameters, latestBlock } = chain;
1822
2229
  const {
1823
2230
  contractParameters,
1824
2231
  feeParameters,
@@ -1869,14 +2276,15 @@ var serializeChain = /* @__PURE__ */ __name((chain) => {
1869
2276
  maxScriptDataLength: scriptParameters.maxScriptDataLength.toString()
1870
2277
  },
1871
2278
  gasCosts
1872
- }
2279
+ },
2280
+ latestBlock
1873
2281
  };
1874
2282
  }, "serializeChain");
1875
2283
  var deserializeNodeInfo = /* @__PURE__ */ __name((nodeInfo) => {
1876
2284
  const { maxDepth, maxTx, nodeVersion, utxoValidation, vmBacktrace, indexation } = nodeInfo;
1877
2285
  return {
1878
- maxDepth: bn4(maxDepth),
1879
- maxTx: bn4(maxTx),
2286
+ maxDepth: bn5(maxDepth),
2287
+ maxTx: bn5(maxTx),
1880
2288
  nodeVersion,
1881
2289
  utxoValidation,
1882
2290
  vmBacktrace,
@@ -1914,13 +2322,13 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1914
2322
  type: ReceiptType.Call,
1915
2323
  id,
1916
2324
  to: hexOrZero(receipt?.to),
1917
- amount: bn4(receipt.amount),
2325
+ amount: bn5(receipt.amount),
1918
2326
  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)
2327
+ gas: bn5(receipt.gas),
2328
+ param1: bn5(receipt.param1),
2329
+ param2: bn5(receipt.param2),
2330
+ pc: bn5(receipt.pc),
2331
+ is: bn5(receipt.is)
1924
2332
  };
1925
2333
  return callReceipt;
1926
2334
  }
@@ -1928,9 +2336,9 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1928
2336
  const returnReceipt = {
1929
2337
  type: ReceiptType.Return,
1930
2338
  id: hexOrZero(receipt.id || receipt.contractId),
1931
- val: bn4(receipt.val),
1932
- pc: bn4(receipt.pc),
1933
- is: bn4(receipt.is)
2339
+ val: bn5(receipt.val),
2340
+ pc: bn5(receipt.pc),
2341
+ is: bn5(receipt.is)
1934
2342
  };
1935
2343
  return returnReceipt;
1936
2344
  }
@@ -1938,12 +2346,12 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1938
2346
  const returnDataReceipt = {
1939
2347
  type: ReceiptType.ReturnData,
1940
2348
  id: hexOrZero(receipt.id || receipt.contractId),
1941
- ptr: bn4(receipt.ptr),
1942
- len: bn4(receipt.len),
2349
+ ptr: bn5(receipt.ptr),
2350
+ len: bn5(receipt.len),
1943
2351
  digest: hexOrZero(receipt.digest),
1944
- pc: bn4(receipt.pc),
2352
+ pc: bn5(receipt.pc),
1945
2353
  data: hexOrZero(receipt.data),
1946
- is: bn4(receipt.is)
2354
+ is: bn5(receipt.is)
1947
2355
  };
1948
2356
  return returnDataReceipt;
1949
2357
  }
@@ -1951,9 +2359,9 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1951
2359
  const panicReceipt = {
1952
2360
  type: ReceiptType.Panic,
1953
2361
  id: hexOrZero(receipt.id),
1954
- reason: bn4(receipt.reason),
1955
- pc: bn4(receipt.pc),
1956
- is: bn4(receipt.is),
2362
+ reason: bn5(receipt.reason),
2363
+ pc: bn5(receipt.pc),
2364
+ is: bn5(receipt.is),
1957
2365
  contractId: hexOrZero(receipt.contractId)
1958
2366
  };
1959
2367
  return panicReceipt;
@@ -1962,17 +2370,17 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1962
2370
  const revertReceipt = {
1963
2371
  type: ReceiptType.Revert,
1964
2372
  id: hexOrZero(receipt.id || receipt.contractId),
1965
- val: bn4(receipt.ra),
1966
- pc: bn4(receipt.pc),
1967
- is: bn4(receipt.is)
2373
+ val: bn5(receipt.ra),
2374
+ pc: bn5(receipt.pc),
2375
+ is: bn5(receipt.is)
1968
2376
  };
1969
2377
  return revertReceipt;
1970
2378
  }
1971
2379
  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);
2380
+ const ra = bn5(receipt.ra);
2381
+ const rb = bn5(receipt.rb);
2382
+ const rc = bn5(receipt.rc);
2383
+ const rd = bn5(receipt.rd);
1976
2384
  const logReceipt = {
1977
2385
  type: ReceiptType.Log,
1978
2386
  id: hexOrZero(receipt.id || receipt.contractId),
@@ -1980,25 +2388,25 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1980
2388
  rb,
1981
2389
  rc,
1982
2390
  rd,
1983
- pc: bn4(receipt.pc),
1984
- is: bn4(receipt.is)
2391
+ pc: bn5(receipt.pc),
2392
+ is: bn5(receipt.is)
1985
2393
  };
1986
2394
  return logReceipt;
1987
2395
  }
1988
2396
  case "LOG_DATA" /* LogData */: {
1989
- const ra = bn4(receipt.ra);
1990
- const rb = bn4(receipt.rb);
2397
+ const ra = bn5(receipt.ra);
2398
+ const rb = bn5(receipt.rb);
1991
2399
  const logDataReceipt = {
1992
2400
  type: ReceiptType.LogData,
1993
2401
  id: hexOrZero(receipt.id || receipt.contractId),
1994
2402
  ra,
1995
2403
  rb,
1996
- ptr: bn4(receipt.ptr),
1997
- len: bn4(receipt.len),
2404
+ ptr: bn5(receipt.ptr),
2405
+ len: bn5(receipt.len),
1998
2406
  digest: hexOrZero(receipt.digest),
1999
- pc: bn4(receipt.pc),
2407
+ pc: bn5(receipt.pc),
2000
2408
  data: hexOrZero(receipt.data),
2001
- is: bn4(receipt.is)
2409
+ is: bn5(receipt.is)
2002
2410
  };
2003
2411
  return logDataReceipt;
2004
2412
  }
@@ -2008,10 +2416,10 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
2008
2416
  type: ReceiptType.Transfer,
2009
2417
  id,
2010
2418
  to: hexOrZero(receipt.toAddress || receipt?.to),
2011
- amount: bn4(receipt.amount),
2419
+ amount: bn5(receipt.amount),
2012
2420
  assetId: hexOrZero(receipt.assetId),
2013
- pc: bn4(receipt.pc),
2014
- is: bn4(receipt.is)
2421
+ pc: bn5(receipt.pc),
2422
+ is: bn5(receipt.is)
2015
2423
  };
2016
2424
  return transferReceipt;
2017
2425
  }
@@ -2021,18 +2429,18 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
2021
2429
  type: ReceiptType.TransferOut,
2022
2430
  id,
2023
2431
  to: hexOrZero(receipt.toAddress || receipt.to),
2024
- amount: bn4(receipt.amount),
2432
+ amount: bn5(receipt.amount),
2025
2433
  assetId: hexOrZero(receipt.assetId),
2026
- pc: bn4(receipt.pc),
2027
- is: bn4(receipt.is)
2434
+ pc: bn5(receipt.pc),
2435
+ is: bn5(receipt.is)
2028
2436
  };
2029
2437
  return transferOutReceipt;
2030
2438
  }
2031
2439
  case "SCRIPT_RESULT" /* ScriptResult */: {
2032
2440
  const scriptResultReceipt = {
2033
2441
  type: ReceiptType.ScriptResult,
2034
- result: bn4(receipt.result),
2035
- gasUsed: bn4(receipt.gasUsed)
2442
+ result: bn5(receipt.result),
2443
+ gasUsed: bn5(receipt.gasUsed)
2036
2444
  };
2037
2445
  return scriptResultReceipt;
2038
2446
  }
@@ -2040,16 +2448,16 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
2040
2448
  const sender = hexOrZero(receipt.sender);
2041
2449
  const recipient = hexOrZero(receipt.recipient);
2042
2450
  const nonce = hexOrZero(receipt.nonce);
2043
- const amount = bn4(receipt.amount);
2451
+ const amount = bn5(receipt.amount);
2044
2452
  const data = receipt.data ? arrayify3(receipt.data) : Uint8Array.from([]);
2045
2453
  const digest = hexOrZero(receipt.digest);
2046
- const len = bn4(receipt.len).toNumber();
2454
+ const len = bn5(receipt.len).toNumber();
2047
2455
  const messageId = InputMessageCoder.getMessageId({
2048
2456
  sender,
2049
2457
  recipient,
2050
2458
  nonce,
2051
2459
  amount,
2052
- data: hexlify6(data)
2460
+ data: hexlify7(data)
2053
2461
  });
2054
2462
  const receiptMessageOut = {
2055
2463
  type: ReceiptType.MessageOut,
@@ -2073,9 +2481,9 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
2073
2481
  subId,
2074
2482
  contractId,
2075
2483
  assetId,
2076
- val: bn4(receipt.val),
2077
- pc: bn4(receipt.pc),
2078
- is: bn4(receipt.is)
2484
+ val: bn5(receipt.val),
2485
+ pc: bn5(receipt.pc),
2486
+ is: bn5(receipt.is)
2079
2487
  };
2080
2488
  return mintReceipt;
2081
2489
  }
@@ -2088,16 +2496,151 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
2088
2496
  subId,
2089
2497
  contractId,
2090
2498
  assetId,
2091
- val: bn4(receipt.val),
2092
- pc: bn4(receipt.pc),
2093
- is: bn4(receipt.is)
2499
+ val: bn5(receipt.val),
2500
+ pc: bn5(receipt.pc),
2501
+ is: bn5(receipt.is)
2094
2502
  };
2095
2503
  return burnReceipt;
2096
2504
  }
2097
2505
  default:
2098
- throw new FuelError6(ErrorCode5.INVALID_RECEIPT_TYPE, `Invalid receipt type: ${receiptType}.`);
2506
+ throw new FuelError7(ErrorCode6.INVALID_RECEIPT_TYPE, `Invalid receipt type: ${receiptType}.`);
2099
2507
  }
2100
2508
  }, "deserializeReceipt");
2509
+ var deserializeInput = /* @__PURE__ */ __name((input) => {
2510
+ let parsedInput;
2511
+ switch (input.type) {
2512
+ case "InputCoin":
2513
+ parsedInput = {
2514
+ type: InputType2.Coin,
2515
+ id: input.utxoId,
2516
+ amount: bn5(input.amount),
2517
+ assetId: input.assetId,
2518
+ owner: input.owner,
2519
+ txPointer: `0x${input.txPointer}`,
2520
+ witnessIndex: Number(input.coinWitnessIndex),
2521
+ predicate: input.predicate,
2522
+ predicateData: input.predicateData,
2523
+ predicateGasUsed: bn5(input.predicateGasUsed)
2524
+ };
2525
+ break;
2526
+ case "InputMessage":
2527
+ parsedInput = {
2528
+ type: InputType2.Message,
2529
+ nonce: input.nonce,
2530
+ amount: bn5(input.amount),
2531
+ recipient: input.recipient,
2532
+ sender: input.sender,
2533
+ data: input.data,
2534
+ witnessIndex: Number(input.messageWitnessIndex),
2535
+ predicate: input.predicate,
2536
+ predicateData: input.predicateData,
2537
+ predicateGasUsed: bn5(input.predicateGasUsed)
2538
+ };
2539
+ break;
2540
+ case "InputContract":
2541
+ parsedInput = {
2542
+ type: InputType2.Contract,
2543
+ contractId: input.contractId,
2544
+ txPointer: `0x${input.txPointer}`,
2545
+ txID: hexlify7(arrayify3(input.utxoId).slice(0, 32))
2546
+ };
2547
+ break;
2548
+ default:
2549
+ assertUnreachable(input);
2550
+ }
2551
+ return parsedInput;
2552
+ }, "deserializeInput");
2553
+ var deserializeOutput = /* @__PURE__ */ __name((output) => {
2554
+ let parsedOutput;
2555
+ switch (output.type) {
2556
+ case "CoinOutput":
2557
+ parsedOutput = {
2558
+ type: OutputType2.Coin,
2559
+ amount: bn5(output.amount),
2560
+ assetId: output.assetId,
2561
+ to: output.to
2562
+ };
2563
+ break;
2564
+ case "ContractOutput":
2565
+ parsedOutput = {
2566
+ type: OutputType2.Contract,
2567
+ inputIndex: Number(output.inputIndex)
2568
+ };
2569
+ break;
2570
+ case "ChangeOutput":
2571
+ parsedOutput = {
2572
+ type: OutputType2.Change,
2573
+ assetId: output.assetId,
2574
+ to: output.to
2575
+ };
2576
+ break;
2577
+ case "ContractCreated":
2578
+ parsedOutput = {
2579
+ type: OutputType2.ContractCreated,
2580
+ stateRoot: output.stateRoot,
2581
+ contractId: output.contract
2582
+ };
2583
+ break;
2584
+ case "VariableOutput":
2585
+ parsedOutput = {
2586
+ type: OutputType2.Variable,
2587
+ amount: bn5(output.amount),
2588
+ assetId: output.assetId,
2589
+ to: output.to
2590
+ };
2591
+ break;
2592
+ default:
2593
+ assertUnreachable(output);
2594
+ }
2595
+ return parsedOutput;
2596
+ }, "deserializeOutput");
2597
+ var deserializeProcessedTxOutput = /* @__PURE__ */ __name((output) => {
2598
+ let parsedOutput;
2599
+ switch (output.type) {
2600
+ case "CoinOutput":
2601
+ parsedOutput = {
2602
+ type: OutputType2.Coin,
2603
+ amount: bn5(output.amount),
2604
+ assetId: output.assetId,
2605
+ to: output.to
2606
+ };
2607
+ break;
2608
+ case "ContractOutput":
2609
+ parsedOutput = {
2610
+ type: OutputType2.Contract,
2611
+ inputIndex: Number(output.inputIndex),
2612
+ balanceRoot: output.balanceRoot,
2613
+ stateRoot: output.stateRoot
2614
+ };
2615
+ break;
2616
+ case "ChangeOutput":
2617
+ parsedOutput = {
2618
+ type: OutputType2.Change,
2619
+ assetId: output.assetId,
2620
+ to: output.to,
2621
+ amount: bn5(output.amount)
2622
+ };
2623
+ break;
2624
+ case "ContractCreated":
2625
+ parsedOutput = {
2626
+ type: OutputType2.ContractCreated,
2627
+ stateRoot: output.stateRoot,
2628
+ contractId: output.contract
2629
+ };
2630
+ break;
2631
+ case "VariableOutput":
2632
+ parsedOutput = {
2633
+ type: OutputType2.Variable,
2634
+ amount: bn5(output.amount),
2635
+ assetId: output.assetId,
2636
+ to: output.to
2637
+ };
2638
+ break;
2639
+ default:
2640
+ assertUnreachable(output);
2641
+ }
2642
+ return parsedOutput;
2643
+ }, "deserializeProcessedTxOutput");
2101
2644
 
2102
2645
  // src/providers/utils/receipts.ts
2103
2646
  var doesReceiptHaveMissingOutputVariables = /* @__PURE__ */ __name((receipt) => receipt.type === ReceiptType2.Revert && receipt.val.toString("hex") === FAILED_TRANSFER_TO_ADDRESS_SIGNAL, "doesReceiptHaveMissingOutputVariables");
@@ -2119,26 +2662,26 @@ var getReceiptsWithMissingData = /* @__PURE__ */ __name((receipts) => receipts.r
2119
2662
  ), "getReceiptsWithMissingData");
2120
2663
 
2121
2664
  // src/providers/utils/block-explorer.ts
2122
- import { ErrorCode as ErrorCode6, FuelError as FuelError7 } from "@fuel-ts/errors";
2665
+ import { ErrorCode as ErrorCode7, FuelError as FuelError8 } from "@fuel-ts/errors";
2123
2666
 
2124
2667
  // src/providers/utils/gas.ts
2125
- import { bn as bn5 } from "@fuel-ts/math";
2668
+ import { bn as bn6 } from "@fuel-ts/math";
2126
2669
  import { ReceiptType as ReceiptType3 } from "@fuel-ts/transactions";
2127
2670
  import { arrayify as arrayify4 } from "@fuel-ts/utils";
2128
2671
  var getGasUsedFromReceipts = /* @__PURE__ */ __name((receipts) => {
2129
2672
  const scriptResult = receipts.filter(
2130
2673
  (receipt) => receipt.type === ReceiptType3.ScriptResult
2131
2674
  );
2132
- const gasUsed = scriptResult.reduce((prev, receipt) => prev.add(receipt.gasUsed), bn5(0));
2675
+ const gasUsed = scriptResult.reduce((prev, receipt) => prev.add(receipt.gasUsed), bn6(0));
2133
2676
  return gasUsed;
2134
2677
  }, "getGasUsedFromReceipts");
2135
2678
  function resolveGasDependentCosts(byteSize, gasDependentCost) {
2136
- const base = bn5(gasDependentCost.base);
2137
- let dependentValue = bn5(0);
2679
+ const base = bn6(gasDependentCost.base);
2680
+ let dependentValue = bn6(0);
2138
2681
  if ("unitsPerGas" in gasDependentCost) {
2139
- dependentValue = bn5(byteSize).div(bn5(gasDependentCost.unitsPerGas));
2682
+ dependentValue = bn6(byteSize).div(bn6(gasDependentCost.unitsPerGas));
2140
2683
  } else {
2141
- dependentValue = bn5(byteSize).mul(bn5(gasDependentCost.gasPerUnit));
2684
+ dependentValue = bn6(byteSize).mul(bn6(gasDependentCost.gasPerUnit));
2142
2685
  }
2143
2686
  return base.add(dependentValue);
2144
2687
  }
@@ -2162,18 +2705,18 @@ function gasUsedByInputs(inputs, txBytesSize, gasCosts) {
2162
2705
  const totalGas = chargeableInputs.reduce((total, input) => {
2163
2706
  if ("predicate" in input && input.predicate && input.predicate !== "0x") {
2164
2707
  return total.add(
2165
- vmInitializationCost.add(resolveGasDependentCosts(arrayify4(input.predicate).length, gasCosts.contractRoot)).add(bn5(input.predicateGasUsed))
2708
+ vmInitializationCost.add(resolveGasDependentCosts(arrayify4(input.predicate).length, gasCosts.contractRoot)).add(bn6(input.predicateGasUsed))
2166
2709
  );
2167
2710
  }
2168
2711
  return total.add(gasCosts.ecr1);
2169
- }, bn5(0));
2712
+ }, bn6(0));
2170
2713
  return totalGas;
2171
2714
  }
2172
2715
  __name(gasUsedByInputs, "gasUsedByInputs");
2173
2716
  function getMinGas(params) {
2174
2717
  const { gasCosts, gasPerByte, inputs, metadataGas, txBytesSize } = params;
2175
2718
  const vmInitGas = resolveGasDependentCosts(txBytesSize, gasCosts.vmInitialization);
2176
- const bytesGas = bn5(txBytesSize).mul(gasPerByte);
2719
+ const bytesGas = bn6(txBytesSize).mul(gasPerByte);
2177
2720
  const inputsGas = gasUsedByInputs(inputs, txBytesSize, gasCosts);
2178
2721
  const minGas = vmInitGas.add(bytesGas).add(inputsGas).add(metadataGas).maxU64();
2179
2722
  return minGas;
@@ -2185,12 +2728,12 @@ function getMaxGas(params) {
2185
2728
  witnessesLength,
2186
2729
  witnessLimit,
2187
2730
  minGas,
2188
- gasLimit = bn5(0),
2731
+ gasLimit = bn6(0),
2189
2732
  maxGasPerTx
2190
2733
  } = params;
2191
- let remainingAllowedWitnessGas = bn5(0);
2734
+ let remainingAllowedWitnessGas = bn6(0);
2192
2735
  if (witnessLimit?.gt(0) && witnessLimit.gte(witnessesLength)) {
2193
- remainingAllowedWitnessGas = bn5(witnessLimit).sub(witnessesLength).mul(gasPerByte);
2736
+ remainingAllowedWitnessGas = bn6(witnessLimit).sub(witnessesLength).mul(gasPerByte);
2194
2737
  }
2195
2738
  const maxGas = remainingAllowedWitnessGas.add(minGas).add(gasLimit);
2196
2739
  return maxGas.gte(maxGasPerTx) ? maxGasPerTx : maxGas;
@@ -2205,7 +2748,7 @@ function calculateMetadataGasForTxCreate({
2205
2748
  const contractRootGas = resolveGasDependentCosts(contractBytesSize, gasCosts.contractRoot);
2206
2749
  const stateRootGas = resolveGasDependentCosts(stateRootSize, gasCosts.stateRoot);
2207
2750
  const txIdGas = resolveGasDependentCosts(txBytesSize, gasCosts.s256);
2208
- const contractIdInputSize = bn5(4 + 32 + 32 + 32);
2751
+ const contractIdInputSize = bn6(4 + 32 + 32 + 32);
2209
2752
  const contractIdGas = resolveGasDependentCosts(contractIdInputSize, gasCosts.s256);
2210
2753
  const metadataGas = contractRootGas.add(stateRootGas).add(txIdGas).add(contractIdGas);
2211
2754
  return metadataGas.maxU64();
@@ -2260,23 +2803,23 @@ function calculateMinGasForTxUpload({
2260
2803
  baseMinGas,
2261
2804
  subsectionSize
2262
2805
  }) {
2263
- const additionalStoragePerByte = bn5(gasCosts.newStoragePerByte).mul(subsectionSize);
2264
- return bn5(baseMinGas).add(additionalStoragePerByte);
2806
+ const additionalStoragePerByte = bn6(gasCosts.newStoragePerByte).mul(subsectionSize);
2807
+ return bn6(baseMinGas).add(additionalStoragePerByte);
2265
2808
  }
2266
2809
  __name(calculateMinGasForTxUpload, "calculateMinGasForTxUpload");
2267
2810
  var calculateGasFee = /* @__PURE__ */ __name((params) => {
2268
2811
  const { gas, gasPrice, priceFactor, tip } = params;
2269
- return gas.mul(gasPrice).div(priceFactor).add(bn5(tip));
2812
+ return gas.mul(gasPrice).div(priceFactor).add(bn6(tip));
2270
2813
  }, "calculateGasFee");
2271
2814
 
2272
2815
  // src/providers/utils/json.ts
2273
- import { hexlify as hexlify7 } from "@fuel-ts/utils";
2816
+ import { hexlify as hexlify8 } from "@fuel-ts/utils";
2274
2817
  import { clone } from "ramda";
2275
2818
  function normalize(object) {
2276
2819
  Object.keys(object).forEach((key) => {
2277
2820
  switch (object[key]?.constructor.name) {
2278
2821
  case "Uint8Array":
2279
- object[key] = hexlify7(object[key]);
2822
+ object[key] = hexlify8(object[key]);
2280
2823
  break;
2281
2824
  case "Array":
2282
2825
  object[key] = normalize(object[key]);
@@ -2303,8 +2846,8 @@ function normalizeJSON(root) {
2303
2846
  __name(normalizeJSON, "normalizeJSON");
2304
2847
 
2305
2848
  // 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";
2849
+ import { ErrorCode as ErrorCode8, FuelError as FuelError9 } from "@fuel-ts/errors";
2850
+ import { bn as bn7 } from "@fuel-ts/math";
2308
2851
  import { ReceiptType as ReceiptType4 } from "@fuel-ts/transactions";
2309
2852
  import {
2310
2853
  FAILED_REQUIRE_SIGNAL,
@@ -2324,7 +2867,7 @@ You can read more about this error at:
2324
2867
 
2325
2868
  ${PANIC_DOC_URL}#variant.${statusReason}`;
2326
2869
  }
2327
- return new FuelError8(ErrorCode7.SCRIPT_REVERTED, errorMessage, {
2870
+ return new FuelError9(ErrorCode8.SCRIPT_REVERTED, errorMessage, {
2328
2871
  ...metadata,
2329
2872
  reason: statusReason
2330
2873
  });
@@ -2335,7 +2878,7 @@ var assembleRevertError = /* @__PURE__ */ __name((receipts, logs, metadata) => {
2335
2878
  const revertReceipt = receipts.find(({ type }) => type === ReceiptType4.Revert);
2336
2879
  let reason = "";
2337
2880
  if (revertReceipt) {
2338
- const reasonHex = bn6(revertReceipt.val).toHex();
2881
+ const reasonHex = bn7(revertReceipt.val).toHex();
2339
2882
  const lastLog = logs[logs.length - 1];
2340
2883
  const lastButOneLog = logs[logs.length - 2];
2341
2884
  switch (reasonHex) {
@@ -2365,8 +2908,8 @@ var assembleRevertError = /* @__PURE__ */ __name((receipts, logs, metadata) => {
2365
2908
  errorMessage = `The transaction reverted because it's missing an "OutputVariable".`;
2366
2909
  break;
2367
2910
  default:
2368
- throw new FuelError8(
2369
- ErrorCode7.UNKNOWN,
2911
+ throw new FuelError9(
2912
+ ErrorCode8.UNKNOWN,
2370
2913
  `The transaction reverted with an unknown reason: ${revertReceipt.val}`,
2371
2914
  {
2372
2915
  ...metadata,
@@ -2375,7 +2918,7 @@ var assembleRevertError = /* @__PURE__ */ __name((receipts, logs, metadata) => {
2375
2918
  );
2376
2919
  }
2377
2920
  }
2378
- return new FuelError8(ErrorCode7.SCRIPT_REVERTED, errorMessage, {
2921
+ return new FuelError9(ErrorCode8.SCRIPT_REVERTED, errorMessage, {
2379
2922
  ...metadata,
2380
2923
  reason
2381
2924
  });
@@ -2398,6 +2941,21 @@ var extractTxError = /* @__PURE__ */ __name((params) => {
2398
2941
  return assembleRevertError(receipts, logs, metadata);
2399
2942
  }, "extractTxError");
2400
2943
 
2944
+ // src/providers/utils/merge-quantities.ts
2945
+ var mergeQuantities = /* @__PURE__ */ __name((...coinQuantities) => {
2946
+ const resultMap = {};
2947
+ function addToMap({ amount, assetId }) {
2948
+ if (resultMap[assetId]) {
2949
+ resultMap[assetId] = resultMap[assetId].add(amount);
2950
+ } else {
2951
+ resultMap[assetId] = amount;
2952
+ }
2953
+ }
2954
+ __name(addToMap, "addToMap");
2955
+ coinQuantities.forEach((arr) => arr.forEach(addToMap));
2956
+ return Object.entries(resultMap).map(([assetId, amount]) => ({ assetId, amount }));
2957
+ }, "mergeQuantities");
2958
+
2401
2959
  // src/providers/transaction-request/errors.ts
2402
2960
  var NoWitnessAtIndexError = class extends Error {
2403
2961
  constructor(index) {
@@ -2412,18 +2970,18 @@ var NoWitnessAtIndexError = class extends Error {
2412
2970
  };
2413
2971
 
2414
2972
  // 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");
2973
+ import { ErrorCode as ErrorCode9, FuelError as FuelError10 } from "@fuel-ts/errors";
2974
+ import { bn as bn8 } from "@fuel-ts/math";
2975
+ import { InputType as InputType3, OutputType as OutputType3 } from "@fuel-ts/transactions";
2976
+ import { hexlify as hexlify9 } from "@fuel-ts/utils";
2977
+ var isRequestInputCoin = /* @__PURE__ */ __name((input) => input.type === InputType3.Coin, "isRequestInputCoin");
2978
+ var isRequestInputMessage = /* @__PURE__ */ __name((input) => input.type === InputType3.Message, "isRequestInputMessage");
2979
+ var isRequestInputMessageWithoutData = /* @__PURE__ */ __name((input) => input.type === InputType3.Message && bn8(input.data).isZero(), "isRequestInputMessageWithoutData");
2422
2980
  var isRequestInputCoinOrMessage = /* @__PURE__ */ __name((input) => isRequestInputCoin(input) || isRequestInputMessage(input), "isRequestInputCoinOrMessage");
2423
2981
  var isRequestInputResource = /* @__PURE__ */ __name((input) => isRequestInputCoin(input) || isRequestInputMessageWithoutData(input), "isRequestInputResource");
2424
2982
  var getRequestInputResourceOwner = /* @__PURE__ */ __name((input) => isRequestInputCoin(input) ? input.owner : input.recipient, "getRequestInputResourceOwner");
2425
2983
  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");
2984
+ var isPredicate = /* @__PURE__ */ __name((input) => isRequestInputCoinOrMessage(input) && !!input.predicate && hexlify9(input.predicate) !== "0x", "isPredicate");
2427
2985
  var getAssetAmountInRequestInputs = /* @__PURE__ */ __name((inputs, assetId, baseAsset) => inputs.filter(isRequestInputResource).reduce((acc, input) => {
2428
2986
  if (isRequestInputCoin(input) && input.assetId === assetId) {
2429
2987
  return acc.add(input.amount);
@@ -2432,7 +2990,7 @@ var getAssetAmountInRequestInputs = /* @__PURE__ */ __name((inputs, assetId, bas
2432
2990
  return acc.add(input.amount);
2433
2991
  }
2434
2992
  return acc;
2435
- }, bn7(0)), "getAssetAmountInRequestInputs");
2993
+ }, bn8(0)), "getAssetAmountInRequestInputs");
2436
2994
  var cacheRequestInputsResourcesFromOwner = /* @__PURE__ */ __name((inputs, owner) => inputs.reduce(
2437
2995
  (acc, input) => {
2438
2996
  if (isRequestInputCoin(input) && input.owner === owner.toB256()) {
@@ -2450,11 +3008,11 @@ var cacheRequestInputsResourcesFromOwner = /* @__PURE__ */ __name((inputs, owner
2450
3008
  var getBurnableAssetCount = /* @__PURE__ */ __name((baseAssetId, transactionRequest) => {
2451
3009
  const { inputs, outputs } = transactionRequest;
2452
3010
  const coinInputs = new Set(inputs.filter(isRequestInputCoin).map((input) => input.assetId));
2453
- if (inputs.some((i) => isRequestInputMessage(i) && bn7(i.amount).gt(0))) {
3011
+ if (inputs.some((i) => isRequestInputMessage(i) && bn8(i.amount).gt(0))) {
2454
3012
  coinInputs.add(baseAssetId);
2455
3013
  }
2456
3014
  const changeOutputs = new Set(
2457
- outputs.filter((output) => output.type === OutputType2.Change).map((output) => output.assetId)
3015
+ outputs.filter((output) => output.type === OutputType3.Change).map((output) => output.assetId)
2458
3016
  );
2459
3017
  const difference = new Set([...coinInputs].filter((x) => !changeOutputs.has(x)));
2460
3018
  return difference.size;
@@ -2471,15 +3029,15 @@ var validateTransactionForAssetBurn = /* @__PURE__ */ __name((baseAssetId, trans
2471
3029
  "Add the relevant change outputs to the transaction to avoid burning assets.",
2472
3030
  "Or enable asset burn, upon sending the transaction."
2473
3031
  ].join("\n");
2474
- throw new FuelError9(ErrorCode8.ASSET_BURN_DETECTED, message);
3032
+ throw new FuelError10(ErrorCode9.ASSET_BURN_DETECTED, message);
2475
3033
  }, "validateTransactionForAssetBurn");
2476
3034
 
2477
3035
  // src/providers/transaction-request/witness.ts
2478
- import { arrayify as arrayify5, hexlify as hexlify9 } from "@fuel-ts/utils";
3036
+ import { arrayify as arrayify5, hexlify as hexlify10 } from "@fuel-ts/utils";
2479
3037
  var witnessify = /* @__PURE__ */ __name((value) => {
2480
3038
  const data = arrayify5(value);
2481
3039
  return {
2482
- data: hexlify9(data),
3040
+ data: hexlify10(data),
2483
3041
  dataLength: data.length
2484
3042
  };
2485
3043
  }, "witnessify");
@@ -2506,8 +3064,6 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2506
3064
  /** List of witnesses */
2507
3065
  witnesses = [];
2508
3066
  /**
2509
- * @hidden
2510
- *
2511
3067
  * The current status of the transaction
2512
3068
  */
2513
3069
  flag = { state: void 0, transactionId: void 0, summary: void 0 };
@@ -2524,28 +3080,30 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2524
3080
  witnessLimit,
2525
3081
  inputs,
2526
3082
  outputs,
2527
- witnesses
3083
+ witnesses,
3084
+ flag
2528
3085
  } = {}) {
2529
- this.tip = tip ? bn8(tip) : void 0;
3086
+ this.tip = tip ? bn9(tip) : void 0;
2530
3087
  this.maturity = maturity && maturity > 0 ? maturity : void 0;
2531
3088
  this.expiration = expiration && expiration > 0 ? expiration : void 0;
2532
- this.witnessLimit = isDefined(witnessLimit) ? bn8(witnessLimit) : void 0;
2533
- this.maxFee = bn8(maxFee);
3089
+ this.witnessLimit = isDefined2(witnessLimit) ? bn9(witnessLimit) : void 0;
3090
+ this.maxFee = bn9(maxFee);
2534
3091
  this.inputs = inputs ?? [];
2535
3092
  this.outputs = outputs ?? [];
2536
3093
  this.witnesses = witnesses ?? [];
3094
+ this.flag = flag ?? { state: void 0, transactionId: void 0, summary: void 0 };
2537
3095
  }
2538
3096
  static getPolicyMeta(req) {
2539
3097
  let policyTypes = 0;
2540
3098
  const policies = [];
2541
3099
  const { tip, witnessLimit, maturity, expiration } = req;
2542
- if (bn8(tip).gt(0)) {
3100
+ if (bn9(tip).gt(0)) {
2543
3101
  policyTypes += PolicyType.Tip;
2544
- policies.push({ data: bn8(tip), type: PolicyType.Tip });
3102
+ policies.push({ data: bn9(tip), type: PolicyType.Tip });
2545
3103
  }
2546
- if (isDefined(witnessLimit) && bn8(witnessLimit).gte(0)) {
3104
+ if (isDefined2(witnessLimit) && bn9(witnessLimit).gte(0)) {
2547
3105
  policyTypes += PolicyType.WitnessLimit;
2548
- policies.push({ data: bn8(witnessLimit), type: PolicyType.WitnessLimit });
3106
+ policies.push({ data: bn9(witnessLimit), type: PolicyType.WitnessLimit });
2549
3107
  }
2550
3108
  if (maturity && maturity > 0) {
2551
3109
  policyTypes += PolicyType.Maturity;
@@ -2679,7 +3237,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2679
3237
  */
2680
3238
  getCoinInputs() {
2681
3239
  return this.inputs.filter(
2682
- (input) => input.type === InputType3.Coin
3240
+ (input) => input.type === InputType4.Coin
2683
3241
  );
2684
3242
  }
2685
3243
  /**
@@ -2689,7 +3247,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2689
3247
  */
2690
3248
  getCoinOutputs() {
2691
3249
  return this.outputs.filter(
2692
- (output) => output.type === OutputType3.Coin
3250
+ (output) => output.type === OutputType4.Coin
2693
3251
  );
2694
3252
  }
2695
3253
  /**
@@ -2699,7 +3257,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2699
3257
  */
2700
3258
  getChangeOutputs() {
2701
3259
  return this.outputs.filter(
2702
- (output) => output.type === OutputType3.Change
3260
+ (output) => output.type === OutputType4.Change
2703
3261
  );
2704
3262
  }
2705
3263
  /**
@@ -2711,10 +3269,10 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2711
3269
  const ownerAddress = addressify(owner);
2712
3270
  const found = this.inputs.find((input) => {
2713
3271
  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();
3272
+ case InputType4.Coin:
3273
+ return hexlify11(input.owner) === ownerAddress.toB256();
3274
+ case InputType4.Message:
3275
+ return hexlify11(input.recipient) === ownerAddress.toB256();
2718
3276
  default:
2719
3277
  return false;
2720
3278
  }
@@ -2740,7 +3298,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2740
3298
  }
2741
3299
  const input = {
2742
3300
  id,
2743
- type: InputType3.Coin,
3301
+ type: InputType4.Coin,
2744
3302
  owner: owner.toB256(),
2745
3303
  amount,
2746
3304
  assetId,
@@ -2771,7 +3329,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2771
3329
  }
2772
3330
  const input = {
2773
3331
  nonce,
2774
- type: InputType3.Message,
3332
+ type: InputType4.Message,
2775
3333
  sender: sender.toB256(),
2776
3334
  recipient: recipient.toB256(),
2777
3335
  data: isMessageCoin(message) ? "0x" : message.data,
@@ -2820,7 +3378,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2820
3378
  */
2821
3379
  addCoinOutput(to, amount, assetId) {
2822
3380
  this.pushOutput({
2823
- type: OutputType3.Coin,
3381
+ type: OutputType4.Coin,
2824
3382
  to: addressify(to).toB256(),
2825
3383
  amount,
2826
3384
  assetId
@@ -2836,7 +3394,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2836
3394
  addCoinOutputs(to, quantities) {
2837
3395
  quantities.map(coinQuantityfy).forEach((quantity) => {
2838
3396
  this.pushOutput({
2839
- type: OutputType3.Coin,
3397
+ type: OutputType4.Coin,
2840
3398
  to: addressify(to).toB256(),
2841
3399
  amount: quantity.amount,
2842
3400
  assetId: quantity.assetId
@@ -2852,11 +3410,11 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2852
3410
  */
2853
3411
  addChangeOutput(to, assetId) {
2854
3412
  const changeOutput = this.getChangeOutputs().find(
2855
- (output) => hexlify10(output.assetId) === assetId
3413
+ (output) => hexlify11(output.assetId) === assetId
2856
3414
  );
2857
3415
  if (!changeOutput) {
2858
3416
  this.pushOutput({
2859
- type: OutputType3.Change,
3417
+ type: OutputType4.Change,
2860
3418
  to: addressify(to).toB256(),
2861
3419
  assetId
2862
3420
  });
@@ -2872,7 +3430,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2872
3430
  * @hidden
2873
3431
  */
2874
3432
  metadataGas(_gasCosts) {
2875
- throw new FuelError10(FuelError10.CODES.NOT_IMPLEMENTED, "Not implemented");
3433
+ throw new FuelError11(FuelError11.CODES.NOT_IMPLEMENTED, "Not implemented");
2876
3434
  }
2877
3435
  /**
2878
3436
  * @hidden
@@ -2929,25 +3487,25 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2929
3487
  const assetInput = findAssetInput(assetId);
2930
3488
  let usedQuantity = quantity;
2931
3489
  if (assetId === baseAssetId) {
2932
- usedQuantity = bn8("1000000000000000000");
3490
+ usedQuantity = bn9("1000000000000000000");
2933
3491
  }
2934
3492
  if (assetInput && "assetId" in assetInput) {
2935
- assetInput.id = hexlify10(randomBytes3(UTXO_ID_LEN2));
3493
+ assetInput.id = hexlify11(randomBytes3(UTXO_ID_LEN2));
2936
3494
  assetInput.amount = usedQuantity;
2937
3495
  } else {
2938
3496
  this.addResources([
2939
3497
  {
2940
- id: hexlify10(randomBytes3(UTXO_ID_LEN2)),
3498
+ id: hexlify11(randomBytes3(UTXO_ID_LEN2)),
2941
3499
  amount: usedQuantity,
2942
3500
  assetId,
2943
3501
  owner: resourcesOwner || Address2.fromRandom(),
2944
- blockCreated: bn8(1),
2945
- txCreatedIdx: bn8(1)
3502
+ blockCreated: bn9(1),
3503
+ txCreatedIdx: bn9(1)
2946
3504
  }
2947
3505
  ]);
2948
3506
  }
2949
3507
  }, "updateAssetInput");
2950
- updateAssetInput(baseAssetId, bn8(1e11));
3508
+ updateAssetInput(baseAssetId, bn9(1e11));
2951
3509
  quantities.forEach((q) => updateAssetInput(q.assetId, q.amount));
2952
3510
  return this;
2953
3511
  }
@@ -2959,7 +3517,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2959
3517
  */
2960
3518
  getCoinOutputsQuantities() {
2961
3519
  const coinsQuantities = this.getCoinOutputs().map(({ amount, assetId }) => ({
2962
- amount: bn8(amount),
3520
+ amount: bn9(amount),
2963
3521
  assetId: assetId.toString()
2964
3522
  }));
2965
3523
  return coinsQuantities;
@@ -2991,7 +3549,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2991
3549
  const correspondingInput = inputsToExtractGasUsed.find(
2992
3550
  (x) => isRequestInputResourceFromOwner(x, new Address2(String(owner)))
2993
3551
  );
2994
- if (correspondingInput && "predicateGasUsed" in correspondingInput && bn8(correspondingInput.predicateGasUsed).gt(0)) {
3552
+ if (correspondingInput && "predicateGasUsed" in correspondingInput && bn9(correspondingInput.predicateGasUsed).gt(0)) {
2995
3553
  i.predicateGasUsed = correspondingInput.predicateGasUsed;
2996
3554
  }
2997
3555
  });
@@ -3022,34 +3580,34 @@ import { clone as clone3 } from "ramda";
3022
3580
  // src/providers/transaction-request/hash-transaction.ts
3023
3581
  import { ZeroBytes32 as ZeroBytes325 } from "@fuel-ts/address/configs";
3024
3582
  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";
3583
+ import { bn as bn10 } from "@fuel-ts/math";
3584
+ import { TransactionType as TransactionType3, InputType as InputType5, OutputType as OutputType5, TransactionCoder as TransactionCoder2 } from "@fuel-ts/transactions";
3027
3585
  import { concat as concat3 } from "@fuel-ts/utils";
3028
3586
  import { clone as clone2 } from "ramda";
3029
3587
  function hashTransaction(transactionRequest, chainId) {
3030
3588
  const transaction = transactionRequest.toTransaction();
3031
- if (transaction.type === TransactionType2.Script) {
3589
+ if (transaction.type === TransactionType3.Script) {
3032
3590
  transaction.receiptsRoot = ZeroBytes325;
3033
3591
  }
3034
3592
  transaction.inputs = transaction.inputs.map((input) => {
3035
3593
  const inputClone = clone2(input);
3036
3594
  switch (inputClone.type) {
3037
3595
  // Zero out on signing: txPointer, predicateGasUsed
3038
- case InputType4.Coin: {
3596
+ case InputType5.Coin: {
3039
3597
  inputClone.txPointer = {
3040
3598
  blockHeight: 0,
3041
3599
  txIndex: 0
3042
3600
  };
3043
- inputClone.predicateGasUsed = bn9(0);
3601
+ inputClone.predicateGasUsed = bn10(0);
3044
3602
  return inputClone;
3045
3603
  }
3046
3604
  // Zero out on signing: predicateGasUsed
3047
- case InputType4.Message: {
3048
- inputClone.predicateGasUsed = bn9(0);
3605
+ case InputType5.Message: {
3606
+ inputClone.predicateGasUsed = bn10(0);
3049
3607
  return inputClone;
3050
3608
  }
3051
3609
  // Zero out on signing: txID, outputIndex, balanceRoot, stateRoot, and txPointer
3052
- case InputType4.Contract: {
3610
+ case InputType5.Contract: {
3053
3611
  inputClone.txPointer = {
3054
3612
  blockHeight: 0,
3055
3613
  txIndex: 0
@@ -3068,20 +3626,20 @@ function hashTransaction(transactionRequest, chainId) {
3068
3626
  const outputClone = clone2(output);
3069
3627
  switch (outputClone.type) {
3070
3628
  // Zero out on signing: balanceRoot, stateRoot
3071
- case OutputType4.Contract: {
3629
+ case OutputType5.Contract: {
3072
3630
  outputClone.balanceRoot = ZeroBytes325;
3073
3631
  outputClone.stateRoot = ZeroBytes325;
3074
3632
  return outputClone;
3075
3633
  }
3076
3634
  // Zero out on signing: amount
3077
- case OutputType4.Change: {
3078
- outputClone.amount = bn9(0);
3635
+ case OutputType5.Change: {
3636
+ outputClone.amount = bn10(0);
3079
3637
  return outputClone;
3080
3638
  }
3081
3639
  // Zero out on signing: amount, to and assetId
3082
- case OutputType4.Variable: {
3640
+ case OutputType5.Variable: {
3083
3641
  outputClone.to = ZeroBytes325;
3084
- outputClone.amount = bn9(0);
3642
+ outputClone.amount = bn10(0);
3085
3643
  outputClone.assetId = ZeroBytes325;
3086
3644
  return outputClone;
3087
3645
  }
@@ -3106,7 +3664,7 @@ var BlobTransactionRequest = class extends BaseTransactionRequest {
3106
3664
  return new this(clone3(obj));
3107
3665
  }
3108
3666
  /** Type of the transaction */
3109
- type = TransactionType.Blob;
3667
+ type = TransactionType2.Blob;
3110
3668
  /** Blob ID */
3111
3669
  blobId;
3112
3670
  /** Witness index of the bytecode to create */
@@ -3130,7 +3688,7 @@ var BlobTransactionRequest = class extends BaseTransactionRequest {
3130
3688
  const baseTransaction = this.getBaseTransaction();
3131
3689
  const { witnessIndex, blobId } = this;
3132
3690
  return {
3133
- type: TransactionType.Blob,
3691
+ type: TransactionType2.Blob,
3134
3692
  ...baseTransaction,
3135
3693
  blobId,
3136
3694
  witnessIndex
@@ -3163,13 +3721,13 @@ var BlobTransactionRequest = class extends BaseTransactionRequest {
3163
3721
 
3164
3722
  // src/providers/transaction-request/create-transaction-request.ts
3165
3723
  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";
3724
+ import { bn as bn11 } from "@fuel-ts/math";
3725
+ import { TransactionType as TransactionType4, OutputType as OutputType6 } from "@fuel-ts/transactions";
3726
+ import { arrayify as arrayify7, hexlify as hexlify13 } from "@fuel-ts/utils";
3169
3727
  import { clone as clone4 } from "ramda";
3170
3728
 
3171
3729
  // src/providers/transaction-request/storage-slot.ts
3172
- import { arrayify as arrayify6, hexlify as hexlify11 } from "@fuel-ts/utils";
3730
+ import { arrayify as arrayify6, hexlify as hexlify12 } from "@fuel-ts/utils";
3173
3731
  var getStorageValue = /* @__PURE__ */ __name((value) => {
3174
3732
  const v = new Uint8Array(32);
3175
3733
  v.set(arrayify6(value));
@@ -3186,8 +3744,8 @@ var storageSlotify = /* @__PURE__ */ __name((storageSlot) => {
3186
3744
  value = storageSlot.value;
3187
3745
  }
3188
3746
  return {
3189
- key: hexlify11(key),
3190
- value: hexlify11(getStorageValue(value))
3747
+ key: hexlify12(key),
3748
+ value: hexlify12(getStorageValue(value))
3191
3749
  };
3192
3750
  }, "storageSlotify");
3193
3751
 
@@ -3200,7 +3758,7 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3200
3758
  return new this(clone4(obj));
3201
3759
  }
3202
3760
  /** Type of the transaction */
3203
- type = TransactionType3.Create;
3761
+ type = TransactionType4.Create;
3204
3762
  /** Witness index of contract bytecode to create */
3205
3763
  bytecodeWitnessIndex;
3206
3764
  /** Salt */
@@ -3215,7 +3773,7 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3215
3773
  constructor({ bytecodeWitnessIndex, salt, storageSlots, ...rest }) {
3216
3774
  super(rest);
3217
3775
  this.bytecodeWitnessIndex = bytecodeWitnessIndex ?? 0;
3218
- this.salt = hexlify12(salt ?? ZeroBytes326);
3776
+ this.salt = hexlify13(salt ?? ZeroBytes326);
3219
3777
  this.storageSlots = [...storageSlots ?? []];
3220
3778
  }
3221
3779
  /**
@@ -3228,11 +3786,11 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3228
3786
  const bytecodeWitnessIndex = this.bytecodeWitnessIndex;
3229
3787
  const storageSlots = this.storageSlots?.map(storageSlotify) ?? [];
3230
3788
  return {
3231
- type: TransactionType3.Create,
3789
+ type: TransactionType4.Create,
3232
3790
  ...baseTransaction,
3233
3791
  bytecodeWitnessIndex,
3234
- storageSlotsCount: bn10(storageSlots.length),
3235
- salt: this.salt ? hexlify12(this.salt) : ZeroBytes326,
3792
+ storageSlotsCount: bn11(storageSlots.length),
3793
+ salt: this.salt ? hexlify13(this.salt) : ZeroBytes326,
3236
3794
  storageSlots
3237
3795
  };
3238
3796
  }
@@ -3243,7 +3801,7 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3243
3801
  */
3244
3802
  getContractCreatedOutputs() {
3245
3803
  return this.outputs.filter(
3246
- (output) => output.type === OutputType5.ContractCreated
3804
+ (output) => output.type === OutputType6.ContractCreated
3247
3805
  );
3248
3806
  }
3249
3807
  /**
@@ -3264,14 +3822,14 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3264
3822
  */
3265
3823
  addContractCreatedOutput(contractId, stateRoot) {
3266
3824
  this.pushOutput({
3267
- type: OutputType5.ContractCreated,
3825
+ type: OutputType6.ContractCreated,
3268
3826
  contractId,
3269
3827
  stateRoot
3270
3828
  });
3271
3829
  }
3272
3830
  metadataGas(gasCosts) {
3273
3831
  return calculateMetadataGasForTxCreate({
3274
- contractBytesSize: bn10(arrayify7(this.witnesses[this.bytecodeWitnessIndex] || "0x").length),
3832
+ contractBytesSize: bn11(arrayify7(this.witnesses[this.bytecodeWitnessIndex] || "0x").length),
3275
3833
  gasCosts,
3276
3834
  stateRootSize: this.storageSlots.length,
3277
3835
  txBytesSize: this.byteSize()
@@ -3283,9 +3841,9 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3283
3841
  import { Interface } from "@fuel-ts/abi-coder";
3284
3842
  import { addressify as addressify2 } from "@fuel-ts/address";
3285
3843
  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";
3844
+ import { bn as bn12 } from "@fuel-ts/math";
3845
+ import { InputType as InputType6, OutputType as OutputType7, TransactionType as TransactionType5 } from "@fuel-ts/transactions";
3846
+ import { arrayify as arrayify9, hexlify as hexlify14 } from "@fuel-ts/utils";
3289
3847
  import { clone as clone5 } from "ramda";
3290
3848
 
3291
3849
  // src/providers/transaction-request/scripts.ts
@@ -3323,7 +3881,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3323
3881
  return new this(clone5(obj));
3324
3882
  }
3325
3883
  /** Type of the transaction */
3326
- type = TransactionType4.Script;
3884
+ type = TransactionType5.Script;
3327
3885
  /** Gas limit for transaction */
3328
3886
  gasLimit;
3329
3887
  /** Script to execute */
@@ -3338,7 +3896,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3338
3896
  */
3339
3897
  constructor({ script, scriptData, gasLimit, ...rest } = {}) {
3340
3898
  super(rest);
3341
- this.gasLimit = bn11(gasLimit);
3899
+ this.gasLimit = bn12(gasLimit);
3342
3900
  this.script = arrayify9(script ?? returnZeroScript.bytes);
3343
3901
  this.scriptData = arrayify9(scriptData ?? returnZeroScript.encodeScriptData());
3344
3902
  this.abis = rest.abis;
@@ -3349,6 +3907,9 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3349
3907
  * @param account - The account to fund the transaction.
3350
3908
  * @param params - The parameters for the transaction cost.
3351
3909
  * @returns The current instance of the `ScriptTransactionRequest` funded.
3910
+ *
3911
+ * @deprecated Use `provider.assembleTx` instead.
3912
+ * Check the migration guide https://docs.fuel.network/guide/assembling-transactions/migration-guide.html for more information.
3352
3913
  */
3353
3914
  async estimateAndFund(account, { signatureCallback, quantities = [] } = {}) {
3354
3915
  const txCost = await account.getTransactionCost(this, { signatureCallback, quantities });
@@ -3366,14 +3927,14 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3366
3927
  const script = arrayify9(this.script ?? "0x");
3367
3928
  const scriptData = arrayify9(this.scriptData ?? "0x");
3368
3929
  return {
3369
- type: TransactionType4.Script,
3930
+ type: TransactionType5.Script,
3370
3931
  scriptGasLimit: this.gasLimit,
3371
3932
  ...super.getBaseTransaction(),
3372
- scriptLength: bn11(script.length),
3373
- scriptDataLength: bn11(scriptData.length),
3933
+ scriptLength: bn12(script.length),
3934
+ scriptDataLength: bn12(scriptData.length),
3374
3935
  receiptsRoot: ZeroBytes327,
3375
- script: hexlify13(script),
3376
- scriptData: hexlify13(scriptData)
3936
+ script: hexlify14(script),
3937
+ scriptData: hexlify14(scriptData)
3377
3938
  };
3378
3939
  }
3379
3940
  /**
@@ -3383,7 +3944,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3383
3944
  */
3384
3945
  getContractInputs() {
3385
3946
  return this.inputs.filter(
3386
- (input) => input.type === InputType5.Contract
3947
+ (input) => input.type === InputType6.Contract
3387
3948
  );
3388
3949
  }
3389
3950
  /**
@@ -3393,7 +3954,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3393
3954
  */
3394
3955
  getContractOutputs() {
3395
3956
  return this.outputs.filter(
3396
- (output) => output.type === OutputType6.Contract
3957
+ (output) => output.type === OutputType7.Contract
3397
3958
  );
3398
3959
  }
3399
3960
  /**
@@ -3403,7 +3964,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3403
3964
  */
3404
3965
  getVariableOutputs() {
3405
3966
  return this.outputs.filter(
3406
- (output) => output.type === OutputType6.Variable
3967
+ (output) => output.type === OutputType7.Variable
3407
3968
  );
3408
3969
  }
3409
3970
  /**
@@ -3426,12 +3987,27 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3426
3987
  let outputsNumber = numberOfVariables;
3427
3988
  while (outputsNumber) {
3428
3989
  this.pushOutput({
3429
- type: OutputType6.Variable
3990
+ type: OutputType7.Variable
3430
3991
  });
3431
3992
  outputsNumber -= 1;
3432
3993
  }
3433
3994
  return this.outputs.length - 1;
3434
3995
  }
3996
+ /**
3997
+ * Adds a variable output to the transaction request.
3998
+ *
3999
+ * @param to - The recipient address as a BytesLike object. Defaults to ZeroBytes32 if not provided.
4000
+ * @param amount - The amount to be transferred as a BigNumberish object. Defaults to 0 if not provided.
4001
+ * @param assetId - The asset ID as a BytesLike object. Defaults to ZeroBytes32 if not provided.
4002
+ */
4003
+ addVariableOutput(to, amount, assetId) {
4004
+ this.pushOutput({
4005
+ type: OutputType7.Variable,
4006
+ to,
4007
+ amount,
4008
+ assetId
4009
+ });
4010
+ }
3435
4011
  /**
3436
4012
  * Calculates the maximum gas for the transaction.
3437
4013
  *
@@ -3470,12 +4046,12 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3470
4046
  return this;
3471
4047
  }
3472
4048
  const inputIndex = super.pushInput({
3473
- type: InputType5.Contract,
4049
+ type: InputType6.Contract,
3474
4050
  contractId: contractAddress.toB256(),
3475
4051
  txPointer: "0x00000000000000000000000000000000"
3476
4052
  });
3477
4053
  this.pushOutput({
3478
- type: OutputType6.Contract,
4054
+ type: OutputType7.Contract,
3479
4055
  inputIndex
3480
4056
  });
3481
4057
  return this;
@@ -3511,13 +4087,13 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3511
4087
  };
3512
4088
 
3513
4089
  // src/providers/transaction-request/upgrade-transaction-request.ts
3514
- import { FuelError as FuelError11 } from "@fuel-ts/errors";
4090
+ import { FuelError as FuelError12 } from "@fuel-ts/errors";
3515
4091
  import { hash as hash2 } from "@fuel-ts/hasher";
3516
4092
  import {
3517
- TransactionType as TransactionType5,
4093
+ TransactionType as TransactionType6,
3518
4094
  UpgradePurposeTypeEnum
3519
4095
  } from "@fuel-ts/transactions";
3520
- import { hexlify as hexlify14 } from "@fuel-ts/utils";
4096
+ import { hexlify as hexlify15 } from "@fuel-ts/utils";
3521
4097
  import { clone as clone6 } from "ramda";
3522
4098
  var UpgradeTransactionRequest = class _UpgradeTransactionRequest extends BaseTransactionRequest {
3523
4099
  static {
@@ -3530,7 +4106,7 @@ var UpgradeTransactionRequest = class _UpgradeTransactionRequest extends BaseTra
3530
4106
  return new this(clone6(obj));
3531
4107
  }
3532
4108
  /** The type of transaction */
3533
- type = TransactionType5.Upgrade;
4109
+ type = TransactionType6.Upgrade;
3534
4110
  /** The upgrade purpose */
3535
4111
  upgradePurpose;
3536
4112
  /** Witness index of consensus */
@@ -3577,7 +4153,7 @@ var UpgradeTransactionRequest = class _UpgradeTransactionRequest extends BaseTra
3577
4153
  addStateTransitionUpgradePurpose(bytecodeRoot) {
3578
4154
  this.upgradePurpose = {
3579
4155
  type: UpgradePurposeTypeEnum.StateTransition,
3580
- data: hexlify14(bytecodeRoot)
4156
+ data: hexlify15(bytecodeRoot)
3581
4157
  };
3582
4158
  return this;
3583
4159
  }
@@ -3617,14 +4193,14 @@ var UpgradeTransactionRequest = class _UpgradeTransactionRequest extends BaseTra
3617
4193
  upgradePurpose = {
3618
4194
  type: UpgradePurposeTypeEnum.StateTransition,
3619
4195
  data: {
3620
- bytecodeRoot: hexlify14(this.upgradePurpose.data)
4196
+ bytecodeRoot: hexlify15(this.upgradePurpose.data)
3621
4197
  }
3622
4198
  };
3623
4199
  } else {
3624
- throw new FuelError11(FuelError11.CODES.NOT_IMPLEMENTED, "Invalid upgrade purpose");
4200
+ throw new FuelError12(FuelError12.CODES.NOT_IMPLEMENTED, "Invalid upgrade purpose");
3625
4201
  }
3626
4202
  return {
3627
- type: TransactionType5.Upgrade,
4203
+ type: TransactionType6.Upgrade,
3628
4204
  ...super.getBaseTransaction(),
3629
4205
  upgradePurpose
3630
4206
  };
@@ -3663,14 +4239,14 @@ var UpgradeTransactionRequest = class _UpgradeTransactionRequest extends BaseTra
3663
4239
  txBytesSize
3664
4240
  });
3665
4241
  }
3666
- throw new FuelError11(FuelError11.CODES.NOT_IMPLEMENTED, "Invalid upgrade purpose");
4242
+ throw new FuelError12(FuelError12.CODES.NOT_IMPLEMENTED, "Invalid upgrade purpose");
3667
4243
  }
3668
4244
  };
3669
4245
 
3670
4246
  // src/providers/transaction-request/upload-transaction-request.ts
3671
4247
  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";
4248
+ import { TransactionType as TransactionType7 } from "@fuel-ts/transactions";
4249
+ import { arrayify as arrayify10, hexlify as hexlify16 } from "@fuel-ts/utils";
3674
4250
  import { clone as clone7 } from "ramda";
3675
4251
  var UploadTransactionRequest = class _UploadTransactionRequest extends BaseTransactionRequest {
3676
4252
  static {
@@ -3683,7 +4259,7 @@ var UploadTransactionRequest = class _UploadTransactionRequest extends BaseTrans
3683
4259
  return new this(clone7(obj));
3684
4260
  }
3685
4261
  /** Type of the transaction */
3686
- type = TransactionType6.Upload;
4262
+ type = TransactionType7.Upload;
3687
4263
  /** The witness index of the subsection of the bytecode. */
3688
4264
  witnessIndex;
3689
4265
  /** The subsection data. */
@@ -3732,12 +4308,12 @@ var UploadTransactionRequest = class _UploadTransactionRequest extends BaseTrans
3732
4308
  const baseTransaction = this.getBaseTransaction();
3733
4309
  const { subsectionIndex, subsectionsNumber, root, proofSet } = this.subsection;
3734
4310
  return {
3735
- type: TransactionType6.Upload,
4311
+ type: TransactionType7.Upload,
3736
4312
  ...baseTransaction,
3737
4313
  subsectionIndex,
3738
4314
  subsectionsNumber,
3739
- root: hexlify15(root),
3740
- proofSet: proofSet.map(hexlify15),
4315
+ root: hexlify16(root),
4316
+ proofSet: proofSet.map(hexlify16),
3741
4317
  witnessIndex: this.witnessIndex,
3742
4318
  proofSetCount: proofSet.length
3743
4319
  };
@@ -3777,39 +4353,39 @@ var UploadTransactionRequest = class _UploadTransactionRequest extends BaseTrans
3777
4353
  };
3778
4354
 
3779
4355
  // 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";
4356
+ import { ErrorCode as ErrorCode10, FuelError as FuelError13 } from "@fuel-ts/errors";
4357
+ import { TransactionType as TransactionType8 } from "@fuel-ts/transactions";
3782
4358
  var transactionRequestify = /* @__PURE__ */ __name((obj) => {
3783
4359
  if (obj instanceof ScriptTransactionRequest || obj instanceof CreateTransactionRequest || obj instanceof BlobTransactionRequest || obj instanceof UpgradeTransactionRequest || obj instanceof UploadTransactionRequest) {
3784
4360
  return obj;
3785
4361
  }
3786
4362
  const { type } = obj;
3787
4363
  switch (obj.type) {
3788
- case TransactionType7.Script: {
4364
+ case TransactionType8.Script: {
3789
4365
  return ScriptTransactionRequest.from(obj);
3790
4366
  }
3791
- case TransactionType7.Create: {
4367
+ case TransactionType8.Create: {
3792
4368
  return CreateTransactionRequest.from(obj);
3793
4369
  }
3794
- case TransactionType7.Blob: {
4370
+ case TransactionType8.Blob: {
3795
4371
  return BlobTransactionRequest.from(obj);
3796
4372
  }
3797
- case TransactionType7.Upgrade: {
4373
+ case TransactionType8.Upgrade: {
3798
4374
  return UpgradeTransactionRequest.from(obj);
3799
4375
  }
3800
- case TransactionType7.Upload: {
4376
+ case TransactionType8.Upload: {
3801
4377
  return UploadTransactionRequest.from(obj);
3802
4378
  }
3803
4379
  default: {
3804
- throw new FuelError12(
3805
- ErrorCode9.UNSUPPORTED_TRANSACTION_TYPE,
4380
+ throw new FuelError13(
4381
+ ErrorCode10.UNSUPPORTED_TRANSACTION_TYPE,
3806
4382
  `Unsupported transaction type: ${type}.`
3807
4383
  );
3808
4384
  }
3809
4385
  }
3810
4386
  }, "transactionRequestify");
3811
- var isTransactionTypeScript = /* @__PURE__ */ __name((request) => request.type === TransactionType7.Script, "isTransactionTypeScript");
3812
- var isTransactionTypeCreate = /* @__PURE__ */ __name((request) => request.type === TransactionType7.Create, "isTransactionTypeCreate");
4387
+ var isTransactionTypeScript = /* @__PURE__ */ __name((request) => request.type === TransactionType8.Script, "isTransactionTypeScript");
4388
+ var isTransactionTypeCreate = /* @__PURE__ */ __name((request) => request.type === TransactionType8.Create, "isTransactionTypeCreate");
3813
4389
 
3814
4390
  // src/providers/resource-cache.ts
3815
4391
  var cache = /* @__PURE__ */ new Map();
@@ -3821,8 +4397,8 @@ var ResourceCache = class {
3821
4397
  constructor(ttl) {
3822
4398
  this.ttl = ttl;
3823
4399
  if (typeof ttl !== "number" || this.ttl <= 0) {
3824
- throw new FuelError13(
3825
- ErrorCode10.INVALID_TTL,
4400
+ throw new FuelError14(
4401
+ ErrorCode11.INVALID_TTL,
3826
4402
  `Invalid TTL: ${this.ttl}. Use a value greater than zero.`
3827
4403
  );
3828
4404
  }
@@ -3899,26 +4475,26 @@ var ResourceCache = class {
3899
4475
  }
3900
4476
  extractResourceData(input) {
3901
4477
  if (isRequestInputCoin(input)) {
3902
- return { owner: hexlify16(input.owner), key: hexlify16(input.id), type: "utxo" };
4478
+ return { owner: hexlify17(input.owner), key: hexlify17(input.id), type: "utxo" };
3903
4479
  }
3904
- return { owner: hexlify16(input.recipient), key: hexlify16(input.nonce), type: "message" };
4480
+ return { owner: hexlify17(input.recipient), key: hexlify17(input.nonce), type: "message" };
3905
4481
  }
3906
4482
  };
3907
4483
 
3908
4484
  // 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";
4485
+ import { ErrorCode as ErrorCode15, FuelError as FuelError18 } from "@fuel-ts/errors";
4486
+ import { bn as bn17 } from "@fuel-ts/math";
4487
+ import { TransactionCoder as TransactionCoder5, TxPointerCoder } from "@fuel-ts/transactions";
4488
+ import { arrayify as arrayify12 } from "@fuel-ts/utils";
3913
4489
 
3914
4490
  // 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";
4491
+ import { bn as bn16 } from "@fuel-ts/math";
4492
+ import { PolicyType as PolicyType3, TransactionCoder as TransactionCoder4 } from "@fuel-ts/transactions";
4493
+ import { DateTime, hexlify as hexlify18 } from "@fuel-ts/utils";
3918
4494
 
3919
4495
  // 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";
4496
+ import { bn as bn13 } from "@fuel-ts/math";
4497
+ import { PolicyType as PolicyType2, TransactionCoder as TransactionCoder3, TransactionType as TransactionType9 } from "@fuel-ts/transactions";
3922
4498
  import { arrayify as arrayify11 } from "@fuel-ts/utils";
3923
4499
  var calculateTXFeeForSummary = /* @__PURE__ */ __name((params) => {
3924
4500
  const {
@@ -3927,19 +4503,19 @@ var calculateTXFeeForSummary = /* @__PURE__ */ __name((params) => {
3927
4503
  tip,
3928
4504
  consensusParameters: { gasCosts, feeParams, maxGasPerTx }
3929
4505
  } = params;
3930
- const gasPerByte = bn12(feeParams.gasPerByte);
3931
- const gasPriceFactor = bn12(feeParams.gasPriceFactor);
4506
+ const gasPerByte = bn13(feeParams.gasPerByte);
4507
+ const gasPriceFactor = bn13(feeParams.gasPriceFactor);
3932
4508
  const transactionBytes = arrayify11(rawPayload);
3933
4509
  const [transaction] = new TransactionCoder3().decode(transactionBytes, 0);
3934
4510
  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);
4511
+ let metadataGas = bn13(0);
4512
+ let gasLimit = bn13(0);
4513
+ if (type !== TransactionType9.Create && type !== TransactionType9.Script) {
4514
+ return bn13(0);
3939
4515
  }
3940
- if (type === TransactionType8.Create) {
4516
+ if (type === TransactionType9.Create) {
3941
4517
  const { bytecodeWitnessIndex, storageSlots } = transaction;
3942
- const contractBytesSize = bn12(arrayify11(witnesses[bytecodeWitnessIndex].data).length);
4518
+ const contractBytesSize = bn13(arrayify11(witnesses[bytecodeWitnessIndex].data).length);
3943
4519
  metadataGas = calculateMetadataGasForTxCreate({
3944
4520
  contractBytesSize,
3945
4521
  gasCosts,
@@ -3958,7 +4534,7 @@ var calculateTXFeeForSummary = /* @__PURE__ */ __name((params) => {
3958
4534
  }
3959
4535
  const minGas = getMinGas({
3960
4536
  gasCosts,
3961
- gasPerByte: bn12(gasPerByte),
4537
+ gasPerByte: bn13(gasPerByte),
3962
4538
  inputs,
3963
4539
  metadataGas,
3964
4540
  txBytesSize: transactionBytes.length
@@ -3984,14 +4560,14 @@ var calculateTXFeeForSummary = /* @__PURE__ */ __name((params) => {
3984
4560
 
3985
4561
  // src/providers/transaction-summary/operations.ts
3986
4562
  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";
4563
+ import { ErrorCode as ErrorCode13, FuelError as FuelError16 } from "@fuel-ts/errors";
4564
+ import { bn as bn14 } from "@fuel-ts/math";
4565
+ import { ReceiptType as ReceiptType5, TransactionType as TransactionType10 } from "@fuel-ts/transactions";
3990
4566
 
3991
4567
  // src/providers/transaction-summary/input.ts
3992
- import { ErrorCode as ErrorCode11, FuelError as FuelError14 } from "@fuel-ts/errors";
4568
+ import { ErrorCode as ErrorCode12, FuelError as FuelError15 } from "@fuel-ts/errors";
3993
4569
  import { BN } from "@fuel-ts/math";
3994
- import { InputType as InputType6 } from "@fuel-ts/transactions";
4570
+ import { InputType as InputType7 } from "@fuel-ts/transactions";
3995
4571
  function getInputsByTypes(inputs, types) {
3996
4572
  return inputs.filter((i) => types.includes(i.type));
3997
4573
  }
@@ -4001,23 +4577,23 @@ function getInputsByType(inputs, type) {
4001
4577
  }
4002
4578
  __name(getInputsByType, "getInputsByType");
4003
4579
  function getInputsCoin(inputs) {
4004
- return getInputsByType(inputs, InputType6.Coin);
4580
+ return getInputsByType(inputs, InputType7.Coin);
4005
4581
  }
4006
4582
  __name(getInputsCoin, "getInputsCoin");
4007
4583
  function getInputsMessage(inputs) {
4008
- return getInputsByType(inputs, InputType6.Message);
4584
+ return getInputsByType(inputs, InputType7.Message);
4009
4585
  }
4010
4586
  __name(getInputsMessage, "getInputsMessage");
4011
4587
  function getInputsCoinAndMessage(inputs) {
4012
- return getInputsByTypes(inputs, [InputType6.Coin, InputType6.Message]);
4588
+ return getInputsByTypes(inputs, [InputType7.Coin, InputType7.Message]);
4013
4589
  }
4014
4590
  __name(getInputsCoinAndMessage, "getInputsCoinAndMessage");
4015
4591
  function isInputCoin(input) {
4016
- return input.type === InputType6.Coin;
4592
+ return input.type === InputType7.Coin;
4017
4593
  }
4018
4594
  __name(isInputCoin, "isInputCoin");
4019
4595
  function getInputsContract(inputs) {
4020
- return getInputsByType(inputs, InputType6.Contract);
4596
+ return getInputsByType(inputs, InputType7.Contract);
4021
4597
  }
4022
4598
  __name(getInputsContract, "getInputsContract");
4023
4599
  function findCoinInput(inputs, assetId) {
@@ -4068,9 +4644,9 @@ function getInputContractFromIndex(inputs, inputIndex) {
4068
4644
  if (!contractInput) {
4069
4645
  return void 0;
4070
4646
  }
4071
- if (contractInput.type !== InputType6.Contract) {
4072
- throw new FuelError14(
4073
- ErrorCode11.INVALID_TRANSACTION_INPUT,
4647
+ if (contractInput.type !== InputType7.Contract) {
4648
+ throw new FuelError15(
4649
+ ErrorCode12.INVALID_TRANSACTION_INPUT,
4074
4650
  `Contract input should be of type 'contract'.`
4075
4651
  );
4076
4652
  }
@@ -4078,10 +4654,10 @@ function getInputContractFromIndex(inputs, inputIndex) {
4078
4654
  }
4079
4655
  __name(getInputContractFromIndex, "getInputContractFromIndex");
4080
4656
  function getInputAccountAddress(input) {
4081
- if (input.type === InputType6.Coin) {
4657
+ if (input.type === InputType7.Coin) {
4082
4658
  return input.owner.toString();
4083
4659
  }
4084
- if (input.type === InputType6.Message) {
4660
+ if (input.type === InputType7.Message) {
4085
4661
  return input.recipient.toString();
4086
4662
  }
4087
4663
  return "";
@@ -4089,25 +4665,25 @@ function getInputAccountAddress(input) {
4089
4665
  __name(getInputAccountAddress, "getInputAccountAddress");
4090
4666
 
4091
4667
  // src/providers/transaction-summary/output.ts
4092
- import { OutputType as OutputType7 } from "@fuel-ts/transactions";
4668
+ import { OutputType as OutputType8 } from "@fuel-ts/transactions";
4093
4669
  function getOutputsByType(outputs, type) {
4094
4670
  return outputs.filter((o) => o.type === type);
4095
4671
  }
4096
4672
  __name(getOutputsByType, "getOutputsByType");
4097
4673
  function getOutputsContractCreated(outputs) {
4098
- return getOutputsByType(outputs, OutputType7.ContractCreated);
4674
+ return getOutputsByType(outputs, OutputType8.ContractCreated);
4099
4675
  }
4100
4676
  __name(getOutputsContractCreated, "getOutputsContractCreated");
4101
4677
  function getOutputsCoin(outputs) {
4102
- return getOutputsByType(outputs, OutputType7.Coin);
4678
+ return getOutputsByType(outputs, OutputType8.Coin);
4103
4679
  }
4104
4680
  __name(getOutputsCoin, "getOutputsCoin");
4105
4681
  function getOutputsChange(outputs) {
4106
- return getOutputsByType(outputs, OutputType7.Change);
4682
+ return getOutputsByType(outputs, OutputType8.Change);
4107
4683
  }
4108
4684
  __name(getOutputsChange, "getOutputsChange");
4109
4685
  function getOutputsContract(outputs) {
4110
- return getOutputsByType(outputs, OutputType7.Contract);
4686
+ return getOutputsByType(outputs, OutputType8.Contract);
4111
4687
  }
4112
4688
  __name(getOutputsContract, "getOutputsContract");
4113
4689
 
@@ -4118,21 +4694,21 @@ function getReceiptsByType(receipts, type) {
4118
4694
  __name(getReceiptsByType, "getReceiptsByType");
4119
4695
  function getTransactionTypeName(transactionType) {
4120
4696
  switch (transactionType) {
4121
- case TransactionType9.Mint:
4697
+ case TransactionType10.Mint:
4122
4698
  return "Mint" /* Mint */;
4123
- case TransactionType9.Create:
4699
+ case TransactionType10.Create:
4124
4700
  return "Create" /* Create */;
4125
- case TransactionType9.Script:
4701
+ case TransactionType10.Script:
4126
4702
  return "Script" /* Script */;
4127
- case TransactionType9.Blob:
4703
+ case TransactionType10.Blob:
4128
4704
  return "Blob" /* Blob */;
4129
- case TransactionType9.Upgrade:
4705
+ case TransactionType10.Upgrade:
4130
4706
  return "Upgrade" /* Upgrade */;
4131
- case TransactionType9.Upload:
4707
+ case TransactionType10.Upload:
4132
4708
  return "Upload" /* Upload */;
4133
4709
  default:
4134
- throw new FuelError15(
4135
- ErrorCode12.UNSUPPORTED_TRANSACTION_TYPE,
4710
+ throw new FuelError16(
4711
+ ErrorCode13.UNSUPPORTED_TRANSACTION_TYPE,
4136
4712
  `Unsupported transaction type: ${transactionType}.`
4137
4713
  );
4138
4714
  }
@@ -4185,7 +4761,7 @@ function mergeAssets(op1, op2) {
4185
4761
  assets2.forEach((asset) => {
4186
4762
  const existingAsset = assetMap.get(asset.assetId);
4187
4763
  if (existingAsset) {
4188
- existingAsset.amount = bn13(existingAsset.amount).add(asset.amount);
4764
+ existingAsset.amount = bn14(existingAsset.amount).add(asset.amount);
4189
4765
  } else {
4190
4766
  assetMap.set(asset.assetId, { ...asset });
4191
4767
  }
@@ -4537,8 +5113,8 @@ var extractBurnedAssetsFromReceipts = /* @__PURE__ */ __name((receipts) => {
4537
5113
  }, "extractBurnedAssetsFromReceipts");
4538
5114
 
4539
5115
  // 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";
5116
+ import { ErrorCode as ErrorCode14, FuelError as FuelError17 } from "@fuel-ts/errors";
5117
+ import { bn as bn15 } from "@fuel-ts/math";
4542
5118
  var getTransactionStatusName = /* @__PURE__ */ __name((gqlStatus) => {
4543
5119
  switch (gqlStatus) {
4544
5120
  case "FailureStatus":
@@ -4549,22 +5125,41 @@ var getTransactionStatusName = /* @__PURE__ */ __name((gqlStatus) => {
4549
5125
  return "submitted" /* submitted */;
4550
5126
  case "SqueezedOutStatus":
4551
5127
  return "squeezedout" /* squeezedout */;
5128
+ case "PreconfirmationSuccessStatus":
5129
+ return "preconfirmationSuccess" /* preconfirmationSuccess */;
5130
+ case "PreconfirmationFailureStatus":
5131
+ return "preconfirmationFailure" /* preconfirmationFailure */;
4552
5132
  default:
4553
- throw new FuelError16(
4554
- ErrorCode13.INVALID_TRANSACTION_STATUS,
5133
+ throw new FuelError17(
5134
+ ErrorCode14.INVALID_TRANSACTION_STATUS,
4555
5135
  `Invalid transaction status: ${gqlStatus}.`
4556
5136
  );
4557
5137
  }
4558
5138
  }, "getTransactionStatusName");
5139
+ var extractResolvedOutputs = /* @__PURE__ */ __name((serializedOutputs) => {
5140
+ const resolvedOutputs = [];
5141
+ serializedOutputs?.forEach(
5142
+ ({ utxoId, output }) => resolvedOutputs.push({
5143
+ utxoId,
5144
+ output: deserializeProcessedTxOutput(output)
5145
+ })
5146
+ );
5147
+ return resolvedOutputs;
5148
+ }, "extractResolvedOutputs");
4559
5149
  var processGraphqlStatus = /* @__PURE__ */ __name((gqlTransactionStatus) => {
4560
5150
  let time;
4561
5151
  let blockId;
4562
5152
  let status;
4563
5153
  let totalFee;
4564
5154
  let totalGas;
5155
+ let receipts;
5156
+ let resolvedOutputs = [];
5157
+ let errorReason;
4565
5158
  let isStatusFailure = false;
4566
5159
  let isStatusSuccess = false;
4567
5160
  let isStatusPending = false;
5161
+ let isStatusPreConfirmationSuccess = false;
5162
+ let isStatusPreConfirmationFailure = false;
4568
5163
  if (gqlTransactionStatus?.type) {
4569
5164
  status = getTransactionStatusName(gqlTransactionStatus.type);
4570
5165
  switch (gqlTransactionStatus.type) {
@@ -4572,20 +5167,37 @@ var processGraphqlStatus = /* @__PURE__ */ __name((gqlTransactionStatus) => {
4572
5167
  time = gqlTransactionStatus.time;
4573
5168
  blockId = gqlTransactionStatus.block?.id;
4574
5169
  isStatusSuccess = true;
4575
- totalFee = bn14(gqlTransactionStatus.totalFee);
4576
- totalGas = bn14(gqlTransactionStatus.totalGas);
5170
+ receipts = gqlTransactionStatus.receipts?.map(deserializeReceipt);
5171
+ totalFee = bn15(gqlTransactionStatus.totalFee);
5172
+ totalGas = bn15(gqlTransactionStatus.totalGas);
4577
5173
  break;
4578
5174
  case "FailureStatus":
4579
5175
  time = gqlTransactionStatus.time;
4580
5176
  blockId = gqlTransactionStatus.block?.id;
4581
5177
  isStatusFailure = true;
4582
- totalFee = bn14(gqlTransactionStatus.totalFee);
4583
- totalGas = bn14(gqlTransactionStatus.totalGas);
5178
+ totalFee = bn15(gqlTransactionStatus.totalFee);
5179
+ receipts = gqlTransactionStatus.receipts?.map(deserializeReceipt);
5180
+ totalGas = bn15(gqlTransactionStatus.totalGas);
4584
5181
  break;
4585
5182
  case "SubmittedStatus":
4586
5183
  time = gqlTransactionStatus.time;
4587
5184
  isStatusPending = true;
4588
5185
  break;
5186
+ case "PreconfirmationSuccessStatus":
5187
+ isStatusPreConfirmationSuccess = true;
5188
+ totalFee = bn15(gqlTransactionStatus.totalFee);
5189
+ totalGas = bn15(gqlTransactionStatus.totalGas);
5190
+ receipts = gqlTransactionStatus.preconfirmationReceipts?.map(deserializeReceipt);
5191
+ resolvedOutputs = extractResolvedOutputs(gqlTransactionStatus.resolvedOutputs);
5192
+ break;
5193
+ case "PreconfirmationFailureStatus":
5194
+ isStatusPreConfirmationFailure = true;
5195
+ totalFee = bn15(gqlTransactionStatus.totalFee);
5196
+ totalGas = bn15(gqlTransactionStatus.totalGas);
5197
+ receipts = gqlTransactionStatus.preconfirmationReceipts?.map(deserializeReceipt);
5198
+ resolvedOutputs = extractResolvedOutputs(gqlTransactionStatus.resolvedOutputs);
5199
+ errorReason = gqlTransactionStatus.reason;
5200
+ break;
4589
5201
  default:
4590
5202
  }
4591
5203
  }
@@ -4595,13 +5207,18 @@ var processGraphqlStatus = /* @__PURE__ */ __name((gqlTransactionStatus) => {
4595
5207
  status,
4596
5208
  totalFee,
4597
5209
  totalGas,
5210
+ receipts,
4598
5211
  isStatusFailure,
4599
5212
  isStatusSuccess,
4600
- isStatusPending
5213
+ isStatusPending,
5214
+ isStatusPreConfirmationSuccess,
5215
+ isStatusPreConfirmationFailure,
5216
+ resolvedOutputs,
5217
+ errorReason
4601
5218
  };
4602
5219
  return processedGraphqlStatus;
4603
5220
  }, "processGraphqlStatus");
4604
- var getTotalFeeFromStatus = /* @__PURE__ */ __name((status) => status && "totalFee" in status ? bn14(status.totalFee) : void 0, "getTotalFeeFromStatus");
5221
+ var getTotalFeeFromStatus = /* @__PURE__ */ __name((status) => status && "totalFee" in status ? bn15(status.totalFee) : void 0, "getTotalFeeFromStatus");
4605
5222
 
4606
5223
  // src/providers/transaction-summary/assemble-transaction-summary.ts
4607
5224
  function assembleTransactionSummary(params) {
@@ -4621,7 +5238,7 @@ function assembleTransactionSummary(params) {
4621
5238
  baseAssetId
4622
5239
  } = params;
4623
5240
  const gasUsed = getGasUsedFromReceipts(receipts);
4624
- const rawPayload = hexlify17(transactionBytes);
5241
+ const rawPayload = hexlify18(transactionBytes);
4625
5242
  const operations = getOperations({
4626
5243
  transactionType: transaction.type,
4627
5244
  inputs: transaction.inputs || [],
@@ -4633,7 +5250,7 @@ function assembleTransactionSummary(params) {
4633
5250
  baseAssetId
4634
5251
  });
4635
5252
  const typeName = getTransactionTypeName(transaction.type);
4636
- const tip = bn15(transaction.policies?.find((policy) => policy.type === PolicyType3.Tip)?.data);
5253
+ const tip = bn16(transaction.policies?.find((policy) => policy.type === PolicyType3.Tip)?.data);
4637
5254
  const { isStatusFailure, isStatusPending, isStatusSuccess, blockId, status, time, totalFee } = processGraphqlStatus(gqlTransactionStatus);
4638
5255
  const fee = totalFee ?? calculateTXFeeForSummary({
4639
5256
  gasPrice,
@@ -4682,6 +5299,81 @@ function assembleTransactionSummary(params) {
4682
5299
  return transactionSummary;
4683
5300
  }
4684
5301
  __name(assembleTransactionSummary, "assembleTransactionSummary");
5302
+ function assemblePreConfirmationTransactionSummary(params) {
5303
+ const { id, gqlTransactionStatus, transactionRequest, baseAssetId, maxInputs, abiMap } = params;
5304
+ let type;
5305
+ let operations;
5306
+ let gasUsed;
5307
+ let tip;
5308
+ let transaction;
5309
+ let mintedAssets;
5310
+ let burnedAssets;
5311
+ const {
5312
+ isStatusFailure,
5313
+ isStatusSuccess,
5314
+ isStatusPending,
5315
+ status,
5316
+ receipts,
5317
+ resolvedOutputs,
5318
+ errorReason,
5319
+ totalFee,
5320
+ isStatusPreConfirmationFailure,
5321
+ isStatusPreConfirmationSuccess
5322
+ } = processGraphqlStatus(gqlTransactionStatus);
5323
+ if (receipts) {
5324
+ gasUsed = getGasUsedFromReceipts(receipts);
5325
+ mintedAssets = extractMintedAssetsFromReceipts(receipts);
5326
+ burnedAssets = extractBurnedAssetsFromReceipts(receipts);
5327
+ }
5328
+ if (transactionRequest) {
5329
+ transaction = transactionRequest.toTransaction();
5330
+ type = getTransactionTypeName(transaction.type);
5331
+ tip = bn16(transaction.policies?.find((policy) => policy.type === PolicyType3.Tip)?.data);
5332
+ if (receipts) {
5333
+ const rawPayload = hexlify18(new TransactionCoder4().encode(transaction));
5334
+ operations = getOperations({
5335
+ transactionType: transaction.type,
5336
+ inputs: transaction.inputs || [],
5337
+ outputs: transaction.outputs || [],
5338
+ receipts,
5339
+ rawPayload,
5340
+ abiMap,
5341
+ maxInputs,
5342
+ baseAssetId
5343
+ });
5344
+ }
5345
+ }
5346
+ const transactionSummary = {
5347
+ id,
5348
+ fee: totalFee,
5349
+ type,
5350
+ status,
5351
+ receipts,
5352
+ gasUsed,
5353
+ tip,
5354
+ isStatusPreConfirmationFailure,
5355
+ isStatusPreConfirmationSuccess,
5356
+ isStatusFailure,
5357
+ isStatusSuccess,
5358
+ isStatusPending,
5359
+ ...transaction && {
5360
+ isTypeMint: isTypeMint(transaction.type),
5361
+ isTypeCreate: isTypeCreate(transaction.type),
5362
+ isTypeScript: isTypeScript(transaction.type),
5363
+ isTypeUpgrade: isTypeUpgrade(transaction.type),
5364
+ isTypeUpload: isTypeUpload(transaction.type),
5365
+ isTypeBlob: isTypeBlob(transaction.type)
5366
+ },
5367
+ mintedAssets,
5368
+ burnedAssets,
5369
+ resolvedOutputs,
5370
+ errorReason,
5371
+ transaction,
5372
+ operations
5373
+ };
5374
+ return transactionSummary;
5375
+ }
5376
+ __name(assemblePreConfirmationTransactionSummary, "assemblePreConfirmationTransactionSummary");
4685
5377
 
4686
5378
  // src/providers/transaction-response/getAllDecodedLogs.ts
4687
5379
  import { Interface as Interface2, BigNumberCoder } from "@fuel-ts/abi-coder";
@@ -4694,7 +5386,9 @@ function getAllDecodedLogs(opts) {
4694
5386
  const firstCallReceipt = receipts.find(
4695
5387
  (r) => r.type === ReceiptType7.Call && r.id === ZeroBytes3210
4696
5388
  );
4697
- mainContract = firstCallReceipt.to;
5389
+ if (firstCallReceipt) {
5390
+ mainContract = firstCallReceipt.to;
5391
+ }
4698
5392
  }
4699
5393
  return receipts.reduce(
4700
5394
  ({ logs, groupedLogs }, receipt) => {
@@ -4717,37 +5411,6 @@ function getAllDecodedLogs(opts) {
4717
5411
  __name(getAllDecodedLogs, "getAllDecodedLogs");
4718
5412
 
4719
5413
  // 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
5414
  var TransactionResponse = class _TransactionResponse {
4752
5415
  /**
4753
5416
  * Constructor for `TransactionResponse`.
@@ -4757,11 +5420,16 @@ var TransactionResponse = class _TransactionResponse {
4757
5420
  */
4758
5421
  constructor(tx, provider, chainId, abis, submitTxSubscription) {
4759
5422
  this.submitTxSubscription = submitTxSubscription;
4760
- this.id = typeof tx === "string" ? tx : tx.getTransactionId(chainId);
5423
+ if (typeof tx === "string") {
5424
+ this.id = tx;
5425
+ } else {
5426
+ this.id = tx.getTransactionId(chainId);
5427
+ this.request = tx;
5428
+ }
4761
5429
  this.provider = provider;
4762
5430
  this.abis = abis;
4763
- this.request = typeof tx === "string" ? void 0 : tx;
4764
5431
  this.waitForResult = this.waitForResult.bind(this);
5432
+ this.waitForPreConfirmation = this.waitForPreConfirmation.bind(this);
4765
5433
  }
4766
5434
  static {
4767
5435
  __name(this, "TransactionResponse");
@@ -4771,12 +5439,15 @@ var TransactionResponse = class _TransactionResponse {
4771
5439
  /** Current provider */
4772
5440
  provider;
4773
5441
  /** Gas used on the transaction */
4774
- gasUsed = bn16(0);
5442
+ gasUsed = bn17(0);
4775
5443
  /** The graphql Transaction with receipts object. */
4776
5444
  gqlTransaction;
4777
5445
  request;
4778
5446
  status;
4779
5447
  abis;
5448
+ preConfirmationStatus;
5449
+ waitingForStreamData = false;
5450
+ statusResolvers = /* @__PURE__ */ new Map();
4780
5451
  /**
4781
5452
  * Async constructor for `TransactionResponse`. This method can be used to create
4782
5453
  * an instance of `TransactionResponse` and wait for the transaction to be fetched
@@ -4808,29 +5479,38 @@ var TransactionResponse = class _TransactionResponse {
4808
5479
  }
4809
5480
  return input;
4810
5481
  });
4811
- tx.outputs = mapGqlOutputsToTxOutputs(status.transaction.outputs);
4812
- if ("receiptsRoot" in status.transaction) {
5482
+ tx.outputs = status.transaction.outputs.map(deserializeProcessedTxOutput);
5483
+ if (status.transaction.receiptsRoot) {
4813
5484
  tx.receiptsRoot = status.transaction.receiptsRoot;
4814
5485
  }
4815
5486
  }
4816
5487
  }
4817
5488
  async getTransaction() {
4818
5489
  if (this.request) {
4819
- const tx = this.request.toTransaction();
4820
- this.applyMalleableSubscriptionFields(tx);
5490
+ const tx2 = this.request.toTransaction();
5491
+ this.applyMalleableSubscriptionFields(tx2);
4821
5492
  return {
4822
- tx,
5493
+ tx: tx2,
4823
5494
  bytes: this.request.toTransactionBytes()
4824
5495
  };
4825
5496
  }
4826
5497
  const gqlTransaction = this.gqlTransaction ?? await this.fetch();
5498
+ const { rawPayload } = gqlTransaction;
5499
+ const bytes = arrayify12(rawPayload);
5500
+ const [tx] = new TransactionCoder5().decode(bytes, 0);
4827
5501
  return {
4828
- tx: this.decodeTransaction(gqlTransaction),
4829
- bytes: arrayify12(gqlTransaction.rawPayload)
5502
+ tx,
5503
+ bytes
4830
5504
  };
4831
5505
  }
5506
+ /**
5507
+ *
5508
+ * NOTE: This method is only called within `getTransactionSummary`, which is invoked after `getTransaction`.
5509
+ * Since `getTransaction` only resolves once the transaction has been processed,
5510
+ * the status at this point is guaranteed to be either `SuccessStatus` or `FailureStatus`.
5511
+ */
4832
5512
  getReceipts() {
4833
- const status = this.status ?? this.gqlTransaction?.status;
5513
+ const status = this.getTransactionStatus();
4834
5514
  switch (status?.type) {
4835
5515
  case "SuccessStatus":
4836
5516
  case "FailureStatus":
@@ -4863,18 +5543,6 @@ var TransactionResponse = class _TransactionResponse {
4863
5543
  this.gqlTransaction = response.transaction;
4864
5544
  return response.transaction;
4865
5545
  }
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
5546
  /**
4879
5547
  * Retrieves the TransactionSummary. If the `gqlTransaction` is not set, it will
4880
5548
  * fetch it from the provider
@@ -4885,8 +5553,9 @@ var TransactionResponse = class _TransactionResponse {
4885
5553
  async getTransactionSummary(contractsAbiMap) {
4886
5554
  const { tx: transaction, bytes: transactionBytes } = await this.getTransaction();
4887
5555
  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();
5556
+ const transactionStatus = this.getTransactionStatus();
5557
+ const totalFee = getTotalFeeFromStatus(transactionStatus);
5558
+ const gasPrice = totalFee ? bn17(0) : await this.provider.getLatestGasPrice();
4890
5559
  const maxInputs = (await this.provider.getChain()).consensusParameters.txParameters.maxInputs;
4891
5560
  const baseAssetId = await this.provider.getBaseAssetId();
4892
5561
  const transactionSummary = assembleTransactionSummary({
@@ -4894,7 +5563,7 @@ var TransactionResponse = class _TransactionResponse {
4894
5563
  receipts: this.getReceipts(),
4895
5564
  transaction,
4896
5565
  transactionBytes,
4897
- gqlTransactionStatus: this.status ?? this.gqlTransaction?.status,
5566
+ gqlTransactionStatus: transactionStatus,
4898
5567
  gasPerByte,
4899
5568
  gasPriceFactor,
4900
5569
  abiMap: contractsAbiMap,
@@ -4904,31 +5573,94 @@ var TransactionResponse = class _TransactionResponse {
4904
5573
  gasPrice,
4905
5574
  baseAssetId
4906
5575
  });
4907
- return transactionSummary;
5576
+ return transactionSummary;
5577
+ }
5578
+ async getPreConfirmationTransactionSummary(contractsAbiMap) {
5579
+ const baseAssetId = await this.provider.getBaseAssetId();
5580
+ const maxInputs = (await this.provider.getChain()).consensusParameters.txParameters.maxInputs;
5581
+ const transactionSummary = assemblePreConfirmationTransactionSummary({
5582
+ id: this.id,
5583
+ gqlTransactionStatus: this.preConfirmationStatus || this.status,
5584
+ baseAssetId,
5585
+ maxInputs,
5586
+ abiMap: contractsAbiMap,
5587
+ transactionRequest: this.request
5588
+ });
5589
+ return transactionSummary;
5590
+ }
5591
+ resolveStatus(type) {
5592
+ const resolvers = this.statusResolvers.get(type) || [];
5593
+ resolvers.forEach((resolve) => resolve());
5594
+ this.statusResolvers.delete(type);
5595
+ }
5596
+ async waitForStatus(type) {
5597
+ return new Promise((resolve, reject) => {
5598
+ const resolvers = this.statusResolvers.get(type) || [];
5599
+ resolvers.push(() => {
5600
+ resolve();
5601
+ });
5602
+ this.statusResolvers.set(type, resolvers);
5603
+ this.waitForStatusChange().catch(reject);
5604
+ });
4908
5605
  }
5606
+ /**
5607
+ * Waits for the status change of the transaction.
5608
+ * If the transaction is already in a final state, it will return immediately.
5609
+ * If the transaction is not in a final state, it will wait for the status change.
5610
+ * If we are already subscribed to the status change, it will return immediately.
5611
+ */
4909
5612
  async waitForStatusChange() {
4910
- const status = this.gqlTransaction?.status?.type;
4911
- if (status && status !== "SubmittedStatus") {
5613
+ const type = this.status?.type;
5614
+ if (type && (type === "FailureStatus" || type === "SuccessStatus")) {
5615
+ this.resolveStatus("preConfirmation");
5616
+ this.resolveStatus("confirmation");
5617
+ return;
5618
+ }
5619
+ if (this.waitingForStreamData) {
4912
5620
  return;
4913
5621
  }
5622
+ this.waitingForStreamData = true;
4914
5623
  const subscription = this.submitTxSubscription ?? await this.provider.operations.statusChange({
4915
- transactionId: this.id
5624
+ transactionId: this.id,
5625
+ includePreConfirmation: true
4916
5626
  });
4917
5627
  for await (const sub of subscription) {
4918
5628
  const statusChange = "statusChange" in sub ? sub.statusChange : sub.submitAndAwaitStatus;
4919
5629
  this.status = statusChange;
4920
5630
  if (statusChange.type === "SqueezedOutStatus") {
4921
- this.unsetResourceCache();
4922
- throw new FuelError17(
4923
- ErrorCode14.TRANSACTION_SQUEEZED_OUT,
5631
+ throw new FuelError18(
5632
+ ErrorCode15.TRANSACTION_SQUEEZED_OUT,
4924
5633
  `Transaction Squeezed Out with reason: ${statusChange.reason}`
4925
5634
  );
4926
5635
  }
4927
- if (statusChange.type !== "SubmittedStatus") {
5636
+ if (statusChange.type === "PreconfirmationSuccessStatus" || statusChange.type === "PreconfirmationFailureStatus") {
5637
+ this.preConfirmationStatus = statusChange;
5638
+ this.resolveStatus("preConfirmation");
5639
+ }
5640
+ if (statusChange.type === "SuccessStatus" || statusChange.type === "FailureStatus") {
5641
+ this.resolveStatus("confirmation");
5642
+ this.resolveStatus("preConfirmation");
5643
+ this.waitingForStreamData = false;
4928
5644
  break;
4929
5645
  }
4930
5646
  }
4931
5647
  }
5648
+ async waitForConfirmationStatuses() {
5649
+ try {
5650
+ await this.waitForStatus("confirmation");
5651
+ } catch (error) {
5652
+ this.unsetResourceCache();
5653
+ throw error;
5654
+ }
5655
+ }
5656
+ async waitForPreConfirmationStatuses() {
5657
+ try {
5658
+ await this.waitForStatus("preConfirmation");
5659
+ } catch (error) {
5660
+ this.unsetResourceCache();
5661
+ throw error;
5662
+ }
5663
+ }
4932
5664
  /**
4933
5665
  * Assembles the result of a transaction by retrieving the transaction summary,
4934
5666
  * decoding logs (if available), and handling transaction failure.
@@ -4957,7 +5689,7 @@ var TransactionResponse = class _TransactionResponse {
4957
5689
  transactionResult.groupedLogs = groupedLogs;
4958
5690
  }
4959
5691
  const { receipts } = transactionResult;
4960
- const status = this.status ?? this.gqlTransaction?.status;
5692
+ const status = this.getTransactionStatus();
4961
5693
  if (status?.type === "FailureStatus") {
4962
5694
  const { reason } = status;
4963
5695
  throw extractTxError({
@@ -4969,16 +5701,46 @@ var TransactionResponse = class _TransactionResponse {
4969
5701
  }
4970
5702
  return transactionResult;
4971
5703
  }
5704
+ async assemblePreConfirmationResult(contractsAbiMap) {
5705
+ const transactionSummary = await this.getPreConfirmationTransactionSummary(contractsAbiMap);
5706
+ const transactionResult = {
5707
+ ...transactionSummary,
5708
+ logs: [],
5709
+ groupedLogs: {}
5710
+ };
5711
+ let { logs, groupedLogs } = { logs: [], groupedLogs: {} };
5712
+ if (this.abis && transactionSummary.receipts) {
5713
+ ({ logs, groupedLogs } = getAllDecodedLogs({
5714
+ receipts: transactionSummary.receipts,
5715
+ mainAbi: this.abis.main,
5716
+ externalAbis: this.abis.otherContractsAbis
5717
+ }));
5718
+ transactionResult.logs = logs;
5719
+ transactionResult.groupedLogs = groupedLogs;
5720
+ }
5721
+ return transactionResult;
5722
+ }
4972
5723
  /**
4973
5724
  * Waits for transaction to complete and returns the result.
4974
5725
  *
4975
5726
  * @returns The completed transaction result
4976
5727
  */
4977
5728
  async waitForResult(contractsAbiMap) {
4978
- await this.waitForStatusChange();
5729
+ await this.waitForConfirmationStatuses();
4979
5730
  this.unsetResourceCache();
4980
5731
  return this.assembleResult(contractsAbiMap);
4981
5732
  }
5733
+ /**
5734
+ * Waits for the transaction's pre-confirmation and returns the result.
5735
+ *
5736
+ * @param contractsAbiMap - The contracts ABI map.
5737
+ * @returns The pre-confirmed transaction result
5738
+ */
5739
+ async waitForPreConfirmation(contractsAbiMap) {
5740
+ await this.waitForPreConfirmationStatuses();
5741
+ this.unsetResourceCache();
5742
+ return this.assemblePreConfirmationResult(contractsAbiMap);
5743
+ }
4982
5744
  /**
4983
5745
  * Waits for transaction to complete and returns the result.
4984
5746
  *
@@ -4990,6 +5752,9 @@ var TransactionResponse = class _TransactionResponse {
4990
5752
  unsetResourceCache() {
4991
5753
  this.provider.cache?.unset(this.id);
4992
5754
  }
5755
+ getTransactionStatus() {
5756
+ return this.status ?? this.gqlTransaction?.status;
5757
+ }
4993
5758
  };
4994
5759
 
4995
5760
  // src/providers/transaction-response/getDecodedLogs.ts
@@ -5036,48 +5801,49 @@ function autoRetryFetch(fetchFn, options, retryAttemptNum = 0) {
5036
5801
  }
5037
5802
  __name(autoRetryFetch, "autoRetryFetch");
5038
5803
 
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)];
5804
+ // src/providers/utils/parse-graphql-response.ts
5805
+ var parseGraphqlResponse = /* @__PURE__ */ __name(async (options) => {
5806
+ const { response, isSubscription } = options;
5807
+ let extensions;
5808
+ const responseClone = response.clone();
5809
+ if (isSubscription) {
5810
+ const reader = responseClone.body?.getReader();
5811
+ const { event } = await FuelGraphqlSubscriber.readEvent(reader);
5812
+ extensions = event?.extensions;
5813
+ } else {
5814
+ extensions = (await responseClone.json()).extensions;
5051
5815
  }
5052
- return final;
5053
- }, "adjustResourcesToExclude");
5816
+ return {
5817
+ extensions
5818
+ };
5819
+ }, "parseGraphqlResponse");
5054
5820
 
5055
5821
  // src/providers/utils/validate-pagination-args.ts
5056
- import { FuelError as FuelError18, ErrorCode as ErrorCode15 } from "@fuel-ts/errors";
5822
+ import { FuelError as FuelError19, ErrorCode as ErrorCode16 } from "@fuel-ts/errors";
5057
5823
  var validatePaginationArgs = /* @__PURE__ */ __name((params) => {
5058
5824
  const { paginationLimit, inputArgs = {} } = params;
5059
5825
  const { first, last, after, before } = inputArgs;
5060
5826
  if (after && before) {
5061
- throw new FuelError18(
5062
- ErrorCode15.INVALID_INPUT_PARAMETERS,
5827
+ throw new FuelError19(
5828
+ ErrorCode16.INVALID_INPUT_PARAMETERS,
5063
5829
  'Pagination arguments "after" and "before" cannot be used together'
5064
5830
  );
5065
5831
  }
5066
5832
  if ((first || 0) > paginationLimit || (last || 0) > paginationLimit) {
5067
- throw new FuelError18(
5068
- ErrorCode15.INVALID_INPUT_PARAMETERS,
5833
+ throw new FuelError19(
5834
+ ErrorCode16.INVALID_INPUT_PARAMETERS,
5069
5835
  `Pagination limit for this query cannot exceed ${paginationLimit} items`
5070
5836
  );
5071
5837
  }
5072
5838
  if (first && before) {
5073
- throw new FuelError18(
5074
- ErrorCode15.INVALID_INPUT_PARAMETERS,
5839
+ throw new FuelError19(
5840
+ ErrorCode16.INVALID_INPUT_PARAMETERS,
5075
5841
  'The use of pagination argument "first" with "before" is not supported'
5076
5842
  );
5077
5843
  }
5078
5844
  if (last && after) {
5079
- throw new FuelError18(
5080
- ErrorCode15.INVALID_INPUT_PARAMETERS,
5845
+ throw new FuelError19(
5846
+ ErrorCode16.INVALID_INPUT_PARAMETERS,
5081
5847
  'The use of pagination argument "last" with "after" is not supported'
5082
5848
  );
5083
5849
  }
@@ -5096,22 +5862,48 @@ var NON_PAGINATED_BALANCES_SIZE = 1e4;
5096
5862
  var BLOCKS_PAGE_SIZE_LIMIT = 5;
5097
5863
  var DEFAULT_RESOURCE_CACHE_TTL = 2e4;
5098
5864
  var GAS_USED_MODIFIER = 1.2;
5865
+ var WRITE_OPERATIONS = [
5866
+ "submit",
5867
+ "submitAndAwaitStatus",
5868
+ "produceBlocks"
5869
+ ];
5099
5870
  var Provider = class _Provider {
5100
5871
  static {
5101
5872
  __name(this, "Provider");
5102
5873
  }
5103
5874
  operations;
5104
5875
  cache;
5105
- /** @hidden */
5106
- static clearChainAndNodeCaches() {
5876
+ /**
5877
+ * @hidden
5878
+ * @param url - If provided, clears cache only for given url
5879
+ */
5880
+ static clearChainAndNodeCaches(url) {
5881
+ if (url) {
5882
+ delete _Provider.inflightFetchChainAndNodeInfoRequests[url];
5883
+ delete _Provider.chainInfoCache[url];
5884
+ delete _Provider.nodeInfoCache[url];
5885
+ delete _Provider.currentBlockHeightCache[url];
5886
+ return;
5887
+ }
5107
5888
  _Provider.inflightFetchChainAndNodeInfoRequests = {};
5108
5889
  _Provider.nodeInfoCache = {};
5109
5890
  _Provider.chainInfoCache = {};
5891
+ _Provider.currentBlockHeightCache = {};
5110
5892
  }
5111
5893
  /** @hidden */
5112
5894
  url;
5113
5895
  /** @hidden */
5114
5896
  urlWithoutAuth;
5897
+ /**
5898
+ * Governs whether to include the required block height in the request body
5899
+ * for block-sensitive operations like when submitting a transaction.
5900
+ *
5901
+ * This ensures that the operation is executed at the correct block height,
5902
+ * regardless of which node in the network the request is routed to.
5903
+ *
5904
+ * `true` by default.
5905
+ */
5906
+ static ENABLE_RPC_CONSISTENCY = true;
5115
5907
  /** @hidden */
5116
5908
  static inflightFetchChainAndNodeInfoRequests = {};
5117
5909
  /** @hidden */
@@ -5119,6 +5911,8 @@ var Provider = class _Provider {
5119
5911
  /** @hidden */
5120
5912
  static nodeInfoCache = {};
5121
5913
  /** @hidden */
5914
+ static currentBlockHeightCache = {};
5915
+ /** @hidden */
5122
5916
  static incompatibleNodeVersionMessage = "";
5123
5917
  /** @hidden */
5124
5918
  consensusParametersTimestamp;
@@ -5130,6 +5924,18 @@ var Provider = class _Provider {
5130
5924
  headers: void 0,
5131
5925
  cache: void 0
5132
5926
  };
5927
+ static extractOperationName(body) {
5928
+ return body?.toString().match(/"operationName":"(.+)"/)?.[1];
5929
+ }
5930
+ static isWriteOperation(body) {
5931
+ return WRITE_OPERATIONS.includes(this.extractOperationName(body));
5932
+ }
5933
+ static normalizeUrl(url) {
5934
+ return url.replace(/-sub$/, "");
5935
+ }
5936
+ static hasWriteOperationHappened(url) {
5937
+ return isDefined3(_Provider.currentBlockHeightCache[this.normalizeUrl(url)]);
5938
+ }
5133
5939
  /**
5134
5940
  * @hidden
5135
5941
  */
@@ -5147,9 +5953,57 @@ var Provider = class _Provider {
5147
5953
  if (options.requestMiddleware) {
5148
5954
  fullRequest = await options.requestMiddleware(fullRequest);
5149
5955
  }
5150
- return options.fetch ? options.fetch(url, fullRequest, options) : fetch(url, fullRequest);
5956
+ if (_Provider.ENABLE_RPC_CONSISTENCY && _Provider.hasWriteOperationHappened(url)) {
5957
+ _Provider.applyBlockHeight(fullRequest, url);
5958
+ }
5959
+ return _Provider.fetchAndProcessBlockHeight(url, fullRequest, options);
5151
5960
  }, retryOptions);
5152
5961
  }
5962
+ static applyBlockHeight(request, url) {
5963
+ const normalizedUrl = this.normalizeUrl(url);
5964
+ const currentBlockHeight = _Provider.currentBlockHeightCache[normalizedUrl] ?? 0;
5965
+ request.body = request.body?.toString().replace(/}$/, `,"extensions":{"required_fuel_block_height":${currentBlockHeight}}}`);
5966
+ }
5967
+ static async fetchAndProcessBlockHeight(url, request, options) {
5968
+ const fetchFn = /* @__PURE__ */ __name(() => options.fetch ? options.fetch(url, request, options) : fetch(url, request), "fetchFn");
5969
+ const isWriteOperation = _Provider.isWriteOperation(request.body);
5970
+ if (isWriteOperation && !_Provider.hasWriteOperationHappened(url)) {
5971
+ _Provider.currentBlockHeightCache[_Provider.normalizeUrl(url)] = 0;
5972
+ }
5973
+ let response = await fetchFn();
5974
+ if (!_Provider.ENABLE_RPC_CONSISTENCY) {
5975
+ return response;
5976
+ }
5977
+ const retryOptions = {
5978
+ maxRetries: 5,
5979
+ baseDelay: 500
5980
+ };
5981
+ for (let retriesLeft = retryOptions.maxRetries; retriesLeft > 0; --retriesLeft) {
5982
+ const { extensions } = await parseGraphqlResponse({
5983
+ response,
5984
+ isSubscription: url.endsWith("-sub")
5985
+ });
5986
+ _Provider.setCurrentBlockHeight(url, extensions?.current_fuel_block_height);
5987
+ if (!extensions?.fuel_block_height_precondition_failed) {
5988
+ break;
5989
+ }
5990
+ const retryAttempt = retryOptions.maxRetries - retriesLeft + 1;
5991
+ const sleepTime = getWaitDelay(retryOptions, retryAttempt);
5992
+ await sleep2(sleepTime);
5993
+ response = await fetchFn();
5994
+ }
5995
+ return response;
5996
+ }
5997
+ static setCurrentBlockHeight(url, height) {
5998
+ const writeOperationHappened = _Provider.hasWriteOperationHappened(url);
5999
+ if (!isDefined3(height) || !writeOperationHappened) {
6000
+ return;
6001
+ }
6002
+ const normalizedUrl = _Provider.normalizeUrl(url);
6003
+ if (height > _Provider.currentBlockHeightCache[normalizedUrl]) {
6004
+ _Provider.currentBlockHeightCache[normalizedUrl] = height;
6005
+ }
6006
+ }
5153
6007
  /**
5154
6008
  * Constructor to initialize a Provider.
5155
6009
  *
@@ -5177,7 +6031,7 @@ var Provider = class _Provider {
5177
6031
  _Provider.chainInfoCache[this.urlWithoutAuth] = chain;
5178
6032
  _Provider.nodeInfoCache[this.urlWithoutAuth] = nodeInfo;
5179
6033
  }
5180
- if (isDefined2(resourceCacheTTL)) {
6034
+ if (isDefined3(resourceCacheTTL)) {
5181
6035
  if (resourceCacheTTL !== -1) {
5182
6036
  this.cache = new ResourceCache(resourceCacheTTL);
5183
6037
  } else {
@@ -5192,7 +6046,7 @@ var Provider = class _Provider {
5192
6046
  try {
5193
6047
  parsedUrl = new URL(url);
5194
6048
  } catch (error) {
5195
- throw new FuelError19(FuelError19.CODES.INVALID_URL, "Invalid URL provided.", { url }, error);
6049
+ throw new FuelError20(FuelError20.CODES.INVALID_URL, "Invalid URL provided.", { url }, error);
5196
6050
  }
5197
6051
  const username = parsedUrl.username;
5198
6052
  const password = parsedUrl.password;
@@ -5235,6 +6089,7 @@ var Provider = class _Provider {
5235
6089
  * Returns some helpful parameters related to gas fees.
5236
6090
  */
5237
6091
  async getGasConfig() {
6092
+ await this.init();
5238
6093
  const {
5239
6094
  txParameters: { maxGasPerTx },
5240
6095
  predicateParameters: { maxGasPerPredicate },
@@ -5297,8 +6152,8 @@ var Provider = class _Provider {
5297
6152
  this.consensusParametersTimestamp = data.consensusParametersTimestamp;
5298
6153
  return data;
5299
6154
  }).catch((err) => {
5300
- const error = new FuelError19(
5301
- FuelError19.CODES.CONNECTION_REFUSED,
6155
+ const error = new FuelError20(
6156
+ FuelError20.CODES.CONNECTION_REFUSED,
5302
6157
  "Unable to fetch chain and node info from the network",
5303
6158
  { url: this.urlWithoutAuth },
5304
6159
  err
@@ -5359,7 +6214,14 @@ var Provider = class _Provider {
5359
6214
  url: this.urlWithoutAuth,
5360
6215
  query,
5361
6216
  fetchFn: /* @__PURE__ */ __name((url, requestInit) => fetchFn(url, requestInit, this.options), "fetchFn"),
5362
- variables: vars
6217
+ variables: vars,
6218
+ operationName: opDefinition.name.value,
6219
+ onEvent: /* @__PURE__ */ __name((event) => {
6220
+ _Provider.setCurrentBlockHeight(
6221
+ this.urlWithoutAuth,
6222
+ event.extensions?.current_fuel_block_height
6223
+ );
6224
+ }, "onEvent")
5363
6225
  });
5364
6226
  }
5365
6227
  return gqlClient.request(query, vars);
@@ -5407,7 +6269,7 @@ var Provider = class _Provider {
5407
6269
  latestBlock: { height }
5408
6270
  }
5409
6271
  } = await this.operations.getLatestBlockHeight();
5410
- return bn17(height);
6272
+ return bn18(height);
5411
6273
  }
5412
6274
  /**
5413
6275
  * Returns the node information for the current provider network.
@@ -5463,8 +6325,8 @@ var Provider = class _Provider {
5463
6325
  async getAssetDetails(assetId) {
5464
6326
  const { assetMetadata } = await this.getNodeFeatures();
5465
6327
  if (!assetMetadata) {
5466
- throw new FuelError19(
5467
- ErrorCode16.UNSUPPORTED_FEATURE,
6328
+ throw new FuelError20(
6329
+ ErrorCode17.UNSUPPORTED_FEATURE,
5468
6330
  "The current node does not supports fetching asset details"
5469
6331
  );
5470
6332
  }
@@ -5473,7 +6335,7 @@ var Provider = class _Provider {
5473
6335
  return {
5474
6336
  subId,
5475
6337
  contractId,
5476
- totalSupply: bn17(totalSupply)
6338
+ totalSupply: bn18(totalSupply)
5477
6339
  };
5478
6340
  }
5479
6341
  /**
@@ -5494,15 +6356,15 @@ var Provider = class _Provider {
5494
6356
  txParameters: { maxInputs, maxOutputs }
5495
6357
  }
5496
6358
  } = await this.getChain();
5497
- if (bn17(tx.inputs.length).gt(maxInputs)) {
5498
- throw new FuelError19(
5499
- ErrorCode16.MAX_INPUTS_EXCEEDED,
6359
+ if (bn18(tx.inputs.length).gt(maxInputs)) {
6360
+ throw new FuelError20(
6361
+ ErrorCode17.MAX_INPUTS_EXCEEDED,
5500
6362
  `The transaction exceeds the maximum allowed number of inputs. Tx inputs: ${tx.inputs.length}, max inputs: ${maxInputs}`
5501
6363
  );
5502
6364
  }
5503
- if (bn17(tx.outputs.length).gt(maxOutputs)) {
5504
- throw new FuelError19(
5505
- ErrorCode16.MAX_OUTPUTS_EXCEEDED,
6365
+ if (bn18(tx.outputs.length).gt(maxOutputs)) {
6366
+ throw new FuelError20(
6367
+ ErrorCode17.MAX_OUTPUTS_EXCEEDED,
5506
6368
  `The transaction exceeds the maximum allowed number of outputs. Tx outputs: ${tx.outputs.length}, max outputs: ${maxOutputs}`
5507
6369
  );
5508
6370
  }
@@ -5517,7 +6379,11 @@ var Provider = class _Provider {
5517
6379
  * @param sendTransactionParams - The provider send transaction parameters (optional).
5518
6380
  * @returns A promise that resolves to the transaction response object.
5519
6381
  */
5520
- async sendTransaction(transactionRequestLike, { estimateTxDependencies = true, enableAssetBurn } = {}) {
6382
+ async sendTransaction(transactionRequestLike, {
6383
+ enableAssetBurn,
6384
+ estimateTxDependencies = true,
6385
+ includePreConfirmation: _includePreConfirmation = true
6386
+ } = {}) {
5521
6387
  const transactionRequest = transactionRequestify(transactionRequestLike);
5522
6388
  validateTransactionForAssetBurn(
5523
6389
  await this.getBaseAssetId(),
@@ -5528,12 +6394,15 @@ var Provider = class _Provider {
5528
6394
  await this.estimateTxDependencies(transactionRequest);
5529
6395
  }
5530
6396
  await this.validateTransaction(transactionRequest);
5531
- const encodedTransaction = hexlify18(transactionRequest.toTransactionBytes());
6397
+ const encodedTransaction = hexlify19(transactionRequest.toTransactionBytes());
5532
6398
  let abis;
5533
6399
  if (isTransactionTypeScript(transactionRequest)) {
5534
6400
  abis = transactionRequest.abis;
5535
6401
  }
5536
- const subscription = await this.operations.submitAndAwaitStatus({ encodedTransaction });
6402
+ const subscription = await this.operations.submitAndAwaitStatus({
6403
+ encodedTransaction,
6404
+ includePreConfirmation: true
6405
+ });
5537
6406
  this.#cacheInputs(
5538
6407
  transactionRequest.inputs,
5539
6408
  transactionRequest.getTransactionId(await this.getChainId())
@@ -5556,7 +6425,7 @@ var Provider = class _Provider {
5556
6425
  if (estimateTxDependencies) {
5557
6426
  return this.estimateTxDependencies(transactionRequest);
5558
6427
  }
5559
- const encodedTransaction = hexlify18(transactionRequest.toTransactionBytes());
6428
+ const encodedTransaction = hexlify19(transactionRequest.toTransactionBytes());
5560
6429
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
5561
6430
  encodedTransactions: encodedTransaction,
5562
6431
  utxoValidation: utxoValidation || false
@@ -5575,12 +6444,12 @@ var Provider = class _Provider {
5575
6444
  */
5576
6445
  async estimatePredicates(transactionRequest) {
5577
6446
  const shouldEstimatePredicates = transactionRequest.inputs.some(
5578
- (input) => isPredicate(input) && bn17(input.predicateGasUsed).isZero()
6447
+ (input) => isPredicate(input) && bn18(input.predicateGasUsed).isZero()
5579
6448
  );
5580
6449
  if (!shouldEstimatePredicates) {
5581
6450
  return transactionRequest;
5582
6451
  }
5583
- const encodedTransaction = hexlify18(transactionRequest.toTransactionBytes());
6452
+ const encodedTransaction = hexlify19(transactionRequest.toTransactionBytes());
5584
6453
  const response = await this.operations.estimatePredicates({
5585
6454
  encodedTransaction
5586
6455
  });
@@ -5601,7 +6470,7 @@ var Provider = class _Provider {
5601
6470
  */
5602
6471
  async estimatePredicatesAndGasPrice(transactionRequest, blockHorizon) {
5603
6472
  const shouldEstimatePredicates = transactionRequest.inputs.some(
5604
- (input) => isPredicate(input) && bn17(input.predicateGasUsed).isZero()
6473
+ (input) => isPredicate(input) && bn18(input.predicateGasUsed).isZero()
5605
6474
  );
5606
6475
  if (!shouldEstimatePredicates) {
5607
6476
  const gasPrice2 = await this.estimateGasPrice(blockHorizon);
@@ -5612,13 +6481,13 @@ var Provider = class _Provider {
5612
6481
  estimatePredicates
5613
6482
  } = await this.operations.estimatePredicatesAndGasPrice({
5614
6483
  blockHorizon: String(blockHorizon),
5615
- encodedTransaction: hexlify18(transactionRequest.toTransactionBytes())
6484
+ encodedTransaction: hexlify19(transactionRequest.toTransactionBytes())
5616
6485
  });
5617
6486
  transactionRequest = this.parseEstimatePredicatesResponse(
5618
6487
  transactionRequest,
5619
6488
  estimatePredicates
5620
6489
  );
5621
- return { transactionRequest, gasPrice: bn17(gasPrice) };
6490
+ return { transactionRequest, gasPrice: bn18(gasPrice) };
5622
6491
  }
5623
6492
  /**
5624
6493
  * Will dryRun a transaction and check for missing dependencies.
@@ -5650,7 +6519,7 @@ var Provider = class _Provider {
5650
6519
  const {
5651
6520
  dryRun: [{ receipts: serializedReceipts, status }]
5652
6521
  } = await this.operations.dryRun({
5653
- encodedTransactions: [hexlify18(transactionRequest.toTransactionBytes())],
6522
+ encodedTransactions: [hexlify19(transactionRequest.toTransactionBytes())],
5654
6523
  utxoValidation: false,
5655
6524
  gasPrice: gasPrice.toString()
5656
6525
  });
@@ -5705,7 +6574,7 @@ var Provider = class _Provider {
5705
6574
  const serializedTransactionsMap = /* @__PURE__ */ new Map();
5706
6575
  allRequests.forEach((req, index) => {
5707
6576
  if (isTransactionTypeScript(req)) {
5708
- serializedTransactionsMap.set(index, hexlify18(req.toTransactionBytes()));
6577
+ serializedTransactionsMap.set(index, hexlify19(req.toTransactionBytes()));
5709
6578
  }
5710
6579
  });
5711
6580
  let transactionsToProcess = Array.from(serializedTransactionsMap.keys());
@@ -5741,7 +6610,7 @@ var Provider = class _Provider {
5741
6610
  transactionRequest: request
5742
6611
  });
5743
6612
  request.maxFee = maxFee;
5744
- serializedTransactionsMap.set(requestIdx, hexlify18(request.toTransactionBytes()));
6613
+ serializedTransactionsMap.set(requestIdx, hexlify19(request.toTransactionBytes()));
5745
6614
  nextRoundTransactions.push(requestIdx);
5746
6615
  }
5747
6616
  }
@@ -5762,7 +6631,7 @@ var Provider = class _Provider {
5762
6631
  if (estimateTxDependencies) {
5763
6632
  return this.estimateMultipleTxDependencies(transactionRequests);
5764
6633
  }
5765
- const encodedTransactions = transactionRequests.map((tx) => hexlify18(tx.toTransactionBytes()));
6634
+ const encodedTransactions = transactionRequests.map((tx) => hexlify19(tx.toTransactionBytes()));
5766
6635
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
5767
6636
  encodedTransactions,
5768
6637
  utxoValidation: utxoValidation || false
@@ -5785,7 +6654,9 @@ var Provider = class _Provider {
5785
6654
  }
5786
6655
  const chainInfo = _Provider.chainInfoCache[this.urlWithoutAuth];
5787
6656
  const {
5788
- consensusParameters: { version: previous }
6657
+ latestBlock: {
6658
+ header: { consensusParametersVersion: previous }
6659
+ }
5789
6660
  } = chainInfo;
5790
6661
  const {
5791
6662
  chain: {
@@ -5810,16 +6681,16 @@ var Provider = class _Provider {
5810
6681
  const chainInfo = await this.getChain();
5811
6682
  const { gasPriceFactor, maxGasPerTx } = await this.getGasConfig();
5812
6683
  const minGas = transactionRequest.calculateMinGas(chainInfo);
5813
- if (!isDefined2(gasPrice)) {
6684
+ if (!isDefined3(gasPrice)) {
5814
6685
  gasPrice = await this.estimateGasPrice(10);
5815
6686
  }
5816
6687
  const minFee = calculateGasFee({
5817
- gasPrice: bn17(gasPrice),
6688
+ gasPrice: bn18(gasPrice),
5818
6689
  gas: minGas,
5819
6690
  priceFactor: gasPriceFactor,
5820
6691
  tip: transactionRequest.tip
5821
6692
  }).add(1);
5822
- let gasLimit = bn17(0);
6693
+ let gasLimit = bn18(0);
5823
6694
  if (isTransactionTypeScript(transactionRequest)) {
5824
6695
  gasLimit = transactionRequest.gasLimit;
5825
6696
  if (transactionRequest.gasLimit.eq(0)) {
@@ -5832,7 +6703,7 @@ var Provider = class _Provider {
5832
6703
  }
5833
6704
  const maxGas = transactionRequest.calculateMaxGas(chainInfo, minGas);
5834
6705
  const maxFee = calculateGasFee({
5835
- gasPrice: bn17(gasPrice),
6706
+ gasPrice: bn18(gasPrice),
5836
6707
  gas: maxGas,
5837
6708
  priceFactor: gasPriceFactor,
5838
6709
  tip: transactionRequest.tip
@@ -5862,7 +6733,7 @@ var Provider = class _Provider {
5862
6733
  if (estimateTxDependencies) {
5863
6734
  return this.estimateTxDependencies(transactionRequest);
5864
6735
  }
5865
- const encodedTransactions = [hexlify18(transactionRequest.toTransactionBytes())];
6736
+ const encodedTransactions = [hexlify19(transactionRequest.toTransactionBytes())];
5866
6737
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
5867
6738
  encodedTransactions,
5868
6739
  utxoValidation: true
@@ -5885,13 +6756,16 @@ var Provider = class _Provider {
5885
6756
  * @param transactionCostParams - The transaction cost parameters (optional).
5886
6757
  *
5887
6758
  * @returns A promise that resolves to the transaction cost object.
6759
+ *
6760
+ * @deprecated Use provider.assembleTx instead
6761
+ * Check the migration guide https://docs.fuel.network/guide/assembling-transactions/migration-guide.html for more information.
5888
6762
  */
5889
6763
  async getTransactionCost(transactionRequestLike, { signatureCallback, gasPrice: gasPriceParam } = {}) {
5890
6764
  const txRequestClone = clone8(transactionRequestify(transactionRequestLike));
5891
6765
  const updateMaxFee = txRequestClone.maxFee.eq(0);
5892
6766
  const isScriptTransaction = isTransactionTypeScript(txRequestClone);
5893
6767
  if (isScriptTransaction) {
5894
- txRequestClone.gasLimit = bn17(0);
6768
+ txRequestClone.gasLimit = bn18(0);
5895
6769
  }
5896
6770
  const signedRequest = clone8(txRequestClone);
5897
6771
  let addedSignatures = 0;
@@ -5918,7 +6792,7 @@ var Provider = class _Provider {
5918
6792
  let dryRunStatus;
5919
6793
  let missingContractIds = [];
5920
6794
  let outputVariables = 0;
5921
- let gasUsed = bn17(0);
6795
+ let gasUsed = bn18(0);
5922
6796
  txRequestClone.maxFee = maxFee;
5923
6797
  if (isScriptTransaction) {
5924
6798
  txRequestClone.gasLimit = gasLimit;
@@ -5927,11 +6801,11 @@ var Provider = class _Provider {
5927
6801
  }
5928
6802
  ({ rawReceipts, receipts, missingContractIds, outputVariables, dryRunStatus } = await this.estimateTxDependencies(txRequestClone, { gasPrice }));
5929
6803
  if (dryRunStatus && "reason" in dryRunStatus) {
5930
- throw this.extractDryRunError(txRequestClone, receipts, dryRunStatus);
6804
+ throw this.extractDryRunError(txRequestClone, receipts, dryRunStatus.reason);
5931
6805
  }
5932
6806
  const { maxGasPerTx } = await this.getGasConfig();
5933
6807
  const pristineGasUsed = getGasUsedFromReceipts(receipts);
5934
- gasUsed = bn17(pristineGasUsed.muln(GAS_USED_MODIFIER)).max(maxGasPerTx.sub(minGas));
6808
+ gasUsed = bn18(pristineGasUsed.muln(GAS_USED_MODIFIER)).max(maxGasPerTx.sub(minGas));
5935
6809
  txRequestClone.gasLimit = gasUsed;
5936
6810
  ({ maxFee, maxGas, minFee, minGas } = await this.estimateTxGasAndFee({
5937
6811
  transactionRequest: txRequestClone,
@@ -5960,6 +6834,102 @@ var Provider = class _Provider {
5960
6834
  transactionSummary
5961
6835
  };
5962
6836
  }
6837
+ /**
6838
+ * Assembles a transaction by completely estimating and funding it.
6839
+ *
6840
+ * @param params - Parameters used to assemble the transaction.
6841
+ *
6842
+ * @returns The assembled transaction request, estimated gas price, and receipts
6843
+ */
6844
+ async assembleTx(params) {
6845
+ const {
6846
+ request,
6847
+ reserveGas,
6848
+ resourcesIdsToIgnore,
6849
+ feePayerAccount,
6850
+ blockHorizon = 10,
6851
+ estimatePredicates = true,
6852
+ accountCoinQuantities = []
6853
+ } = params;
6854
+ const allAddresses = /* @__PURE__ */ new Set();
6855
+ const baseAssetId = await this.getBaseAssetId();
6856
+ let feePayerIndex = -1;
6857
+ let baseAssetChange;
6858
+ const requiredBalances = accountCoinQuantities.map((quantity, index) => {
6859
+ const { amount, assetId, account = feePayerAccount, changeOutputAccount } = quantity;
6860
+ const changeAccountAddress = changeOutputAccount ? changeOutputAccount.address.toB256() : account.address.toB256();
6861
+ allAddresses.add(account.address.toB256());
6862
+ const changePolicy = {
6863
+ change: changeAccountAddress
6864
+ };
6865
+ if (assetId === baseAssetId) {
6866
+ baseAssetChange = changePolicy.change;
6867
+ }
6868
+ if (account.address.equals(feePayerAccount.address)) {
6869
+ feePayerIndex = index;
6870
+ }
6871
+ const requiredBalance = {
6872
+ account: resolveAccountForAssembleTxParams(account),
6873
+ amount: bn18(amount).toString(10),
6874
+ assetId,
6875
+ changePolicy
6876
+ };
6877
+ return requiredBalance;
6878
+ });
6879
+ if (feePayerIndex === -1) {
6880
+ allAddresses.add(feePayerAccount.address.toB256());
6881
+ const newLength = requiredBalances.push({
6882
+ account: resolveAccountForAssembleTxParams(feePayerAccount),
6883
+ amount: bn18(0).toString(10),
6884
+ // Since the correct fee amount cannot be determined yet, we can use 0
6885
+ assetId: baseAssetId,
6886
+ changePolicy: {
6887
+ change: baseAssetChange || feePayerAccount.address.toB256()
6888
+ }
6889
+ });
6890
+ feePayerIndex = newLength - 1;
6891
+ }
6892
+ const excludeInput = await this.adjustResourcesToIgnoreForAddresses(
6893
+ Array.from(allAddresses),
6894
+ resourcesIdsToIgnore
6895
+ );
6896
+ const {
6897
+ assembleTx: { status, transaction: gqlTransaction, gasPrice }
6898
+ } = await this.operations.assembleTx({
6899
+ tx: hexlify19(request.toTransactionBytes()),
6900
+ blockHorizon: String(blockHorizon),
6901
+ feeAddressIndex: String(feePayerIndex),
6902
+ requiredBalances,
6903
+ estimatePredicates,
6904
+ excludeInput,
6905
+ reserveGas: reserveGas ? reserveGas.toString(10) : void 0
6906
+ });
6907
+ if (status.type === "DryRunFailureStatus") {
6908
+ const parsedReceipts = status.receipts.map(deserializeReceipt);
6909
+ throw this.extractDryRunError(request, parsedReceipts, status.reason);
6910
+ }
6911
+ request.witnesses = gqlTransaction.witnesses || request.witnesses;
6912
+ request.inputs = gqlTransaction.inputs?.map(deserializeInput) || request.inputs;
6913
+ request.outputs = gqlTransaction.outputs?.map(deserializeOutput) || request.outputs;
6914
+ if (gqlTransaction.policies?.maxFee) {
6915
+ request.maxFee = bn18(gqlTransaction.policies.maxFee);
6916
+ }
6917
+ if (gqlTransaction.scriptGasLimit) {
6918
+ request.gasLimit = bn18(gqlTransaction.scriptGasLimit);
6919
+ }
6920
+ const rawReceipts = status.receipts;
6921
+ const chainId = await this.getChainId();
6922
+ request.updateState(chainId, "funded", {
6923
+ gasPrice: gasPrice.toString(),
6924
+ receipts: rawReceipts
6925
+ });
6926
+ return {
6927
+ assembledRequest: request,
6928
+ gasPrice: bn18(gasPrice),
6929
+ receipts: status.receipts.map(deserializeReceipt),
6930
+ rawReceipts
6931
+ };
6932
+ }
5963
6933
  /**
5964
6934
  * Returns coins for the given owner.
5965
6935
  *
@@ -5978,15 +6948,15 @@ var Provider = class _Provider {
5978
6948
  paginationLimit: RESOURCES_PAGE_SIZE_LIMIT,
5979
6949
  inputArgs: paginationArgs
5980
6950
  }),
5981
- filter: { owner: ownerAddress.toB256(), assetId: assetId && hexlify18(assetId) }
6951
+ filter: { owner: ownerAddress.toB256(), assetId: assetId && hexlify19(assetId) }
5982
6952
  });
5983
6953
  const coins = edges.map(({ node }) => ({
5984
6954
  id: node.utxoId,
5985
6955
  assetId: node.assetId,
5986
- amount: bn17(node.amount),
6956
+ amount: bn18(node.amount),
5987
6957
  owner: ownerAddress,
5988
- blockCreated: bn17(node.blockCreated),
5989
- txCreatedIdx: bn17(node.txCreatedIdx)
6958
+ blockCreated: bn18(node.blockCreated),
6959
+ txCreatedIdx: bn18(node.txCreatedIdx)
5990
6960
  }));
5991
6961
  return {
5992
6962
  coins,
@@ -5998,47 +6968,32 @@ var Provider = class _Provider {
5998
6968
  *
5999
6969
  * @param owner - The address to get resources for.
6000
6970
  * @param quantities - The coin quantities to get.
6001
- * @param excludedIds - IDs of excluded resources from the selection (optional).
6971
+ * @param resourcesIdsToIgnore - IDs of excluded resources from the selection (optional).
6002
6972
  * @returns A promise that resolves to the resources.
6003
6973
  */
6004
- async getResourcesToSpend(owner, quantities, excludedIds) {
6974
+ async getResourcesToSpend(owner, quantities, resourcesIdsToIgnore) {
6005
6975
  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
- }
6976
+ const excludedIds = await this.adjustResourcesToIgnoreForAddresses(
6977
+ [ownerAddress.b256Address],
6978
+ resourcesIdsToIgnore
6979
+ );
6025
6980
  const coinsQuery = {
6026
6981
  owner: ownerAddress.toB256(),
6027
6982
  queryPerAsset: quantities.map(coinQuantityfy).map(({ assetId, amount, max: maxPerAsset }) => ({
6028
- assetId: hexlify18(assetId),
6029
- amount: (amount.eqn(0) ? bn17(1) : amount).toString(10),
6983
+ assetId: hexlify19(assetId),
6984
+ amount: (amount.eqn(0) ? bn18(1) : amount).toString(10),
6030
6985
  max: maxPerAsset ? maxPerAsset.toString(10) : void 0
6031
6986
  })),
6032
- excludedIds: idsToExclude
6987
+ excludedIds
6033
6988
  };
6034
6989
  const result = await this.operations.getCoinsToSpend(coinsQuery);
6035
6990
  const coins = result.coinsToSpend.flat().map((coin) => {
6036
6991
  switch (coin.type) {
6037
6992
  case "MessageCoin":
6038
6993
  return {
6039
- amount: bn17(coin.amount),
6994
+ amount: bn18(coin.amount),
6040
6995
  assetId: coin.assetId,
6041
- daHeight: bn17(coin.daHeight),
6996
+ daHeight: bn18(coin.daHeight),
6042
6997
  sender: new Address3(coin.sender),
6043
6998
  recipient: new Address3(coin.recipient),
6044
6999
  nonce: coin.nonce
@@ -6046,11 +7001,11 @@ var Provider = class _Provider {
6046
7001
  case "Coin":
6047
7002
  return {
6048
7003
  id: coin.utxoId,
6049
- amount: bn17(coin.amount),
7004
+ amount: bn18(coin.amount),
6050
7005
  assetId: coin.assetId,
6051
7006
  owner: ownerAddress,
6052
- blockCreated: bn17(coin.blockCreated),
6053
- txCreatedIdx: bn17(coin.txCreatedIdx)
7007
+ blockCreated: bn18(coin.blockCreated),
7008
+ txCreatedIdx: bn18(coin.txCreatedIdx)
6054
7009
  };
6055
7010
  default:
6056
7011
  return null;
@@ -6088,7 +7043,7 @@ var Provider = class _Provider {
6088
7043
  block = latestBlock;
6089
7044
  } else {
6090
7045
  const isblockId = typeof idOrHeight === "string" && isB256(idOrHeight);
6091
- const variables = isblockId ? { blockId: idOrHeight } : { height: bn17(idOrHeight).toString(10) };
7046
+ const variables = isblockId ? { blockId: idOrHeight } : { height: bn18(idOrHeight).toString(10) };
6092
7047
  const response = await this.operations.getBlock(variables);
6093
7048
  block = response.block;
6094
7049
  }
@@ -6098,11 +7053,11 @@ var Provider = class _Provider {
6098
7053
  const { header, height, id, transactions } = block;
6099
7054
  return {
6100
7055
  id,
6101
- height: bn17(height),
7056
+ height: bn18(height),
6102
7057
  time: header.time,
6103
7058
  header: {
6104
7059
  applicationHash: header.applicationHash,
6105
- daHeight: bn17(header.daHeight),
7060
+ daHeight: bn18(header.daHeight),
6106
7061
  eventInboxRoot: header.eventInboxRoot,
6107
7062
  messageOutboxRoot: header.messageOutboxRoot,
6108
7063
  prevRoot: header.prevRoot,
@@ -6130,11 +7085,11 @@ var Provider = class _Provider {
6130
7085
  });
6131
7086
  const blocks = edges.map(({ node: block }) => ({
6132
7087
  id: block.id,
6133
- height: bn17(block.height),
7088
+ height: bn18(block.height),
6134
7089
  time: block.header.time,
6135
7090
  header: {
6136
7091
  applicationHash: block.header.applicationHash,
6137
- daHeight: bn17(block.header.daHeight),
7092
+ daHeight: bn18(block.header.daHeight),
6138
7093
  eventInboxRoot: block.header.eventInboxRoot,
6139
7094
  messageOutboxRoot: block.header.messageOutboxRoot,
6140
7095
  prevRoot: block.header.prevRoot,
@@ -6155,13 +7110,13 @@ var Provider = class _Provider {
6155
7110
  async getBlockWithTransactions(idOrHeight) {
6156
7111
  let variables;
6157
7112
  if (typeof idOrHeight === "number") {
6158
- variables = { blockHeight: bn17(idOrHeight).toString(10) };
7113
+ variables = { blockHeight: bn18(idOrHeight).toString(10) };
6159
7114
  } else if (idOrHeight === "latest") {
6160
7115
  variables = { blockHeight: (await this.getBlockNumber()).toString() };
6161
7116
  } else if (typeof idOrHeight === "string" && isB256(idOrHeight)) {
6162
7117
  variables = { blockId: idOrHeight };
6163
7118
  } else {
6164
- variables = { blockHeight: bn17(idOrHeight).toString() };
7119
+ variables = { blockHeight: bn18(idOrHeight).toString() };
6165
7120
  }
6166
7121
  const { block } = await this.operations.getBlockWithTransactions(variables);
6167
7122
  if (!block) {
@@ -6169,11 +7124,11 @@ var Provider = class _Provider {
6169
7124
  }
6170
7125
  return {
6171
7126
  id: block.id,
6172
- height: bn17(block.height, 10),
7127
+ height: bn18(block.height, 10),
6173
7128
  time: block.header.time,
6174
7129
  header: {
6175
7130
  applicationHash: block.header.applicationHash,
6176
- daHeight: bn17(block.header.daHeight),
7131
+ daHeight: bn18(block.header.daHeight),
6177
7132
  eventInboxRoot: block.header.eventInboxRoot,
6178
7133
  messageOutboxRoot: block.header.messageOutboxRoot,
6179
7134
  prevRoot: block.header.prevRoot,
@@ -6183,7 +7138,7 @@ var Provider = class _Provider {
6183
7138
  },
6184
7139
  transactionIds: block.transactions.map((tx) => tx.id),
6185
7140
  transactions: block.transactions.map(
6186
- (tx) => new TransactionCoder5().decode(arrayify13(tx.rawPayload), 0)?.[0]
7141
+ (tx) => new TransactionCoder6().decode(arrayify13(tx.rawPayload), 0)?.[0]
6187
7142
  )
6188
7143
  };
6189
7144
  }
@@ -6199,12 +7154,12 @@ var Provider = class _Provider {
6199
7154
  return null;
6200
7155
  }
6201
7156
  try {
6202
- return new TransactionCoder5().decode(
7157
+ return new TransactionCoder6().decode(
6203
7158
  arrayify13(transaction.rawPayload),
6204
7159
  0
6205
7160
  )?.[0];
6206
7161
  } catch (error) {
6207
- if (error instanceof FuelError19 && error.code === ErrorCode16.UNSUPPORTED_TRANSACTION_TYPE) {
7162
+ if (error instanceof FuelError20 && error.code === ErrorCode17.UNSUPPORTED_TRANSACTION_TYPE) {
6208
7163
  console.warn("Unsupported transaction type encountered");
6209
7164
  return null;
6210
7165
  }
@@ -6225,12 +7180,12 @@ var Provider = class _Provider {
6225
7180
  paginationLimit: TRANSACTIONS_PAGE_SIZE_LIMIT
6226
7181
  })
6227
7182
  });
6228
- const coder = new TransactionCoder5();
7183
+ const coder = new TransactionCoder6();
6229
7184
  const transactions = edges.map(({ node: { rawPayload } }) => {
6230
7185
  try {
6231
7186
  return coder.decode(arrayify13(rawPayload), 0)[0];
6232
7187
  } catch (error) {
6233
- if (error instanceof FuelError19 && error.code === ErrorCode16.UNSUPPORTED_TRANSACTION_TYPE) {
7188
+ if (error instanceof FuelError20 && error.code === ErrorCode17.UNSUPPORTED_TRANSACTION_TYPE) {
6234
7189
  console.warn("Unsupported transaction type encountered");
6235
7190
  return null;
6236
7191
  }
@@ -6277,9 +7232,9 @@ var Provider = class _Provider {
6277
7232
  async getContractBalance(contractId, assetId) {
6278
7233
  const { contractBalance } = await this.operations.getContractBalance({
6279
7234
  contract: new Address3(contractId).toB256(),
6280
- asset: hexlify18(assetId)
7235
+ asset: hexlify19(assetId)
6281
7236
  });
6282
- return bn17(contractBalance.amount, 10);
7237
+ return bn18(contractBalance.amount, 10);
6283
7238
  }
6284
7239
  /**
6285
7240
  * Returns the balance for the given owner for the given asset ID.
@@ -6291,9 +7246,9 @@ var Provider = class _Provider {
6291
7246
  async getBalance(owner, assetId) {
6292
7247
  const { balance } = await this.operations.getBalanceV2({
6293
7248
  owner: new Address3(owner).toB256(),
6294
- assetId: hexlify18(assetId)
7249
+ assetId: hexlify19(assetId)
6295
7250
  });
6296
- return bn17(balance.amountU128, 10);
7251
+ return bn18(balance.amountU128, 10);
6297
7252
  }
6298
7253
  /**
6299
7254
  * Returns balances for the given owner.
@@ -6320,7 +7275,7 @@ var Provider = class _Provider {
6320
7275
  });
6321
7276
  const balances = edges.map(({ node }) => ({
6322
7277
  assetId: node.assetId,
6323
- amount: bn17(node.amountU128)
7278
+ amount: bn18(node.amountU128)
6324
7279
  }));
6325
7280
  return {
6326
7281
  balances,
@@ -6349,15 +7304,15 @@ var Provider = class _Provider {
6349
7304
  sender: node.sender,
6350
7305
  recipient: node.recipient,
6351
7306
  nonce: node.nonce,
6352
- amount: bn17(node.amount),
7307
+ amount: bn18(node.amount),
6353
7308
  data: node.data
6354
7309
  }),
6355
7310
  sender: new Address3(node.sender),
6356
7311
  recipient: new Address3(node.recipient),
6357
7312
  nonce: node.nonce,
6358
- amount: bn17(node.amount),
7313
+ amount: bn18(node.amount),
6359
7314
  data: InputMessageCoder2.decodeData(node.data),
6360
- daHeight: bn17(node.daHeight)
7315
+ daHeight: bn18(node.daHeight)
6361
7316
  }));
6362
7317
  return {
6363
7318
  messages,
@@ -6379,8 +7334,8 @@ var Provider = class _Provider {
6379
7334
  nonce
6380
7335
  };
6381
7336
  if (commitBlockId && commitBlockHeight) {
6382
- throw new FuelError19(
6383
- ErrorCode16.INVALID_INPUT_PARAMETERS,
7337
+ throw new FuelError20(
7338
+ ErrorCode17.INVALID_INPUT_PARAMETERS,
6384
7339
  "commitBlockId and commitBlockHeight cannot be used together"
6385
7340
  );
6386
7341
  }
@@ -6411,19 +7366,19 @@ var Provider = class _Provider {
6411
7366
  } = result.messageProof;
6412
7367
  return {
6413
7368
  messageProof: {
6414
- proofIndex: bn17(messageProof.proofIndex),
7369
+ proofIndex: bn18(messageProof.proofIndex),
6415
7370
  proofSet: messageProof.proofSet
6416
7371
  },
6417
7372
  blockProof: {
6418
- proofIndex: bn17(blockProof.proofIndex),
7373
+ proofIndex: bn18(blockProof.proofIndex),
6419
7374
  proofSet: blockProof.proofSet
6420
7375
  },
6421
7376
  messageBlockHeader: {
6422
7377
  id: messageBlockHeader.id,
6423
- daHeight: bn17(messageBlockHeader.daHeight),
7378
+ daHeight: bn18(messageBlockHeader.daHeight),
6424
7379
  transactionsCount: Number(messageBlockHeader.transactionsCount),
6425
7380
  transactionsRoot: messageBlockHeader.transactionsRoot,
6426
- height: bn17(messageBlockHeader.height),
7381
+ height: bn18(messageBlockHeader.height),
6427
7382
  prevRoot: messageBlockHeader.prevRoot,
6428
7383
  time: messageBlockHeader.time,
6429
7384
  applicationHash: messageBlockHeader.applicationHash,
@@ -6435,10 +7390,10 @@ var Provider = class _Provider {
6435
7390
  },
6436
7391
  commitBlockHeader: {
6437
7392
  id: commitBlockHeader.id,
6438
- daHeight: bn17(commitBlockHeader.daHeight),
7393
+ daHeight: bn18(commitBlockHeader.daHeight),
6439
7394
  transactionsCount: Number(commitBlockHeader.transactionsCount),
6440
7395
  transactionsRoot: commitBlockHeader.transactionsRoot,
6441
- height: bn17(commitBlockHeader.height),
7396
+ height: bn18(commitBlockHeader.height),
6442
7397
  prevRoot: commitBlockHeader.prevRoot,
6443
7398
  time: commitBlockHeader.time,
6444
7399
  applicationHash: commitBlockHeader.applicationHash,
@@ -6451,7 +7406,7 @@ var Provider = class _Provider {
6451
7406
  sender: new Address3(sender),
6452
7407
  recipient: new Address3(recipient),
6453
7408
  nonce,
6454
- amount: bn17(amount),
7409
+ amount: bn18(amount),
6455
7410
  data
6456
7411
  };
6457
7412
  }
@@ -6462,7 +7417,7 @@ var Provider = class _Provider {
6462
7417
  */
6463
7418
  async getLatestGasPrice() {
6464
7419
  const { latestGasPrice } = await this.operations.getLatestGasPrice();
6465
- return bn17(latestGasPrice.gasPrice);
7420
+ return bn18(latestGasPrice.gasPrice);
6466
7421
  }
6467
7422
  /**
6468
7423
  * Returns the estimate gas price for the given block horizon.
@@ -6474,7 +7429,7 @@ var Provider = class _Provider {
6474
7429
  const { estimateGasPrice } = await this.operations.estimateGasPrice({
6475
7430
  blockHorizon: String(blockHorizon)
6476
7431
  });
6477
- return bn17(estimateGasPrice.gasPrice);
7432
+ return bn18(estimateGasPrice.gasPrice);
6478
7433
  }
6479
7434
  /**
6480
7435
  * Returns Message Proof for given transaction id and the message id from MessageOut receipt.
@@ -6495,10 +7450,10 @@ var Provider = class _Provider {
6495
7450
  */
6496
7451
  async produceBlocks(amount, startTime) {
6497
7452
  const { produceBlocks: latestBlockHeight } = await this.operations.produceBlocks({
6498
- blocksToProduce: bn17(amount).toString(10),
7453
+ blocksToProduce: bn18(amount).toString(10),
6499
7454
  startTimestamp: startTime ? DateTime2.fromUnixMilliseconds(startTime).toTai64() : void 0
6500
7455
  });
6501
- return bn17(latestBlockHeight);
7456
+ return bn18(latestBlockHeight);
6502
7457
  }
6503
7458
  /**
6504
7459
  * Check if the given ID is an account.
@@ -6566,15 +7521,15 @@ var Provider = class _Provider {
6566
7521
  sender: rawMessage.sender,
6567
7522
  recipient: rawMessage.recipient,
6568
7523
  nonce,
6569
- amount: bn17(rawMessage.amount),
7524
+ amount: bn18(rawMessage.amount),
6570
7525
  data: rawMessage.data
6571
7526
  }),
6572
7527
  sender: new Address3(rawMessage.sender),
6573
7528
  recipient: new Address3(rawMessage.recipient),
6574
7529
  nonce,
6575
- amount: bn17(rawMessage.amount),
7530
+ amount: bn18(rawMessage.amount),
6576
7531
  data: InputMessageCoder2.decodeData(rawMessage.data),
6577
- daHeight: bn17(rawMessage.daHeight)
7532
+ daHeight: bn18(rawMessage.daHeight)
6578
7533
  };
6579
7534
  return message;
6580
7535
  }
@@ -6596,11 +7551,10 @@ var Provider = class _Provider {
6596
7551
  /**
6597
7552
  * @hidden
6598
7553
  */
6599
- extractDryRunError(transactionRequest, receipts, dryRunStatus) {
6600
- const status = dryRunStatus;
7554
+ extractDryRunError(transactionRequest, receipts, reason) {
6601
7555
  let logs = [];
6602
7556
  let groupedLogs = {};
6603
- if (transactionRequest.abis) {
7557
+ if (transactionRequest.type === TransactionType11.Script && transactionRequest.abis) {
6604
7558
  ({ logs, groupedLogs } = getAllDecodedLogs({
6605
7559
  receipts,
6606
7560
  mainAbi: transactionRequest.abis.main,
@@ -6611,7 +7565,7 @@ var Provider = class _Provider {
6611
7565
  logs,
6612
7566
  groupedLogs,
6613
7567
  receipts,
6614
- statusReason: status.reason
7568
+ statusReason: reason
6615
7569
  });
6616
7570
  }
6617
7571
  /**
@@ -6631,29 +7585,68 @@ var Provider = class _Provider {
6631
7585
  parseEstimatePredicatesResponse(transactionRequest, { inputs }) {
6632
7586
  if (inputs) {
6633
7587
  inputs.forEach((input, i) => {
6634
- if (input && "predicateGasUsed" in input && bn17(input.predicateGasUsed).gt(0)) {
7588
+ if (input && "predicateGasUsed" in input && bn18(input.predicateGasUsed).gt(0)) {
6635
7589
  transactionRequest.inputs[i].predicateGasUsed = input.predicateGasUsed;
6636
7590
  }
6637
7591
  });
6638
7592
  }
6639
7593
  return transactionRequest;
6640
7594
  }
7595
+ /**
7596
+ * @hidden
7597
+ *
7598
+ * This helper adjusts the resources to be excluded for a given set of addresses.
7599
+ * Supporting multiple addresses is important because of the `assembleTx` method,
7600
+ * which may be invoked with different addresses. It handles both messages and UTXOs,
7601
+ * ensuring the total number of inputs does not exceed the maximum allowed by the chain's
7602
+ * consensus parameters. The resources specified in the `resourcesIdsToIgnore` parameter have priority
7603
+ * over those retrieved from the cache.
7604
+ */
7605
+ async adjustResourcesToIgnoreForAddresses(addresses, resourcesIdsToIgnore) {
7606
+ const final = {
7607
+ messages: resourcesIdsToIgnore?.messages?.map((nonce) => hexlify19(nonce)) || [],
7608
+ utxos: resourcesIdsToIgnore?.utxos?.map((id) => hexlify19(id)) || []
7609
+ };
7610
+ if (this.cache) {
7611
+ const cache2 = this.cache;
7612
+ const allCached = addresses.map((address) => cache2.getActiveData(address));
7613
+ const {
7614
+ consensusParameters: {
7615
+ txParameters: { maxInputs: maxInputsBn }
7616
+ }
7617
+ } = await this.getChain();
7618
+ const maxInputs = maxInputsBn.toNumber();
7619
+ for (let i = 0; i < allCached.length; i++) {
7620
+ let total = final.utxos.length + final.messages.length;
7621
+ if (total >= maxInputs) {
7622
+ break;
7623
+ }
7624
+ final.utxos = [...final.utxos, ...allCached[i].utxos.slice(0, maxInputs - total)];
7625
+ total = final.utxos.length + final.messages.length;
7626
+ if (total >= maxInputs) {
7627
+ break;
7628
+ }
7629
+ final.messages = [...final.messages, ...allCached[i].messages.slice(0, maxInputs - total)];
7630
+ }
7631
+ }
7632
+ return final;
7633
+ }
6641
7634
  };
6642
7635
 
6643
7636
  // 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";
7637
+ import { ErrorCode as ErrorCode18, FuelError as FuelError21 } from "@fuel-ts/errors";
7638
+ import { bn as bn19 } from "@fuel-ts/math";
7639
+ import { TransactionCoder as TransactionCoder7 } from "@fuel-ts/transactions";
6647
7640
  import { arrayify as arrayify14 } from "@fuel-ts/utils";
6648
7641
 
6649
7642
  // 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";
7643
+ import { bn as bn20 } from "@fuel-ts/math";
7644
+ import { TransactionCoder as TransactionCoder8 } from "@fuel-ts/transactions";
6652
7645
  import { arrayify as arrayify15 } from "@fuel-ts/utils";
6653
7646
 
6654
7647
  // src/test-utils/test-asset-id.ts
6655
7648
  import { randomBytes as randomBytes4 } from "@fuel-ts/crypto";
6656
- import { hexlify as hexlify19 } from "@fuel-ts/utils";
7649
+ import { hexlify as hexlify20 } from "@fuel-ts/utils";
6657
7650
  var TestAssetId = class _TestAssetId {
6658
7651
  constructor(value) {
6659
7652
  this.value = value;
@@ -6670,7 +7663,7 @@ var TestAssetId = class _TestAssetId {
6670
7663
  static random(count = 1) {
6671
7664
  const assetIds = [];
6672
7665
  for (let i = 0; i < count; i++) {
6673
- assetIds.push(new _TestAssetId(hexlify19(randomBytes4(32))));
7666
+ assetIds.push(new _TestAssetId(hexlify20(randomBytes4(32))));
6674
7667
  }
6675
7668
  return assetIds;
6676
7669
  }
@@ -6678,38 +7671,47 @@ var TestAssetId = class _TestAssetId {
6678
7671
 
6679
7672
  // src/test-utils/wallet-config.ts
6680
7673
  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";
7674
+ import { FuelError as FuelError27 } from "@fuel-ts/errors";
7675
+ import { bn as bn23 } from "@fuel-ts/math";
7676
+ import { defaultSnapshotConfigs as defaultSnapshotConfigs2, hexlify as hexlify26 } from "@fuel-ts/utils";
6684
7677
 
6685
7678
  // src/wallet/base-wallet-unlocked.ts
6686
7679
  import { hashMessage } from "@fuel-ts/hasher";
6687
- import { hexlify as hexlify22 } from "@fuel-ts/utils";
7680
+ import { hexlify as hexlify23 } from "@fuel-ts/utils";
6688
7681
 
6689
7682
  // src/account.ts
6690
7683
  import { UTXO_ID_LEN as UTXO_ID_LEN3 } from "@fuel-ts/abi-coder";
6691
7684
  import { Address as Address5 } from "@fuel-ts/address";
6692
7685
  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";
7686
+ import { ErrorCode as ErrorCode19, FuelError as FuelError22 } from "@fuel-ts/errors";
7687
+ import { bn as bn21 } from "@fuel-ts/math";
7688
+ import { InputType as InputType8, OutputType as OutputType9 } from "@fuel-ts/transactions";
7689
+ import { arrayify as arrayify17, hexlify as hexlify21, isDefined as isDefined4 } from "@fuel-ts/utils";
6697
7690
  import { clone as clone9 } from "ramda";
6698
7691
 
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");
7692
+ // src/providers/utils/transaction-response-serialization.ts
7693
+ var deserializeTransactionResponseJson = /* @__PURE__ */ __name((json) => {
7694
+ const {
7695
+ id,
7696
+ abis,
7697
+ status,
7698
+ providerUrl,
7699
+ requestJson,
7700
+ providerCache,
7701
+ gqlTransaction,
7702
+ preConfirmationStatus
7703
+ } = json;
7704
+ const provider = new Provider(providerUrl, { cache: providerCache });
7705
+ const { chainId } = providerCache.chain.consensusParameters;
7706
+ const response = new TransactionResponse(id, provider, Number(chainId), abis);
7707
+ if (requestJson) {
7708
+ response.request = transactionRequestify(JSON.parse(requestJson));
7709
+ }
7710
+ response.status = status;
7711
+ response.gqlTransaction = gqlTransaction;
7712
+ response.preConfirmationStatus = preConfirmationStatus;
7713
+ return response;
7714
+ }, "deserializeTransactionResponseJson");
6713
7715
 
6714
7716
  // src/types.ts
6715
7717
  var AbstractAccount = class {
@@ -6758,6 +7760,18 @@ var assembleTransferToContractScript = /* @__PURE__ */ __name(async (transferPar
6758
7760
  return { script, scriptData };
6759
7761
  }, "assembleTransferToContractScript");
6760
7762
 
7763
+ // src/utils/split-coins-into-batches.ts
7764
+ var splitCoinsIntoBatches = /* @__PURE__ */ __name((coins, maxBatchLength) => {
7765
+ const batchesNum = Math.ceil(coins.length / maxBatchLength);
7766
+ const batches = [];
7767
+ for (let i = 0; i < batchesNum; i += 1) {
7768
+ const batchStart = i * maxBatchLength;
7769
+ const batchEnd = (i + 1) * maxBatchLength;
7770
+ batches.push(coins.slice(batchStart, batchEnd));
7771
+ }
7772
+ return batches;
7773
+ }, "splitCoinsIntoBatches");
7774
+
6761
7775
  // src/account.ts
6762
7776
  var MAX_FUNDING_ATTEMPTS = 5;
6763
7777
  var Account = class extends AbstractAccount {
@@ -6798,7 +7812,7 @@ var Account = class extends AbstractAccount {
6798
7812
  */
6799
7813
  get provider() {
6800
7814
  if (!this._provider) {
6801
- throw new FuelError21(ErrorCode18.MISSING_PROVIDER, "Provider not set");
7815
+ throw new FuelError22(ErrorCode19.MISSING_PROVIDER, "Provider not set");
6802
7816
  }
6803
7817
  return this._provider;
6804
7818
  }
@@ -6824,11 +7838,11 @@ var Account = class extends AbstractAccount {
6824
7838
  * Retrieves resources satisfying the spend query for the account.
6825
7839
  *
6826
7840
  * @param quantities - Quantities of resources to be obtained.
6827
- * @param excludedIds - IDs of resources to be excluded from the query (optional).
7841
+ * @param resourcesIdsToIgnore - IDs of resources to be excluded from the query (optional).
6828
7842
  * @returns A promise that resolves to an array of Resources.
6829
7843
  */
6830
- async getResourcesToSpend(quantities, excludedIds) {
6831
- return this.provider.getResourcesToSpend(this.address, quantities, excludedIds);
7844
+ async getResourcesToSpend(quantities, resourcesIdsToIgnore) {
7845
+ return this.provider.getResourcesToSpend(this.address, quantities, resourcesIdsToIgnore);
6832
7846
  }
6833
7847
  /**
6834
7848
  * Retrieves coins owned by the account.
@@ -6873,6 +7887,9 @@ var Account = class extends AbstractAccount {
6873
7887
  * @param request - The transaction request to fund.
6874
7888
  * @param params - The estimated transaction parameters.
6875
7889
  * @returns A promise that resolves to the funded transaction request.
7890
+ *
7891
+ * @deprecated Use provider.assembleTx instead
7892
+ * Check the migration guide https://docs.fuel.network/guide/assembling-transactions/migration-guide.html for more information.
6876
7893
  */
6877
7894
  async fund(request, params) {
6878
7895
  const {
@@ -6886,9 +7903,9 @@ var Account = class extends AbstractAccount {
6886
7903
  const chainId = await this.provider.getChainId();
6887
7904
  const fee = request.maxFee;
6888
7905
  const baseAssetId = await this.provider.getBaseAssetId();
6889
- const requiredInBaseAsset = requiredQuantities.find((quantity) => quantity.assetId === baseAssetId)?.amount || bn20(0);
7906
+ const requiredInBaseAsset = requiredQuantities.find((quantity) => quantity.assetId === baseAssetId)?.amount || bn21(0);
6890
7907
  const requiredQuantitiesWithFee = addAmountToCoinQuantities({
6891
- amount: bn20(fee),
7908
+ amount: bn21(fee),
6892
7909
  assetId: baseAssetId,
6893
7910
  coinQuantities: requiredQuantities
6894
7911
  });
@@ -6896,7 +7913,7 @@ var Account = class extends AbstractAccount {
6896
7913
  requiredQuantitiesWithFee.forEach(({ amount, assetId }) => {
6897
7914
  quantitiesDict[assetId] = {
6898
7915
  required: amount,
6899
- owned: bn20(0)
7916
+ owned: bn21(0)
6900
7917
  };
6901
7918
  });
6902
7919
  request.inputs.filter(isRequestInputResource).forEach((input) => {
@@ -6957,8 +7974,8 @@ var Account = class extends AbstractAccount {
6957
7974
  fundingAttempts += 1;
6958
7975
  }
6959
7976
  if (needsToBeFunded) {
6960
- throw new FuelError21(
6961
- ErrorCode18.INSUFFICIENT_FUNDS_OR_MAX_COINS,
7977
+ throw new FuelError22(
7978
+ ErrorCode19.INSUFFICIENT_FUNDS_OR_MAX_COINS,
6962
7979
  `The account ${this.address} does not have enough base asset funds to cover the transaction execution.`
6963
7980
  );
6964
7981
  }
@@ -6995,7 +8012,14 @@ var Account = class extends AbstractAccount {
6995
8012
  amount,
6996
8013
  assetId: assetId || await this.provider.getBaseAssetId()
6997
8014
  });
6998
- request = await this.estimateAndFundTransaction(request, txParams);
8015
+ const { gasPrice, transactionRequest } = await this.assembleTx(request);
8016
+ request = await setAndValidateGasAndFeeForAssembledTx({
8017
+ gasPrice,
8018
+ provider: this.provider,
8019
+ transactionRequest,
8020
+ setGasLimit: txParams?.gasLimit,
8021
+ setMaxFee: txParams?.maxFee
8022
+ });
6999
8023
  return request;
7000
8024
  }
7001
8025
  /**
@@ -7021,7 +8045,14 @@ var Account = class extends AbstractAccount {
7021
8045
  async batchTransfer(transferParams, txParams = {}) {
7022
8046
  let request = new ScriptTransactionRequest(txParams);
7023
8047
  request = this.addBatchTransfer(request, transferParams);
7024
- request = await this.estimateAndFundTransaction(request, txParams);
8048
+ const { gasPrice, transactionRequest } = await this.assembleTx(request);
8049
+ request = await setAndValidateGasAndFeeForAssembledTx({
8050
+ gasPrice,
8051
+ provider: this.provider,
8052
+ transactionRequest,
8053
+ setGasLimit: txParams?.gasLimit,
8054
+ setMaxFee: txParams?.maxFee
8055
+ });
7025
8056
  return this.sendTransaction(request, { estimateTxDependencies: false });
7026
8057
  }
7027
8058
  /**
@@ -7073,12 +8104,12 @@ var Account = class extends AbstractAccount {
7073
8104
  const quantities = [];
7074
8105
  const defaultAssetId = await this.provider.getBaseAssetId();
7075
8106
  const transferParams = contractTransferParams.map((transferParam) => {
7076
- const amount = bn20(transferParam.amount);
8107
+ const amount = bn21(transferParam.amount);
7077
8108
  const contractAddress = new Address5(transferParam.contractId);
7078
- const assetId = transferParam.assetId ? hexlify20(transferParam.assetId) : defaultAssetId;
8109
+ const assetId = transferParam.assetId ? hexlify21(transferParam.assetId) : defaultAssetId;
7079
8110
  if (amount.lte(0)) {
7080
- throw new FuelError21(
7081
- ErrorCode18.INVALID_TRANSFER_AMOUNT,
8111
+ throw new FuelError22(
8112
+ ErrorCode19.INVALID_TRANSFER_AMOUNT,
7082
8113
  "Transfer amount must be a positive number."
7083
8114
  );
7084
8115
  }
@@ -7093,7 +8124,14 @@ var Account = class extends AbstractAccount {
7093
8124
  const { script, scriptData } = await assembleTransferToContractScript(transferParams);
7094
8125
  request.script = script;
7095
8126
  request.scriptData = scriptData;
7096
- request = await this.estimateAndFundTransaction(request, txParams, { quantities });
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
8134
+ });
7097
8135
  return this.sendTransaction(request);
7098
8136
  }
7099
8137
  /**
@@ -7110,7 +8148,7 @@ var Account = class extends AbstractAccount {
7110
8148
  "0x".concat(recipientAddress.toHexString().substring(2).padStart(64, "0"))
7111
8149
  );
7112
8150
  const amountDataArray = arrayify17(
7113
- "0x".concat(bn20(amount).toHex().substring(2).padStart(16, "0"))
8151
+ "0x".concat(bn21(amount).toHex().substring(2).padStart(16, "0"))
7114
8152
  );
7115
8153
  const script = new Uint8Array([
7116
8154
  ...arrayify17(withdrawScript.bytes),
@@ -7120,17 +8158,145 @@ var Account = class extends AbstractAccount {
7120
8158
  const params = { script, ...txParams };
7121
8159
  const baseAssetId = await this.provider.getBaseAssetId();
7122
8160
  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
8161
+ const quantities = [{ amount: bn21(amount), assetId: baseAssetId }];
8162
+ const { gasPrice, transactionRequest } = await this.assembleTx(request, quantities);
8163
+ request = await setAndValidateGasAndFeeForAssembledTx({
8164
+ gasPrice,
8165
+ provider: this.provider,
8166
+ transactionRequest,
8167
+ setGasLimit: txParams?.gasLimit,
8168
+ setMaxFee: txParams?.maxFee
7130
8169
  });
7131
- await this.fund(request, txCost);
7132
8170
  return this.sendTransaction(request);
7133
8171
  }
8172
+ /**
8173
+ * Consolidates base asset UTXOs into fewer, larger ones.
8174
+ *
8175
+ * Retrieves a limited number of base asset coins (as defined by `Provider.RESOURCES_PAGE_SIZE_LIMIT`),
8176
+ * assembles consolidation transactions, and submits them to the network.
8177
+ *
8178
+ * Note: This method currently supports only the base asset.
8179
+ *
8180
+ * @param params - The parameters for coin consolidation, including the asset ID, mode, and output number.
8181
+ * @returns A promise that resolves to the response of the submitted transactions.
8182
+ * @throws Will throw an error if the asset is not a base asset as non-base asset consolidation is not implemented.
8183
+ */
8184
+ async consolidateCoins(params) {
8185
+ const { assetId } = params;
8186
+ const { coins } = await this.getCoins(assetId);
8187
+ const baseAssetId = await this.provider.getBaseAssetId();
8188
+ const isBaseAsset = baseAssetId === assetId;
8189
+ let submitAll;
8190
+ const consolidationParams = {
8191
+ coins,
8192
+ mode: params.mode,
8193
+ outputNum: params.outputNum
8194
+ };
8195
+ if (isBaseAsset) {
8196
+ ({ submitAll } = await this.assembleBaseAssetConsolidationTxs(consolidationParams));
8197
+ } else {
8198
+ throw new FuelError22(
8199
+ ErrorCode19.UNSUPPORTED_FEATURE,
8200
+ "Consolidation for non-base assets is not supported yet."
8201
+ );
8202
+ }
8203
+ return submitAll();
8204
+ }
8205
+ /**
8206
+ * Assembles transactions for consolidating base asset coins into fewer UTXOs.
8207
+ *
8208
+ * This method splits the provided coins into batches and creates transaction requests
8209
+ * to consolidate them. It calculates the necessary fee and sets up the transactions
8210
+ * to be submitted either in parallel (default) or sequentially.
8211
+ *
8212
+ * @param params - The parameters for assembling base asset consolidation transactions.
8213
+ *
8214
+ * @returns An object containing the assembled transactions, the total fee cost, and a callback to submit all transactions.
8215
+ */
8216
+ async assembleBaseAssetConsolidationTxs(params) {
8217
+ const { coins, mode = "parallel", outputNum = 1 } = params;
8218
+ const baseAssetId = await this.provider.getBaseAssetId();
8219
+ this.validateConsolidationTxsCoins(coins, baseAssetId);
8220
+ const chainInfo = await this.provider.getChain();
8221
+ const maxInputsNumber = chainInfo.consensusParameters.txParameters.maxInputs.toNumber();
8222
+ let totalFeeCost = bn21(0);
8223
+ const txs = [];
8224
+ const coinsBatches = splitCoinsIntoBatches(coins, maxInputsNumber);
8225
+ const gasPrice = await this.provider.estimateGasPrice(10);
8226
+ const consolidateMoreThanOneCoin = outputNum > 1;
8227
+ coinsBatches.filter((batch) => batch.length > 1).forEach((coinBatch) => {
8228
+ const request = new ScriptTransactionRequest({
8229
+ script: "0x"
8230
+ });
8231
+ request.addResources(coinBatch);
8232
+ if (consolidateMoreThanOneCoin) {
8233
+ Array.from({ length: outputNum - 1 }).forEach(() => {
8234
+ request.addCoinOutput(this.address, 0, baseAssetId);
8235
+ });
8236
+ }
8237
+ const minGas = request.calculateMinGas(chainInfo);
8238
+ const fee = calculateGasFee({
8239
+ gasPrice,
8240
+ gas: minGas,
8241
+ priceFactor: chainInfo.consensusParameters.feeParameters.gasPriceFactor,
8242
+ tip: request.tip
8243
+ });
8244
+ request.maxFee = fee;
8245
+ if (consolidateMoreThanOneCoin) {
8246
+ const total = request.inputs.filter(isRequestInputCoin).reduce((acc, input) => acc.add(input.amount), bn21(0));
8247
+ const amountPerNewUtxo = total.div(outputNum + 1);
8248
+ request.outputs.forEach((output) => {
8249
+ if (output.type === OutputType9.Coin) {
8250
+ output.amount = amountPerNewUtxo;
8251
+ }
8252
+ });
8253
+ }
8254
+ totalFeeCost = totalFeeCost.add(fee);
8255
+ txs.push(request);
8256
+ });
8257
+ const submitAll = this.prepareSubmitAll({ txs, mode });
8258
+ return { txs, totalFeeCost, submitAll };
8259
+ }
8260
+ /**
8261
+ * Prepares a function to submit all transactions either sequentially or in parallel.
8262
+ *
8263
+ * @param params - The parameters for preparing the submitAll callback.
8264
+ *
8265
+ * @returns A callback that, when called, submits all transactions and returns their results and any errors encountered.
8266
+ */
8267
+ prepareSubmitAll = /* @__PURE__ */ __name((params) => {
8268
+ const { txs, mode = "sequential" } = params;
8269
+ return async () => {
8270
+ const txResponses = [];
8271
+ const errors = [];
8272
+ if (mode === "sequential") {
8273
+ for (const tx of txs) {
8274
+ try {
8275
+ const submit = await this.sendTransaction(tx);
8276
+ const response = await submit.waitForResult();
8277
+ txResponses.push(response);
8278
+ } catch (error) {
8279
+ errors.push(error);
8280
+ }
8281
+ }
8282
+ } else {
8283
+ const results = await Promise.allSettled(
8284
+ txs.map(async (tx) => {
8285
+ const submit = await this.sendTransaction(tx);
8286
+ return submit.waitForResult();
8287
+ })
8288
+ );
8289
+ results.forEach((result) => {
8290
+ if (result.status === "fulfilled") {
8291
+ txResponses.push(result.value);
8292
+ } else {
8293
+ errors.push(result.reason);
8294
+ }
8295
+ });
8296
+ }
8297
+ return { txResponses, errors };
8298
+ };
8299
+ }, "prepareSubmitAll");
7134
8300
  /**
7135
8301
  * Returns a transaction cost to enable user
7136
8302
  * to set gasLimit and also reserve balance amounts
@@ -7140,15 +8306,18 @@ var Account = class extends AbstractAccount {
7140
8306
  * @param transactionCostParams - The transaction cost parameters (optional).
7141
8307
  *
7142
8308
  * @returns A promise that resolves to the transaction cost object.
8309
+ *
8310
+ * @deprecated Use provider.assembleTx instead
8311
+ * Check the migration guide https://docs.fuel.network/guide/assembling-transactions/migration-guide.html for more information.
7143
8312
  */
7144
8313
  async getTransactionCost(transactionRequestLike, { signatureCallback, quantities = [], gasPrice } = {}) {
7145
8314
  const txRequestClone = clone9(transactionRequestify(transactionRequestLike));
7146
8315
  const baseAssetId = await this.provider.getBaseAssetId();
7147
8316
  const coinOutputsQuantities = txRequestClone.getCoinOutputsQuantities();
7148
8317
  const requiredQuantities = mergeQuantities(coinOutputsQuantities, quantities);
7149
- const transactionFeeForDryRun = [{ assetId: baseAssetId, amount: bn20("100000000000000000") }];
8318
+ const transactionFeeForDryRun = [{ assetId: baseAssetId, amount: bn21("100000000000000000") }];
7150
8319
  const findAssetInput = /* @__PURE__ */ __name((assetId) => txRequestClone.inputs.find((input) => {
7151
- if (input.type === InputType7.Coin) {
8320
+ if (input.type === InputType8.Coin) {
7152
8321
  return input.assetId === assetId;
7153
8322
  }
7154
8323
  if (isRequestInputMessageWithoutData(input)) {
@@ -7194,7 +8363,7 @@ var Account = class extends AbstractAccount {
7194
8363
  */
7195
8364
  async signMessage(message) {
7196
8365
  if (!this._connector) {
7197
- throw new FuelError21(ErrorCode18.MISSING_CONNECTOR, "A connector is required to sign messages.");
8366
+ throw new FuelError22(ErrorCode19.MISSING_CONNECTOR, "A connector is required to sign messages.");
7198
8367
  }
7199
8368
  return this._connector.signMessage(this.address.toString(), message);
7200
8369
  }
@@ -7206,8 +8375,8 @@ var Account = class extends AbstractAccount {
7206
8375
  */
7207
8376
  async signTransaction(transactionRequestLike) {
7208
8377
  if (!this._connector) {
7209
- throw new FuelError21(
7210
- ErrorCode18.MISSING_CONNECTOR,
8378
+ throw new FuelError22(
8379
+ ErrorCode19.MISSING_CONNECTOR,
7211
8380
  "A connector is required to sign transactions."
7212
8381
  );
7213
8382
  }
@@ -7240,7 +8409,7 @@ var Account = class extends AbstractAccount {
7240
8409
  transactionRequest,
7241
8410
  params
7242
8411
  );
7243
- return typeof transaction === "string" ? this.provider.getTransactionResponse(transaction) : transaction;
8412
+ return typeof transaction === "string" ? this.provider.getTransactionResponse(transaction) : deserializeTransactionResponseJson(transaction);
7244
8413
  }
7245
8414
  if (estimateTxDependencies) {
7246
8415
  await this.provider.estimateTxDependencies(transactionRequest);
@@ -7271,17 +8440,17 @@ var Account = class extends AbstractAccount {
7271
8440
  */
7272
8441
  generateFakeResources(coins) {
7273
8442
  return coins.map((coin) => ({
7274
- id: hexlify20(randomBytes5(UTXO_ID_LEN3)),
8443
+ id: hexlify21(randomBytes5(UTXO_ID_LEN3)),
7275
8444
  owner: this.address,
7276
- blockCreated: bn20(1),
7277
- txCreatedIdx: bn20(1),
8445
+ blockCreated: bn21(1),
8446
+ txCreatedIdx: bn21(1),
7278
8447
  ...coin
7279
8448
  }));
7280
8449
  }
7281
8450
  /** @hidden */
7282
8451
  async prepareTransactionForSend(request) {
7283
8452
  const { transactionId } = request.flag;
7284
- if (!isDefined3(transactionId)) {
8453
+ if (!isDefined4(transactionId)) {
7285
8454
  return request;
7286
8455
  }
7287
8456
  const chainId = await this.provider.getChainId();
@@ -7294,17 +8463,29 @@ var Account = class extends AbstractAccount {
7294
8463
  /** @hidden */
7295
8464
  async prepareTransactionSummary(request) {
7296
8465
  const chainId = await this.provider.getChainId();
7297
- return isDefined3(request.flag.summary) ? {
8466
+ return isDefined4(request.flag.summary) ? {
7298
8467
  ...request.flag.summary,
7299
8468
  id: request.getTransactionId(chainId),
7300
- transactionBytes: hexlify20(request.toTransactionBytes())
8469
+ transactionBytes: hexlify21(request.toTransactionBytes())
7301
8470
  } : void 0;
7302
8471
  }
7303
8472
  /** @hidden * */
8473
+ async assembleTx(transactionRequest, quantities = []) {
8474
+ const outputQuantities = transactionRequest.outputs.filter((o) => o.type === OutputType9.Coin).map(({ amount, assetId }) => ({ assetId: String(assetId), amount: bn21(amount) }));
8475
+ transactionRequest.gasLimit = bn21(0);
8476
+ transactionRequest.maxFee = bn21(0);
8477
+ const { assembledRequest, gasPrice } = await this.provider.assembleTx({
8478
+ request: transactionRequest,
8479
+ accountCoinQuantities: mergeQuantities(outputQuantities, quantities),
8480
+ feePayerAccount: this
8481
+ });
8482
+ return { transactionRequest: assembledRequest, gasPrice };
8483
+ }
8484
+ /** @hidden * */
7304
8485
  validateTransferAmount(amount) {
7305
- if (bn20(amount).lte(0)) {
7306
- throw new FuelError21(
7307
- ErrorCode18.INVALID_TRANSFER_AMOUNT,
8486
+ if (bn21(amount).lte(0)) {
8487
+ throw new FuelError22(
8488
+ ErrorCode19.INVALID_TRANSFER_AMOUNT,
7308
8489
  "Transfer amount must be a positive number."
7309
8490
  );
7310
8491
  }
@@ -7330,24 +8511,36 @@ var Account = class extends AbstractAccount {
7330
8511
  txParams: { gasLimit: setGasLimit, maxFee: setMaxFee }
7331
8512
  }) {
7332
8513
  const request = transactionRequestify(transactionRequest);
7333
- if (!isDefined3(setGasLimit)) {
8514
+ if (!isDefined4(setGasLimit)) {
7334
8515
  request.gasLimit = gasUsed;
7335
8516
  } else if (gasUsed.gt(setGasLimit)) {
7336
- throw new FuelError21(
7337
- ErrorCode18.GAS_LIMIT_TOO_LOW,
8517
+ throw new FuelError22(
8518
+ ErrorCode19.GAS_LIMIT_TOO_LOW,
7338
8519
  `Gas limit '${setGasLimit}' is lower than the required: '${gasUsed}'.`
7339
8520
  );
7340
8521
  }
7341
- if (!isDefined3(setMaxFee)) {
8522
+ if (!isDefined4(setMaxFee)) {
7342
8523
  request.maxFee = maxFee;
7343
8524
  } else if (maxFee.gt(setMaxFee)) {
7344
- throw new FuelError21(
7345
- ErrorCode18.MAX_FEE_TOO_LOW,
8525
+ throw new FuelError22(
8526
+ ErrorCode19.MAX_FEE_TOO_LOW,
7346
8527
  `Max fee '${setMaxFee}' is lower than the required: '${maxFee}'.`
7347
8528
  );
7348
8529
  }
7349
8530
  return request;
7350
8531
  }
8532
+ /** @hidden * */
8533
+ validateConsolidationTxsCoins(coins, assetId) {
8534
+ if (coins.length <= 1) {
8535
+ throw new FuelError22(ErrorCode19.NO_COINS_TO_CONSOLIDATE, "No coins to consolidate.");
8536
+ }
8537
+ if (!coins.every((c) => c.assetId === assetId)) {
8538
+ throw new FuelError22(
8539
+ ErrorCode19.COINS_ASSET_ID_MISMATCH,
8540
+ "All coins to consolidate must be from the same asset id."
8541
+ );
8542
+ }
8543
+ }
7351
8544
  };
7352
8545
 
7353
8546
  // src/wallet/keystore-wallet.ts
@@ -7362,8 +8555,8 @@ import {
7362
8555
  encryptJsonWalletData,
7363
8556
  randomUUID as randomUUID2
7364
8557
  } 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";
8558
+ import { ErrorCode as ErrorCode20, FuelError as FuelError23 } from "@fuel-ts/errors";
8559
+ import { hexlify as hexlify22 } from "@fuel-ts/utils";
7367
8560
  var DEFAULT_KDF_PARAMS_LOG_N = 13;
7368
8561
  var DEFAULT_KDF_PARAMS_R = 8;
7369
8562
  var DEFAULT_KDF_PARAMS_P = 1;
@@ -7440,13 +8633,13 @@ async function decryptKeystoreWallet(jsonWallet, password) {
7440
8633
  const macHashUint8Array = keccak256(data);
7441
8634
  const macHash = stringFromBuffer(macHashUint8Array, "hex");
7442
8635
  if (mac !== macHash) {
7443
- throw new FuelError22(
7444
- ErrorCode19.INVALID_PASSWORD,
8636
+ throw new FuelError23(
8637
+ ErrorCode20.INVALID_PASSWORD,
7445
8638
  "Failed to decrypt the keystore wallet, the provided password is incorrect."
7446
8639
  );
7447
8640
  }
7448
8641
  const buffer = await decryptJsonWalletData(ciphertextBuffer, key, ivBuffer);
7449
- const privateKey = hexlify21(buffer);
8642
+ const privateKey = hexlify22(buffer);
7450
8643
  return privateKey;
7451
8644
  }
7452
8645
  __name(decryptKeystoreWallet, "decryptKeystoreWallet");
@@ -7499,7 +8692,7 @@ var BaseWalletUnlocked = class extends Account {
7499
8692
  */
7500
8693
  async signMessage(message) {
7501
8694
  const signedMessage = await this.signer().sign(hashMessage(message));
7502
- return hexlify22(signedMessage);
8695
+ return hexlify23(signedMessage);
7503
8696
  }
7504
8697
  /**
7505
8698
  * Signs a transaction with the wallet's private key.
@@ -7512,7 +8705,7 @@ var BaseWalletUnlocked = class extends Account {
7512
8705
  const chainId = await this.provider.getChainId();
7513
8706
  const hashedTransaction = transactionRequest.getTransactionId(chainId);
7514
8707
  const signature = await this.signer().sign(hashedTransaction);
7515
- return hexlify22(signature);
8708
+ return hexlify23(signature);
7516
8709
  }
7517
8710
  /**
7518
8711
  * Populates a transaction with the witnesses signature.
@@ -7580,16 +8773,16 @@ var BaseWalletUnlocked = class extends Account {
7580
8773
 
7581
8774
  // src/hdwallet/hdwallet.ts
7582
8775
  import { computeHmac as computeHmac2, ripemd160 } from "@fuel-ts/crypto";
7583
- import { ErrorCode as ErrorCode22, FuelError as FuelError25 } from "@fuel-ts/errors";
8776
+ import { ErrorCode as ErrorCode23, FuelError as FuelError26 } from "@fuel-ts/errors";
7584
8777
  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";
8778
+ import { bn as bn22, toBytes as toBytes2, toHex } from "@fuel-ts/math";
8779
+ import { arrayify as arrayify20, hexlify as hexlify25, concat as concat6, dataSlice as dataSlice2, encodeBase58 as encodeBase582, decodeBase58 } from "@fuel-ts/utils";
7587
8780
 
7588
8781
  // src/mnemonic/mnemonic.ts
7589
8782
  import { randomBytes as randomBytes7, pbkdf2, computeHmac } from "@fuel-ts/crypto";
7590
- import { ErrorCode as ErrorCode21, FuelError as FuelError24 } from "@fuel-ts/errors";
8783
+ import { ErrorCode as ErrorCode22, FuelError as FuelError25 } from "@fuel-ts/errors";
7591
8784
  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";
8785
+ import { arrayify as arrayify19, hexlify as hexlify24, concat as concat5, dataSlice, encodeBase58, toUtf8Bytes } from "@fuel-ts/utils";
7593
8786
 
7594
8787
  // src/wordlists/words/english.ts
7595
8788
  var english = [
@@ -9644,7 +10837,7 @@ var english = [
9644
10837
  ];
9645
10838
 
9646
10839
  // src/mnemonic/utils.ts
9647
- import { ErrorCode as ErrorCode20, FuelError as FuelError23 } from "@fuel-ts/errors";
10840
+ import { ErrorCode as ErrorCode21, FuelError as FuelError24 } from "@fuel-ts/errors";
9648
10841
  import { sha256 as sha2562 } from "@fuel-ts/hasher";
9649
10842
  import { arrayify as arrayify18 } from "@fuel-ts/utils";
9650
10843
  function getLowerMask(bits) {
@@ -9698,8 +10891,8 @@ function mnemonicWordsToEntropy(words, wordlist) {
9698
10891
  for (let i = 0; i < words.length; i += 1) {
9699
10892
  const index = wordlist.indexOf(words[i].normalize("NFKD"));
9700
10893
  if (index === -1) {
9701
- throw new FuelError23(
9702
- ErrorCode20.INVALID_MNEMONIC,
10894
+ throw new FuelError24(
10895
+ ErrorCode21.INVALID_MNEMONIC,
9703
10896
  `Invalid mnemonic: the word '${words[i]}' is not found in the provided wordlist.`
9704
10897
  );
9705
10898
  }
@@ -9715,8 +10908,8 @@ function mnemonicWordsToEntropy(words, wordlist) {
9715
10908
  const checksumMask = getUpperMask(checksumBits);
9716
10909
  const checksum = arrayify18(sha2562(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
9717
10910
  if (checksum !== (entropy[entropy.length - 1] & checksumMask)) {
9718
- throw new FuelError23(
9719
- ErrorCode20.INVALID_CHECKSUM,
10911
+ throw new FuelError24(
10912
+ ErrorCode21.INVALID_CHECKSUM,
9720
10913
  "Checksum validation failed for the provided mnemonic."
9721
10914
  );
9722
10915
  }
@@ -9731,8 +10924,8 @@ var TestnetPRV = "0x04358394";
9731
10924
  var MNEMONIC_SIZES = [12, 15, 18, 21, 24];
9732
10925
  function assertWordList(wordlist) {
9733
10926
  if (wordlist.length !== 2048) {
9734
- throw new FuelError24(
9735
- ErrorCode21.INVALID_WORD_LIST,
10927
+ throw new FuelError25(
10928
+ ErrorCode22.INVALID_WORD_LIST,
9736
10929
  `Expected word list length of 2048, but got ${wordlist.length}.`
9737
10930
  );
9738
10931
  }
@@ -9740,8 +10933,8 @@ function assertWordList(wordlist) {
9740
10933
  __name(assertWordList, "assertWordList");
9741
10934
  function assertEntropy(entropy) {
9742
10935
  if (entropy.length % 4 !== 0 || entropy.length < 16 || entropy.length > 32) {
9743
- throw new FuelError24(
9744
- ErrorCode21.INVALID_ENTROPY,
10936
+ throw new FuelError25(
10937
+ ErrorCode22.INVALID_ENTROPY,
9745
10938
  `Entropy should be between 16 and 32 bytes and a multiple of 4, but got ${entropy.length} bytes.`
9746
10939
  );
9747
10940
  }
@@ -9752,7 +10945,7 @@ function assertMnemonic(words) {
9752
10945
  const errorMsg = `Invalid mnemonic size. Expected one of [${MNEMONIC_SIZES.join(
9753
10946
  ", "
9754
10947
  )}] words, but got ${words.length}.`;
9755
- throw new FuelError24(ErrorCode21.INVALID_MNEMONIC, errorMsg);
10948
+ throw new FuelError25(ErrorCode22.INVALID_MNEMONIC, errorMsg);
9756
10949
  }
9757
10950
  }
9758
10951
  __name(assertMnemonic, "assertMnemonic");
@@ -9795,7 +10988,7 @@ var Mnemonic = class _Mnemonic {
9795
10988
  static mnemonicToEntropy(phrase, wordlist = english) {
9796
10989
  const words = getWords(phrase);
9797
10990
  assertMnemonic(words);
9798
- return hexlify23(mnemonicWordsToEntropy(words, wordlist));
10991
+ return hexlify24(mnemonicWordsToEntropy(words, wordlist));
9799
10992
  }
9800
10993
  /**
9801
10994
  * @param entropy - Entropy source to the mnemonic phrase.
@@ -9874,8 +11067,8 @@ var Mnemonic = class _Mnemonic {
9874
11067
  static masterKeysFromSeed(seed) {
9875
11068
  const seedArray = arrayify19(seed);
9876
11069
  if (seedArray.length < 16 || seedArray.length > 64) {
9877
- throw new FuelError24(
9878
- ErrorCode21.INVALID_SEED,
11070
+ throw new FuelError25(
11071
+ ErrorCode22.INVALID_SEED,
9879
11072
  `Seed length should be between 16 and 64 bytes, but received ${seedArray.length} bytes.`
9880
11073
  );
9881
11074
  }
@@ -9928,10 +11121,10 @@ var mnemonic_default = Mnemonic;
9928
11121
 
9929
11122
  // src/hdwallet/hdwallet.ts
9930
11123
  var HARDENED_INDEX = 2147483648;
9931
- var MainnetPRV2 = hexlify24("0x0488ade4");
9932
- var MainnetPUB = hexlify24("0x0488b21e");
9933
- var TestnetPRV2 = hexlify24("0x04358394");
9934
- var TestnetPUB = hexlify24("0x043587cf");
11124
+ var MainnetPRV2 = hexlify25("0x0488ade4");
11125
+ var MainnetPUB = hexlify25("0x0488b21e");
11126
+ var TestnetPRV2 = hexlify25("0x04358394");
11127
+ var TestnetPUB = hexlify25("0x043587cf");
9935
11128
  function base58check(data) {
9936
11129
  return encodeBase582(concat6([data, dataSlice2(sha2564(sha2564(data)), 0, 4)]));
9937
11130
  }
@@ -9944,19 +11137,19 @@ function getExtendedKeyPrefix(isPublic = false, testnet = false) {
9944
11137
  }
9945
11138
  __name(getExtendedKeyPrefix, "getExtendedKeyPrefix");
9946
11139
  function isPublicExtendedKey(extendedKey) {
9947
- return [MainnetPUB, TestnetPUB].includes(hexlify24(extendedKey.slice(0, 4)));
11140
+ return [MainnetPUB, TestnetPUB].includes(hexlify25(extendedKey.slice(0, 4)));
9948
11141
  }
9949
11142
  __name(isPublicExtendedKey, "isPublicExtendedKey");
9950
11143
  function isValidExtendedKey(extendedKey) {
9951
11144
  return [MainnetPRV2, TestnetPRV2, MainnetPUB, TestnetPUB].includes(
9952
- hexlify24(extendedKey.slice(0, 4))
11145
+ hexlify25(extendedKey.slice(0, 4))
9953
11146
  );
9954
11147
  }
9955
11148
  __name(isValidExtendedKey, "isValidExtendedKey");
9956
11149
  function parsePath(path2, depth = 0) {
9957
11150
  const components = path2.split("/");
9958
11151
  if (components.length === 0 || components[0] === "m" && depth !== 0) {
9959
- throw new FuelError25(ErrorCode22.HD_WALLET_ERROR, `invalid path - ${path2}`);
11152
+ throw new FuelError26(ErrorCode23.HD_WALLET_ERROR, `invalid path - ${path2}`);
9960
11153
  }
9961
11154
  if (components[0] === "m") {
9962
11155
  components.shift();
@@ -9972,8 +11165,8 @@ var HDWallet = class _HDWallet {
9972
11165
  }
9973
11166
  depth = 0;
9974
11167
  index = 0;
9975
- fingerprint = hexlify24("0x00000000");
9976
- parentFingerprint = hexlify24("0x00000000");
11168
+ fingerprint = hexlify25("0x00000000");
11169
+ parentFingerprint = hexlify25("0x00000000");
9977
11170
  privateKey;
9978
11171
  publicKey;
9979
11172
  chainCode;
@@ -9985,16 +11178,16 @@ var HDWallet = class _HDWallet {
9985
11178
  constructor(config) {
9986
11179
  if (config.privateKey) {
9987
11180
  const signer = new Signer(config.privateKey);
9988
- this.publicKey = hexlify24(signer.compressedPublicKey);
9989
- this.privateKey = hexlify24(config.privateKey);
11181
+ this.publicKey = hexlify25(signer.compressedPublicKey);
11182
+ this.privateKey = hexlify25(config.privateKey);
9990
11183
  } else {
9991
11184
  if (!config.publicKey) {
9992
- throw new FuelError25(
9993
- ErrorCode22.HD_WALLET_ERROR,
11185
+ throw new FuelError26(
11186
+ ErrorCode23.HD_WALLET_ERROR,
9994
11187
  "Both public and private Key cannot be missing. At least one should be provided."
9995
11188
  );
9996
11189
  }
9997
- this.publicKey = hexlify24(config.publicKey);
11190
+ this.publicKey = hexlify25(config.publicKey);
9998
11191
  }
9999
11192
  this.parentFingerprint = config.parentFingerprint || this.parentFingerprint;
10000
11193
  this.fingerprint = dataSlice2(ripemd160(sha2564(this.publicKey)), 0, 4);
@@ -10019,8 +11212,8 @@ var HDWallet = class _HDWallet {
10019
11212
  const data = new Uint8Array(37);
10020
11213
  if (index & HARDENED_INDEX) {
10021
11214
  if (!privateKey) {
10022
- throw new FuelError25(
10023
- ErrorCode22.HD_WALLET_ERROR,
11215
+ throw new FuelError26(
11216
+ ErrorCode23.HD_WALLET_ERROR,
10024
11217
  "Cannot derive a hardened index without a private Key."
10025
11218
  );
10026
11219
  }
@@ -10034,7 +11227,7 @@ var HDWallet = class _HDWallet {
10034
11227
  const IR = bytes.slice(32);
10035
11228
  if (privateKey) {
10036
11229
  const N = "0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141";
10037
- const ki = bn21(IL).add(privateKey).mod(N).toBytes(32);
11230
+ const ki = bn22(IL).add(privateKey).mod(N).toBytes(32);
10038
11231
  return new _HDWallet({
10039
11232
  privateKey: ki,
10040
11233
  chainCode: IR,
@@ -10043,7 +11236,7 @@ var HDWallet = class _HDWallet {
10043
11236
  parentFingerprint: this.fingerprint
10044
11237
  });
10045
11238
  }
10046
- const signer = new Signer(hexlify24(IL));
11239
+ const signer = new Signer(hexlify25(IL));
10047
11240
  const Ki = signer.addPoint(publicKey);
10048
11241
  return new _HDWallet({
10049
11242
  publicKey: Ki,
@@ -10072,13 +11265,13 @@ var HDWallet = class _HDWallet {
10072
11265
  */
10073
11266
  toExtendedKey(isPublic = false, testnet = false) {
10074
11267
  if (this.depth >= 256) {
10075
- throw new FuelError25(
10076
- ErrorCode22.HD_WALLET_ERROR,
11268
+ throw new FuelError26(
11269
+ ErrorCode23.HD_WALLET_ERROR,
10077
11270
  `Exceeded max depth of 255. Current depth: ${this.depth}.`
10078
11271
  );
10079
11272
  }
10080
11273
  const prefix = getExtendedKeyPrefix(this.privateKey == null || isPublic, testnet);
10081
- const depth = hexlify24(Uint8Array.from([this.depth]));
11274
+ const depth = hexlify25(Uint8Array.from([this.depth]));
10082
11275
  const parentFingerprint = this.parentFingerprint;
10083
11276
  const index = toHex(this.index, 4);
10084
11277
  const chainCode = this.chainCode;
@@ -10100,29 +11293,29 @@ var HDWallet = class _HDWallet {
10100
11293
  });
10101
11294
  }
10102
11295
  static fromExtendedKey(extendedKey) {
10103
- const decoded = hexlify24(toBytes2(decodeBase58(extendedKey)));
11296
+ const decoded = hexlify25(toBytes2(decodeBase58(extendedKey)));
10104
11297
  const bytes = arrayify20(decoded);
10105
11298
  const validChecksum = base58check(bytes.slice(0, 78)) === extendedKey;
10106
11299
  if (bytes.length !== 82 || !isValidExtendedKey(bytes)) {
10107
- throw new FuelError25(ErrorCode22.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
11300
+ throw new FuelError26(ErrorCode23.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
10108
11301
  }
10109
11302
  if (!validChecksum) {
10110
- throw new FuelError25(ErrorCode22.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
11303
+ throw new FuelError26(ErrorCode23.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
10111
11304
  }
10112
11305
  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));
11306
+ const parentFingerprint = hexlify25(bytes.slice(5, 9));
11307
+ const index = parseInt(hexlify25(bytes.slice(9, 13)).substring(2), 16);
11308
+ const chainCode = hexlify25(bytes.slice(13, 45));
10116
11309
  const key = bytes.slice(45, 78);
10117
11310
  if (depth === 0 && parentFingerprint !== "0x00000000" || depth === 0 && index !== 0) {
10118
- throw new FuelError25(
10119
- ErrorCode22.HD_WALLET_ERROR,
11311
+ throw new FuelError26(
11312
+ ErrorCode23.HD_WALLET_ERROR,
10120
11313
  "Inconsistency detected: Depth is zero but fingerprint/index is non-zero."
10121
11314
  );
10122
11315
  }
10123
11316
  if (isPublicExtendedKey(bytes)) {
10124
11317
  if (key[0] !== 3) {
10125
- throw new FuelError25(ErrorCode22.HD_WALLET_ERROR, "Invalid public extended key.");
11318
+ throw new FuelError26(ErrorCode23.HD_WALLET_ERROR, "Invalid public extended key.");
10126
11319
  }
10127
11320
  return new _HDWallet({
10128
11321
  publicKey: key,
@@ -10133,7 +11326,7 @@ var HDWallet = class _HDWallet {
10133
11326
  });
10134
11327
  }
10135
11328
  if (key[0] !== 0) {
10136
- throw new FuelError25(ErrorCode22.HD_WALLET_ERROR, "Invalid private extended key.");
11329
+ throw new FuelError26(ErrorCode23.HD_WALLET_ERROR, "Invalid private extended key.");
10137
11330
  }
10138
11331
  return new _HDWallet({
10139
11332
  privateKey: key.slice(1),
@@ -10369,13 +11562,13 @@ var WalletsConfig = class _WalletsConfig {
10369
11562
  assetIds.forEach((assetId) => {
10370
11563
  for (let index = 0; index < coinsPerAsset; index++) {
10371
11564
  coins.push({
10372
- amount: bn22(amountPerCoin).toString(),
11565
+ amount: bn23(amountPerCoin).toString(),
10373
11566
  asset_id: assetId,
10374
11567
  owner: walletAddress,
10375
11568
  tx_pointer_block_height: 0,
10376
11569
  tx_pointer_tx_idx: 0,
10377
11570
  output_index: 0,
10378
- tx_id: hexlify25(randomBytes8(32))
11571
+ tx_id: hexlify26(randomBytes8(32))
10379
11572
  });
10380
11573
  }
10381
11574
  });
@@ -10389,26 +11582,26 @@ var WalletsConfig = class _WalletsConfig {
10389
11582
  amountPerCoin
10390
11583
  }) {
10391
11584
  if (Array.isArray(wallets) && wallets.length === 0 || typeof wallets === "number" && wallets <= 0) {
10392
- throw new FuelError26(
10393
- FuelError26.CODES.INVALID_INPUT_PARAMETERS,
11585
+ throw new FuelError27(
11586
+ FuelError27.CODES.INVALID_INPUT_PARAMETERS,
10394
11587
  "Number of wallets must be greater than zero."
10395
11588
  );
10396
11589
  }
10397
11590
  if (Array.isArray(assets) && assets.length === 0 || typeof assets === "number" && assets <= 0) {
10398
- throw new FuelError26(
10399
- FuelError26.CODES.INVALID_INPUT_PARAMETERS,
11591
+ throw new FuelError27(
11592
+ FuelError27.CODES.INVALID_INPUT_PARAMETERS,
10400
11593
  "Number of assets per wallet must be greater than zero."
10401
11594
  );
10402
11595
  }
10403
11596
  if (coinsPerAsset <= 0) {
10404
- throw new FuelError26(
10405
- FuelError26.CODES.INVALID_INPUT_PARAMETERS,
11597
+ throw new FuelError27(
11598
+ FuelError27.CODES.INVALID_INPUT_PARAMETERS,
10406
11599
  "Number of coins per asset must be greater than zero."
10407
11600
  );
10408
11601
  }
10409
- if (bn22(amountPerCoin).lt(0)) {
10410
- throw new FuelError26(
10411
- FuelError26.CODES.INVALID_INPUT_PARAMETERS,
11602
+ if (bn23(amountPerCoin).lt(0)) {
11603
+ throw new FuelError27(
11604
+ FuelError27.CODES.INVALID_INPUT_PARAMETERS,
10412
11605
  "Amount per coin must be greater than or equal to zero."
10413
11606
  );
10414
11607
  }
@@ -10446,23 +11639,26 @@ async function setupTestProviderAndWallets({
10446
11639
  ),
10447
11640
  port: nodeOptions.port || "0"
10448
11641
  };
10449
- let cleanup;
11642
+ let killNode;
10450
11643
  let url;
10451
11644
  if (launchNodeServerPort) {
10452
11645
  const serverUrl = `http://localhost:${launchNodeServerPort}`;
10453
11646
  url = await (await fetch(serverUrl, { method: "POST", body: JSON.stringify(launchNodeOptions) })).text();
10454
- cleanup = /* @__PURE__ */ __name(() => {
11647
+ killNode = /* @__PURE__ */ __name(() => {
10455
11648
  fetch(`${serverUrl}/cleanup/${url}`);
10456
- }, "cleanup");
11649
+ }, "killNode");
10457
11650
  } else {
10458
11651
  const settings = await launchNode(launchNodeOptions);
10459
11652
  url = settings.url;
10460
- cleanup = settings.cleanup;
11653
+ killNode = settings.cleanup;
10461
11654
  }
11655
+ const cleanup = /* @__PURE__ */ __name(() => {
11656
+ Provider.clearChainAndNodeCaches(url);
11657
+ killNode();
11658
+ }, "cleanup");
10462
11659
  let provider;
10463
11660
  try {
10464
11661
  provider = new Provider(url, providerOptions);
10465
- await provider.init();
10466
11662
  } catch (err) {
10467
11663
  cleanup();
10468
11664
  throw err;
@@ -10483,8 +11679,8 @@ __name(setupTestProviderAndWallets, "setupTestProviderAndWallets");
10483
11679
  // src/test-utils/test-message.ts
10484
11680
  import { Address as Address7 } from "@fuel-ts/address";
10485
11681
  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";
11682
+ import { bn as bn24 } from "@fuel-ts/math";
11683
+ import { hexlify as hexlify27 } from "@fuel-ts/utils";
10488
11684
  var TestMessage = class {
10489
11685
  static {
10490
11686
  __name(this, "TestMessage");
@@ -10504,7 +11700,7 @@ var TestMessage = class {
10504
11700
  constructor({
10505
11701
  sender = Address7.fromRandom(),
10506
11702
  recipient = Address7.fromRandom(),
10507
- nonce = hexlify26(randomBytes9(32)),
11703
+ nonce = hexlify27(randomBytes9(32)),
10508
11704
  amount = 1e6,
10509
11705
  data = "",
10510
11706
  // Will default to empty data in order to be a spendable message
@@ -10523,7 +11719,7 @@ var TestMessage = class {
10523
11719
  sender: this.sender.toB256(),
10524
11720
  recipient: recipient?.toB256() ?? this.recipient.toB256(),
10525
11721
  nonce: this.nonce,
10526
- amount: bn23(this.amount).toNumber(),
11722
+ amount: bn24(this.amount).toNumber(),
10527
11723
  data,
10528
11724
  da_height: this.da_height
10529
11725
  };