@fuel-ts/account 0.100.2 → 0.100.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/account.d.ts +71 -3
  2. package/dist/account.d.ts.map +1 -1
  3. package/dist/index.global.js +1587 -289
  4. package/dist/index.global.js.map +1 -1
  5. package/dist/index.js +2133 -920
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +2041 -831
  8. package/dist/index.mjs.map +1 -1
  9. package/dist/predicate/predicate.d.ts +9 -4
  10. package/dist/predicate/predicate.d.ts.map +1 -1
  11. package/dist/providers/__generated__/operations.d.ts +1183 -87
  12. package/dist/providers/__generated__/operations.d.ts.map +1 -1
  13. package/dist/providers/assemble-tx-helpers.d.ts +39 -0
  14. package/dist/providers/assemble-tx-helpers.d.ts.map +1 -0
  15. package/dist/providers/fuel-graphql-subscriber.d.ts +28 -0
  16. package/dist/providers/fuel-graphql-subscriber.d.ts.map +1 -1
  17. package/dist/providers/index.d.ts +1 -0
  18. package/dist/providers/index.d.ts.map +1 -1
  19. package/dist/providers/provider.d.ts +80 -6
  20. package/dist/providers/provider.d.ts.map +1 -1
  21. package/dist/providers/resource.d.ts +4 -1
  22. package/dist/providers/resource.d.ts.map +1 -1
  23. package/dist/providers/transaction-request/helpers.d.ts +3 -3
  24. package/dist/providers/transaction-request/helpers.d.ts.map +1 -1
  25. package/dist/providers/transaction-request/input.d.ts +2 -0
  26. package/dist/providers/transaction-request/input.d.ts.map +1 -1
  27. package/dist/providers/transaction-request/output.d.ts +6 -0
  28. package/dist/providers/transaction-request/output.d.ts.map +1 -1
  29. package/dist/providers/transaction-request/script-transaction-request.d.ts +11 -0
  30. package/dist/providers/transaction-request/script-transaction-request.d.ts.map +1 -1
  31. package/dist/providers/transaction-response/getAllDecodedLogs.d.ts +30 -0
  32. package/dist/providers/transaction-response/getAllDecodedLogs.d.ts.map +1 -0
  33. package/dist/providers/transaction-response/getDecodedLogs.d.ts +20 -1
  34. package/dist/providers/transaction-response/getDecodedLogs.d.ts.map +1 -1
  35. package/dist/providers/transaction-response/index.d.ts +1 -0
  36. package/dist/providers/transaction-response/index.d.ts.map +1 -1
  37. package/dist/providers/transaction-response/transaction-response.d.ts +41 -12
  38. package/dist/providers/transaction-response/transaction-response.d.ts.map +1 -1
  39. package/dist/providers/transaction-summary/assemble-transaction-summary.d.ts +12 -1
  40. package/dist/providers/transaction-summary/assemble-transaction-summary.d.ts.map +1 -1
  41. package/dist/providers/transaction-summary/get-transaction-summary.d.ts.map +1 -1
  42. package/dist/providers/transaction-summary/status.d.ts +16 -2
  43. package/dist/providers/transaction-summary/status.d.ts.map +1 -1
  44. package/dist/providers/transaction-summary/types.d.ts +85 -4
  45. package/dist/providers/transaction-summary/types.d.ts.map +1 -1
  46. package/dist/providers/utils/extract-tx-error.d.ts +4 -3
  47. package/dist/providers/utils/extract-tx-error.d.ts.map +1 -1
  48. package/dist/providers/utils/handle-gql-error-message.d.ts.map +1 -1
  49. package/dist/providers/utils/index.d.ts +1 -0
  50. package/dist/providers/utils/index.d.ts.map +1 -1
  51. package/dist/providers/utils/parse-graphql-response.d.ts +12 -0
  52. package/dist/providers/utils/parse-graphql-response.d.ts.map +1 -0
  53. package/dist/providers/utils/serialization.d.ts +9 -0
  54. package/dist/providers/utils/serialization.d.ts.map +1 -1
  55. package/dist/test-utils/launchNode.d.ts.map +1 -1
  56. package/dist/test-utils/setup-test-provider-and-wallets.d.ts.map +1 -1
  57. package/dist/test-utils.global.js +1540 -268
  58. package/dist/test-utils.global.js.map +1 -1
  59. package/dist/test-utils.js +2008 -837
  60. package/dist/test-utils.js.map +1 -1
  61. package/dist/test-utils.mjs +1931 -754
  62. package/dist/test-utils.mjs.map +1 -1
  63. package/dist/utils/deployScriptOrPredicate.d.ts.map +1 -1
  64. package/dist/utils/split-coins-into-batches.d.ts +3 -0
  65. package/dist/utils/split-coins-into-batches.d.ts.map +1 -0
  66. package/package.json +15 -15
  67. package/dist/providers/utils/helpers.d.ts +0 -14
  68. 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,29 +406,94 @@ 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 FuelError20 } 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";
414
416
  import { clone as clone8 } from "ramda";
415
417
 
416
- // src/connectors/utils/promises.ts
417
- import { FuelError as FuelError2 } from "@fuel-ts/errors";
418
- function deferPromise() {
419
- const defer = {};
420
- defer.promise = new Promise((resolve, reject) => {
421
- defer.reject = reject;
422
- defer.resolve = resolve;
423
- });
424
- return defer;
425
- }
426
- __name(deferPromise, "deferPromise");
427
-
428
418
  // src/providers/__generated__/operations.ts
429
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
+ `;
430
497
  var SubmittedStatusFragmentDoc = gql`
431
498
  fragment SubmittedStatusFragment on SubmittedStatus {
432
499
  type: __typename
@@ -555,6 +622,87 @@ var SqueezedOutStatusFragmentDoc = gql`
555
622
  reason
556
623
  }
557
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}`;
558
706
  var TransactionStatusSubscriptionFragmentDoc = gql`
559
707
  fragment transactionStatusSubscriptionFragment on TransactionStatus {
560
708
  ... on SubmittedStatus {
@@ -575,12 +723,20 @@ var TransactionStatusSubscriptionFragmentDoc = gql`
575
723
  ... on SqueezedOutStatus {
576
724
  ...SqueezedOutStatusFragment
577
725
  }
726
+ ... on PreconfirmationSuccessStatus {
727
+ ...PreconfirmationSuccessStatusFragment
728
+ }
729
+ ... on PreconfirmationFailureStatus {
730
+ ...PreconfirmationFailureStatusFragment
731
+ }
578
732
  }
579
733
  ${SubmittedStatusFragmentDoc}
580
734
  ${SuccessStatusWithBlockIdFragmentDoc}
581
735
  ${MalleableTransactionFieldsFragmentDoc}
582
736
  ${FailureStatusWithBlockIdFragmentDoc}
583
- ${SqueezedOutStatusFragmentDoc}`;
737
+ ${SqueezedOutStatusFragmentDoc}
738
+ ${PreconfirmationSuccessStatusFragmentDoc}
739
+ ${PreconfirmationFailureStatusFragmentDoc}`;
584
740
  var TransactionStatusFragmentDoc = gql`
585
741
  fragment transactionStatusFragment on TransactionStatus {
586
742
  ... on SubmittedStatus {
@@ -632,6 +788,23 @@ var TransactionEstimatePredicatesFragmentDoc = gql`
632
788
  }
633
789
  }
634
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}`;
635
808
  var DryRunFailureStatusFragmentDoc = gql`
