@fuel-ts/account 0.96.0 → 0.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/account.d.ts +6 -0
  2. package/dist/account.d.ts.map +1 -1
  3. package/dist/connectors/fuel.d.ts.map +1 -1
  4. package/dist/index.d.ts +1 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.global.js +639 -310
  7. package/dist/index.global.js.map +1 -1
  8. package/dist/index.js +661 -331
  9. package/dist/index.js.map +1 -1
  10. package/dist/index.mjs +666 -338
  11. package/dist/index.mjs.map +1 -1
  12. package/dist/predicate/predicate.d.ts +16 -11
  13. package/dist/predicate/predicate.d.ts.map +1 -1
  14. package/dist/providers/__generated__/operations.d.ts +108 -126
  15. package/dist/providers/__generated__/operations.d.ts.map +1 -1
  16. package/dist/providers/provider.d.ts +15 -11
  17. package/dist/providers/provider.d.ts.map +1 -1
  18. package/dist/providers/transaction-request/blob-transaction-request.d.ts +2 -2
  19. package/dist/providers/transaction-request/blob-transaction-request.d.ts.map +1 -1
  20. package/dist/providers/transaction-summary/get-transaction-summary.d.ts +3 -2
  21. package/dist/providers/transaction-summary/get-transaction-summary.d.ts.map +1 -1
  22. package/dist/providers/transaction-summary/types.d.ts +38 -8
  23. package/dist/providers/transaction-summary/types.d.ts.map +1 -1
  24. package/dist/providers/utils/handle-gql-error-message.d.ts +2 -1
  25. package/dist/providers/utils/handle-gql-error-message.d.ts.map +1 -1
  26. package/dist/providers/utils/receipts.d.ts.map +1 -1
  27. package/dist/providers/utils/validate-pagination-args.d.ts +9 -0
  28. package/dist/providers/utils/validate-pagination-args.d.ts.map +1 -0
  29. package/dist/test-utils.global.js +376 -248
  30. package/dist/test-utils.global.js.map +1 -1
  31. package/dist/test-utils.js +339 -221
  32. package/dist/test-utils.js.map +1 -1
  33. package/dist/test-utils.mjs +350 -232
  34. package/dist/test-utils.mjs.map +1 -1
  35. package/dist/utils/deployScriptOrPredicate.d.ts +14 -0
  36. package/dist/utils/deployScriptOrPredicate.d.ts.map +1 -0
  37. package/dist/utils/formatTransferToContractScriptData.d.ts +7 -7
  38. package/dist/utils/formatTransferToContractScriptData.d.ts.map +1 -1
  39. package/dist/utils/predicate-script-loader-instructions.d.ts +9 -0
  40. package/dist/utils/predicate-script-loader-instructions.d.ts.map +1 -0
  41. package/package.json +17 -17
