@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.mjs CHANGED
@@ -29,9 +29,9 @@ var __privateMethod = (obj, member, method) => {
29
29
 
30
30
  // src/account.ts
31
31
  import { UTXO_ID_LEN as UTXO_ID_LEN3 } from "@fuel-ts/abi-coder";
32
- import { Address as Address3 } from "@fuel-ts/address";
32
+ import { Address as Address4 } from "@fuel-ts/address";
33
33
  import { randomBytes as randomBytes2 } from "@fuel-ts/crypto";
34
- import { ErrorCode as ErrorCode16, FuelError as FuelError18 } from "@fuel-ts/errors";
34
+ import { ErrorCode as ErrorCode17, FuelError as FuelError19 } from "@fuel-ts/errors";
35
35
  import { AbstractAccount } from "@fuel-ts/interfaces";
36
36
  import { bn as bn19 } from "@fuel-ts/math";
37
37
  import { InputType as InputType8 } from "@fuel-ts/transactions";
@@ -75,7 +75,7 @@ var addAmountToCoinQuantities = (params) => {
75
75
 
76
76
  // src/providers/provider.ts
77
77
  import { Address as Address2 } from "@fuel-ts/address";
78
- import { ErrorCode as ErrorCode14, FuelError as FuelError16 } from "@fuel-ts/errors";
78
+ import { ErrorCode as ErrorCode15, FuelError as FuelError17 } from "@fuel-ts/errors";
79
79
  import { BN as BN2, bn as bn17 } from "@fuel-ts/math";
80
80
  import { InputType as InputType7, InputMessageCoder as InputMessageCoder2, TransactionCoder as TransactionCoder5 } from "@fuel-ts/transactions";
81
81
  import { arrayify as arrayify12, hexlify as hexlify15, DateTime as DateTime2, isDefined as isDefined2 } from "@fuel-ts/utils";
@@ -128,9 +128,6 @@ var ReceiptFragmentDoc = gql`
128
128
  var SuccessStatusFragmentDoc = gql`
129
129
  fragment SuccessStatusFragment on SuccessStatus {
130
130
  type: __typename
131
- block {
132
- id
133
- }
134
131
  time
135
132
  programState {
136
133
  returnType
@@ -143,6 +140,14 @@ var SuccessStatusFragmentDoc = gql`
143
140
  totalFee
144
141
  }
145
142
  ${ReceiptFragmentDoc}`;
143
+ var SuccessStatusWithBlockIdFragmentDoc = gql`
144
+ fragment SuccessStatusWithBlockIdFragment on SuccessStatus {
145
+ ...SuccessStatusFragment
146
+ block {
147
+ id
148
+ }
149
+ }
150
+ ${SuccessStatusFragmentDoc}`;
146
151
  var MalleableTransactionFieldsFragmentDoc = gql`
147
152
  fragment malleableTransactionFieldsFragment on Transaction {
148
153
  receiptsRoot
@@ -187,9 +192,6 @@ var MalleableTransactionFieldsFragmentDoc = gql`
187
192
  var FailureStatusFragmentDoc = gql`
188
193
  fragment FailureStatusFragment on FailureStatus {
189
194
  type: __typename
190
- block {
191
- id
192
- }
193
195
  totalGas
194
196
  totalFee
195
197
  time
@@ -199,6 +201,14 @@ var FailureStatusFragmentDoc = gql`
199
201
  }
200
202
  }
201
203
  ${ReceiptFragmentDoc}`;
204
+ var FailureStatusWithBlockIdFragmentDoc = gql`
205
+ fragment FailureStatusWithBlockIdFragment on FailureStatus {
206
+ ...FailureStatusFragment
207
+ block {
208
+ id
209
+ }
210
+ }
211
+ ${FailureStatusFragmentDoc}`;
202
212
  var SqueezedOutStatusFragmentDoc = gql`
203
213
  fragment SqueezedOutStatusFragment on SqueezedOutStatus {
204
214
  type: __typename
@@ -211,13 +221,13 @@ var TransactionStatusSubscriptionFragmentDoc = gql`
211
221
  ...SubmittedStatusFragment
212
222
  }
213
223
  ... on SuccessStatus {
214
- ...SuccessStatusFragment
224
+ ...SuccessStatusWithBlockIdFragment
215
225
  transaction {
216
226
  ...malleableTransactionFieldsFragment
217
227
  }
218
228
  }
219
229
  ... on FailureStatus {
220
- ...FailureStatusFragment
230
+ ...FailureStatusWithBlockIdFragment
221
231
  transaction {
222
232
  ...malleableTransactionFieldsFragment
223
233
  }
@@ -227,9 +237,9 @@ var TransactionStatusSubscriptionFragmentDoc = gql`
227
237
  }
228
238
  }
229
239
  ${SubmittedStatusFragmentDoc}
230
- ${SuccessStatusFragmentDoc}
240
+ ${SuccessStatusWithBlockIdFragmentDoc}
231
241
  ${MalleableTransactionFieldsFragmentDoc}
232
- ${FailureStatusFragmentDoc}
242
+ ${FailureStatusWithBlockIdFragmentDoc}
233
243
  ${SqueezedOutStatusFragmentDoc}`;
234
244
  var TransactionStatusFragmentDoc = gql`
235
245
  fragment transactionStatusFragment on TransactionStatus {
@@ -259,6 +269,12 @@ var TransactionFragmentDoc = gql`
259
269
  }
260
270
  }
261
271
  ${TransactionStatusFragmentDoc}`;
272
+ var TransactionRawPayloadFragmentDoc = gql`
273
+ fragment transactionRawPayloadFragment on Transaction {
274
+ id
275
+ rawPayload
276
+ }
277
+ `;
262
278
  var InputEstimatePredicatesFragmentDoc = gql`
263
279
  fragment inputEstimatePredicatesFragment on Input {
264
280
  ... on InputCoin {
@@ -346,7 +362,6 @@ var CoinFragmentDoc = gql`
346
362
  fragment coinFragment on Coin {
347
363
  type: __typename
348
364
  utxoId
349
- owner
350
365
  amount
351
366
  assetId
352
367
  blockCreated
@@ -370,10 +385,15 @@ var MessageFragmentDoc = gql`
370
385
  sender
371
386
  recipient
372
387
  data
373
- nonce
374
388
  daHeight
375
389
  }
376
390
  `;
391
+ var GetMessageFragmentDoc = gql`
392
+ fragment getMessageFragment on Message {
393
+ ...messageFragment
394
+ nonce
395
+ }
396
+ ${MessageFragmentDoc}`;
377
397
  var MessageProofFragmentDoc = gql`
378
398
  fragment messageProofFragment on MessageProof {
379
399
  messageProof {
@@ -418,7 +438,6 @@ var MessageProofFragmentDoc = gql`
418
438
  }
419
439
  sender
420
440
  recipient
421
- nonce
422
441
  amount
423
442
  data
424
443
  }
@@ -567,12 +586,6 @@ var RelayedTransactionStatusFragmentDoc = gql`
567
586
  }
568
587
  }
569
588
  `;
570
- var TransactionRawPayloadFragmentDoc = gql`
571
- fragment transactionRawPayload on Transaction {
572
- id
573
- rawPayload
574
- }
575
- `;
576
589
  var GetVersionDocument = gql`
577
590
  query getVersion {
578
591
  nodeInfo {
@@ -615,16 +628,34 @@ var GetTransactionDocument = gql`
615
628
  var GetTransactionWithReceiptsDocument = gql`
616
629
  query getTransactionWithReceipts($transactionId: TransactionId!) {
617
630
  transaction(id: $transactionId) {
618
- ...transactionFragment
631
+ id
632
+ rawPayload
633
+ status {
634
+ ... on SubmittedStatus {
635
+ ...SubmittedStatusFragment
636
+ }
637
+ ... on SuccessStatus {
638
+ ...SuccessStatusWithBlockIdFragment
639
+ }
640
+ ... on FailureStatus {
641
+ ...FailureStatusWithBlockIdFragment
642
+ }
643
+ ... on SqueezedOutStatus {
644
+ ...SqueezedOutStatusFragment
645
+ }
646
+ }
619
647
  }
620
648
  }
621
- ${TransactionFragmentDoc}`;
649
+ ${SubmittedStatusFragmentDoc}
650
+ ${SuccessStatusWithBlockIdFragmentDoc}
651
+ ${FailureStatusWithBlockIdFragmentDoc}
652
+ ${SqueezedOutStatusFragmentDoc}`;
622
653
  var GetTransactionsDocument = gql`
623
654
  query getTransactions($after: String, $before: String, $first: Int, $last: Int) {
624
655
  transactions(after: $after, before: $before, first: $first, last: $last) {
625
656
  edges {
626
657
  node {
627
- ...transactionFragment
658
+ rawPayload
628
659
  }
629
660
  }
630
661
  pageInfo {
@@ -632,8 +663,7 @@ var GetTransactionsDocument = gql`
632
663
  }
633
664
  }
634
665
  }
635
- ${TransactionFragmentDoc}
636
- ${PageInfoFragmentDoc}`;
666
+ ${PageInfoFragmentDoc}`;
637
667
  var GetTransactionsByOwnerDocument = gql`
638
668
  query getTransactionsByOwner($owner: Address!, $after: String, $before: String, $first: Int, $last: Int) {
639
669
  transactionsByOwner(
@@ -692,7 +722,7 @@ var GetBlockWithTransactionsDocument = gql`
692
722
  block(id: $blockId, height: $blockHeight) {
693
723
  ...blockFragment
694
724
  transactions {
695
- ...transactionRawPayload
725
+ ...transactionRawPayloadFragment
696
726
  }
697
727
  }
698
728
  }
@@ -717,6 +747,7 @@ var GetCoinDocument = gql`
717
747
  query getCoin($coinId: UtxoId!) {
718
748
  coin(utxoId: $coinId) {
719
749
  ...coinFragment
750
+ owner
720
751
  }
721
752
  }
722
753
  ${CoinFragmentDoc}`;
@@ -825,13 +856,13 @@ var GetMessagesDocument = gql`
825
856
  }
826
857
  edges {
827
858
  node {
828
- ...messageFragment
859
+ ...getMessageFragment
829
860
  }
830
861
  }
831
862
  }
832
863
  }
833
864
  ${PageInfoFragmentDoc}
834
- ${MessageFragmentDoc}`;
865
+ ${GetMessageFragmentDoc}`;
835
866
  var GetMessageProofDocument = gql`
836
867
  query getMessageProof($transactionId: TransactionId!, $nonce: Nonce!, $commitBlockId: BlockId, $commitBlockHeight: U32) {
837
868
  messageProof(
@@ -904,6 +935,17 @@ var IsUserAccountDocument = gql`
904
935
  }
905
936
  }
906
937
  `;
938
+ var GetConsensusParametersVersionDocument = gql`
939
+ query getConsensusParametersVersion {
940
+ chain {
941
+ latestBlock {
942
+ header {
943
+ consensusParametersVersion
944
+ }
945
+ }
946
+ }
947
+ }
948
+ `;
907
949
  var SubmitAndAwaitDocument = gql`
908
950
  subscription submitAndAwait($encodedTransaction: HexString!) {
909
951
  submitAndAwait(tx: $encodedTransaction) {
@@ -1023,6 +1065,9 @@ function getSdk(requester) {
1023
1065
  isUserAccount(variables, options) {
1024
1066
  return requester(IsUserAccountDocument, variables, options);
1025
1067
  },
1068
+ getConsensusParametersVersion(variables, options) {
1069
+ return requester(GetConsensusParametersVersionDocument, variables, options);
1070
+ },
1026
1071
  submitAndAwait(variables, options) {
1027
1072
  return requester(SubmitAndAwaitDocument, variables, options);
1028
1073
  },
@@ -1358,9 +1403,11 @@ function assembleReceiptByType(receipt) {
1358
1403
  const { receiptType } = receipt;
1359
1404
  switch (receiptType) {
1360
1405
  case "CALL" /* Call */: {
1406
+ const id = hexOrZero(receipt.id || receipt.contractId);
1361
1407
  const callReceipt = {
1362
1408
  type: ReceiptType.Call,
1363
- from: hexOrZero(receipt.id || receipt.contractId),
1409
+ id,
1410
+ from: id,
1364
1411
  to: hexOrZero(receipt?.to),
1365
1412
  amount: bn4(receipt.amount),
1366
1413
  assetId: hexOrZero(receipt.assetId),
@@ -1417,24 +1464,36 @@ function assembleReceiptByType(receipt) {
1417
1464
  return revertReceipt;
1418
1465
  }
1419
1466
  case "LOG" /* Log */: {
1467
+ const ra = bn4(receipt.ra);
1468
+ const rb = bn4(receipt.rb);
1469
+ const rc = bn4(receipt.rc);
1470
+ const rd = bn4(receipt.rd);
1420
1471
  const logReceipt = {
1421
1472
  type: ReceiptType.Log,
1422
1473
  id: hexOrZero(receipt.id || receipt.contractId),
1423
- val0: bn4(receipt.ra),
1424
- val1: bn4(receipt.rb),
1425
- val2: bn4(receipt.rc),
1426
- val3: bn4(receipt.rd),
1474
+ ra,
1475
+ rb,
1476
+ rc,
1477
+ rd,
1478
+ val0: ra,
1479
+ val1: rb,
1480
+ val2: rc,
1481
+ val3: rd,
1427
1482
  pc: bn4(receipt.pc),
1428
1483
  is: bn4(receipt.is)
1429
1484
  };
1430
1485
  return logReceipt;
1431
1486
  }
1432
1487
  case "LOG_DATA" /* LogData */: {
1488
+ const ra = bn4(receipt.ra);
1489
+ const rb = bn4(receipt.rb);
1433
1490
  const logDataReceipt = {
1434
1491
  type: ReceiptType.LogData,
1435
1492
  id: hexOrZero(receipt.id || receipt.contractId),
1436
- val0: bn4(receipt.ra),
1437
- val1: bn4(receipt.rb),
1493
+ ra,
1494
+ rb,
1495
+ val0: ra,
1496
+ val1: rb,
1438
1497
  ptr: bn4(receipt.ptr),
1439
1498
  len: bn4(receipt.len),
1440
1499
  digest: hexOrZero(receipt.digest),
@@ -1445,9 +1504,11 @@ function assembleReceiptByType(receipt) {
1445
1504
  return logDataReceipt;
1446
1505
  }
1447
1506
  case "TRANSFER" /* Transfer */: {
1507
+ const id = hexOrZero(receipt.id || receipt.contractId);
1448
1508
  const transferReceipt = {
1449
1509
  type: ReceiptType.Transfer,
1450
- from: hexOrZero(receipt.id || receipt.contractId),
1510
+ id,
1511
+ from: id,
1451
1512
  to: hexOrZero(receipt.toAddress || receipt?.to),
1452
1513
  amount: bn4(receipt.amount),
1453
1514
  assetId: hexOrZero(receipt.assetId),
@@ -1457,9 +1518,11 @@ function assembleReceiptByType(receipt) {
1457
1518
  return transferReceipt;
1458
1519
  }
1459
1520
  case "TRANSFER_OUT" /* TransferOut */: {
1521
+ const id = hexOrZero(receipt.id || receipt.contractId);
1460
1522
  const transferOutReceipt = {
1461
1523
  type: ReceiptType.TransferOut,
1462
- from: hexOrZero(receipt.id || receipt.contractId),
1524
+ id,
1525
+ from: id,
1463
1526
  to: hexOrZero(receipt.toAddress || receipt.to),
1464
1527
  amount: bn4(receipt.amount),
1465
1528
  assetId: hexOrZero(receipt.assetId),
@@ -2529,7 +2592,7 @@ var BlobTransactionRequest = class extends BaseTransactionRequest {
2529
2592
  type = TransactionType.Blob;
2530
2593
  /** Blob ID */
2531
2594
  blobId;
2532
- /** Witness index of contract bytecode to create */
2595
+ /** Witness index of the bytecode to create */
2533
2596
  witnessIndex;
2534
2597
  /**
2535
2598
  * Creates an instance `BlobTransactionRequest`.
@@ -3916,14 +3979,14 @@ var processGraphqlStatus = (gqlTransactionStatus) => {
3916
3979
  switch (gqlTransactionStatus.type) {
3917
3980
  case "SuccessStatus":
3918
3981
  time = gqlTransactionStatus.time;
3919
- blockId = gqlTransactionStatus.block.id;
3982
+ blockId = gqlTransactionStatus.block?.id;
3920
3983
  isStatusSuccess = true;
3921
3984
  totalFee = bn14(gqlTransactionStatus.totalFee);
3922
3985
  totalGas = bn14(gqlTransactionStatus.totalGas);
3923
3986
  break;
3924
3987
  case "FailureStatus":
3925
3988
  time = gqlTransactionStatus.time;
3926
- blockId = gqlTransactionStatus.block.id;
3989
+ blockId = gqlTransactionStatus.block?.id;
3927
3990
  isStatusFailure = true;
3928
3991
  totalFee = bn14(gqlTransactionStatus.totalFee);
3929
3992
  totalGas = bn14(gqlTransactionStatus.totalGas);
@@ -4234,8 +4297,8 @@ var TransactionResponse = class {
4234
4297
  const subscription = this.submitTxSubscription ?? await this.provider.operations.statusChange({
4235
4298
  transactionId: this.id
4236
4299
  });
4237
- for await (const sub of subscription) {
4238
- const statusChange = "statusChange" in sub ? sub.statusChange : sub.submitAndAwaitStatus;
4300
+ for await (const sub2 of subscription) {
4301
+ const statusChange = "statusChange" in sub2 ? sub2.statusChange : sub2.submitAndAwaitStatus;
4239
4302
  this.status = statusChange;
4240
4303
  if (statusChange.type === "SqueezedOutStatus") {
4241
4304
  this.unsetResourceCache();
@@ -4358,17 +4421,60 @@ var handleGqlErrorMessage = (errorMessage, rawError) => {
4358
4421
  {},
4359
4422
  rawError
4360
4423
  );
4424
+ case "max number of coins is reached while trying to fit the target" /* MAX_COINS_REACHED */:
4425
+ throw new FuelError15(
4426
+ ErrorCode13.MAX_COINS_REACHED,
4427
+ "The account retrieving coins has exceeded the maximum number of coins per asset. Please consider combining your coins into a single UTXO.",
4428
+ {},
4429
+ rawError
4430
+ );
4361
4431
  default:
4362
4432
  throw new FuelError15(ErrorCode13.INVALID_REQUEST, errorMessage);
4363
4433
  }
4364
4434
  };
4365
4435
 
4436
+ // src/providers/utils/validate-pagination-args.ts
4437
+ import { FuelError as FuelError16, ErrorCode as ErrorCode14 } from "@fuel-ts/errors";
4438
+ var validatePaginationArgs = (params) => {
4439
+ const { paginationLimit, inputArgs = {} } = params;
4440
+ const { first, last, after, before } = inputArgs;
4441
+ if (after && before) {
4442
+ throw new FuelError16(
4443
+ ErrorCode14.INVALID_INPUT_PARAMETERS,
4444
+ 'Pagination arguments "after" and "before" cannot be used together'
4445
+ );
4446
+ }
4447
+ if ((first || 0) > paginationLimit || (last || 0) > paginationLimit) {
4448
+ throw new FuelError16(
4449
+ ErrorCode14.INVALID_INPUT_PARAMETERS,
4450
+ `Pagination limit for this query cannot exceed ${paginationLimit} items`
4451
+ );
4452
+ }
4453
+ if (first && before) {
4454
+ throw new FuelError16(
4455
+ ErrorCode14.INVALID_INPUT_PARAMETERS,
4456
+ 'The use of pagination argument "first" with "before" is not supported'
4457
+ );
4458
+ }
4459
+ if (last && after) {
4460
+ throw new FuelError16(
4461
+ ErrorCode14.INVALID_INPUT_PARAMETERS,
4462
+ 'The use of pagination argument "last" with "after" is not supported'
4463
+ );
4464
+ }
4465
+ if (!first && !last) {
4466
+ inputArgs.first = paginationLimit;
4467
+ }
4468
+ return inputArgs;
4469
+ };
4470
+
4366
4471
  // src/providers/provider.ts
4367
4472
  var MAX_RETRIES = 10;
4368
4473
  var RESOURCES_PAGE_SIZE_LIMIT = 512;
4369
4474
  var TRANSACTIONS_PAGE_SIZE_LIMIT = 60;
4370
4475
  var BLOCKS_PAGE_SIZE_LIMIT = 5;
4371
4476
  var DEFAULT_RESOURCE_CACHE_TTL = 2e4;
4477
+ var GAS_USED_MODIFIER = 1.2;
4372
4478
  var processGqlChain = (chain) => {
4373
4479
  const { name, daHeight, consensusParameters } = chain;
4374
4480
  const {
@@ -4444,6 +4550,8 @@ var _Provider = class {
4444
4550
  __publicField(this, "url");
4445
4551
  /** @hidden */
4446
4552
  __publicField(this, "urlWithoutAuth");
4553
+ /** @hidden */
4554
+ __publicField(this, "consensusParametersTimestamp");
4447
4555
  __publicField(this, "options", {
4448
4556
  timeout: void 0,
4449
4557
  resourceCacheTTL: void 0,
@@ -4504,7 +4612,7 @@ var _Provider = class {
4504
4612
  try {
4505
4613
  parsedUrl = new URL(url);
4506
4614
  } catch (error) {
4507
- throw new FuelError16(FuelError16.CODES.INVALID_URL, "Invalid URL provided.", { url }, error);
4615
+ throw new FuelError17(FuelError17.CODES.INVALID_URL, "Invalid URL provided.", { url }, error);
4508
4616
  }
4509
4617
  const username = parsedUrl.username;
4510
4618
  const password = parsedUrl.password;
@@ -4539,8 +4647,8 @@ var _Provider = class {
4539
4647
  getChain() {
4540
4648
  const chain = _Provider.chainInfoCache[this.urlWithoutAuth];
4541
4649
  if (!chain) {
4542
- throw new FuelError16(
4543
- ErrorCode14.CHAIN_INFO_CACHE_EMPTY,
4650
+ throw new FuelError17(
4651
+ ErrorCode15.CHAIN_INFO_CACHE_EMPTY,
4544
4652
  "Chain info cache is empty. Make sure you have called `Provider.create` to initialize the provider."
4545
4653
  );
4546
4654
  }
@@ -4554,8 +4662,8 @@ var _Provider = class {
4554
4662
  getNode() {
4555
4663
  const node = _Provider.nodeInfoCache[this.urlWithoutAuth];
4556
4664
  if (!node) {
4557
- throw new FuelError16(
4558
- ErrorCode14.NODE_INFO_CACHE_EMPTY,
4665
+ throw new FuelError17(
4666
+ ErrorCode15.NODE_INFO_CACHE_EMPTY,
4559
4667
  "Node info cache is empty. Make sure you have called `Provider.create` to initialize the provider."
4560
4668
  );
4561
4669
  }
@@ -4596,16 +4704,19 @@ var _Provider = class {
4596
4704
  }
4597
4705
  /**
4598
4706
  * Return the chain and node information.
4599
- *
4707
+ * @param ignoreCache - If true, ignores the cache and re-fetch configs.
4600
4708
  * @returns A promise that resolves to the Chain and NodeInfo.
4601
4709
  */
4602
- async fetchChainAndNodeInfo() {
4710
+ async fetchChainAndNodeInfo(ignoreCache = false) {
4603
4711
  let nodeInfo;
4604
4712
  let chain;
4605
4713
  try {
4714
+ if (ignoreCache) {
4715
+ throw new Error(`Jumps to the catch block andre-fetch`);
4716
+ }
4606
4717
  nodeInfo = this.getNode();
4607
4718
  chain = this.getChain();
4608
- } catch (error) {
4719
+ } catch (_err) {
4609
4720
  const data = await this.operations.getChainAndNodeInfo();
4610
4721
  nodeInfo = {
4611
4722
  maxDepth: bn17(data.nodeInfo.maxDepth),
@@ -4618,6 +4729,7 @@ var _Provider = class {
4618
4729
  chain = processGqlChain(data.chain);
4619
4730
  _Provider.chainInfoCache[this.urlWithoutAuth] = chain;
4620
4731
  _Provider.nodeInfoCache[this.urlWithoutAuth] = nodeInfo;
4732
+ this.consensusParametersTimestamp = Date.now();
4621
4733
  }
4622
4734
  return {
4623
4735
  chain,
@@ -4767,18 +4879,25 @@ Supported fuel-core version: ${supportedVersion}.`
4767
4879
  } = this.getChain();
4768
4880
  return baseAssetId;
4769
4881
  }
4770
- validateTransaction(tx, consensusParameters) {
4771
- const { maxOutputs, maxInputs } = consensusParameters.txParameters;
4882
+ /**
4883
+ * @hidden
4884
+ */
4885
+ validateTransaction(tx) {
4886
+ const {
4887
+ consensusParameters: {
4888
+ txParameters: { maxInputs, maxOutputs }
4889
+ }
4890
+ } = this.getChain();
4772
4891
  if (bn17(tx.inputs.length).gt(maxInputs)) {
4773
- throw new FuelError16(
4774
- ErrorCode14.MAX_INPUTS_EXCEEDED,
4775
- "The transaction exceeds the maximum allowed number of inputs."
4892
+ throw new FuelError17(
4893
+ ErrorCode15.MAX_INPUTS_EXCEEDED,
4894
+ `The transaction exceeds the maximum allowed number of inputs. Tx inputs: ${tx.inputs.length}, max inputs: ${maxInputs}`
4776
4895
  );
4777
4896
  }
4778
4897
  if (bn17(tx.outputs.length).gt(maxOutputs)) {
4779
- throw new FuelError16(
4780
- ErrorCode14.MAX_OUTPUTS_EXCEEDED,
4781
- "The transaction exceeds the maximum allowed number of outputs."
4898
+ throw new FuelError17(
4899
+ ErrorCode15.MAX_OUTPUTS_EXCEEDED,
4900
+ `The transaction exceeds the maximum allowed number of outputs. Tx outputs: ${tx.outputs.length}, max outputs: ${maxOutputs}`
4782
4901
  );
4783
4902
  }
4784
4903
  }
@@ -4797,8 +4916,7 @@ Supported fuel-core version: ${supportedVersion}.`
4797
4916
  if (estimateTxDependencies) {
4798
4917
  await this.estimateTxDependencies(transactionRequest);
4799
4918
  }
4800
- const { consensusParameters } = this.getChain();
4801
- this.validateTransaction(transactionRequest, consensusParameters);
4919
+ this.validateTransaction(transactionRequest);
4802
4920
  const encodedTransaction = hexlify15(transactionRequest.toTransactionBytes());
4803
4921
  let abis;
4804
4922
  if (isTransactionTypeScript(transactionRequest)) {
@@ -4886,6 +5004,7 @@ Supported fuel-core version: ${supportedVersion}.`
4886
5004
  const missingContractIds = [];
4887
5005
  let outputVariables = 0;
4888
5006
  let dryRunStatus;
5007
+ this.validateTransaction(transactionRequest);
4889
5008
  for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
4890
5009
  const {
4891
5010
  dryRun: [{ receipts: rawReceipts, status }]
@@ -5008,6 +5127,27 @@ Supported fuel-core version: ${supportedVersion}.`
5008
5127
  });
5009
5128
  return results;
5010
5129
  }
5130
+ async autoRefetchConfigs() {
5131
+ const now = Date.now();
5132
+ const diff = now - (this.consensusParametersTimestamp ?? 0);
5133
+ if (diff < 6e4) {
5134
+ return;
5135
+ }
5136
+ const chainInfo = this.getChain();
5137
+ const {
5138
+ consensusParameters: { version: previous }
5139
+ } = chainInfo;
5140
+ const {
5141
+ chain: {
5142
+ latestBlock: {
5143
+ header: { consensusParametersVersion: current }
5144
+ }
5145
+ }
5146
+ } = await this.operations.getConsensusParametersVersion();
5147
+ if (previous !== current) {
5148
+ await this.fetchChainAndNodeInfo(true);
5149
+ }
5150
+ }
5011
5151
  /**
5012
5152
  * Estimates the transaction gas and fee based on the provided transaction request.
5013
5153
  * @param transactionRequest - The transaction request object.
@@ -5016,6 +5156,7 @@ Supported fuel-core version: ${supportedVersion}.`
5016
5156
  async estimateTxGasAndFee(params) {
5017
5157
  const { transactionRequest } = params;
5018
5158
  let { gasPrice } = params;
5159
+ await this.autoRefetchConfigs();
5019
5160
  const chainInfo = this.getChain();
5020
5161
  const { gasPriceFactor, maxGasPerTx } = this.getGasConfig();
5021
5162
  const minGas = transactionRequest.calculateMinGas(chainInfo);
@@ -5129,7 +5270,9 @@ Supported fuel-core version: ${supportedVersion}.`
5129
5270
  if (dryRunStatus && "reason" in dryRunStatus) {
5130
5271
  throw this.extractDryRunError(txRequestClone, receipts, dryRunStatus);
5131
5272
  }
5132
- gasUsed = getGasUsedFromReceipts(receipts);
5273
+ const { maxGasPerTx } = this.getGasConfig();
5274
+ const pristineGasUsed = getGasUsedFromReceipts(receipts);
5275
+ gasUsed = bn17(pristineGasUsed.muln(GAS_USED_MODIFIER)).max(maxGasPerTx.sub(minGas));
5133
5276
  txRequestClone.gasLimit = gasUsed;
5134
5277
  ({ maxFee, maxGas, minFee, minGas, gasPrice } = await this.estimateTxGasAndFee({
5135
5278
  transactionRequest: txRequestClone,
@@ -5166,7 +5309,7 @@ Supported fuel-core version: ${supportedVersion}.`
5166
5309
  const {
5167
5310
  coins: { edges, pageInfo }
5168
5311
  } = await this.operations.getCoins({
5169
- ...this.validatePaginationArgs({
5312
+ ...validatePaginationArgs({
5170
5313
  paginationLimit: RESOURCES_PAGE_SIZE_LIMIT,
5171
5314
  inputArgs: paginationArgs
5172
5315
  }),
@@ -5176,7 +5319,7 @@ Supported fuel-core version: ${supportedVersion}.`
5176
5319
  id: node.utxoId,
5177
5320
  assetId: node.assetId,
5178
5321
  amount: bn17(node.amount),
5179
- owner: Address2.fromAddressOrString(node.owner),
5322
+ owner: ownerAddress,
5180
5323
  blockCreated: bn17(node.blockCreated),
5181
5324
  txCreatedIdx: bn17(node.txCreatedIdx)
5182
5325
  }));
@@ -5230,7 +5373,7 @@ Supported fuel-core version: ${supportedVersion}.`
5230
5373
  id: coin.utxoId,
5231
5374
  amount: bn17(coin.amount),
5232
5375
  assetId: coin.assetId,
5233
- owner: Address2.fromAddressOrString(coin.owner),
5376
+ owner: ownerAddress,
5234
5377
  blockCreated: bn17(coin.blockCreated),
5235
5378
  txCreatedIdx: bn17(coin.txCreatedIdx)
5236
5379
  };
@@ -5305,7 +5448,7 @@ Supported fuel-core version: ${supportedVersion}.`
5305
5448
  const {
5306
5449
  blocks: { edges, pageInfo }
5307
5450
  } = await this.operations.getBlocks({
5308
- ...this.validatePaginationArgs({
5451
+ ...validatePaginationArgs({
5309
5452
  paginationLimit: BLOCKS_PAGE_SIZE_LIMIT,
5310
5453
  inputArgs: params
5311
5454
  })
@@ -5384,7 +5527,7 @@ Supported fuel-core version: ${supportedVersion}.`
5384
5527
  0
5385
5528
  )?.[0];
5386
5529
  } catch (error) {
5387
- if (error instanceof FuelError16 && error.code === ErrorCode14.UNSUPPORTED_TRANSACTION_TYPE) {
5530
+ if (error instanceof FuelError17 && error.code === ErrorCode15.UNSUPPORTED_TRANSACTION_TYPE) {
5388
5531
  console.warn("Unsupported transaction type encountered");
5389
5532
  return null;
5390
5533
  }
@@ -5400,7 +5543,7 @@ Supported fuel-core version: ${supportedVersion}.`
5400
5543
  const {
5401
5544
  transactions: { edges, pageInfo }
5402
5545
  } = await this.operations.getTransactions({
5403
- ...this.validatePaginationArgs({
5546
+ ...validatePaginationArgs({
5404
5547
  inputArgs: paginationArgs,
5405
5548
  paginationLimit: TRANSACTIONS_PAGE_SIZE_LIMIT
5406
5549
  })
@@ -5410,7 +5553,7 @@ Supported fuel-core version: ${supportedVersion}.`
5410
5553
  try {
5411
5554
  return coder.decode(arrayify12(rawPayload), 0)[0];
5412
5555
  } catch (error) {
5413
- if (error instanceof FuelError16 && error.code === ErrorCode14.UNSUPPORTED_TRANSACTION_TYPE) {
5556
+ if (error instanceof FuelError17 && error.code === ErrorCode15.UNSUPPORTED_TRANSACTION_TYPE) {
5414
5557
  console.warn("Unsupported transaction type encountered");
5415
5558
  return null;
5416
5559
  }
@@ -5495,7 +5638,7 @@ Supported fuel-core version: ${supportedVersion}.`
5495
5638
  const {
5496
5639
  messages: { edges, pageInfo }
5497
5640
  } = await this.operations.getMessages({
5498
- ...this.validatePaginationArgs({
5641
+ ...validatePaginationArgs({
5499
5642
  inputArgs: paginationArgs,
5500
5643
  paginationLimit: RESOURCES_PAGE_SIZE_LIMIT
5501
5644
  }),
@@ -5536,8 +5679,8 @@ Supported fuel-core version: ${supportedVersion}.`
5536
5679
  nonce
5537
5680
  };
5538
5681
  if (commitBlockId && commitBlockHeight) {
5539
- throw new FuelError16(
5540
- ErrorCode14.INVALID_INPUT_PARAMETERS,
5682
+ throw new FuelError17(
5683
+ ErrorCode15.INVALID_INPUT_PARAMETERS,
5541
5684
  "commitBlockId and commitBlockHeight cannot be used together"
5542
5685
  );
5543
5686
  }
@@ -5719,13 +5862,13 @@ Supported fuel-core version: ${supportedVersion}.`
5719
5862
  messageId: InputMessageCoder2.getMessageId({
5720
5863
  sender: rawMessage.sender,
5721
5864
  recipient: rawMessage.recipient,
5722
- nonce: rawMessage.nonce,
5865
+ nonce,
5723
5866
  amount: bn17(rawMessage.amount),
5724
5867
  data: rawMessage.data
5725
5868
  }),
5726
5869
  sender: Address2.fromAddressOrString(rawMessage.sender),
5727
5870
  recipient: Address2.fromAddressOrString(rawMessage.recipient),
5728
- nonce: rawMessage.nonce,
5871
+ nonce,
5729
5872
  amount: bn17(rawMessage.amount),
5730
5873
  data: InputMessageCoder2.decodeData(rawMessage.data),
5731
5874
  daHeight: bn17(rawMessage.daHeight)
@@ -5747,41 +5890,6 @@ Supported fuel-core version: ${supportedVersion}.`
5747
5890
  }
5748
5891
  return relayedTransactionStatus;
5749
5892
  }
5750
- /**
5751
- * @hidden
5752
- */
5753
- validatePaginationArgs(params) {
5754
- const { paginationLimit, inputArgs = {} } = params;
5755
- const { first, last, after, before } = inputArgs;
5756
- if (after && before) {
5757
- throw new FuelError16(
5758
- ErrorCode14.INVALID_INPUT_PARAMETERS,
5759
- 'Pagination arguments "after" and "before" cannot be used together'
5760
- );
5761
- }
5762
- if ((first || 0) > paginationLimit || (last || 0) > paginationLimit) {
5763
- throw new FuelError16(
5764
- ErrorCode14.INVALID_INPUT_PARAMETERS,
5765
- `Pagination limit for this query cannot exceed ${paginationLimit} items`
5766
- );
5767
- }
5768
- if (first && before) {
5769
- throw new FuelError16(
5770
- ErrorCode14.INVALID_INPUT_PARAMETERS,
5771
- 'The use of pagination argument "first" with "before" is not supported'
5772
- );
5773
- }
5774
- if (last && after) {
5775
- throw new FuelError16(
5776
- ErrorCode14.INVALID_INPUT_PARAMETERS,
5777
- 'The use of pagination argument "last" with "after" is not supported'
5778
- );
5779
- }
5780
- if (!first && !last) {
5781
- inputArgs.first = paginationLimit;
5782
- }
5783
- return inputArgs;
5784
- }
5785
5893
  /**
5786
5894
  * @hidden
5787
5895
  */
@@ -5827,7 +5935,7 @@ __publicField(Provider, "chainInfoCache", {});
5827
5935
  __publicField(Provider, "nodeInfoCache", {});
5828
5936
 
5829
5937
  // src/providers/transaction-summary/get-transaction-summary.ts
5830
- import { ErrorCode as ErrorCode15, FuelError as FuelError17 } from "@fuel-ts/errors";
5938
+ import { ErrorCode as ErrorCode16, FuelError as FuelError18 } from "@fuel-ts/errors";
5831
5939
  import { bn as bn18 } from "@fuel-ts/math";
5832
5940
  import { TransactionCoder as TransactionCoder6 } from "@fuel-ts/transactions";
5833
5941
  import { arrayify as arrayify13 } from "@fuel-ts/utils";
@@ -5837,8 +5945,8 @@ async function getTransactionSummary(params) {
5837
5945
  transactionId: id
5838
5946
  });
5839
5947
  if (!gqlTransaction) {
5840
- throw new FuelError17(
5841
- ErrorCode15.TRANSACTION_NOT_FOUND,
5948
+ throw new FuelError18(
5949
+ ErrorCode16.TRANSACTION_NOT_FOUND,
5842
5950
  `Transaction not found for given id: ${id}.`
5843
5951
  );
5844
5952
  }
@@ -5906,7 +6014,15 @@ async function getTransactionSummaryFromRequest(params) {
5906
6014
  }
5907
6015
  async function getTransactionsSummaries(params) {
5908
6016
  const { filters, provider, abiMap } = params;
5909
- const { transactionsByOwner } = await provider.operations.getTransactionsByOwner(filters);
6017
+ const { owner, ...inputArgs } = filters;
6018
+ const validPaginationParams = validatePaginationArgs({
6019
+ inputArgs,
6020
+ paginationLimit: TRANSACTIONS_PAGE_SIZE_LIMIT
6021
+ });
6022
+ const { transactionsByOwner } = await provider.operations.getTransactionsByOwner({
6023
+ ...validPaginationParams,
6024
+ owner
6025
+ });
5910
6026
  const { edges, pageInfo } = transactionsByOwner;
5911
6027
  const {
5912
6028
  consensusParameters: {
@@ -6625,38 +6741,47 @@ var mergeQuantities = (...coinQuantities) => {
6625
6741
  };
6626
6742
 
6627
6743
  // src/utils/formatTransferToContractScriptData.ts
6628
- import { BigNumberCoder as BigNumberCoder2 } from "@fuel-ts/abi-coder";
6744
+ import { ASSET_ID_LEN, BigNumberCoder as BigNumberCoder2, CONTRACT_ID_LEN, WORD_SIZE } from "@fuel-ts/abi-coder";
6745
+ import { Address as Address3 } from "@fuel-ts/address";
6629
6746
  import { BN as BN3 } from "@fuel-ts/math";
6630
- import { arrayify as arrayify14 } from "@fuel-ts/utils";
6747
+ import { arrayify as arrayify14, concat as concat3 } from "@fuel-ts/utils";
6631
6748
  import * as asm from "@fuels/vm-asm";
6632
- var formatTransferToContractScriptData = (params) => {
6633
- const { assetId, amountToTransfer, hexlifiedContractId } = params;
6749
+ var formatTransferToContractScriptData = (transferParams) => {
6634
6750
  const numberCoder = new BigNumberCoder2("u64");
6635
- const encoded = numberCoder.encode(new BN3(amountToTransfer).toNumber());
6636
- const scriptData = Uint8Array.from([
6637
- ...arrayify14(hexlifiedContractId),
6638
- ...encoded,
6639
- ...arrayify14(assetId)
6640
- ]);
6641
- return scriptData;
6751
+ return transferParams.reduce((acc, transferParam) => {
6752
+ const { assetId, amount, contractId } = transferParam;
6753
+ const encoded = numberCoder.encode(new BN3(amount).toNumber());
6754
+ const scriptData = concat3([
6755
+ Address3.fromAddressOrString(contractId).toBytes(),
6756
+ encoded,
6757
+ arrayify14(assetId)
6758
+ ]);
6759
+ return concat3([acc, scriptData]);
6760
+ }, new Uint8Array());
6642
6761
  };
6643
- var assembleTransferToContractScript = async (params) => {
6644
- const scriptData = formatTransferToContractScriptData(params);
6762
+ var assembleTransferToContractScript = async (transferParams) => {
6763
+ const scriptData = formatTransferToContractScriptData(transferParams);
6645
6764
  await asm.initWasm();
6646
- const gtf2 = asm.gtf(16, 0, asm.GTFArgs.ScriptData);
6647
- const addi2 = asm.addi(17, 16, 32);
6648
- const lw2 = asm.lw(18, 17, 0);
6649
- const addi22 = asm.addi(19, 17, 8);
6650
- const tr2 = asm.tr(16, 18, 19);
6651
- const ret2 = asm.ret(1);
6652
- const script = Uint8Array.from([
6653
- ...gtf2.to_bytes(),
6654
- ...addi2.to_bytes(),
6655
- ...lw2.to_bytes(),
6656
- ...addi22.to_bytes(),
6657
- ...tr2.to_bytes(),
6658
- ...ret2.to_bytes()
6659
- ]);
6765
+ let script = new Uint8Array();
6766
+ transferParams.forEach((_, i) => {
6767
+ const offset = (CONTRACT_ID_LEN + WORD_SIZE + ASSET_ID_LEN) * i;
6768
+ script = concat3([
6769
+ script,
6770
+ // Load ScriptData into register 0x10.
6771
+ asm.gtf(16, 0, asm.GTFArgs.ScriptData).to_bytes(),
6772
+ // Add the offset to 0x10 so it will point to the current contract ID, store in 0x11.
6773
+ asm.addi(17, 16, offset).to_bytes(),
6774
+ // Add CONTRACT_ID_LEN to 0x11 to point to the amount in the ScriptData, store in 0x12.
6775
+ asm.addi(18, 17, CONTRACT_ID_LEN).to_bytes(),
6776
+ // Load word to the amount at 0x12 into register 0x13.
6777
+ asm.lw(19, 18, 0).to_bytes(),
6778
+ // Add WORD_SIZE to 0x12 to point to the asset ID in the ScriptData, store in 0x14.
6779
+ asm.addi(20, 18, WORD_SIZE).to_bytes(),
6780
+ // Perform the transfer using contract ID in 0x11, amount in 0x13, and asset ID in 0x14.
6781
+ asm.tr(17, 19, 20).to_bytes()
6782
+ ]);
6783
+ });
6784
+ script = concat3([script, asm.ret(1).to_bytes()]);
6660
6785
  return { script, scriptData };
6661
6786
  };
6662
6787
 
@@ -6686,7 +6811,7 @@ var Account = class extends AbstractAccount {
6686
6811
  super();
6687
6812
  this._provider = provider;
6688
6813
  this._connector = connector;
6689
- this.address = Address3.fromDynamicInput(address);
6814
+ this.address = Address4.fromDynamicInput(address);
6690
6815
  }
6691
6816
  /**
6692
6817
  * The provider used to interact with the network.
@@ -6697,7 +6822,7 @@ var Account = class extends AbstractAccount {
6697
6822
  */
6698
6823
  get provider() {
6699
6824
  if (!this._provider) {
6700
- throw new FuelError18(ErrorCode16.MISSING_PROVIDER, "Provider not set");
6825
+ throw new FuelError19(ErrorCode17.MISSING_PROVIDER, "Provider not set");
6701
6826
  }
6702
6827
  return this._provider;
6703
6828
  }
@@ -6848,11 +6973,12 @@ var Account = class extends AbstractAccount {
6848
6973
  fundingAttempts += 1;
6849
6974
  }
6850
6975
  if (needsToBeFunded) {
6851
- throw new FuelError18(
6852
- ErrorCode16.NOT_ENOUGH_FUNDS,
6976
+ throw new FuelError19(
6977
+ ErrorCode17.NOT_ENOUGH_FUNDS,
6853
6978
  `The account ${this.address} does not have enough base asset funds to cover the transaction execution.`
6854
6979
  );
6855
6980
  }
6981
+ this.provider.validateTransaction(request);
6856
6982
  request.updatePredicateGasUsed(estimatedPredicates);
6857
6983
  const requestToReestimate = clone9(request);
6858
6984
  if (addedSignatures) {
@@ -6919,7 +7045,7 @@ var Account = class extends AbstractAccount {
6919
7045
  const { destination, amount, assetId } = transferParams;
6920
7046
  this.validateTransferAmount(amount);
6921
7047
  request.addCoinOutput(
6922
- Address3.fromAddressOrString(destination),
7048
+ Address4.fromAddressOrString(destination),
6923
7049
  amount,
6924
7050
  assetId ?? this.provider.getBaseAssetId()
6925
7051
  );
@@ -6953,35 +7079,35 @@ var Account = class extends AbstractAccount {
6953
7079
  * @returns A promise that resolves to the transaction response.
6954
7080
  */
6955
7081
  async transferToContract(contractId, amount, assetId, txParams = {}) {
6956
- if (bn19(amount).lte(0)) {
6957
- throw new FuelError18(
6958
- ErrorCode16.INVALID_TRANSFER_AMOUNT,
6959
- "Transfer amount must be a positive number."
6960
- );
6961
- }
6962
- const contractAddress = Address3.fromAddressOrString(contractId);
6963
- const assetIdToTransfer = assetId ?? this.provider.getBaseAssetId();
6964
- const { script, scriptData } = await assembleTransferToContractScript({
6965
- hexlifiedContractId: contractAddress.toB256(),
6966
- amountToTransfer: bn19(amount),
6967
- assetId: assetIdToTransfer
6968
- });
7082
+ return this.batchTransferToContracts([{ amount, assetId, contractId }], txParams);
7083
+ }
7084
+ async batchTransferToContracts(contractTransferParams, txParams = {}) {
6969
7085
  let request = new ScriptTransactionRequest({
6970
- ...txParams,
6971
- script,
6972
- scriptData
6973
- });
6974
- request.addContractInputAndOutput(contractAddress);
6975
- const txCost = await this.getTransactionCost(request, {
6976
- quantities: [{ amount: bn19(amount), assetId: String(assetIdToTransfer) }]
7086
+ ...txParams
6977
7087
  });
6978
- request = this.validateGasLimitAndMaxFee({
6979
- transactionRequest: request,
6980
- gasUsed: txCost.gasUsed,
6981
- maxFee: txCost.maxFee,
6982
- txParams
7088
+ const quantities = [];
7089
+ const transferParams = contractTransferParams.map((transferParam) => {
7090
+ const amount = bn19(transferParam.amount);
7091
+ const contractAddress = Address4.fromAddressOrString(transferParam.contractId);
7092
+ const assetId = transferParam.assetId ? hexlify16(transferParam.assetId) : this.provider.getBaseAssetId();
7093
+ if (amount.lte(0)) {
7094
+ throw new FuelError19(
7095
+ ErrorCode17.INVALID_TRANSFER_AMOUNT,
7096
+ "Transfer amount must be a positive number."
7097
+ );
7098
+ }
7099
+ request.addContractInputAndOutput(contractAddress);
7100
+ quantities.push({ amount, assetId });
7101
+ return {
7102
+ amount,
7103
+ contractId: contractAddress.toB256(),
7104
+ assetId
7105
+ };
6983
7106
  });
6984
- await this.fund(request, txCost);
7107
+ const { script, scriptData } = await assembleTransferToContractScript(transferParams);
7108
+ request.script = script;
7109
+ request.scriptData = scriptData;
7110
+ request = await this.estimateAndFundTransaction(request, txParams, { quantities });
6985
7111
  return this.sendTransaction(request);
6986
7112
  }
6987
7113
  /**
@@ -6993,7 +7119,7 @@ var Account = class extends AbstractAccount {
6993
7119
  * @returns A promise that resolves to the transaction response.
6994
7120
  */
6995
7121
  async withdrawToBaseLayer(recipient, amount, txParams = {}) {
6996
- const recipientAddress = Address3.fromAddressOrString(recipient);
7122
+ const recipientAddress = Address4.fromAddressOrString(recipient);
6997
7123
  const recipientDataArray = arrayify15(
6998
7124
  "0x".concat(recipientAddress.toHexString().substring(2).padStart(64, "0"))
6999
7125
  );
@@ -7081,7 +7207,7 @@ var Account = class extends AbstractAccount {
7081
7207
  */
7082
7208
  async signMessage(message) {
7083
7209
  if (!this._connector) {
7084
- throw new FuelError18(ErrorCode16.MISSING_CONNECTOR, "A connector is required to sign messages.");
7210
+ throw new FuelError19(ErrorCode17.MISSING_CONNECTOR, "A connector is required to sign messages.");
7085
7211
  }
7086
7212
  return this._connector.signMessage(this.address.toString(), message);
7087
7213
  }
@@ -7093,8 +7219,8 @@ var Account = class extends AbstractAccount {
7093
7219
  */
7094
7220
  async signTransaction(transactionRequestLike) {
7095
7221
  if (!this._connector) {
7096
- throw new FuelError18(
7097
- ErrorCode16.MISSING_CONNECTOR,
7222
+ throw new FuelError19(
7223
+ ErrorCode17.MISSING_CONNECTOR,
7098
7224
  "A connector is required to sign transactions."
7099
7225
  );
7100
7226
  }
@@ -7153,16 +7279,16 @@ var Account = class extends AbstractAccount {
7153
7279
  /** @hidden * */
7154
7280
  validateTransferAmount(amount) {
7155
7281
  if (bn19(amount).lte(0)) {
7156
- throw new FuelError18(
7157
- ErrorCode16.INVALID_TRANSFER_AMOUNT,
7282
+ throw new FuelError19(
7283
+ ErrorCode17.INVALID_TRANSFER_AMOUNT,
7158
7284
  "Transfer amount must be a positive number."
7159
7285
  );
7160
7286
  }
7161
7287
  }
7162
7288
  /** @hidden * */
7163
- async estimateAndFundTransaction(transactionRequest, txParams) {
7289
+ async estimateAndFundTransaction(transactionRequest, txParams, costParams) {
7164
7290
  let request = transactionRequest;
7165
- const txCost = await this.getTransactionCost(request);
7291
+ const txCost = await this.getTransactionCost(request, costParams);
7166
7292
  request = this.validateGasLimitAndMaxFee({
7167
7293
  transactionRequest: request,
7168
7294
  gasUsed: txCost.gasUsed,
@@ -7183,16 +7309,16 @@ var Account = class extends AbstractAccount {
7183
7309
  if (!isDefined3(setGasLimit)) {
7184
7310
  request.gasLimit = gasUsed;
7185
7311
  } else if (gasUsed.gt(setGasLimit)) {
7186
- throw new FuelError18(
7187
- ErrorCode16.GAS_LIMIT_TOO_LOW,
7312
+ throw new FuelError19(
7313
+ ErrorCode17.GAS_LIMIT_TOO_LOW,
7188
7314
  `Gas limit '${setGasLimit}' is lower than the required: '${gasUsed}'.`
7189
7315
  );
7190
7316
  }
7191
7317
  if (!isDefined3(setMaxFee)) {
7192
7318
  request.maxFee = maxFee;
7193
7319
  } else if (maxFee.gt(setMaxFee)) {
7194
- throw new FuelError18(
7195
- ErrorCode16.MAX_FEE_TOO_LOW,
7320
+ throw new FuelError19(
7321
+ ErrorCode17.MAX_FEE_TOO_LOW,
7196
7322
  `Max fee '${setMaxFee}' is lower than the required: '${maxFee}'.`
7197
7323
  );
7198
7324
  }
@@ -7205,11 +7331,11 @@ import { hashMessage } from "@fuel-ts/hasher";
7205
7331
  import { hexlify as hexlify19 } from "@fuel-ts/utils";
7206
7332
 
7207
7333
  // src/signer/signer.ts
7208
- import { Address as Address4 } from "@fuel-ts/address";
7334
+ import { Address as Address5 } from "@fuel-ts/address";
7209
7335
  import { randomBytes as randomBytes3 } from "@fuel-ts/crypto";
7210
7336
  import { hash as hash2 } from "@fuel-ts/hasher";
7211
7337
  import { toBytes } from "@fuel-ts/math";
7212
- import { hexlify as hexlify17, concat as concat3, arrayify as arrayify16 } from "@fuel-ts/utils";
7338
+ import { hexlify as hexlify17, concat as concat4, arrayify as arrayify16 } from "@fuel-ts/utils";
7213
7339
  import { secp256k1 } from "@noble/curves/secp256k1";
7214
7340
  var Signer = class {
7215
7341
  address;
@@ -7232,7 +7358,7 @@ var Signer = class {
7232
7358
  this.privateKey = hexlify17(privateKeyBytes);
7233
7359
  this.publicKey = hexlify17(secp256k1.getPublicKey(privateKeyBytes, false).slice(1));
7234
7360
  this.compressedPublicKey = hexlify17(secp256k1.getPublicKey(privateKeyBytes, true));
7235
- this.address = Address4.fromPublicKey(this.publicKey);
7361
+ this.address = Address5.fromPublicKey(this.publicKey);
7236
7362
  }
7237
7363
  /**
7238
7364
  * Sign data using the Signer instance
@@ -7249,7 +7375,7 @@ var Signer = class {
7249
7375
  const r = toBytes(`0x${signature.r.toString(16)}`, 32);
7250
7376
  const s = toBytes(`0x${signature.s.toString(16)}`, 32);
7251
7377
  s[0] |= (signature.recovery || 0) << 7;
7252
- return hexlify17(concat3([r, s]));
7378
+ return hexlify17(concat4([r, s]));
7253
7379
  }
7254
7380
  /**
7255
7381
  * Add point on the current elliptic curve
@@ -7290,7 +7416,7 @@ var Signer = class {
7290
7416
  * @returns Address from signature
7291
7417
  */
7292
7418
  static recoverAddress(data, signature) {
7293
- return Address4.fromPublicKey(Signer.recoverPublicKey(data, signature));
7419
+ return Address5.fromPublicKey(Signer.recoverPublicKey(data, signature));
7294
7420
  }
7295
7421
  /**
7296
7422
  * Generate a random privateKey
@@ -7299,7 +7425,7 @@ var Signer = class {
7299
7425
  * @returns random 32-byte hashed
7300
7426
  */
7301
7427
  static generatePrivateKey(entropy) {
7302
- return entropy ? hash2(concat3([randomBytes3(32), arrayify16(entropy)])) : randomBytes3(32);
7428
+ return entropy ? hash2(concat4([randomBytes3(32), arrayify16(entropy)])) : randomBytes3(32);
7303
7429
  }
7304
7430
  /**
7305
7431
  * Extended publicKey from a compact publicKey
@@ -7314,7 +7440,7 @@ var Signer = class {
7314
7440
  };
7315
7441
 
7316
7442
  // src/wallet/keystore-wallet.ts
7317
- import { Address as Address5 } from "@fuel-ts/address";
7443
+ import { Address as Address6 } from "@fuel-ts/address";
7318
7444
  import {
7319
7445
  bufferFromString,
7320
7446
  keccak256,
@@ -7325,7 +7451,7 @@ import {
7325
7451
  encryptJsonWalletData,
7326
7452
  randomUUID
7327
7453
  } from "@fuel-ts/crypto";
7328
- import { ErrorCode as ErrorCode17, FuelError as FuelError19 } from "@fuel-ts/errors";
7454
+ import { ErrorCode as ErrorCode18, FuelError as FuelError20 } from "@fuel-ts/errors";
7329
7455
  import { hexlify as hexlify18 } from "@fuel-ts/utils";
7330
7456
  var DEFAULT_KDF_PARAMS_LOG_N = 13;
7331
7457
  var DEFAULT_KDF_PARAMS_R = 8;
@@ -7340,7 +7466,7 @@ var removeHexPrefix = (hexString) => {
7340
7466
  };
7341
7467
  async function encryptKeystoreWallet(privateKey, address, password) {
7342
7468
  const privateKeyBuffer = bufferFromString(removeHexPrefix(privateKey), "hex");
7343
- const ownerAddress = Address5.fromAddressOrString(address);
7469
+ const ownerAddress = Address6.fromAddressOrString(address);
7344
7470
  const salt = randomBytes4(DEFAULT_KEY_SIZE);
7345
7471
  const key = scrypt({
7346
7472
  password: bufferFromString(password),
@@ -7402,8 +7528,8 @@ async function decryptKeystoreWallet(jsonWallet, password) {
7402
7528
  const macHashUint8Array = keccak256(data);
7403
7529
  const macHash = stringFromBuffer(macHashUint8Array, "hex");
7404
7530
  if (mac !== macHash) {
7405
- throw new FuelError19(
7406
- ErrorCode17.INVALID_PASSWORD,
7531
+ throw new FuelError20(
7532
+ ErrorCode18.INVALID_PASSWORD,
7407
7533
  "Failed to decrypt the keystore wallet, the provided password is incorrect."
7408
7534
  );
7409
7535
  }
@@ -7533,16 +7659,16 @@ __publicField(BaseWalletUnlocked, "defaultPath", "m/44'/1179993420'/0'/0/0");
7533
7659
 
7534
7660
  // src/hdwallet/hdwallet.ts
7535
7661
  import { computeHmac as computeHmac2, ripemd160 } from "@fuel-ts/crypto";
7536
- import { ErrorCode as ErrorCode20, FuelError as FuelError22 } from "@fuel-ts/errors";
7662
+ import { ErrorCode as ErrorCode21, FuelError as FuelError23 } from "@fuel-ts/errors";
7537
7663
  import { sha256 as sha2564 } from "@fuel-ts/hasher";
7538
7664
  import { bn as bn20, toBytes as toBytes2, toHex } from "@fuel-ts/math";
7539
- import { arrayify as arrayify19, hexlify as hexlify21, concat as concat5, dataSlice as dataSlice2, encodeBase58 as encodeBase582, decodeBase58 } from "@fuel-ts/utils";
7665
+ import { arrayify as arrayify19, hexlify as hexlify21, concat as concat6, dataSlice as dataSlice2, encodeBase58 as encodeBase582, decodeBase58 } from "@fuel-ts/utils";
7540
7666
 
7541
7667
  // src/mnemonic/mnemonic.ts
7542
7668
  import { randomBytes as randomBytes5, pbkdf2, computeHmac } from "@fuel-ts/crypto";
7543
- import { ErrorCode as ErrorCode19, FuelError as FuelError21 } from "@fuel-ts/errors";
7669
+ import { ErrorCode as ErrorCode20, FuelError as FuelError22 } from "@fuel-ts/errors";
7544
7670
  import { sha256 as sha2563 } from "@fuel-ts/hasher";
7545
- import { arrayify as arrayify18, hexlify as hexlify20, concat as concat4, dataSlice, encodeBase58, toUtf8Bytes } from "@fuel-ts/utils";
7671
+ import { arrayify as arrayify18, hexlify as hexlify20, concat as concat5, dataSlice, encodeBase58, toUtf8Bytes } from "@fuel-ts/utils";
7546
7672
 
7547
7673
  // src/wordlists/words/english.ts
7548
7674
  var english = [
@@ -9603,7 +9729,7 @@ var Language = /* @__PURE__ */ ((Language2) => {
9603
9729
  })(Language || {});
9604
9730
 
9605
9731
  // src/mnemonic/utils.ts
9606
- import { ErrorCode as ErrorCode18, FuelError as FuelError20 } from "@fuel-ts/errors";
9732
+ import { ErrorCode as ErrorCode19, FuelError as FuelError21 } from "@fuel-ts/errors";
9607
9733
  import { sha256 as sha2562 } from "@fuel-ts/hasher";
9608
9734
  import { arrayify as arrayify17 } from "@fuel-ts/utils";
9609
9735
  function getLowerMask(bits) {
@@ -9652,8 +9778,8 @@ function mnemonicWordsToEntropy(words, wordlist) {
9652
9778
  for (let i = 0; i < words.length; i += 1) {
9653
9779
  const index = wordlist.indexOf(words[i].normalize("NFKD"));
9654
9780
  if (index === -1) {
9655
- throw new FuelError20(
9656
- ErrorCode18.INVALID_MNEMONIC,
9781
+ throw new FuelError21(
9782
+ ErrorCode19.INVALID_MNEMONIC,
9657
9783
  `Invalid mnemonic: the word '${words[i]}' is not found in the provided wordlist.`
9658
9784
  );
9659
9785
  }
@@ -9669,8 +9795,8 @@ function mnemonicWordsToEntropy(words, wordlist) {
9669
9795
  const checksumMask = getUpperMask(checksumBits);
9670
9796
  const checksum = arrayify17(sha2562(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
9671
9797
  if (checksum !== (entropy[entropy.length - 1] & checksumMask)) {
9672
- throw new FuelError20(
9673
- ErrorCode18.INVALID_CHECKSUM,
9798
+ throw new FuelError21(
9799
+ ErrorCode19.INVALID_CHECKSUM,
9674
9800
  "Checksum validation failed for the provided mnemonic."
9675
9801
  );
9676
9802
  }
@@ -9684,16 +9810,16 @@ var TestnetPRV = "0x04358394";
9684
9810
  var MNEMONIC_SIZES = [12, 15, 18, 21, 24];
9685
9811
  function assertWordList(wordlist) {
9686
9812
  if (wordlist.length !== 2048) {
9687
- throw new FuelError21(
9688
- ErrorCode19.INVALID_WORD_LIST,
9813
+ throw new FuelError22(
9814
+ ErrorCode20.INVALID_WORD_LIST,
9689
9815
  `Expected word list length of 2048, but got ${wordlist.length}.`
9690
9816
  );
9691
9817
  }
9692
9818
  }
9693
9819
  function assertEntropy(entropy) {
9694
9820
  if (entropy.length % 4 !== 0 || entropy.length < 16 || entropy.length > 32) {
9695
- throw new FuelError21(
9696
- ErrorCode19.INVALID_ENTROPY,
9821
+ throw new FuelError22(
9822
+ ErrorCode20.INVALID_ENTROPY,
9697
9823
  `Entropy should be between 16 and 32 bytes and a multiple of 4, but got ${entropy.length} bytes.`
9698
9824
  );
9699
9825
  }
@@ -9703,7 +9829,7 @@ function assertMnemonic(words) {
9703
9829
  const errorMsg = `Invalid mnemonic size. Expected one of [${MNEMONIC_SIZES.join(
9704
9830
  ", "
9705
9831
  )}] words, but got ${words.length}.`;
9706
- throw new FuelError21(ErrorCode19.INVALID_MNEMONIC, errorMsg);
9832
+ throw new FuelError22(ErrorCode20.INVALID_MNEMONIC, errorMsg);
9707
9833
  }
9708
9834
  }
9709
9835
  var Mnemonic = class {
@@ -9821,8 +9947,8 @@ var Mnemonic = class {
9821
9947
  static masterKeysFromSeed(seed) {
9822
9948
  const seedArray = arrayify18(seed);
9823
9949
  if (seedArray.length < 16 || seedArray.length > 64) {
9824
- throw new FuelError21(
9825
- ErrorCode19.INVALID_SEED,
9950
+ throw new FuelError22(
9951
+ ErrorCode20.INVALID_SEED,
9826
9952
  `Seed length should be between 16 and 64 bytes, but received ${seedArray.length} bytes.`
9827
9953
  );
9828
9954
  }
@@ -9843,16 +9969,16 @@ var Mnemonic = class {
9843
9969
  const index = "0x00000000";
9844
9970
  const chainCode = masterKey.slice(32);
9845
9971
  const privateKey = masterKey.slice(0, 32);
9846
- const extendedKey = concat4([
9972
+ const extendedKey = concat5([
9847
9973
  prefix,
9848
9974
  depth,
9849
9975
  fingerprint,
9850
9976
  index,
9851
9977
  chainCode,
9852
- concat4(["0x00", privateKey])
9978
+ concat5(["0x00", privateKey])
9853
9979
  ]);
9854
9980
  const checksum = dataSlice(sha2563(sha2563(extendedKey)), 0, 4);
9855
- return encodeBase58(concat4([extendedKey, checksum]));
9981
+ return encodeBase58(concat5([extendedKey, checksum]));
9856
9982
  }
9857
9983
  /**
9858
9984
  * Create a new mnemonic using a randomly generated number as entropy.
@@ -9867,7 +9993,7 @@ var Mnemonic = class {
9867
9993
  * @returns A randomly generated mnemonic
9868
9994
  */
9869
9995
  static generate(size = 32, extraEntropy = "") {
9870
- const entropy = extraEntropy ? sha2563(concat4([randomBytes5(size), arrayify18(extraEntropy)])) : randomBytes5(size);
9996
+ const entropy = extraEntropy ? sha2563(concat5([randomBytes5(size), arrayify18(extraEntropy)])) : randomBytes5(size);
9871
9997
  return Mnemonic.entropyToMnemonic(entropy);
9872
9998
  }
9873
9999
  };
@@ -9880,7 +10006,7 @@ var MainnetPUB = hexlify21("0x0488b21e");
9880
10006
  var TestnetPRV2 = hexlify21("0x04358394");
9881
10007
  var TestnetPUB = hexlify21("0x043587cf");
9882
10008
  function base58check(data) {
9883
- return encodeBase582(concat5([data, dataSlice2(sha2564(sha2564(data)), 0, 4)]));
10009
+ return encodeBase582(concat6([data, dataSlice2(sha2564(sha2564(data)), 0, 4)]));
9884
10010
  }
9885
10011
  function getExtendedKeyPrefix(isPublic = false, testnet = false) {
9886
10012
  if (isPublic) {
@@ -9899,7 +10025,7 @@ function isValidExtendedKey(extendedKey) {
9899
10025
  function parsePath(path, depth = 0) {
9900
10026
  const components = path.split("/");
9901
10027
  if (components.length === 0 || components[0] === "m" && depth !== 0) {
9902
- throw new FuelError22(ErrorCode20.HD_WALLET_ERROR, `invalid path - ${path}`);
10028
+ throw new FuelError23(ErrorCode21.HD_WALLET_ERROR, `invalid path - ${path}`);
9903
10029
  }
9904
10030
  if (components[0] === "m") {
9905
10031
  components.shift();
@@ -9928,8 +10054,8 @@ var HDWallet = class {
9928
10054
  this.privateKey = hexlify21(config.privateKey);
9929
10055
  } else {
9930
10056
  if (!config.publicKey) {
9931
- throw new FuelError22(
9932
- ErrorCode20.HD_WALLET_ERROR,
10057
+ throw new FuelError23(
10058
+ ErrorCode21.HD_WALLET_ERROR,
9933
10059
  "Both public and private Key cannot be missing. At least one should be provided."
9934
10060
  );
9935
10061
  }
@@ -9958,8 +10084,8 @@ var HDWallet = class {
9958
10084
  const data = new Uint8Array(37);
9959
10085
  if (index & HARDENED_INDEX) {
9960
10086
  if (!privateKey) {
9961
- throw new FuelError22(
9962
- ErrorCode20.HD_WALLET_ERROR,
10087
+ throw new FuelError23(
10088
+ ErrorCode21.HD_WALLET_ERROR,
9963
10089
  "Cannot derive a hardened index without a private Key."
9964
10090
  );
9965
10091
  }
@@ -10011,8 +10137,8 @@ var HDWallet = class {
10011
10137
  */
10012
10138
  toExtendedKey(isPublic = false, testnet = false) {
10013
10139
  if (this.depth >= 256) {
10014
- throw new FuelError22(
10015
- ErrorCode20.HD_WALLET_ERROR,
10140
+ throw new FuelError23(
10141
+ ErrorCode21.HD_WALLET_ERROR,
10016
10142
  `Exceeded max depth of 255. Current depth: ${this.depth}.`
10017
10143
  );
10018
10144
  }
@@ -10021,8 +10147,8 @@ var HDWallet = class {
10021
10147
  const parentFingerprint = this.parentFingerprint;
10022
10148
  const index = toHex(this.index, 4);
10023
10149
  const chainCode = this.chainCode;
10024
- const key = this.privateKey != null && !isPublic ? concat5(["0x00", this.privateKey]) : this.publicKey;
10025
- const extendedKey = arrayify19(concat5([prefix, depth, parentFingerprint, index, chainCode, key]));
10150
+ const key = this.privateKey != null && !isPublic ? concat6(["0x00", this.privateKey]) : this.publicKey;
10151
+ const extendedKey = arrayify19(concat6([prefix, depth, parentFingerprint, index, chainCode, key]));
10026
10152
  return base58check(extendedKey);
10027
10153
  }
10028
10154
  /**
@@ -10043,10 +10169,10 @@ var HDWallet = class {
10043
10169
  const bytes = arrayify19(decoded);
10044
10170
  const validChecksum = base58check(bytes.slice(0, 78)) === extendedKey;
10045
10171
  if (bytes.length !== 82 || !isValidExtendedKey(bytes)) {
10046
- throw new FuelError22(ErrorCode20.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
10172
+ throw new FuelError23(ErrorCode21.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
10047
10173
  }
10048
10174
  if (!validChecksum) {
10049
- throw new FuelError22(ErrorCode20.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
10175
+ throw new FuelError23(ErrorCode21.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
10050
10176
  }
10051
10177
  const depth = bytes[4];
10052
10178
  const parentFingerprint = hexlify21(bytes.slice(5, 9));
@@ -10054,14 +10180,14 @@ var HDWallet = class {
10054
10180
  const chainCode = hexlify21(bytes.slice(13, 45));
10055
10181
  const key = bytes.slice(45, 78);
10056
10182
  if (depth === 0 && parentFingerprint !== "0x00000000" || depth === 0 && index !== 0) {
10057
- throw new FuelError22(
10058
- ErrorCode20.HD_WALLET_ERROR,
10183
+ throw new FuelError23(
10184
+ ErrorCode21.HD_WALLET_ERROR,
10059
10185
  "Inconsistency detected: Depth is zero but fingerprint/index is non-zero."
10060
10186
  );
10061
10187
  }
10062
10188
  if (isPublicExtendedKey(bytes)) {
10063
10189
  if (key[0] !== 3) {
10064
- throw new FuelError22(ErrorCode20.HD_WALLET_ERROR, "Invalid public extended key.");
10190
+ throw new FuelError23(ErrorCode21.HD_WALLET_ERROR, "Invalid public extended key.");
10065
10191
  }
10066
10192
  return new HDWallet({
10067
10193
  publicKey: key,
@@ -10072,7 +10198,7 @@ var HDWallet = class {
10072
10198
  });
10073
10199
  }
10074
10200
  if (key[0] !== 0) {
10075
- throw new FuelError22(ErrorCode20.HD_WALLET_ERROR, "Invalid private extended key.");
10201
+ throw new FuelError23(ErrorCode21.HD_WALLET_ERROR, "Invalid private extended key.");
10076
10202
  }
10077
10203
  return new HDWallet({
10078
10204
  privateKey: key.slice(1),
@@ -10238,9 +10364,9 @@ __publicField(Wallet, "fromExtendedKey", WalletUnlocked.fromExtendedKey);
10238
10364
  __publicField(Wallet, "fromEncryptedJson", WalletUnlocked.fromEncryptedJson);
10239
10365
 
10240
10366
  // src/wallet-manager/wallet-manager.ts
10241
- import { Address as Address8 } from "@fuel-ts/address";
10367
+ import { Address as Address9 } from "@fuel-ts/address";
10242
10368
  import { encrypt, decrypt } from "@fuel-ts/crypto";
10243
- import { ErrorCode as ErrorCode23, FuelError as FuelError25 } from "@fuel-ts/errors";
10369
+ import { ErrorCode as ErrorCode24, FuelError as FuelError26 } from "@fuel-ts/errors";
10244
10370
  import { EventEmitter } from "events";
10245
10371
 
10246
10372
  // src/wallet-manager/storages/memory-storage.ts
@@ -10262,8 +10388,8 @@ var MemoryStorage = class {
10262
10388
  };
10263
10389
 
10264
10390
  // src/wallet-manager/vaults/mnemonic-vault.ts
10265
- import { Address as Address6 } from "@fuel-ts/address";
10266
- import { ErrorCode as ErrorCode21, FuelError as FuelError23 } from "@fuel-ts/errors";
10391
+ import { Address as Address7 } from "@fuel-ts/address";
10392
+ import { ErrorCode as ErrorCode22, FuelError as FuelError24 } from "@fuel-ts/errors";
10267
10393
  var _secret;
10268
10394
  var MnemonicVault = class {
10269
10395
  constructor(options) {
@@ -10311,7 +10437,7 @@ var MnemonicVault = class {
10311
10437
  }
10312
10438
  exportAccount(address) {
10313
10439
  let numberOfAccounts = 0;
10314
- const ownerAddress = Address6.fromAddressOrString(address);
10440
+ const ownerAddress = Address7.fromAddressOrString(address);
10315
10441
  do {
10316
10442
  const wallet = Wallet.fromMnemonic(__privateGet(this, _secret), this.getDerivePath(numberOfAccounts));
10317
10443
  if (wallet.address.equals(ownerAddress)) {
@@ -10319,8 +10445,8 @@ var MnemonicVault = class {
10319
10445
  }
10320
10446
  numberOfAccounts += 1;
10321
10447
  } while (numberOfAccounts < this.numberOfAccounts);
10322
- throw new FuelError23(
10323
- ErrorCode21.WALLET_MANAGER_ERROR,
10448
+ throw new FuelError24(
10449
+ ErrorCode22.WALLET_MANAGER_ERROR,
10324
10450
  `Account with address '${address}' not found in derived wallets.`
10325
10451
  );
10326
10452
  }
@@ -10333,8 +10459,8 @@ _secret = new WeakMap();
10333
10459
  __publicField(MnemonicVault, "type", "mnemonic");
10334
10460
 
10335
10461
  // src/wallet-manager/vaults/privatekey-vault.ts
10336
- import { Address as Address7 } from "@fuel-ts/address";
10337
- import { ErrorCode as ErrorCode22, FuelError as FuelError24 } from "@fuel-ts/errors";
10462
+ import { Address as Address8 } from "@fuel-ts/address";
10463
+ import { ErrorCode as ErrorCode23, FuelError as FuelError25 } from "@fuel-ts/errors";
10338
10464
  var _privateKeys;
10339
10465
  var PrivateKeyVault = class {
10340
10466
  /**
@@ -10370,13 +10496,13 @@ var PrivateKeyVault = class {
10370
10496
  return this.getPublicAccount(wallet.privateKey);
10371
10497
  }
10372
10498
  exportAccount(address) {
10373
- const ownerAddress = Address7.fromAddressOrString(address);
10499
+ const ownerAddress = Address8.fromAddressOrString(address);
10374
10500
  const privateKey = __privateGet(this, _privateKeys).find(
10375
10501
  (pk) => Wallet.fromPrivateKey(pk).address.equals(ownerAddress)
10376
10502
  );
10377
10503
  if (!privateKey) {
10378
- throw new FuelError24(
10379
- ErrorCode22.WALLET_MANAGER_ERROR,
10504
+ throw new FuelError25(
10505
+ ErrorCode23.WALLET_MANAGER_ERROR,
10380
10506
  `No private key found for address '${address}'.`
10381
10507
  );
10382
10508
  }
@@ -10400,7 +10526,7 @@ var ERROR_MESSAGES = {
10400
10526
  };
10401
10527
  function assert(condition, message) {
10402
10528
  if (!condition) {
10403
- throw new FuelError25(ErrorCode23.WALLET_MANAGER_ERROR, message);
10529
+ throw new FuelError26(ErrorCode24.WALLET_MANAGER_ERROR, message);
10404
10530
  }
10405
10531
  }
10406
10532
  var _vaults, _passphrase, _isLocked, _serializeVaults, serializeVaults_fn, _deserializeVaults, deserializeVaults_fn;
@@ -10468,7 +10594,7 @@ var _WalletManager = class extends EventEmitter {
10468
10594
  * Create a Wallet instance for the specific account
10469
10595
  */
10470
10596
  getWallet(address) {
10471
- const ownerAddress = Address8.fromAddressOrString(address);
10597
+ const ownerAddress = Address9.fromAddressOrString(address);
10472
10598
  const vaultState = __privateGet(this, _vaults).find(
10473
10599
  (vs) => vs.vault.getAccounts().find((a) => a.address.equals(ownerAddress))
10474
10600
  );
@@ -10479,7 +10605,7 @@ var _WalletManager = class extends EventEmitter {
10479
10605
  * Export specific account privateKey
10480
10606
  */
10481
10607
  exportPrivateKey(address) {
10482
- const ownerAddress = Address8.fromAddressOrString(address);
10608
+ const ownerAddress = Address9.fromAddressOrString(address);
10483
10609
  assert(!__privateGet(this, _isLocked), ERROR_MESSAGES.wallet_not_unlocked);
10484
10610
  const vaultState = __privateGet(this, _vaults).find(
10485
10611
  (vs) => vs.vault.getAccounts().find((a) => a.address.equals(ownerAddress))
@@ -10626,25 +10752,25 @@ deserializeVaults_fn = function(vaults) {
10626
10752
  __publicField(WalletManager, "Vaults", [MnemonicVault, PrivateKeyVault]);
10627
10753
 
10628
10754
  // src/wallet-manager/types.ts
10629
- import { ErrorCode as ErrorCode24, FuelError as FuelError26 } from "@fuel-ts/errors";
10755
+ import { ErrorCode as ErrorCode25, FuelError as FuelError27 } from "@fuel-ts/errors";
10630
10756
  var Vault = class {
10631
10757
  constructor(_options) {
10632
- throw new FuelError26(ErrorCode24.NOT_IMPLEMENTED, "Not implemented.");
10758
+ throw new FuelError27(ErrorCode25.NOT_IMPLEMENTED, "Not implemented.");
10633
10759
  }
10634
10760
  serialize() {
10635
- throw new FuelError26(ErrorCode24.NOT_IMPLEMENTED, "Not implemented.");
10761
+ throw new FuelError27(ErrorCode25.NOT_IMPLEMENTED, "Not implemented.");
10636
10762
  }
10637
10763
  getAccounts() {
10638
- throw new FuelError26(ErrorCode24.NOT_IMPLEMENTED, "Not implemented.");
10764
+ throw new FuelError27(ErrorCode25.NOT_IMPLEMENTED, "Not implemented.");
10639
10765
  }
10640
10766
  addAccount() {
10641
- throw new FuelError26(ErrorCode24.NOT_IMPLEMENTED, "Not implemented.");
10767
+ throw new FuelError27(ErrorCode25.NOT_IMPLEMENTED, "Not implemented.");
10642
10768
  }
10643
10769
  exportAccount(_address) {
10644
- throw new FuelError26(ErrorCode24.NOT_IMPLEMENTED, "Not implemented.");
10770
+ throw new FuelError27(ErrorCode25.NOT_IMPLEMENTED, "Not implemented.");
10645
10771
  }
10646
10772
  getWallet(_address) {
10647
- throw new FuelError26(ErrorCode24.NOT_IMPLEMENTED, "Not implemented.");
10773
+ throw new FuelError27(ErrorCode25.NOT_IMPLEMENTED, "Not implemented.");
10648
10774
  }
10649
10775
  };
10650
10776
  __publicField(Vault, "type");
@@ -10653,35 +10779,237 @@ var StorageAbstract = class {
10653
10779
 
10654
10780
  // src/predicate/predicate.ts
10655
10781
  import { Interface as Interface4 } from "@fuel-ts/abi-coder";
10656
- import { Address as Address9 } from "@fuel-ts/address";
10657
- import { ErrorCode as ErrorCode25, FuelError as FuelError27 } from "@fuel-ts/errors";
10658
- import { arrayify as arrayify21, hexlify as hexlify23, concat as concat7 } from "@fuel-ts/utils";
10782
+ import { Address as Address10 } from "@fuel-ts/address";
10783
+ import { ErrorCode as ErrorCode27, FuelError as FuelError29 } from "@fuel-ts/errors";
10784
+ import { arrayify as arrayify22, hexlify as hexlify23 } from "@fuel-ts/utils";
10659
10785
 
10660
- // src/predicate/utils/getPredicateRoot.ts
10786
+ // src/utils/deployScriptOrPredicate.ts
10787
+ import { FuelError as FuelError28, ErrorCode as ErrorCode26 } from "@fuel-ts/errors";
10661
10788
  import { hash as hash3 } from "@fuel-ts/hasher";
10789
+ import { bn as bn21 } from "@fuel-ts/math";
10790
+ import { arrayify as arrayify20 } from "@fuel-ts/utils";
10791
+
10792
+ // src/utils/predicate-script-loader-instructions.ts
10793
+ import { concat as concat7 } from "@fuel-ts/utils";
10794
+ import * as asm2 from "@fuels/vm-asm";
10795
+ var BLOB_ID_SIZE = 32;
10796
+ var REG_ADDRESS_OF_DATA_AFTER_CODE = 16;
10797
+ var REG_START_OF_LOADED_CODE = 17;
10798
+ var REG_GENERAL_USE = 18;
10799
+ var WORD_SIZE2 = 8;
10800
+ function getDataOffset(binary) {
10801
+ const OFFSET_INDEX = 8;
10802
+ const dataView = new DataView(binary.buffer, OFFSET_INDEX, 8);
10803
+ const dataOffset = dataView.getBigUint64(0, false);
10804
+ return Number(dataOffset);
10805
+ }
10806
+ function getPredicateScriptLoaderInstructions(originalBinary, blobId) {
10807
+ const { RegId, Instruction } = asm2;
10808
+ const REG_PC = RegId.pc().to_u8();
10809
+ const REG_SP = RegId.sp().to_u8();
10810
+ const REG_IS = RegId.is().to_u8();
10811
+ const getInstructions = (numOfInstructions2) => [
10812
+ // 1. Load the blob content into memory
10813
+ // Find the start of the hardcoded blob ID, which is located after the loader code ends.
10814
+ asm2.move_(REG_ADDRESS_OF_DATA_AFTER_CODE, REG_PC),
10815
+ // hold the address of the blob ID.
10816
+ asm2.addi(
10817
+ REG_ADDRESS_OF_DATA_AFTER_CODE,
10818
+ REG_ADDRESS_OF_DATA_AFTER_CODE,
10819
+ numOfInstructions2 * Instruction.size()
10820
+ ),
10821
+ // The code is going to be loaded from the current value of SP onwards, save
10822
+ // the location into REG_START_OF_LOADED_CODE so we can jump into it at the end.
10823
+ asm2.move_(REG_START_OF_LOADED_CODE, REG_SP),
10824
+ // REG_GENERAL_USE to hold the size of the blob.
10825
+ asm2.bsiz(REG_GENERAL_USE, REG_ADDRESS_OF_DATA_AFTER_CODE),
10826
+ // Push the blob contents onto the stack.
10827
+ asm2.ldc(REG_ADDRESS_OF_DATA_AFTER_CODE, 0, REG_GENERAL_USE, 1),
10828
+ // Move on to the data section length
10829
+ asm2.addi(REG_ADDRESS_OF_DATA_AFTER_CODE, REG_ADDRESS_OF_DATA_AFTER_CODE, BLOB_ID_SIZE),
10830
+ // load the size of the data section into REG_GENERAL_USE
10831
+ asm2.lw(REG_GENERAL_USE, REG_ADDRESS_OF_DATA_AFTER_CODE, 0),
10832
+ // after we have read the length of the data section, we move the pointer to the actual
10833
+ // data by skipping WORD_SIZE bytes.
10834
+ asm2.addi(REG_ADDRESS_OF_DATA_AFTER_CODE, REG_ADDRESS_OF_DATA_AFTER_CODE, WORD_SIZE2),
10835
+ // load the data section of the executable
10836
+ asm2.ldc(REG_ADDRESS_OF_DATA_AFTER_CODE, 0, REG_GENERAL_USE, 2),
10837
+ // Jump into the memory where the contract is loaded.
10838
+ // What follows is called _jmp_mem by the sway compiler.
10839
+ // Subtract the address contained in IS because jmp will add it back.
10840
+ asm2.sub(REG_START_OF_LOADED_CODE, REG_START_OF_LOADED_CODE, REG_IS),
10841
+ // jmp will multiply by 4, so we need to divide to cancel that out.
10842
+ asm2.divi(REG_START_OF_LOADED_CODE, REG_START_OF_LOADED_CODE, 4),
10843
+ // Jump to the start of the contract we loaded.
10844
+ asm2.jmp(REG_START_OF_LOADED_CODE)
10845
+ ];
10846
+ const getInstructionsNoDataSection = (numOfInstructions2) => [
10847
+ // 1. Load the blob content into memory
10848
+ // Find the start of the hardcoded blob ID, which is located after the loader code ends.
10849
+ // 1. Load the blob content into memory
10850
+ // Find the start of the hardcoded blob ID, which is located after the loader code ends.
10851
+ asm2.move_(REG_ADDRESS_OF_DATA_AFTER_CODE, REG_PC),
10852
+ // hold the address of the blob ID.
10853
+ asm2.addi(
10854
+ REG_ADDRESS_OF_DATA_AFTER_CODE,
10855
+ REG_ADDRESS_OF_DATA_AFTER_CODE,
10856
+ numOfInstructions2 * Instruction.size()
10857
+ ),
10858
+ // The code is going to be loaded from the current value of SP onwards, save
10859
+ // the location into REG_START_OF_LOADED_CODE so we can jump into it at the end.
10860
+ asm2.move_(REG_START_OF_LOADED_CODE, REG_SP),
10861
+ // REG_GENERAL_USE to hold the size of the blob.
10862
+ asm2.bsiz(REG_GENERAL_USE, REG_ADDRESS_OF_DATA_AFTER_CODE),
10863
+ // Push the blob contents onto the stack.
10864
+ asm2.ldc(REG_ADDRESS_OF_DATA_AFTER_CODE, 0, REG_GENERAL_USE, 1),
10865
+ // Jump into the memory where the contract is loaded.
10866
+ // What follows is called _jmp_mem by the sway compiler.
10867
+ // Subtract the address contained in IS because jmp will add it back.
10868
+ asm2.sub(REG_START_OF_LOADED_CODE, REG_START_OF_LOADED_CODE, REG_IS),
10869
+ // jmp will multiply by 4, so we need to divide to cancel that out.
10870
+ asm2.divi(REG_START_OF_LOADED_CODE, REG_START_OF_LOADED_CODE, 4),
10871
+ // Jump to the start of the contract we loaded.
10872
+ asm2.jmp(REG_START_OF_LOADED_CODE)
10873
+ ];
10874
+ const offset = getDataOffset(originalBinary);
10875
+ if (originalBinary.length < offset) {
10876
+ throw new Error(
10877
+ `Data section offset is out of bounds, offset: ${offset}, binary length: ${originalBinary.length}`
10878
+ );
10879
+ }
10880
+ const dataSection = originalBinary.slice(offset);
10881
+ if (dataSection.length > 0) {
10882
+ const numOfInstructions2 = getInstructions(0).length;
10883
+ if (numOfInstructions2 > 65535) {
10884
+ throw new Error("Too many instructions, exceeding u16::MAX.");
10885
+ }
10886
+ const instructionBytes2 = new Uint8Array(
10887
+ getInstructions(numOfInstructions2).flatMap(
10888
+ (instruction) => Array.from(instruction.to_bytes())
10889
+ )
10890
+ );
10891
+ const blobBytes2 = new Uint8Array(blobId);
10892
+ const dataSectionLenBytes = new Uint8Array(8);
10893
+ const dataView = new DataView(dataSectionLenBytes.buffer);
10894
+ dataView.setBigUint64(0, BigInt(dataSection.length), false);
10895
+ const loaderBytecode2 = new Uint8Array([
10896
+ ...instructionBytes2,
10897
+ ...blobBytes2,
10898
+ ...dataSectionLenBytes
10899
+ ]);
10900
+ return {
10901
+ loaderBytecode: concat7([loaderBytecode2, dataSection]),
10902
+ blobOffset: loaderBytecode2.length
10903
+ };
10904
+ }
10905
+ const numOfInstructions = getInstructionsNoDataSection(0).length;
10906
+ if (numOfInstructions > 65535) {
10907
+ throw new Error("Too many instructions, exceeding u16::MAX.");
10908
+ }
10909
+ const instructionBytes = new Uint8Array(
10910
+ getInstructionsNoDataSection(numOfInstructions).flatMap(
10911
+ (instruction) => Array.from(instruction.to_bytes())
10912
+ )
10913
+ );
10914
+ const blobBytes = new Uint8Array(blobId);
10915
+ const loaderBytecode = new Uint8Array([...instructionBytes, ...blobBytes]);
10916
+ return { loaderBytecode };
10917
+ }
10918
+
10919
+ // src/utils/deployScriptOrPredicate.ts
10920
+ async function fundBlobTx(deployer, blobTxRequest) {
10921
+ let totalCost = bn21(0);
10922
+ const chainInfo = deployer.provider.getChain();
10923
+ const gasPrice = await deployer.provider.estimateGasPrice(10);
10924
+ const priceFactor = chainInfo.consensusParameters.feeParameters.gasPriceFactor;
10925
+ const minGas = blobTxRequest.calculateMinGas(chainInfo);
10926
+ const minFee = calculateGasFee({
10927
+ gasPrice,
10928
+ gas: minGas,
10929
+ priceFactor,
10930
+ tip: blobTxRequest.tip
10931
+ }).add(1);
10932
+ totalCost = totalCost.add(minFee);
10933
+ if (totalCost.gt(await deployer.getBalance())) {
10934
+ throw new FuelError28(ErrorCode26.FUNDS_TOO_LOW, "Insufficient balance to deploy predicate.");
10935
+ }
10936
+ const txCost = await deployer.getTransactionCost(blobTxRequest);
10937
+ blobTxRequest.maxFee = txCost.maxFee;
10938
+ return deployer.fund(blobTxRequest, txCost);
10939
+ }
10940
+ function adjustConfigurableOffsets(jsonAbi, configurableOffsetDiff) {
10941
+ const { configurables: readOnlyConfigurables } = jsonAbi;
10942
+ const configurables = [];
10943
+ readOnlyConfigurables.forEach((config) => {
10944
+ configurables.push({ ...config, offset: config.offset - configurableOffsetDiff });
10945
+ });
10946
+ return { ...jsonAbi, configurables };
10947
+ }
10948
+ async function deployScriptOrPredicate({
10949
+ deployer,
10950
+ bytecode,
10951
+ abi,
10952
+ loaderInstanceCallback
10953
+ }) {
10954
+ const dataSectionOffset = getDataOffset(arrayify20(bytecode));
10955
+ const byteCodeWithoutDataSection = bytecode.slice(0, dataSectionOffset);
10956
+ const blobId = hash3(byteCodeWithoutDataSection);
10957
+ const blobTxRequest = new BlobTransactionRequest({
10958
+ blobId,
10959
+ witnessIndex: 0,
10960
+ witnesses: [byteCodeWithoutDataSection]
10961
+ });
10962
+ const { loaderBytecode, blobOffset } = getPredicateScriptLoaderInstructions(
10963
+ arrayify20(bytecode),
10964
+ arrayify20(blobId)
10965
+ );
10966
+ const configurableOffsetDiff = byteCodeWithoutDataSection.length - (blobOffset || 0);
10967
+ const newAbi = adjustConfigurableOffsets(abi, configurableOffsetDiff);
10968
+ const blobExists = (await deployer.provider.getBlobs([blobId])).length > 0;
10969
+ const loaderInstance = loaderInstanceCallback(loaderBytecode, newAbi);
10970
+ if (blobExists) {
10971
+ return {
10972
+ waitForResult: () => Promise.resolve(loaderInstance),
10973
+ blobId
10974
+ };
10975
+ }
10976
+ const fundedBlobRequest = await fundBlobTx(deployer, blobTxRequest);
10977
+ const waitForResult = async () => {
10978
+ try {
10979
+ const blobTx = await deployer.sendTransaction(fundedBlobRequest);
10980
+ const result = await blobTx.waitForResult();
10981
+ if (result.status !== "success" /* success */) {
10982
+ throw new Error();
10983
+ }
10984
+ } catch (err) {
10985
+ throw new FuelError28(ErrorCode26.TRANSACTION_FAILED, "Failed to deploy predicate chunk");
10986
+ }
10987
+ return loaderInstance;
10988
+ };
10989
+ return {
10990
+ waitForResult,
10991
+ blobId
10992
+ };
10993
+ }
10994
+
10995
+ // src/predicate/utils/getPredicateRoot.ts
10996
+ import { hash as hash4 } from "@fuel-ts/hasher";
10662
10997
  import { calcRoot } from "@fuel-ts/merkle";
10663
- import { chunkAndPadBytes, hexlify as hexlify22, concat as concat6, arrayify as arrayify20 } from "@fuel-ts/utils";
10998
+ import { chunkAndPadBytes, hexlify as hexlify22, concat as concat8, arrayify as arrayify21 } from "@fuel-ts/utils";
10664
10999
  var getPredicateRoot = (bytecode) => {
10665
11000
  const chunkSize = 16 * 1024;
10666
- const bytes = arrayify20(bytecode);
11001
+ const bytes = arrayify21(bytecode);
10667
11002
  const chunks = chunkAndPadBytes(bytes, chunkSize);
10668
11003
  const codeRoot = calcRoot(chunks.map((c) => hexlify22(c)));
10669
- const predicateRoot = hash3(concat6(["0x4655454C", codeRoot]));
11004
+ const predicateRoot = hash4(concat8(["0x4655454C", codeRoot]));
10670
11005
  return predicateRoot;
10671
11006
  };
10672
11007
 
10673
11008
  // src/predicate/predicate.ts
10674
- function getDataOffset(binary) {
10675
- const buffer = binary.buffer.slice(binary.byteOffset + 8, binary.byteOffset + 16);
10676
- const dataView = new DataView(buffer);
10677
- const dataOffset = dataView.getBigUint64(0, false);
10678
- return Number(dataOffset);
10679
- }
10680
11009
  var Predicate = class extends Account {
10681
11010
  bytes;
10682
11011
  predicateData = [];
10683
11012
  interface;
10684
- loaderBytecode = "";
10685
11013
  /**
10686
11014
  * Creates an instance of the Predicate class.
10687
11015
  *
@@ -10696,24 +11024,17 @@ var Predicate = class extends Account {
10696
11024
  abi,
10697
11025
  provider,
10698
11026
  data,
10699
- configurableConstants,
10700
- /**
10701
- * TODO: Implement a getBytes method within the Predicate class. This method should return the loaderBytecode if it is set.
10702
- * The getBytes method should be used in all places where we use this.bytes.
10703
- * Note: Do not set loaderBytecode to a default string here; it should remain undefined when not provided.
10704
- */
10705
- loaderBytecode = ""
11027
+ configurableConstants
10706
11028
  }) {
10707
11029
  const { predicateBytes, predicateInterface } = Predicate.processPredicateData(
10708
11030
  bytecode,
10709
11031
  abi,
10710
11032
  configurableConstants
10711
11033
  );
10712
- const address = Address9.fromB256(getPredicateRoot(predicateBytes));
11034
+ const address = Address10.fromB256(getPredicateRoot(predicateBytes));
10713
11035
  super(address, provider);
10714
11036
  this.bytes = predicateBytes;
10715
11037
  this.interface = predicateInterface;
10716
- this.loaderBytecode = loaderBytecode;
10717
11038
  if (data !== void 0 && data.length > 0) {
10718
11039
  this.predicateData = data;
10719
11040
  }
@@ -10775,16 +11096,13 @@ var Predicate = class extends Account {
10775
11096
  * @returns An object containing the new predicate bytes and interface.
10776
11097
  */
10777
11098
  static processPredicateData(bytes, jsonAbi, configurableConstants) {
10778
- let predicateBytes = arrayify21(bytes);
10779
- let abiInterface;
10780
- if (jsonAbi) {
10781
- abiInterface = new Interface4(jsonAbi);
10782
- if (abiInterface.functions.main === void 0) {
10783
- throw new FuelError27(
10784
- ErrorCode25.ABI_MAIN_METHOD_MISSING,
10785
- 'Cannot use ABI without "main" function.'
10786
- );
10787
- }
11099
+ let predicateBytes = arrayify22(bytes);
11100
+ const abiInterface = new Interface4(jsonAbi);
11101
+ if (abiInterface.functions.main === void 0) {
11102
+ throw new FuelError29(
11103
+ ErrorCode27.ABI_MAIN_METHOD_MISSING,
11104
+ 'Cannot use ABI without "main" function.'
11105
+ );
10788
11106
  }
10789
11107
  if (configurableConstants && Object.keys(configurableConstants).length) {
10790
11108
  predicateBytes = Predicate.setConfigurableConstants(
@@ -10838,25 +11156,19 @@ var Predicate = class extends Account {
10838
11156
  * @param abiInterface - The ABI interface of the predicate.
10839
11157
  * @returns The mutated bytes with the configurable constants set.
10840
11158
  */
10841
- static setConfigurableConstants(bytes, configurableConstants, abiInterface, loaderBytecode) {
11159
+ static setConfigurableConstants(bytes, configurableConstants, abiInterface) {
10842
11160
  const mutatedBytes = bytes;
10843
11161
  try {
10844
- if (!abiInterface) {
10845
- throw new FuelError27(
10846
- ErrorCode25.INVALID_CONFIGURABLE_CONSTANTS,
10847
- "Cannot validate configurable constants because the Predicate was instantiated without a JSON ABI"
10848
- );
10849
- }
10850
11162
  if (Object.keys(abiInterface.configurables).length === 0) {
10851
- throw new FuelError27(
10852
- ErrorCode25.INVALID_CONFIGURABLE_CONSTANTS,
11163
+ throw new FuelError29(
11164
+ ErrorCode27.INVALID_CONFIGURABLE_CONSTANTS,
10853
11165
  "Predicate has no configurable constants to be set"
10854
11166
  );
10855
11167
  }
10856
11168
  Object.entries(configurableConstants).forEach(([key, value]) => {
10857
11169
  if (!abiInterface?.configurables[key]) {
10858
- throw new FuelError27(
10859
- ErrorCode25.CONFIGURABLE_NOT_FOUND,
11170
+ throw new FuelError29(
11171
+ ErrorCode27.CONFIGURABLE_NOT_FOUND,
10860
11172
  `No configurable constant named '${key}' found in the Predicate`
10861
11173
  );
10862
11174
  }
@@ -10864,18 +11176,9 @@ var Predicate = class extends Account {
10864
11176
  const encoded = abiInterface.encodeConfigurable(key, value);
10865
11177
  mutatedBytes.set(encoded, offset);
10866
11178
  });
10867
- if (loaderBytecode) {
10868
- const offset = getDataOffset(bytes);
10869
- const dataSection = mutatedBytes.slice(offset);
10870
- const dataSectionLen = dataSection.length;
10871
- const dataSectionLenBytes = new Uint8Array(8);
10872
- const dataSectionLenDataView = new DataView(dataSectionLenBytes.buffer);
10873
- dataSectionLenDataView.setBigUint64(0, BigInt(dataSectionLen), false);
10874
- mutatedBytes.set(concat7([loaderBytecode, dataSectionLenBytes, dataSection]));
10875
- }
10876
11179
  } catch (err) {
10877
- throw new FuelError27(
10878
- ErrorCode25.INVALID_CONFIGURABLE_CONSTANTS,
11180
+ throw new FuelError29(
11181
+ ErrorCode27.INVALID_CONFIGURABLE_CONSTANTS,
10879
11182
  `Error setting configurable constants: ${err.message}.`
10880
11183
  );
10881
11184
  }
@@ -10903,13 +11206,35 @@ var Predicate = class extends Account {
10903
11206
  }
10904
11207
  return index;
10905
11208
  }
11209
+ /**
11210
+ *
11211
+ * @param account - The account used to pay the deployment costs.
11212
+ * @returns The _blobId_ and a _waitForResult_ callback that returns the deployed predicate
11213
+ * once the blob deployment transaction finishes.
11214
+ *
11215
+ * The returned loader predicate will have the same configurable constants
11216
+ * as the original predicate which was used to generate the loader predicate.
11217
+ */
11218
+ async deploy(account) {
11219
+ return deployScriptOrPredicate({
11220
+ deployer: account,
11221
+ abi: this.interface.jsonAbi,
11222
+ bytecode: this.bytes,
11223
+ loaderInstanceCallback: (loaderBytecode, newAbi) => new Predicate({
11224
+ bytecode: loaderBytecode,
11225
+ abi: newAbi,
11226
+ provider: this.provider,
11227
+ data: this.predicateData
11228
+ })
11229
+ });
11230
+ }
10906
11231
  };
10907
11232
 
10908
11233
  // src/connectors/fuel.ts
10909
- import { ErrorCode as ErrorCode26, FuelError as FuelError30 } from "@fuel-ts/errors";
11234
+ import { ErrorCode as ErrorCode28, FuelError as FuelError32 } from "@fuel-ts/errors";
10910
11235
 
10911
11236
  // src/connectors/fuel-connector.ts
10912
- import { FuelError as FuelError28 } from "@fuel-ts/errors";
11237
+ import { FuelError as FuelError30 } from "@fuel-ts/errors";
10913
11238
  import { EventEmitter as EventEmitter2 } from "events";
10914
11239
 
10915
11240
  // src/connectors/types/connector-types.ts
@@ -10984,7 +11309,7 @@ var FuelConnector = class extends EventEmitter2 {
10984
11309
  * @returns Always true.
10985
11310
  */
10986
11311
  async ping() {
10987
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11312
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
10988
11313
  }
10989
11314
  /**
10990
11315
  * Should return the current version of the connector
@@ -10993,7 +11318,7 @@ var FuelConnector = class extends EventEmitter2 {
10993
11318
  * @returns boolean - connection status.
10994
11319
  */
10995
11320
  async version() {
10996
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11321
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
10997
11322
  }
10998
11323
  /**
10999
11324
  * Should return true if the connector is connected
@@ -11002,7 +11327,7 @@ var FuelConnector = class extends EventEmitter2 {
11002
11327
  * @returns The connection status.
11003
11328
  */
11004
11329
  async isConnected() {
11005
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11330
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11006
11331
  }
11007
11332
  /**
11008
11333
  * Should return all the accounts authorized for the
@@ -11011,7 +11336,7 @@ var FuelConnector = class extends EventEmitter2 {
11011
11336
  * @returns The accounts addresses strings
11012
11337
  */
11013
11338
  async accounts() {
11014
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11339
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11015
11340
  }
11016
11341
  /**
11017
11342
  * Should start the connection process and return
@@ -11023,7 +11348,7 @@ var FuelConnector = class extends EventEmitter2 {
11023
11348
  * @returns boolean - connection status.
11024
11349
  */
11025
11350
  async connect() {
11026
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11351
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11027
11352
  }
11028
11353
  /**
11029
11354
  * Should disconnect the current connection and
@@ -11033,7 +11358,7 @@ var FuelConnector = class extends EventEmitter2 {
11033
11358
  * @returns The connection status.
11034
11359
  */
11035
11360
  async disconnect() {
11036
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11361
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11037
11362
  }
11038
11363
  /**
11039
11364
  * Should start the sign message process and return
@@ -11045,7 +11370,7 @@ var FuelConnector = class extends EventEmitter2 {
11045
11370
  * @returns Message signature
11046
11371
  */
11047
11372
  async signMessage(_address, _message) {
11048
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11373
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11049
11374
  }
11050
11375
  /**
11051
11376
  * Should start the sign transaction process and return
@@ -11057,7 +11382,7 @@ var FuelConnector = class extends EventEmitter2 {
11057
11382
  * @returns Transaction signature
11058
11383
  */
11059
11384
  async signTransaction(_address, _transaction) {
11060
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11385
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11061
11386
  }
11062
11387
  /**
11063
11388
  * Should start the send transaction process and return
@@ -11073,7 +11398,7 @@ var FuelConnector = class extends EventEmitter2 {
11073
11398
  * @returns The transaction id
11074
11399
  */
11075
11400
  async sendTransaction(_address, _transaction) {
11076
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11401
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11077
11402
  }
11078
11403
  /**
11079
11404
  * Should return the current account selected inside the connector, if the account
@@ -11084,7 +11409,7 @@ var FuelConnector = class extends EventEmitter2 {
11084
11409
  * @returns The current account selected otherwise null.
11085
11410
  */
11086
11411
  async currentAccount() {
11087
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11412
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11088
11413
  }
11089
11414
  /**
11090
11415
  * Should add the assets metadata to the connector and return true if the asset
@@ -11098,7 +11423,7 @@ var FuelConnector = class extends EventEmitter2 {
11098
11423
  * @returns True if the asset was added successfully
11099
11424
  */
11100
11425
  async addAssets(_assets) {
11101
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11426
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11102
11427
  }
11103
11428
  /**
11104
11429
  * Should add the asset metadata to the connector and return true if the asset
@@ -11112,7 +11437,7 @@ var FuelConnector = class extends EventEmitter2 {
11112
11437
  * @returns True if the asset was added successfully
11113
11438
  */
11114
11439
  async addAsset(_asset) {
11115
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11440
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11116
11441
  }
11117
11442
  /**
11118
11443
  * Should return all the assets added to the connector. If a connection is already established.
@@ -11120,7 +11445,7 @@ var FuelConnector = class extends EventEmitter2 {
11120
11445
  * @returns Array of assets metadata from the connector vinculated to the all accounts from a specific Wallet.
11121
11446
  */
11122
11447
  async assets() {
11123
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11448
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11124
11449
  }
11125
11450
  /**
11126
11451
  * Should start the add network process and return true if the network was added successfully.
@@ -11131,7 +11456,7 @@ var FuelConnector = class extends EventEmitter2 {
11131
11456
  * @returns Return true if the network was added successfully
11132
11457
  */
11133
11458
  async addNetwork(_networkUrl) {
11134
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11459
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11135
11460
  }
11136
11461
  /**
11137
11462
  * Should start the select network process and return true if the network has change successfully.
@@ -11142,7 +11467,7 @@ var FuelConnector = class extends EventEmitter2 {
11142
11467
  * @returns Return true if the network was added successfully
11143
11468
  */
11144
11469
  async selectNetwork(_network) {
11145
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11470
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11146
11471
  }
11147
11472
  /**
11148
11473
  * Should return all the networks available from the connector. If the connection is already established.
@@ -11150,7 +11475,7 @@ var FuelConnector = class extends EventEmitter2 {
11150
11475
  * @returns Return all the networks added to the connector.
11151
11476
  */
11152
11477
  async networks() {
11153
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11478
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11154
11479
  }
11155
11480
  /**
11156
11481
  * Should return the current network selected inside the connector. Even if the connection is not established.
@@ -11158,7 +11483,7 @@ var FuelConnector = class extends EventEmitter2 {
11158
11483
  * @returns Return the current network selected inside the connector.
11159
11484
  */
11160
11485
  async currentNetwork() {
11161
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11486
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11162
11487
  }
11163
11488
  /**
11164
11489
  * Should add the ABI to the connector and return true if the ABI was added successfully.
@@ -11168,7 +11493,7 @@ var FuelConnector = class extends EventEmitter2 {
11168
11493
  * @returns Return true if the ABI was added successfully.
11169
11494
  */
11170
11495
  async addABI(_contractId, _abi) {
11171
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11496
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11172
11497
  }
11173
11498
  /**
11174
11499
  * Should return the ABI from the connector vinculated to the all accounts from a specific Wallet.
@@ -11177,7 +11502,7 @@ var FuelConnector = class extends EventEmitter2 {
11177
11502
  * @returns The ABI if it exists, otherwise return null.
11178
11503
  */
11179
11504
  async getABI(_id) {
11180
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11505
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11181
11506
  }
11182
11507
  /**
11183
11508
  * Should return true if the abi exists in the connector vinculated to the all accounts from a specific Wallet.
@@ -11186,7 +11511,7 @@ var FuelConnector = class extends EventEmitter2 {
11186
11511
  * @returns Returns true if the abi exists or false if not.
11187
11512
  */
11188
11513
  async hasABI(_id) {
11189
- throw new FuelError28(FuelError28.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11514
+ throw new FuelError30(FuelError30.CODES.NOT_IMPLEMENTED, "Method not implemented.");
11190
11515
  }
11191
11516
  /**
11192
11517
  * Event listener for the connector.
@@ -11230,7 +11555,7 @@ function dispatchFuelConnectorEvent(connector) {
11230
11555
  }
11231
11556
 
11232
11557
  // src/connectors/utils/promises.ts
11233
- import { FuelError as FuelError29 } from "@fuel-ts/errors";
11558
+ import { FuelError as FuelError31 } from "@fuel-ts/errors";
11234
11559
  function deferPromise() {
11235
11560
  const defer = {};
11236
11561
  defer.promise = new Promise((resolve, reject) => {
@@ -11242,7 +11567,7 @@ function deferPromise() {
11242
11567
  async function withTimeout(promise, timeout = 1050) {
11243
11568
  const timeoutPromise = new Promise((resolve, reject) => {
11244
11569
  setTimeout(() => {
11245
- reject(new FuelError29(FuelError29.CODES.TIMEOUT_EXCEEDED, "Promise timed out"));
11570
+ reject(new FuelError31(FuelError31.CODES.TIMEOUT_EXCEEDED, "Promise timed out"));
11246
11571
  }, timeout);
11247
11572
  });
11248
11573
  return Promise.race([timeoutPromise, promise]);
@@ -11273,10 +11598,11 @@ var _Fuel = class extends FuelConnector {
11273
11598
  }
11274
11599
  async initialize() {
11275
11600
  try {
11276
- await this.setDefaultConnector();
11601
+ const connectResponse = this.setDefaultConnector();
11277
11602
  this._targetUnsubscribe = this.setupConnectorListener();
11603
+ await connectResponse;
11278
11604
  } catch (error) {
11279
- throw new FuelError30(ErrorCode26.INVALID_PROVIDER, "Error initializing Fuel Connector");
11605
+ throw new FuelError32(ErrorCode28.INVALID_PROVIDER, "Error initializing Fuel Connector");
11280
11606
  }
11281
11607
  }
11282
11608
  async init() {
@@ -11342,8 +11668,8 @@ var _Fuel = class extends FuelConnector {
11342
11668
  const hasConnector = await this.hasConnector();
11343
11669
  await this.pingConnector();
11344
11670
  if (!this._currentConnector || !hasConnector) {
11345
- throw new FuelError30(
11346
- ErrorCode26.MISSING_CONNECTOR,
11671
+ throw new FuelError32(
11672
+ ErrorCode28.MISSING_CONNECTOR,
11347
11673
  `No connector selected for calling ${method}. Use hasConnector before executing other methods.`
11348
11674
  );
11349
11675
  }
@@ -11407,7 +11733,7 @@ var _Fuel = class extends FuelConnector {
11407
11733
  cacheTime: PING_CACHE_TIME
11408
11734
  })();
11409
11735
  } catch {
11410
- throw new FuelError30(ErrorCode26.INVALID_PROVIDER, "Current connector is not available.");
11736
+ throw new FuelError32(ErrorCode28.INVALID_PROVIDER, "Current connector is not available.");
11411
11737
  }
11412
11738
  }
11413
11739
  /**
@@ -11556,7 +11882,7 @@ var _Fuel = class extends FuelConnector {
11556
11882
  const currentNetwork = await this.currentNetwork();
11557
11883
  provider = await Provider.create(currentNetwork.url);
11558
11884
  } else {
11559
- throw new FuelError30(ErrorCode26.INVALID_PROVIDER, "Provider is not valid.");
11885
+ throw new FuelError32(ErrorCode28.INVALID_PROVIDER, "Provider is not valid.");
11560
11886
  }
11561
11887
  return provider;
11562
11888
  }
@@ -11611,6 +11937,7 @@ export {
11611
11937
  FuelConnectorEventType,
11612
11938
  FuelConnectorEventTypes,
11613
11939
  FuelConnectorMethods,
11940
+ GAS_USED_MODIFIER,
11614
11941
  hdwallet_default as HDWallet,
11615
11942
  Language,
11616
11943
  LocalStorage,
@@ -11662,6 +11989,7 @@ export {
11662
11989
  calculateTXFeeForSummary,
11663
11990
  coinQuantityfy,
11664
11991
  deferPromise,
11992
+ deployScriptOrPredicate,
11665
11993
  dispatchFuelConnectorEvent,
11666
11994
  english,
11667
11995
  extractBurnedAssetsFromReceipts,