636
809
  fragment dryRunFailureStatusFragment on DryRunFailureStatus {
637
810
  type: __typename
@@ -988,13 +1161,21 @@ var GetTransactionWithReceiptsDocument = gql`
988
1161
  ... on SqueezedOutStatus {
989
1162
  ...SqueezedOutStatusFragment
990
1163
  }
1164
+ ... on PreconfirmationSuccessStatus {
1165
+ ...PreconfirmationSuccessStatusFragment
1166
+ }
1167
+ ... on PreconfirmationFailureStatus {
1168
+ ...PreconfirmationFailureStatusFragment
1169
+ }
991
1170
  }
992
1171
  }
993
1172
  }
994
1173
  ${SubmittedStatusFragmentDoc}
995
1174
  ${SuccessStatusWithBlockIdFragmentDoc}
996
1175
  ${FailureStatusWithBlockIdFragmentDoc}
997
- ${SqueezedOutStatusFragmentDoc}`;
1176
+ ${SqueezedOutStatusFragmentDoc}
1177
+ ${PreconfirmationSuccessStatusFragmentDoc}
1178
+ ${PreconfirmationFailureStatusFragmentDoc}`;
998
1179
  var GetTransactionsDocument = gql`
999
1180
  query getTransactions($after: String, $before: String, $first: Int, $last: Int) {
1000
1181
  transactions(after: $after, before: $before, first: $first, last: $last) {
@@ -1285,6 +1466,77 @@ var GetAssetDetailsDocument = gql`
1285
1466
  }
1286
1467
  }
1287
1468
  `;
1469
+ var AssembleTxDocument = gql`
1470
+ query assembleTx($tx: HexString!, $blockHorizon: U32!, $requiredBalances: [RequiredBalance!]!, $feeAddressIndex: U16!, $excludeInput: ExcludeInput, $estimatePredicates: Boolean, $reserveGas: U64) {
1471
+ assembleTx(
1472
+ tx: $tx
1473
+ blockHorizon: $blockHorizon
1474
+ requiredBalances: $requiredBalances
1475
+ feeAddressIndex: $feeAddressIndex
1476
+ excludeInput: $excludeInput
1477
+ estimatePredicates: $estimatePredicates
1478
+ reserveGas: $reserveGas
1479
+ ) {
1480
+ transaction {
1481
+ id
1482
+ inputs {
1483
+ ... on InputCoin {
1484
+ ...InputCoinFragment
1485
+ }
1486
+ ... on InputContract {
1487
+ ...InputContractFragment
1488
+ }
1489
+ ... on InputMessage {
1490
+ ...InputMessageFragment
1491
+ }
1492
+ }
1493
+ outputs {
1494
+ ... on CoinOutput {
1495
+ ...OutputCoinFragment
1496
+ }
1497
+ ... on ContractOutput {
1498
+ ...OutputContractFragment
1499
+ }
1500
+ ... on ChangeOutput {
1501
+ ...OutputChangeFragment
1502
+ }
1503
+ ... on VariableOutput {
1504
+ ...OutputVariableFragment
1505
+ }
1506
+ ... on ContractCreated {
1507
+ ...OutputContractCreatedFragment
1508
+ }
1509
+ }
1510
+ policies {
1511
+ tip
1512
+ witnessLimit
1513
+ maturity
1514
+ maxFee
1515
+ }
1516
+ witnesses
1517
+ scriptGasLimit
1518
+ }
1519
+ status {
1520
+ ... on DryRunFailureStatus {
1521
+ ...dryRunFailureAssembleTxFragment
1522
+ }
1523
+ ... on DryRunSuccessStatus {
1524
+ ...dryRunSuccessAssembleTxFragment
1525
+ }
1526
+ }
1527
+ gasPrice
1528
+ }
1529
+ }
1530
+ ${InputCoinFragmentDoc}
1531
+ ${InputContractFragmentDoc}
1532
+ ${InputMessageFragmentDoc}
1533
+ ${OutputCoinFragmentDoc}
1534
+ ${OutputContractFragmentDoc}
1535
+ ${OutputChangeFragmentDoc}
1536
+ ${OutputVariableFragmentDoc}
1537
+ ${OutputContractCreatedFragmentDoc}
1538
+ ${DryRunFailureAssembleTxFragmentDoc}
1539
+ ${DryRunSuccessAssembleTxFragmentDoc}`;
1288
1540
  var DryRunDocument = gql`
1289
1541
  mutation dryRun($encodedTransactions: [HexString!]!, $utxoValidation: Boolean, $gasPrice: U64) {
1290
1542
  dryRun(
@@ -1343,15 +1595,22 @@ var GetConsensusParametersVersionDocument = gql`
1343
1595
  }
1344
1596
  `;
1345
1597
  var SubmitAndAwaitStatusDocument = gql`
1346
- subscription submitAndAwaitStatus($encodedTransaction: HexString!) {
1347
- submitAndAwaitStatus(tx: $encodedTransaction) {
1598
+ subscription submitAndAwaitStatus($encodedTransaction: HexString!, $estimatePredicates: Boolean, $includePreConfirmation: Boolean) {
1599
+ submitAndAwaitStatus(
1600
+ tx: $encodedTransaction
1601
+ estimatePredicates: $estimatePredicates
1602
+ includePreconfirmation: $includePreConfirmation
1603
+ ) {
1348
1604
  ...transactionStatusSubscriptionFragment
1349
1605
  }
1350
1606
  }
1351
1607
  ${TransactionStatusSubscriptionFragmentDoc}`;
1352
1608
  var StatusChangeDocument = gql`
1353
- subscription statusChange($transactionId: TransactionId!) {
1354
- statusChange(id: $transactionId) {
1609
+ subscription statusChange($transactionId: TransactionId!, $includePreConfirmation: Boolean) {
1610
+ statusChange(
1611
+ id: $transactionId
1612
+ includePreconfirmation: $includePreConfirmation
1613
+ ) {
1355
1614
  ...transactionStatusSubscriptionFragment
1356
1615
  }
1357
1616
  }
@@ -1454,6 +1713,9 @@ function getSdk(requester) {
1454
1713
  getAssetDetails(variables, options) {
1455
1714
  return requester(GetAssetDetailsDocument, variables, options);
1456
1715
  },
1716
+ assembleTx(variables, options) {
1717
+ return requester(AssembleTxDocument, variables, options);
1718
+ },
1457
1719
  dryRun(variables, options) {
1458
1720
  return requester(DryRunDocument, variables, options);
1459
1721
  },
@@ -1482,30 +1744,117 @@ function getSdk(requester) {
1482
1744
  }
1483
1745
  __name(getSdk, "getSdk");
1484
1746
 
1747
+ // src/providers/assemble-tx-helpers.ts
1748
+ import { FuelError as FuelError2, ErrorCode } from "@fuel-ts/errors";
1749
+ import { bn as bn2 } from "@fuel-ts/math";
1750
+ import { TransactionType } from "@fuel-ts/transactions";
1751
+ import { hexlify as hexlify4, isDefined } from "@fuel-ts/utils";
1752
+ var resolveAccountForAssembleTxParams = /* @__PURE__ */ __name((account) => {
1753
+ const assembleTxAccount = {};
1754
+ const accountIsPredicate = "bytes" in account;
1755
+ if (accountIsPredicate) {
1756
+ assembleTxAccount.predicate = {
1757
+ predicate: hexlify4(account.bytes),
1758
+ predicateAddress: account.address.toB256(),
1759
+ predicateData: hexlify4(account.getPredicateData())
1760
+ };
1761
+ } else {
1762
+ assembleTxAccount.address = account.address.toB256();
1763
+ }
1764
+ return assembleTxAccount;
1765
+ }, "resolveAccountForAssembleTxParams");
1766
+ var setAndValidateGasAndFeeForAssembledTx = /* @__PURE__ */ __name(async (params) => {
1767
+ const { gasPrice, transactionRequest, setGasLimit, setMaxFee, provider } = params;
1768
+ const gasLimitSpecified = isDefined(setGasLimit);
1769
+ const maxFeeSpecified = isDefined(setMaxFee);
1770
+ const isScriptTx = transactionRequest.type === TransactionType.Script;
1771
+ if (gasLimitSpecified && isScriptTx) {
1772
+ const requiredGasLimit = transactionRequest.gasLimit;
1773
+ if (bn2(setGasLimit).lt(bn2(requiredGasLimit))) {
1774
+ throw new FuelError2(
1775
+ ErrorCode.GAS_LIMIT_TOO_LOW,
1776
+ `Gas limit '${setGasLimit}' is lower than the required: '${requiredGasLimit}'.`
1777
+ );
1778
+ }
1779
+ transactionRequest.gasLimit = bn2(setGasLimit);
1780
+ }
1781
+ if (maxFeeSpecified) {
1782
+ const requiredMaxFee = transactionRequest.maxFee;
1783
+ if (bn2(setMaxFee).lt(requiredMaxFee)) {
1784
+ throw new FuelError2(
1785
+ ErrorCode.MAX_FEE_TOO_LOW,
1786
+ `Max fee '${setMaxFee}' is lower than the required: '${requiredMaxFee}'.`
1787
+ );
1788
+ }
1789
+ transactionRequest.maxFee = bn2(setMaxFee);
1790
+ }
1791
+ if (gasLimitSpecified && !maxFeeSpecified) {
1792
+ const { maxFee: feeForGasPrice } = await provider.estimateTxGasAndFee({
1793
+ transactionRequest,
1794
+ gasPrice
1795
+ });
1796
+ transactionRequest.maxFee = feeForGasPrice;
1797
+ }
1798
+ return transactionRequest;
1799
+ }, "setAndValidateGasAndFeeForAssembledTx");
1800
+
1485
1801
  // src/providers/fuel-graphql-subscriber.ts
1486
- import { ErrorCode as ErrorCode2, FuelError as FuelError4 } from "@fuel-ts/errors";
1802
+ import { ErrorCode as ErrorCode3, FuelError as FuelError4 } from "@fuel-ts/errors";
1487
1803
  import { print } from "graphql";
1488
1804
 
1489
1805
  // src/providers/utils/handle-gql-error-message.ts
1490
- import { ErrorCode, FuelError as FuelError3 } from "@fuel-ts/errors";
1806
+ import { ErrorCode as ErrorCode2, FuelError as FuelError3 } from "@fuel-ts/errors";
1807
+ var gqlErrorMessage = {
1808
+ RPC_CONSISTENCY: /The required fuel block height is higher than the current block height. Required: \d+, Current: \d+/,
1809
+ NOT_ENOUGH_COINS_MAX_COINS: /the target cannot be met due to no coins available or exceeding the \d+ coin limit./,
1810
+ ASSET_NOT_FOUND: /resource was not found in table/,
1811
+ MULTIPLE_CHANGE_POLICIES: /The asset ([a-fA-F0-9]{64}) has multiple change policies/,
1812
+ DUPLICATE_CHANGE_OUTPUT_ACCOUNT: /required balances contain duplicate \(asset, account\) pair/,
1813
+ INSUFFICIENT_FEE_AMOUNT: /InsufficientFeeAmount { expected: (\d+), provided: (\d+) }/
1814
+ };
1491
1815
  var mapGqlErrorMessage = /* @__PURE__ */ __name((error) => {
1492
- 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)) {
1816
+ if (gqlErrorMessage.NOT_ENOUGH_COINS_MAX_COINS.test(error.message)) {
1493
1817
  return new FuelError3(
1494
- ErrorCode.INSUFFICIENT_FUNDS_OR_MAX_COINS,
1818
+ ErrorCode2.INSUFFICIENT_FUNDS_OR_MAX_COINS,
1495
1819
  `Insufficient funds or too many small value coins. Consider combining UTXOs.`,
1496
1820
  {},
1497
1821
  error
1498
1822
  );
1499
1823
  }
1500
- if (new RegExp("resource was not found in table" /* ASSET_NOT_FOUND */).test(error.message)) {
1824
+ if (gqlErrorMessage.MULTIPLE_CHANGE_POLICIES.test(error.message)) {
1825
+ const match = error.message.match(/asset ([a-fA-F0-9]{64})/);
1826
+ const assetId = match?.[1] || "";
1501
1827
  return new FuelError3(
1502
- ErrorCode.ASSET_NOT_FOUND,
1828
+ ErrorCode2.CHANGE_OUTPUT_COLLISION,
1829
+ `OutputChange address for asset 0x${assetId} differs between transaction request and assembleTx parameters.`,
1830
+ {},
1831
+ error
1832
+ );
1833
+ }
1834
+ if (gqlErrorMessage.DUPLICATE_CHANGE_OUTPUT_ACCOUNT.test(error.message)) {
1835
+ return new FuelError3(
1836
+ ErrorCode2.DUPLICATE_CHANGE_OUTPUT_ACCOUNT,
1837
+ `The parameter 'accountCoinQuantities' of assembleTx contains duplicate entries for the same assetId with different 'changeOutputAccount'.`,
1838
+ {},
1839
+ error
1840
+ );
1841
+ }
1842
+ if (gqlErrorMessage.ASSET_NOT_FOUND.test(error.message)) {
1843
+ return new FuelError3(
1844
+ ErrorCode2.ASSET_NOT_FOUND,
1503
1845
  `Asset not found for given asset id.`,
1504
1846
  {},
1505
1847
  error
1506
1848
  );
1507
1849
  }
1508
- return new FuelError3(ErrorCode.INVALID_REQUEST, error.message, {}, error);
1850
+ if (gqlErrorMessage.RPC_CONSISTENCY.test(error.message)) {
1851
+ return new FuelError3(ErrorCode2.RPC_CONSISTENCY, error.message, {}, error);
1852
+ }
1853
+ if (gqlErrorMessage.INSUFFICIENT_FEE_AMOUNT.test(error.message)) {
1854
+ const match = error.message.match(gqlErrorMessage.INSUFFICIENT_FEE_AMOUNT);
1855
+ return new FuelError3(ErrorCode2.FUNDS_TOO_LOW, match?.[0] || error.message, {}, error);
1856
+ }
1857
+ return new FuelError3(ErrorCode2.INVALID_REQUEST, error.message, {}, error);
1509
1858
  }, "mapGqlErrorMessage");
1510
1859
  var mapGqlErrorWithIncompatibleNodeVersion = /* @__PURE__ */ __name((error, incompatibleNodeVersionMessage) => {
1511
1860
  if (!incompatibleNodeVersionMessage) {
@@ -1530,15 +1879,16 @@ var assertGqlResponseHasNoErrors = /* @__PURE__ */ __name((errors, incompatibleN
1530
1879
  }
1531
1880
  const errorMessage = mappedErrors.map((err) => err.message).join("\n");
1532
1881
  throw mapGqlErrorWithIncompatibleNodeVersion(
1533
- new FuelError3(ErrorCode.INVALID_REQUEST, errorMessage, {}, mappedErrors),
1882
+ new FuelError3(ErrorCode2.INVALID_REQUEST, errorMessage, {}, mappedErrors),
1534
1883
  incompatibleNodeVersionMessage
1535
1884
  );
1536
1885
  }, "assertGqlResponseHasNoErrors");
1537
1886
 
1538
1887
  // src/providers/fuel-graphql-subscriber.ts
1539
1888
  var FuelGraphqlSubscriber = class _FuelGraphqlSubscriber {
1540
- constructor(stream) {
1889
+ constructor(stream, onEvent) {
1541
1890
  this.stream = stream;
1891
+ this.onEvent = onEvent;
1542
1892
  }
1543
1893
  static {
1544
1894
  __name(this, "FuelGraphqlSubscriber");
@@ -1546,12 +1896,13 @@ var FuelGraphqlSubscriber = class _FuelGraphqlSubscriber {
1546
1896
  static incompatibleNodeVersionMessage = false;
1547
1897
  static textDecoder = new TextDecoder();
1548
1898
  static async create(options) {
1549
- const { url, query, variables, fetchFn } = options;
1899
+ const { url, query, variables, fetchFn, operationName, onEvent } = options;
1550
1900
  const response = await fetchFn(`${url}-sub`, {
1551
1901
  method: "POST",
1552
1902
  body: JSON.stringify({
1553
1903
  query: print(query),
1554
- variables
1904
+ variables,
1905
+ operationName
1555
1906
  }),
1556
1907
  headers: {
1557
1908
  "Content-Type": "application/json",
@@ -1560,39 +1911,71 @@ var FuelGraphqlSubscriber = class _FuelGraphqlSubscriber {
1560
1911
  });
1561
1912
  const [errorReader, resultReader] = response.body.tee().map((stream) => stream.getReader());
1562
1913
  await new _FuelGraphqlSubscriber(errorReader).next();
1563
- return new _FuelGraphqlSubscriber(resultReader);
1914
+ return new _FuelGraphqlSubscriber(resultReader, onEvent);
1564
1915
  }
1565
- events = [];
1566
- parsingLeftover = "";
1567
- async next() {
1916
+ /**
1917
+ * This method will take a stream reader and parse the event from the stream.
1918
+ *
1919
+ * @param reader - The reader of the SSE stream
1920
+ * @param parsingLeftover - The leftover string from parsing the previous event
1921
+ * @returns The event parsed as a full GraphQL response, whether the stream is done and the leftover string after parsing
1922
+ */
1923
+ static async readEvent(reader, parsingLeftover = "") {
1924
+ let text = parsingLeftover;
1925
+ const regex = /data:.*\n\n/g;
1568
1926
  while (true) {
1569
- if (this.events.length > 0) {
1570
- const { data, errors } = this.events.shift();
1571
- assertGqlResponseHasNoErrors(errors, _FuelGraphqlSubscriber.incompatibleNodeVersionMessage);
1572
- return { value: data, done: false };
1573
- }
1574
- const { value, done } = await this.stream.read();
1575
- if (done) {
1576
- return { value, done };
1577
- }
1578
- const decoded = _FuelGraphqlSubscriber.textDecoder.decode(value).replace(":keep-alive-text\n\n", "");
1579
- if (decoded === "") {
1580
- continue;
1581
- }
1582
- const text = `${this.parsingLeftover}${decoded}`;
1583
- const regex = /data:.*\n\n/g;
1584
1927
  const matches = [...text.matchAll(regex)].flatMap((match) => match);
1585
- matches.forEach((match) => {
1928
+ if (matches.length > 0) {
1586
1929
  try {
1587
- this.events.push(JSON.parse(match.replace(/^data:/, "")));
1930
+ const event = JSON.parse(matches[0].replace(/^data:/, ""));
1931
+ return {
1932
+ event,
1933
+ done: false,
1934
+ parsingLeftover: text.replace(matches[0], "")
1935
+ };
1588
1936
  } catch (e) {
1589
1937
  throw new FuelError4(
1590
- ErrorCode2.STREAM_PARSING_ERROR,
1938
+ ErrorCode3.STREAM_PARSING_ERROR,
1591
1939
  `Error while parsing stream data response: ${text}`
1592
1940
  );
1593
1941
  }
1594
- });
1595
- this.parsingLeftover = text.replace(matches.join(), "");
1942
+ }
1943
+ const { value, done } = await reader.read();
1944
+ if (done) {
1945
+ return { event: void 0, done, parsingLeftover: "" };
1946
+ }
1947
+ const decoded = _FuelGraphqlSubscriber.textDecoder.decode(value).replace(":keep-alive-text\n\n", "");
1948
+ text += decoded;
1949
+ }
1950
+ }
1951
+ events = [];
1952
+ parsingLeftover = "";
1953
+ /**
1954
+ * Gets automatically called when iterating in a `for-await-of` loop.
1955
+ * It can also be called manually.
1956
+ *
1957
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/next
1958
+ */
1959
+ async next() {
1960
+ while (true) {
1961
+ const nextEvent = this.events.shift();
1962
+ if (nextEvent) {
1963
+ this.onEvent?.(nextEvent);
1964
+ assertGqlResponseHasNoErrors(
1965
+ nextEvent.errors,
1966
+ _FuelGraphqlSubscriber.incompatibleNodeVersionMessage
1967
+ );
1968
+ return { value: nextEvent.data, done: false };
1969
+ }
1970
+ const { event, done, parsingLeftover } = await _FuelGraphqlSubscriber.readEvent(
1971
+ this.stream,
1972
+ this.parsingLeftover
1973
+ );
1974
+ this.parsingLeftover = parsingLeftover;
1975
+ if (done) {
1976
+ return { value: void 0, done: true };
1977
+ }
1978
+ this.events.push(event);
1596
1979
  }
1597
1980
  }
1598
1981
  /**
@@ -1607,16 +1990,16 @@ var FuelGraphqlSubscriber = class _FuelGraphqlSubscriber {
1607
1990
  };
1608
1991
 
1609
1992
  // src/providers/resource-cache.ts
1610
- import { FuelError as FuelError14, ErrorCode as ErrorCode10 } from "@fuel-ts/errors";
1611
- import { hexlify as hexlify16 } from "@fuel-ts/utils";
1993
+ import { FuelError as FuelError14, ErrorCode as ErrorCode11 } from "@fuel-ts/errors";
1994
+ import { hexlify as hexlify17 } from "@fuel-ts/utils";
1612
1995
 
1613
1996
  // src/providers/transaction-request/input.ts
1614
1997
  import { BYTES_32 as BYTES_322, UTXO_ID_LEN } from "@fuel-ts/abi-coder";
1615
1998
  import { ZeroBytes32 } from "@fuel-ts/address/configs";
1616
- import { ErrorCode as ErrorCode3, FuelError as FuelError5 } from "@fuel-ts/errors";
1617
- import { bn as bn2, toNumber } from "@fuel-ts/math";
1999
+ import { ErrorCode as ErrorCode4, FuelError as FuelError5 } from "@fuel-ts/errors";
2000
+ import { bn as bn3, toNumber } from "@fuel-ts/math";
1618
2001
  import { InputType } from "@fuel-ts/transactions";
1619
- import { arrayify as arrayify2, hexlify as hexlify4 } from "@fuel-ts/utils";
2002
+ import { arrayify as arrayify2, hexlify as hexlify5 } from "@fuel-ts/utils";
1620
2003
  var inputify = /* @__PURE__ */ __name((value) => {
1621
2004
  const { type } = value;
1622
2005
  switch (value.type) {
@@ -1625,27 +2008,27 @@ var inputify = /* @__PURE__ */ __name((value) => {
1625
2008
  const predicateData = arrayify2(value.predicateData ?? "0x");
1626
2009
  return {
1627
2010
  type: InputType.Coin,
1628
- txID: hexlify4(arrayify2(value.id).slice(0, BYTES_322)),
2011
+ txID: hexlify5(arrayify2(value.id).slice(0, BYTES_322)),
1629
2012
  outputIndex: toNumber(arrayify2(value.id).slice(BYTES_322, UTXO_ID_LEN)),
1630
- owner: hexlify4(value.owner),
1631
- amount: bn2(value.amount),
1632
- assetId: hexlify4(value.assetId),
2013
+ owner: hexlify5(value.owner),
2014
+ amount: bn3(value.amount),
2015
+ assetId: hexlify5(value.assetId),
1633
2016
  txPointer: {
1634
2017
  blockHeight: toNumber(arrayify2(value.txPointer).slice(0, 8)),
1635
2018
  txIndex: toNumber(arrayify2(value.txPointer).slice(8, 16))
1636
2019
  },
1637
2020
  witnessIndex: value.witnessIndex,
1638
- predicateGasUsed: bn2(value.predicateGasUsed),
1639
- predicateLength: bn2(predicate.length),
1640
- predicateDataLength: bn2(predicateData.length),
1641
- predicate: hexlify4(predicate),
1642
- predicateData: hexlify4(predicateData)
2021
+ predicateGasUsed: bn3(value.predicateGasUsed),
2022
+ predicateLength: bn3(predicate.length),
2023
+ predicateDataLength: bn3(predicateData.length),
2024
+ predicate: hexlify5(predicate),
2025
+ predicateData: hexlify5(predicateData)
1643
2026
  };
1644
2027
  }
1645
2028
  case InputType.Contract: {
1646
2029
  return {
1647
2030
  type: InputType.Contract,
1648
- txID: ZeroBytes32,
2031
+ txID: hexlify5(value.txID || ZeroBytes32),
1649
2032
  outputIndex: 0,
1650
2033
  balanceRoot: ZeroBytes32,
1651
2034
  stateRoot: ZeroBytes32,
@@ -1653,7 +2036,7 @@ var inputify = /* @__PURE__ */ __name((value) => {
1653
2036
  blockHeight: toNumber(arrayify2(value.txPointer).slice(0, 8)),
1654
2037
  txIndex: toNumber(arrayify2(value.txPointer).slice(8, 16))
1655
2038
  },
1656
- contractID: hexlify4(value.contractId)
2039
+ contractID: hexlify5(value.contractId)
1657
2040
  };
1658
2041
  }
1659
2042
  case InputType.Message: {
@@ -1662,23 +2045,23 @@ var inputify = /* @__PURE__ */ __name((value) => {
1662
2045
  const data = arrayify2(value.data ?? "0x");
1663
2046
  return {
1664
2047
  type: InputType.Message,
1665
- sender: hexlify4(value.sender),
1666
- recipient: hexlify4(value.recipient),
1667
- amount: bn2(value.amount),
1668
- nonce: hexlify4(value.nonce),
2048
+ sender: hexlify5(value.sender),
2049
+ recipient: hexlify5(value.recipient),
2050
+ amount: bn3(value.amount),
2051
+ nonce: hexlify5(value.nonce),
1669
2052
  witnessIndex: value.witnessIndex,
1670
- predicateGasUsed: bn2(value.predicateGasUsed),
1671
- predicateLength: bn2(predicate.length),
1672
- predicateDataLength: bn2(predicateData.length),
1673
- predicate: hexlify4(predicate),
1674
- predicateData: hexlify4(predicateData),
1675
- data: hexlify4(data),
2053
+ predicateGasUsed: bn3(value.predicateGasUsed),
2054
+ predicateLength: bn3(predicate.length),
2055
+ predicateDataLength: bn3(predicateData.length),
2056
+ predicate: hexlify5(predicate),
2057
+ predicateData: hexlify5(predicateData),
2058
+ data: hexlify5(data),
1676
2059
  dataLength: data.length
1677
2060
  };
1678
2061
  }
1679
2062
  default: {
1680
2063
  throw new FuelError5(
1681
- ErrorCode3.INVALID_TRANSACTION_INPUT,
2064
+ ErrorCode4.INVALID_TRANSACTION_INPUT,
1682
2065
  `Invalid transaction input type: ${type}.`
1683
2066
  );
1684
2067
  }
@@ -1687,19 +2070,19 @@ var inputify = /* @__PURE__ */ __name((value) => {
1687
2070
 
1688
2071
  // src/providers/transaction-request/output.ts
1689
2072
  import { ZeroBytes32 as ZeroBytes322 } from "@fuel-ts/address/configs";
1690
- import { ErrorCode as ErrorCode4, FuelError as FuelError6 } from "@fuel-ts/errors";
1691
- import { bn as bn3 } from "@fuel-ts/math";
2073
+ import { ErrorCode as ErrorCode5, FuelError as FuelError6 } from "@fuel-ts/errors";
2074
+ import { bn as bn4 } from "@fuel-ts/math";
1692
2075
  import { OutputType } from "@fuel-ts/transactions";
1693
- import { hexlify as hexlify5 } from "@fuel-ts/utils";
2076
+ import { hexlify as hexlify6 } from "@fuel-ts/utils";
1694
2077
  var outputify = /* @__PURE__ */ __name((value) => {
1695
2078
  const { type } = value;
1696
2079
  switch (type) {
1697
2080
  case OutputType.Coin: {
1698
2081
  return {
1699
2082
  type: OutputType.Coin,
1700
- to: hexlify5(value.to),
1701
- amount: bn3(value.amount),
1702
- assetId: hexlify5(value.assetId)
2083
+ to: hexlify6(value.to),
2084
+ amount: bn4(value.amount),
2085
+ assetId: hexlify6(value.assetId)
1703
2086
  };
1704
2087
  }
1705
2088
  case OutputType.Contract: {
@@ -1713,29 +2096,29 @@ var outputify = /* @__PURE__ */ __name((value) => {
1713
2096
  case OutputType.Change: {
1714
2097
  return {
1715
2098
  type: OutputType.Change,
1716
- to: hexlify5(value.to),
1717
- amount: bn3(0),
1718
- assetId: hexlify5(value.assetId)
2099
+ to: hexlify6(value.to),
2100
+ amount: bn4(0),
2101
+ assetId: hexlify6(value.assetId)
1719
2102
  };
1720
2103
  }
1721
2104
  case OutputType.Variable: {
1722
2105
  return {
1723
2106
  type: OutputType.Variable,
1724
- to: ZeroBytes322,
1725
- amount: bn3(0),
1726
- assetId: ZeroBytes322
2107
+ to: hexlify6(value.to || ZeroBytes322),
2108
+ amount: bn4(value.amount),
2109
+ assetId: hexlify6(value.assetId || ZeroBytes322)
1727
2110
  };
1728
2111
  }
1729
2112
  case OutputType.ContractCreated: {
1730
2113
  return {
1731
2114
  type: OutputType.ContractCreated,
1732
- contractId: hexlify5(value.contractId),
1733
- stateRoot: hexlify5(value.stateRoot)
2115
+ contractId: hexlify6(value.contractId),
2116
+ stateRoot: hexlify6(value.stateRoot)
1734
2117
  };
1735
2118
  }
1736
2119
  default: {
1737
2120
  throw new FuelError6(
1738
- ErrorCode4.INVALID_TRANSACTION_INPUT,
2121
+ ErrorCode5.INVALID_TRANSACTION_INPUT,
1739
2122
  `Invalid transaction output type: ${type}.`
1740
2123
  );
1741
2124
  }
@@ -1748,15 +2131,15 @@ import { Address as Address2, addressify } from "@fuel-ts/address";
1748
2131
  import { ZeroBytes32 as ZeroBytes324 } from "@fuel-ts/address/configs";
1749
2132
  import { randomBytes as randomBytes3 } from "@fuel-ts/crypto";
1750
2133
  import { FuelError as FuelError11 } from "@fuel-ts/errors";
1751
- import { bn as bn8 } from "@fuel-ts/math";
2134
+ import { bn as bn9 } from "@fuel-ts/math";
1752
2135
  import {
1753
2136
  PolicyType,
1754
2137
  TransactionCoder,
1755
- InputType as InputType3,
1756
- OutputType as OutputType3,
1757
- TransactionType
2138
+ InputType as InputType4,
2139
+ OutputType as OutputType4,
2140
+ TransactionType as TransactionType2
1758
2141
  } from "@fuel-ts/transactions";
1759
- import { concat as concat2, hexlify as hexlify10, isDefined } from "@fuel-ts/utils";
2142
+ import { concat as concat2, hexlify as hexlify11, isDefined as isDefined2 } from "@fuel-ts/utils";
1760
2143
 
1761
2144
  // src/providers/message.ts
1762
2145
  var isMessageCoin = /* @__PURE__ */ __name((message) => !("data" in message), "isMessageCoin");
@@ -1770,10 +2153,16 @@ import { FAILED_TRANSFER_TO_ADDRESS_SIGNAL } from "@fuel-ts/transactions/configs
1770
2153
 
1771
2154
  // src/providers/utils/serialization.ts
1772
2155
  import { ZeroBytes32 as ZeroBytes323 } from "@fuel-ts/address/configs";
1773
- import { ErrorCode as ErrorCode5, FuelError as FuelError7 } from "@fuel-ts/errors";
1774
- import { bn as bn4 } from "@fuel-ts/math";
1775
- import { getMintedAssetId, InputMessageCoder, ReceiptType } from "@fuel-ts/transactions";
1776
- import { hexlify as hexlify6, arrayify as arrayify3 } from "@fuel-ts/utils";
2156
+ import { ErrorCode as ErrorCode6, FuelError as FuelError7 } from "@fuel-ts/errors";
2157
+ import { bn as bn5 } from "@fuel-ts/math";
2158
+ import {
2159
+ getMintedAssetId,
2160
+ InputMessageCoder,
2161
+ InputType as InputType2,
2162
+ OutputType as OutputType2,
2163
+ ReceiptType
2164
+ } from "@fuel-ts/transactions";
2165
+ import { hexlify as hexlify7, arrayify as arrayify3, assertUnreachable } from "@fuel-ts/utils";
1777
2166
  var deserializeChain = /* @__PURE__ */ __name((chain) => {
1778
2167
  const { name, daHeight, consensusParameters } = chain;
1779
2168
  const {
@@ -1789,41 +2178,41 @@ var deserializeChain = /* @__PURE__ */ __name((chain) => {
1789
2178
  } = consensusParameters;
1790
2179
  return {
1791
2180
  name,
1792
- baseChainHeight: bn4(daHeight),
2181
+ baseChainHeight: bn5(daHeight),
1793
2182
  consensusParameters: {
1794
2183
  version,
1795
- chainId: bn4(chainId),
2184
+ chainId: bn5(chainId),
1796
2185
  baseAssetId,
1797
2186
  feeParameters: {
1798
2187
  version: feeParams.version,
1799
- gasPerByte: bn4(feeParams.gasPerByte),
1800
- gasPriceFactor: bn4(feeParams.gasPriceFactor)
2188
+ gasPerByte: bn5(feeParams.gasPerByte),
2189
+ gasPriceFactor: bn5(feeParams.gasPriceFactor)
1801
2190
  },
1802
2191
  contractParameters: {
1803
2192
  version: contractParams.version,
1804
- contractMaxSize: bn4(contractParams.contractMaxSize),
1805
- maxStorageSlots: bn4(contractParams.maxStorageSlots)
2193
+ contractMaxSize: bn5(contractParams.contractMaxSize),
2194
+ maxStorageSlots: bn5(contractParams.maxStorageSlots)
1806
2195
  },
1807
2196
  txParameters: {
1808
2197
  version: txParams.version,
1809
- maxInputs: bn4(txParams.maxInputs),
1810
- maxOutputs: bn4(txParams.maxOutputs),
1811
- maxWitnesses: bn4(txParams.maxWitnesses),
1812
- maxGasPerTx: bn4(txParams.maxGasPerTx),
1813
- maxSize: bn4(txParams.maxSize),
1814
- maxBytecodeSubsections: bn4(txParams.maxBytecodeSubsections)
2198
+ maxInputs: bn5(txParams.maxInputs),
2199
+ maxOutputs: bn5(txParams.maxOutputs),
2200
+ maxWitnesses: bn5(txParams.maxWitnesses),
2201
+ maxGasPerTx: bn5(txParams.maxGasPerTx),
2202
+ maxSize: bn5(txParams.maxSize),
2203
+ maxBytecodeSubsections: bn5(txParams.maxBytecodeSubsections)
1815
2204
  },
1816
2205
  predicateParameters: {
1817
2206
  version: predicateParams.version,
1818
- maxPredicateLength: bn4(predicateParams.maxPredicateLength),
1819
- maxPredicateDataLength: bn4(predicateParams.maxPredicateDataLength),
1820
- maxGasPerPredicate: bn4(predicateParams.maxGasPerPredicate),
1821
- maxMessageDataLength: bn4(predicateParams.maxMessageDataLength)
2207
+ maxPredicateLength: bn5(predicateParams.maxPredicateLength),
2208
+ maxPredicateDataLength: bn5(predicateParams.maxPredicateDataLength),
2209
+ maxGasPerPredicate: bn5(predicateParams.maxGasPerPredicate),
2210
+ maxMessageDataLength: bn5(predicateParams.maxMessageDataLength)
1822
2211
  },
1823
2212
  scriptParameters: {
1824
2213
  version: scriptParams.version,
1825
- maxScriptLength: bn4(scriptParams.maxScriptLength),
1826
- maxScriptDataLength: bn4(scriptParams.maxScriptDataLength)
2214
+ maxScriptLength: bn5(scriptParams.maxScriptLength),
2215
+ maxScriptDataLength: bn5(scriptParams.maxScriptDataLength)
1827
2216
  },
1828
2217
  gasCosts
1829
2218
  }
@@ -1887,8 +2276,8 @@ var serializeChain = /* @__PURE__ */ __name((chain) => {
1887
2276
  var deserializeNodeInfo = /* @__PURE__ */ __name((nodeInfo) => {
1888
2277
  const { maxDepth, maxTx, nodeVersion, utxoValidation, vmBacktrace, indexation } = nodeInfo;
1889
2278
  return {
1890
- maxDepth: bn4(maxDepth),
1891
- maxTx: bn4(maxTx),
2279
+ maxDepth: bn5(maxDepth),
2280
+ maxTx: bn5(maxTx),
1892
2281
  nodeVersion,
1893
2282
  utxoValidation,
1894
2283
  vmBacktrace,
@@ -1926,13 +2315,13 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1926
2315
  type: ReceiptType.Call,
1927
2316
  id,
1928
2317
  to: hexOrZero(receipt?.to),
1929
- amount: bn4(receipt.amount),
2318
+ amount: bn5(receipt.amount),
1930
2319
  assetId: hexOrZero(receipt.assetId),
1931
- gas: bn4(receipt.gas),
1932
- param1: bn4(receipt.param1),
1933
- param2: bn4(receipt.param2),
1934
- pc: bn4(receipt.pc),
1935
- is: bn4(receipt.is)
2320
+ gas: bn5(receipt.gas),
2321
+ param1: bn5(receipt.param1),
2322
+ param2: bn5(receipt.param2),
2323
+ pc: bn5(receipt.pc),
2324
+ is: bn5(receipt.is)
1936
2325
  };
1937
2326
  return callReceipt;
1938
2327
  }
@@ -1940,9 +2329,9 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1940
2329
  const returnReceipt = {
1941
2330
  type: ReceiptType.Return,
1942
2331
  id: hexOrZero(receipt.id || receipt.contractId),
1943
- val: bn4(receipt.val),
1944
- pc: bn4(receipt.pc),
1945
- is: bn4(receipt.is)
2332
+ val: bn5(receipt.val),
2333
+ pc: bn5(receipt.pc),
2334
+ is: bn5(receipt.is)
1946
2335
  };
1947
2336
  return returnReceipt;
1948
2337
  }
@@ -1950,12 +2339,12 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1950
2339
  const returnDataReceipt = {
1951
2340
  type: ReceiptType.ReturnData,
1952
2341
  id: hexOrZero(receipt.id || receipt.contractId),
1953
- ptr: bn4(receipt.ptr),
1954
- len: bn4(receipt.len),
2342
+ ptr: bn5(receipt.ptr),
2343
+ len: bn5(receipt.len),
1955
2344
  digest: hexOrZero(receipt.digest),
1956
- pc: bn4(receipt.pc),
2345
+ pc: bn5(receipt.pc),
1957
2346
  data: hexOrZero(receipt.data),
1958
- is: bn4(receipt.is)
2347
+ is: bn5(receipt.is)
1959
2348
  };
1960
2349
  return returnDataReceipt;
1961
2350
  }
@@ -1963,9 +2352,9 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1963
2352
  const panicReceipt = {
1964
2353
  type: ReceiptType.Panic,
1965
2354
  id: hexOrZero(receipt.id),
1966
- reason: bn4(receipt.reason),
1967
- pc: bn4(receipt.pc),
1968
- is: bn4(receipt.is),
2355
+ reason: bn5(receipt.reason),
2356
+ pc: bn5(receipt.pc),
2357
+ is: bn5(receipt.is),
1969
2358
  contractId: hexOrZero(receipt.contractId)
1970
2359
  };
1971
2360
  return panicReceipt;
@@ -1974,17 +2363,17 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1974
2363
  const revertReceipt = {
1975
2364
  type: ReceiptType.Revert,
1976
2365
  id: hexOrZero(receipt.id || receipt.contractId),
1977
- val: bn4(receipt.ra),
1978
- pc: bn4(receipt.pc),
1979
- is: bn4(receipt.is)
2366
+ val: bn5(receipt.ra),
2367
+ pc: bn5(receipt.pc),
2368
+ is: bn5(receipt.is)
1980
2369
  };
1981
2370
  return revertReceipt;
1982
2371
  }
1983
2372
  case "LOG" /* Log */: {
1984
- const ra = bn4(receipt.ra);
1985
- const rb = bn4(receipt.rb);
1986
- const rc = bn4(receipt.rc);
1987
- const rd = bn4(receipt.rd);
2373
+ const ra = bn5(receipt.ra);
2374
+ const rb = bn5(receipt.rb);
2375
+ const rc = bn5(receipt.rc);
2376
+ const rd = bn5(receipt.rd);
1988
2377
  const logReceipt = {
1989
2378
  type: ReceiptType.Log,
1990
2379
  id: hexOrZero(receipt.id || receipt.contractId),
@@ -1992,25 +2381,25 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
1992
2381
  rb,
1993
2382
  rc,
1994
2383
  rd,
1995
- pc: bn4(receipt.pc),
1996
- is: bn4(receipt.is)
2384
+ pc: bn5(receipt.pc),
2385
+ is: bn5(receipt.is)
1997
2386
  };
1998
2387
  return logReceipt;
1999
2388
  }
2000
2389
  case "LOG_DATA" /* LogData */: {
2001
- const ra = bn4(receipt.ra);
2002
- const rb = bn4(receipt.rb);
2390
+ const ra = bn5(receipt.ra);
2391
+ const rb = bn5(receipt.rb);
2003
2392
  const logDataReceipt = {
2004
2393
  type: ReceiptType.LogData,
2005
2394
  id: hexOrZero(receipt.id || receipt.contractId),
2006
2395
  ra,
2007
2396
  rb,
2008
- ptr: bn4(receipt.ptr),
2009
- len: bn4(receipt.len),
2397
+ ptr: bn5(receipt.ptr),
2398
+ len: bn5(receipt.len),
2010
2399
  digest: hexOrZero(receipt.digest),
2011
- pc: bn4(receipt.pc),
2400
+ pc: bn5(receipt.pc),
2012
2401
  data: hexOrZero(receipt.data),
2013
- is: bn4(receipt.is)
2402
+ is: bn5(receipt.is)
2014
2403
  };
2015
2404
  return logDataReceipt;
2016
2405
  }
@@ -2020,10 +2409,10 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
2020
2409
  type: ReceiptType.Transfer,
2021
2410
  id,
2022
2411
  to: hexOrZero(receipt.toAddress || receipt?.to),
2023
- amount: bn4(receipt.amount),
2412
+ amount: bn5(receipt.amount),
2024
2413
  assetId: hexOrZero(receipt.assetId),
2025
- pc: bn4(receipt.pc),
2026
- is: bn4(receipt.is)
2414
+ pc: bn5(receipt.pc),
2415
+ is: bn5(receipt.is)
2027
2416
  };
2028
2417
  return transferReceipt;
2029
2418
  }
@@ -2033,18 +2422,18 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
2033
2422
  type: ReceiptType.TransferOut,
2034
2423
  id,
2035
2424
  to: hexOrZero(receipt.toAddress || receipt.to),
2036
- amount: bn4(receipt.amount),
2425
+ amount: bn5(receipt.amount),
2037
2426
  assetId: hexOrZero(receipt.assetId),
2038
- pc: bn4(receipt.pc),
2039
- is: bn4(receipt.is)
2427
+ pc: bn5(receipt.pc),
2428
+ is: bn5(receipt.is)
2040
2429
  };
2041
2430
  return transferOutReceipt;
2042
2431
  }
2043
2432
  case "SCRIPT_RESULT" /* ScriptResult */: {
2044
2433
  const scriptResultReceipt = {
2045
2434
  type: ReceiptType.ScriptResult,
2046
- result: bn4(receipt.result),
2047
- gasUsed: bn4(receipt.gasUsed)
2435
+ result: bn5(receipt.result),
2436
+ gasUsed: bn5(receipt.gasUsed)
2048
2437
  };
2049
2438
  return scriptResultReceipt;
2050
2439
  }
@@ -2052,16 +2441,16 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
2052
2441
  const sender = hexOrZero(receipt.sender);
2053
2442
  const recipient = hexOrZero(receipt.recipient);
2054
2443
  const nonce = hexOrZero(receipt.nonce);
2055
- const amount = bn4(receipt.amount);
2444
+ const amount = bn5(receipt.amount);
2056
2445
  const data = receipt.data ? arrayify3(receipt.data) : Uint8Array.from([]);
2057
2446
  const digest = hexOrZero(receipt.digest);
2058
- const len = bn4(receipt.len).toNumber();
2447
+ const len = bn5(receipt.len).toNumber();
2059
2448
  const messageId = InputMessageCoder.getMessageId({
2060
2449
  sender,
2061
2450
  recipient,
2062
2451
  nonce,
2063
2452
  amount,
2064
- data: hexlify6(data)
2453
+ data: hexlify7(data)
2065
2454
  });
2066
2455
  const receiptMessageOut = {
2067
2456
  type: ReceiptType.MessageOut,
@@ -2085,9 +2474,9 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
2085
2474
  subId,
2086
2475
  contractId,
2087
2476
  assetId,
2088
- val: bn4(receipt.val),
2089
- pc: bn4(receipt.pc),
2090
- is: bn4(receipt.is)
2477
+ val: bn5(receipt.val),
2478
+ pc: bn5(receipt.pc),
2479
+ is: bn5(receipt.is)
2091
2480
  };
2092
2481
  return mintReceipt;
2093
2482
  }
@@ -2100,16 +2489,151 @@ var deserializeReceipt = /* @__PURE__ */ __name((receipt) => {
2100
2489
  subId,
2101
2490
  contractId,
2102
2491
  assetId,
2103
- val: bn4(receipt.val),
2104
- pc: bn4(receipt.pc),
2105
- is: bn4(receipt.is)
2492
+ val: bn5(receipt.val),
2493
+ pc: bn5(receipt.pc),
2494
+ is: bn5(receipt.is)
2106
2495
  };
2107
2496
  return burnReceipt;
2108
2497
  }
2109
2498
  default:
2110
- throw new FuelError7(ErrorCode5.INVALID_RECEIPT_TYPE, `Invalid receipt type: ${receiptType}.`);
2499
+ throw new FuelError7(ErrorCode6.INVALID_RECEIPT_TYPE, `Invalid receipt type: ${receiptType}.`);
2111
2500
  }
2112
2501
  }, "deserializeReceipt");
2502
+ var deserializeInput = /* @__PURE__ */ __name((input) => {
2503
+ let parsedInput;
2504
+ switch (input.type) {
2505
+ case "InputCoin":
2506
+ parsedInput = {
2507
+ type: InputType2.Coin,
2508
+ id: input.utxoId,
2509
+ amount: bn5(input.amount),
2510
+ assetId: input.assetId,
2511
+ owner: input.owner,
2512
+ txPointer: `0x${input.txPointer}`,
2513
+ witnessIndex: Number(input.coinWitnessIndex),
2514
+ predicate: input.predicate,
2515
+ predicateData: input.predicateData,
2516
+ predicateGasUsed: bn5(input.predicateGasUsed)
2517
+ };
2518
+ break;
2519
+ case "InputMessage":
2520
+ parsedInput = {
2521
+ type: InputType2.Message,
2522
+ nonce: input.nonce,
2523
+ amount: bn5(input.amount),
2524
+ recipient: input.recipient,
2525
+ sender: input.sender,
2526
+ data: input.data,
2527
+ witnessIndex: Number(input.messageWitnessIndex),
2528
+ predicate: input.predicate,
2529
+ predicateData: input.predicateData,
2530
+ predicateGasUsed: bn5(input.predicateGasUsed)
2531
+ };
2532
+ break;
2533
+ case "InputContract":
2534
+ parsedInput = {
2535
+ type: InputType2.Contract,
2536
+ contractId: input.contractId,
2537
+ txPointer: `0x${input.txPointer}`,
2538
+ txID: hexlify7(arrayify3(input.utxoId).slice(0, 32))
2539
+ };
2540
+ break;
2541
+ default:
2542
+ assertUnreachable(input);
2543
+ }
2544
+ return parsedInput;
2545
+ }, "deserializeInput");
2546
+ var deserializeOutput = /* @__PURE__ */ __name((output) => {
2547
+ let parsedOutput;
2548
+ switch (output.type) {
2549
+ case "CoinOutput":
2550
+ parsedOutput = {
2551
+ type: OutputType2.Coin,
2552
+ amount: bn5(output.amount),
2553
+ assetId: output.assetId,
2554
+ to: output.to
2555
+ };
2556
+ break;
2557
+ case "ContractOutput":
2558
+ parsedOutput = {
2559
+ type: OutputType2.Contract,
2560
+ inputIndex: Number(output.inputIndex)
2561
+ };
2562
+ break;
2563
+ case "ChangeOutput":
2564
+ parsedOutput = {
2565
+ type: OutputType2.Change,
2566
+ assetId: output.assetId,
2567
+ to: output.to
2568
+ };
2569
+ break;
2570
+ case "ContractCreated":
2571
+ parsedOutput = {
2572
+ type: OutputType2.ContractCreated,
2573
+ stateRoot: output.stateRoot,
2574
+ contractId: output.contract
2575
+ };
2576
+ break;
2577
+ case "VariableOutput":
2578
+ parsedOutput = {
2579
+ type: OutputType2.Variable,
2580
+ amount: bn5(output.amount),
2581
+ assetId: output.assetId,
2582
+ to: output.to
2583
+ };
2584
+ break;
2585
+ default:
2586
+ assertUnreachable(output);
2587
+ }
2588
+ return parsedOutput;
2589
+ }, "deserializeOutput");
2590
+ var deserializeProcessedTxOutput = /* @__PURE__ */ __name((output) => {
2591
+ let parsedOutput;
2592
+ switch (output.type) {
2593
+ case "CoinOutput":
2594
+ parsedOutput = {
2595
+ type: OutputType2.Coin,
2596
+ amount: bn5(output.amount),
2597
+ assetId: output.assetId,
2598
+ to: output.to
2599
+ };
2600
+ break;
2601
+ case "ContractOutput":
2602
+ parsedOutput = {
2603
+ type: OutputType2.Contract,
2604
+ inputIndex: Number(output.inputIndex),
2605
+ balanceRoot: output.balanceRoot,
2606
+ stateRoot: output.stateRoot
2607
+ };
2608
+ break;
2609
+ case "ChangeOutput":
2610
+ parsedOutput = {
2611
+ type: OutputType2.Change,
2612
+ assetId: output.assetId,
2613
+ to: output.to,
2614
+ amount: bn5(output.amount)
2615
+ };
2616
+ break;
2617
+ case "ContractCreated":
2618
+ parsedOutput = {
2619
+ type: OutputType2.ContractCreated,
2620
+ stateRoot: output.stateRoot,
2621
+ contractId: output.contract
2622
+ };
2623
+ break;
2624
+ case "VariableOutput":
2625
+ parsedOutput = {
2626
+ type: OutputType2.Variable,
2627
+ amount: bn5(output.amount),
2628
+ assetId: output.assetId,
2629
+ to: output.to
2630
+ };
2631
+ break;
2632
+ default:
2633
+ assertUnreachable(output);
2634
+ }
2635
+ return parsedOutput;
2636
+ }, "deserializeProcessedTxOutput");
2113
2637
 
2114
2638
  // src/providers/utils/receipts.ts
2115
2639
  var doesReceiptHaveMissingOutputVariables = /* @__PURE__ */ __name((receipt) => receipt.type === ReceiptType2.Revert && receipt.val.toString("hex") === FAILED_TRANSFER_TO_ADDRESS_SIGNAL, "doesReceiptHaveMissingOutputVariables");
@@ -2131,26 +2655,26 @@ var getReceiptsWithMissingData = /* @__PURE__ */ __name((receipts) => receipts.r
2131
2655
  ), "getReceiptsWithMissingData");
2132
2656
 
2133
2657
  // src/providers/utils/block-explorer.ts
2134
- import { ErrorCode as ErrorCode6, FuelError as FuelError8 } from "@fuel-ts/errors";
2658
+ import { ErrorCode as ErrorCode7, FuelError as FuelError8 } from "@fuel-ts/errors";
2135
2659
 
2136
2660
  // src/providers/utils/gas.ts
2137
- import { bn as bn5 } from "@fuel-ts/math";
2661
+ import { bn as bn6 } from "@fuel-ts/math";
2138
2662
  import { ReceiptType as ReceiptType3 } from "@fuel-ts/transactions";
2139
2663
  import { arrayify as arrayify4 } from "@fuel-ts/utils";
2140
2664
  var getGasUsedFromReceipts = /* @__PURE__ */ __name((receipts) => {
2141
2665
  const scriptResult = receipts.filter(
2142
2666
  (receipt) => receipt.type === ReceiptType3.ScriptResult
2143
2667
  );
2144
- const gasUsed = scriptResult.reduce((prev, receipt) => prev.add(receipt.gasUsed), bn5(0));
2668
+ const gasUsed = scriptResult.reduce((prev, receipt) => prev.add(receipt.gasUsed), bn6(0));
2145
2669
  return gasUsed;
2146
2670
  }, "getGasUsedFromReceipts");
2147
2671
  function resolveGasDependentCosts(byteSize, gasDependentCost) {
2148
- const base = bn5(gasDependentCost.base);
2149
- let dependentValue = bn5(0);
2672
+ const base = bn6(gasDependentCost.base);
2673
+ let dependentValue = bn6(0);
2150
2674
  if ("unitsPerGas" in gasDependentCost) {
2151
- dependentValue = bn5(byteSize).div(bn5(gasDependentCost.unitsPerGas));
2675
+ dependentValue = bn6(byteSize).div(bn6(gasDependentCost.unitsPerGas));
2152
2676
  } else {
2153
- dependentValue = bn5(byteSize).mul(bn5(gasDependentCost.gasPerUnit));
2677
+ dependentValue = bn6(byteSize).mul(bn6(gasDependentCost.gasPerUnit));
2154
2678
  }
2155
2679
  return base.add(dependentValue);
2156
2680
  }
@@ -2174,18 +2698,18 @@ function gasUsedByInputs(inputs, txBytesSize, gasCosts) {
2174
2698
  const totalGas = chargeableInputs.reduce((total, input) => {
2175
2699
  if ("predicate" in input && input.predicate && input.predicate !== "0x") {
2176
2700
  return total.add(
2177
- vmInitializationCost.add(resolveGasDependentCosts(arrayify4(input.predicate).length, gasCosts.contractRoot)).add(bn5(input.predicateGasUsed))
2701
+ vmInitializationCost.add(resolveGasDependentCosts(arrayify4(input.predicate).length, gasCosts.contractRoot)).add(bn6(input.predicateGasUsed))
2178
2702
  );
2179
2703
  }
2180
2704
  return total.add(gasCosts.ecr1);
2181
- }, bn5(0));
2705
+ }, bn6(0));
2182
2706
  return totalGas;
2183
2707
  }
2184
2708
  __name(gasUsedByInputs, "gasUsedByInputs");
2185
2709
  function getMinGas(params) {
2186
2710
  const { gasCosts, gasPerByte, inputs, metadataGas, txBytesSize } = params;
2187
2711
  const vmInitGas = resolveGasDependentCosts(txBytesSize, gasCosts.vmInitialization);
2188
- const bytesGas = bn5(txBytesSize).mul(gasPerByte);
2712
+ const bytesGas = bn6(txBytesSize).mul(gasPerByte);
2189
2713
  const inputsGas = gasUsedByInputs(inputs, txBytesSize, gasCosts);
2190
2714
  const minGas = vmInitGas.add(bytesGas).add(inputsGas).add(metadataGas).maxU64();
2191
2715
  return minGas;
@@ -2197,12 +2721,12 @@ function getMaxGas(params) {
2197
2721
  witnessesLength,
2198
2722
  witnessLimit,
2199
2723
  minGas,
2200
- gasLimit = bn5(0),
2724
+ gasLimit = bn6(0),
2201
2725
  maxGasPerTx
2202
2726
  } = params;
2203
- let remainingAllowedWitnessGas = bn5(0);
2727
+ let remainingAllowedWitnessGas = bn6(0);
2204
2728
  if (witnessLimit?.gt(0) && witnessLimit.gte(witnessesLength)) {
2205
- remainingAllowedWitnessGas = bn5(witnessLimit).sub(witnessesLength).mul(gasPerByte);
2729
+ remainingAllowedWitnessGas = bn6(witnessLimit).sub(witnessesLength).mul(gasPerByte);
2206
2730
  }
2207
2731
  const maxGas = remainingAllowedWitnessGas.add(minGas).add(gasLimit);
2208
2732
  return maxGas.gte(maxGasPerTx) ? maxGasPerTx : maxGas;
@@ -2217,7 +2741,7 @@ function calculateMetadataGasForTxCreate({
2217
2741
  const contractRootGas = resolveGasDependentCosts(contractBytesSize, gasCosts.contractRoot);
2218
2742
  const stateRootGas = resolveGasDependentCosts(stateRootSize, gasCosts.stateRoot);
2219
2743
  const txIdGas = resolveGasDependentCosts(txBytesSize, gasCosts.s256);
2220
- const contractIdInputSize = bn5(4 + 32 + 32 + 32);
2744
+ const contractIdInputSize = bn6(4 + 32 + 32 + 32);
2221
2745
  const contractIdGas = resolveGasDependentCosts(contractIdInputSize, gasCosts.s256);
2222
2746
  const metadataGas = contractRootGas.add(stateRootGas).add(txIdGas).add(contractIdGas);
2223
2747
  return metadataGas.maxU64();
@@ -2272,23 +2796,23 @@ function calculateMinGasForTxUpload({
2272
2796
  baseMinGas,
2273
2797
  subsectionSize
2274
2798
  }) {
2275
- const additionalStoragePerByte = bn5(gasCosts.newStoragePerByte).mul(subsectionSize);
2276
- return bn5(baseMinGas).add(additionalStoragePerByte);
2799
+ const additionalStoragePerByte = bn6(gasCosts.newStoragePerByte).mul(subsectionSize);
2800
+ return bn6(baseMinGas).add(additionalStoragePerByte);
2277
2801
  }
2278
2802
  __name(calculateMinGasForTxUpload, "calculateMinGasForTxUpload");
2279
2803
  var calculateGasFee = /* @__PURE__ */ __name((params) => {
2280
2804
  const { gas, gasPrice, priceFactor, tip } = params;
2281
- return gas.mul(gasPrice).div(priceFactor).add(bn5(tip));
2805
+ return gas.mul(gasPrice).div(priceFactor).add(bn6(tip));
2282
2806
  }, "calculateGasFee");
2283
2807
 
2284
2808
  // src/providers/utils/json.ts
2285
- import { hexlify as hexlify7 } from "@fuel-ts/utils";
2809
+ import { hexlify as hexlify8 } from "@fuel-ts/utils";
2286
2810
  import { clone } from "ramda";
2287
2811
  function normalize(object) {
2288
2812
  Object.keys(object).forEach((key) => {
2289
2813
  switch (object[key]?.constructor.name) {
2290
2814
  case "Uint8Array":
2291
- object[key] = hexlify7(object[key]);
2815
+ object[key] = hexlify8(object[key]);
2292
2816
  break;
2293
2817
  case "Array":
2294
2818
  object[key] = normalize(object[key]);
@@ -2315,8 +2839,8 @@ function normalizeJSON(root) {
2315
2839
  __name(normalizeJSON, "normalizeJSON");
2316
2840
 
2317
2841
  // src/providers/utils/extract-tx-error.ts
2318
- import { ErrorCode as ErrorCode7, FuelError as FuelError9 } from "@fuel-ts/errors";
2319
- import { bn as bn6 } from "@fuel-ts/math";
2842
+ import { ErrorCode as ErrorCode8, FuelError as FuelError9 } from "@fuel-ts/errors";
2843
+ import { bn as bn7 } from "@fuel-ts/math";
2320
2844
  import { ReceiptType as ReceiptType4 } from "@fuel-ts/transactions";
2321
2845
  import {
2322
2846
  FAILED_REQUIRE_SIGNAL,
@@ -2336,7 +2860,7 @@ You can read more about this error at:
2336
2860
 
2337
2861
  ${PANIC_DOC_URL}#variant.${statusReason}`;
2338
2862
  }
2339
- return new FuelError9(ErrorCode7.SCRIPT_REVERTED, errorMessage, {
2863
+ return new FuelError9(ErrorCode8.SCRIPT_REVERTED, errorMessage, {
2340
2864
  ...metadata,
2341
2865
  reason: statusReason
2342
2866
  });
@@ -2347,7 +2871,7 @@ var assembleRevertError = /* @__PURE__ */ __name((receipts, logs, metadata) => {
2347
2871
  const revertReceipt = receipts.find(({ type }) => type === ReceiptType4.Revert);
2348
2872
  let reason = "";
2349
2873
  if (revertReceipt) {
2350
- const reasonHex = bn6(revertReceipt.val).toHex();
2874
+ const reasonHex = bn7(revertReceipt.val).toHex();
2351
2875
  const lastLog = logs[logs.length - 1];
2352
2876
  const lastButOneLog = logs[logs.length - 2];
2353
2877
  switch (reasonHex) {
@@ -2378,7 +2902,7 @@ var assembleRevertError = /* @__PURE__ */ __name((receipts, logs, metadata) => {
2378
2902
  break;
2379
2903
  default:
2380
2904
  throw new FuelError9(
2381
- ErrorCode7.UNKNOWN,
2905
+ ErrorCode8.UNKNOWN,
2382
2906
  `The transaction reverted with an unknown reason: ${revertReceipt.val}`,
2383
2907
  {
2384
2908
  ...metadata,
@@ -2387,17 +2911,18 @@ var assembleRevertError = /* @__PURE__ */ __name((receipts, logs, metadata) => {
2387
2911
  );
2388
2912
  }
2389
2913
  }
2390
- return new FuelError9(ErrorCode7.SCRIPT_REVERTED, errorMessage, {
2914
+ return new FuelError9(ErrorCode8.SCRIPT_REVERTED, errorMessage, {
2391
2915
  ...metadata,
2392
2916
  reason
2393
2917
  });
2394
2918
  }, "assembleRevertError");
2395
2919
  var extractTxError = /* @__PURE__ */ __name((params) => {
2396
- const { receipts, statusReason, logs } = params;
2920
+ const { receipts, statusReason, logs, groupedLogs } = params;
2397
2921
  const isPanic = receipts.some(({ type }) => type === ReceiptType4.Panic);
2398
2922
  const isRevert = receipts.some(({ type }) => type === ReceiptType4.Revert);
2399
2923
  const metadata = {
2400
2924
  logs,
2925
+ groupedLogs,
2401
2926
  receipts,
2402
2927
  panic: isPanic,
2403
2928
  revert: isRevert,
@@ -2409,6 +2934,21 @@ var extractTxError = /* @__PURE__ */ __name((params) => {
2409
2934
  return assembleRevertError(receipts, logs, metadata);
2410
2935
  }, "extractTxError");
2411
2936
 
2937
+ // src/providers/utils/merge-quantities.ts
2938
+ var mergeQuantities = /* @__PURE__ */ __name((...coinQuantities) => {
2939
+ const resultMap = {};
2940
+ function addToMap({ amount, assetId }) {
2941
+ if (resultMap[assetId]) {
2942
+ resultMap[assetId] = resultMap[assetId].add(amount);
2943
+ } else {
2944
+ resultMap[assetId] = amount;
2945
+ }
2946
+ }
2947
+ __name(addToMap, "addToMap");
2948
+ coinQuantities.forEach((arr) => arr.forEach(addToMap));
2949
+ return Object.entries(resultMap).map(([assetId, amount]) => ({ assetId, amount }));
2950
+ }, "mergeQuantities");
2951
+
2412
2952
  // src/providers/transaction-request/errors.ts
2413
2953
  var NoWitnessAtIndexError = class extends Error {
2414
2954
  constructor(index) {
@@ -2423,18 +2963,18 @@ var NoWitnessAtIndexError = class extends Error {
2423
2963
  };
2424
2964
 
2425
2965
  // src/providers/transaction-request/helpers.ts
2426
- import { ErrorCode as ErrorCode8, FuelError as FuelError10 } from "@fuel-ts/errors";
2427
- import { bn as bn7 } from "@fuel-ts/math";
2428
- import { InputType as InputType2, OutputType as OutputType2 } from "@fuel-ts/transactions";
2429
- import { hexlify as hexlify8 } from "@fuel-ts/utils";
2430
- var isRequestInputCoin = /* @__PURE__ */ __name((input) => input.type === InputType2.Coin, "isRequestInputCoin");
2431
- var isRequestInputMessage = /* @__PURE__ */ __name((input) => input.type === InputType2.Message, "isRequestInputMessage");
2432
- var isRequestInputMessageWithoutData = /* @__PURE__ */ __name((input) => input.type === InputType2.Message && bn7(input.data).isZero(), "isRequestInputMessageWithoutData");
2966
+ import { ErrorCode as ErrorCode9, FuelError as FuelError10 } from "@fuel-ts/errors";
2967
+ import { bn as bn8 } from "@fuel-ts/math";
2968
+ import { InputType as InputType3, OutputType as OutputType3 } from "@fuel-ts/transactions";
2969
+ import { hexlify as hexlify9 } from "@fuel-ts/utils";
2970
+ var isRequestInputCoin = /* @__PURE__ */ __name((input) => input.type === InputType3.Coin, "isRequestInputCoin");
2971
+ var isRequestInputMessage = /* @__PURE__ */ __name((input) => input.type === InputType3.Message, "isRequestInputMessage");
2972
+ var isRequestInputMessageWithoutData = /* @__PURE__ */ __name((input) => input.type === InputType3.Message && bn8(input.data).isZero(), "isRequestInputMessageWithoutData");
2433
2973
  var isRequestInputCoinOrMessage = /* @__PURE__ */ __name((input) => isRequestInputCoin(input) || isRequestInputMessage(input), "isRequestInputCoinOrMessage");
2434
2974
  var isRequestInputResource = /* @__PURE__ */ __name((input) => isRequestInputCoin(input) || isRequestInputMessageWithoutData(input), "isRequestInputResource");
2435
2975
  var getRequestInputResourceOwner = /* @__PURE__ */ __name((input) => isRequestInputCoin(input) ? input.owner : input.recipient, "getRequestInputResourceOwner");
2436
2976
  var isRequestInputResourceFromOwner = /* @__PURE__ */ __name((input, owner) => getRequestInputResourceOwner(input) === owner.toB256(), "isRequestInputResourceFromOwner");
2437
- var isPredicate = /* @__PURE__ */ __name((input) => isRequestInputCoinOrMessage(input) && !!input.predicate && hexlify8(input.predicate) !== "0x", "isPredicate");
2977
+ var isPredicate = /* @__PURE__ */ __name((input) => isRequestInputCoinOrMessage(input) && !!input.predicate && hexlify9(input.predicate) !== "0x", "isPredicate");
2438
2978
  var getAssetAmountInRequestInputs = /* @__PURE__ */ __name((inputs, assetId, baseAsset) => inputs.filter(isRequestInputResource).reduce((acc, input) => {
2439
2979
  if (isRequestInputCoin(input) && input.assetId === assetId) {
2440
2980
  return acc.add(input.amount);
@@ -2443,7 +2983,7 @@ var getAssetAmountInRequestInputs = /* @__PURE__ */ __name((inputs, assetId, bas
2443
2983
  return acc.add(input.amount);
2444
2984
  }
2445
2985
  return acc;
2446
- }, bn7(0)), "getAssetAmountInRequestInputs");
2986
+ }, bn8(0)), "getAssetAmountInRequestInputs");
2447
2987
  var cacheRequestInputsResourcesFromOwner = /* @__PURE__ */ __name((inputs, owner) => inputs.reduce(
2448
2988
  (acc, input) => {
2449
2989
  if (isRequestInputCoin(input) && input.owner === owner.toB256()) {
@@ -2461,11 +3001,11 @@ var cacheRequestInputsResourcesFromOwner = /* @__PURE__ */ __name((inputs, owner
2461
3001
  var getBurnableAssetCount = /* @__PURE__ */ __name((baseAssetId, transactionRequest) => {
2462
3002
  const { inputs, outputs } = transactionRequest;
2463
3003
  const coinInputs = new Set(inputs.filter(isRequestInputCoin).map((input) => input.assetId));
2464
- if (inputs.some((i) => isRequestInputMessage(i) && bn7(i.amount).gt(0))) {
3004
+ if (inputs.some((i) => isRequestInputMessage(i) && bn8(i.amount).gt(0))) {
2465
3005
  coinInputs.add(baseAssetId);
2466
3006
  }
2467
3007
  const changeOutputs = new Set(
2468
- outputs.filter((output) => output.type === OutputType2.Change).map((output) => output.assetId)
3008
+ outputs.filter((output) => output.type === OutputType3.Change).map((output) => output.assetId)
2469
3009
  );
2470
3010
  const difference = new Set([...coinInputs].filter((x) => !changeOutputs.has(x)));
2471
3011
  return difference.size;
@@ -2482,15 +3022,15 @@ var validateTransactionForAssetBurn = /* @__PURE__ */ __name((baseAssetId, trans
2482
3022
  "Add the relevant change outputs to the transaction to avoid burning assets.",
2483
3023
  "Or enable asset burn, upon sending the transaction."
2484
3024
  ].join("\n");
2485
- throw new FuelError10(ErrorCode8.ASSET_BURN_DETECTED, message);
3025
+ throw new FuelError10(ErrorCode9.ASSET_BURN_DETECTED, message);
2486
3026
  }, "validateTransactionForAssetBurn");
2487
3027
 
2488
3028
  // src/providers/transaction-request/witness.ts
2489
- import { arrayify as arrayify5, hexlify as hexlify9 } from "@fuel-ts/utils";
3029
+ import { arrayify as arrayify5, hexlify as hexlify10 } from "@fuel-ts/utils";
2490
3030
  var witnessify = /* @__PURE__ */ __name((value) => {
2491
3031
  const data = arrayify5(value);
2492
3032
  return {
2493
- data: hexlify9(data),
3033
+ data: hexlify10(data),
2494
3034
  dataLength: data.length
2495
3035
  };
2496
3036
  }, "witnessify");
@@ -2537,11 +3077,11 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2537
3077
  outputs,
2538
3078
  witnesses
2539
3079
  } = {}) {
2540
- this.tip = tip ? bn8(tip) : void 0;
3080
+ this.tip = tip ? bn9(tip) : void 0;
2541
3081
  this.maturity = maturity && maturity > 0 ? maturity : void 0;
2542
3082
  this.expiration = expiration && expiration > 0 ? expiration : void 0;
2543
- this.witnessLimit = isDefined(witnessLimit) ? bn8(witnessLimit) : void 0;
2544
- this.maxFee = bn8(maxFee);
3083
+ this.witnessLimit = isDefined2(witnessLimit) ? bn9(witnessLimit) : void 0;
3084
+ this.maxFee = bn9(maxFee);
2545
3085
  this.inputs = inputs ?? [];
2546
3086
  this.outputs = outputs ?? [];
2547
3087
  this.witnesses = witnesses ?? [];
@@ -2550,13 +3090,13 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2550
3090
  let policyTypes = 0;
2551
3091
  const policies = [];
2552
3092
  const { tip, witnessLimit, maturity, expiration } = req;
2553
- if (bn8(tip).gt(0)) {
3093
+ if (bn9(tip).gt(0)) {
2554
3094
  policyTypes += PolicyType.Tip;
2555
- policies.push({ data: bn8(tip), type: PolicyType.Tip });
3095
+ policies.push({ data: bn9(tip), type: PolicyType.Tip });
2556
3096
  }
2557
- if (isDefined(witnessLimit) && bn8(witnessLimit).gte(0)) {
3097
+ if (isDefined2(witnessLimit) && bn9(witnessLimit).gte(0)) {
2558
3098
  policyTypes += PolicyType.WitnessLimit;
2559
- policies.push({ data: bn8(witnessLimit), type: PolicyType.WitnessLimit });
3099
+ policies.push({ data: bn9(witnessLimit), type: PolicyType.WitnessLimit });
2560
3100
  }
2561
3101
  if (maturity && maturity > 0) {
2562
3102
  policyTypes += PolicyType.Maturity;
@@ -2690,7 +3230,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2690
3230
  */
2691
3231
  getCoinInputs() {
2692
3232
  return this.inputs.filter(
2693
- (input) => input.type === InputType3.Coin
3233
+ (input) => input.type === InputType4.Coin
2694
3234
  );
2695
3235
  }
2696
3236
  /**
@@ -2700,7 +3240,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2700
3240
  */
2701
3241
  getCoinOutputs() {
2702
3242
  return this.outputs.filter(
2703
- (output) => output.type === OutputType3.Coin
3243
+ (output) => output.type === OutputType4.Coin
2704
3244
  );
2705
3245
  }
2706
3246
  /**
@@ -2710,7 +3250,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2710
3250
  */
2711
3251
  getChangeOutputs() {
2712
3252
  return this.outputs.filter(
2713
- (output) => output.type === OutputType3.Change
3253
+ (output) => output.type === OutputType4.Change
2714
3254
  );
2715
3255
  }
2716
3256
  /**
@@ -2722,10 +3262,10 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2722
3262
  const ownerAddress = addressify(owner);
2723
3263
  const found = this.inputs.find((input) => {
2724
3264
  switch (input.type) {
2725
- case InputType3.Coin:
2726
- return hexlify10(input.owner) === ownerAddress.toB256();
2727
- case InputType3.Message:
2728
- return hexlify10(input.recipient) === ownerAddress.toB256();
3265
+ case InputType4.Coin:
3266
+ return hexlify11(input.owner) === ownerAddress.toB256();
3267
+ case InputType4.Message:
3268
+ return hexlify11(input.recipient) === ownerAddress.toB256();
2729
3269
  default:
2730
3270
  return false;
2731
3271
  }
@@ -2751,7 +3291,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2751
3291
  }
2752
3292
  const input = {
2753
3293
  id,
2754
- type: InputType3.Coin,
3294
+ type: InputType4.Coin,
2755
3295
  owner: owner.toB256(),
2756
3296
  amount,
2757
3297
  assetId,
@@ -2782,7 +3322,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2782
3322
  }
2783
3323
  const input = {
2784
3324
  nonce,
2785
- type: InputType3.Message,
3325
+ type: InputType4.Message,
2786
3326
  sender: sender.toB256(),
2787
3327
  recipient: recipient.toB256(),
2788
3328
  data: isMessageCoin(message) ? "0x" : message.data,
@@ -2831,7 +3371,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2831
3371
  */
2832
3372
  addCoinOutput(to, amount, assetId) {
2833
3373
  this.pushOutput({
2834
- type: OutputType3.Coin,
3374
+ type: OutputType4.Coin,
2835
3375
  to: addressify(to).toB256(),
2836
3376
  amount,
2837
3377
  assetId
@@ -2847,7 +3387,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2847
3387
  addCoinOutputs(to, quantities) {
2848
3388
  quantities.map(coinQuantityfy).forEach((quantity) => {
2849
3389
  this.pushOutput({
2850
- type: OutputType3.Coin,
3390
+ type: OutputType4.Coin,
2851
3391
  to: addressify(to).toB256(),
2852
3392
  amount: quantity.amount,
2853
3393
  assetId: quantity.assetId
@@ -2863,11 +3403,11 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2863
3403
  */
2864
3404
  addChangeOutput(to, assetId) {
2865
3405
  const changeOutput = this.getChangeOutputs().find(
2866
- (output) => hexlify10(output.assetId) === assetId
3406
+ (output) => hexlify11(output.assetId) === assetId
2867
3407
  );
2868
3408
  if (!changeOutput) {
2869
3409
  this.pushOutput({
2870
- type: OutputType3.Change,
3410
+ type: OutputType4.Change,
2871
3411
  to: addressify(to).toB256(),
2872
3412
  assetId
2873
3413
  });
@@ -2940,25 +3480,25 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2940
3480
  const assetInput = findAssetInput(assetId);
2941
3481
  let usedQuantity = quantity;
2942
3482
  if (assetId === baseAssetId) {
2943
- usedQuantity = bn8("1000000000000000000");
3483
+ usedQuantity = bn9("1000000000000000000");
2944
3484
  }
2945
3485
  if (assetInput && "assetId" in assetInput) {
2946
- assetInput.id = hexlify10(randomBytes3(UTXO_ID_LEN2));
3486
+ assetInput.id = hexlify11(randomBytes3(UTXO_ID_LEN2));
2947
3487
  assetInput.amount = usedQuantity;
2948
3488
  } else {
2949
3489
  this.addResources([
2950
3490
  {
2951
- id: hexlify10(randomBytes3(UTXO_ID_LEN2)),
3491
+ id: hexlify11(randomBytes3(UTXO_ID_LEN2)),
2952
3492
  amount: usedQuantity,
2953
3493
  assetId,
2954
3494
  owner: resourcesOwner || Address2.fromRandom(),
2955
- blockCreated: bn8(1),
2956
- txCreatedIdx: bn8(1)
3495
+ blockCreated: bn9(1),
3496
+ txCreatedIdx: bn9(1)
2957
3497
  }
2958
3498
  ]);
2959
3499
  }
2960
3500
  }, "updateAssetInput");
2961
- updateAssetInput(baseAssetId, bn8(1e11));
3501
+ updateAssetInput(baseAssetId, bn9(1e11));
2962
3502
  quantities.forEach((q) => updateAssetInput(q.assetId, q.amount));
2963
3503
  return this;
2964
3504
  }
@@ -2970,7 +3510,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
2970
3510
  */
2971
3511
  getCoinOutputsQuantities() {
2972
3512
  const coinsQuantities = this.getCoinOutputs().map(({ amount, assetId }) => ({
2973
- amount: bn8(amount),
3513
+ amount: bn9(amount),
2974
3514
  assetId: assetId.toString()
2975
3515
  }));
2976
3516
  return coinsQuantities;
@@ -3002,7 +3542,7 @@ var BaseTransactionRequest = class _BaseTransactionRequest {
3002
3542
  const correspondingInput = inputsToExtractGasUsed.find(
3003
3543
  (x) => isRequestInputResourceFromOwner(x, new Address2(String(owner)))
3004
3544
  );
3005
- if (correspondingInput && "predicateGasUsed" in correspondingInput && bn8(correspondingInput.predicateGasUsed).gt(0)) {
3545
+ if (correspondingInput && "predicateGasUsed" in correspondingInput && bn9(correspondingInput.predicateGasUsed).gt(0)) {
3006
3546
  i.predicateGasUsed = correspondingInput.predicateGasUsed;
3007
3547
  }
3008
3548
  });
@@ -3033,34 +3573,34 @@ import { clone as clone3 } from "ramda";
3033
3573
  // src/providers/transaction-request/hash-transaction.ts
3034
3574
  import { ZeroBytes32 as ZeroBytes325 } from "@fuel-ts/address/configs";
3035
3575
  import { uint64ToBytesBE, sha256 } from "@fuel-ts/hasher";
3036
- import { bn as bn9 } from "@fuel-ts/math";
3037
- import { TransactionType as TransactionType2, InputType as InputType4, OutputType as OutputType4, TransactionCoder as TransactionCoder2 } from "@fuel-ts/transactions";
3576
+ import { bn as bn10 } from "@fuel-ts/math";
3577
+ import { TransactionType as TransactionType3, InputType as InputType5, OutputType as OutputType5, TransactionCoder as TransactionCoder2 } from "@fuel-ts/transactions";
3038
3578
  import { concat as concat3 } from "@fuel-ts/utils";
3039
3579
  import { clone as clone2 } from "ramda";
3040
3580
  function hashTransaction(transactionRequest, chainId) {
3041
3581
  const transaction = transactionRequest.toTransaction();
3042
- if (transaction.type === TransactionType2.Script) {
3582
+ if (transaction.type === TransactionType3.Script) {
3043
3583
  transaction.receiptsRoot = ZeroBytes325;
3044
3584
  }
3045
3585
  transaction.inputs = transaction.inputs.map((input) => {
3046
3586
  const inputClone = clone2(input);
3047
3587
  switch (inputClone.type) {
3048
3588
  // Zero out on signing: txPointer, predicateGasUsed
3049
- case InputType4.Coin: {
3589
+ case InputType5.Coin: {
3050
3590
  inputClone.txPointer = {
3051
3591
  blockHeight: 0,
3052
3592
  txIndex: 0
3053
3593
  };
3054
- inputClone.predicateGasUsed = bn9(0);
3594
+ inputClone.predicateGasUsed = bn10(0);
3055
3595
  return inputClone;
3056
3596
  }
3057
3597
  // Zero out on signing: predicateGasUsed
3058
- case InputType4.Message: {
3059
- inputClone.predicateGasUsed = bn9(0);
3598
+ case InputType5.Message: {
3599
+ inputClone.predicateGasUsed = bn10(0);
3060
3600
  return inputClone;
3061
3601
  }
3062
3602
  // Zero out on signing: txID, outputIndex, balanceRoot, stateRoot, and txPointer
3063
- case InputType4.Contract: {
3603
+ case InputType5.Contract: {
3064
3604
  inputClone.txPointer = {
3065
3605
  blockHeight: 0,
3066
3606
  txIndex: 0
@@ -3079,20 +3619,20 @@ function hashTransaction(transactionRequest, chainId) {
3079
3619
  const outputClone = clone2(output);
3080
3620
  switch (outputClone.type) {
3081
3621
  // Zero out on signing: balanceRoot, stateRoot
3082
- case OutputType4.Contract: {
3622
+ case OutputType5.Contract: {
3083
3623
  outputClone.balanceRoot = ZeroBytes325;
3084
3624
  outputClone.stateRoot = ZeroBytes325;
3085
3625
  return outputClone;
3086
3626
  }
3087
3627
  // Zero out on signing: amount
3088
- case OutputType4.Change: {
3089
- outputClone.amount = bn9(0);
3628
+ case OutputType5.Change: {
3629
+ outputClone.amount = bn10(0);
3090
3630
  return outputClone;
3091
3631
  }
3092
3632
  // Zero out on signing: amount, to and assetId
3093
- case OutputType4.Variable: {
3633
+ case OutputType5.Variable: {
3094
3634
  outputClone.to = ZeroBytes325;
3095
- outputClone.amount = bn9(0);
3635
+ outputClone.amount = bn10(0);
3096
3636
  outputClone.assetId = ZeroBytes325;
3097
3637
  return outputClone;
3098
3638
  }
@@ -3117,7 +3657,7 @@ var BlobTransactionRequest = class extends BaseTransactionRequest {
3117
3657
  return new this(clone3(obj));
3118
3658
  }
3119
3659
  /** Type of the transaction */
3120
- type = TransactionType.Blob;
3660
+ type = TransactionType2.Blob;
3121
3661
  /** Blob ID */
3122
3662
  blobId;
3123
3663
  /** Witness index of the bytecode to create */
@@ -3141,7 +3681,7 @@ var BlobTransactionRequest = class extends BaseTransactionRequest {
3141
3681
  const baseTransaction = this.getBaseTransaction();
3142
3682
  const { witnessIndex, blobId } = this;
3143
3683
  return {
3144
- type: TransactionType.Blob,
3684
+ type: TransactionType2.Blob,
3145
3685
  ...baseTransaction,
3146
3686
  blobId,
3147
3687
  witnessIndex
@@ -3174,13 +3714,13 @@ var BlobTransactionRequest = class extends BaseTransactionRequest {
3174
3714
 
3175
3715
  // src/providers/transaction-request/create-transaction-request.ts
3176
3716
  import { ZeroBytes32 as ZeroBytes326 } from "@fuel-ts/address/configs";
3177
- import { bn as bn10 } from "@fuel-ts/math";
3178
- import { TransactionType as TransactionType3, OutputType as OutputType5 } from "@fuel-ts/transactions";
3179
- import { arrayify as arrayify7, hexlify as hexlify12 } from "@fuel-ts/utils";
3717
+ import { bn as bn11 } from "@fuel-ts/math";
3718
+ import { TransactionType as TransactionType4, OutputType as OutputType6 } from "@fuel-ts/transactions";
3719
+ import { arrayify as arrayify7, hexlify as hexlify13 } from "@fuel-ts/utils";
3180
3720
  import { clone as clone4 } from "ramda";
3181
3721
 
3182
3722
  // src/providers/transaction-request/storage-slot.ts
3183
- import { arrayify as arrayify6, hexlify as hexlify11 } from "@fuel-ts/utils";
3723
+ import { arrayify as arrayify6, hexlify as hexlify12 } from "@fuel-ts/utils";
3184
3724
  var getStorageValue = /* @__PURE__ */ __name((value) => {
3185
3725
  const v = new Uint8Array(32);
3186
3726
  v.set(arrayify6(value));
@@ -3197,8 +3737,8 @@ var storageSlotify = /* @__PURE__ */ __name((storageSlot) => {
3197
3737
  value = storageSlot.value;
3198
3738
  }
3199
3739
  return {
3200
- key: hexlify11(key),
3201
- value: hexlify11(getStorageValue(value))
3740
+ key: hexlify12(key),
3741
+ value: hexlify12(getStorageValue(value))
3202
3742
  };
3203
3743
  }, "storageSlotify");
3204
3744
 
@@ -3211,7 +3751,7 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3211
3751
  return new this(clone4(obj));
3212
3752
  }
3213
3753
  /** Type of the transaction */
3214
- type = TransactionType3.Create;
3754
+ type = TransactionType4.Create;
3215
3755
  /** Witness index of contract bytecode to create */
3216
3756
  bytecodeWitnessIndex;
3217
3757
  /** Salt */
@@ -3226,7 +3766,7 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3226
3766
  constructor({ bytecodeWitnessIndex, salt, storageSlots, ...rest }) {
3227
3767
  super(rest);
3228
3768
  this.bytecodeWitnessIndex = bytecodeWitnessIndex ?? 0;
3229
- this.salt = hexlify12(salt ?? ZeroBytes326);
3769
+ this.salt = hexlify13(salt ?? ZeroBytes326);
3230
3770
  this.storageSlots = [...storageSlots ?? []];
3231
3771
  }
3232
3772
  /**
@@ -3239,11 +3779,11 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3239
3779
  const bytecodeWitnessIndex = this.bytecodeWitnessIndex;
3240
3780
  const storageSlots = this.storageSlots?.map(storageSlotify) ?? [];
3241
3781
  return {
3242
- type: TransactionType3.Create,
3782
+ type: TransactionType4.Create,
3243
3783
  ...baseTransaction,
3244
3784
  bytecodeWitnessIndex,
3245
- storageSlotsCount: bn10(storageSlots.length),
3246
- salt: this.salt ? hexlify12(this.salt) : ZeroBytes326,
3785
+ storageSlotsCount: bn11(storageSlots.length),
3786
+ salt: this.salt ? hexlify13(this.salt) : ZeroBytes326,
3247
3787
  storageSlots
3248
3788
  };
3249
3789
  }
@@ -3254,7 +3794,7 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3254
3794
  */
3255
3795
  getContractCreatedOutputs() {
3256
3796
  return this.outputs.filter(
3257
- (output) => output.type === OutputType5.ContractCreated
3797
+ (output) => output.type === OutputType6.ContractCreated
3258
3798
  );
3259
3799
  }
3260
3800
  /**
@@ -3275,14 +3815,14 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3275
3815
  */
3276
3816
  addContractCreatedOutput(contractId, stateRoot) {
3277
3817
  this.pushOutput({
3278
- type: OutputType5.ContractCreated,
3818
+ type: OutputType6.ContractCreated,
3279
3819
  contractId,
3280
3820
  stateRoot
3281
3821
  });
3282
3822
  }
3283
3823
  metadataGas(gasCosts) {
3284
3824
  return calculateMetadataGasForTxCreate({
3285
- contractBytesSize: bn10(arrayify7(this.witnesses[this.bytecodeWitnessIndex] || "0x").length),
3825
+ contractBytesSize: bn11(arrayify7(this.witnesses[this.bytecodeWitnessIndex] || "0x").length),
3286
3826
  gasCosts,
3287
3827
  stateRootSize: this.storageSlots.length,
3288
3828
  txBytesSize: this.byteSize()
@@ -3294,9 +3834,9 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
3294
3834
  import { Interface } from "@fuel-ts/abi-coder";
3295
3835
  import { addressify as addressify2 } from "@fuel-ts/address";
3296
3836
  import { ZeroBytes32 as ZeroBytes327 } from "@fuel-ts/address/configs";
3297
- import { bn as bn11 } from "@fuel-ts/math";
3298
- import { InputType as InputType5, OutputType as OutputType6, TransactionType as TransactionType4 } from "@fuel-ts/transactions";
3299
- import { arrayify as arrayify9, hexlify as hexlify13 } from "@fuel-ts/utils";
3837
+ import { bn as bn12 } from "@fuel-ts/math";
3838
+ import { InputType as InputType6, OutputType as OutputType7, TransactionType as TransactionType5 } from "@fuel-ts/transactions";
3839
+ import { arrayify as arrayify9, hexlify as hexlify14 } from "@fuel-ts/utils";
3300
3840
  import { clone as clone5 } from "ramda";
3301
3841
 
3302
3842
  // src/providers/transaction-request/scripts.ts
@@ -3334,7 +3874,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3334
3874
  return new this(clone5(obj));
3335
3875
  }
3336
3876
  /** Type of the transaction */
3337
- type = TransactionType4.Script;
3877
+ type = TransactionType5.Script;
3338
3878
  /** Gas limit for transaction */
3339
3879
  gasLimit;
3340
3880
  /** Script to execute */
@@ -3349,7 +3889,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3349
3889
  */
3350
3890
  constructor({ script, scriptData, gasLimit, ...rest } = {}) {
3351
3891
  super(rest);
3352
- this.gasLimit = bn11(gasLimit);
3892
+ this.gasLimit = bn12(gasLimit);
3353
3893
  this.script = arrayify9(script ?? returnZeroScript.bytes);
3354
3894
  this.scriptData = arrayify9(scriptData ?? returnZeroScript.encodeScriptData());
3355
3895
  this.abis = rest.abis;
@@ -3360,6 +3900,9 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3360
3900
  * @param account - The account to fund the transaction.
3361
3901
  * @param params - The parameters for the transaction cost.
3362
3902
  * @returns The current instance of the `ScriptTransactionRequest` funded.
3903
+ *
3904
+ * @deprecated Use `provider.assembleTx` instead.
3905
+ * Check the migration guide https://docs.fuel.network/guide/assembling-transactions/migration-guide.html for more information.
3363
3906
  */
3364
3907
  async estimateAndFund(account, { signatureCallback, quantities = [] } = {}) {
3365
3908
  const txCost = await account.getTransactionCost(this, { signatureCallback, quantities });
@@ -3377,14 +3920,14 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3377
3920
  const script = arrayify9(this.script ?? "0x");
3378
3921
  const scriptData = arrayify9(this.scriptData ?? "0x");
3379
3922
  return {
3380
- type: TransactionType4.Script,
3923
+ type: TransactionType5.Script,
3381
3924
  scriptGasLimit: this.gasLimit,
3382
3925
  ...super.getBaseTransaction(),
3383
- scriptLength: bn11(script.length),
3384
- scriptDataLength: bn11(scriptData.length),
3926
+ scriptLength: bn12(script.length),
3927
+ scriptDataLength: bn12(scriptData.length),
3385
3928
  receiptsRoot: ZeroBytes327,
3386
- script: hexlify13(script),
3387
- scriptData: hexlify13(scriptData)
3929
+ script: hexlify14(script),
3930
+ scriptData: hexlify14(scriptData)
3388
3931
  };
3389
3932
  }
3390
3933
  /**
@@ -3394,7 +3937,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3394
3937
  */
3395
3938
  getContractInputs() {
3396
3939
  return this.inputs.filter(
3397
- (input) => input.type === InputType5.Contract
3940
+ (input) => input.type === InputType6.Contract
3398
3941
  );
3399
3942
  }
3400
3943
  /**
@@ -3404,7 +3947,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3404
3947
  */
3405
3948
  getContractOutputs() {
3406
3949
  return this.outputs.filter(
3407
- (output) => output.type === OutputType6.Contract
3950
+ (output) => output.type === OutputType7.Contract
3408
3951
  );
3409
3952
  }
3410
3953
  /**
@@ -3414,7 +3957,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3414
3957
  */
3415
3958
  getVariableOutputs() {
3416
3959
  return this.outputs.filter(
3417
- (output) => output.type === OutputType6.Variable
3960
+ (output) => output.type === OutputType7.Variable
3418
3961
  );
3419
3962
  }
3420
3963
  /**
@@ -3437,12 +3980,27 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3437
3980
  let outputsNumber = numberOfVariables;
3438
3981
  while (outputsNumber) {
3439
3982
  this.pushOutput({
3440
- type: OutputType6.Variable
3983
+ type: OutputType7.Variable
3441
3984
  });
3442
3985
  outputsNumber -= 1;
3443
3986
  }
3444
3987
  return this.outputs.length - 1;
3445
3988
  }
3989
+ /**
3990
+ * Adds a variable output to the transaction request.
3991
+ *
3992
+ * @param to - The recipient address as a BytesLike object. Defaults to ZeroBytes32 if not provided.
3993
+ * @param amount - The amount to be transferred as a BigNumberish object. Defaults to 0 if not provided.
3994
+ * @param assetId - The asset ID as a BytesLike object. Defaults to ZeroBytes32 if not provided.
3995
+ */
3996
+ addVariableOutput(to, amount, assetId) {
3997
+ this.pushOutput({
3998
+ type: OutputType7.Variable,
3999
+ to,
4000
+ amount,
4001
+ assetId
4002
+ });
4003
+ }
3446
4004
  /**
3447
4005
  * Calculates the maximum gas for the transaction.
3448
4006
  *
@@ -3481,12 +4039,12 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3481
4039
  return this;
3482
4040
  }
3483
4041
  const inputIndex = super.pushInput({
3484
- type: InputType5.Contract,
4042
+ type: InputType6.Contract,
3485
4043
  contractId: contractAddress.toB256(),
3486
4044
  txPointer: "0x00000000000000000000000000000000"
3487
4045
  });
3488
4046
  this.pushOutput({
3489
- type: OutputType6.Contract,
4047
+ type: OutputType7.Contract,
3490
4048
  inputIndex
3491
4049
  });
3492
4050
  return this;
@@ -3525,10 +4083,10 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
3525
4083
  import { FuelError as FuelError12 } from "@fuel-ts/errors";
3526
4084
  import { hash as hash2 } from "@fuel-ts/hasher";
3527
4085
  import {
3528
- TransactionType as TransactionType5,
4086
+ TransactionType as TransactionType6,
3529
4087
  UpgradePurposeTypeEnum
3530
4088
  } from "@fuel-ts/transactions";
3531
- import { hexlify as hexlify14 } from "@fuel-ts/utils";
4089
+ import { hexlify as hexlify15 } from "@fuel-ts/utils";
3532
4090
  import { clone as clone6 } from "ramda";
3533
4091
  var UpgradeTransactionRequest = class _UpgradeTransactionRequest extends BaseTransactionRequest {
3534
4092
  static {
@@ -3541,7 +4099,7 @@ var UpgradeTransactionRequest = class _UpgradeTransactionRequest extends BaseTra
3541
4099
  return new this(clone6(obj));
3542
4100
  }
3543
4101
  /** The type of transaction */
3544
- type = TransactionType5.Upgrade;
4102
+ type = TransactionType6.Upgrade;
3545
4103
  /** The upgrade purpose */
3546
4104
  upgradePurpose;
3547
4105
  /** Witness index of consensus */
@@ -3588,7 +4146,7 @@ var UpgradeTransactionRequest = class _UpgradeTransactionRequest extends BaseTra
3588
4146
  addStateTransitionUpgradePurpose(bytecodeRoot) {
3589
4147
  this.upgradePurpose = {
3590
4148
  type: UpgradePurposeTypeEnum.StateTransition,
3591
- data: hexlify14(bytecodeRoot)
4149
+ data: hexlify15(bytecodeRoot)
3592
4150
  };
3593
4151
  return this;
3594
4152
  }
@@ -3628,14 +4186,14 @@ var UpgradeTransactionRequest = class _UpgradeTransactionRequest extends BaseTra
3628
4186
  upgradePurpose = {
3629
4187
  type: UpgradePurposeTypeEnum.StateTransition,
3630
4188
  data: {
3631
- bytecodeRoot: hexlify14(this.upgradePurpose.data)
4189
+ bytecodeRoot: hexlify15(this.upgradePurpose.data)
3632
4190
  }
3633
4191
  };
3634
4192
  } else {
3635
4193
  throw new FuelError12(FuelError12.CODES.NOT_IMPLEMENTED, "Invalid upgrade purpose");
3636
4194
  }
3637
4195
  return {
3638
- type: TransactionType5.Upgrade,
4196
+ type: TransactionType6.Upgrade,
3639
4197
  ...super.getBaseTransaction(),
3640
4198
  upgradePurpose
3641
4199
  };
@@ -3680,8 +4238,8 @@ var UpgradeTransactionRequest = class _UpgradeTransactionRequest extends BaseTra
3680
4238
 
3681
4239
  // src/providers/transaction-request/upload-transaction-request.ts
3682
4240
  import { ZeroBytes32 as ZeroBytes328 } from "@fuel-ts/address/configs";
3683
- import { TransactionType as TransactionType6 } from "@fuel-ts/transactions";
3684
- import { arrayify as arrayify10, hexlify as hexlify15 } from "@fuel-ts/utils";
4241
+ import { TransactionType as TransactionType7 } from "@fuel-ts/transactions";
4242
+ import { arrayify as arrayify10, hexlify as hexlify16 } from "@fuel-ts/utils";
3685
4243
  import { clone as clone7 } from "ramda";
3686
4244
  var UploadTransactionRequest = class _UploadTransactionRequest extends BaseTransactionRequest {
3687
4245
  static {
@@ -3694,7 +4252,7 @@ var UploadTransactionRequest = class _UploadTransactionRequest extends BaseTrans
3694
4252
  return new this(clone7(obj));
3695
4253
  }
3696
4254
  /** Type of the transaction */
3697
- type = TransactionType6.Upload;
4255
+ type = TransactionType7.Upload;
3698
4256
  /** The witness index of the subsection of the bytecode. */
3699
4257
  witnessIndex;
3700
4258
  /** The subsection data. */
@@ -3743,12 +4301,12 @@ var UploadTransactionRequest = class _UploadTransactionRequest extends BaseTrans
3743
4301
  const baseTransaction = this.getBaseTransaction();
3744
4302
  const { subsectionIndex, subsectionsNumber, root, proofSet } = this.subsection;
3745
4303
  return {
3746
- type: TransactionType6.Upload,
4304
+ type: TransactionType7.Upload,
3747
4305
  ...baseTransaction,
3748
4306
  subsectionIndex,
3749
4307
  subsectionsNumber,
3750
- root: hexlify15(root),
3751
- proofSet: proofSet.map(hexlify15),
4308
+ root: hexlify16(root),
4309
+ proofSet: proofSet.map(hexlify16),
3752
4310
  witnessIndex: this.witnessIndex,
3753
4311
  proofSetCount: proofSet.length
3754
4312
  };
@@ -3788,39 +4346,39 @@ var UploadTransactionRequest = class _UploadTransactionRequest extends BaseTrans
3788
4346
  };
3789
4347
 
3790
4348
  // src/providers/transaction-request/utils.ts
3791
- import { ErrorCode as ErrorCode9, FuelError as FuelError13 } from "@fuel-ts/errors";
3792
- import { TransactionType as TransactionType7 } from "@fuel-ts/transactions";
4349
+ import { ErrorCode as ErrorCode10, FuelError as FuelError13 } from "@fuel-ts/errors";
4350
+ import { TransactionType as TransactionType8 } from "@fuel-ts/transactions";
3793
4351
  var transactionRequestify = /* @__PURE__ */ __name((obj) => {
3794
4352
  if (obj instanceof ScriptTransactionRequest || obj instanceof CreateTransactionRequest || obj instanceof BlobTransactionRequest || obj instanceof UpgradeTransactionRequest || obj instanceof UploadTransactionRequest) {
3795
4353
  return obj;
3796
4354
  }
3797
4355
  const { type } = obj;
3798
4356
  switch (obj.type) {
3799
- case TransactionType7.Script: {
4357
+ case TransactionType8.Script: {
3800
4358
  return ScriptTransactionRequest.from(obj);
3801
4359
  }
3802
- case TransactionType7.Create: {
4360
+ case TransactionType8.Create: {
3803
4361
  return CreateTransactionRequest.from(obj);
3804
4362
  }
3805
- case TransactionType7.Blob: {
4363
+ case TransactionType8.Blob: {
3806
4364
  return BlobTransactionRequest.from(obj);
3807
4365
  }
3808
- case TransactionType7.Upgrade: {
4366
+ case TransactionType8.Upgrade: {
3809
4367
  return UpgradeTransactionRequest.from(obj);
3810
4368
  }
3811
- case TransactionType7.Upload: {
4369
+ case TransactionType8.Upload: {
3812
4370
  return UploadTransactionRequest.from(obj);
3813
4371
  }
3814
4372
  default: {
3815
4373
  throw new FuelError13(
3816
- ErrorCode9.UNSUPPORTED_TRANSACTION_TYPE,
4374
+ ErrorCode10.UNSUPPORTED_TRANSACTION_TYPE,
3817
4375
  `Unsupported transaction type: ${type}.`
3818
4376
  );
3819
4377
  }
3820
4378
  }
3821
4379
  }, "transactionRequestify");
3822
- var isTransactionTypeScript = /* @__PURE__ */ __name((request) => request.type === TransactionType7.Script, "isTransactionTypeScript");
3823
- var isTransactionTypeCreate = /* @__PURE__ */ __name((request) => request.type === TransactionType7.Create, "isTransactionTypeCreate");
4380
+ var isTransactionTypeScript = /* @__PURE__ */ __name((request) => request.type === TransactionType8.Script, "isTransactionTypeScript");
4381
+ var isTransactionTypeCreate = /* @__PURE__ */ __name((request) => request.type === TransactionType8.Create, "isTransactionTypeCreate");
3824
4382
 
3825
4383
  // src/providers/resource-cache.ts
3826
4384
  var cache = /* @__PURE__ */ new Map();
@@ -3833,7 +4391,7 @@ var ResourceCache = class {
3833
4391
  this.ttl = ttl;
3834
4392
  if (typeof ttl !== "number" || this.ttl <= 0) {
3835
4393
  throw new FuelError14(
3836
- ErrorCode10.INVALID_TTL,
4394
+ ErrorCode11.INVALID_TTL,
3837
4395
  `Invalid TTL: ${this.ttl}. Use a value greater than zero.`
3838
4396
  );
3839
4397
  }
@@ -3910,26 +4468,26 @@ var ResourceCache = class {
3910
4468
  }
3911
4469
  extractResourceData(input) {
3912
4470
  if (isRequestInputCoin(input)) {
3913
- return { owner: hexlify16(input.owner), key: hexlify16(input.id), type: "utxo" };
4471
+ return { owner: hexlify17(input.owner), key: hexlify17(input.id), type: "utxo" };
3914
4472
  }
3915
- return { owner: hexlify16(input.recipient), key: hexlify16(input.nonce), type: "message" };
4473
+ return { owner: hexlify17(input.recipient), key: hexlify17(input.nonce), type: "message" };
3916
4474
  }
3917
4475
  };
3918
4476
 
3919
4477
  // src/providers/transaction-response/transaction-response.ts
3920
- import { ErrorCode as ErrorCode14, FuelError as FuelError18 } from "@fuel-ts/errors";
3921
- import { bn as bn16 } from "@fuel-ts/math";
3922
- import { OutputType as OutputType8, TransactionCoder as TransactionCoder4, TxPointerCoder } from "@fuel-ts/transactions";
3923
- import { arrayify as arrayify12, assertUnreachable } from "@fuel-ts/utils";
4478
+ import { ErrorCode as ErrorCode15, FuelError as FuelError18 } from "@fuel-ts/errors";
4479
+ import { bn as bn17 } from "@fuel-ts/math";
4480
+ import { TransactionCoder as TransactionCoder5, TxPointerCoder } from "@fuel-ts/transactions";
4481
+ import { arrayify as arrayify12 } from "@fuel-ts/utils";
3924
4482
 
3925
4483
  // src/providers/transaction-summary/assemble-transaction-summary.ts
3926
- import { bn as bn15 } from "@fuel-ts/math";
3927
- import { PolicyType as PolicyType3 } from "@fuel-ts/transactions";
3928
- import { DateTime, hexlify as hexlify17 } from "@fuel-ts/utils";
4484
+ import { bn as bn16 } from "@fuel-ts/math";
4485
+ import { PolicyType as PolicyType3, TransactionCoder as TransactionCoder4 } from "@fuel-ts/transactions";
4486
+ import { DateTime, hexlify as hexlify18 } from "@fuel-ts/utils";
3929
4487
 
3930
4488
  // src/providers/transaction-summary/calculate-tx-fee-for-summary.ts
3931
- import { bn as bn12 } from "@fuel-ts/math";
3932
- import { PolicyType as PolicyType2, TransactionCoder as TransactionCoder3, TransactionType as TransactionType8 } from "@fuel-ts/transactions";
4489
+ import { bn as bn13 } from "@fuel-ts/math";
4490
+ import { PolicyType as PolicyType2, TransactionCoder as TransactionCoder3, TransactionType as TransactionType9 } from "@fuel-ts/transactions";
3933
4491
  import { arrayify as arrayify11 } from "@fuel-ts/utils";
3934
4492
  var calculateTXFeeForSummary = /* @__PURE__ */ __name((params) => {
3935
4493
  const {
@@ -3938,19 +4496,19 @@ var calculateTXFeeForSummary = /* @__PURE__ */ __name((params) => {
3938
4496
  tip,
3939
4497
  consensusParameters: { gasCosts, feeParams, maxGasPerTx }
3940
4498
  } = params;
3941
- const gasPerByte = bn12(feeParams.gasPerByte);
3942
- const gasPriceFactor = bn12(feeParams.gasPriceFactor);
4499
+ const gasPerByte = bn13(feeParams.gasPerByte);
4500
+ const gasPriceFactor = bn13(feeParams.gasPriceFactor);
3943
4501
  const transactionBytes = arrayify11(rawPayload);
3944
4502
  const [transaction] = new TransactionCoder3().decode(transactionBytes, 0);
3945
4503
  const { type, witnesses, inputs, policies } = transaction;
3946
- let metadataGas = bn12(0);
3947
- let gasLimit = bn12(0);
3948
- if (type !== TransactionType8.Create && type !== TransactionType8.Script) {
3949
- return bn12(0);
4504
+ let metadataGas = bn13(0);
4505
+ let gasLimit = bn13(0);
4506
+ if (type !== TransactionType9.Create && type !== TransactionType9.Script) {
4507
+ return bn13(0);
3950
4508
  }
3951
- if (type === TransactionType8.Create) {
4509
+ if (type === TransactionType9.Create) {
3952
4510
  const { bytecodeWitnessIndex, storageSlots } = transaction;
3953
- const contractBytesSize = bn12(arrayify11(witnesses[bytecodeWitnessIndex].data).length);
4511
+ const contractBytesSize = bn13(arrayify11(witnesses[bytecodeWitnessIndex].data).length);
3954
4512
  metadataGas = calculateMetadataGasForTxCreate({
3955
4513
  contractBytesSize,
3956
4514
  gasCosts,
@@ -3969,7 +4527,7 @@ var calculateTXFeeForSummary = /* @__PURE__ */ __name((params) => {
3969
4527
  }
3970
4528
  const minGas = getMinGas({
3971
4529
  gasCosts,
3972
- gasPerByte: bn12(gasPerByte),
4530
+ gasPerByte: bn13(gasPerByte),
3973
4531
  inputs,
3974
4532
  metadataGas,
3975
4533
  txBytesSize: transactionBytes.length
@@ -3995,14 +4553,14 @@ var calculateTXFeeForSummary = /* @__PURE__ */ __name((params) => {
3995
4553
 
3996
4554
  // src/providers/transaction-summary/operations.ts
3997
4555
  import { ZeroBytes32 as ZeroBytes329 } from "@fuel-ts/address/configs";
3998
- import { ErrorCode as ErrorCode12, FuelError as FuelError16 } from "@fuel-ts/errors";
3999
- import { bn as bn13 } from "@fuel-ts/math";
4000
- import { ReceiptType as ReceiptType5, TransactionType as TransactionType9 } from "@fuel-ts/transactions";
4556
+ import { ErrorCode as ErrorCode13, FuelError as FuelError16 } from "@fuel-ts/errors";
4557
+ import { bn as bn14 } from "@fuel-ts/math";
4558
+ import { ReceiptType as ReceiptType5, TransactionType as TransactionType10 } from "@fuel-ts/transactions";
4001
4559
 
4002
4560
  // src/providers/transaction-summary/input.ts
4003
- import { ErrorCode as ErrorCode11, FuelError as FuelError15 } from "@fuel-ts/errors";
4561
+ import { ErrorCode as ErrorCode12, FuelError as FuelError15 } from "@fuel-ts/errors";
4004
4562
  import { BN } from "@fuel-ts/math";
4005
- import { InputType as InputType6 } from "@fuel-ts/transactions";
4563
+ import { InputType as InputType7 } from "@fuel-ts/transactions";
4006
4564
  function getInputsByTypes(inputs, types) {
4007
4565
  return inputs.filter((i) => types.includes(i.type));
4008
4566
  }
@@ -4012,23 +4570,23 @@ function getInputsByType(inputs, type) {
4012
4570
  }
4013
4571
  __name(getInputsByType, "getInputsByType");
4014
4572
  function getInputsCoin(inputs) {
4015
- return getInputsByType(inputs, InputType6.Coin);
4573
+ return getInputsByType(inputs, InputType7.Coin);
4016
4574
  }
4017
4575
  __name(getInputsCoin, "getInputsCoin");
4018
4576
  function getInputsMessage(inputs) {
4019
- return getInputsByType(inputs, InputType6.Message);
4577
+ return getInputsByType(inputs, InputType7.Message);
4020
4578
  }
4021
4579
  __name(getInputsMessage, "getInputsMessage");
4022
4580
  function getInputsCoinAndMessage(inputs) {
4023
- return getInputsByTypes(inputs, [InputType6.Coin, InputType6.Message]);
4581
+ return getInputsByTypes(inputs, [InputType7.Coin, InputType7.Message]);
4024
4582
  }
4025
4583
  __name(getInputsCoinAndMessage, "getInputsCoinAndMessage");
4026
4584
  function isInputCoin(input) {
4027
- return input.type === InputType6.Coin;
4585
+ return input.type === InputType7.Coin;
4028
4586
  }
4029
4587
  __name(isInputCoin, "isInputCoin");
4030
4588
  function getInputsContract(inputs) {
4031
- return getInputsByType(inputs, InputType6.Contract);
4589
+ return getInputsByType(inputs, InputType7.Contract);
4032
4590
  }
4033
4591
  __name(getInputsContract, "getInputsContract");
4034
4592
  function findCoinInput(inputs, assetId) {
@@ -4079,9 +4637,9 @@ function getInputContractFromIndex(inputs, inputIndex) {
4079
4637
  if (!contractInput) {
4080
4638
  return void 0;
4081
4639
  }
4082
- if (contractInput.type !== InputType6.Contract) {
4640
+ if (contractInput.type !== InputType7.Contract) {
4083
4641
  throw new FuelError15(
4084
- ErrorCode11.INVALID_TRANSACTION_INPUT,
4642
+ ErrorCode12.INVALID_TRANSACTION_INPUT,
4085
4643
  `Contract input should be of type 'contract'.`
4086
4644
  );
4087
4645
  }
@@ -4089,10 +4647,10 @@ function getInputContractFromIndex(inputs, inputIndex) {
4089
4647
  }
4090
4648
  __name(getInputContractFromIndex, "getInputContractFromIndex");
4091
4649
  function getInputAccountAddress(input) {
4092
- if (input.type === InputType6.Coin) {
4650
+ if (input.type === InputType7.Coin) {
4093
4651
  return input.owner.toString();
4094
4652
  }
4095
- if (input.type === InputType6.Message) {
4653
+ if (input.type === InputType7.Message) {
4096
4654
  return input.recipient.toString();
4097
4655
  }
4098
4656
  return "";
@@ -4100,25 +4658,25 @@ function getInputAccountAddress(input) {
4100
4658
  __name(getInputAccountAddress, "getInputAccountAddress");
4101
4659
 
4102
4660
  // src/providers/transaction-summary/output.ts
4103
- import { OutputType as OutputType7 } from "@fuel-ts/transactions";
4661
+ import { OutputType as OutputType8 } from "@fuel-ts/transactions";
4104
4662
  function getOutputsByType(outputs, type) {
4105
4663
  return outputs.filter((o) => o.type === type);
4106
4664
  }
4107
4665
  __name(getOutputsByType, "getOutputsByType");
4108
4666
  function getOutputsContractCreated(outputs) {
4109
- return getOutputsByType(outputs, OutputType7.ContractCreated);
4667
+ return getOutputsByType(outputs, OutputType8.ContractCreated);
4110
4668
  }
4111
4669
  __name(getOutputsContractCreated, "getOutputsContractCreated");
4112
4670
  function getOutputsCoin(outputs) {
4113
- return getOutputsByType(outputs, OutputType7.Coin);
4671
+ return getOutputsByType(outputs, OutputType8.Coin);
4114
4672
  }
4115
4673
  __name(getOutputsCoin, "getOutputsCoin");
4116
4674
  function getOutputsChange(outputs) {
4117
- return getOutputsByType(outputs, OutputType7.Change);
4675
+ return getOutputsByType(outputs, OutputType8.Change);
4118
4676
  }
4119
4677
  __name(getOutputsChange, "getOutputsChange");
4120
4678
  function getOutputsContract(outputs) {
4121
- return getOutputsByType(outputs, OutputType7.Contract);
4679
+ return getOutputsByType(outputs, OutputType8.Contract);
4122
4680
  }
4123
4681
  __name(getOutputsContract, "getOutputsContract");
4124
4682
 
@@ -4129,21 +4687,21 @@ function getReceiptsByType(receipts, type) {
4129
4687
  __name(getReceiptsByType, "getReceiptsByType");
4130
4688
  function getTransactionTypeName(transactionType) {
4131
4689
  switch (transactionType) {
4132
- case TransactionType9.Mint:
4690
+ case TransactionType10.Mint:
4133
4691
  return "Mint" /* Mint */;
4134
- case TransactionType9.Create:
4692
+ case TransactionType10.Create:
4135
4693
  return "Create" /* Create */;
4136
- case TransactionType9.Script:
4694
+ case TransactionType10.Script:
4137
4695
  return "Script" /* Script */;
4138
- case TransactionType9.Blob:
4696
+ case TransactionType10.Blob:
4139
4697
  return "Blob" /* Blob */;
4140
- case TransactionType9.Upgrade:
4698
+ case TransactionType10.Upgrade:
4141
4699
  return "Upgrade" /* Upgrade */;
4142
- case TransactionType9.Upload:
4700
+ case TransactionType10.Upload:
4143
4701
  return "Upload" /* Upload */;
4144
4702
  default:
4145
4703
  throw new FuelError16(
4146
- ErrorCode12.UNSUPPORTED_TRANSACTION_TYPE,
4704
+ ErrorCode13.UNSUPPORTED_TRANSACTION_TYPE,
4147
4705
  `Unsupported transaction type: ${transactionType}.`
4148
4706
  );
4149
4707
  }
@@ -4196,7 +4754,7 @@ function mergeAssets(op1, op2) {
4196
4754
  assets2.forEach((asset) => {
4197
4755
  const existingAsset = assetMap.get(asset.assetId);
4198
4756
  if (existingAsset) {
4199
- existingAsset.amount = bn13(existingAsset.amount).add(asset.amount);
4757
+ existingAsset.amount = bn14(existingAsset.amount).add(asset.amount);
4200
4758
  } else {
4201
4759
  assetMap.set(asset.assetId, { ...asset });
4202
4760
  }
@@ -4548,8 +5106,8 @@ var extractBurnedAssetsFromReceipts = /* @__PURE__ */ __name((receipts) => {
4548
5106
  }, "extractBurnedAssetsFromReceipts");
4549
5107
 
4550
5108
  // src/providers/transaction-summary/status.ts
4551
- import { ErrorCode as ErrorCode13, FuelError as FuelError17 } from "@fuel-ts/errors";
4552
- import { bn as bn14 } from "@fuel-ts/math";
5109
+ import { ErrorCode as ErrorCode14, FuelError as FuelError17 } from "@fuel-ts/errors";
5110
+ import { bn as bn15 } from "@fuel-ts/math";
4553
5111
  var getTransactionStatusName = /* @__PURE__ */ __name((gqlStatus) => {
4554
5112
  switch (gqlStatus) {
4555
5113
  case "FailureStatus":
@@ -4560,22 +5118,41 @@ var getTransactionStatusName = /* @__PURE__ */ __name((gqlStatus) => {
4560
5118
  return "submitted" /* submitted */;
4561
5119
  case "SqueezedOutStatus":
4562
5120
  return "squeezedout" /* squeezedout */;
5121
+ case "PreconfirmationSuccessStatus":
5122
+ return "preconfirmationSuccess" /* preconfirmationSuccess */;
5123
+ case "PreconfirmationFailureStatus":
5124
+ return "preconfirmationFailure" /* preconfirmationFailure */;
4563
5125
  default:
4564
5126
  throw new FuelError17(
4565
- ErrorCode13.INVALID_TRANSACTION_STATUS,
5127
+ ErrorCode14.INVALID_TRANSACTION_STATUS,
4566
5128
  `Invalid transaction status: ${gqlStatus}.`
4567
5129
  );
4568
5130
  }
4569
5131
  }, "getTransactionStatusName");
5132
+ var extractResolvedOutputs = /* @__PURE__ */ __name((serializedOutputs) => {
5133
+ const resolvedOutputs = [];
5134
+ serializedOutputs?.forEach(
5135
+ ({ utxoId, output }) => resolvedOutputs.push({
5136
+ utxoId,
5137
+ output: deserializeProcessedTxOutput(output)
5138
+ })
5139
+ );
5140
+ return resolvedOutputs;
5141
+ }, "extractResolvedOutputs");
4570
5142
  var processGraphqlStatus = /* @__PURE__ */ __name((gqlTransactionStatus) => {
4571
5143
  let time;
4572
5144
  let blockId;
4573
5145
  let status;
4574
5146
  let totalFee;
4575
5147
  let totalGas;
5148
+ let receipts;
5149
+ let resolvedOutputs = [];
5150
+ let errorReason;
4576
5151
  let isStatusFailure = false;
4577
5152
  let isStatusSuccess = false;
4578
5153
  let isStatusPending = false;
5154
+ let isStatusPreConfirmationSuccess = false;
5155
+ let isStatusPreConfirmationFailure = false;
4579
5156
  if (gqlTransactionStatus?.type) {
4580
5157
  status = getTransactionStatusName(gqlTransactionStatus.type);
4581
5158
  switch (gqlTransactionStatus.type) {
@@ -4583,20 +5160,37 @@ var processGraphqlStatus = /* @__PURE__ */ __name((gqlTransactionStatus) => {
4583
5160
  time = gqlTransactionStatus.time;
4584
5161
  blockId = gqlTransactionStatus.block?.id;
4585
5162
  isStatusSuccess = true;
4586
- totalFee = bn14(gqlTransactionStatus.totalFee);
4587
- totalGas = bn14(gqlTransactionStatus.totalGas);
5163
+ receipts = gqlTransactionStatus.receipts?.map(deserializeReceipt);
5164
+ totalFee = bn15(gqlTransactionStatus.totalFee);
5165
+ totalGas = bn15(gqlTransactionStatus.totalGas);
4588
5166
  break;
4589
5167
  case "FailureStatus":
4590
5168
  time = gqlTransactionStatus.time;
4591
5169
  blockId = gqlTransactionStatus.block?.id;
4592
5170
  isStatusFailure = true;
4593
- totalFee = bn14(gqlTransactionStatus.totalFee);
4594
- totalGas = bn14(gqlTransactionStatus.totalGas);
5171
+ totalFee = bn15(gqlTransactionStatus.totalFee);
5172
+ receipts = gqlTransactionStatus.receipts?.map(deserializeReceipt);
5173
+ totalGas = bn15(gqlTransactionStatus.totalGas);
4595
5174
  break;
4596
5175
  case "SubmittedStatus":
4597
5176
  time = gqlTransactionStatus.time;
4598
5177
  isStatusPending = true;
4599
5178
  break;
5179
+ case "PreconfirmationSuccessStatus":
5180
+ isStatusPreConfirmationSuccess = true;
5181
+ totalFee = bn15(gqlTransactionStatus.totalFee);
5182
+ totalGas = bn15(gqlTransactionStatus.totalGas);
5183
+ receipts = gqlTransactionStatus.preconfirmationReceipts?.map(deserializeReceipt);
5184
+ resolvedOutputs = extractResolvedOutputs(gqlTransactionStatus.resolvedOutputs);
5185
+ break;
5186
+ case "PreconfirmationFailureStatus":
5187
+ isStatusPreConfirmationFailure = true;
5188
+ totalFee = bn15(gqlTransactionStatus.totalFee);
5189
+ totalGas = bn15(gqlTransactionStatus.totalGas);
5190
+ receipts = gqlTransactionStatus.preconfirmationReceipts?.map(deserializeReceipt);
5191
+ resolvedOutputs = extractResolvedOutputs(gqlTransactionStatus.resolvedOutputs);
5192
+ errorReason = gqlTransactionStatus.reason;
5193
+ break;
4600
5194
  default:
4601
5195
  }
4602
5196
  }
@@ -4606,13 +5200,18 @@ var processGraphqlStatus = /* @__PURE__ */ __name((gqlTransactionStatus) => {
4606
5200
  status,
4607
5201
  totalFee,
4608
5202
  totalGas,
5203
+ receipts,
4609
5204
  isStatusFailure,
4610
5205
  isStatusSuccess,
4611
- isStatusPending
5206
+ isStatusPending,
5207
+ isStatusPreConfirmationSuccess,
5208
+ isStatusPreConfirmationFailure,
5209
+ resolvedOutputs,
5210
+ errorReason
4612
5211
  };
4613
5212
  return processedGraphqlStatus;
4614
5213
  }, "processGraphqlStatus");
4615
- var getTotalFeeFromStatus = /* @__PURE__ */ __name((status) => status && "totalFee" in status ? bn14(status.totalFee) : void 0, "getTotalFeeFromStatus");
5214
+ var getTotalFeeFromStatus = /* @__PURE__ */ __name((status) => status && "totalFee" in status ? bn15(status.totalFee) : void 0, "getTotalFeeFromStatus");
4616
5215
 
4617
5216
  // src/providers/transaction-summary/assemble-transaction-summary.ts
4618
5217
  function assembleTransactionSummary(params) {
@@ -4632,7 +5231,7 @@ function assembleTransactionSummary(params) {
4632
5231
  baseAssetId
4633
5232
  } = params;
4634
5233
  const gasUsed = getGasUsedFromReceipts(receipts);
4635
- const rawPayload = hexlify17(transactionBytes);
5234
+ const rawPayload = hexlify18(transactionBytes);
4636
5235
  const operations = getOperations({
4637
5236
  transactionType: transaction.type,
4638
5237
  inputs: transaction.inputs || [],
@@ -4644,7 +5243,7 @@ function assembleTransactionSummary(params) {
4644
5243
  baseAssetId
4645
5244
  });
4646
5245
  const typeName = getTransactionTypeName(transaction.type);
4647
- const tip = bn15(transaction.policies?.find((policy) => policy.type === PolicyType3.Tip)?.data);
5246
+ const tip = bn16(transaction.policies?.find((policy) => policy.type === PolicyType3.Tip)?.data);
4648
5247
  const { isStatusFailure, isStatusPending, isStatusSuccess, blockId, status, time, totalFee } = processGraphqlStatus(gqlTransactionStatus);
4649
5248
  const fee = totalFee ?? calculateTXFeeForSummary({
4650
5249
  gasPrice,
@@ -4693,12 +5292,88 @@ function assembleTransactionSummary(params) {
4693
5292
  return transactionSummary;
4694
5293
  }
4695
5294
  __name(assembleTransactionSummary, "assembleTransactionSummary");
5295
+ function assemblePreConfirmationTransactionSummary(params) {
5296
+ const { id, gqlTransactionStatus, transactionRequest, baseAssetId, maxInputs, abiMap } = params;
5297
+ let type;
5298
+ let operations;
5299
+ let gasUsed;
5300
+ let tip;
5301
+ let transaction;
5302
+ let mintedAssets;
5303
+ let burnedAssets;
5304
+ const {
5305
+ isStatusFailure,
5306
+ isStatusSuccess,
5307
+ isStatusPending,
5308
+ status,
5309
+ receipts,
5310
+ resolvedOutputs,
5311
+ errorReason,
5312
+ totalFee,
5313
+ isStatusPreConfirmationFailure,
5314
+ isStatusPreConfirmationSuccess
5315
+ } = processGraphqlStatus(gqlTransactionStatus);
5316
+ if (receipts) {
5317
+ gasUsed = getGasUsedFromReceipts(receipts);
5318
+ mintedAssets = extractMintedAssetsFromReceipts(receipts);
5319
+ burnedAssets = extractBurnedAssetsFromReceipts(receipts);
5320
+ }
5321
+ if (transactionRequest) {
5322
+ transaction = transactionRequest.toTransaction();
5323
+ type = getTransactionTypeName(transaction.type);
5324
+ tip = bn16(transaction.policies?.find((policy) => policy.type === PolicyType3.Tip)?.data);
5325
+ if (receipts) {
5326
+ const rawPayload = hexlify18(new TransactionCoder4().encode(transaction));
5327
+ operations = getOperations({
5328
+ transactionType: transaction.type,
5329
+ inputs: transaction.inputs || [],
5330
+ outputs: transaction.outputs || [],
5331
+ receipts,
5332
+ rawPayload,
5333
+ abiMap,
5334
+ maxInputs,
5335
+ baseAssetId
5336
+ });
5337
+ }
5338
+ }
5339
+ const transactionSummary = {
5340
+ id,
5341
+ fee: totalFee,
5342
+ type,
5343
+ status,
5344
+ receipts,
5345
+ gasUsed,
5346
+ tip,
5347
+ isStatusPreConfirmationFailure,
5348
+ isStatusPreConfirmationSuccess,
5349
+ isStatusFailure,
5350
+ isStatusSuccess,
5351
+ isStatusPending,
5352
+ ...transaction && {
5353
+ isTypeMint: isTypeMint(transaction.type),
5354
+ isTypeCreate: isTypeCreate(transaction.type),
5355
+ isTypeScript: isTypeScript(transaction.type),
5356
+ isTypeUpgrade: isTypeUpgrade(transaction.type),
5357
+ isTypeUpload: isTypeUpload(transaction.type),
5358
+ isTypeBlob: isTypeBlob(transaction.type)
5359
+ },
5360
+ mintedAssets,
5361
+ burnedAssets,
5362
+ resolvedOutputs,
5363
+ errorReason,
5364
+ transaction,
5365
+ operations
5366
+ };
5367
+ return transactionSummary;
5368
+ }
5369
+ __name(assemblePreConfirmationTransactionSummary, "assemblePreConfirmationTransactionSummary");
4696
5370
 
4697
- // src/providers/transaction-response/getDecodedLogs.ts
5371
+ // src/providers/transaction-response/getAllDecodedLogs.ts
4698
5372
  import { Interface as Interface2, BigNumberCoder } from "@fuel-ts/abi-coder";
4699
5373
  import { ZeroBytes32 as ZeroBytes3210 } from "@fuel-ts/address/configs";
4700
5374
  import { ReceiptType as ReceiptType7 } from "@fuel-ts/transactions";
4701
- function getDecodedLogs(receipts, mainAbi, externalAbis = {}) {
5375
+ function getAllDecodedLogs(opts) {
5376
+ const { receipts, mainAbi, externalAbis = {} } = opts;
4702
5377
  let mainContract = "";
4703
5378
  if (mainAbi.programType === "contract") {
4704
5379
  const firstCallReceipt = receipts.find(
@@ -4706,54 +5381,27 @@ function getDecodedLogs(receipts, mainAbi, externalAbis = {}) {
4706
5381
  );
4707
5382
  mainContract = firstCallReceipt.to;
4708
5383
  }
4709
- return receipts.reduce((logs, receipt) => {
4710
- if (receipt.type === ReceiptType7.LogData || receipt.type === ReceiptType7.Log) {
4711
- const isLogFromMainAbi = receipt.id === ZeroBytes3210 || mainContract === receipt.id;
4712
- const isDecodable = isLogFromMainAbi || externalAbis[receipt.id];
4713
- if (isDecodable) {
4714
- const interfaceToUse = isLogFromMainAbi ? new Interface2(mainAbi) : new Interface2(externalAbis[receipt.id]);
4715
- const data = receipt.type === ReceiptType7.Log ? new BigNumberCoder("u64").encode(receipt.ra) : receipt.data;
4716
- const [decodedLog] = interfaceToUse.decodeLog(data, receipt.rb.toString());
4717
- logs.push(decodedLog);
5384
+ return receipts.reduce(
5385
+ ({ logs, groupedLogs }, receipt) => {
5386
+ if (receipt.type === ReceiptType7.LogData || receipt.type === ReceiptType7.Log) {
5387
+ const isLogFromMainAbi = receipt.id === ZeroBytes3210 || mainContract === receipt.id;
5388
+ const isDecodable = isLogFromMainAbi || externalAbis[receipt.id];
5389
+ if (isDecodable) {
5390
+ const interfaceToUse = isLogFromMainAbi ? new Interface2(mainAbi) : new Interface2(externalAbis[receipt.id]);
5391
+ const data = receipt.type === ReceiptType7.Log ? new BigNumberCoder("u64").encode(receipt.ra) : receipt.data;
5392
+ const [decodedLog] = interfaceToUse.decodeLog(data, receipt.rb.toString());
5393
+ logs.push(decodedLog);
5394
+ groupedLogs[receipt.id] = [...groupedLogs[receipt.id] || [], decodedLog];
5395
+ }
4718
5396
  }
4719
- }
4720
- return logs;
4721
- }, []);
5397
+ return { logs, groupedLogs };
5398
+ },
5399
+ { logs: [], groupedLogs: {} }
5400
+ );
4722
5401
  }
4723
- __name(getDecodedLogs, "getDecodedLogs");
5402
+ __name(getAllDecodedLogs, "getAllDecodedLogs");
4724
5403
 
4725
5404
  // src/providers/transaction-response/transaction-response.ts
4726
- function mapGqlOutputsToTxOutputs(outputs) {
4727
- return outputs.map((o) => {
4728
- const obj = "amount" in o ? { ...o, amount: bn16(o.amount) } : o;
4729
- switch (obj.type) {
4730
- case "CoinOutput":
4731
- return { ...obj, type: OutputType8.Coin };
4732
- case "ContractOutput":
4733
- return {
4734
- ...obj,
4735
- type: OutputType8.Contract,
4736
- inputIndex: parseInt(obj.inputIndex, 10)
4737
- };
4738
- case "ChangeOutput":
4739
- return {
4740
- ...obj,
4741
- type: OutputType8.Change
4742
- };
4743
- case "VariableOutput":
4744
- return { ...obj, type: OutputType8.Variable };
4745
- case "ContractCreated":
4746
- return {
4747
- ...obj,
4748
- type: OutputType8.ContractCreated,
4749
- contractId: obj.contract
4750
- };
4751
- default:
4752
- return assertUnreachable(obj);
4753
- }
4754
- });
4755
- }
4756
- __name(mapGqlOutputsToTxOutputs, "mapGqlOutputsToTxOutputs");
4757
5405
  var TransactionResponse = class _TransactionResponse {
4758
5406
  /**
4759
5407
  * Constructor for `TransactionResponse`.
@@ -4763,11 +5411,16 @@ var TransactionResponse = class _TransactionResponse {
4763
5411
  */
4764
5412
  constructor(tx, provider, chainId, abis, submitTxSubscription) {
4765
5413
  this.submitTxSubscription = submitTxSubscription;
4766
- this.id = typeof tx === "string" ? tx : tx.getTransactionId(chainId);
5414
+ if (typeof tx === "string") {
5415
+ this.id = tx;
5416
+ } else {
5417
+ this.id = tx.getTransactionId(chainId);
5418
+ this.request = tx;
5419
+ }
4767
5420
  this.provider = provider;
4768
5421
  this.abis = abis;
4769
- this.request = typeof tx === "string" ? void 0 : tx;
4770
5422
  this.waitForResult = this.waitForResult.bind(this);
5423
+ this.waitForPreConfirmation = this.waitForPreConfirmation.bind(this);
4771
5424
  }
4772
5425
  static {
4773
5426
  __name(this, "TransactionResponse");
@@ -4777,12 +5430,15 @@ var TransactionResponse = class _TransactionResponse {
4777
5430
  /** Current provider */
4778
5431
  provider;
4779
5432
  /** Gas used on the transaction */
4780
- gasUsed = bn16(0);
5433
+ gasUsed = bn17(0);
4781
5434
  /** The graphql Transaction with receipts object. */
4782
5435
  gqlTransaction;
4783
5436
  request;
4784
5437
  status;
4785
5438
  abis;
5439
+ waitingForStreamData = false;
5440
+ statusResolvers = /* @__PURE__ */ new Map();
5441
+ preConfirmationStatus;
4786
5442
  /**
4787
5443
  * Async constructor for `TransactionResponse`. This method can be used to create
4788
5444
  * an instance of `TransactionResponse` and wait for the transaction to be fetched
@@ -4814,29 +5470,38 @@ var TransactionResponse = class _TransactionResponse {
4814
5470
  }
4815
5471
  return input;
4816
5472
  });
4817
- tx.outputs = mapGqlOutputsToTxOutputs(status.transaction.outputs);
4818
- if ("receiptsRoot" in status.transaction) {
5473
+ tx.outputs = status.transaction.outputs.map(deserializeProcessedTxOutput);
5474
+ if (status.transaction.receiptsRoot) {
4819
5475
  tx.receiptsRoot = status.transaction.receiptsRoot;
4820
5476
  }
4821
5477
  }
4822
5478
  }
4823
5479
  async getTransaction() {
4824
5480
  if (this.request) {
4825
- const tx = this.request.toTransaction();
4826
- this.applyMalleableSubscriptionFields(tx);
5481
+ const tx2 = this.request.toTransaction();
5482
+ this.applyMalleableSubscriptionFields(tx2);
4827
5483
  return {
4828
- tx,
5484
+ tx: tx2,
4829
5485
  bytes: this.request.toTransactionBytes()
4830
5486
  };
4831
5487
  }
4832
5488
  const gqlTransaction = this.gqlTransaction ?? await this.fetch();
5489
+ const { rawPayload } = gqlTransaction;
5490
+ const bytes = arrayify12(rawPayload);
5491
+ const [tx] = new TransactionCoder5().decode(bytes, 0);
4833
5492
  return {
4834
- tx: this.decodeTransaction(gqlTransaction),
4835
- bytes: arrayify12(gqlTransaction.rawPayload)
5493
+ tx,
5494
+ bytes
4836
5495
  };
4837
5496
  }
5497
+ /**
5498
+ *
5499
+ * NOTE: This method is only called within `getTransactionSummary`, which is invoked after `getTransaction`.
5500
+ * Since `getTransaction` only resolves once the transaction has been processed,
5501
+ * the status at this point is guaranteed to be either `SuccessStatus` or `FailureStatus`.
5502
+ */
4838
5503
  getReceipts() {
4839
- const status = this.status ?? this.gqlTransaction?.status;
5504
+ const status = this.getTransactionStatus();
4840
5505
  switch (status?.type) {
4841
5506
  case "SuccessStatus":
4842
5507
  case "FailureStatus":
@@ -4869,18 +5534,6 @@ var TransactionResponse = class _TransactionResponse {
4869
5534
  this.gqlTransaction = response.transaction;
4870
5535
  return response.transaction;
4871
5536
  }
4872
- /**
4873
- * Decode the raw payload of the transaction.
4874
- *
4875
- * @param transactionWithReceipts - The transaction with receipts object.
4876
- * @returns The decoded transaction.
4877
- */
4878
- decodeTransaction(transactionWithReceipts) {
4879
- return new TransactionCoder4().decode(
4880
- arrayify12(transactionWithReceipts.rawPayload),
4881
- 0
4882
- )?.[0];
4883
- }
4884
5537
  /**
4885
5538
  * Retrieves the TransactionSummary. If the `gqlTransaction` is not set, it will
4886
5539
  * fetch it from the provider
@@ -4891,8 +5544,9 @@ var TransactionResponse = class _TransactionResponse {
4891
5544
  async getTransactionSummary(contractsAbiMap) {
4892
5545
  const { tx: transaction, bytes: transactionBytes } = await this.getTransaction();
4893
5546
  const { gasPerByte, gasPriceFactor, gasCosts, maxGasPerTx } = await this.provider.getGasConfig();
4894
- const totalFee = getTotalFeeFromStatus(this.status ?? this.gqlTransaction?.status);
4895
- const gasPrice = totalFee ? bn16(0) : await this.provider.getLatestGasPrice();
5547
+ const transactionStatus = this.getTransactionStatus();
5548
+ const totalFee = getTotalFeeFromStatus(transactionStatus);
5549
+ const gasPrice = totalFee ? bn17(0) : await this.provider.getLatestGasPrice();
4896
5550
  const maxInputs = (await this.provider.getChain()).consensusParameters.txParameters.maxInputs;
4897
5551
  const baseAssetId = await this.provider.getBaseAssetId();
4898
5552
  const transactionSummary = assembleTransactionSummary({
@@ -4900,41 +5554,104 @@ var TransactionResponse = class _TransactionResponse {
4900
5554
  receipts: this.getReceipts(),
4901
5555
  transaction,
4902
5556
  transactionBytes,
4903
- gqlTransactionStatus: this.status ?? this.gqlTransaction?.status,
5557
+ gqlTransactionStatus: transactionStatus,
4904
5558
  gasPerByte,
4905
5559
  gasPriceFactor,
4906
5560
  abiMap: contractsAbiMap,
4907
5561
  maxInputs,
4908
- gasCosts,
4909
- maxGasPerTx,
4910
- gasPrice,
4911
- baseAssetId
5562
+ gasCosts,
5563
+ maxGasPerTx,
5564
+ gasPrice,
5565
+ baseAssetId
5566
+ });
5567
+ return transactionSummary;
5568
+ }
5569
+ async getPreConfirmationTransactionSummary(contractsAbiMap) {
5570
+ const baseAssetId = await this.provider.getBaseAssetId();
5571
+ const maxInputs = (await this.provider.getChain()).consensusParameters.txParameters.maxInputs;
5572
+ const transactionSummary = assemblePreConfirmationTransactionSummary({
5573
+ id: this.id,
5574
+ gqlTransactionStatus: this.preConfirmationStatus || this.status,
5575
+ baseAssetId,
5576
+ maxInputs,
5577
+ abiMap: contractsAbiMap,
5578
+ transactionRequest: this.request
4912
5579
  });
4913
5580
  return transactionSummary;
4914
5581
  }
5582
+ resolveStatus(type) {
5583
+ const resolvers = this.statusResolvers.get(type) || [];
5584
+ resolvers.forEach((resolve) => resolve());
5585
+ this.statusResolvers.delete(type);
5586
+ }
5587
+ async waitForStatus(type) {
5588
+ return new Promise((resolve, reject) => {
5589
+ const resolvers = this.statusResolvers.get(type) || [];
5590
+ resolvers.push(() => {
5591
+ resolve();
5592
+ });
5593
+ this.statusResolvers.set(type, resolvers);
5594
+ this.waitForStatusChange().catch(reject);
5595
+ });
5596
+ }
5597
+ /**
5598
+ * Waits for the status change of the transaction.
5599
+ * If the transaction is already in a final state, it will return immediately.
5600
+ * If the transaction is not in a final state, it will wait for the status change.
5601
+ * If we are already subscribed to the status change, it will return immediately.
5602
+ */
4915
5603
  async waitForStatusChange() {
4916
- const status = this.gqlTransaction?.status?.type;
4917
- if (status && status !== "SubmittedStatus") {
5604
+ const type = this.status?.type;
5605
+ if (type && (type === "FailureStatus" || type === "SuccessStatus")) {
5606
+ this.resolveStatus("preConfirmation");
5607
+ this.resolveStatus("confirmation");
5608
+ return;
5609
+ }
5610
+ if (this.waitingForStreamData) {
4918
5611
  return;
4919
5612
  }
5613
+ this.waitingForStreamData = true;
4920
5614
  const subscription = this.submitTxSubscription ?? await this.provider.operations.statusChange({
4921
- transactionId: this.id
5615
+ transactionId: this.id,
5616
+ includePreConfirmation: true
4922
5617
  });
4923
5618
  for await (const sub of subscription) {
4924
5619
  const statusChange = "statusChange" in sub ? sub.statusChange : sub.submitAndAwaitStatus;
4925
5620
  this.status = statusChange;
4926
5621
  if (statusChange.type === "SqueezedOutStatus") {
4927
- this.unsetResourceCache();
4928
5622
  throw new FuelError18(
4929
- ErrorCode14.TRANSACTION_SQUEEZED_OUT,
5623
+ ErrorCode15.TRANSACTION_SQUEEZED_OUT,
4930
5624
  `Transaction Squeezed Out with reason: ${statusChange.reason}`
4931
5625
  );
4932
5626
  }
4933
- if (statusChange.type !== "SubmittedStatus") {
5627
+ if (statusChange.type === "PreconfirmationSuccessStatus" || statusChange.type === "PreconfirmationFailureStatus") {
5628
+ this.preConfirmationStatus = statusChange;
5629
+ this.resolveStatus("preConfirmation");
5630
+ }
5631
+ if (statusChange.type === "SuccessStatus" || statusChange.type === "FailureStatus") {
5632
+ this.resolveStatus("confirmation");
5633
+ this.resolveStatus("preConfirmation");
5634
+ this.waitingForStreamData = false;
4934
5635
  break;
4935
5636
  }
4936
5637
  }
4937
5638
  }
5639
+ async waitForConfirmationStatuses() {
5640
+ try {
5641
+ await this.waitForStatus("confirmation");
5642
+ } catch (error) {
5643
+ this.unsetResourceCache();
5644
+ throw error;
5645
+ }
5646
+ }
5647
+ async waitForPreConfirmationStatuses() {
5648
+ try {
5649
+ await this.waitForStatus("preConfirmation");
5650
+ } catch (error) {
5651
+ this.unsetResourceCache();
5652
+ throw error;
5653
+ }
5654
+ }
4938
5655
  /**
4939
5656
  * Assembles the result of a transaction by retrieving the transaction summary,
4940
5657
  * decoding logs (if available), and handling transaction failure.
@@ -4952,37 +5669,69 @@ var TransactionResponse = class _TransactionResponse {
4952
5669
  const transactionResult = {
4953
5670
  ...transactionSummary
4954
5671
  };
4955
- let logs = [];
5672
+ let { logs, groupedLogs } = { logs: [], groupedLogs: {} };
4956
5673
  if (this.abis) {
4957
- logs = getDecodedLogs(
4958
- transactionSummary.receipts,
4959
- this.abis.main,
4960
- this.abis.otherContractsAbis
4961
- );
5674
+ ({ logs, groupedLogs } = getAllDecodedLogs({
5675
+ receipts: transactionSummary.receipts,
5676
+ mainAbi: this.abis.main,
5677
+ externalAbis: this.abis.otherContractsAbis
5678
+ }));
4962
5679
  transactionResult.logs = logs;
5680
+ transactionResult.groupedLogs = groupedLogs;
4963
5681
  }
4964
5682
  const { receipts } = transactionResult;
4965
- const status = this.status ?? this.gqlTransaction?.status;
5683
+ const status = this.getTransactionStatus();
4966
5684
  if (status?.type === "FailureStatus") {
4967
5685
  const { reason } = status;
4968
5686
  throw extractTxError({
4969
5687
  receipts,
4970
5688
  statusReason: reason,
4971
- logs
5689
+ logs,
5690
+ groupedLogs
4972
5691
  });
4973
5692
  }
4974
5693
  return transactionResult;
4975
5694
  }
5695
+ async assemblePreConfirmationResult(contractsAbiMap) {
5696
+ const transactionSummary = await this.getPreConfirmationTransactionSummary(contractsAbiMap);
5697
+ const transactionResult = {
5698
+ ...transactionSummary,
5699
+ logs: [],
5700
+ groupedLogs: {}
5701
+ };
5702
+ let { logs, groupedLogs } = { logs: [], groupedLogs: {} };
5703
+ if (this.abis && transactionSummary.receipts) {
5704
+ ({ logs, groupedLogs } = getAllDecodedLogs({
5705
+ receipts: transactionSummary.receipts,
5706
+ mainAbi: this.abis.main,
5707
+ externalAbis: this.abis.otherContractsAbis
5708
+ }));
5709
+ transactionResult.logs = logs;
5710
+ transactionResult.groupedLogs = groupedLogs;
5711
+ }
5712
+ return transactionResult;
5713
+ }
4976
5714
  /**
4977
5715
  * Waits for transaction to complete and returns the result.
4978
5716
  *
4979
5717
  * @returns The completed transaction result
4980
5718
  */
4981
5719
  async waitForResult(contractsAbiMap) {
4982
- await this.waitForStatusChange();
5720
+ await this.waitForConfirmationStatuses();
4983
5721
  this.unsetResourceCache();
4984
5722
  return this.assembleResult(contractsAbiMap);
4985
5723
  }
5724
+ /**
5725
+ * Waits for the transaction's pre-confirmation and returns the result.
5726
+ *
5727
+ * @param contractsAbiMap - The contracts ABI map.
5728
+ * @returns The pre-confirmed transaction result
5729
+ */
5730
+ async waitForPreConfirmation(contractsAbiMap) {
5731
+ await this.waitForPreConfirmationStatuses();
5732
+ this.unsetResourceCache();
5733
+ return this.assemblePreConfirmationResult(contractsAbiMap);
5734
+ }
4986
5735
  /**
4987
5736
  * Waits for transaction to complete and returns the result.
4988
5737
  *
@@ -4994,8 +5743,16 @@ var TransactionResponse = class _TransactionResponse {
4994
5743
  unsetResourceCache() {
4995
5744
  this.provider.cache?.unset(this.id);
4996
5745
  }
5746
+ getTransactionStatus() {
5747
+ return this.status ?? this.gqlTransaction?.status;
5748
+ }
4997
5749
  };
4998
5750
 
5751
+ // src/providers/transaction-response/getDecodedLogs.ts
5752
+ import { Interface as Interface3, BigNumberCoder as BigNumberCoder2 } from "@fuel-ts/abi-coder";
5753
+ import { ZeroBytes32 as ZeroBytes3211 } from "@fuel-ts/address/configs";
5754
+ import { ReceiptType as ReceiptType8 } from "@fuel-ts/transactions";
5755
+
4999
5756
  // src/providers/utils/auto-retry-fetch.ts
5000
5757
  import { sleep } from "@fuel-ts/utils";
5001
5758
  function getWaitDelay(options, retryAttemptNum) {
@@ -5035,48 +5792,49 @@ function autoRetryFetch(fetchFn, options, retryAttemptNum = 0) {
5035
5792
  }
5036
5793
  __name(autoRetryFetch, "autoRetryFetch");
5037
5794
 
5038
- // src/providers/utils/helpers.ts
5039
- var adjustResourcesToExclude = /* @__PURE__ */ __name((params) => {
5040
- const { userInput, cached, maxInputs } = params;
5041
- const final = { ...userInput };
5042
- let total = final.utxos.length + final.messages.length;
5043
- if (total >= maxInputs) {
5044
- return final;
5045
- }
5046
- final.utxos = [...final.utxos, ...cached.utxos.slice(0, maxInputs - total)];
5047
- total = final.utxos.length + final.messages.length;
5048
- if (total < maxInputs) {
5049
- final.messages = [...final.messages, ...cached.messages.slice(0, maxInputs - total)];
5795
+ // src/providers/utils/parse-graphql-response.ts
5796
+ var parseGraphqlResponse = /* @__PURE__ */ __name(async (options) => {
5797
+ const { response, isSubscription } = options;
5798
+ let extensions;
5799
+ const responseClone = response.clone();
5800
+ if (isSubscription) {
5801
+ const reader = responseClone.body?.getReader();
5802
+ const { event } = await FuelGraphqlSubscriber.readEvent(reader);
5803
+ extensions = event?.extensions;
5804
+ } else {
5805
+ extensions = (await responseClone.json()).extensions;
5050
5806
  }
5051
- return final;
5052
- }, "adjustResourcesToExclude");
5807
+ return {
5808
+ extensions
5809
+ };
5810
+ }, "parseGraphqlResponse");
5053
5811
 
5054
5812
  // src/providers/utils/validate-pagination-args.ts
5055
- import { FuelError as FuelError19, ErrorCode as ErrorCode15 } from "@fuel-ts/errors";
5813
+ import { FuelError as FuelError19, ErrorCode as ErrorCode16 } from "@fuel-ts/errors";
5056
5814
  var validatePaginationArgs = /* @__PURE__ */ __name((params) => {
5057
5815
  const { paginationLimit, inputArgs = {} } = params;
5058
5816
  const { first, last, after, before } = inputArgs;
5059
5817
  if (after && before) {
5060
5818
  throw new FuelError19(
5061
- ErrorCode15.INVALID_INPUT_PARAMETERS,
5819
+ ErrorCode16.INVALID_INPUT_PARAMETERS,
5062
5820
  'Pagination arguments "after" and "before" cannot be used together'
5063
5821
  );
5064
5822
  }
5065
5823
  if ((first || 0) > paginationLimit || (last || 0) > paginationLimit) {
5066
5824
  throw new FuelError19(
5067
- ErrorCode15.INVALID_INPUT_PARAMETERS,
5825
+ ErrorCode16.INVALID_INPUT_PARAMETERS,
5068
5826
  `Pagination limit for this query cannot exceed ${paginationLimit} items`
5069
5827
  );
5070
5828
  }
5071
5829
  if (first && before) {
5072
5830
  throw new FuelError19(
5073
- ErrorCode15.INVALID_INPUT_PARAMETERS,
5831
+ ErrorCode16.INVALID_INPUT_PARAMETERS,
5074
5832
  'The use of pagination argument "first" with "before" is not supported'
5075
5833
  );
5076
5834
  }
5077
5835
  if (last && after) {
5078
5836
  throw new FuelError19(
5079
- ErrorCode15.INVALID_INPUT_PARAMETERS,
5837
+ ErrorCode16.INVALID_INPUT_PARAMETERS,
5080
5838
  'The use of pagination argument "last" with "after" is not supported'
5081
5839
  );
5082
5840
  }
@@ -5095,22 +5853,48 @@ var NON_PAGINATED_BALANCES_SIZE = 1e4;
5095
5853
  var BLOCKS_PAGE_SIZE_LIMIT = 5;
5096
5854
  var DEFAULT_RESOURCE_CACHE_TTL = 2e4;
5097
5855
  var GAS_USED_MODIFIER = 1.2;
5856
+ var WRITE_OPERATIONS = [
5857
+ "submit",
5858
+ "submitAndAwaitStatus",
5859
+ "produceBlocks"
5860
+ ];
5098
5861
  var Provider = class _Provider {
5099
5862
  static {
5100
5863
  __name(this, "Provider");
5101
5864
  }
5102
5865
  operations;
5103
5866
  cache;
5104
- /** @hidden */
5105
- static clearChainAndNodeCaches() {
5867
+ /**
5868
+ * @hidden
5869
+ * @param url - If provided, clears cache only for given url
5870
+ */
5871
+ static clearChainAndNodeCaches(url) {
5872
+ if (url) {
5873
+ delete _Provider.inflightFetchChainAndNodeInfoRequests[url];
5874
+ delete _Provider.chainInfoCache[url];
5875
+ delete _Provider.nodeInfoCache[url];
5876
+ delete _Provider.currentBlockHeightCache[url];
5877
+ return;
5878
+ }
5106
5879
  _Provider.inflightFetchChainAndNodeInfoRequests = {};
5107
5880
  _Provider.nodeInfoCache = {};
5108
5881
  _Provider.chainInfoCache = {};
5882
+ _Provider.currentBlockHeightCache = {};
5109
5883
  }
5110
5884
  /** @hidden */
5111
5885
  url;
5112
5886
  /** @hidden */
5113
5887
  urlWithoutAuth;
5888
+ /**
5889
+ * Governs whether to include the required block height in the request body
5890
+ * for block-sensitive operations like when submitting a transaction.
5891
+ *
5892
+ * This ensures that the operation is executed at the correct block height,
5893
+ * regardless of which node in the network the request is routed to.
5894
+ *
5895
+ * `true` by default.
5896
+ */
5897
+ static ENABLE_RPC_CONSISTENCY = true;
5114
5898
  /** @hidden */
5115
5899
  static inflightFetchChainAndNodeInfoRequests = {};
5116
5900
  /** @hidden */
@@ -5118,6 +5902,8 @@ var Provider = class _Provider {
5118
5902
  /** @hidden */
5119
5903
  static nodeInfoCache = {};
5120
5904
  /** @hidden */
5905
+ static currentBlockHeightCache = {};
5906
+ /** @hidden */
5121
5907
  static incompatibleNodeVersionMessage = "";
5122
5908
  /** @hidden */
5123
5909
  consensusParametersTimestamp;
@@ -5129,6 +5915,18 @@ var Provider = class _Provider {
5129
5915
  headers: void 0,
5130
5916
  cache: void 0
5131
5917
  };
5918
+ static extractOperationName(body) {
5919
+ return body?.toString().match(/"operationName":"(.+)"/)?.[1];
5920
+ }
5921
+ static isWriteOperation(body) {
5922
+ return WRITE_OPERATIONS.includes(this.extractOperationName(body));
5923
+ }
5924
+ static normalizeUrl(url) {
5925
+ return url.replace(/-sub$/, "");
5926
+ }
5927
+ static hasWriteOperationHappened(url) {
5928
+ return isDefined3(_Provider.currentBlockHeightCache[this.normalizeUrl(url)]);
5929
+ }
5132
5930
  /**
5133
5931
  * @hidden
5134
5932
  */
@@ -5146,9 +5944,57 @@ var Provider = class _Provider {
5146
5944
  if (options.requestMiddleware) {
5147
5945
  fullRequest = await options.requestMiddleware(fullRequest);
5148
5946
  }
5149
- return options.fetch ? options.fetch(url, fullRequest, options) : fetch(url, fullRequest);
5947
+ if (_Provider.ENABLE_RPC_CONSISTENCY && _Provider.hasWriteOperationHappened(url)) {
5948
+ _Provider.applyBlockHeight(fullRequest, url);
5949
+ }
5950
+ return _Provider.fetchAndProcessBlockHeight(url, fullRequest, options);
5150
5951
  }, retryOptions);
5151
5952
  }
5953
+ static applyBlockHeight(request, url) {
5954
+ const normalizedUrl = this.normalizeUrl(url);
5955
+ const currentBlockHeight = _Provider.currentBlockHeightCache[normalizedUrl] ?? 0;
5956
+ request.body = request.body?.toString().replace(/}$/, `,"extensions":{"required_fuel_block_height":${currentBlockHeight}}}`);
5957
+ }
5958
+ static async fetchAndProcessBlockHeight(url, request, options) {
5959
+ const fetchFn = /* @__PURE__ */ __name(() => options.fetch ? options.fetch(url, request, options) : fetch(url, request), "fetchFn");
5960
+ const isWriteOperation = _Provider.isWriteOperation(request.body);
5961
+ if (isWriteOperation && !_Provider.hasWriteOperationHappened(url)) {
5962
+ _Provider.currentBlockHeightCache[_Provider.normalizeUrl(url)] = 0;
5963
+ }
5964
+ let response = await fetchFn();
5965
+ if (!_Provider.ENABLE_RPC_CONSISTENCY) {
5966
+ return response;
5967
+ }
5968
+ const retryOptions = {
5969
+ maxRetries: 5,
5970
+ baseDelay: 500
5971
+ };
5972
+ for (let retriesLeft = retryOptions.maxRetries; retriesLeft > 0; --retriesLeft) {
5973
+ const { extensions } = await parseGraphqlResponse({
5974
+ response,
5975
+ isSubscription: url.endsWith("-sub")
5976
+ });
5977
+ _Provider.setCurrentBlockHeight(url, extensions?.current_fuel_block_height);
5978
+ if (!extensions?.fuel_block_height_precondition_failed) {
5979
+ break;
5980
+ }
5981
+ const retryAttempt = retryOptions.maxRetries - retriesLeft + 1;
5982
+ const sleepTime = getWaitDelay(retryOptions, retryAttempt);
5983
+ await sleep2(sleepTime);
5984
+ response = await fetchFn();
5985
+ }
5986
+ return response;
5987
+ }
5988
+ static setCurrentBlockHeight(url, height) {
5989
+ const writeOperationHappened = _Provider.hasWriteOperationHappened(url);
5990
+ if (!isDefined3(height) || !writeOperationHappened) {
5991
+ return;
5992
+ }
5993
+ const normalizedUrl = _Provider.normalizeUrl(url);
5994
+ if (height > _Provider.currentBlockHeightCache[normalizedUrl]) {
5995
+ _Provider.currentBlockHeightCache[normalizedUrl] = height;
5996
+ }
5997
+ }
5152
5998
  /**
5153
5999
  * Constructor to initialize a Provider.
5154
6000
  *
@@ -5176,7 +6022,7 @@ var Provider = class _Provider {
5176
6022
  _Provider.chainInfoCache[this.urlWithoutAuth] = chain;
5177
6023
  _Provider.nodeInfoCache[this.urlWithoutAuth] = nodeInfo;
5178
6024
  }
5179
- if (isDefined2(resourceCacheTTL)) {
6025
+ if (isDefined3(resourceCacheTTL)) {
5180
6026
  if (resourceCacheTTL !== -1) {
5181
6027
  this.cache = new ResourceCache(resourceCacheTTL);
5182
6028
  } else {
@@ -5234,6 +6080,7 @@ var Provider = class _Provider {
5234
6080
  * Returns some helpful parameters related to gas fees.
5235
6081
  */
5236
6082
  async getGasConfig() {
6083
+ await this.init();
5237
6084
  const {
5238
6085
  txParameters: { maxGasPerTx },
5239
6086
  predicateParameters: { maxGasPerPredicate },
@@ -5269,39 +6116,52 @@ var Provider = class _Provider {
5269
6116
  * @returns A promise that resolves to the Chain and NodeInfo.
5270
6117
  */
5271
6118
  async fetchChainAndNodeInfo(ignoreCache = false) {
5272
- let nodeInfo;
5273
- let chain;
5274
- try {
5275
- nodeInfo = _Provider.nodeInfoCache[this.urlWithoutAuth];
5276
- chain = _Provider.chainInfoCache[this.urlWithoutAuth];
5277
- const noCache = !nodeInfo || !chain;
5278
- if (ignoreCache || noCache) {
5279
- throw new Error(`Jumps to the catch block and re-fetch`);
5280
- }
5281
- } catch (_err) {
5282
- const inflightRequest = _Provider.inflightFetchChainAndNodeInfoRequests[this.urlWithoutAuth];
5283
- if (inflightRequest) {
5284
- const now2 = await inflightRequest;
5285
- this.consensusParametersTimestamp = now2;
5286
- return this.fetchChainAndNodeInfo();
5287
- }
5288
- const { promise, resolve } = deferPromise();
5289
- _Provider.inflightFetchChainAndNodeInfoRequests[this.urlWithoutAuth] = promise;
5290
- const data = await this.operations.getChainAndNodeInfo();
5291
- nodeInfo = deserializeNodeInfo(data.nodeInfo);
5292
- chain = deserializeChain(data.chain);
5293
- _Provider.setIncompatibleNodeVersionMessage(nodeInfo);
5294
- _Provider.chainInfoCache[this.urlWithoutAuth] = chain;
5295
- _Provider.nodeInfoCache[this.urlWithoutAuth] = nodeInfo;
5296
- const now = Date.now();
5297
- this.consensusParametersTimestamp = now;
5298
- resolve(now);
5299
- delete _Provider.inflightFetchChainAndNodeInfoRequests[this.urlWithoutAuth];
6119
+ const nodeInfo = _Provider.nodeInfoCache[this.urlWithoutAuth];
6120
+ const chain = _Provider.chainInfoCache[this.urlWithoutAuth];
6121
+ const hasCache = nodeInfo && chain;
6122
+ if (hasCache && !ignoreCache) {
6123
+ return { nodeInfo, chain };
6124
+ }
6125
+ const inflightRequest = _Provider.inflightFetchChainAndNodeInfoRequests[this.urlWithoutAuth];
6126
+ if (inflightRequest) {
6127
+ return inflightRequest.then((data) => {
6128
+ this.consensusParametersTimestamp = data.consensusParametersTimestamp;
6129
+ return {
6130
+ nodeInfo: _Provider.nodeInfoCache[this.urlWithoutAuth],
6131
+ chain: _Provider.chainInfoCache[this.urlWithoutAuth]
6132
+ };
6133
+ });
5300
6134
  }
5301
- return {
5302
- chain,
5303
- nodeInfo
5304
- };
6135
+ const getChainAndNodeInfoFromNetwork = this.operations.getChainAndNodeInfo().then((data) => ({
6136
+ chain: deserializeChain(data.chain),
6137
+ nodeInfo: deserializeNodeInfo(data.nodeInfo),
6138
+ consensusParametersTimestamp: Date.now()
6139
+ })).then((data) => {
6140
+ _Provider.setIncompatibleNodeVersionMessage(data.nodeInfo);
6141
+ _Provider.chainInfoCache[this.urlWithoutAuth] = data.chain;
6142
+ _Provider.nodeInfoCache[this.urlWithoutAuth] = data.nodeInfo;
6143
+ this.consensusParametersTimestamp = data.consensusParametersTimestamp;
6144
+ return data;
6145
+ }).catch((err) => {
6146
+ const error = new FuelError20(
6147
+ FuelError20.CODES.CONNECTION_REFUSED,
6148
+ "Unable to fetch chain and node info from the network",
6149
+ { url: this.urlWithoutAuth },
6150
+ err
6151
+ );
6152
+ error.cause = { code: "ECONNREFUSED" };
6153
+ throw error;
6154
+ }).finally(() => {
6155
+ delete _Provider.inflightFetchChainAndNodeInfoRequests[this.urlWithoutAuth];
6156
+ });
6157
+ _Provider.inflightFetchChainAndNodeInfoRequests[this.urlWithoutAuth] = getChainAndNodeInfoFromNetwork;
6158
+ return _Provider.inflightFetchChainAndNodeInfoRequests[this.urlWithoutAuth].then((data) => {
6159
+ this.consensusParametersTimestamp = data.consensusParametersTimestamp;
6160
+ return {
6161
+ nodeInfo: _Provider.nodeInfoCache[this.urlWithoutAuth],
6162
+ chain: _Provider.chainInfoCache[this.urlWithoutAuth]
6163
+ };
6164
+ });
5305
6165
  }
5306
6166
  /**
5307
6167
  * @hidden
@@ -5345,7 +6205,14 @@ var Provider = class _Provider {
5345
6205
  url: this.urlWithoutAuth,
5346
6206
  query,
5347
6207
  fetchFn: /* @__PURE__ */ __name((url, requestInit) => fetchFn(url, requestInit, this.options), "fetchFn"),
5348
- variables: vars
6208
+ variables: vars,
6209
+ operationName: opDefinition.name.value,
6210
+ onEvent: /* @__PURE__ */ __name((event) => {
6211
+ _Provider.setCurrentBlockHeight(
6212
+ this.urlWithoutAuth,
6213
+ event.extensions?.current_fuel_block_height
6214
+ );
6215
+ }, "onEvent")
5349
6216
  });
5350
6217
  }
5351
6218
  return gqlClient.request(query, vars);
@@ -5393,7 +6260,7 @@ var Provider = class _Provider {
5393
6260
  latestBlock: { height }
5394
6261
  }
5395
6262
  } = await this.operations.getLatestBlockHeight();
5396
- return bn17(height);
6263
+ return bn18(height);
5397
6264
  }
5398
6265
  /**
5399
6266
  * Returns the node information for the current provider network.
@@ -5450,7 +6317,7 @@ var Provider = class _Provider {
5450
6317
  const { assetMetadata } = await this.getNodeFeatures();
5451
6318
  if (!assetMetadata) {
5452
6319
  throw new FuelError20(
5453
- ErrorCode16.UNSUPPORTED_FEATURE,
6320
+ ErrorCode17.UNSUPPORTED_FEATURE,
5454
6321
  "The current node does not supports fetching asset details"
5455
6322
  );
5456
6323
  }
@@ -5459,7 +6326,7 @@ var Provider = class _Provider {
5459
6326
  return {
5460
6327
  subId,
5461
6328
  contractId,
5462
- totalSupply: bn17(totalSupply)
6329
+ totalSupply: bn18(totalSupply)
5463
6330
  };
5464
6331
  }
5465
6332
  /**
@@ -5480,15 +6347,15 @@ var Provider = class _Provider {
5480
6347
  txParameters: { maxInputs, maxOutputs }
5481
6348
  }
5482
6349
  } = await this.getChain();
5483
- if (bn17(tx.inputs.length).gt(maxInputs)) {
6350
+ if (bn18(tx.inputs.length).gt(maxInputs)) {
5484
6351
  throw new FuelError20(
5485
- ErrorCode16.MAX_INPUTS_EXCEEDED,
6352
+ ErrorCode17.MAX_INPUTS_EXCEEDED,
5486
6353
  `The transaction exceeds the maximum allowed number of inputs. Tx inputs: ${tx.inputs.length}, max inputs: ${maxInputs}`
5487
6354
  );
5488
6355
  }
5489
- if (bn17(tx.outputs.length).gt(maxOutputs)) {
6356
+ if (bn18(tx.outputs.length).gt(maxOutputs)) {
5490
6357
  throw new FuelError20(
5491
- ErrorCode16.MAX_OUTPUTS_EXCEEDED,
6358
+ ErrorCode17.MAX_OUTPUTS_EXCEEDED,
5492
6359
  `The transaction exceeds the maximum allowed number of outputs. Tx outputs: ${tx.outputs.length}, max outputs: ${maxOutputs}`
5493
6360
  );
5494
6361
  }
@@ -5503,7 +6370,11 @@ var Provider = class _Provider {
5503
6370
  * @param sendTransactionParams - The provider send transaction parameters (optional).
5504
6371
  * @returns A promise that resolves to the transaction response object.
5505
6372
  */
5506
- async sendTransaction(transactionRequestLike, { estimateTxDependencies = true, enableAssetBurn } = {}) {
6373
+ async sendTransaction(transactionRequestLike, {
6374
+ enableAssetBurn,
6375
+ estimateTxDependencies = true,
6376
+ includePreConfirmation: _includePreConfirmation = true
6377
+ } = {}) {
5507
6378
  const transactionRequest = transactionRequestify(transactionRequestLike);
5508
6379
  validateTransactionForAssetBurn(
5509
6380
  await this.getBaseAssetId(),
@@ -5514,12 +6385,15 @@ var Provider = class _Provider {
5514
6385
  await this.estimateTxDependencies(transactionRequest);
5515
6386
  }
5516
6387
  await this.validateTransaction(transactionRequest);
5517
- const encodedTransaction = hexlify18(transactionRequest.toTransactionBytes());
6388
+ const encodedTransaction = hexlify19(transactionRequest.toTransactionBytes());
5518
6389
  let abis;
5519
6390
  if (isTransactionTypeScript(transactionRequest)) {
5520
6391
  abis = transactionRequest.abis;
5521
6392
  }
5522
- const subscription = await this.operations.submitAndAwaitStatus({ encodedTransaction });
6393
+ const subscription = await this.operations.submitAndAwaitStatus({
6394
+ encodedTransaction,
6395
+ includePreConfirmation: true
6396
+ });
5523
6397
  this.#cacheInputs(
5524
6398
  transactionRequest.inputs,
5525
6399
  transactionRequest.getTransactionId(await this.getChainId())
@@ -5542,7 +6416,7 @@ var Provider = class _Provider {
5542
6416
  if (estimateTxDependencies) {
5543
6417
  return this.estimateTxDependencies(transactionRequest);
5544
6418
  }
5545
- const encodedTransaction = hexlify18(transactionRequest.toTransactionBytes());
6419
+ const encodedTransaction = hexlify19(transactionRequest.toTransactionBytes());
5546
6420
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
5547
6421
  encodedTransactions: encodedTransaction,
5548
6422
  utxoValidation: utxoValidation || false
@@ -5561,12 +6435,12 @@ var Provider = class _Provider {
5561
6435
  */
5562
6436
  async estimatePredicates(transactionRequest) {
5563
6437
  const shouldEstimatePredicates = transactionRequest.inputs.some(
5564
- (input) => isPredicate(input) && bn17(input.predicateGasUsed).isZero()
6438
+ (input) => isPredicate(input) && bn18(input.predicateGasUsed).isZero()
5565
6439
  );
5566
6440
  if (!shouldEstimatePredicates) {
5567
6441
  return transactionRequest;
5568
6442
  }
5569
- const encodedTransaction = hexlify18(transactionRequest.toTransactionBytes());
6443
+ const encodedTransaction = hexlify19(transactionRequest.toTransactionBytes());
5570
6444
  const response = await this.operations.estimatePredicates({
5571
6445
  encodedTransaction
5572
6446
  });
@@ -5587,7 +6461,7 @@ var Provider = class _Provider {
5587
6461
  */
5588
6462
  async estimatePredicatesAndGasPrice(transactionRequest, blockHorizon) {
5589
6463
  const shouldEstimatePredicates = transactionRequest.inputs.some(
5590
- (input) => isPredicate(input) && bn17(input.predicateGasUsed).isZero()
6464
+ (input) => isPredicate(input) && bn18(input.predicateGasUsed).isZero()
5591
6465
  );
5592
6466
  if (!shouldEstimatePredicates) {
5593
6467
  const gasPrice2 = await this.estimateGasPrice(blockHorizon);
@@ -5598,13 +6472,13 @@ var Provider = class _Provider {
5598
6472
  estimatePredicates
5599
6473
  } = await this.operations.estimatePredicatesAndGasPrice({
5600
6474
  blockHorizon: String(blockHorizon),
5601
- encodedTransaction: hexlify18(transactionRequest.toTransactionBytes())
6475
+ encodedTransaction: hexlify19(transactionRequest.toTransactionBytes())
5602
6476
  });
5603
6477
  transactionRequest = this.parseEstimatePredicatesResponse(
5604
6478
  transactionRequest,
5605
6479
  estimatePredicates
5606
6480
  );
5607
- return { transactionRequest, gasPrice: bn17(gasPrice) };
6481
+ return { transactionRequest, gasPrice: bn18(gasPrice) };
5608
6482
  }
5609
6483
  /**
5610
6484
  * Will dryRun a transaction and check for missing dependencies.
@@ -5636,7 +6510,7 @@ var Provider = class _Provider {
5636
6510
  const {
5637
6511
  dryRun: [{ receipts: serializedReceipts, status }]
5638
6512
  } = await this.operations.dryRun({
5639
- encodedTransactions: [hexlify18(transactionRequest.toTransactionBytes())],
6513
+ encodedTransactions: [hexlify19(transactionRequest.toTransactionBytes())],
5640
6514
  utxoValidation: false,
5641
6515
  gasPrice: gasPrice.toString()
5642
6516
  });
@@ -5691,7 +6565,7 @@ var Provider = class _Provider {
5691
6565
  const serializedTransactionsMap = /* @__PURE__ */ new Map();
5692
6566
  allRequests.forEach((req, index) => {
5693
6567
  if (isTransactionTypeScript(req)) {
5694
- serializedTransactionsMap.set(index, hexlify18(req.toTransactionBytes()));
6568
+ serializedTransactionsMap.set(index, hexlify19(req.toTransactionBytes()));
5695
6569
  }
5696
6570
  });
5697
6571
  let transactionsToProcess = Array.from(serializedTransactionsMap.keys());
@@ -5727,7 +6601,7 @@ var Provider = class _Provider {
5727
6601
  transactionRequest: request
5728
6602
  });
5729
6603
  request.maxFee = maxFee;
5730
- serializedTransactionsMap.set(requestIdx, hexlify18(request.toTransactionBytes()));
6604
+ serializedTransactionsMap.set(requestIdx, hexlify19(request.toTransactionBytes()));
5731
6605
  nextRoundTransactions.push(requestIdx);
5732
6606
  }
5733
6607
  }
@@ -5748,7 +6622,7 @@ var Provider = class _Provider {
5748
6622
  if (estimateTxDependencies) {
5749
6623
  return this.estimateMultipleTxDependencies(transactionRequests);
5750
6624
  }
5751
- const encodedTransactions = transactionRequests.map((tx) => hexlify18(tx.toTransactionBytes()));
6625
+ const encodedTransactions = transactionRequests.map((tx) => hexlify19(tx.toTransactionBytes()));
5752
6626
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
5753
6627
  encodedTransactions,
5754
6628
  utxoValidation: utxoValidation || false
@@ -5796,16 +6670,16 @@ var Provider = class _Provider {
5796
6670
  const chainInfo = await this.getChain();
5797
6671
  const { gasPriceFactor, maxGasPerTx } = await this.getGasConfig();
5798
6672
  const minGas = transactionRequest.calculateMinGas(chainInfo);
5799
- if (!isDefined2(gasPrice)) {
6673
+ if (!isDefined3(gasPrice)) {
5800
6674
  gasPrice = await this.estimateGasPrice(10);
5801
6675
  }
5802
6676
  const minFee = calculateGasFee({
5803
- gasPrice: bn17(gasPrice),
6677
+ gasPrice: bn18(gasPrice),
5804
6678
  gas: minGas,
5805
6679
  priceFactor: gasPriceFactor,
5806
6680
  tip: transactionRequest.tip
5807
6681
  }).add(1);
5808
- let gasLimit = bn17(0);
6682
+ let gasLimit = bn18(0);
5809
6683
  if (isTransactionTypeScript(transactionRequest)) {
5810
6684
  gasLimit = transactionRequest.gasLimit;
5811
6685
  if (transactionRequest.gasLimit.eq(0)) {
@@ -5818,7 +6692,7 @@ var Provider = class _Provider {
5818
6692
  }
5819
6693
  const maxGas = transactionRequest.calculateMaxGas(chainInfo, minGas);
5820
6694
  const maxFee = calculateGasFee({
5821
- gasPrice: bn17(gasPrice),
6695
+ gasPrice: bn18(gasPrice),
5822
6696
  gas: maxGas,
5823
6697
  priceFactor: gasPriceFactor,
5824
6698
  tip: transactionRequest.tip
@@ -5848,7 +6722,7 @@ var Provider = class _Provider {
5848
6722
  if (estimateTxDependencies) {
5849
6723
  return this.estimateTxDependencies(transactionRequest);
5850
6724
  }
5851
- const encodedTransactions = [hexlify18(transactionRequest.toTransactionBytes())];
6725
+ const encodedTransactions = [hexlify19(transactionRequest.toTransactionBytes())];
5852
6726
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
5853
6727
  encodedTransactions,
5854
6728
  utxoValidation: true
@@ -5871,13 +6745,16 @@ var Provider = class _Provider {
5871
6745
  * @param transactionCostParams - The transaction cost parameters (optional).
5872
6746
  *
5873
6747
  * @returns A promise that resolves to the transaction cost object.
6748
+ *
6749
+ * @deprecated Use provider.assembleTx instead
6750
+ * Check the migration guide https://docs.fuel.network/guide/assembling-transactions/migration-guide.html for more information.
5874
6751
  */
5875
6752
  async getTransactionCost(transactionRequestLike, { signatureCallback, gasPrice: gasPriceParam } = {}) {
5876
6753
  const txRequestClone = clone8(transactionRequestify(transactionRequestLike));
5877
6754
  const updateMaxFee = txRequestClone.maxFee.eq(0);
5878
6755
  const isScriptTransaction = isTransactionTypeScript(txRequestClone);
5879
6756
  if (isScriptTransaction) {
5880
- txRequestClone.gasLimit = bn17(0);
6757
+ txRequestClone.gasLimit = bn18(0);
5881
6758
  }
5882
6759
  const signedRequest = clone8(txRequestClone);
5883
6760
  let addedSignatures = 0;
@@ -5904,7 +6781,7 @@ var Provider = class _Provider {
5904
6781
  let dryRunStatus;
5905
6782
  let missingContractIds = [];
5906
6783
  let outputVariables = 0;
5907
- let gasUsed = bn17(0);
6784
+ let gasUsed = bn18(0);
5908
6785
  txRequestClone.maxFee = maxFee;
5909
6786
  if (isScriptTransaction) {
5910
6787
  txRequestClone.gasLimit = gasLimit;
@@ -5913,11 +6790,11 @@ var Provider = class _Provider {
5913
6790
  }
5914
6791
  ({ rawReceipts, receipts, missingContractIds, outputVariables, dryRunStatus } = await this.estimateTxDependencies(txRequestClone, { gasPrice }));
5915
6792
  if (dryRunStatus && "reason" in dryRunStatus) {
5916
- throw this.extractDryRunError(txRequestClone, receipts, dryRunStatus);
6793
+ throw this.extractDryRunError(txRequestClone, receipts, dryRunStatus.reason);
5917
6794
  }
5918
6795
  const { maxGasPerTx } = await this.getGasConfig();
5919
6796
  const pristineGasUsed = getGasUsedFromReceipts(receipts);
5920
- gasUsed = bn17(pristineGasUsed.muln(GAS_USED_MODIFIER)).max(maxGasPerTx.sub(minGas));
6797
+ gasUsed = bn18(pristineGasUsed.muln(GAS_USED_MODIFIER)).max(maxGasPerTx.sub(minGas));
5921
6798
  txRequestClone.gasLimit = gasUsed;
5922
6799
  ({ maxFee, maxGas, minFee, minGas } = await this.estimateTxGasAndFee({
5923
6800
  transactionRequest: txRequestClone,
@@ -5946,6 +6823,102 @@ var Provider = class _Provider {
5946
6823
  transactionSummary
5947
6824
  };
5948
6825
  }
6826
+ /**
6827
+ * Assembles a transaction by completely estimating and funding it.
6828
+ *
6829
+ * @param params - Parameters used to assemble the transaction.
6830
+ *
6831
+ * @returns The assembled transaction request, estimated gas price, and receipts
6832
+ */
6833
+ async assembleTx(params) {
6834
+ const {
6835
+ request,
6836
+ reserveGas,
6837
+ resourcesIdsToIgnore,
6838
+ feePayerAccount,
6839
+ blockHorizon = 10,
6840
+ estimatePredicates = true,
6841
+ accountCoinQuantities = []
6842
+ } = params;
6843
+ const allAddresses = /* @__PURE__ */ new Set();
6844
+ const baseAssetId = await this.getBaseAssetId();
6845
+ let feePayerIndex = -1;
6846
+ let baseAssetChange;
6847
+ const requiredBalances = accountCoinQuantities.map((quantity, index) => {
6848
+ const { amount, assetId, account = feePayerAccount, changeOutputAccount } = quantity;
6849
+ const changeAccountAddress = changeOutputAccount ? changeOutputAccount.address.toB256() : account.address.toB256();
6850
+ allAddresses.add(account.address.toB256());
6851
+ const changePolicy = {
6852
+ change: changeAccountAddress
6853
+ };
6854
+ if (assetId === baseAssetId) {
6855
+ baseAssetChange = changePolicy.change;
6856
+ }
6857
+ if (account.address.equals(feePayerAccount.address)) {
6858
+ feePayerIndex = index;
6859
+ }
6860
+ const requiredBalance = {
6861
+ account: resolveAccountForAssembleTxParams(account),
6862
+ amount: bn18(amount).toString(10),
6863
+ assetId,
6864
+ changePolicy
6865
+ };
6866
+ return requiredBalance;
6867
+ });
6868
+ if (feePayerIndex === -1) {
6869
+ allAddresses.add(feePayerAccount.address.toB256());
6870
+ const newLength = requiredBalances.push({
6871
+ account: resolveAccountForAssembleTxParams(feePayerAccount),
6872
+ amount: bn18(0).toString(10),
6873
+ // Since the correct fee amount cannot be determined yet, we can use 0
6874
+ assetId: baseAssetId,
6875
+ changePolicy: {
6876
+ change: baseAssetChange || feePayerAccount.address.toB256()
6877
+ }
6878
+ });
6879
+ feePayerIndex = newLength - 1;
6880
+ }
6881
+ const excludeInput = await this.adjustResourcesToIgnoreForAddresses(
6882
+ Array.from(allAddresses),
6883
+ resourcesIdsToIgnore
6884
+ );
6885
+ const {
6886
+ assembleTx: { status, transaction: gqlTransaction, gasPrice }
6887
+ } = await this.operations.assembleTx({
6888
+ tx: hexlify19(request.toTransactionBytes()),
6889
+ blockHorizon: String(blockHorizon),
6890
+ feeAddressIndex: String(feePayerIndex),
6891
+ requiredBalances,
6892
+ estimatePredicates,
6893
+ excludeInput,
6894
+ reserveGas: reserveGas ? reserveGas.toString(10) : void 0
6895
+ });
6896
+ if (status.type === "DryRunFailureStatus") {
6897
+ const parsedReceipts = status.receipts.map(deserializeReceipt);
6898
+ throw this.extractDryRunError(request, parsedReceipts, status.reason);
6899
+ }
6900
+ request.witnesses = gqlTransaction.witnesses || request.witnesses;
6901
+ request.inputs = gqlTransaction.inputs?.map(deserializeInput) || request.inputs;
6902
+ request.outputs = gqlTransaction.outputs?.map(deserializeOutput) || request.outputs;
6903
+ if (gqlTransaction.policies?.maxFee) {
6904
+ request.maxFee = bn18(gqlTransaction.policies.maxFee);
6905
+ }
6906
+ if (gqlTransaction.scriptGasLimit) {
6907
+ request.gasLimit = bn18(gqlTransaction.scriptGasLimit);
6908
+ }
6909
+ const rawReceipts = status.receipts;
6910
+ const chainId = await this.getChainId();
6911
+ request.updateState(chainId, "funded", {
6912
+ gasPrice: gasPrice.toString(),
6913
+ receipts: rawReceipts
6914
+ });
6915
+ return {
6916
+ assembledRequest: request,
6917
+ gasPrice: bn18(gasPrice),
6918
+ receipts: status.receipts.map(deserializeReceipt),
6919
+ rawReceipts
6920
+ };
6921
+ }
5949
6922
  /**
5950
6923
  * Returns coins for the given owner.
5951
6924
  *
@@ -5964,15 +6937,15 @@ var Provider = class _Provider {
5964
6937
  paginationLimit: RESOURCES_PAGE_SIZE_LIMIT,
5965
6938
  inputArgs: paginationArgs
5966
6939
  }),
5967
- filter: { owner: ownerAddress.toB256(), assetId: assetId && hexlify18(assetId) }
6940
+ filter: { owner: ownerAddress.toB256(), assetId: assetId && hexlify19(assetId) }
5968
6941
  });
5969
6942
  const coins = edges.map(({ node }) => ({
5970
6943
  id: node.utxoId,
5971
6944
  assetId: node.assetId,
5972
- amount: bn17(node.amount),
6945
+ amount: bn18(node.amount),
5973
6946
  owner: ownerAddress,
5974
- blockCreated: bn17(node.blockCreated),
5975
- txCreatedIdx: bn17(node.txCreatedIdx)
6947
+ blockCreated: bn18(node.blockCreated),
6948
+ txCreatedIdx: bn18(node.txCreatedIdx)
5976
6949
  }));
5977
6950
  return {
5978
6951
  coins,
@@ -5984,47 +6957,32 @@ var Provider = class _Provider {
5984
6957
  *
5985
6958
  * @param owner - The address to get resources for.
5986
6959
  * @param quantities - The coin quantities to get.
5987
- * @param excludedIds - IDs of excluded resources from the selection (optional).
6960
+ * @param resourcesIdsToIgnore - IDs of excluded resources from the selection (optional).
5988
6961
  * @returns A promise that resolves to the resources.
5989
6962
  */
5990
- async getResourcesToSpend(owner, quantities, excludedIds) {
6963
+ async getResourcesToSpend(owner, quantities, resourcesIdsToIgnore) {
5991
6964
  const ownerAddress = new Address3(owner);
5992
- let idsToExclude = {
5993
- messages: excludedIds?.messages?.map((nonce) => hexlify18(nonce)) || [],
5994
- utxos: excludedIds?.utxos?.map((id) => hexlify18(id)) || []
5995
- };
5996
- if (this.cache) {
5997
- const cached = this.cache.getActiveData(ownerAddress.toB256());
5998
- if (cached.utxos.length || cached.messages.length) {
5999
- const {
6000
- consensusParameters: {
6001
- txParameters: { maxInputs }
6002
- }
6003
- } = await this.getChain();
6004
- idsToExclude = adjustResourcesToExclude({
6005
- userInput: idsToExclude,
6006
- cached,
6007
- maxInputs: maxInputs.toNumber()
6008
- });
6009
- }
6010
- }
6965
+ const excludedIds = await this.adjustResourcesToIgnoreForAddresses(
6966
+ [ownerAddress.b256Address],
6967
+ resourcesIdsToIgnore
6968
+ );
6011
6969
  const coinsQuery = {
6012
6970
  owner: ownerAddress.toB256(),
6013
6971
  queryPerAsset: quantities.map(coinQuantityfy).map(({ assetId, amount, max: maxPerAsset }) => ({
6014
- assetId: hexlify18(assetId),
6015
- amount: (amount.eqn(0) ? bn17(1) : amount).toString(10),
6972
+ assetId: hexlify19(assetId),
6973
+ amount: (amount.eqn(0) ? bn18(1) : amount).toString(10),
6016
6974
  max: maxPerAsset ? maxPerAsset.toString(10) : void 0
6017
6975
  })),
6018
- excludedIds: idsToExclude
6976
+ excludedIds
6019
6977
  };
6020
6978
  const result = await this.operations.getCoinsToSpend(coinsQuery);
6021
6979
  const coins = result.coinsToSpend.flat().map((coin) => {
6022
6980
  switch (coin.type) {
6023
6981
  case "MessageCoin":
6024
6982
  return {
6025
- amount: bn17(coin.amount),
6983
+ amount: bn18(coin.amount),
6026
6984
  assetId: coin.assetId,
6027
- daHeight: bn17(coin.daHeight),
6985
+ daHeight: bn18(coin.daHeight),
6028
6986
  sender: new Address3(coin.sender),
6029
6987
  recipient: new Address3(coin.recipient),
6030
6988
  nonce: coin.nonce
@@ -6032,11 +6990,11 @@ var Provider = class _Provider {
6032
6990
  case "Coin":
6033
6991
  return {
6034
6992
  id: coin.utxoId,
6035
- amount: bn17(coin.amount),
6993
+ amount: bn18(coin.amount),
6036
6994
  assetId: coin.assetId,
6037
6995
  owner: ownerAddress,
6038
- blockCreated: bn17(coin.blockCreated),
6039
- txCreatedIdx: bn17(coin.txCreatedIdx)
6996
+ blockCreated: bn18(coin.blockCreated),
6997
+ txCreatedIdx: bn18(coin.txCreatedIdx)
6040
6998
  };
6041
6999
  default:
6042
7000
  return null;
@@ -6074,7 +7032,7 @@ var Provider = class _Provider {
6074
7032
  block = latestBlock;
6075
7033
  } else {
6076
7034
  const isblockId = typeof idOrHeight === "string" && isB256(idOrHeight);
6077
- const variables = isblockId ? { blockId: idOrHeight } : { height: bn17(idOrHeight).toString(10) };
7035
+ const variables = isblockId ? { blockId: idOrHeight } : { height: bn18(idOrHeight).toString(10) };
6078
7036
  const response = await this.operations.getBlock(variables);
6079
7037
  block = response.block;
6080
7038
  }
@@ -6084,11 +7042,11 @@ var Provider = class _Provider {
6084
7042
  const { header, height, id, transactions } = block;
6085
7043
  return {
6086
7044
  id,
6087
- height: bn17(height),
7045
+ height: bn18(height),
6088
7046
  time: header.time,
6089
7047
  header: {
6090
7048
  applicationHash: header.applicationHash,
6091
- daHeight: bn17(header.daHeight),
7049
+ daHeight: bn18(header.daHeight),
6092
7050
  eventInboxRoot: header.eventInboxRoot,
6093
7051
  messageOutboxRoot: header.messageOutboxRoot,
6094
7052
  prevRoot: header.prevRoot,
@@ -6116,11 +7074,11 @@ var Provider = class _Provider {
6116
7074
  });
6117
7075
  const blocks = edges.map(({ node: block }) => ({
6118
7076
  id: block.id,
6119
- height: bn17(block.height),
7077
+ height: bn18(block.height),
6120
7078
  time: block.header.time,
6121
7079
  header: {
6122
7080
  applicationHash: block.header.applicationHash,
6123
- daHeight: bn17(block.header.daHeight),
7081
+ daHeight: bn18(block.header.daHeight),
6124
7082
  eventInboxRoot: block.header.eventInboxRoot,
6125
7083
  messageOutboxRoot: block.header.messageOutboxRoot,
6126
7084
  prevRoot: block.header.prevRoot,
@@ -6141,13 +7099,13 @@ var Provider = class _Provider {
6141
7099
  async getBlockWithTransactions(idOrHeight) {
6142
7100
  let variables;
6143
7101
  if (typeof idOrHeight === "number") {
6144
- variables = { blockHeight: bn17(idOrHeight).toString(10) };
7102
+ variables = { blockHeight: bn18(idOrHeight).toString(10) };
6145
7103
  } else if (idOrHeight === "latest") {
6146
7104
  variables = { blockHeight: (await this.getBlockNumber()).toString() };
6147
7105
  } else if (typeof idOrHeight === "string" && isB256(idOrHeight)) {
6148
7106
  variables = { blockId: idOrHeight };
6149
7107
  } else {
6150
- variables = { blockHeight: bn17(idOrHeight).toString() };
7108
+ variables = { blockHeight: bn18(idOrHeight).toString() };
6151
7109
  }
6152
7110
  const { block } = await this.operations.getBlockWithTransactions(variables);
6153
7111
  if (!block) {
@@ -6155,11 +7113,11 @@ var Provider = class _Provider {
6155
7113
  }
6156
7114
  return {
6157
7115
  id: block.id,
6158
- height: bn17(block.height, 10),
7116
+ height: bn18(block.height, 10),
6159
7117
  time: block.header.time,
6160
7118
  header: {
6161
7119
  applicationHash: block.header.applicationHash,
6162
- daHeight: bn17(block.header.daHeight),
7120
+ daHeight: bn18(block.header.daHeight),
6163
7121
  eventInboxRoot: block.header.eventInboxRoot,
6164
7122
  messageOutboxRoot: block.header.messageOutboxRoot,
6165
7123
  prevRoot: block.header.prevRoot,
@@ -6169,7 +7127,7 @@ var Provider = class _Provider {
6169
7127
  },
6170
7128
  transactionIds: block.transactions.map((tx) => tx.id),
6171
7129
  transactions: block.transactions.map(
6172
- (tx) => new TransactionCoder5().decode(arrayify13(tx.rawPayload), 0)?.[0]
7130
+ (tx) => new TransactionCoder6().decode(arrayify13(tx.rawPayload), 0)?.[0]
6173
7131
  )
6174
7132
  };
6175
7133
  }
@@ -6185,12 +7143,12 @@ var Provider = class _Provider {
6185
7143
  return null;
6186
7144
  }
6187
7145
  try {
6188
- return new TransactionCoder5().decode(
7146
+ return new TransactionCoder6().decode(
6189
7147
  arrayify13(transaction.rawPayload),
6190
7148
  0
6191
7149
  )?.[0];
6192
7150
  } catch (error) {
6193
- if (error instanceof FuelError20 && error.code === ErrorCode16.UNSUPPORTED_TRANSACTION_TYPE) {
7151
+ if (error instanceof FuelError20 && error.code === ErrorCode17.UNSUPPORTED_TRANSACTION_TYPE) {
6194
7152
  console.warn("Unsupported transaction type encountered");
6195
7153
  return null;
6196
7154
  }
@@ -6211,12 +7169,12 @@ var Provider = class _Provider {
6211
7169
  paginationLimit: TRANSACTIONS_PAGE_SIZE_LIMIT
6212
7170
  })
6213
7171
  });
6214
- const coder = new TransactionCoder5();
7172
+ const coder = new TransactionCoder6();
6215
7173
  const transactions = edges.map(({ node: { rawPayload } }) => {
6216
7174
  try {
6217
7175
  return coder.decode(arrayify13(rawPayload), 0)[0];
6218
7176
  } catch (error) {
6219
- if (error instanceof FuelError20 && error.code === ErrorCode16.UNSUPPORTED_TRANSACTION_TYPE) {
7177
+ if (error instanceof FuelError20 && error.code === ErrorCode17.UNSUPPORTED_TRANSACTION_TYPE) {
6220
7178
  console.warn("Unsupported transaction type encountered");
6221
7179
  return null;
6222
7180
  }
@@ -6263,9 +7221,9 @@ var Provider = class _Provider {
6263
7221
  async getContractBalance(contractId, assetId) {
6264
7222
  const { contractBalance } = await this.operations.getContractBalance({
6265
7223
  contract: new Address3(contractId).toB256(),
6266
- asset: hexlify18(assetId)
7224
+ asset: hexlify19(assetId)
6267
7225
  });
6268
- return bn17(contractBalance.amount, 10);
7226
+ return bn18(contractBalance.amount, 10);
6269
7227
  }
6270
7228
  /**
6271
7229
  * Returns the balance for the given owner for the given asset ID.
@@ -6277,9 +7235,9 @@ var Provider = class _Provider {
6277
7235
  async getBalance(owner, assetId) {
6278
7236
  const { balance } = await this.operations.getBalanceV2({
6279
7237
  owner: new Address3(owner).toB256(),
6280
- assetId: hexlify18(assetId)
7238
+ assetId: hexlify19(assetId)
6281
7239
  });
6282
- return bn17(balance.amountU128, 10);
7240
+ return bn18(balance.amountU128, 10);
6283
7241
  }
6284
7242
  /**
6285
7243
  * Returns balances for the given owner.
@@ -6306,7 +7264,7 @@ var Provider = class _Provider {
6306
7264
  });
6307
7265
  const balances = edges.map(({ node }) => ({
6308
7266
  assetId: node.assetId,
6309
- amount: bn17(node.amountU128)
7267
+ amount: bn18(node.amountU128)
6310
7268
  }));
6311
7269
  return {
6312
7270
  balances,
@@ -6335,15 +7293,15 @@ var Provider = class _Provider {
6335
7293
  sender: node.sender,
6336
7294
  recipient: node.recipient,
6337
7295
  nonce: node.nonce,
6338
- amount: bn17(node.amount),
7296
+ amount: bn18(node.amount),
6339
7297
  data: node.data
6340
7298
  }),
6341
7299
  sender: new Address3(node.sender),
6342
7300
  recipient: new Address3(node.recipient),
6343
7301
  nonce: node.nonce,
6344
- amount: bn17(node.amount),
7302
+ amount: bn18(node.amount),
6345
7303
  data: InputMessageCoder2.decodeData(node.data),
6346
- daHeight: bn17(node.daHeight)
7304
+ daHeight: bn18(node.daHeight)
6347
7305
  }));
6348
7306
  return {
6349
7307
  messages,
@@ -6366,7 +7324,7 @@ var Provider = class _Provider {
6366
7324
  };
6367
7325
  if (commitBlockId && commitBlockHeight) {
6368
7326
  throw new FuelError20(
6369
- ErrorCode16.INVALID_INPUT_PARAMETERS,
7327
+ ErrorCode17.INVALID_INPUT_PARAMETERS,
6370
7328
  "commitBlockId and commitBlockHeight cannot be used together"
6371
7329
  );
6372
7330
  }
@@ -6397,19 +7355,19 @@ var Provider = class _Provider {
6397
7355
  } = result.messageProof;
6398
7356
  return {
6399
7357
  messageProof: {
6400
- proofIndex: bn17(messageProof.proofIndex),
7358
+ proofIndex: bn18(messageProof.proofIndex),
6401
7359
  proofSet: messageProof.proofSet
6402
7360
  },
6403
7361
  blockProof: {
6404
- proofIndex: bn17(blockProof.proofIndex),
7362
+ proofIndex: bn18(blockProof.proofIndex),
6405
7363
  proofSet: blockProof.proofSet
6406
7364
  },
6407
7365
  messageBlockHeader: {
6408
7366
  id: messageBlockHeader.id,
6409
- daHeight: bn17(messageBlockHeader.daHeight),
7367
+ daHeight: bn18(messageBlockHeader.daHeight),
6410
7368
  transactionsCount: Number(messageBlockHeader.transactionsCount),
6411
7369
  transactionsRoot: messageBlockHeader.transactionsRoot,
6412
- height: bn17(messageBlockHeader.height),
7370
+ height: bn18(messageBlockHeader.height),
6413
7371
  prevRoot: messageBlockHeader.prevRoot,
6414
7372
  time: messageBlockHeader.time,
6415
7373
  applicationHash: messageBlockHeader.applicationHash,
@@ -6421,10 +7379,10 @@ var Provider = class _Provider {
6421
7379
  },
6422
7380
  commitBlockHeader: {
6423
7381
  id: commitBlockHeader.id,
6424
- daHeight: bn17(commitBlockHeader.daHeight),
7382
+ daHeight: bn18(commitBlockHeader.daHeight),
6425
7383
  transactionsCount: Number(commitBlockHeader.transactionsCount),
6426
7384
  transactionsRoot: commitBlockHeader.transactionsRoot,
6427
- height: bn17(commitBlockHeader.height),
7385
+ height: bn18(commitBlockHeader.height),
6428
7386
  prevRoot: commitBlockHeader.prevRoot,
6429
7387
  time: commitBlockHeader.time,
6430
7388
  applicationHash: commitBlockHeader.applicationHash,
@@ -6437,7 +7395,7 @@ var Provider = class _Provider {
6437
7395
  sender: new Address3(sender),
6438
7396
  recipient: new Address3(recipient),
6439
7397
  nonce,
6440
- amount: bn17(amount),
7398
+ amount: bn18(amount),
6441
7399
  data
6442
7400
  };
6443
7401
  }
@@ -6448,7 +7406,7 @@ var Provider = class _Provider {
6448
7406
  */
6449
7407
  async getLatestGasPrice() {
6450
7408
  const { latestGasPrice } = await this.operations.getLatestGasPrice();
6451
- return bn17(latestGasPrice.gasPrice);
7409
+ return bn18(latestGasPrice.gasPrice);
6452
7410
  }
6453
7411
  /**
6454
7412
  * Returns the estimate gas price for the given block horizon.
@@ -6460,7 +7418,7 @@ var Provider = class _Provider {
6460
7418
  const { estimateGasPrice } = await this.operations.estimateGasPrice({
6461
7419
  blockHorizon: String(blockHorizon)
6462
7420
  });
6463
- return bn17(estimateGasPrice.gasPrice);
7421
+ return bn18(estimateGasPrice.gasPrice);
6464
7422
  }
6465
7423
  /**
6466
7424
  * Returns Message Proof for given transaction id and the message id from MessageOut receipt.
@@ -6481,10 +7439,10 @@ var Provider = class _Provider {
6481
7439
  */
6482
7440
  async produceBlocks(amount, startTime) {
6483
7441
  const { produceBlocks: latestBlockHeight } = await this.operations.produceBlocks({
6484
- blocksToProduce: bn17(amount).toString(10),
7442
+ blocksToProduce: bn18(amount).toString(10),
6485
7443
  startTimestamp: startTime ? DateTime2.fromUnixMilliseconds(startTime).toTai64() : void 0
6486
7444
  });
6487
- return bn17(latestBlockHeight);
7445
+ return bn18(latestBlockHeight);
6488
7446
  }
6489
7447
  /**
6490
7448
  * Check if the given ID is an account.
@@ -6552,15 +7510,15 @@ var Provider = class _Provider {
6552
7510
  sender: rawMessage.sender,
6553
7511
  recipient: rawMessage.recipient,
6554
7512
  nonce,
6555
- amount: bn17(rawMessage.amount),
7513
+ amount: bn18(rawMessage.amount),
6556
7514
  data: rawMessage.data
6557
7515
  }),
6558
7516
  sender: new Address3(rawMessage.sender),
6559
7517
  recipient: new Address3(rawMessage.recipient),
6560
7518
  nonce,
6561
- amount: bn17(rawMessage.amount),
7519
+ amount: bn18(rawMessage.amount),
6562
7520
  data: InputMessageCoder2.decodeData(rawMessage.data),
6563
- daHeight: bn17(rawMessage.daHeight)
7521
+ daHeight: bn18(rawMessage.daHeight)
6564
7522
  };
6565
7523
  return message;
6566
7524
  }
@@ -6582,20 +7540,21 @@ var Provider = class _Provider {
6582
7540
  /**
6583
7541
  * @hidden
6584
7542
  */
6585
- extractDryRunError(transactionRequest, receipts, dryRunStatus) {
6586
- const status = dryRunStatus;
7543
+ extractDryRunError(transactionRequest, receipts, reason) {
6587
7544
  let logs = [];
6588
- if (transactionRequest.abis) {
6589
- logs = getDecodedLogs(
7545
+ let groupedLogs = {};
7546
+ if (transactionRequest.type === TransactionType11.Script && transactionRequest.abis) {
7547
+ ({ logs, groupedLogs } = getAllDecodedLogs({
6590
7548
  receipts,
6591
- transactionRequest.abis.main,
6592
- transactionRequest.abis.otherContractsAbis
6593
- );
7549
+ mainAbi: transactionRequest.abis.main,
7550
+ externalAbis: transactionRequest.abis.otherContractsAbis
7551
+ }));
6594
7552
  }
6595
7553
  return extractTxError({
6596
7554
  logs,
7555
+ groupedLogs,
6597
7556
  receipts,
6598
- statusReason: status.reason
7557
+ statusReason: reason
6599
7558
  });
6600
7559
  }
6601
7560
  /**
@@ -6615,29 +7574,68 @@ var Provider = class _Provider {
6615
7574
  parseEstimatePredicatesResponse(transactionRequest, { inputs }) {
6616
7575
  if (inputs) {
6617
7576
  inputs.forEach((input, i) => {
6618
- if (input && "predicateGasUsed" in input && bn17(input.predicateGasUsed).gt(0)) {
7577
+ if (input && "predicateGasUsed" in input && bn18(input.predicateGasUsed).gt(0)) {
6619
7578
  transactionRequest.inputs[i].predicateGasUsed = input.predicateGasUsed;
6620
7579
  }
6621
7580
  });
6622
7581
  }
6623
7582
  return transactionRequest;
6624
7583
  }
7584
+ /**
7585
+ * @hidden
7586
+ *
7587
+ * This helper adjusts the resources to be excluded for a given set of addresses.
7588
+ * Supporting multiple addresses is important because of the `assembleTx` method,
7589
+ * which may be invoked with different addresses. It handles both messages and UTXOs,
7590
+ * ensuring the total number of inputs does not exceed the maximum allowed by the chain's
7591
+ * consensus parameters. The resources specified in the `resourcesIdsToIgnore` parameter have priority
7592
+ * over those retrieved from the cache.
7593
+ */
7594
+ async adjustResourcesToIgnoreForAddresses(addresses, resourcesIdsToIgnore) {
7595
+ const final = {
7596
+ messages: resourcesIdsToIgnore?.messages?.map((nonce) => hexlify19(nonce)) || [],
7597
+ utxos: resourcesIdsToIgnore?.utxos?.map((id) => hexlify19(id)) || []
7598
+ };
7599
+ if (this.cache) {
7600
+ const cache2 = this.cache;
7601
+ const allCached = addresses.map((address) => cache2.getActiveData(address));
7602
+ const {
7603
+ consensusParameters: {
7604
+ txParameters: { maxInputs: maxInputsBn }
7605
+ }
7606
+ } = await this.getChain();
7607
+ const maxInputs = maxInputsBn.toNumber();
7608
+ for (let i = 0; i < allCached.length; i++) {
7609
+ let total = final.utxos.length + final.messages.length;
7610
+ if (total >= maxInputs) {
7611
+ break;
7612
+ }
7613
+ final.utxos = [...final.utxos, ...allCached[i].utxos.slice(0, maxInputs - total)];
7614
+ total = final.utxos.length + final.messages.length;
7615
+ if (total >= maxInputs) {
7616
+ break;
7617
+ }
7618
+ final.messages = [...final.messages, ...allCached[i].messages.slice(0, maxInputs - total)];
7619
+ }
7620
+ }
7621
+ return final;
7622
+ }
6625
7623
  };
6626
7624
 
6627
7625
  // src/providers/transaction-summary/get-transaction-summary.ts
6628
- import { ErrorCode as ErrorCode17, FuelError as FuelError21 } from "@fuel-ts/errors";
6629
- import { bn as bn18 } from "@fuel-ts/math";
6630
- import { TransactionCoder as TransactionCoder6 } from "@fuel-ts/transactions";
7626
+ import { ErrorCode as ErrorCode18, FuelError as FuelError21 } from "@fuel-ts/errors";
7627
+ import { bn as bn19 } from "@fuel-ts/math";
7628
+ import { TransactionCoder as TransactionCoder7 } from "@fuel-ts/transactions";
6631
7629
  import { arrayify as arrayify14 } from "@fuel-ts/utils";
6632
7630
 
6633
7631
  // src/providers/transaction-summary/assemble-transaction-summary-from-serialized.ts
6634
- import { bn as bn19 } from "@fuel-ts/math";
6635
- import { TransactionCoder as TransactionCoder7 } from "@fuel-ts/transactions";
7632
+ import { bn as bn20 } from "@fuel-ts/math";
7633
+ import { TransactionCoder as TransactionCoder8 } from "@fuel-ts/transactions";
6636
7634
  import { arrayify as arrayify15 } from "@fuel-ts/utils";
6637
7635
 
6638
7636
  // src/test-utils/test-asset-id.ts
6639
7637
  import { randomBytes as randomBytes4 } from "@fuel-ts/crypto";
6640
- import { hexlify as hexlify19 } from "@fuel-ts/utils";
7638
+ import { hexlify as hexlify20 } from "@fuel-ts/utils";
6641
7639
  var TestAssetId = class _TestAssetId {
6642
7640
  constructor(value) {
6643
7641
  this.value = value;
@@ -6654,7 +7652,7 @@ var TestAssetId = class _TestAssetId {
6654
7652
  static random(count = 1) {
6655
7653
  const assetIds = [];
6656
7654
  for (let i = 0; i < count; i++) {
6657
- assetIds.push(new _TestAssetId(hexlify19(randomBytes4(32))));
7655
+ assetIds.push(new _TestAssetId(hexlify20(randomBytes4(32))));
6658
7656
  }
6659
7657
  return assetIds;
6660
7658
  }
@@ -6663,38 +7661,23 @@ var TestAssetId = class _TestAssetId {
6663
7661
  // src/test-utils/wallet-config.ts
6664
7662
  import { randomBytes as randomBytes8 } from "@fuel-ts/crypto";
6665
7663
  import { FuelError as FuelError27 } from "@fuel-ts/errors";
6666
- import { bn as bn22 } from "@fuel-ts/math";
6667
- import { defaultSnapshotConfigs as defaultSnapshotConfigs2, hexlify as hexlify25 } from "@fuel-ts/utils";
7664
+ import { bn as bn23 } from "@fuel-ts/math";
7665
+ import { defaultSnapshotConfigs as defaultSnapshotConfigs2, hexlify as hexlify26 } from "@fuel-ts/utils";
6668
7666
 
6669
7667
  // src/wallet/base-wallet-unlocked.ts
6670
7668
  import { hashMessage } from "@fuel-ts/hasher";
6671
- import { hexlify as hexlify22 } from "@fuel-ts/utils";
7669
+ import { hexlify as hexlify23 } from "@fuel-ts/utils";
6672
7670
 
6673
7671
  // src/account.ts
6674
7672
  import { UTXO_ID_LEN as UTXO_ID_LEN3 } from "@fuel-ts/abi-coder";
6675
7673
  import { Address as Address5 } from "@fuel-ts/address";
6676
7674
  import { randomBytes as randomBytes5 } from "@fuel-ts/crypto";
6677
- import { ErrorCode as ErrorCode18, FuelError as FuelError22 } from "@fuel-ts/errors";
6678
- import { bn as bn20 } from "@fuel-ts/math";
6679
- import { InputType as InputType7 } from "@fuel-ts/transactions";
6680
- import { arrayify as arrayify17, hexlify as hexlify20, isDefined as isDefined3 } from "@fuel-ts/utils";
7675
+ import { ErrorCode as ErrorCode19, FuelError as FuelError22 } from "@fuel-ts/errors";
7676
+ import { bn as bn21 } from "@fuel-ts/math";
7677
+ import { InputType as InputType8, OutputType as OutputType9 } from "@fuel-ts/transactions";
7678
+ import { arrayify as arrayify17, hexlify as hexlify21, isDefined as isDefined4 } from "@fuel-ts/utils";
6681
7679
  import { clone as clone9 } from "ramda";
6682
7680
 
6683
- // src/providers/utils/merge-quantities.ts
6684
- var mergeQuantities = /* @__PURE__ */ __name((...coinQuantities) => {
6685
- const resultMap = {};
6686
- function addToMap({ amount, assetId }) {
6687
- if (resultMap[assetId]) {
6688
- resultMap[assetId] = resultMap[assetId].add(amount);
6689
- } else {
6690
- resultMap[assetId] = amount;
6691
- }
6692
- }
6693
- __name(addToMap, "addToMap");
6694
- coinQuantities.forEach((arr) => arr.forEach(addToMap));
6695
- return Object.entries(resultMap).map(([assetId, amount]) => ({ assetId, amount }));
6696
- }, "mergeQuantities");
6697
-
6698
7681
  // src/types.ts
6699
7682
  var AbstractAccount = class {
6700
7683
  static {
@@ -6703,12 +7686,12 @@ var AbstractAccount = class {
6703
7686
  };
6704
7687
 
6705
7688
  // src/utils/formatTransferToContractScriptData.ts
6706
- import { ASSET_ID_LEN, BigNumberCoder as BigNumberCoder2, CONTRACT_ID_LEN, WORD_SIZE } from "@fuel-ts/abi-coder";
7689
+ import { ASSET_ID_LEN, BigNumberCoder as BigNumberCoder3, CONTRACT_ID_LEN, WORD_SIZE } from "@fuel-ts/abi-coder";
6707
7690
  import { Address as Address4 } from "@fuel-ts/address";
6708
7691
  import { arrayify as arrayify16, concat as concat4 } from "@fuel-ts/utils";
6709
7692
  import * as asm from "@fuels/vm-asm";
6710
7693
  var formatTransferToContractScriptData = /* @__PURE__ */ __name((transferParams) => {
6711
- const numberCoder = new BigNumberCoder2("u64");
7694
+ const numberCoder = new BigNumberCoder3("u64");
6712
7695
  return transferParams.reduce((acc, transferParam) => {
6713
7696
  const { assetId, amount, contractId } = transferParam;
6714
7697
  const encoded = numberCoder.encode(amount);
@@ -6742,6 +7725,18 @@ var assembleTransferToContractScript = /* @__PURE__ */ __name(async (transferPar
6742
7725
  return { script, scriptData };
6743
7726
  }, "assembleTransferToContractScript");
6744
7727
 
7728
+ // src/utils/split-coins-into-batches.ts
7729
+ var splitCoinsIntoBatches = /* @__PURE__ */ __name((coins, maxBatchLength) => {
7730
+ const batchesNum = Math.ceil(coins.length / maxBatchLength);
7731
+ const batches = [];
7732
+ for (let i = 0; i < batchesNum; i += 1) {
7733
+ const batchStart = i * maxBatchLength;
7734
+ const batchEnd = (i + 1) * maxBatchLength;
7735
+ batches.push(coins.slice(batchStart, batchEnd));
7736
+ }
7737
+ return batches;
7738
+ }, "splitCoinsIntoBatches");
7739
+
6745
7740
  // src/account.ts
6746
7741
  var MAX_FUNDING_ATTEMPTS = 5;
6747
7742
  var Account = class extends AbstractAccount {
@@ -6782,7 +7777,7 @@ var Account = class extends AbstractAccount {
6782
7777
  */
6783
7778
  get provider() {
6784
7779
  if (!this._provider) {
6785
- throw new FuelError22(ErrorCode18.MISSING_PROVIDER, "Provider not set");
7780
+ throw new FuelError22(ErrorCode19.MISSING_PROVIDER, "Provider not set");
6786
7781
  }
6787
7782
  return this._provider;
6788
7783
  }
@@ -6808,11 +7803,11 @@ var Account = class extends AbstractAccount {
6808
7803
  * Retrieves resources satisfying the spend query for the account.
6809
7804
  *
6810
7805
  * @param quantities - Quantities of resources to be obtained.
6811
- * @param excludedIds - IDs of resources to be excluded from the query (optional).
7806
+ * @param resourcesIdsToIgnore - IDs of resources to be excluded from the query (optional).
6812
7807
  * @returns A promise that resolves to an array of Resources.
6813
7808
  */
6814
- async getResourcesToSpend(quantities, excludedIds) {
6815
- return this.provider.getResourcesToSpend(this.address, quantities, excludedIds);
7809
+ async getResourcesToSpend(quantities, resourcesIdsToIgnore) {
7810
+ return this.provider.getResourcesToSpend(this.address, quantities, resourcesIdsToIgnore);
6816
7811
  }
6817
7812
  /**
6818
7813
  * Retrieves coins owned by the account.
@@ -6857,6 +7852,9 @@ var Account = class extends AbstractAccount {
6857
7852
  * @param request - The transaction request to fund.
6858
7853
  * @param params - The estimated transaction parameters.
6859
7854
  * @returns A promise that resolves to the funded transaction request.
7855
+ *
7856
+ * @deprecated Use provider.assembleTx instead
7857
+ * Check the migration guide https://docs.fuel.network/guide/assembling-transactions/migration-guide.html for more information.
6860
7858
  */
6861
7859
  async fund(request, params) {
6862
7860
  const {
@@ -6870,9 +7868,9 @@ var Account = class extends AbstractAccount {
6870
7868
  const chainId = await this.provider.getChainId();
6871
7869
  const fee = request.maxFee;
6872
7870
  const baseAssetId = await this.provider.getBaseAssetId();
6873
- const requiredInBaseAsset = requiredQuantities.find((quantity) => quantity.assetId === baseAssetId)?.amount || bn20(0);
7871
+ const requiredInBaseAsset = requiredQuantities.find((quantity) => quantity.assetId === baseAssetId)?.amount || bn21(0);
6874
7872
  const requiredQuantitiesWithFee = addAmountToCoinQuantities({
6875
- amount: bn20(fee),
7873
+ amount: bn21(fee),
6876
7874
  assetId: baseAssetId,
6877
7875
  coinQuantities: requiredQuantities
6878
7876
  });
@@ -6880,7 +7878,7 @@ var Account = class extends AbstractAccount {
6880
7878
  requiredQuantitiesWithFee.forEach(({ amount, assetId }) => {
6881
7879
  quantitiesDict[assetId] = {
6882
7880
  required: amount,
6883
- owned: bn20(0)
7881
+ owned: bn21(0)
6884
7882
  };
6885
7883
  });
6886
7884
  request.inputs.filter(isRequestInputResource).forEach((input) => {
@@ -6942,7 +7940,7 @@ var Account = class extends AbstractAccount {
6942
7940
  }
6943
7941
  if (needsToBeFunded) {
6944
7942
  throw new FuelError22(
6945
- ErrorCode18.INSUFFICIENT_FUNDS_OR_MAX_COINS,
7943
+ ErrorCode19.INSUFFICIENT_FUNDS_OR_MAX_COINS,
6946
7944
  `The account ${this.address} does not have enough base asset funds to cover the transaction execution.`
6947
7945
  );
6948
7946
  }
@@ -6979,7 +7977,14 @@ var Account = class extends AbstractAccount {
6979
7977
  amount,
6980
7978
  assetId: assetId || await this.provider.getBaseAssetId()
6981
7979
  });
6982
- request = await this.estimateAndFundTransaction(request, txParams);
7980
+ const { gasPrice, transactionRequest } = await this.assembleTx(request);
7981
+ request = await setAndValidateGasAndFeeForAssembledTx({
7982
+ gasPrice,
7983
+ provider: this.provider,
7984
+ transactionRequest,
7985
+ setGasLimit: txParams?.gasLimit,
7986
+ setMaxFee: txParams?.maxFee
7987
+ });
6983
7988
  return request;
6984
7989
  }
6985
7990
  /**
@@ -7005,7 +8010,14 @@ var Account = class extends AbstractAccount {
7005
8010
  async batchTransfer(transferParams, txParams = {}) {
7006
8011
  let request = new ScriptTransactionRequest(txParams);
7007
8012
  request = this.addBatchTransfer(request, transferParams);
7008
- request = await this.estimateAndFundTransaction(request, txParams);
8013
+ const { gasPrice, transactionRequest } = await this.assembleTx(request);
8014
+ request = await setAndValidateGasAndFeeForAssembledTx({
8015
+ gasPrice,
8016
+ provider: this.provider,
8017
+ transactionRequest,
8018
+ setGasLimit: txParams?.gasLimit,
8019
+ setMaxFee: txParams?.maxFee
8020
+ });
7009
8021
  return this.sendTransaction(request, { estimateTxDependencies: false });
7010
8022
  }
7011
8023
  /**
@@ -7057,12 +8069,12 @@ var Account = class extends AbstractAccount {
7057
8069
  const quantities = [];
7058
8070
  const defaultAssetId = await this.provider.getBaseAssetId();
7059
8071
  const transferParams = contractTransferParams.map((transferParam) => {
7060
- const amount = bn20(transferParam.amount);
8072
+ const amount = bn21(transferParam.amount);
7061
8073
  const contractAddress = new Address5(transferParam.contractId);
7062
- const assetId = transferParam.assetId ? hexlify20(transferParam.assetId) : defaultAssetId;
8074
+ const assetId = transferParam.assetId ? hexlify21(transferParam.assetId) : defaultAssetId;
7063
8075
  if (amount.lte(0)) {
7064
8076
  throw new FuelError22(
7065
- ErrorCode18.INVALID_TRANSFER_AMOUNT,
8077
+ ErrorCode19.INVALID_TRANSFER_AMOUNT,
7066
8078
  "Transfer amount must be a positive number."
7067
8079
  );
7068
8080
  }
@@ -7077,7 +8089,14 @@ var Account = class extends AbstractAccount {
7077
8089
  const { script, scriptData } = await assembleTransferToContractScript(transferParams);
7078
8090
  request.script = script;
7079
8091
  request.scriptData = scriptData;
7080
- request = await this.estimateAndFundTransaction(request, txParams, { quantities });
8092
+ const { gasPrice, transactionRequest } = await this.assembleTx(request, quantities);
8093
+ request = await setAndValidateGasAndFeeForAssembledTx({
8094
+ gasPrice,
8095
+ provider: this.provider,
8096
+ transactionRequest,
8097
+ setGasLimit: txParams?.gasLimit,
8098
+ setMaxFee: txParams?.maxFee
8099
+ });
7081
8100
  return this.sendTransaction(request);
7082
8101
  }
7083
8102
  /**
@@ -7094,7 +8113,7 @@ var Account = class extends AbstractAccount {
7094
8113
  "0x".concat(recipientAddress.toHexString().substring(2).padStart(64, "0"))
7095
8114
  );
7096
8115
  const amountDataArray = arrayify17(
7097
- "0x".concat(bn20(amount).toHex().substring(2).padStart(16, "0"))
8116
+ "0x".concat(bn21(amount).toHex().substring(2).padStart(16, "0"))
7098
8117
  );
7099
8118
  const script = new Uint8Array([
7100
8119
  ...arrayify17(withdrawScript.bytes),
@@ -7104,17 +8123,145 @@ var Account = class extends AbstractAccount {
7104
8123
  const params = { script, ...txParams };
7105
8124
  const baseAssetId = await this.provider.getBaseAssetId();
7106
8125
  let request = new ScriptTransactionRequest(params);
7107
- const quantities = [{ amount: bn20(amount), assetId: baseAssetId }];
7108
- const txCost = await this.getTransactionCost(request, { quantities });
7109
- request = this.validateGasLimitAndMaxFee({
7110
- transactionRequest: request,
7111
- gasUsed: txCost.gasUsed,
7112
- maxFee: txCost.maxFee,
7113
- txParams
8126
+ const quantities = [{ amount: bn21(amount), assetId: baseAssetId }];
8127
+ const { gasPrice, transactionRequest } = await this.assembleTx(request, quantities);
8128
+ request = await setAndValidateGasAndFeeForAssembledTx({
8129
+ gasPrice,
8130
+ provider: this.provider,
8131
+ transactionRequest,
8132
+ setGasLimit: txParams?.gasLimit,
8133
+ setMaxFee: txParams?.maxFee
7114
8134
  });
7115
- await this.fund(request, txCost);
7116
8135
  return this.sendTransaction(request);
7117
8136
  }
8137
+ /**
8138
+ * Consolidates base asset UTXOs into fewer, larger ones.
8139
+ *
8140
+ * Retrieves a limited number of base asset coins (as defined by `Provider.RESOURCES_PAGE_SIZE_LIMIT`),
8141
+ * assembles consolidation transactions, and submits them to the network.
8142
+ *
8143
+ * Note: This method currently supports only the base asset.
8144
+ *
8145
+ * @param params - The parameters for coin consolidation, including the asset ID, mode, and output number.
8146
+ * @returns A promise that resolves to the response of the submitted transactions.
8147
+ * @throws Will throw an error if the asset is not a base asset as non-base asset consolidation is not implemented.
8148
+ */
8149
+ async consolidateCoins(params) {
8150
+ const { assetId } = params;
8151
+ const { coins } = await this.getCoins(assetId);
8152
+ const baseAssetId = await this.provider.getBaseAssetId();
8153
+ const isBaseAsset = baseAssetId === assetId;
8154
+ let submitAll;
8155
+ const consolidationParams = {
8156
+ coins,
8157
+ mode: params.mode,
8158
+ outputNum: params.outputNum
8159
+ };
8160
+ if (isBaseAsset) {
8161
+ ({ submitAll } = await this.assembleBaseAssetConsolidationTxs(consolidationParams));
8162
+ } else {
8163
+ throw new FuelError22(
8164
+ ErrorCode19.UNSUPPORTED_FEATURE,
8165
+ "Consolidation for non-base assets is not supported yet."
8166
+ );
8167
+ }
8168
+ return submitAll();
8169
+ }
8170
+ /**
8171
+ * Assembles transactions for consolidating base asset coins into fewer UTXOs.
8172
+ *
8173
+ * This method splits the provided coins into batches and creates transaction requests
8174
+ * to consolidate them. It calculates the necessary fee and sets up the transactions
8175
+ * to be submitted either in parallel (default) or sequentially.
8176
+ *
8177
+ * @param params - The parameters for assembling base asset consolidation transactions.
8178
+ *
8179
+ * @returns An object containing the assembled transactions, the total fee cost, and a callback to submit all transactions.
8180
+ */
8181
+ async assembleBaseAssetConsolidationTxs(params) {
8182
+ const { coins, mode = "parallel", outputNum = 1 } = params;
8183
+ const baseAssetId = await this.provider.getBaseAssetId();
8184
+ this.validateConsolidationTxsCoins(coins, baseAssetId);
8185
+ const chainInfo = await this.provider.getChain();
8186
+ const maxInputsNumber = chainInfo.consensusParameters.txParameters.maxInputs.toNumber();
8187
+ let totalFeeCost = bn21(0);
8188
+ const txs = [];
8189
+ const coinsBatches = splitCoinsIntoBatches(coins, maxInputsNumber);
8190
+ const gasPrice = await this.provider.estimateGasPrice(10);
8191
+ const consolidateMoreThanOneCoin = outputNum > 1;
8192
+ coinsBatches.filter((batch) => batch.length > 1).forEach((coinBatch) => {
8193
+ const request = new ScriptTransactionRequest({
8194
+ script: "0x"
8195
+ });
8196
+ request.addResources(coinBatch);
8197
+ if (consolidateMoreThanOneCoin) {
8198
+ Array.from({ length: outputNum - 1 }).forEach(() => {
8199
+ request.addCoinOutput(this.address, 0, baseAssetId);
8200
+ });
8201
+ }
8202
+ const minGas = request.calculateMinGas(chainInfo);
8203
+ const fee = calculateGasFee({
8204
+ gasPrice,
8205
+ gas: minGas,
8206
+ priceFactor: chainInfo.consensusParameters.feeParameters.gasPriceFactor,
8207
+ tip: request.tip
8208
+ });
8209
+ request.maxFee = fee;
8210
+ if (consolidateMoreThanOneCoin) {
8211
+ const total = request.inputs.filter(isRequestInputCoin).reduce((acc, input) => acc.add(input.amount), bn21(0));
8212
+ const amountPerNewUtxo = total.div(outputNum + 1);
8213
+ request.outputs.forEach((output) => {
8214
+ if (output.type === OutputType9.Coin) {
8215
+ output.amount = amountPerNewUtxo;
8216
+ }
8217
+ });
8218
+ }
8219
+ totalFeeCost = totalFeeCost.add(fee);
8220
+ txs.push(request);
8221
+ });
8222
+ const submitAll = this.prepareSubmitAll({ txs, mode });
8223
+ return { txs, totalFeeCost, submitAll };
8224
+ }
8225
+ /**
8226
+ * Prepares a function to submit all transactions either sequentially or in parallel.
8227
+ *
8228
+ * @param params - The parameters for preparing the submitAll callback.
8229
+ *
8230
+ * @returns A callback that, when called, submits all transactions and returns their results and any errors encountered.
8231
+ */
8232
+ prepareSubmitAll = /* @__PURE__ */ __name((params) => {
8233
+ const { txs, mode = "sequential" } = params;
8234
+ return async () => {
8235
+ const txResponses = [];
8236
+ const errors = [];
8237
+ if (mode === "sequential") {
8238
+ for (const tx of txs) {
8239
+ try {
8240
+ const submit = await this.sendTransaction(tx);
8241
+ const response = await submit.waitForResult();
8242
+ txResponses.push(response);
8243
+ } catch (error) {
8244
+ errors.push(error);
8245
+ }
8246
+ }
8247
+ } else {
8248
+ const results = await Promise.allSettled(
8249
+ txs.map(async (tx) => {
8250
+ const submit = await this.sendTransaction(tx);
8251
+ return submit.waitForResult();
8252
+ })
8253
+ );
8254
+ results.forEach((result) => {
8255
+ if (result.status === "fulfilled") {
8256
+ txResponses.push(result.value);
8257
+ } else {
8258
+ errors.push(result.reason);
8259
+ }
8260
+ });
8261
+ }
8262
+ return { txResponses, errors };
8263
+ };
8264
+ }, "prepareSubmitAll");
7118
8265
  /**
7119
8266
  * Returns a transaction cost to enable user
7120
8267
  * to set gasLimit and also reserve balance amounts
@@ -7124,15 +8271,18 @@ var Account = class extends AbstractAccount {
7124
8271
  * @param transactionCostParams - The transaction cost parameters (optional).
7125
8272
  *
7126
8273
  * @returns A promise that resolves to the transaction cost object.
8274
+ *
8275
+ * @deprecated Use provider.assembleTx instead
8276
+ * Check the migration guide https://docs.fuel.network/guide/assembling-transactions/migration-guide.html for more information.
7127
8277
  */
7128
8278
  async getTransactionCost(transactionRequestLike, { signatureCallback, quantities = [], gasPrice } = {}) {
7129
8279
  const txRequestClone = clone9(transactionRequestify(transactionRequestLike));
7130
8280
  const baseAssetId = await this.provider.getBaseAssetId();
7131
8281
  const coinOutputsQuantities = txRequestClone.getCoinOutputsQuantities();
7132
8282
  const requiredQuantities = mergeQuantities(coinOutputsQuantities, quantities);
7133
- const transactionFeeForDryRun = [{ assetId: baseAssetId, amount: bn20("100000000000000000") }];
8283
+ const transactionFeeForDryRun = [{ assetId: baseAssetId, amount: bn21("100000000000000000") }];
7134
8284
  const findAssetInput = /* @__PURE__ */ __name((assetId) => txRequestClone.inputs.find((input) => {
7135
- if (input.type === InputType7.Coin) {
8285
+ if (input.type === InputType8.Coin) {
7136
8286
  return input.assetId === assetId;
7137
8287
  }
7138
8288
  if (isRequestInputMessageWithoutData(input)) {
@@ -7178,7 +8328,7 @@ var Account = class extends AbstractAccount {
7178
8328
  */
7179
8329
  async signMessage(message) {
7180
8330
  if (!this._connector) {
7181
- throw new FuelError22(ErrorCode18.MISSING_CONNECTOR, "A connector is required to sign messages.");
8331
+ throw new FuelError22(ErrorCode19.MISSING_CONNECTOR, "A connector is required to sign messages.");
7182
8332
  }
7183
8333
  return this._connector.signMessage(this.address.toString(), message);
7184
8334
  }
@@ -7191,7 +8341,7 @@ var Account = class extends AbstractAccount {
7191
8341
  async signTransaction(transactionRequestLike) {
7192
8342
  if (!this._connector) {
7193
8343
  throw new FuelError22(
7194
- ErrorCode18.MISSING_CONNECTOR,
8344
+ ErrorCode19.MISSING_CONNECTOR,
7195
8345
  "A connector is required to sign transactions."
7196
8346
  );
7197
8347
  }
@@ -7255,17 +8405,17 @@ var Account = class extends AbstractAccount {
7255
8405
  */
7256
8406
  generateFakeResources(coins) {
7257
8407
  return coins.map((coin) => ({
7258
- id: hexlify20(randomBytes5(UTXO_ID_LEN3)),
8408
+ id: hexlify21(randomBytes5(UTXO_ID_LEN3)),
7259
8409
  owner: this.address,
7260
- blockCreated: bn20(1),
7261
- txCreatedIdx: bn20(1),
8410
+ blockCreated: bn21(1),
8411
+ txCreatedIdx: bn21(1),
7262
8412
  ...coin
7263
8413
  }));
7264
8414
  }
7265
8415
  /** @hidden */
7266
8416
  async prepareTransactionForSend(request) {
7267
8417
  const { transactionId } = request.flag;
7268
- if (!isDefined3(transactionId)) {
8418
+ if (!isDefined4(transactionId)) {
7269
8419
  return request;
7270
8420
  }
7271
8421
  const chainId = await this.provider.getChainId();
@@ -7278,17 +8428,29 @@ var Account = class extends AbstractAccount {
7278
8428
  /** @hidden */
7279
8429
  async prepareTransactionSummary(request) {
7280
8430
  const chainId = await this.provider.getChainId();
7281
- return isDefined3(request.flag.summary) ? {
8431
+ return isDefined4(request.flag.summary) ? {
7282
8432
  ...request.flag.summary,
7283
8433
  id: request.getTransactionId(chainId),
7284
- transactionBytes: hexlify20(request.toTransactionBytes())
8434
+ transactionBytes: hexlify21(request.toTransactionBytes())
7285
8435
  } : void 0;
7286
8436
  }
7287
8437
  /** @hidden * */
8438
+ async assembleTx(transactionRequest, quantities = []) {
8439
+ const outputQuantities = transactionRequest.outputs.filter((o) => o.type === OutputType9.Coin).map(({ amount, assetId }) => ({ assetId: String(assetId), amount: bn21(amount) }));
8440
+ transactionRequest.gasLimit = bn21(0);
8441
+ transactionRequest.maxFee = bn21(0);
8442
+ const { assembledRequest, gasPrice } = await this.provider.assembleTx({
8443
+ request: transactionRequest,
8444
+ accountCoinQuantities: mergeQuantities(outputQuantities, quantities),
8445
+ feePayerAccount: this
8446
+ });
8447
+ return { transactionRequest: assembledRequest, gasPrice };
8448
+ }
8449
+ /** @hidden * */
7288
8450
  validateTransferAmount(amount) {
7289
- if (bn20(amount).lte(0)) {
8451
+ if (bn21(amount).lte(0)) {
7290
8452
  throw new FuelError22(
7291
- ErrorCode18.INVALID_TRANSFER_AMOUNT,
8453
+ ErrorCode19.INVALID_TRANSFER_AMOUNT,
7292
8454
  "Transfer amount must be a positive number."
7293
8455
  );
7294
8456
  }
@@ -7314,24 +8476,36 @@ var Account = class extends AbstractAccount {
7314
8476
  txParams: { gasLimit: setGasLimit, maxFee: setMaxFee }
7315
8477
  }) {
7316
8478
  const request = transactionRequestify(transactionRequest);
7317
- if (!isDefined3(setGasLimit)) {
8479
+ if (!isDefined4(setGasLimit)) {
7318
8480
  request.gasLimit = gasUsed;
7319
8481
  } else if (gasUsed.gt(setGasLimit)) {
7320
8482
  throw new FuelError22(
7321
- ErrorCode18.GAS_LIMIT_TOO_LOW,
8483
+ ErrorCode19.GAS_LIMIT_TOO_LOW,
7322
8484
  `Gas limit '${setGasLimit}' is lower than the required: '${gasUsed}'.`
7323
8485
  );
7324
8486
  }
7325
- if (!isDefined3(setMaxFee)) {
8487
+ if (!isDefined4(setMaxFee)) {
7326
8488
  request.maxFee = maxFee;
7327
8489
  } else if (maxFee.gt(setMaxFee)) {
7328
8490
  throw new FuelError22(
7329
- ErrorCode18.MAX_FEE_TOO_LOW,
8491
+ ErrorCode19.MAX_FEE_TOO_LOW,
7330
8492
  `Max fee '${setMaxFee}' is lower than the required: '${maxFee}'.`
7331
8493
  );
7332
8494
  }
7333
8495
  return request;
7334
8496
  }
8497
+ /** @hidden * */
8498
+ validateConsolidationTxsCoins(coins, assetId) {
8499
+ if (coins.length <= 1) {
8500
+ throw new FuelError22(ErrorCode19.NO_COINS_TO_CONSOLIDATE, "No coins to consolidate.");
8501
+ }
8502
+ if (!coins.every((c) => c.assetId === assetId)) {
8503
+ throw new FuelError22(
8504
+ ErrorCode19.COINS_ASSET_ID_MISMATCH,
8505
+ "All coins to consolidate must be from the same asset id."
8506
+ );
8507
+ }
8508
+ }
7335
8509
  };
7336
8510
 
7337
8511
  // src/wallet/keystore-wallet.ts
@@ -7346,8 +8520,8 @@ import {
7346
8520
  encryptJsonWalletData,
7347
8521
  randomUUID as randomUUID2
7348
8522
  } from "@fuel-ts/crypto";
7349
- import { ErrorCode as ErrorCode19, FuelError as FuelError23 } from "@fuel-ts/errors";
7350
- import { hexlify as hexlify21 } from "@fuel-ts/utils";
8523
+ import { ErrorCode as ErrorCode20, FuelError as FuelError23 } from "@fuel-ts/errors";
8524
+ import { hexlify as hexlify22 } from "@fuel-ts/utils";
7351
8525
  var DEFAULT_KDF_PARAMS_LOG_N = 13;
7352
8526
  var DEFAULT_KDF_PARAMS_R = 8;
7353
8527
  var DEFAULT_KDF_PARAMS_P = 1;
@@ -7425,12 +8599,12 @@ async function decryptKeystoreWallet(jsonWallet, password) {
7425
8599
  const macHash = stringFromBuffer(macHashUint8Array, "hex");
7426
8600
  if (mac !== macHash) {
7427
8601
  throw new FuelError23(
7428
- ErrorCode19.INVALID_PASSWORD,
8602
+ ErrorCode20.INVALID_PASSWORD,
7429
8603
  "Failed to decrypt the keystore wallet, the provided password is incorrect."
7430
8604
  );
7431
8605
  }
7432
8606
  const buffer = await decryptJsonWalletData(ciphertextBuffer, key, ivBuffer);
7433
- const privateKey = hexlify21(buffer);
8607
+ const privateKey = hexlify22(buffer);
7434
8608
  return privateKey;
7435
8609
  }
7436
8610
  __name(decryptKeystoreWallet, "decryptKeystoreWallet");
@@ -7483,7 +8657,7 @@ var BaseWalletUnlocked = class extends Account {
7483
8657
  */
7484
8658
  async signMessage(message) {
7485
8659
  const signedMessage = await this.signer().sign(hashMessage(message));
7486
- return hexlify22(signedMessage);
8660
+ return hexlify23(signedMessage);
7487
8661
  }
7488
8662
  /**
7489
8663
  * Signs a transaction with the wallet's private key.
@@ -7496,7 +8670,7 @@ var BaseWalletUnlocked = class extends Account {
7496
8670
  const chainId = await this.provider.getChainId();
7497
8671
  const hashedTransaction = transactionRequest.getTransactionId(chainId);
7498
8672
  const signature = await this.signer().sign(hashedTransaction);
7499
- return hexlify22(signature);
8673
+ return hexlify23(signature);
7500
8674
  }
7501
8675
  /**
7502
8676
  * Populates a transaction with the witnesses signature.
@@ -7564,16 +8738,16 @@ var BaseWalletUnlocked = class extends Account {
7564
8738
 
7565
8739
  // src/hdwallet/hdwallet.ts
7566
8740
  import { computeHmac as computeHmac2, ripemd160 } from "@fuel-ts/crypto";
7567
- import { ErrorCode as ErrorCode22, FuelError as FuelError26 } from "@fuel-ts/errors";
8741
+ import { ErrorCode as ErrorCode23, FuelError as FuelError26 } from "@fuel-ts/errors";
7568
8742
  import { sha256 as sha2564 } from "@fuel-ts/hasher";
7569
- import { bn as bn21, toBytes as toBytes2, toHex } from "@fuel-ts/math";
7570
- import { arrayify as arrayify20, hexlify as hexlify24, concat as concat6, dataSlice as dataSlice2, encodeBase58 as encodeBase582, decodeBase58 } from "@fuel-ts/utils";
8743
+ import { bn as bn22, toBytes as toBytes2, toHex } from "@fuel-ts/math";
8744
+ import { arrayify as arrayify20, hexlify as hexlify25, concat as concat6, dataSlice as dataSlice2, encodeBase58 as encodeBase582, decodeBase58 } from "@fuel-ts/utils";
7571
8745
 
7572
8746
  // src/mnemonic/mnemonic.ts
7573
8747
  import { randomBytes as randomBytes7, pbkdf2, computeHmac } from "@fuel-ts/crypto";
7574
- import { ErrorCode as ErrorCode21, FuelError as FuelError25 } from "@fuel-ts/errors";
8748
+ import { ErrorCode as ErrorCode22, FuelError as FuelError25 } from "@fuel-ts/errors";
7575
8749
  import { sha256 as sha2563 } from "@fuel-ts/hasher";
7576
- import { arrayify as arrayify19, hexlify as hexlify23, concat as concat5, dataSlice, encodeBase58, toUtf8Bytes } from "@fuel-ts/utils";
8750
+ import { arrayify as arrayify19, hexlify as hexlify24, concat as concat5, dataSlice, encodeBase58, toUtf8Bytes } from "@fuel-ts/utils";
7577
8751
 
7578
8752
  // src/wordlists/words/english.ts
7579
8753
  var english = [
@@ -9628,7 +10802,7 @@ var english = [
9628
10802
  ];
9629
10803
 
9630
10804
  // src/mnemonic/utils.ts
9631
- import { ErrorCode as ErrorCode20, FuelError as FuelError24 } from "@fuel-ts/errors";
10805
+ import { ErrorCode as ErrorCode21, FuelError as FuelError24 } from "@fuel-ts/errors";
9632
10806
  import { sha256 as sha2562 } from "@fuel-ts/hasher";
9633
10807
  import { arrayify as arrayify18 } from "@fuel-ts/utils";
9634
10808
  function getLowerMask(bits) {
@@ -9683,7 +10857,7 @@ function mnemonicWordsToEntropy(words, wordlist) {
9683
10857
  const index = wordlist.indexOf(words[i].normalize("NFKD"));
9684
10858
  if (index === -1) {
9685
10859
  throw new FuelError24(
9686
- ErrorCode20.INVALID_MNEMONIC,
10860
+ ErrorCode21.INVALID_MNEMONIC,
9687
10861
  `Invalid mnemonic: the word '${words[i]}' is not found in the provided wordlist.`
9688
10862
  );
9689
10863
  }
@@ -9700,7 +10874,7 @@ function mnemonicWordsToEntropy(words, wordlist) {
9700
10874
  const checksum = arrayify18(sha2562(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
9701
10875
  if (checksum !== (entropy[entropy.length - 1] & checksumMask)) {
9702
10876
  throw new FuelError24(
9703
- ErrorCode20.INVALID_CHECKSUM,
10877
+ ErrorCode21.INVALID_CHECKSUM,
9704
10878
  "Checksum validation failed for the provided mnemonic."
9705
10879
  );
9706
10880
  }
@@ -9716,7 +10890,7 @@ var MNEMONIC_SIZES = [12, 15, 18, 21, 24];
9716
10890
  function assertWordList(wordlist) {
9717
10891
  if (wordlist.length !== 2048) {
9718
10892
  throw new FuelError25(
9719
- ErrorCode21.INVALID_WORD_LIST,
10893
+ ErrorCode22.INVALID_WORD_LIST,
9720
10894
  `Expected word list length of 2048, but got ${wordlist.length}.`
9721
10895
  );
9722
10896
  }
@@ -9725,7 +10899,7 @@ __name(assertWordList, "assertWordList");
9725
10899
  function assertEntropy(entropy) {
9726
10900
  if (entropy.length % 4 !== 0 || entropy.length < 16 || entropy.length > 32) {
9727
10901
  throw new FuelError25(
9728
- ErrorCode21.INVALID_ENTROPY,
10902
+ ErrorCode22.INVALID_ENTROPY,
9729
10903
  `Entropy should be between 16 and 32 bytes and a multiple of 4, but got ${entropy.length} bytes.`
9730
10904
  );
9731
10905
  }
@@ -9736,7 +10910,7 @@ function assertMnemonic(words) {
9736
10910
  const errorMsg = `Invalid mnemonic size. Expected one of [${MNEMONIC_SIZES.join(
9737
10911
  ", "
9738
10912
  )}] words, but got ${words.length}.`;
9739
- throw new FuelError25(ErrorCode21.INVALID_MNEMONIC, errorMsg);
10913
+ throw new FuelError25(ErrorCode22.INVALID_MNEMONIC, errorMsg);
9740
10914
  }
9741
10915
  }
9742
10916
  __name(assertMnemonic, "assertMnemonic");
@@ -9779,7 +10953,7 @@ var Mnemonic = class _Mnemonic {
9779
10953
  static mnemonicToEntropy(phrase, wordlist = english) {
9780
10954
  const words = getWords(phrase);
9781
10955
  assertMnemonic(words);
9782
- return hexlify23(mnemonicWordsToEntropy(words, wordlist));
10956
+ return hexlify24(mnemonicWordsToEntropy(words, wordlist));
9783
10957
  }
9784
10958
  /**
9785
10959
  * @param entropy - Entropy source to the mnemonic phrase.
@@ -9859,7 +11033,7 @@ var Mnemonic = class _Mnemonic {
9859
11033
  const seedArray = arrayify19(seed);
9860
11034
  if (seedArray.length < 16 || seedArray.length > 64) {
9861
11035
  throw new FuelError25(
9862
- ErrorCode21.INVALID_SEED,
11036
+ ErrorCode22.INVALID_SEED,
9863
11037
  `Seed length should be between 16 and 64 bytes, but received ${seedArray.length} bytes.`
9864
11038
  );
9865
11039
  }
@@ -9912,10 +11086,10 @@ var mnemonic_default = Mnemonic;
9912
11086
 
9913
11087
  // src/hdwallet/hdwallet.ts
9914
11088
  var HARDENED_INDEX = 2147483648;
9915
- var MainnetPRV2 = hexlify24("0x0488ade4");
9916
- var MainnetPUB = hexlify24("0x0488b21e");
9917
- var TestnetPRV2 = hexlify24("0x04358394");
9918
- var TestnetPUB = hexlify24("0x043587cf");
11089
+ var MainnetPRV2 = hexlify25("0x0488ade4");
11090
+ var MainnetPUB = hexlify25("0x0488b21e");
11091
+ var TestnetPRV2 = hexlify25("0x04358394");
11092
+ var TestnetPUB = hexlify25("0x043587cf");
9919
11093
  function base58check(data) {
9920
11094
  return encodeBase582(concat6([data, dataSlice2(sha2564(sha2564(data)), 0, 4)]));
9921
11095
  }
@@ -9928,19 +11102,19 @@ function getExtendedKeyPrefix(isPublic = false, testnet = false) {
9928
11102
  }
9929
11103
  __name(getExtendedKeyPrefix, "getExtendedKeyPrefix");
9930
11104
  function isPublicExtendedKey(extendedKey) {
9931
- return [MainnetPUB, TestnetPUB].includes(hexlify24(extendedKey.slice(0, 4)));
11105
+ return [MainnetPUB, TestnetPUB].includes(hexlify25(extendedKey.slice(0, 4)));
9932
11106
  }
9933
11107
  __name(isPublicExtendedKey, "isPublicExtendedKey");
9934
11108
  function isValidExtendedKey(extendedKey) {
9935
11109
  return [MainnetPRV2, TestnetPRV2, MainnetPUB, TestnetPUB].includes(
9936
- hexlify24(extendedKey.slice(0, 4))
11110
+ hexlify25(extendedKey.slice(0, 4))
9937
11111
  );
9938
11112
  }
9939
11113
  __name(isValidExtendedKey, "isValidExtendedKey");
9940
11114
  function parsePath(path2, depth = 0) {
9941
11115
  const components = path2.split("/");
9942
11116
  if (components.length === 0 || components[0] === "m" && depth !== 0) {
9943
- throw new FuelError26(ErrorCode22.HD_WALLET_ERROR, `invalid path - ${path2}`);
11117
+ throw new FuelError26(ErrorCode23.HD_WALLET_ERROR, `invalid path - ${path2}`);
9944
11118
  }
9945
11119
  if (components[0] === "m") {
9946
11120
  components.shift();
@@ -9956,8 +11130,8 @@ var HDWallet = class _HDWallet {
9956
11130
  }
9957
11131
  depth = 0;
9958
11132
  index = 0;
9959
- fingerprint = hexlify24("0x00000000");
9960
- parentFingerprint = hexlify24("0x00000000");
11133
+ fingerprint = hexlify25("0x00000000");
11134
+ parentFingerprint = hexlify25("0x00000000");
9961
11135
  privateKey;
9962
11136
  publicKey;
9963
11137
  chainCode;
@@ -9969,16 +11143,16 @@ var HDWallet = class _HDWallet {
9969
11143
  constructor(config) {
9970
11144
  if (config.privateKey) {
9971
11145
  const signer = new Signer(config.privateKey);
9972
- this.publicKey = hexlify24(signer.compressedPublicKey);
9973
- this.privateKey = hexlify24(config.privateKey);
11146
+ this.publicKey = hexlify25(signer.compressedPublicKey);
11147
+ this.privateKey = hexlify25(config.privateKey);
9974
11148
  } else {
9975
11149
  if (!config.publicKey) {
9976
11150
  throw new FuelError26(
9977
- ErrorCode22.HD_WALLET_ERROR,
11151
+ ErrorCode23.HD_WALLET_ERROR,
9978
11152
  "Both public and private Key cannot be missing. At least one should be provided."
9979
11153
  );
9980
11154
  }
9981
- this.publicKey = hexlify24(config.publicKey);
11155
+ this.publicKey = hexlify25(config.publicKey);
9982
11156
  }
9983
11157
  this.parentFingerprint = config.parentFingerprint || this.parentFingerprint;
9984
11158
  this.fingerprint = dataSlice2(ripemd160(sha2564(this.publicKey)), 0, 4);
@@ -10004,7 +11178,7 @@ var HDWallet = class _HDWallet {
10004
11178
  if (index & HARDENED_INDEX) {
10005
11179
  if (!privateKey) {
10006
11180
  throw new FuelError26(
10007
- ErrorCode22.HD_WALLET_ERROR,
11181
+ ErrorCode23.HD_WALLET_ERROR,
10008
11182
  "Cannot derive a hardened index without a private Key."
10009
11183
  );
10010
11184
  }
@@ -10018,7 +11192,7 @@ var HDWallet = class _HDWallet {
10018
11192
  const IR = bytes.slice(32);
10019
11193
  if (privateKey) {
10020
11194
  const N = "0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141";
10021
- const ki = bn21(IL).add(privateKey).mod(N).toBytes(32);
11195
+ const ki = bn22(IL).add(privateKey).mod(N).toBytes(32);
10022
11196
  return new _HDWallet({
10023
11197
  privateKey: ki,
10024
11198
  chainCode: IR,
@@ -10027,7 +11201,7 @@ var HDWallet = class _HDWallet {
10027
11201
  parentFingerprint: this.fingerprint
10028
11202
  });
10029
11203
  }
10030
- const signer = new Signer(hexlify24(IL));
11204
+ const signer = new Signer(hexlify25(IL));
10031
11205
  const Ki = signer.addPoint(publicKey);
10032
11206
  return new _HDWallet({
10033
11207
  publicKey: Ki,
@@ -10057,12 +11231,12 @@ var HDWallet = class _HDWallet {
10057
11231
  toExtendedKey(isPublic = false, testnet = false) {
10058
11232
  if (this.depth >= 256) {
10059
11233
  throw new FuelError26(
10060
- ErrorCode22.HD_WALLET_ERROR,
11234
+ ErrorCode23.HD_WALLET_ERROR,
10061
11235
  `Exceeded max depth of 255. Current depth: ${this.depth}.`
10062
11236
  );
10063
11237
  }
10064
11238
  const prefix = getExtendedKeyPrefix(this.privateKey == null || isPublic, testnet);
10065
- const depth = hexlify24(Uint8Array.from([this.depth]));
11239
+ const depth = hexlify25(Uint8Array.from([this.depth]));
10066
11240
  const parentFingerprint = this.parentFingerprint;
10067
11241
  const index = toHex(this.index, 4);
10068
11242
  const chainCode = this.chainCode;
@@ -10084,29 +11258,29 @@ var HDWallet = class _HDWallet {
10084
11258
  });
10085
11259
  }
10086
11260
  static fromExtendedKey(extendedKey) {
10087
- const decoded = hexlify24(toBytes2(decodeBase58(extendedKey)));
11261
+ const decoded = hexlify25(toBytes2(decodeBase58(extendedKey)));
10088
11262
  const bytes = arrayify20(decoded);
10089
11263
  const validChecksum = base58check(bytes.slice(0, 78)) === extendedKey;
10090
11264
  if (bytes.length !== 82 || !isValidExtendedKey(bytes)) {
10091
- throw new FuelError26(ErrorCode22.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
11265
+ throw new FuelError26(ErrorCode23.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
10092
11266
  }
10093
11267
  if (!validChecksum) {
10094
- throw new FuelError26(ErrorCode22.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
11268
+ throw new FuelError26(ErrorCode23.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
10095
11269
  }
10096
11270
  const depth = bytes[4];
10097
- const parentFingerprint = hexlify24(bytes.slice(5, 9));
10098
- const index = parseInt(hexlify24(bytes.slice(9, 13)).substring(2), 16);
10099
- const chainCode = hexlify24(bytes.slice(13, 45));
11271
+ const parentFingerprint = hexlify25(bytes.slice(5, 9));
11272
+ const index = parseInt(hexlify25(bytes.slice(9, 13)).substring(2), 16);
11273
+ const chainCode = hexlify25(bytes.slice(13, 45));
10100
11274
  const key = bytes.slice(45, 78);
10101
11275
  if (depth === 0 && parentFingerprint !== "0x00000000" || depth === 0 && index !== 0) {
10102
11276
  throw new FuelError26(
10103
- ErrorCode22.HD_WALLET_ERROR,
11277
+ ErrorCode23.HD_WALLET_ERROR,
10104
11278
  "Inconsistency detected: Depth is zero but fingerprint/index is non-zero."
10105
11279
  );
10106
11280
  }
10107
11281
  if (isPublicExtendedKey(bytes)) {
10108
11282
  if (key[0] !== 3) {
10109
- throw new FuelError26(ErrorCode22.HD_WALLET_ERROR, "Invalid public extended key.");
11283
+ throw new FuelError26(ErrorCode23.HD_WALLET_ERROR, "Invalid public extended key.");
10110
11284
  }
10111
11285
  return new _HDWallet({
10112
11286
  publicKey: key,
@@ -10117,7 +11291,7 @@ var HDWallet = class _HDWallet {
10117
11291
  });
10118
11292
  }
10119
11293
  if (key[0] !== 0) {
10120
- throw new FuelError26(ErrorCode22.HD_WALLET_ERROR, "Invalid private extended key.");
11294
+ throw new FuelError26(ErrorCode23.HD_WALLET_ERROR, "Invalid private extended key.");
10121
11295
  }
10122
11296
  return new _HDWallet({
10123
11297
  privateKey: key.slice(1),
@@ -10353,13 +11527,13 @@ var WalletsConfig = class _WalletsConfig {
10353
11527
  assetIds.forEach((assetId) => {
10354
11528
  for (let index = 0; index < coinsPerAsset; index++) {
10355
11529
  coins.push({
10356
- amount: bn22(amountPerCoin).toString(),
11530
+ amount: bn23(amountPerCoin).toString(),
10357
11531
  asset_id: assetId,
10358
11532
  owner: walletAddress,
10359
11533
  tx_pointer_block_height: 0,
10360
11534
  tx_pointer_tx_idx: 0,
10361
11535
  output_index: 0,
10362
- tx_id: hexlify25(randomBytes8(32))
11536
+ tx_id: hexlify26(randomBytes8(32))
10363
11537
  });
10364
11538
  }
10365
11539
  });
@@ -10390,7 +11564,7 @@ var WalletsConfig = class _WalletsConfig {
10390
11564
  "Number of coins per asset must be greater than zero."
10391
11565
  );
10392
11566
  }
10393
- if (bn22(amountPerCoin).lt(0)) {
11567
+ if (bn23(amountPerCoin).lt(0)) {
10394
11568
  throw new FuelError27(
10395
11569
  FuelError27.CODES.INVALID_INPUT_PARAMETERS,
10396
11570
  "Amount per coin must be greater than or equal to zero."
@@ -10430,23 +11604,26 @@ async function setupTestProviderAndWallets({
10430
11604
  ),
10431
11605
  port: nodeOptions.port || "0"
10432
11606
  };
10433
- let cleanup;
11607
+ let killNode;
10434
11608
  let url;
10435
11609
  if (launchNodeServerPort) {
10436
11610
  const serverUrl = `http://localhost:${launchNodeServerPort}`;
10437
11611
  url = await (await fetch(serverUrl, { method: "POST", body: JSON.stringify(launchNodeOptions) })).text();
10438
- cleanup = /* @__PURE__ */ __name(() => {
11612
+ killNode = /* @__PURE__ */ __name(() => {
10439
11613
  fetch(`${serverUrl}/cleanup/${url}`);
10440
- }, "cleanup");
11614
+ }, "killNode");
10441
11615
  } else {
10442
11616
  const settings = await launchNode(launchNodeOptions);
10443
11617
  url = settings.url;
10444
- cleanup = settings.cleanup;
11618
+ killNode = settings.cleanup;
10445
11619
  }
11620
+ const cleanup = /* @__PURE__ */ __name(() => {
11621
+ Provider.clearChainAndNodeCaches(url);
11622
+ killNode();
11623
+ }, "cleanup");
10446
11624
  let provider;
10447
11625
  try {
10448
11626
  provider = new Provider(url, providerOptions);
10449
- await provider.init();
10450
11627
  } catch (err) {
10451
11628
  cleanup();
10452
11629
  throw err;
@@ -10467,8 +11644,8 @@ __name(setupTestProviderAndWallets, "setupTestProviderAndWallets");
10467
11644
  // src/test-utils/test-message.ts
10468
11645
  import { Address as Address7 } from "@fuel-ts/address";
10469
11646
  import { randomBytes as randomBytes9 } from "@fuel-ts/crypto";
10470
- import { bn as bn23 } from "@fuel-ts/math";
10471
- import { hexlify as hexlify26 } from "@fuel-ts/utils";
11647
+ import { bn as bn24 } from "@fuel-ts/math";
11648
+ import { hexlify as hexlify27 } from "@fuel-ts/utils";
10472
11649
  var TestMessage = class {
10473
11650
  static {
10474
11651
  __name(this, "TestMessage");
@@ -10488,7 +11665,7 @@ var TestMessage = class {
10488
11665
  constructor({
10489
11666
  sender = Address7.fromRandom(),
10490
11667
  recipient = Address7.fromRandom(),
10491
- nonce = hexlify26(randomBytes9(32)),
11668
+ nonce = hexlify27(randomBytes9(32)),
10492
11669
  amount = 1e6,
10493
11670
  data = "",
10494
11671
  // Will default to empty data in order to be a spendable message
@@ -10507,7 +11684,7 @@ var TestMessage = class {
10507
11684
  sender: this.sender.toB256(),
10508
11685
  recipient: recipient?.toB256() ?? this.recipient.toB256(),
10509
11686
  nonce: this.nonce,
10510
- amount: bn23(this.amount).toNumber(),
11687
+ amount: bn24(this.amount).toNumber(),
10511
11688
  data,
10512
11689
  da_height: this.da_height
10513
11690
  };