package/dist/index.js CHANGED
@@ -73,6 +73,7 @@ __export(src_exports, {
73
73
  FuelConnectorEventType: () => FuelConnectorEventType,
74
74
  FuelConnectorEventTypes: () => FuelConnectorEventTypes,
75
75
  FuelConnectorMethods: () => FuelConnectorMethods,
76
+ GAS_USED_MODIFIER: () => GAS_USED_MODIFIER,
76
77
  HDWallet: () => hdwallet_default,
77
78
  Language: () => Language,
78
79
  LocalStorage: () => LocalStorage,
@@ -124,6 +125,7 @@ __export(src_exports, {
124
125
  calculateTXFeeForSummary: () => calculateTXFeeForSummary,
125
126
  coinQuantityfy: () => coinQuantityfy,
126
127
  deferPromise: () => deferPromise,
128
+ deployScriptOrPredicate: () => deployScriptOrPredicate,
127
129
  dispatchFuelConnectorEvent: () => dispatchFuelConnectorEvent,
128
130
  english: () => english,
129
131
  extractBurnedAssetsFromReceipts: () => extractBurnedAssetsFromReceipts,
@@ -217,9 +219,9 @@ module.exports = __toCommonJS(src_exports);
217
219
 
218
220
  // src/account.ts
219
221
  var import_abi_coder7 = require("@fuel-ts/abi-coder");
220
- var import_address4 = require("@fuel-ts/address");
222
+ var import_address5 = require("@fuel-ts/address");
221
223
  var import_crypto2 = require("@fuel-ts/crypto");
222
- var import_errors19 = require("@fuel-ts/errors");
224
+ var import_errors20 = require("@fuel-ts/errors");
223
225
  var import_interfaces = require("@fuel-ts/interfaces");
224
226
  var import_math21 = require("@fuel-ts/math");
225
227
  var import_transactions24 = require("@fuel-ts/transactions");
@@ -263,7 +265,7 @@ var addAmountToCoinQuantities = (params) => {
263
265
 
264
266
  // src/providers/provider.ts
265
267
  var import_address3 = require("@fuel-ts/address");
266
- var import_errors17 = require("@fuel-ts/errors");
268
+ var import_errors18 = require("@fuel-ts/errors");
267
269
  var import_math18 = require("@fuel-ts/math");
268
270
  var import_transactions22 = require("@fuel-ts/transactions");
269
271
  var import_utils28 = require("@fuel-ts/utils");
@@ -316,9 +318,6 @@ var ReceiptFragmentDoc = import_graphql_tag.default`
316
318
  var SuccessStatusFragmentDoc = import_graphql_tag.default`
317
319
  fragment SuccessStatusFragment on SuccessStatus {
318
320
  type: __typename
319
- block {
320
- id
321
- }
322
321
  time
323
322
  programState {
324
323
  returnType
@@ -331,6 +330,14 @@ var SuccessStatusFragmentDoc = import_graphql_tag.default`
331
330
  totalFee
332
331
  }
333
332
  ${ReceiptFragmentDoc}`;
333
+ var SuccessStatusWithBlockIdFragmentDoc = import_graphql_tag.default`
334
+ fragment SuccessStatusWithBlockIdFragment on SuccessStatus {
335
+ ...SuccessStatusFragment
336
+ block {
337
+ id
338
+ }
339
+ }
340
+ ${SuccessStatusFragmentDoc}`;
334
341
  var MalleableTransactionFieldsFragmentDoc = import_graphql_tag.default`
335
342
  fragment malleableTransactionFieldsFragment on Transaction {
336
343
  receiptsRoot
@@ -375,9 +382,6 @@ var MalleableTransactionFieldsFragmentDoc = import_graphql_tag.default`
375
382
  var FailureStatusFragmentDoc = import_graphql_tag.default`
376
383
  fragment FailureStatusFragment on FailureStatus {
377
384
  type: __typename
378
- block {
379
- id
380
- }
381
385
  totalGas
382
386
  totalFee
383
387
  time
@@ -387,6 +391,14 @@ var FailureStatusFragmentDoc = import_graphql_tag.default`
387
391
  }
388
392
  }
389
393
  ${ReceiptFragmentDoc}`;
394
+ var FailureStatusWithBlockIdFragmentDoc = import_graphql_tag.default`
395
+ fragment FailureStatusWithBlockIdFragment on FailureStatus {
396
+ ...FailureStatusFragment
397
+ block {
398
+ id
399
+ }
400
+ }
401
+ ${FailureStatusFragmentDoc}`;
390
402
  var SqueezedOutStatusFragmentDoc = import_graphql_tag.default`
391
403
  fragment SqueezedOutStatusFragment on SqueezedOutStatus {
392
404
  type: __typename
@@ -399,13 +411,13 @@ var TransactionStatusSubscriptionFragmentDoc = import_graphql_tag.default`
399
411
  ...SubmittedStatusFragment
400
412
  }
401
413
  ... on SuccessStatus {
402
- ...SuccessStatusFragment
414
+ ...SuccessStatusWithBlockIdFragment
403
415
  transaction {
404
416
  ...malleableTransactionFieldsFragment
405
417
  }
406
418
  }
407
419
  ... on FailureStatus {
408
- ...FailureStatusFragment
420
+ ...FailureStatusWithBlockIdFragment
409
421
  transaction {
410
422
  ...malleableTransactionFieldsFragment
411
423
  }
@@ -415,9 +427,9 @@ var TransactionStatusSubscriptionFragmentDoc = import_graphql_tag.default`
415
427
  }
416
428
  }
417
429
  ${SubmittedStatusFragmentDoc}
418
- ${SuccessStatusFragmentDoc}
430
+ ${SuccessStatusWithBlockIdFragmentDoc}
419
431
  ${MalleableTransactionFieldsFragmentDoc}
420
- ${FailureStatusFragmentDoc}
432
+ ${FailureStatusWithBlockIdFragmentDoc}
421
433
  ${SqueezedOutStatusFragmentDoc}`;
422
434
  var TransactionStatusFragmentDoc = import_graphql_tag.default`
423
435
  fragment transactionStatusFragment on TransactionStatus {
@@ -447,6 +459,12 @@ var TransactionFragmentDoc = import_graphql_tag.default`
447
459
  }
448
460
  }
449
461
  ${TransactionStatusFragmentDoc}`;
462
+ var TransactionRawPayloadFragmentDoc = import_graphql_tag.default`
463
+ fragment transactionRawPayloadFragment on Transaction {
464
+ id
465
+ rawPayload
466
+ }
467
+ `;
450
468
  var InputEstimatePredicatesFragmentDoc = import_graphql_tag.default`
451
469
  fragment inputEstimatePredicatesFragment on Input {
452
470
  ... on InputCoin {
@@ -534,7 +552,6 @@ var CoinFragmentDoc = import_graphql_tag.default`
534
552
  fragment coinFragment on Coin {
535
553
  type: __typename
536
554
  utxoId
537
- owner
538
555
  amount
539
556
  assetId
540
557
  blockCreated
@@ -558,10 +575,15 @@ var MessageFragmentDoc = import_graphql_tag.default`
558
575
  sender
559
576
  recipient
560
577
  data
561
- nonce
562
578
  daHeight
563
579
  }
564
580
  `;
581
+ var GetMessageFragmentDoc = import_graphql_tag.default`
582
+ fragment getMessageFragment on Message {
583
+ ...messageFragment
584
+ nonce
585
+ }
586
+ ${MessageFragmentDoc}`;
565
587
  var MessageProofFragmentDoc = import_graphql_tag.default`
566
588
  fragment messageProofFragment on MessageProof {
567
589
  messageProof {
@@ -606,7 +628,6 @@ var MessageProofFragmentDoc = import_graphql_tag.default`
606
628
  }
607
629
  sender
608
630
  recipient
609
- nonce
610
631
  amount
611
632
  data
612
633
  }
@@ -755,12 +776,6 @@ var RelayedTransactionStatusFragmentDoc = import_graphql_tag.default`
755
776
  }
756
777
  }
757
778
  `;
758
- var TransactionRawPayloadFragmentDoc = import_graphql_tag.default`
759
- fragment transactionRawPayload on Transaction {
760
- id
761
- rawPayload
762
- }
763
- `;
764
779
  var GetVersionDocument = import_graphql_tag.default`
765
780
  query getVersion {
766
781
  nodeInfo {
@@ -803,16 +818,34 @@ var GetTransactionDocument = import_graphql_tag.default`
803
818
  var GetTransactionWithReceiptsDocument = import_graphql_tag.default`
804
819
  query getTransactionWithReceipts($transactionId: TransactionId!) {
805
820
  transaction(id: $transactionId) {
806
- ...transactionFragment
821
+ id
822
+ rawPayload
823
+ status {
824
+ ... on SubmittedStatus {
825
+ ...SubmittedStatusFragment
826
+ }
827
+ ... on SuccessStatus {
828
+ ...SuccessStatusWithBlockIdFragment
829
+ }
830
+ ... on FailureStatus {
831
+ ...FailureStatusWithBlockIdFragment
832
+ }
833
+ ... on SqueezedOutStatus {
834
+ ...SqueezedOutStatusFragment
835
+ }
836
+ }
807
837
  }
808
838
  }
809
- ${TransactionFragmentDoc}`;
839
+ ${SubmittedStatusFragmentDoc}
840
+ ${SuccessStatusWithBlockIdFragmentDoc}
841
+ ${FailureStatusWithBlockIdFragmentDoc}
842
+ ${SqueezedOutStatusFragmentDoc}`;
810
843
  var GetTransactionsDocument = import_graphql_tag.default`
811
844
  query getTransactions($after: String, $before: String, $first: Int, $last: Int) {
812
845
  transactions(after: $after, before: $before, first: $first, last: $last) {
813
846
  edges {
814
847
  node {
815
- ...transactionFragment
848
+ rawPayload
816
849
  }
817
850
  }
818
851
  pageInfo {
@@ -820,8 +853,7 @@ var GetTransactionsDocument = import_graphql_tag.default`
820
853
  }
821
854
  }
822
855
  }
823
- ${TransactionFragmentDoc}
824
- ${PageInfoFragmentDoc}`;
856
+ ${PageInfoFragmentDoc}`;
825
857
  var GetTransactionsByOwnerDocument = import_graphql_tag.default`
826
858
  query getTransactionsByOwner($owner: Address!, $after: String, $before: String, $first: Int, $last: Int) {
827
859
  transactionsByOwner(
@@ -880,7 +912,7 @@ var GetBlockWithTransactionsDocument = import_graphql_tag.default`
880
912
  block(id: $blockId, height: $blockHeight) {
881
913
  ...blockFragment
882
914
  transactions {
883
- ...transactionRawPayload
915
+ ...transactionRawPayloadFragment
884
916
  }
885
917
  }
886
918
  }
@@ -905,6 +937,7 @@ var GetCoinDocument = import_graphql_tag.default`
905
937
  query getCoin($coinId: UtxoId!) {
906
938
  coin(utxoId: $coinId) {
907
939
  ...coinFragment
940
+ owner
908
941
  }
909
942
  }
910
943
  ${CoinFragmentDoc}`;
@@ -1013,13 +1046,13 @@ var GetMessagesDocument = import_graphql_tag.default`
1013
1046
  }
1014
1047
  edges {
1015
1048
  node {
1016
- ...messageFragment
1049
+ ...getMessageFragment
1017
1050
  }
1018
1051
  }
1019
1052
  }
1020
1053
  }
1021
1054
  ${PageInfoFragmentDoc}
1022
- ${MessageFragmentDoc}`;
1055
+ ${GetMessageFragmentDoc}`;
1023
1056
  var GetMessageProofDocument = import_graphql_tag.default`
1024
1057
  query getMessageProof($transactionId: TransactionId!, $nonce: Nonce!, $commitBlockId: BlockId, $commitBlockHeight: U32) {
1025
1058
  messageProof(
@@ -1092,6 +1125,17 @@ var IsUserAccountDocument = import_graphql_tag.default`
1092
1125
  }
1093
1126
  }
1094
1127
  `;
1128
+ var GetConsensusParametersVersionDocument = import_graphql_tag.default`
1129
+ query getConsensusParametersVersion {
1130
+ chain {
1131
+ latestBlock {
1132
+ header {
1133
+ consensusParametersVersion
1134
+ }
1135
+ }
1136
+ }
1137
+ }
1138
+ `;
1095
1139
  var SubmitAndAwaitDocument = import_graphql_tag.default`
1096
1140
  subscription submitAndAwait($encodedTransaction: HexString!) {
1097
1141
  submitAndAwait(tx: $encodedTransaction) {
@@ -1211,6 +1255,9 @@ function getSdk(requester) {
1211
1255
  isUserAccount(variables, options) {
1212
1256
  return requester(IsUserAccountDocument, variables, options);
1213
1257
  },
1258
+ getConsensusParametersVersion(variables, options) {
1259
+ return requester(GetConsensusParametersVersionDocument, variables, options);
1260
+ },
1214
1261
  submitAndAwait(variables, options) {
1215
1262
  return requester(SubmitAndAwaitDocument, variables, options);
1216
1263
  },
@@ -1540,9 +1587,11 @@ function assembleReceiptByType(receipt) {
1540
1587
  const { receiptType } = receipt;
1541
1588
  switch (receiptType) {
1542
1589
  case "CALL" /* Call */: {
1590
+ const id = hexOrZero(receipt.id || receipt.contractId);
1543
1591
  const callReceipt = {
1544
1592
  type: import_transactions3.ReceiptType.Call,
1545
- from: hexOrZero(receipt.id || receipt.contractId),
1593
+ id,
1594
+ from: id,
1546
1595
  to: hexOrZero(receipt?.to),
1547
1596
  amount: (0, import_math4.bn)(receipt.amount),
1548
1597
  assetId: hexOrZero(receipt.assetId),
@@ -1599,24 +1648,36 @@ function assembleReceiptByType(receipt) {
1599
1648
  return revertReceipt;
1600
1649
  }
1601
1650
  case "LOG" /* Log */: {
1651
+ const ra = (0, import_math4.bn)(receipt.ra);
1652
+ const rb = (0, import_math4.bn)(receipt.rb);
1653
+ const rc = (0, import_math4.bn)(receipt.rc);
1654
+ const rd = (0, import_math4.bn)(receipt.rd);
1602
1655
  const logReceipt = {
1603
1656
  type: import_transactions3.ReceiptType.Log,
1604
1657
  id: hexOrZero(receipt.id || receipt.contractId),
1605
- val0: (0, import_math4.bn)(receipt.ra),
1606
- val1: (0, import_math4.bn)(receipt.rb),
1607
- val2: (0, import_math4.bn)(receipt.rc),
1608
- val3: (0, import_math4.bn)(receipt.rd),
1658
+ ra,
1659
+ rb,
1660
+ rc,
1661
+ rd,
1662
+ val0: ra,
1663
+ val1: rb,
1664
+ val2: rc,
1665
+ val3: rd,
1609
1666
  pc: (0, import_math4.bn)(receipt.pc),
1610
1667
  is: (0, import_math4.bn)(receipt.is)
1611
1668
  };
1612
1669
  return logReceipt;
1613
1670
  }
1614
1671
  case "LOG_DATA" /* LogData */: {
1672
+ const ra = (0, import_math4.bn)(receipt.ra);
1673
+ const rb = (0, import_math4.bn)(receipt.rb);
1615
1674
  const logDataReceipt = {
1616
1675
  type: import_transactions3.ReceiptType.LogData,
1617
1676
  id: hexOrZero(receipt.id || receipt.contractId),
1618
- val0: (0, import_math4.bn)(receipt.ra),
1619
- val1: (0, import_math4.bn)(receipt.rb),
1677
+ ra,
1678
+ rb,
1679
+ val0: ra,
1680
+ val1: rb,
1620
1681
  ptr: (0, import_math4.bn)(receipt.ptr),
1621
1682
  len: (0, import_math4.bn)(receipt.len),
1622
1683
  digest: hexOrZero(receipt.digest),
@@ -1627,9 +1688,11 @@ function assembleReceiptByType(receipt) {
1627
1688
  return logDataReceipt;
1628
1689
  }
1629
1690
  case "TRANSFER" /* Transfer */: {
1691
+ const id = hexOrZero(receipt.id || receipt.contractId);
1630
1692
  const transferReceipt = {
1631
1693
  type: import_transactions3.ReceiptType.Transfer,
1632
- from: hexOrZero(receipt.id || receipt.contractId),
1694
+ id,
1695
+ from: id,
1633
1696
  to: hexOrZero(receipt.toAddress || receipt?.to),
1634
1697
  amount: (0, import_math4.bn)(receipt.amount),
1635
1698
  assetId: hexOrZero(receipt.assetId),
@@ -1639,9 +1702,11 @@ function assembleReceiptByType(receipt) {
1639
1702
  return transferReceipt;
1640
1703
  }
1641
1704
  case "TRANSFER_OUT" /* TransferOut */: {
1705
+ const id = hexOrZero(receipt.id || receipt.contractId);
1642
1706
  const transferOutReceipt = {
1643
1707
  type: import_transactions3.ReceiptType.TransferOut,
1644
- from: hexOrZero(receipt.id || receipt.contractId),
1708
+ id,
1709
+ from: id,
1645
1710
  to: hexOrZero(receipt.toAddress || receipt.to),
1646
1711
  amount: (0, import_math4.bn)(receipt.amount),
1647
1712
  assetId: hexOrZero(receipt.assetId),
@@ -2703,7 +2768,7 @@ var BlobTransactionRequest = class extends BaseTransactionRequest {
2703
2768
  type = import_transactions7.TransactionType.Blob;
2704
2769
  /** Blob ID */
2705
2770
  blobId;
2706
- /** Witness index of contract bytecode to create */
2771
+ /** Witness index of the bytecode to create */
2707
2772
  witnessIndex;
2708
2773
  /**
2709
2774
  * Creates an instance `BlobTransactionRequest`.
@@ -4087,14 +4152,14 @@ var processGraphqlStatus = (gqlTransactionStatus) => {
4087
4152
  switch (gqlTransactionStatus.type) {
4088
4153
  case "SuccessStatus":
4089
4154
  time = gqlTransactionStatus.time;
4090
- blockId = gqlTransactionStatus.block.id;
4155
+ blockId = gqlTransactionStatus.block?.id;
4091
4156
  isStatusSuccess = true;
4092
4157
  totalFee = (0, import_math15.bn)(gqlTransactionStatus.totalFee);
4093
4158
  totalGas = (0, import_math15.bn)(gqlTransactionStatus.totalGas);
4094
4159
  break;
4095
4160
  case "FailureStatus":
4096
4161
  time = gqlTransactionStatus.time;
4097
- blockId = gqlTransactionStatus.block.id;
4162
+ blockId = gqlTransactionStatus.block?.id;
4098
4163
  isStatusFailure = true;
4099
4164
  totalFee = (0, import_math15.bn)(gqlTransactionStatus.totalFee);
4100
4165
  totalGas = (0, import_math15.bn)(gqlTransactionStatus.totalGas);
@@ -4405,8 +4470,8 @@ var TransactionResponse = class {
4405
4470
  const subscription = this.submitTxSubscription ?? await this.provider.operations.statusChange({
4406
4471
  transactionId: this.id
4407
4472
  });
4408
- for await (const sub of subscription) {
4409
- const statusChange = "statusChange" in sub ? sub.statusChange : sub.submitAndAwaitStatus;
4473
+ for await (const sub2 of subscription) {
4474
+ const statusChange = "statusChange" in sub2 ? sub2.statusChange : sub2.submitAndAwaitStatus;
4410
4475
  this.status = statusChange;
4411
4476
  if (statusChange.type === "SqueezedOutStatus") {
4412
4477
  this.unsetResourceCache();
@@ -4529,17 +4594,60 @@ var handleGqlErrorMessage = (errorMessage, rawError) => {
4529
4594
  {},
4530
4595
  rawError
4531
4596
  );
4597
+ case "max number of coins is reached while trying to fit the target" /* MAX_COINS_REACHED */:
4598
+ throw new import_errors16.FuelError(
4599
+ import_errors16.ErrorCode.MAX_COINS_REACHED,
4600
+ "The account retrieving coins has exceeded the maximum number of coins per asset. Please consider combining your coins into a single UTXO.",
4601
+ {},
4602
+ rawError
4603
+ );
4532
4604
  default:
4533
4605
  throw new import_errors16.FuelError(import_errors16.ErrorCode.INVALID_REQUEST, errorMessage);
4534
4606
  }
4535
4607
  };
4536
4608
 
4609
+ // src/providers/utils/validate-pagination-args.ts
4610
+ var import_errors17 = require("@fuel-ts/errors");
4611
+ var validatePaginationArgs = (params) => {
4612
+ const { paginationLimit, inputArgs = {} } = params;
4613
+ const { first, last, after, before } = inputArgs;
4614
+ if (after && before) {
4615
+ throw new import_errors17.FuelError(
4616
+ import_errors17.ErrorCode.INVALID_INPUT_PARAMETERS,
4617
+ 'Pagination arguments "after" and "before" cannot be used together'
4618
+ );
4619
+ }
4620
+ if ((first || 0) > paginationLimit || (last || 0) > paginationLimit) {
4621
+ throw new import_errors17.FuelError(
4622
+ import_errors17.ErrorCode.INVALID_INPUT_PARAMETERS,
4623
+ `Pagination limit for this query cannot exceed ${paginationLimit} items`
4624
+ );
4625
+ }
4626
+ if (first && before) {
4627
+ throw new import_errors17.FuelError(
4628
+ import_errors17.ErrorCode.INVALID_INPUT_PARAMETERS,
4629
+ 'The use of pagination argument "first" with "before" is not supported'
4630
+ );
4631
+ }
4632
+ if (last && after) {
4633
+ throw new import_errors17.FuelError(
4634
+ import_errors17.ErrorCode.INVALID_INPUT_PARAMETERS,
4635
+ 'The use of pagination argument "last" with "after" is not supported'
4636
+ );
4637
+ }
4638
+ if (!first && !last) {
4639
+ inputArgs.first = paginationLimit;
4640
+ }
4641
+ return inputArgs;
4642
+ };
4643
+
4537
4644
  // src/providers/provider.ts
4538
4645
  var MAX_RETRIES = 10;
4539
4646
  var RESOURCES_PAGE_SIZE_LIMIT = 512;
4540
4647
  var TRANSACTIONS_PAGE_SIZE_LIMIT = 60;
4541
4648
  var BLOCKS_PAGE_SIZE_LIMIT = 5;
4542
4649
  var DEFAULT_RESOURCE_CACHE_TTL = 2e4;
4650
+ var GAS_USED_MODIFIER = 1.2;
4543
4651
  var processGqlChain = (chain) => {
4544
4652
  const { name, daHeight, consensusParameters } = chain;
4545
4653
  const {
@@ -4615,6 +4723,8 @@ var _Provider = class {
4615
4723
  __publicField(this, "url");
4616
4724
  /** @hidden */
4617
4725
  __publicField(this, "urlWithoutAuth");
4726
+ /** @hidden */
4727
+ __publicField(this, "consensusParametersTimestamp");
4618
4728
  __publicField(this, "options", {
4619
4729
  timeout: void 0,
4620
4730
  resourceCacheTTL: void 0,
@@ -4675,7 +4785,7 @@ var _Provider = class {
4675
4785
  try {
4676
4786
  parsedUrl = new URL(url);
4677
4787
  } catch (error) {
4678
- throw new import_errors17.FuelError(import_errors17.FuelError.CODES.INVALID_URL, "Invalid URL provided.", { url }, error);
4788
+ throw new import_errors18.FuelError(import_errors18.FuelError.CODES.INVALID_URL, "Invalid URL provided.", { url }, error);
4679
4789
  }
4680
4790
  const username = parsedUrl.username;
4681
4791
  const password = parsedUrl.password;
@@ -4710,8 +4820,8 @@ var _Provider = class {
4710
4820
  getChain() {
4711
4821
  const chain = _Provider.chainInfoCache[this.urlWithoutAuth];
4712
4822
  if (!chain) {
4713
- throw new import_errors17.FuelError(
4714
- import_errors17.ErrorCode.CHAIN_INFO_CACHE_EMPTY,
4823
+ throw new import_errors18.FuelError(
4824
+ import_errors18.ErrorCode.CHAIN_INFO_CACHE_EMPTY,
4715
4825
  "Chain info cache is empty. Make sure you have called `Provider.create` to initialize the provider."
4716
4826
  );
4717
4827
  }
@@ -4725,8 +4835,8 @@ var _Provider = class {
4725
4835
  getNode() {
4726
4836
  const node = _Provider.nodeInfoCache[this.urlWithoutAuth];
4727
4837
  if (!node) {
4728
- throw new import_errors17.FuelError(
4729
- import_errors17.ErrorCode.NODE_INFO_CACHE_EMPTY,
4838
+ throw new import_errors18.FuelError(
4839
+ import_errors18.ErrorCode.NODE_INFO_CACHE_EMPTY,
4730
4840
  "Node info cache is empty. Make sure you have called `Provider.create` to initialize the provider."
4731
4841
  );
4732
4842
  }
@@ -4767,16 +4877,19 @@ var _Provider = class {
4767
4877
  }
4768
4878
  /**
4769
4879
  * Return the chain and node information.
4770
- *
4880
+ * @param ignoreCache - If true, ignores the cache and re-fetch configs.
4771
4881
  * @returns A promise that resolves to the Chain and NodeInfo.
4772
4882
  */
4773
- async fetchChainAndNodeInfo() {
4883
+ async fetchChainAndNodeInfo(ignoreCache = false) {
4774
4884
  let nodeInfo;
4775
4885
  let chain;
4776
4886
  try {
4887
+ if (ignoreCache) {
4888
+ throw new Error(`Jumps to the catch block andre-fetch`);
4889
+ }
4777
4890
  nodeInfo = this.getNode();
4778
4891
  chain = this.getChain();
4779
- } catch (error) {
4892
+ } catch (_err) {
4780
4893
  const data = await this.operations.getChainAndNodeInfo();
4781
4894
  nodeInfo = {
4782
4895
  maxDepth: (0, import_math18.bn)(data.nodeInfo.maxDepth),
@@ -4789,6 +4902,7 @@ var _Provider = class {
4789
4902
  chain = processGqlChain(data.chain);
4790
4903
  _Provider.chainInfoCache[this.urlWithoutAuth] = chain;
4791
4904
  _Provider.nodeInfoCache[this.urlWithoutAuth] = nodeInfo;
4905
+ this.consensusParametersTimestamp = Date.now();
4792
4906
  }
4793
4907
  return {
4794
4908
  chain,
@@ -4938,18 +5052,25 @@ Supported fuel-core version: ${supportedVersion}.`
4938
5052
  } = this.getChain();
4939
5053
  return baseAssetId;
4940
5054
  }
4941
- validateTransaction(tx, consensusParameters) {
4942
- const { maxOutputs, maxInputs } = consensusParameters.txParameters;
5055
+ /**
5056
+ * @hidden
5057
+ */
5058
+ validateTransaction(tx) {
5059
+ const {
5060
+ consensusParameters: {
5061
+ txParameters: { maxInputs, maxOutputs }
5062
+ }
5063
+ } = this.getChain();
4943
5064
  if ((0, import_math18.bn)(tx.inputs.length).gt(maxInputs)) {
4944
- throw new import_errors17.FuelError(
4945
- import_errors17.ErrorCode.MAX_INPUTS_EXCEEDED,
4946
- "The transaction exceeds the maximum allowed number of inputs."
5065
+ throw new import_errors18.FuelError(
5066
+ import_errors18.ErrorCode.MAX_INPUTS_EXCEEDED,
5067
+ `The transaction exceeds the maximum allowed number of inputs. Tx inputs: ${tx.inputs.length}, max inputs: ${maxInputs}`
4947
5068
  );
4948
5069
  }
4949
5070
  if ((0, import_math18.bn)(tx.outputs.length).gt(maxOutputs)) {
4950
- throw new import_errors17.FuelError(
4951
- import_errors17.ErrorCode.MAX_OUTPUTS_EXCEEDED,
4952
- "The transaction exceeds the maximum allowed number of outputs."
5071
+ throw new import_errors18.FuelError(
5072
+ import_errors18.ErrorCode.MAX_OUTPUTS_EXCEEDED,
5073
+ `The transaction exceeds the maximum allowed number of outputs. Tx outputs: ${tx.outputs.length}, max outputs: ${maxOutputs}`
4953
5074
  );
4954
5075
  }
4955
5076
  }
@@ -4968,8 +5089,7 @@ Supported fuel-core version: ${supportedVersion}.`
4968
5089
  if (estimateTxDependencies) {
4969
5090
  await this.estimateTxDependencies(transactionRequest);
4970
5091
  }
4971
- const { consensusParameters } = this.getChain();
4972
- this.validateTransaction(transactionRequest, consensusParameters);
5092
+ this.validateTransaction(transactionRequest);
4973
5093
  const encodedTransaction = (0, import_utils28.hexlify)(transactionRequest.toTransactionBytes());
4974
5094
  let abis;
4975
5095
  if (isTransactionTypeScript(transactionRequest)) {
@@ -5057,6 +5177,7 @@ Supported fuel-core version: ${supportedVersion}.`
5057
5177
  const missingContractIds = [];
5058
5178
  let outputVariables = 0;
5059
5179
  let dryRunStatus;
5180
+ this.validateTransaction(transactionRequest);
5060
5181
  for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
5061
5182
  const {
5062
5183
  dryRun: [{ receipts: rawReceipts, status }]
@@ -5179,6 +5300,27 @@ Supported fuel-core version: ${supportedVersion}.`
5179
5300
  });
5180
5301
  return results;
5181
5302
  }
5303
+ async autoRefetchConfigs() {
5304
+ const now = Date.now();
5305
+ const diff = now - (this.consensusParametersTimestamp ?? 0);
5306
+ if (diff < 6e4) {
5307
+ return;
5308
+ }
5309
+ const chainInfo = this.getChain();
5310
+ const {
5311
+ consensusParameters: { version: previous }
5312
+ } = chainInfo;
5313
+ const {
5314
+ chain: {
5315
+ latestBlock: {
5316
+ header: { consensusParametersVersion: current }
5317
+ }
5318
+ }
5319
+ } = await this.operations.getConsensusParametersVersion();
5320
+ if (previous !== current) {
5321
+ await this.fetchChainAndNodeInfo(true);
5322
+ }
5323
+ }
5182
5324
  /**
5183
5325
  * Estimates the transaction gas and fee based on the provided transaction request.
5184
5326
  * @param transactionRequest - The transaction request object.
@@ -5187,6 +5329,7 @@ Supported fuel-core version: ${supportedVersion}.`
5187
5329
  async estimateTxGasAndFee(params) {
5188
5330
  const { transactionRequest } = params;
5189
5331
  let { gasPrice } = params;
5332
+ await this.autoRefetchConfigs();
5190
5333
  const chainInfo = this.getChain();
5191
5334
  const { gasPriceFactor, maxGasPerTx } = this.getGasConfig();
5192
5335
  const minGas = transactionRequest.calculateMinGas(chainInfo);
@@ -5300,7 +5443,9 @@ Supported fuel-core version: ${supportedVersion}.`
5300
5443
  if (dryRunStatus && "reason" in dryRunStatus) {
5301
5444
  throw this.extractDryRunError(txRequestClone, receipts, dryRunStatus);
5302
5445
  }
5303
- gasUsed = getGasUsedFromReceipts(receipts);
5446
+ const { maxGasPerTx } = this.getGasConfig();
5447
+ const pristineGasUsed = getGasUsedFromReceipts(receipts);
5448
+ gasUsed = (0, import_math18.bn)(pristineGasUsed.muln(GAS_USED_MODIFIER)).max(maxGasPerTx.sub(minGas));
5304
5449
  txRequestClone.gasLimit = gasUsed;
5305
5450
  ({ maxFee, maxGas, minFee, minGas, gasPrice } = await this.estimateTxGasAndFee({
5306
5451
  transactionRequest: txRequestClone,
@@ -5337,7 +5482,7 @@ Supported fuel-core version: ${supportedVersion}.`
5337
5482
  const {
5338
5483
  coins: { edges, pageInfo }
5339
5484
  } = await this.operations.getCoins({
5340
- ...this.validatePaginationArgs({
5485
+ ...validatePaginationArgs({
5341
5486
  paginationLimit: RESOURCES_PAGE_SIZE_LIMIT,
5342
5487
  inputArgs: paginationArgs
5343
5488
  }),
@@ -5347,7 +5492,7 @@ Supported fuel-core version: ${supportedVersion}.`
5347
5492
  id: node.utxoId,
5348
5493
  assetId: node.assetId,
5349
5494
  amount: (0, import_math18.bn)(node.amount),
5350
- owner: import_address3.Address.fromAddressOrString(node.owner),
5495
+ owner: ownerAddress,
5351
5496
  blockCreated: (0, import_math18.bn)(node.blockCreated),
5352
5497
  txCreatedIdx: (0, import_math18.bn)(node.txCreatedIdx)
5353
5498
  }));
@@ -5401,7 +5546,7 @@ Supported fuel-core version: ${supportedVersion}.`
5401
5546
  id: coin.utxoId,
5402
5547
  amount: (0, import_math18.bn)(coin.amount),
5403
5548
  assetId: coin.assetId,
5404
- owner: import_address3.Address.fromAddressOrString(coin.owner),
5549
+ owner: ownerAddress,
5405
5550
  blockCreated: (0, import_math18.bn)(coin.blockCreated),
5406
5551
  txCreatedIdx: (0, import_math18.bn)(coin.txCreatedIdx)
5407
5552
  };
@@ -5476,7 +5621,7 @@ Supported fuel-core version: ${supportedVersion}.`
5476
5621
  const {
5477
5622
  blocks: { edges, pageInfo }
5478
5623
  } = await this.operations.getBlocks({
5479
- ...this.validatePaginationArgs({
5624
+ ...validatePaginationArgs({
5480
5625
  paginationLimit: BLOCKS_PAGE_SIZE_LIMIT,
5481
5626
  inputArgs: params
5482
5627
  })
@@ -5555,7 +5700,7 @@ Supported fuel-core version: ${supportedVersion}.`
5555
5700
  0
5556
5701
  )?.[0];
5557
5702
  } catch (error) {
5558
- if (error instanceof import_errors17.FuelError && error.code === import_errors17.ErrorCode.UNSUPPORTED_TRANSACTION_TYPE) {
5703
+ if (error instanceof import_errors18.FuelError && error.code === import_errors18.ErrorCode.UNSUPPORTED_TRANSACTION_TYPE) {
5559
5704
  console.warn("Unsupported transaction type encountered");
5560
5705
  return null;
5561
5706
  }
@@ -5571,7 +5716,7 @@ Supported fuel-core version: ${supportedVersion}.`
5571
5716
  const {
5572
5717
  transactions: { edges, pageInfo }
5573
5718
  } = await this.operations.getTransactions({
5574
- ...this.validatePaginationArgs({
5719
+ ...validatePaginationArgs({
5575
5720
  inputArgs: paginationArgs,
5576
5721
  paginationLimit: TRANSACTIONS_PAGE_SIZE_LIMIT
5577
5722
  })
@@ -5581,7 +5726,7 @@ Supported fuel-core version: ${supportedVersion}.`
5581
5726
  try {
5582
5727
  return coder.decode((0, import_utils28.arrayify)(rawPayload), 0)[0];
5583
5728
  } catch (error) {
5584
- if (error instanceof import_errors17.FuelError && error.code === import_errors17.ErrorCode.UNSUPPORTED_TRANSACTION_TYPE) {
5729
+ if (error instanceof import_errors18.FuelError && error.code === import_errors18.ErrorCode.UNSUPPORTED_TRANSACTION_TYPE) {
5585
5730
  console.warn("Unsupported transaction type encountered");
5586
5731
  return null;
5587
5732
  }
@@ -5666,7 +5811,7 @@ Supported fuel-core version: ${supportedVersion}.`
5666
5811
  const {
5667
5812
  messages: { edges, pageInfo }
5668
5813
  } = await this.operations.getMessages({
5669
- ...this.validatePaginationArgs({
5814
+ ...validatePaginationArgs({
5670
5815
  inputArgs: paginationArgs,
5671
5816
  paginationLimit: RESOURCES_PAGE_SIZE_LIMIT
5672
5817
  }),
@@ -5707,8 +5852,8 @@ Supported fuel-core version: ${supportedVersion}.`
5707
5852
  nonce
5708
5853
  };
5709
5854
  if (commitBlockId && commitBlockHeight) {
5710
- throw new import_errors17.FuelError(
5711
- import_errors17.ErrorCode.INVALID_INPUT_PARAMETERS,
5855
+ throw new import_errors18.FuelError(
5856
+ import_errors18.ErrorCode.INVALID_INPUT_PARAMETERS,
5712
5857
  "commitBlockId and commitBlockHeight cannot be used together"
5713
5858
  );
5714
5859
  }
@@ -5890,13 +6035,13 @@ Supported fuel-core version: ${supportedVersion}.`
5890
6035
  messageId: import_transactions22.InputMessageCoder.getMessageId({
5891
6036
  sender: rawMessage.sender,
5892
6037
  recipient: rawMessage.recipient,
5893
- nonce: rawMessage.nonce,
6038
+ nonce,
5894
6039
  amount: (0, import_math18.bn)(rawMessage.amount),
5895
6040
  data: rawMessage.data
5896
6041
  }),
5897
6042
  sender: import_address3.Address.fromAddressOrString(rawMessage.sender),
5898
6043
  recipient: import_address3.Address.fromAddressOrString(rawMessage.recipient),
5899
- nonce: rawMessage.nonce,
6044
+ nonce,
5900
6045
  amount: (0, import_math18.bn)(rawMessage.amount),
5901
6046
  data: import_transactions22.InputMessageCoder.decodeData(rawMessage.data),
5902
6047
  daHeight: (0, import_math18.bn)(rawMessage.daHeight)
@@ -5918,41 +6063,6 @@ Supported fuel-core version: ${supportedVersion}.`
5918
6063
  }
5919
6064
  return relayedTransactionStatus;
5920
6065
  }
5921
- /**
5922
- * @hidden
5923
- */
5924
- validatePaginationArgs(params) {
5925
- const { paginationLimit, inputArgs = {} } = params;
5926
- const { first, last, after, before } = inputArgs;
5927
- if (after && before) {
5928
- throw new import_errors17.FuelError(
5929
- import_errors17.ErrorCode.INVALID_INPUT_PARAMETERS,
5930
- 'Pagination arguments "after" and "before" cannot be used together'
5931
- );
5932
- }
5933
- if ((first || 0) > paginationLimit || (last || 0) > paginationLimit) {
5934
- throw new import_errors17.FuelError(
5935
- import_errors17.ErrorCode.INVALID_INPUT_PARAMETERS,
5936
- `Pagination limit for this query cannot exceed ${paginationLimit} items`
5937
- );
5938
- }
5939
- if (first && before) {
5940
- throw new import_errors17.FuelError(
5941
- import_errors17.ErrorCode.INVALID_INPUT_PARAMETERS,
5942
- 'The use of pagination argument "first" with "before" is not supported'
5943
- );
5944
- }
5945
- if (last && after) {
5946
- throw new import_errors17.FuelError(
5947
- import_errors17.ErrorCode.INVALID_INPUT_PARAMETERS,
5948
- 'The use of pagination argument "last" with "after" is not supported'
5949
- );
5950
- }
5951
- if (!first && !last) {
5952
- inputArgs.first = paginationLimit;
5953
- }
5954
- return inputArgs;
5955
- }
5956
6066
  /**
5957
6067
  * @hidden
5958
6068
  */
@@ -5998,7 +6108,7 @@ __publicField(Provider, "chainInfoCache", {});
5998
6108
  __publicField(Provider, "nodeInfoCache", {});
5999
6109
 
6000
6110
  // src/providers/transaction-summary/get-transaction-summary.ts
6001
- var import_errors18 = require("@fuel-ts/errors");
6111
+ var import_errors19 = require("@fuel-ts/errors");
6002
6112
  var import_math19 = require("@fuel-ts/math");
6003
6113
  var import_transactions23 = require("@fuel-ts/transactions");
6004
6114
  var import_utils31 = require("@fuel-ts/utils");
@@ -6008,8 +6118,8 @@ async function getTransactionSummary(params) {
6008
6118
  transactionId: id
6009
6119
  });
6010
6120
  if (!gqlTransaction) {
6011
- throw new import_errors18.FuelError(
6012
- import_errors18.ErrorCode.TRANSACTION_NOT_FOUND,
6121
+ throw new import_errors19.FuelError(
6122
+ import_errors19.ErrorCode.TRANSACTION_NOT_FOUND,
6013
6123
  `Transaction not found for given id: ${id}.`
6014
6124
  );
6015
6125
  }
@@ -6077,7 +6187,15 @@ async function getTransactionSummaryFromRequest(params) {
6077
6187
  }
6078
6188
  async function getTransactionsSummaries(params) {
6079
6189
  const { filters, provider, abiMap } = params;
6080
- const { transactionsByOwner } = await provider.operations.getTransactionsByOwner(filters);
6190
+ const { owner, ...inputArgs } = filters;
6191
+ const validPaginationParams = validatePaginationArgs({
6192
+ inputArgs,
6193
+ paginationLimit: TRANSACTIONS_PAGE_SIZE_LIMIT
6194
+ });
6195
+ const { transactionsByOwner } = await provider.operations.getTransactionsByOwner({
6196
+ ...validPaginationParams,
6197
+ owner
6198
+ });
6081
6199
  const { edges, pageInfo } = transactionsByOwner;
6082
6200
  const {
6083
6201
  consensusParameters: {
@@ -6797,37 +6915,46 @@ var mergeQuantities = (...coinQuantities) => {
6797
6915
 
6798
6916
  // src/utils/formatTransferToContractScriptData.ts
6799
6917
  var import_abi_coder6 = require("@fuel-ts/abi-coder");
6918
+ var import_address4 = require("@fuel-ts/address");
6800
6919
  var import_math20 = require("@fuel-ts/math");
6801
6920
  var import_utils33 = require("@fuel-ts/utils");
6802
6921
  var asm = __toESM(require("@fuels/vm-asm"));
6803
- var formatTransferToContractScriptData = (params) => {
6804
- const { assetId, amountToTransfer, hexlifiedContractId } = params;
6922
+ var formatTransferToContractScriptData = (transferParams) => {
6805
6923
  const numberCoder = new import_abi_coder6.BigNumberCoder("u64");
6806
- const encoded = numberCoder.encode(new import_math20.BN(amountToTransfer).toNumber());
6807
- const scriptData = Uint8Array.from([
6808
- ...(0, import_utils33.arrayify)(hexlifiedContractId),
6809
- ...encoded,
6810
- ...(0, import_utils33.arrayify)(assetId)
6811
- ]);
6812
- return scriptData;
6924
+ return transferParams.reduce((acc, transferParam) => {
6925
+ const { assetId, amount, contractId } = transferParam;
6926
+ const encoded = numberCoder.encode(new import_math20.BN(amount).toNumber());
6927
+ const scriptData = (0, import_utils33.concat)([
6928
+ import_address4.Address.fromAddressOrString(contractId).toBytes(),
6929
+ encoded,
6930
+ (0, import_utils33.arrayify)(assetId)
6931
+ ]);
6932
+ return (0, import_utils33.concat)([acc, scriptData]);
6933
+ }, new Uint8Array());
6813
6934
  };
6814
- var assembleTransferToContractScript = async (params) => {
6815
- const scriptData = formatTransferToContractScriptData(params);
6935
+ var assembleTransferToContractScript = async (transferParams) => {
6936
+ const scriptData = formatTransferToContractScriptData(transferParams);
6816
6937
  await asm.initWasm();
6817
- const gtf2 = asm.gtf(16, 0, asm.GTFArgs.ScriptData);
6818
- const addi2 = asm.addi(17, 16, 32);
6819
- const lw2 = asm.lw(18, 17, 0);
6820
- const addi22 = asm.addi(19, 17, 8);
6821
- const tr2 = asm.tr(16, 18, 19);
6822
- const ret2 = asm.ret(1);
6823
- const script = Uint8Array.from([
6824
- ...gtf2.to_bytes(),
6825
- ...addi2.to_bytes(),
6826
- ...lw2.to_bytes(),
6827
- ...addi22.to_bytes(),
6828
- ...tr2.to_bytes(),
6829
- ...ret2.to_bytes()
6830
- ]);
6938
+ let script = new Uint8Array();
6939
+ transferParams.forEach((_, i) => {
6940
+ const offset = (import_abi_coder6.CONTRACT_ID_LEN + import_abi_coder6.WORD_SIZE + import_abi_coder6.ASSET_ID_LEN) * i;
6941
+ script = (0, import_utils33.concat)([
6942
+ script,
6943
+ // Load ScriptData into register 0x10.
6944
+ asm.gtf(16, 0, asm.GTFArgs.ScriptData).to_bytes(),
6945
+ // Add the offset to 0x10 so it will point to the current contract ID, store in 0x11.
6946
+ asm.addi(17, 16, offset).to_bytes(),
6947
+ // Add CONTRACT_ID_LEN to 0x11 to point to the amount in the ScriptData, store in 0x12.
6948
+ asm.addi(18, 17, import_abi_coder6.CONTRACT_ID_LEN).to_bytes(),
6949
+ // Load word to the amount at 0x12 into register 0x13.
6950
+ asm.lw(19, 18, 0).to_bytes(),
6951
+ // Add WORD_SIZE to 0x12 to point to the asset ID in the ScriptData, store in 0x14.
6952
+ asm.addi(20, 18, import_abi_coder6.WORD_SIZE).to_bytes(),
6953
+ // Perform the transfer using contract ID in 0x11, amount in 0x13, and asset ID in 0x14.
6954
+ asm.tr(17, 19, 20).to_bytes()
6955
+ ]);
6956
+ });
6957
+ script = (0, import_utils33.concat)([script, asm.ret(1).to_bytes()]);
6831
6958
  return { script, scriptData };
6832
6959
  };
6833
6960
 
@@ -6857,7 +6984,7 @@ var Account = class extends import_interfaces.AbstractAccount {
6857
6984
  super();
6858
6985
  this._provider = provider;
6859
6986
  this._connector = connector;
6860
- this.address = import_address4.Address.fromDynamicInput(address);
6987
+ this.address = import_address5.Address.fromDynamicInput(address);
6861
6988
  }
6862
6989
  /**
6863
6990
  * The provider used to interact with the network.
@@ -6868,7 +6995,7 @@ var Account = class extends import_interfaces.AbstractAccount {
6868
6995
  */
6869
6996
  get provider() {
6870
6997
  if (!this._provider) {
6871
- throw new import_errors19.FuelError(import_errors19.ErrorCode.MISSING_PROVIDER, "Provider not set");
6998
+ throw new import_errors20.FuelError(import_errors20.ErrorCode.MISSING_PROVIDER, "Provider not set");
6872
6999
  }
6873
7000
  return this._provider;
6874
7001
  }
@@ -7019,11 +7146,12 @@ var Account = class extends import_interfaces.AbstractAccount {
7019
7146
  fundingAttempts += 1;
7020
7147
  }
7021
7148
  if (needsToBeFunded) {
7022
- throw new import_errors19.FuelError(
7023
- import_errors19.ErrorCode.NOT_ENOUGH_FUNDS,
7149
+ throw new import_errors20.FuelError(
7150
+ import_errors20.ErrorCode.NOT_ENOUGH_FUNDS,
7024
7151
  `The account ${this.address} does not have enough base asset funds to cover the transaction execution.`
7025
7152
  );
7026
7153
  }
7154
+ this.provider.validateTransaction(request);
7027
7155
  request.updatePredicateGasUsed(estimatedPredicates);
7028
7156
  const requestToReestimate = (0, import_ramda9.clone)(request);
7029
7157
  if (addedSignatures) {
@@ -7090,7 +7218,7 @@ var Account = class extends import_interfaces.AbstractAccount {
7090
7218
  const { destination, amount, assetId } = transferParams;
7091
7219
  this.validateTransferAmount(amount);
7092
7220
  request.addCoinOutput(
7093
- import_address4.Address.fromAddressOrString(destination),
7221
+ import_address5.Address.fromAddressOrString(destination),
7094
7222
  amount,
7095
7223
  assetId ?? this.provider.getBaseAssetId()
7096
7224
  );
@@ -7124,35 +7252,35 @@ var Account = class extends import_interfaces.AbstractAccount {
7124
7252
  * @returns A promise that resolves to the transaction response.
7125
7253
  */
7126
7254
  async transferToContract(contractId, amount, assetId, txParams = {}) {
7127
- if ((0, import_math21.bn)(amount).lte(0)) {
7128
- throw new import_errors19.FuelError(
7129
- import_errors19.ErrorCode.INVALID_TRANSFER_AMOUNT,
7130
- "Transfer amount must be a positive number."
7131
- );
7132
- }
7133
- const contractAddress = import_address4.Address.fromAddressOrString(contractId);
7134
- const assetIdToTransfer = assetId ?? this.provider.getBaseAssetId();
7135
- const { script, scriptData } = await assembleTransferToContractScript({
7136
- hexlifiedContractId: contractAddress.toB256(),
7137
- amountToTransfer: (0, import_math21.bn)(amount),
7138
- assetId: assetIdToTransfer
7139
- });
7255
+ return this.batchTransferToContracts([{ amount, assetId, contractId }], txParams);
7256
+ }
7257
+ async batchTransferToContracts(contractTransferParams, txParams = {}) {
7140
7258
  let request = new ScriptTransactionRequest({
7141
- ...txParams,
7142
- script,
7143
- scriptData
7259
+ ...txParams
7144
7260
  });
7145
- request.addContractInputAndOutput(contractAddress);
7146
- const txCost = await this.getTransactionCost(request, {
7147
- quantities: [{ amount: (0, import_math21.bn)(amount), assetId: String(assetIdToTransfer) }]
7148
- });
7149
- request = this.validateGasLimitAndMaxFee({
7150
- transactionRequest: request,
7151
- gasUsed: txCost.gasUsed,
7152
- maxFee: txCost.maxFee,
7153
- txParams
7261
+ const quantities = [];
7262
+ const transferParams = contractTransferParams.map((transferParam) => {
7263
+ const amount = (0, import_math21.bn)(transferParam.amount);
7264
+ const contractAddress = import_address5.Address.fromAddressOrString(transferParam.contractId);
7265
+ const assetId = transferParam.assetId ? (0, import_utils34.hexlify)(transferParam.assetId) : this.provider.getBaseAssetId();
7266
+ if (amount.lte(0)) {
7267
+ throw new import_errors20.FuelError(
7268
+ import_errors20.ErrorCode.INVALID_TRANSFER_AMOUNT,
7269
+ "Transfer amount must be a positive number."
7270
+ );
7271
+ }
7272
+ request.addContractInputAndOutput(contractAddress);
7273
+ quantities.push({ amount, assetId });
7274
+ return {
7275
+ amount,
7276
+ contractId: contractAddress.toB256(),
7277
+ assetId
7278
+ };
7154
7279
  });
7155
- await this.fund(request, txCost);
7280
+ const { script, scriptData } = await assembleTransferToContractScript(transferParams);
7281
+ request.script = script;
7282
+ request.scriptData = scriptData;
7283
+ request = await this.estimateAndFundTransaction(request, txParams, { quantities });
7156
7284
  return this.sendTransaction(request);
7157
7285
  }
7158
7286
  /**
@@ -7164,7 +7292,7 @@ var Account = class extends import_interfaces.AbstractAccount {
7164
7292
  * @returns A promise that resolves to the transaction response.
7165
7293
  */
7166
7294
  async withdrawToBaseLayer(recipient, amount, txParams = {}) {
7167
- const recipientAddress = import_address4.Address.fromAddressOrString(recipient);
7295
+ const recipientAddress = import_address5.Address.fromAddressOrString(recipient);
7168
7296
  const recipientDataArray = (0, import_utils34.arrayify)(
7169
7297
  "0x".concat(recipientAddress.toHexString().substring(2).padStart(64, "0"))
7170
7298
  );
@@ -7252,7 +7380,7 @@ var Account = class extends import_interfaces.AbstractAccount {
7252
7380
  */
7253
7381
  async signMessage(message) {
7254
7382
  if (!this._connector) {
7255
- throw new import_errors19.FuelError(import_errors19.ErrorCode.MISSING_CONNECTOR, "A connector is required to sign messages.");
7383
+ throw new import_errors20.FuelError(import_errors20.ErrorCode.MISSING_CONNECTOR, "A connector is required to sign messages.");
7256
7384
  }
7257
7385
  return this._connector.signMessage(this.address.toString(), message);
7258
7386
  }
@@ -7264,8 +7392,8 @@ var Account = class extends import_interfaces.AbstractAccount {
7264
7392
  */
7265
7393
  async signTransaction(transactionRequestLike) {
7266
7394
  if (!this._connector) {
7267
- throw new import_errors19.FuelError(
7268
- import_errors19.ErrorCode.MISSING_CONNECTOR,
7395
+ throw new import_errors20.FuelError(
7396
+ import_errors20.ErrorCode.MISSING_CONNECTOR,
7269
7397
  "A connector is required to sign transactions."
7270
7398
  );
7271
7399
  }
@@ -7324,16 +7452,16 @@ var Account = class extends import_interfaces.AbstractAccount {
7324
7452
  /** @hidden * */
7325
7453
  validateTransferAmount(amount) {
7326
7454
  if ((0, import_math21.bn)(amount).lte(0)) {
7327
- throw new import_errors19.FuelError(
7328
- import_errors19.ErrorCode.INVALID_TRANSFER_AMOUNT,
7455
+ throw new import_errors20.FuelError(
7456
+ import_errors20.ErrorCode.INVALID_TRANSFER_AMOUNT,
7329
7457
  "Transfer amount must be a positive number."
7330
7458
  );
7331
7459
  }
7332
7460
  }
7333
7461
  /** @hidden * */
7334
- async estimateAndFundTransaction(transactionRequest, txParams) {
7462
+ async estimateAndFundTransaction(transactionRequest, txParams, costParams) {
7335
7463
  let request = transactionRequest;
7336
- const txCost = await this.getTransactionCost(request);
7464
+ const txCost = await this.getTransactionCost(request, costParams);
7337
7465
  request = this.validateGasLimitAndMaxFee({
7338
7466
  transactionRequest: request,
7339
7467
  gasUsed: txCost.gasUsed,
@@ -7354,16 +7482,16 @@ var Account = class extends import_interfaces.AbstractAccount {
7354
7482
  if (!(0, import_utils34.isDefined)(setGasLimit)) {
7355
7483
  request.gasLimit = gasUsed;
7356
7484
  } else if (gasUsed.gt(setGasLimit)) {
7357
- throw new import_errors19.FuelError(
7358
- import_errors19.ErrorCode.GAS_LIMIT_TOO_LOW,
7485
+ throw new import_errors20.FuelError(
7486
+ import_errors20.ErrorCode.GAS_LIMIT_TOO_LOW,
7359
7487
  `Gas limit '${setGasLimit}' is lower than the required: '${gasUsed}'.`
7360
7488
  );
7361
7489
  }
7362
7490
  if (!(0, import_utils34.isDefined)(setMaxFee)) {
7363
7491
  request.maxFee = maxFee;
7364
7492
  } else if (maxFee.gt(setMaxFee)) {
7365
- throw new import_errors19.FuelError(
7366
- import_errors19.ErrorCode.MAX_FEE_TOO_LOW,
7493
+ throw new import_errors20.FuelError(
7494
+ import_errors20.ErrorCode.MAX_FEE_TOO_LOW,
7367
7495
  `Max fee '${setMaxFee}' is lower than the required: '${maxFee}'.`
7368
7496
  );
7369
7497
  }
@@ -7376,7 +7504,7 @@ var import_hasher4 = require("@fuel-ts/hasher");
7376
7504
  var import_utils37 = require("@fuel-ts/utils");
7377
7505
 
7378
7506
  // src/signer/signer.ts
7379
- var import_address5 = require("@fuel-ts/address");
7507
+ var import_address6 = require("@fuel-ts/address");
7380
7508
  var import_crypto3 = require("@fuel-ts/crypto");
7381
7509
  var import_hasher3 = require("@fuel-ts/hasher");
7382
7510
  var import_math22 = require("@fuel-ts/math");
@@ -7403,7 +7531,7 @@ var Signer = class {
7403
7531
  this.privateKey = (0, import_utils35.hexlify)(privateKeyBytes);
7404
7532
  this.publicKey = (0, import_utils35.hexlify)(import_secp256k1.secp256k1.getPublicKey(privateKeyBytes, false).slice(1));
7405
7533
  this.compressedPublicKey = (0, import_utils35.hexlify)(import_secp256k1.secp256k1.getPublicKey(privateKeyBytes, true));
7406
- this.address = import_address5.Address.fromPublicKey(this.publicKey);
7534
+ this.address = import_address6.Address.fromPublicKey(this.publicKey);
7407
7535
  }
7408
7536
  /**
7409
7537
  * Sign data using the Signer instance
@@ -7461,7 +7589,7 @@ var Signer = class {
7461
7589
  * @returns Address from signature
7462
7590
  */
7463
7591
  static recoverAddress(data, signature) {
7464
- return import_address5.Address.fromPublicKey(Signer.recoverPublicKey(data, signature));
7592
+ return import_address6.Address.fromPublicKey(Signer.recoverPublicKey(data, signature));
7465
7593
  }
7466
7594
  /**
7467
7595
  * Generate a random privateKey
@@ -7485,9 +7613,9 @@ var Signer = class {
7485
7613
  };
7486
7614
 
7487
7615
  // src/wallet/keystore-wallet.ts
7488
- var import_address6 = require("@fuel-ts/address");
7616
+ var import_address7 = require("@fuel-ts/address");
7489
7617
  var import_crypto4 = require("@fuel-ts/crypto");
7490
- var import_errors20 = require("@fuel-ts/errors");
7618
+ var import_errors21 = require("@fuel-ts/errors");
7491
7619
  var import_utils36 = require("@fuel-ts/utils");
7492
7620
  var DEFAULT_KDF_PARAMS_LOG_N = 13;
7493
7621
  var DEFAULT_KDF_PARAMS_R = 8;
@@ -7502,7 +7630,7 @@ var removeHexPrefix = (hexString) => {
7502
7630
  };
7503
7631
  async function encryptKeystoreWallet(privateKey, address, password) {
7504
7632
  const privateKeyBuffer = (0, import_crypto4.bufferFromString)(removeHexPrefix(privateKey), "hex");
7505
- const ownerAddress = import_address6.Address.fromAddressOrString(address);
7633
+ const ownerAddress = import_address7.Address.fromAddressOrString(address);
7506
7634
  const salt = (0, import_crypto4.randomBytes)(DEFAULT_KEY_SIZE);
7507
7635
  const key = (0, import_crypto4.scrypt)({
7508
7636
  password: (0, import_crypto4.bufferFromString)(password),
@@ -7564,8 +7692,8 @@ async function decryptKeystoreWallet(jsonWallet, password) {
7564
7692
  const macHashUint8Array = (0, import_crypto4.keccak256)(data);
7565
7693
  const macHash = (0, import_crypto4.stringFromBuffer)(macHashUint8Array, "hex");
7566
7694
  if (mac !== macHash) {
7567
- throw new import_errors20.FuelError(
7568
- import_errors20.ErrorCode.INVALID_PASSWORD,
7695
+ throw new import_errors21.FuelError(
7696
+ import_errors21.ErrorCode.INVALID_PASSWORD,
7569
7697
  "Failed to decrypt the keystore wallet, the provided password is incorrect."
7570
7698
  );
7571
7699
  }
@@ -7695,14 +7823,14 @@ __publicField(BaseWalletUnlocked, "defaultPath", "m/44'/1179993420'/0'/0/0");
7695
7823
 
7696
7824
  // src/hdwallet/hdwallet.ts
7697
7825
  var import_crypto6 = require("@fuel-ts/crypto");
7698
- var import_errors23 = require("@fuel-ts/errors");
7826
+ var import_errors24 = require("@fuel-ts/errors");
7699
7827
  var import_hasher7 = require("@fuel-ts/hasher");
7700
7828
  var import_math23 = require("@fuel-ts/math");
7701
7829
  var import_utils41 = require("@fuel-ts/utils");
7702
7830
 
7703
7831
  // src/mnemonic/mnemonic.ts
7704
7832
  var import_crypto5 = require("@fuel-ts/crypto");
7705
- var import_errors22 = require("@fuel-ts/errors");
7833
+ var import_errors23 = require("@fuel-ts/errors");
7706
7834
  var import_hasher6 = require("@fuel-ts/hasher");
7707
7835
  var import_utils39 = require("@fuel-ts/utils");
7708
7836
 
@@ -9765,7 +9893,7 @@ var Language = /* @__PURE__ */ ((Language2) => {
9765
9893
  })(Language || {});
9766
9894
 
9767
9895
  // src/mnemonic/utils.ts
9768
- var import_errors21 = require("@fuel-ts/errors");
9896
+ var import_errors22 = require("@fuel-ts/errors");
9769
9897
  var import_hasher5 = require("@fuel-ts/hasher");
9770
9898
  var import_utils38 = require("@fuel-ts/utils");
9771
9899
  function getLowerMask(bits) {
@@ -9814,8 +9942,8 @@ function mnemonicWordsToEntropy(words, wordlist) {
9814
9942
  for (let i = 0; i < words.length; i += 1) {
9815
9943
  const index = wordlist.indexOf(words[i].normalize("NFKD"));
9816
9944
  if (index === -1) {
9817
- throw new import_errors21.FuelError(
9818
- import_errors21.ErrorCode.INVALID_MNEMONIC,
9945
+ throw new import_errors22.FuelError(
9946
+ import_errors22.ErrorCode.INVALID_MNEMONIC,
9819
9947
  `Invalid mnemonic: the word '${words[i]}' is not found in the provided wordlist.`
9820
9948
  );
9821
9949
  }
@@ -9831,8 +9959,8 @@ function mnemonicWordsToEntropy(words, wordlist) {
9831
9959
  const checksumMask = getUpperMask(checksumBits);
9832
9960
  const checksum = (0, import_utils38.arrayify)((0, import_hasher5.sha256)(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
9833
9961
  if (checksum !== (entropy[entropy.length - 1] & checksumMask)) {
9834
- throw new import_errors21.FuelError(
9835
- import_errors21.ErrorCode.INVALID_CHECKSUM,
9962
+ throw new import_errors22.FuelError(
9963
+ import_errors22.ErrorCode.INVALID_CHECKSUM,
9836
9964
  "Checksum validation failed for the provided mnemonic."
9837
9965
  );
9838
9966
  }
@@ -9846,16 +9974,16 @@ var TestnetPRV = "0x04358394";
9846
9974
  var MNEMONIC_SIZES = [12, 15, 18, 21, 24];
9847
9975
  function assertWordList(wordlist) {
9848
9976
  if (wordlist.length !== 2048) {
9849
- throw new import_errors22.FuelError(
9850
- import_errors22.ErrorCode.INVALID_WORD_LIST,
9977
+ throw new import_errors23.FuelError(
9978
+ import_errors23.ErrorCode.INVALID_WORD_LIST,
9851
9979
  `Expected word list length of 2048, but got ${wordlist.length}.`
9852
9980
  );
9853
9981
  }
9854
9982
  }
9855
9983
  function assertEntropy(entropy) {
9856
9984
  if (entropy.length % 4 !== 0 || entropy.length < 16 || entropy.length > 32) {
9857
- throw new import_errors22.FuelError(
9858
- import_errors22.ErrorCode.INVALID_ENTROPY,
9985
+ throw new import_errors23.FuelError(
9986
+ import_errors23.ErrorCode.INVALID_ENTROPY,
9859
9987
  `Entropy should be between 16 and 32 bytes and a multiple of 4, but got ${entropy.length} bytes.`
9860
9988
  );
9861
9989
  }
@@ -9865,7 +9993,7 @@ function assertMnemonic(words) {
9865
9993
  const errorMsg = `Invalid mnemonic size. Expected one of [${MNEMONIC_SIZES.join(
9866
9994
  ", "
9867
9995
  )}] words, but got ${words.length}.`;
9868
- throw new import_errors22.FuelError(import_errors22.ErrorCode.INVALID_MNEMONIC, errorMsg);
9996
+ throw new import_errors23.FuelError(import_errors23.ErrorCode.INVALID_MNEMONIC, errorMsg);
9869
9997
  }
9870
9998
  }
9871
9999
  var Mnemonic = class {
@@ -9983,8 +10111,8 @@ var Mnemonic = class {
9983
10111
  static masterKeysFromSeed(seed) {
9984
10112
  const seedArray = (0, import_utils39.arrayify)(seed);
9985
10113
  if (seedArray.length < 16 || seedArray.length > 64) {
9986
- throw new import_errors22.FuelError(
9987
- import_errors22.ErrorCode.INVALID_SEED,
10114
+ throw new import_errors23.FuelError(
10115
+ import_errors23.ErrorCode.INVALID_SEED,
9988
10116
  `Seed length should be between 16 and 64 bytes, but received ${seedArray.length} bytes.`
9989
10117
  );
9990
10118
  }
@@ -10061,7 +10189,7 @@ function isValidExtendedKey(extendedKey) {
10061
10189
  function parsePath(path, depth = 0) {
10062
10190
  const components = path.split("/");
10063
10191
  if (components.length === 0 || components[0] === "m" && depth !== 0) {
10064
- throw new import_errors23.FuelError(import_errors23.ErrorCode.HD_WALLET_ERROR, `invalid path - ${path}`);
10192
+ throw new import_errors24.FuelError(import_errors24.ErrorCode.HD_WALLET_ERROR, `invalid path - ${path}`);
10065
10193
  }
10066
10194
  if (components[0] === "m") {
10067
10195
  components.shift();
@@ -10090,8 +10218,8 @@ var HDWallet = class {
10090
10218
  this.privateKey = (0, import_utils41.hexlify)(config.privateKey);
10091
10219
  } else {
10092
10220
  if (!config.publicKey) {
10093
- throw new import_errors23.FuelError(
10094
- import_errors23.ErrorCode.HD_WALLET_ERROR,
10221
+ throw new import_errors24.FuelError(
10222
+ import_errors24.ErrorCode.HD_WALLET_ERROR,
10095
10223
  "Both public and private Key cannot be missing. At least one should be provided."
10096
10224
  );
10097
10225
  }
@@ -10120,8 +10248,8 @@ var HDWallet = class {
10120
10248
  const data = new Uint8Array(37);
10121
10249
  if (index & HARDENED_INDEX) {
10122
10250
  if (!privateKey) {
10123
- throw new import_errors23.FuelError(
10124
- import_errors23.ErrorCode.HD_WALLET_ERROR,
10251
+ throw new import_errors24.FuelError(
10252
+ import_errors24.ErrorCode.HD_WALLET_ERROR,
10125
10253
  "Cannot derive a hardened index without a private Key."
10126
10254
  );
10127
10255
  }
@@ -10173,8 +10301,8 @@ var HDWallet = class {
10173
10301
  */
10174
10302
  toExtendedKey(isPublic = false, testnet = false) {
10175
10303
  if (this.depth >= 256) {
10176
- throw new import_errors23.FuelError(
10177
- import_errors23.ErrorCode.HD_WALLET_ERROR,
10304
+ throw new import_errors24.FuelError(
10305
+ import_errors24.ErrorCode.HD_WALLET_ERROR,
10178
10306
  `Exceeded max depth of 255. Current depth: ${this.depth}.`
10179
10307
  );
10180
10308
  }
@@ -10205,10 +10333,10 @@ var HDWallet = class {
10205
10333
  const bytes = (0, import_utils41.arrayify)(decoded);
10206
10334
  const validChecksum = base58check(bytes.slice(0, 78)) === extendedKey;
10207
10335
  if (bytes.length !== 82 || !isValidExtendedKey(bytes)) {
10208
- throw new import_errors23.FuelError(import_errors23.ErrorCode.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
10336
+ throw new import_errors24.FuelError(import_errors24.ErrorCode.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
10209
10337
  }
10210
10338
  if (!validChecksum) {
10211
- throw new import_errors23.FuelError(import_errors23.ErrorCode.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
10339
+ throw new import_errors24.FuelError(import_errors24.ErrorCode.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
10212
10340
  }
10213
10341
  const depth = bytes[4];
10214
10342
  const parentFingerprint = (0, import_utils41.hexlify)(bytes.slice(5, 9));
@@ -10216,14 +10344,14 @@ var HDWallet = class {
10216
10344
  const chainCode = (0, import_utils41.hexlify)(bytes.slice(13, 45));
10217
10345
  const key = bytes.slice(45, 78);
10218
10346
  if (depth === 0 && parentFingerprint !== "0x00000000" || depth === 0 && index !== 0) {
10219
- throw new import_errors23.FuelError(
10220
- import_errors23.ErrorCode.HD_WALLET_ERROR,
10347
+ throw new import_errors24.FuelError(
10348
+ import_errors24.ErrorCode.HD_WALLET_ERROR,
10221
10349
  "Inconsistency detected: Depth is zero but fingerprint/index is non-zero."
10222
10350
  );
10223
10351
  }
10224
10352
  if (isPublicExtendedKey(bytes)) {
10225
10353
  if (key[0] !== 3) {
10226
- throw new import_errors23.FuelError(import_errors23.ErrorCode.HD_WALLET_ERROR, "Invalid public extended key.");
10354
+ throw new import_errors24.FuelError(import_errors24.ErrorCode.HD_WALLET_ERROR, "Invalid public extended key.");
10227
10355
  }
10228
10356
  return new HDWallet({
10229
10357
  publicKey: key,
@@ -10234,7 +10362,7 @@ var HDWallet = class {
10234
10362
  });
10235
10363
  }
10236
10364
  if (key[0] !== 0) {
10237
- throw new import_errors23.FuelError(import_errors23.ErrorCode.HD_WALLET_ERROR, "Invalid private extended key.");
10365
+ throw new import_errors24.FuelError(import_errors24.ErrorCode.HD_WALLET_ERROR, "Invalid private extended key.");
10238
10366
  }
10239
10367
  return new HDWallet({
10240
10368
  privateKey: key.slice(1),
@@ -10400,9 +10528,9 @@ __publicField(Wallet, "fromExtendedKey", WalletUnlocked.fromExtendedKey);
10400
10528
  __publicField(Wallet, "fromEncryptedJson", WalletUnlocked.fromEncryptedJson);
10401
10529
 
10402
10530
  // src/wallet-manager/wallet-manager.ts
10403
- var import_address9 = require("@fuel-ts/address");
10531
+ var import_address10 = require("@fuel-ts/address");
10404
10532
  var import_crypto7 = require("@fuel-ts/crypto");
10405
- var import_errors26 = require("@fuel-ts/errors");
10533
+ var import_errors27 = require("@fuel-ts/errors");
10406
10534
  var import_events = require("events");
10407
10535
 
10408
10536
  // src/wallet-manager/storages/memory-storage.ts
@@ -10424,8 +10552,8 @@ var MemoryStorage = class {
10424
10552
  };
10425
10553
 
10426
10554
  // src/wallet-manager/vaults/mnemonic-vault.ts
10427
- var import_address7 = require("@fuel-ts/address");
10428
- var import_errors24 = require("@fuel-ts/errors");
10555
+ var import_address8 = require("@fuel-ts/address");
10556
+ var import_errors25 = require("@fuel-ts/errors");
10429
10557
  var _secret;
10430
10558
  var MnemonicVault = class {
10431
10559
  constructor(options) {
@@ -10473,7 +10601,7 @@ var MnemonicVault = class {
10473
10601
  }
10474
10602
  exportAccount(address) {
10475
10603
  let numberOfAccounts = 0;
10476
- const ownerAddress = import_address7.Address.fromAddressOrString(address);
10604
+ const ownerAddress = import_address8.Address.fromAddressOrString(address);
10477
10605
  do {
10478
10606
  const wallet = Wallet.fromMnemonic(__privateGet(this, _secret), this.getDerivePath(numberOfAccounts));
10479
10607
  if (wallet.address.equals(ownerAddress)) {
@@ -10481,8 +10609,8 @@ var MnemonicVault = class {
10481
10609
  }
10482
10610
  numberOfAccounts += 1;
10483
10611
  } while (numberOfAccounts < this.numberOfAccounts);
10484
- throw new import_errors24.FuelError(
10485
- import_errors24.ErrorCode.WALLET_MANAGER_ERROR,
10612
+ throw new import_errors25.FuelError(
10613
+ import_errors25.ErrorCode.WALLET_MANAGER_ERROR,
10486
10614
  `Account with address '${address}' not found in derived wallets.`
10487
10615
  );
10488
10616
  }
@@ -10495,8 +10623,8 @@ _secret = new WeakMap();
10495
10623
  __publicField(MnemonicVault, "type", "mnemonic");
10496
10624
 
10497
10625
  // src/wallet-manager/vaults/privatekey-vault.ts
10498
- var import_address8 = require("@fuel-ts/address");
10499
- var import_errors25 = require("@fuel-ts/errors");
10626
+ var import_address9 = require("@fuel-ts/address");
10627
+ var import_errors26 = require("@fuel-ts/errors");
10500
10628
  var _privateKeys;
10501
10629
  var PrivateKeyVault = class {
10502
10630
  /**
@@ -10532,13 +10660,13 @@ var PrivateKeyVault = class {
10532
10660
  return this.getPublicAccount(wallet.privateKey);
10533
10661
  }
10534
10662
  exportAccount(address) {
10535
- const ownerAddress = import_address8.Address.fromAddressOrString(address);
10663
+ const ownerAddress = import_address9.Address.fromAddressOrString(address);
10536
10664
  const privateKey = __privateGet(this, _privateKeys).find(
10537
10665
  (pk) => Wallet.fromPrivateKey(pk).address.equals(ownerAddress)
10538
10666
  );
10539
10667
  if (!privateKey) {
10540
- throw new import_errors25.FuelError(
10541
- import_errors25.ErrorCode.WALLET_MANAGER_ERROR,
10668
+ throw new import_errors26.FuelError(
10669
+ import_errors26.ErrorCode.WALLET_MANAGER_ERROR,
10542
10670
  `No private key found for address '${address}'.`
10543
10671
  );
10544
10672
  }
@@ -10562,7 +10690,7 @@ var ERROR_MESSAGES = {
10562
10690
  };
10563
10691
  function assert(condition, message) {
10564
10692
  if (!condition) {
10565
- throw new import_errors26.FuelError(import_errors26.ErrorCode.WALLET_MANAGER_ERROR, message);
10693
+ throw new import_errors27.FuelError(import_errors27.ErrorCode.WALLET_MANAGER_ERROR, message);
10566
10694
  }
10567
10695
  }
10568
10696
  var _vaults, _passphrase, _isLocked, _serializeVaults, serializeVaults_fn, _deserializeVaults, deserializeVaults_fn;
@@ -10630,7 +10758,7 @@ var _WalletManager = class extends import_events.EventEmitter {
10630
10758
  * Create a Wallet instance for the specific account
10631
10759
  */
10632
10760
  getWallet(address) {
10633
- const ownerAddress = import_address9.Address.fromAddressOrString(address);
10761
+ const ownerAddress = import_address10.Address.fromAddressOrString(address);
10634
10762
  const vaultState = __privateGet(this, _vaults).find(
10635
10763
  (vs) => vs.vault.getAccounts().find((a) => a.address.equals(ownerAddress))
10636
10764
  );
@@ -10641,7 +10769,7 @@ var _WalletManager = class extends import_events.EventEmitter {
10641
10769
  * Export specific account privateKey
10642
10770
  */
10643
10771
  exportPrivateKey(address) {
10644
- const ownerAddress = import_address9.Address.fromAddressOrString(address);
10772
+ const ownerAddress = import_address10.Address.fromAddressOrString(address);
10645
10773
  assert(!__privateGet(this, _isLocked), ERROR_MESSAGES.wallet_not_unlocked);
10646
10774
  const vaultState = __privateGet(this, _vaults).find(
10647
10775
  (vs) => vs.vault.getAccounts().find((a) => a.address.equals(ownerAddress))
@@ -10788,25 +10916,25 @@ deserializeVaults_fn = function(vaults) {
10788
10916
  __publicField(WalletManager, "Vaults", [MnemonicVault, PrivateKeyVault]);
10789
10917
 
10790
10918
  // src/wallet-manager/types.ts
10791
- var import_errors27 = require("@fuel-ts/errors");
10919
+ var import_errors28 = require("@fuel-ts/errors");
10792
10920
  var Vault = class {
10793
10921
  constructor(_options) {
10794
- throw new import_errors27.FuelError(import_errors27.ErrorCode.NOT_IMPLEMENTED, "Not implemented.");
10922
+ throw new import_errors28.FuelError(import_errors28.ErrorCode.NOT_IMPLEMENTED, "Not implemented.");
10795
10923
  }
10796
10924
  serialize() {
10797
- throw new import_errors27.FuelError(import_errors27.ErrorCode.NOT_IMPLEMENTED, "Not implemented.");
10925
+ throw new import_errors28.FuelError(import_errors28.ErrorCode.NOT_IMPLEMENTED, "Not implemented.");
10798
10926
  }
10799
10927
  getAccounts() {
10800
- throw new import_errors27.FuelError(import_errors27.ErrorCode.NOT_IMPLEMENTED, "Not implemented.");
10928
+ throw new import_errors28.FuelError(import_errors28.ErrorCode.NOT_IMPLEMENTED, "Not implemented.");
10801
10929
  }
10802
10930
  addAccount() {
10803
- throw new import_errors27.FuelError(import_errors27.ErrorCode.NOT_IMPLEMENTED, "Not implemented.");
10931
+ throw new import_errors28.FuelError(import_errors28.ErrorCode.NOT_IMPLEMENTED, "Not implemented.");
10804
10932
  }
10805
10933
  exportAccount(_address) {
10806
- throw new import_errors27.FuelError(import_errors27.ErrorCode.NOT_IMPLEMENTED, "Not implemented.");
10934
+ throw new import_errors28.FuelError(import_errors28.ErrorCode.NOT_IMPLEMENTED, "Not implemented.");
10807
10935
  }
10808
10936
  getWallet(_address) {
10809
- throw new import_errors27.FuelError(import_errors27.ErrorCode.NOT_IMPLEMENTED, "Not implemented.");
10937
+ throw new import_errors28.FuelError(import_errors28.ErrorCode.NOT_IMPLEMENTED, "Not implemented.");
10810
10938
  }
10811
10939
  };
10812
10940
  __publicField(Vault, "type");
@@ -10815,35 +10943,237 @@ var StorageAbstract = class {
10815
10943
 
10816
10944
  // src/predicate/predicate.ts
10817
10945
  var import_abi_coder8 = require("@fuel-ts/abi-coder");
10818
- var import_address10 = require("@fuel-ts/address");
10819
- var import_errors28 = require("@fuel-ts/errors");
10946
+ var import_address11 = require("@fuel-ts/address");
10947
+ var import_errors30 = require("@fuel-ts/errors");
10948
+ var import_utils45 = require("@fuel-ts/utils");
10949
+
10950
+ // src/utils/deployScriptOrPredicate.ts
10951
+ var import_errors29 = require("@fuel-ts/errors");
10952
+ var import_hasher8 = require("@fuel-ts/hasher");
10953
+ var import_math24 = require("@fuel-ts/math");
10820
10954
  var import_utils43 = require("@fuel-ts/utils");
10821
10955
 
10956
+ // src/utils/predicate-script-loader-instructions.ts
10957
+ var import_utils42 = require("@fuel-ts/utils");
10958
+ var asm2 = __toESM(require("@fuels/vm-asm"));
10959
+ var BLOB_ID_SIZE = 32;
10960
+ var REG_ADDRESS_OF_DATA_AFTER_CODE = 16;
10961
+ var REG_START_OF_LOADED_CODE = 17;
10962
+ var REG_GENERAL_USE = 18;
10963
+ var WORD_SIZE2 = 8;
10964
+ function getDataOffset(binary) {
10965
+ const OFFSET_INDEX = 8;
10966
+ const dataView = new DataView(binary.buffer, OFFSET_INDEX, 8);
10967
+ const dataOffset = dataView.getBigUint64(0, false);
10968
+ return Number(dataOffset);
10969
+ }
10970
+ function getPredicateScriptLoaderInstructions(originalBinary, blobId) {
10971
+ const { RegId, Instruction } = asm2;
10972
+ const REG_PC = RegId.pc().to_u8();
10973
+ const REG_SP = RegId.sp().to_u8();
10974
+ const REG_IS = RegId.is().to_u8();
10975
+ const getInstructions = (numOfInstructions2) => [
10976
+ // 1. Load the blob content into memory
10977
+ // Find the start of the hardcoded blob ID, which is located after the loader code ends.
10978
+ asm2.move_(REG_ADDRESS_OF_DATA_AFTER_CODE, REG_PC),
10979
+ // hold the address of the blob ID.
10980
+ asm2.addi(
10981
+ REG_ADDRESS_OF_DATA_AFTER_CODE,
10982
+ REG_ADDRESS_OF_DATA_AFTER_CODE,
10983
+ numOfInstructions2 * Instruction.size()
10984
+ ),
10985
+ // The code is going to be loaded from the current value of SP onwards, save
10986
+ // the location into REG_START_OF_LOADED_CODE so we can jump into it at the end.
10987
+ asm2.move_(REG_START_OF_LOADED_CODE, REG_SP),
10988
+ // REG_GENERAL_USE to hold the size of the blob.
10989
+ asm2.bsiz(REG_GENERAL_USE, REG_ADDRESS_OF_DATA_AFTER_CODE),
10990
+ // Push the blob contents onto the stack.
10991
+ asm2.ldc(REG_ADDRESS_OF_DATA_AFTER_CODE, 0, REG_GENERAL_USE, 1),
10992
+ // Move on to the data section length
10993
+ asm2.addi(REG_ADDRESS_OF_DATA_AFTER_CODE, REG_ADDRESS_OF_DATA_AFTER_CODE, BLOB_ID_SIZE),
10994
+ // load the size of the data section into REG_GENERAL_USE
10995
+ asm2.lw(REG_GENERAL_USE, REG_ADDRESS_OF_DATA_AFTER_CODE, 0),
10996
+ // after we have read the length of the data section, we move the pointer to the actual
10997
+ // data by skipping WORD_SIZE bytes.
10998
+ asm2.addi(REG_ADDRESS_OF_DATA_AFTER_CODE, REG_ADDRESS_OF_DATA_AFTER_CODE, WORD_SIZE2),
10999
+ // load the data section of the executable
11000
+ asm2.ldc(REG_ADDRESS_OF_DATA_AFTER_CODE, 0, REG_GENERAL_USE, 2),
11001
+ // Jump into the memory where the contract is loaded.
11002
+ // What follows is called _jmp_mem by the sway compiler.
11003
+ // Subtract the address contained in IS because jmp will add it back.
11004
+ asm2.sub(REG_START_OF_LOADED_CODE, REG_START_OF_LOADED_CODE, REG_IS),
11005
+ // jmp will multiply by 4, so we need to divide to cancel that out.
11006
+ asm2.divi(REG_START_OF_LOADED_CODE, REG_START_OF_LOADED_CODE, 4),
11007
+ // Jump to the start of the contract we loaded.
11008
+ asm2.jmp(REG_START_OF_LOADED_CODE)
11009
+ ];
11010
+ const getInstructionsNoDataSection = (numOfInstructions2) => [
11011
+ // 1. Load the blob content into memory
11012
+ // Find the start of the hardcoded blob ID, which is located after the loader code ends.
11013
+ // 1. Load the blob content into memory
11014
+ // Find the start of the hardcoded blob ID, which is located after the loader code ends.
11015
+ asm2.move_(REG_ADDRESS_OF_DATA_AFTER_CODE, REG_PC),
11016
+ // hold the address of the blob ID.
11017
+ asm2.addi(
11018
+ REG_ADDRESS_OF_DATA_AFTER_CODE,
11019
+ REG_ADDRESS_OF_DATA_AFTER_CODE,
11020
+ numOfInstructions2 * Instruction.size()
11021
+ ),
11022
+ // The code is going to be loaded from the current value of SP onwards, save
11023
+ // the location into REG_START_OF_LOADED_CODE so we can jump into it at the end.
11024
+ asm2.move_(REG_START_OF_LOADED_CODE, REG_SP),
11025
+ // REG_GENERAL_USE to hold the size of the blob.
11026
+ asm2.bsiz(REG_GENERAL_USE, REG_ADDRESS_OF_DATA_AFTER_CODE),
11027
+ // Push the blob contents onto the stack.
11028
+ asm2.ldc(REG_ADDRESS_OF_DATA_AFTER_CODE, 0, REG_GENERAL_USE, 1),
11029
+ // Jump into the memory where the contract is loaded.
11030
+ // What follows is called _jmp_mem by the sway compiler.
11031
+ // Subtract the address contained in IS because jmp will add it back.
11032
+ asm2.sub(REG_START_OF_LOADED_CODE, REG_START_OF_LOADED_CODE, REG_IS),
11033
+ // jmp will multiply by 4, so we need to divide to cancel that out.
11034
+ asm2.divi(REG_START_OF_LOADED_CODE, REG_START_OF_LOADED_CODE, 4),
11035
+ // Jump to the start of the contract we loaded.
11036
+ asm2.jmp(REG_START_OF_LOADED_CODE)
11037
+ ];
11038
+ const offset = getDataOffset(originalBinary);
11039
+ if (originalBinary.length < offset) {
11040
+ throw new Error(
11041
+ `Data section offset is out of bounds, offset: ${offset}, binary length: ${originalBinary.length}`
11042
+ );
11043
+ }
11044
+ const dataSection = originalBinary.slice(offset);
11045
+ if (dataSection.length > 0) {
11046
+ const numOfInstructions2 = getInstructions(0).length;
11047
+ if (numOfInstructions2 > 65535) {
11048
+ throw new Error("Too many instructions, exceeding u16::MAX.");
11049
+ }
11050
+ const instructionBytes2 = new Uint8Array(
11051
+ getInstructions(numOfInstructions2).flatMap(
11052
+ (instruction) => Array.from(instruction.to_bytes())
11053
+ )
11054
+ );
11055
+ const blobBytes2 = new Uint8Array(blobId);
11056
+ const dataSectionLenBytes = new Uint8Array(8);
11057
+ const dataView = new DataView(dataSectionLenBytes.buffer);
11058
+ dataView.setBigUint64(0, BigInt(dataSection.length), false);
11059
+ const loaderBytecode2 = new Uint8Array([
11060
+ ...instructionBytes2,
11061
+ ...blobBytes2,
11062
+ ...dataSectionLenBytes
11063
+ ]);
11064
+ return {
11065
+ loaderBytecode: (0, import_utils42.concat)([loaderBytecode2, dataSection]),
11066
+ blobOffset: loaderBytecode2.length
11067
+ };
11068
+ }
11069
+ const numOfInstructions = getInstructionsNoDataSection(0).length;
11070
+ if (numOfInstructions > 65535) {
11071
+ throw new Error("Too many instructions, exceeding u16::MAX.");
11072
+ }
11073
+ const instructionBytes = new Uint8Array(
11074
+ getInstructionsNoDataSection(numOfInstructions).flatMap(
11075
+ (instruction) => Array.from(instruction.to_bytes())
11076
+ )
11077
+ );
11078
+ const blobBytes = new Uint8Array(blobId);
11079
+ const loaderBytecode = new Uint8Array([...instructionBytes, ...blobBytes]);
11080
+ return { loaderBytecode };
11081
+ }
11082
+
11083
+ // src/utils/deployScriptOrPredicate.ts
11084
+ async function fundBlobTx(deployer, blobTxRequest) {
11085
+ let totalCost = (0, import_math24.bn)(0);
11086
+ const chainInfo = deployer.provider.getChain();
11087
+ const gasPrice = await deployer.provider.estimateGasPrice(10);
11088
+ const priceFactor = chainInfo.consensusParameters.feeParameters.gasPriceFactor;
11089
+ const minGas = blobTxRequest.calculateMinGas(chainInfo);
11090
+ const minFee = calculateGasFee({
11091
+ gasPrice,
11092
+ gas: minGas,
11093
+ priceFactor,
11094
+ tip: blobTxRequest.tip
11095
+ }).add(1);
11096
+ totalCost = totalCost.add(minFee);
11097
+ if (totalCost.gt(await deployer.getBalance())) {
11098
+ throw new import_errors29.FuelError(import_errors29.ErrorCode.FUNDS_TOO_LOW, "Insufficient balance to deploy predicate.");
11099
+ }
11100
+ const txCost = await deployer.getTransactionCost(blobTxRequest);
11101
+ blobTxRequest.maxFee = txCost.maxFee;
11102
+ return deployer.fund(blobTxRequest, txCost);
11103
+ }
11104
+ function adjustConfigurableOffsets(jsonAbi, configurableOffsetDiff) {
11105
+ const { configurables: readOnlyConfigurables } = jsonAbi;
11106
+ const configurables = [];
11107
+ readOnlyConfigurables.forEach((config) => {
11108
+ configurables.push({ ...config, offset: config.offset - configurableOffsetDiff });
11109
+ });
11110
+ return { ...jsonAbi, configurables };
11111
+ }
11112
+ async function deployScriptOrPredicate({
11113
+ deployer,
11114
+ bytecode,
11115
+ abi,
11116
+ loaderInstanceCallback
11117
+ }) {
11118
+ const dataSectionOffset = getDataOffset((0, import_utils43.arrayify)(bytecode));
11119
+ const byteCodeWithoutDataSection = bytecode.slice(0, dataSectionOffset);
11120
+ const blobId = (0, import_hasher8.hash)(byteCodeWithoutDataSection);
11121
+ const blobTxRequest = new BlobTransactionRequest({
11122
+ blobId,
11123
+ witnessIndex: 0,
11124
+ witnesses: [byteCodeWithoutDataSection]
11125
+ });
11126
+ const { loaderBytecode, blobOffset } = getPredicateScriptLoaderInstructions(
11127
+ (0, import_utils43.arrayify)(bytecode),
11128
+ (0, import_utils43.arrayify)(blobId)
11129
+ );
11130
+ const configurableOffsetDiff = byteCodeWithoutDataSection.length - (blobOffset || 0);
11131
+ const newAbi = adjustConfigurableOffsets(abi, configurableOffsetDiff);
11132
+ const blobExists = (await deployer.provider.getBlobs([blobId])).length > 0;
11133
+ const loaderInstance = loaderInstanceCallback(loaderBytecode, newAbi);
11134
+ if (blobExists) {
11135
+ return {
11136
+ waitForResult: () => Promise.resolve(loaderInstance),
11137
+ blobId
11138
+ };
11139
+ }
11140
+ const fundedBlobRequest = await fundBlobTx(deployer, blobTxRequest);
11141
+ const waitForResult = async () => {
11142
+ try {
11143
+ const blobTx = await deployer.sendTransaction(fundedBlobRequest);
11144
+ const result = await blobTx.waitForResult();
11145
+ if (result.status !== "success" /* success */) {
11146
+ throw new Error();
11147
+ }
11148
+ } catch (err) {
11149
+ throw new import_errors29.FuelError(import_errors29.ErrorCode.TRANSACTION_FAILED, "Failed to deploy predicate chunk");
11150
+ }
11151
+ return loaderInstance;
11152
+ };
11153
+ return {
11154
+ waitForResult,
11155
+ blobId
11156
+ };
11157
+ }
11158
+
10822
11159
  // src/predicate/utils/getPredicateRoot.ts
10823
- var import_hasher8 = require("@fuel-ts/hasher");
11160
+ var import_hasher9 = require("@fuel-ts/hasher");
10824
11161
  var import_merkle = require("@fuel-ts/merkle");
10825
- var import_utils42 = require("@fuel-ts/utils");
11162
+ var import_utils44 = require("@fuel-ts/utils");
10826
11163
  var getPredicateRoot = (bytecode) => {
10827
11164
  const chunkSize = 16 * 1024;
10828
- const bytes = (0, import_utils42.arrayify)(bytecode);
10829
- const chunks = (0, import_utils42.chunkAndPadBytes)(bytes, chunkSize);
10830
- const codeRoot = (0, import_merkle.calcRoot)(chunks.map((c) => (0, import_utils42.hexlify)(c)));
10831
- const predicateRoot = (0, import_hasher8.hash)((0, import_utils42.concat)(["0x4655454C", codeRoot]));
11165
+ const bytes = (0, import_utils44.arrayify)(bytecode);
11166
+ const chunks = (0, import_utils44.chunkAndPadBytes)(bytes, chunkSize);
11167
+ const codeRoot = (0, import_merkle.calcRoot)(chunks.map((c) => (0, import_utils44.hexlify)(c)));
11168
+ const predicateRoot = (0, import_hasher9.hash)((0, import_utils44.concat)(["0x4655454C", codeRoot]));
10832
11169
  return predicateRoot;
10833
11170
  };
10834
11171
 
10835
11172
  // src/predicate/predicate.ts
10836
- function getDataOffset(binary) {
10837
- const buffer = binary.buffer.slice(binary.byteOffset + 8, binary.byteOffset + 16);
10838
- const dataView = new DataView(buffer);
10839
- const dataOffset = dataView.getBigUint64(0, false);
10840
- return Number(dataOffset);
10841
- }
10842
11173
  var Predicate = class extends Account {
10843
11174
  bytes;
10844
11175
  predicateData = [];
10845
11176
  interface;
10846
- loaderBytecode = "";
10847
11177
  /**
10848
11178
  * Creates an instance of the Predicate class.
10849
11179
  *
@@ -10858,24 +11188,17 @@ var Predicate = class extends Account {
10858
11188
  abi,
10859
11189
  provider,
10860
11190
  data,
10861
- configurableConstants,
10862
- /**
10863
- * TODO: Implement a getBytes method within the Predicate class. This method should return the loaderBytecode if it is set.
10864
- * The getBytes method should be used in all places where we use this.bytes.
10865
- * Note: Do not set loaderBytecode to a default string here; it should remain undefined when not provided.
10866
- */
10867
- loaderBytecode = ""
11191
+ configurableConstants
10868
11192
  }) {
10869
11193
  const { predicateBytes, predicateInterface } = Predicate.processPredicateData(
10870
11194
  bytecode,
10871
11195
  abi,
10872
11196
  configurableConstants
10873
11197
  );
10874
- const address = import_address10.Address.fromB256(getPredicateRoot(predicateBytes));
11198
+ const address = import_address11.Address.fromB256(getPredicateRoot(predicateBytes));
10875
11199
  super(address, provider);
10876
11200
  this.bytes = predicateBytes;
10877
11201
  this.interface = predicateInterface;
10878
- this.loaderBytecode = loaderBytecode;
10879
11202
  if (data !== void 0 && data.length > 0) {
10880
11203
  this.predicateData = data;
10881
11204
  }
@@ -10894,8 +11217,8 @@ var Predicate = class extends Account {
10894
11217
  }
10895
11218
  request.inputs.filter(isRequestInputCoinOrMessage).forEach((input) => {
10896
11219
  if (isRequestInputResourceFromOwner(input, this.address)) {
10897
- input.predicate = (0, import_utils43.hexlify)(this.bytes);
10898
- input.predicateData = (0, import_utils43.hexlify)(this.getPredicateData());
11220
+ input.predicate = (0, import_utils45.hexlify)(this.bytes);
11221
+ input.predicateData = (0, import_utils45.hexlify)(this.getPredicateData());
10899
11222
  input.witnessIndex = 0;
10900
11223
  }
10901
11224
  });
@@ -10937,16 +11260,13 @@ var Predicate = class extends Account {
10937
11260
  * @returns An object containing the new predicate bytes and interface.
10938
11261
  */
10939
11262
  static processPredicateData(bytes, jsonAbi, configurableConstants) {
10940
- let predicateBytes = (0, import_utils43.arrayify)(bytes);
10941
- let abiInterface;
10942
- if (jsonAbi) {
10943
- abiInterface = new import_abi_coder8.Interface(jsonAbi);
10944
- if (abiInterface.functions.main === void 0) {
10945
- throw new import_errors28.FuelError(
10946
- import_errors28.ErrorCode.ABI_MAIN_METHOD_MISSING,
10947
- 'Cannot use ABI without "main" function.'
10948
- );
10949
- }
11263
+ let predicateBytes = (0, import_utils45.arrayify)(bytes);
11264
+ const abiInterface = new import_abi_coder8.Interface(jsonAbi);
11265
+ if (abiInterface.functions.main === void 0) {
11266
+ throw new import_errors30.FuelError(
11267
+ import_errors30.ErrorCode.ABI_MAIN_METHOD_MISSING,
11268
+ 'Cannot use ABI without "main" function.'
11269
+ );
10950
11270
  }
10951
11271
  if (configurableConstants && Object.keys(configurableConstants).length) {
10952
11272
  predicateBytes = Predicate.setConfigurableConstants(
@@ -10975,8 +11295,8 @@ var Predicate = class extends Account {
10975
11295
  );
10976
11296
  return resources.map((resource) => ({
10977
11297
  ...resource,
10978
- predicate: (0, import_utils43.hexlify)(this.bytes),
10979
- predicateData: (0, import_utils43.hexlify)(this.getPredicateData())
11298
+ predicate: (0, import_utils45.hexlify)(this.bytes),
11299
+ predicateData: (0, import_utils45.hexlify)(this.getPredicateData())
10980
11300
  }));
10981
11301
  }
10982
11302
  /**
@@ -10988,8 +11308,8 @@ var Predicate = class extends Account {
10988
11308
  generateFakeResources(coins) {
10989
11309
  return super.generateFakeResources(coins).map((coin) => ({
10990
11310
  ...coin,
10991
- predicate: (0, import_utils43.hexlify)(this.bytes),
10992
- predicateData: (0, import_utils43.hexlify)(this.getPredicateData())
11311
+ predicate: (0, import_utils45.hexlify)(this.bytes),
11312
+ predicateData: (0, import_utils45.hexlify)(this.getPredicateData())
10993
11313
  }));
10994
11314
  }
10995
11315
  /**
@@ -11000,25 +11320,19 @@ var Predicate = class extends Account {
11000
11320
  * @param abiInterface - The ABI interface of the predicate.
11001
11321
  * @returns The mutated bytes with the configurable constants set.
11002
11322
  */
11003
- static setConfigurableConstants(bytes, configurableConstants, abiInterface, loaderBytecode) {
11323
+ static setConfigurableConstants(bytes, configurableConstants, abiInterface) {
11004
11324
  const mutatedBytes = bytes;
11005
11325
  try {
11006
- if (!abiInterface) {
11007
- throw new import_errors28.FuelError(
11008
- import_errors28.ErrorCode.INVALID_CONFIGURABLE_CONSTANTS,
11009
- "Cannot validate configurable constants because the Predicate was instantiated without a JSON ABI"
11010
- );
11011
- }
11012
11326
  if (Object.keys(abiInterface.configurables).length === 0) {
11013
- throw new import_errors28.FuelError(
11014
- import_errors28.ErrorCode.INVALID_CONFIGURABLE_CONSTANTS,
11327
+ throw new import_errors30.FuelError(
11328
+ import_errors30.ErrorCode.INVALID_CONFIGURABLE_CONSTANTS,
11015
11329
  "Predicate has no configurable constants to be set"
11016
11330
  );
11017
11331
  }
11018
11332
  Object.entries(configurableConstants).forEach(([key, value]) => {
11019
11333
  if (!abiInterface?.configurables[key]) {
11020
- throw new import_errors28.FuelError(
11021
- import_errors28.ErrorCode.CONFIGURABLE_NOT_FOUND,
11334
+ throw new import_errors30.FuelError(
11335
+ import_errors30.ErrorCode.CONFIGURABLE_NOT_FOUND,
11022
11336
  `No configurable constant named '${key}' found in the Predicate`
11023
11337
  );
11024
11338
  }
@@ -11026,18 +11340,9 @@ var Predicate = class extends Account {
11026
11340
  const encoded = abiInterface.encodeConfigurable(key, value);
11027
11341
  mutatedBytes.set(encoded, offset);
11028
11342
  });
11029
- if (loaderBytecode) {
11030
- const offset = getDataOffset(bytes);
11031
- const dataSection = mutatedBytes.slice(offset);
11032
- const dataSectionLen = dataSection.length;
11033
- const dataSectionLenBytes = new Uint8Array(8);
11034
- const dataSectionLenDataView = new DataView(dataSectionLenBytes.buffer);
11035
- dataSectionLenDataView.setBigUint64(0, BigInt(dataSectionLen), false);
11036
- mutatedBytes.set((0, import_utils43.concat)([loaderBytecode, dataSectionLenBytes, dataSection]));
11037
- }
11038
11343
  } catch (err) {
11039
- throw new import_errors28.FuelError(
11040
- import_errors28.ErrorCode.INVALID_CONFIGURABLE_CONSTANTS,
11344
+ throw new import_errors30.FuelError(
11345
+ import_errors30.ErrorCode.INVALID_CONFIGURABLE_CONSTANTS,
11041
11346
  `Error setting configurable constants: ${err.message}.`
11042
11347
  );
11043
11348
  }
@@ -11065,13 +11370,35 @@ var Predicate = class extends Account {
11065
11370
  }
11066
11371
  return index;
11067
11372
  }
11373
+ /**
11374
+ *
11375
+ * @param account - The account used to pay the deployment costs.
11376
+ * @returns The _blobId_ and a _waitForResult_ callback that returns the deployed predicate
11377
+ * once the blob deployment transaction finishes.
11378
+ *
11379
+ * The returned loader predicate will have the same configurable constants
11380
+ * as the original predicate which was used to generate the loader predicate.
11381
+ */
11382
+ async deploy(account) {
11383
+ return deployScriptOrPredicate({
11384
+ deployer: account,
11385
+ abi: this.interface.jsonAbi,
11386
+ bytecode: this.bytes,
11387
+ loaderInstanceCallback: (loaderBytecode, newAbi) => new Predicate({
11388
+ bytecode: loaderBytecode,
11389
+ abi: newAbi,
11390
+ provider: this.provider,
11391
+ data: this.predicateData
11392
+ })
11393
+ });
11394
+ }
11068
11395
  };
11069
11396
 
11070
11397
  // src/connectors/fuel.ts
11071
- var import_errors31 = require("@fuel-ts/errors");
11398
+ var import_errors33 = require("@fuel-ts/errors");
11072
11399
 
11073
11400
  // src/connectors/fuel-connector.ts
11074
- var import_errors29 = require("@fuel-ts/errors");
11401
+ var import_errors31 = require("@fuel-ts/errors");
11075
11402
  var import_events2 = require("events");
11076
11403
 
11077
11404
  // src/connectors/types/connector-types.ts
@@ -11146,7 +11473,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11146
11473
  * @returns Always true.
11147
11474
  */
11148
11475
  async ping() {
11149
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11476
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11150
11477
  }
11151
11478
  /**
11152
11479
  * Should return the current version of the connector
@@ -11155,7 +11482,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11155
11482
  * @returns boolean - connection status.
11156
11483
  */
11157
11484
  async version() {
11158
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11485
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11159
11486
  }
11160
11487
  /**
11161
11488
  * Should return true if the connector is connected
@@ -11164,7 +11491,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11164
11491
  * @returns The connection status.
11165
11492
  */
11166
11493
  async isConnected() {
11167
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11494
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11168
11495
  }
11169
11496
  /**
11170
11497
  * Should return all the accounts authorized for the
@@ -11173,7 +11500,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11173
11500
  * @returns The accounts addresses strings
11174
11501
  */
11175
11502
  async accounts() {
11176
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11503
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11177
11504
  }
11178
11505
  /**
11179
11506
  * Should start the connection process and return
@@ -11185,7 +11512,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11185
11512
  * @returns boolean - connection status.
11186
11513
  */
11187
11514
  async connect() {
11188
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11515
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11189
11516
  }
11190
11517
  /**
11191
11518
  * Should disconnect the current connection and
@@ -11195,7 +11522,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11195
11522
  * @returns The connection status.
11196
11523
  */
11197
11524
  async disconnect() {
11198
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11525
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11199
11526
  }
11200
11527
  /**
11201
11528
  * Should start the sign message process and return
@@ -11207,7 +11534,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11207
11534
  * @returns Message signature
11208
11535
  */
11209
11536
  async signMessage(_address, _message) {
11210
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11537
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11211
11538
  }
11212
11539
  /**
11213
11540
  * Should start the sign transaction process and return
@@ -11219,7 +11546,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11219
11546
  * @returns Transaction signature
11220
11547
  */
11221
11548
  async signTransaction(_address, _transaction) {
11222
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11549
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11223
11550
  }
11224
11551
  /**
11225
11552
  * Should start the send transaction process and return
@@ -11235,7 +11562,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11235
11562
  * @returns The transaction id
11236
11563
  */
11237
11564
  async sendTransaction(_address, _transaction) {
11238
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11565
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11239
11566
  }
11240
11567
  /**
11241
11568
  * Should return the current account selected inside the connector, if the account
@@ -11246,7 +11573,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11246
11573
  * @returns The current account selected otherwise null.
11247
11574
  */
11248
11575
  async currentAccount() {
11249
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11576
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11250
11577
  }
11251
11578
  /**
11252
11579
  * Should add the assets metadata to the connector and return true if the asset
@@ -11260,7 +11587,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11260
11587
  * @returns True if the asset was added successfully
11261
11588
  */
11262
11589
  async addAssets(_assets) {
11263
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11590
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11264
11591
  }
11265
11592
  /**
11266
11593
  * Should add the asset metadata to the connector and return true if the asset
@@ -11274,7 +11601,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11274
11601
  * @returns True if the asset was added successfully
11275
11602
  */
11276
11603
  async addAsset(_asset) {
11277
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11604
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11278
11605
  }
11279
11606
  /**
11280
11607
  * Should return all the assets added to the connector. If a connection is already established.
@@ -11282,7 +11609,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11282
11609
  * @returns Array of assets metadata from the connector vinculated to the all accounts from a specific Wallet.
11283
11610
  */
11284
11611
  async assets() {
11285
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11612
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11286
11613
  }
11287
11614
  /**
11288
11615
  * Should start the add network process and return true if the network was added successfully.
@@ -11293,7 +11620,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11293
11620
  * @returns Return true if the network was added successfully
11294
11621
  */
11295
11622
  async addNetwork(_networkUrl) {
11296
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11623
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11297
11624
  }
11298
11625
  /**
11299
11626
  * Should start the select network process and return true if the network has change successfully.
@@ -11304,7 +11631,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11304
11631
  * @returns Return true if the network was added successfully
11305
11632
  */
11306
11633
  async selectNetwork(_network) {
11307
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11634
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11308
11635
  }
11309
11636
  /**
11310
11637
  * Should return all the networks available from the connector. If the connection is already established.
@@ -11312,7 +11639,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11312
11639
  * @returns Return all the networks added to the connector.
11313
11640
  */
11314
11641
  async networks() {
11315
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11642
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11316
11643
  }
11317
11644
  /**
11318
11645
  * Should return the current network selected inside the connector. Even if the connection is not established.
@@ -11320,7 +11647,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11320
11647
  * @returns Return the current network selected inside the connector.
11321
11648
  */
11322
11649
  async currentNetwork() {
11323
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11650
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11324
11651
  }
11325
11652
  /**
11326
11653
  * Should add the ABI to the connector and return true if the ABI was added successfully.
@@ -11330,7 +11657,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11330
11657
  * @returns Return true if the ABI was added successfully.
11331
11658
  */
11332
11659
  async addABI(_contractId, _abi) {
11333
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11660
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11334
11661
  }
11335
11662
  /**
11336
11663
  * Should return the ABI from the connector vinculated to the all accounts from a specific Wallet.
@@ -11339,7 +11666,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11339
11666
  * @returns The ABI if it exists, otherwise return null.
11340
11667
  */
11341
11668
  async getABI(_id) {
11342
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11669
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11343
11670
  }
11344
11671
  /**
11345
11672
  * Should return true if the abi exists in the connector vinculated to the all accounts from a specific Wallet.
@@ -11348,7 +11675,7 @@ var FuelConnector = class extends import_events2.EventEmitter {
11348
11675
  * @returns Returns true if the abi exists or false if not.
11349
11676
  */
11350
11677
  async hasABI(_id) {
11351
- throw new import_errors29.FuelError(import_errors29.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11678
+ throw new import_errors31.FuelError(import_errors31.FuelError.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11352
11679
  }
11353
11680
  /**
11354
11681
  * Event listener for the connector.
@@ -11392,7 +11719,7 @@ function dispatchFuelConnectorEvent(connector) {
11392
11719
  }
11393
11720
 
11394
11721
  // src/connectors/utils/promises.ts
11395
- var import_errors30 = require("@fuel-ts/errors");
11722
+ var import_errors32 = require("@fuel-ts/errors");
11396
11723
  function deferPromise() {
11397
11724
  const defer = {};
11398
11725
  defer.promise = new Promise((resolve, reject) => {
@@ -11404,7 +11731,7 @@ function deferPromise() {
11404
11731
  async function withTimeout(promise, timeout = 1050) {
11405
11732
  const timeoutPromise = new Promise((resolve, reject) => {
11406
11733
  setTimeout(() => {
11407
- reject(new import_errors30.FuelError(import_errors30.FuelError.CODES.TIMEOUT_EXCEEDED, "Promise timed out"));
11734
+ reject(new import_errors32.FuelError(import_errors32.FuelError.CODES.TIMEOUT_EXCEEDED, "Promise timed out"));
11408
11735
  }, timeout);
11409
11736
  });
11410
11737
  return Promise.race([timeoutPromise, promise]);
@@ -11435,10 +11762,11 @@ var _Fuel = class extends FuelConnector {
11435
11762
  }
11436
11763
  async initialize() {
11437
11764
  try {
11438
- await this.setDefaultConnector();
11765
+ const connectResponse = this.setDefaultConnector();
11439
11766
  this._targetUnsubscribe = this.setupConnectorListener();
11767
+ await connectResponse;
11440
11768
  } catch (error) {
11441
- throw new import_errors31.FuelError(import_errors31.ErrorCode.INVALID_PROVIDER, "Error initializing Fuel Connector");
11769
+ throw new import_errors33.FuelError(import_errors33.ErrorCode.INVALID_PROVIDER, "Error initializing Fuel Connector");
11442
11770
  }
11443
11771
  }
11444
11772
  async init() {
@@ -11504,8 +11832,8 @@ var _Fuel = class extends FuelConnector {
11504
11832
  const hasConnector = await this.hasConnector();
11505
11833
  await this.pingConnector();
11506
11834
  if (!this._currentConnector || !hasConnector) {
11507
- throw new import_errors31.FuelError(
11508
- import_errors31.ErrorCode.MISSING_CONNECTOR,
11835
+ throw new import_errors33.FuelError(
11836
+ import_errors33.ErrorCode.MISSING_CONNECTOR,
11509
11837
  `No connector selected for calling ${method}. Use hasConnector before executing other methods.`
11510
11838
  );
11511
11839
  }
@@ -11569,7 +11897,7 @@ var _Fuel = class extends FuelConnector {
11569
11897
  cacheTime: PING_CACHE_TIME
11570
11898
  })();
11571
11899
  } catch {
11572
- throw new import_errors31.FuelError(import_errors31.ErrorCode.INVALID_PROVIDER, "Current connector is not available.");
11900
+ throw new import_errors33.FuelError(import_errors33.ErrorCode.INVALID_PROVIDER, "Current connector is not available.");
11573
11901
  }
11574
11902
  }
11575
11903
  /**
@@ -11718,7 +12046,7 @@ var _Fuel = class extends FuelConnector {
11718
12046
  const currentNetwork = await this.currentNetwork();
11719
12047
  provider = await Provider.create(currentNetwork.url);
11720
12048
  } else {
11721
- throw new import_errors31.FuelError(import_errors31.ErrorCode.INVALID_PROVIDER, "Provider is not valid.");
12049
+ throw new import_errors33.FuelError(import_errors33.ErrorCode.INVALID_PROVIDER, "Provider is not valid.");
11722
12050
  }
11723
12051
  return provider;
11724
12052
  }
@@ -11774,6 +12102,7 @@ __publicField(Fuel, "defaultConfig", {});
11774
12102
  FuelConnectorEventType,
11775
12103
  FuelConnectorEventTypes,
11776
12104
  FuelConnectorMethods,
12105
+ GAS_USED_MODIFIER,
11777
12106
  HDWallet,
11778
12107
  Language,
11779
12108
  LocalStorage,
@@ -11825,6 +12154,7 @@ __publicField(Fuel, "defaultConfig", {});
11825
12154
  calculateTXFeeForSummary,
11826
12155
  coinQuantityfy,
11827
12156
  deferPromise,
12157
+ deployScriptOrPredicate,
11828
12158
  dispatchFuelConnectorEvent,
11829
12159
  english,
11830
12160
  extractBurnedAssetsFromReceipts,