@fuel-ts/account 0.101.2 → 0.101.3

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 (36) hide show
  1. package/dist/account.d.ts +45 -14
  2. package/dist/account.d.ts.map +1 -1
  3. package/dist/connectors/fuel-connector.d.ts +8 -0
  4. package/dist/connectors/fuel-connector.d.ts.map +1 -1
  5. package/dist/connectors/types/connector-types.d.ts +4 -2
  6. package/dist/connectors/types/connector-types.d.ts.map +1 -1
  7. package/dist/connectors/types/events.d.ts +6 -1
  8. package/dist/connectors/types/events.d.ts.map +1 -1
  9. package/dist/index.d.ts +1 -0
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.global.js +538 -101
  12. package/dist/index.global.js.map +1 -1
  13. package/dist/index.js +598 -250
  14. package/dist/index.js.map +1 -1
  15. package/dist/index.mjs +583 -238
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/providers/provider.d.ts.map +1 -1
  18. package/dist/providers/transaction-request/script-transaction-request.d.ts +2 -1
  19. package/dist/providers/transaction-request/script-transaction-request.d.ts.map +1 -1
  20. package/dist/providers/transaction-response/transaction-response.d.ts +23 -4
  21. package/dist/providers/transaction-response/transaction-response.d.ts.map +1 -1
  22. package/dist/providers/utils/extract-tx-error.d.ts.map +1 -1
  23. package/dist/providers/utils/handle-gql-error-message.d.ts.map +1 -1
  24. package/dist/providers/utils/transaction-response-serialization.d.ts.map +1 -1
  25. package/dist/test-utils/launchNode.d.ts.map +1 -1
  26. package/dist/test-utils.global.js +465 -101
  27. package/dist/test-utils.global.js.map +1 -1
  28. package/dist/test-utils.js +525 -198
  29. package/dist/test-utils.js.map +1 -1
  30. package/dist/test-utils.mjs +515 -188
  31. package/dist/test-utils.mjs.map +1 -1
  32. package/dist/types.d.ts +1 -1
  33. package/dist/types.d.ts.map +1 -1
  34. package/dist/utils/consolidate-coins.d.ts +43 -0
  35. package/dist/utils/consolidate-coins.d.ts.map +1 -0
  36. package/package.json +14 -14
package/dist/index.mjs CHANGED
@@ -705,11 +705,11 @@ var getAssetsByOwner = /* @__PURE__ */ __name(async (opts) => {
705
705
 
706
706
  // src/account.ts
707
707
  import { UTXO_ID_LEN as UTXO_ID_LEN3 } from "@fuel-ts/abi-coder";
708
- import { Address as Address4 } from "@fuel-ts/address";
708
+ import { Address as Address5 } from "@fuel-ts/address";
709
709
  import { randomBytes as randomBytes2 } from "@fuel-ts/crypto";
710
- import { ErrorCode as ErrorCode19, FuelError as FuelError21 } from "@fuel-ts/errors";
711
- import { bn as bn21 } from "@fuel-ts/math";
712
- import { InputType as InputType8, OutputType as OutputType9 } from "@fuel-ts/transactions";
710
+ import { ErrorCode as ErrorCode20, FuelError as FuelError22 } from "@fuel-ts/errors";
711
+ import { bn as bn22 } from "@fuel-ts/math";
712
+ import { InputType as InputType8, OutputType as OutputType10 } from "@fuel-ts/transactions";
713
713
  import { arrayify as arrayify17, hexlify as hexlify18, isDefined as isDefined4 } from "@fuel-ts/utils";
714
714
  import { clone as clone9 } from "ramda";
715
715
 
@@ -2152,8 +2152,11 @@ import { print } from "graphql";
2152
2152
 
2153
2153
  // src/providers/utils/handle-gql-error-message.ts
2154
2154
  import { ErrorCode as ErrorCode2, FuelError as FuelError2 } from "@fuel-ts/errors";
2155
+ var ASSET_ID_REGEX = /[0-9a-fA-F]{32,64}/g;
2155
2156
  var gqlErrorMessage = {
2156
2157
  RPC_CONSISTENCY: /The required fuel block height is higher than the current block height. Required: \d+, Current: \d+/,
2158
+ INSUFFICIENT_FUNDS: /the target cannot be met due to insufficient coins available for [0-9a-fA-F]{32,64}. Collected: \d+/,
2159
+ MAX_COINS_REACHED: /the target for [0-9a-fA-F]{32,64} cannot be met due to exceeding the \d+ coin limit. Collected: \d+./,
2157
2160
  NOT_ENOUGH_COINS_MAX_COINS: /the target cannot be met due to no coins available or exceeding the \d+ coin limit./,
2158
2161
  ASSET_NOT_FOUND: /resource was not found in table/,
2159
2162
  MULTIPLE_CHANGE_POLICIES: /The asset ([a-fA-F0-9]{64}) has multiple change policies/,
@@ -2169,6 +2172,46 @@ var mapGqlErrorMessage = /* @__PURE__ */ __name((error) => {
2169
2172
  error
2170
2173
  );
2171
2174
  }
2175
+ if (gqlErrorMessage.MAX_COINS_REACHED.test(error.message)) {
2176
+ const matches = error.message.match(ASSET_ID_REGEX);
2177
+ const assetId = matches ? `0x${matches[0]}` : null;
2178
+ const owner = matches ? `0x${matches[1]}` : null;
2179
+ let suffix = "";
2180
+ if (assetId) {
2181
+ suffix += `
2182
+ Asset ID: '${assetId}'.`;
2183
+ }
2184
+ if (owner) {
2185
+ suffix += `
2186
+ Owner: '${owner}'.`;
2187
+ }
2188
+ return new FuelError2(
2189
+ ErrorCode2.MAX_COINS_REACHED,
2190
+ `You have too many small value coins - consider combining UTXOs.${suffix}`,
2191
+ { assetId, owner },
2192
+ error
2193
+ );
2194
+ }
2195
+ if (gqlErrorMessage.INSUFFICIENT_FUNDS.test(error.message)) {
2196
+ const matches = error.message.match(ASSET_ID_REGEX);
2197
+ const assetId = matches ? `0x${matches[0]}` : null;
2198
+ const owner = matches ? `0x${matches[1]}` : null;
2199
+ let suffix = "";
2200
+ if (assetId) {
2201
+ suffix += `
2202
+ Asset ID: '${assetId}'.`;
2203
+ }
2204
+ if (owner) {
2205
+ suffix += `
2206
+ Owner: '${owner}'.`;
2207
+ }
2208
+ return new FuelError2(
2209
+ ErrorCode2.INSUFFICIENT_FUNDS,
2210
+ `Insufficient funds.${suffix}`,
2211
+ { assetId, owner },
2212
+ error
2213
+ );
2214
+ }
2172
2215
  if (gqlErrorMessage.MULTIPLE_CHANGE_POLICIES.test(error.message)) {
2173
2216
  const match = error.message.match(/asset ([a-fA-F0-9]{64})/);
2174
2217
  const assetId = match?.[1] || "";
@@ -3335,6 +3378,7 @@ This error originated at ${JSON.stringify(pos, null, 2)}` : "";
3335
3378
  }
3336
3379
  return new FuelError8(ErrorCode8.SCRIPT_REVERTED, errorMessage, {
3337
3380
  ...metadata,
3381
+ abiError,
3338
3382
  reason
3339
3383
  });
3340
3384
  }
@@ -4389,11 +4433,15 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
4389
4433
  * @deprecated Use `provider.assembleTx` instead.
4390
4434
  * Check the migration guide https://docs.fuel.network/guide/assembling-transactions/migration-guide.html for more information.
4391
4435
  */
4392
- async estimateAndFund(account, { signatureCallback, quantities = [] } = {}) {
4436
+ async estimateAndFund(account, {
4437
+ signatureCallback,
4438
+ quantities = [],
4439
+ skipAutoConsolidation
4440
+ } = {}) {
4393
4441
  const txCost = await account.getTransactionCost(this, { signatureCallback, quantities });
4394
4442
  this.maxFee = txCost.maxFee;
4395
4443
  this.gasLimit = txCost.gasUsed;
4396
- await account.fund(this, txCost);
4444
+ await account.fund(this, txCost, { skipAutoConsolidation });
4397
4445
  return this;
4398
4446
  }
4399
4447
  /**
@@ -6022,25 +6070,6 @@ __name(getAllDecodedLogs, "getAllDecodedLogs");
6022
6070
 
6023
6071
  // src/providers/transaction-response/transaction-response.ts
6024
6072
  var TransactionResponse = class _TransactionResponse {
6025
- /**
6026
- * Constructor for `TransactionResponse`.
6027
- *
6028
- * @param tx - The transaction ID or TransactionRequest.
6029
- * @param provider - The provider.
6030
- */
6031
- constructor(tx, provider, chainId, abis, submitTxSubscription) {
6032
- this.submitTxSubscription = submitTxSubscription;
6033
- if (typeof tx === "string") {
6034
- this.id = tx;
6035
- } else {
6036
- this.id = tx.getTransactionId(chainId);
6037
- this.request = tx;
6038
- }
6039
- this.provider = provider;
6040
- this.abis = abis;
6041
- this.waitForResult = this.waitForResult.bind(this);
6042
- this.waitForPreConfirmation = this.waitForPreConfirmation.bind(this);
6043
- }
6044
6073
  static {
6045
6074
  __name(this, "TransactionResponse");
6046
6075
  }
@@ -6055,9 +6084,42 @@ var TransactionResponse = class _TransactionResponse {
6055
6084
  request;
6056
6085
  status;
6057
6086
  abis;
6087
+ submitTxSubscription;
6058
6088
  preConfirmationStatus;
6059
6089
  waitingForStreamData = false;
6060
6090
  statusResolvers = /* @__PURE__ */ new Map();
6091
+ /**
6092
+ * Constructor for `TransactionResponse`.
6093
+ */
6094
+ constructor(constructorParams, provider, chainId, abis, submitTxSubscription) {
6095
+ let tx;
6096
+ let _provider;
6097
+ let _chainId;
6098
+ let _abis;
6099
+ if (typeof constructorParams === "object" && "provider" in constructorParams && arguments.length === 1) {
6100
+ tx = constructorParams.transactionRequestOrId;
6101
+ _provider = constructorParams.provider;
6102
+ _chainId = constructorParams.chainId;
6103
+ _abis = constructorParams.abis;
6104
+ this.submitTxSubscription = constructorParams.submitAndAwaitSubscription;
6105
+ } else {
6106
+ tx = constructorParams;
6107
+ _provider = provider;
6108
+ _chainId = chainId;
6109
+ _abis = abis;
6110
+ this.submitTxSubscription = submitTxSubscription;
6111
+ }
6112
+ if (typeof tx === "string") {
6113
+ this.id = tx;
6114
+ } else {
6115
+ this.id = tx.getTransactionId(_chainId);
6116
+ this.request = tx;
6117
+ }
6118
+ this.provider = _provider;
6119
+ this.abis = _abis;
6120
+ this.waitForResult = this.waitForResult.bind(this);
6121
+ this.waitForPreConfirmation = this.waitForPreConfirmation.bind(this);
6122
+ }
6061
6123
  /**
6062
6124
  * Async constructor for `TransactionResponse`. This method can be used to create
6063
6125
  * an instance of `TransactionResponse` and wait for the transaction to be fetched
@@ -6597,7 +6659,15 @@ var Provider = class _Provider {
6597
6659
  if (_Provider.ENABLE_RPC_CONSISTENCY && _Provider.hasWriteOperationHappened(url)) {
6598
6660
  _Provider.applyBlockHeight(fullRequest, url);
6599
6661
  }
6600
- return _Provider.fetchAndProcessBlockHeight(url, fullRequest, options);
6662
+ const response = await _Provider.fetchAndProcessBlockHeight(url, fullRequest, options);
6663
+ if (response.body === null) {
6664
+ throw new FuelError19(
6665
+ ErrorCode17.RESPONSE_BODY_EMPTY,
6666
+ "The response from the server is missing the body",
6667
+ { timestamp: (/* @__PURE__ */ new Date()).toISOString(), request: request2, response }
6668
+ );
6669
+ }
6670
+ return response;
6601
6671
  }, retryOptions);
6602
6672
  }
6603
6673
  static applyBlockHeight(request2, url) {
@@ -6620,13 +6690,15 @@ var Provider = class _Provider {
6620
6690
  baseDelay: 500
6621
6691
  };
6622
6692
  for (let retriesLeft = retryOptions.maxRetries; retriesLeft > 0; --retriesLeft) {
6623
- const { extensions } = await parseGraphqlResponse({
6624
- response,
6625
- isSubscription: url.endsWith("-sub")
6626
- });
6627
- _Provider.setCurrentBlockHeight(url, extensions?.current_fuel_block_height);
6628
- if (!extensions?.fuel_block_height_precondition_failed) {
6629
- break;
6693
+ if (response.body) {
6694
+ const { extensions } = await parseGraphqlResponse({
6695
+ response,
6696
+ isSubscription: url.endsWith("-sub")
6697
+ });
6698
+ _Provider.setCurrentBlockHeight(url, extensions?.current_fuel_block_height);
6699
+ if (!extensions?.fuel_block_height_precondition_failed) {
6700
+ break;
6701
+ }
6630
6702
  }
6631
6703
  const retryAttempt = retryOptions.maxRetries - retriesLeft + 1;
6632
6704
  const sleepTime = getWaitDelay(retryOptions, retryAttempt);
@@ -7049,7 +7121,13 @@ var Provider = class _Provider {
7049
7121
  transactionRequest.getTransactionId(await this.getChainId())
7050
7122
  );
7051
7123
  const chainId = await this.getChainId();
7052
- return new TransactionResponse(transactionRequest, this, chainId, abis, subscription);
7124
+ return new TransactionResponse({
7125
+ transactionRequestOrId: transactionRequest,
7126
+ provider: this,
7127
+ chainId,
7128
+ abis,
7129
+ submitAndAwaitSubscription: subscription
7130
+ });
7053
7131
  }
7054
7132
  /**
7055
7133
  * Executes a transaction without actually submitting it to the chain.
@@ -8144,7 +8222,11 @@ var Provider = class _Provider {
8144
8222
  */
8145
8223
  async getTransactionResponse(transactionId) {
8146
8224
  const chainId = await this.getChainId();
8147
- return new TransactionResponse(transactionId, this, chainId);
8225
+ return new TransactionResponse({
8226
+ transactionRequestOrId: transactionId,
8227
+ provider: this,
8228
+ chainId
8229
+ });
8148
8230
  }
8149
8231
  /**
8150
8232
  * Returns Message for given nonce.
@@ -8475,7 +8557,12 @@ var deserializeTransactionResponseJson = /* @__PURE__ */ __name((json) => {
8475
8557
  } = json;
8476
8558
  const provider = new Provider(providerUrl, { cache: providerCache });
8477
8559
  const { chainId } = providerCache.chain.consensusParameters;
8478
- const response = new TransactionResponse(id, provider, Number(chainId), abis);
8560
+ const response = new TransactionResponse({
8561
+ transactionRequestOrId: id,
8562
+ provider,
8563
+ chainId: Number(chainId),
8564
+ abis
8565
+ });
8479
8566
  if (requestJson) {
8480
8567
  response.request = transactionRequestify(JSON.parse(requestJson));
8481
8568
  }
@@ -8492,9 +8579,157 @@ var AbstractAccount = class {
8492
8579
  }
8493
8580
  };
8494
8581
 
8582
+ // src/utils/consolidate-coins.ts
8583
+ import { Address as Address3 } from "@fuel-ts/address";
8584
+ import { ErrorCode as ErrorCode19, FuelError as FuelError21 } from "@fuel-ts/errors";
8585
+ import { bn as bn21 } from "@fuel-ts/math";
8586
+ import { OutputType as OutputType9 } from "@fuel-ts/transactions";
8587
+ import { splitEvery } from "ramda";
8588
+ var CONSOLIDATABLE_ERROR_CODES = [ErrorCode19.MAX_COINS_REACHED];
8589
+ var consolidateCoinsIfRequired = /* @__PURE__ */ __name(async (opts) => {
8590
+ const { error: errorUnknown, account, skipAutoConsolidation = false } = opts;
8591
+ if (skipAutoConsolidation) {
8592
+ return false;
8593
+ }
8594
+ const error = FuelError21.parse(errorUnknown);
8595
+ if (CONSOLIDATABLE_ERROR_CODES.includes(error.code)) {
8596
+ const { assetId, owner } = error.metadata;
8597
+ return account.startConsolidation({
8598
+ owner,
8599
+ assetId
8600
+ });
8601
+ }
8602
+ return false;
8603
+ }, "consolidateCoinsIfRequired");
8604
+ var getAllCoins = /* @__PURE__ */ __name(async (account, assetId) => {
8605
+ const all = [];
8606
+ let hasNextPage = true;
8607
+ let after;
8608
+ while (hasNextPage) {
8609
+ const { coins, pageInfo } = await account.getCoins(assetId, { after });
8610
+ all.push(...coins);
8611
+ after = coins.pop()?.id;
8612
+ hasNextPage = pageInfo.hasNextPage;
8613
+ }
8614
+ return { coins: all };
8615
+ }, "getAllCoins");
8616
+ var sortCoins = /* @__PURE__ */ __name(({ coins }) => coins.sort((a, b) => b.amount.cmp(a.amount)), "sortCoins");
8617
+ var createOuputCoin = /* @__PURE__ */ __name((opts) => {
8618
+ const { transactionId, outputs, baseAssetId } = opts;
8619
+ const outputChangeIndex = outputs.findIndex(
8620
+ (output) => output.type === OutputType9.Change && output.assetId === baseAssetId
8621
+ );
8622
+ if (outputChangeIndex === -1) {
8623
+ throw new FuelError21(ErrorCode19.UNKNOWN, "No change output found");
8624
+ }
8625
+ const outputCoin = outputs[outputChangeIndex];
8626
+ const outputIndexPadded = Number(outputChangeIndex).toString().padStart(4, "0");
8627
+ return {
8628
+ id: `${transactionId}${outputIndexPadded}`,
8629
+ assetId: outputCoin.assetId,
8630
+ amount: outputCoin.amount,
8631
+ owner: new Address3(outputCoin.to),
8632
+ blockCreated: bn21(0),
8633
+ txCreatedIdx: bn21(0)
8634
+ };
8635
+ }, "createOuputCoin");
8636
+ var consolidateCoins = /* @__PURE__ */ __name(async ({
8637
+ account,
8638
+ assetId
8639
+ }) => {
8640
+ const chainInfo = await account.provider.getChain();
8641
+ const chainId = chainInfo.consensusParameters.chainId.toNumber();
8642
+ const gasPrice = await account.provider.estimateGasPrice(10);
8643
+ const maxInputs = chainInfo.consensusParameters.txParameters.maxInputs.toNumber();
8644
+ const baseAssetId = await account.provider.getBaseAssetId();
8645
+ const isBaseAsset = assetId === baseAssetId;
8646
+ const batchSize = maxInputs;
8647
+ const numberOfFundingCoins = maxInputs;
8648
+ let funding = [];
8649
+ let dust = [];
8650
+ if (isBaseAsset) {
8651
+ const coins = await getAllCoins(account, baseAssetId).then(sortCoins);
8652
+ funding = coins.slice(0, numberOfFundingCoins);
8653
+ dust = coins.slice(numberOfFundingCoins);
8654
+ } else {
8655
+ funding = await getAllCoins(account, baseAssetId).then(sortCoins).then((coins) => coins.slice(0, numberOfFundingCoins));
8656
+ dust = await getAllCoins(account, assetId).then(({ coins }) => coins);
8657
+ }
8658
+ if (funding.length === 0) {
8659
+ throw new FuelError21(
8660
+ ErrorCode19.INSUFFICIENT_FUNDS,
8661
+ `Insufficient funds to consolidate.
8662
+ Asset ID: ${baseAssetId}
8663
+ Owner: ${account.address.toB256()}`
8664
+ );
8665
+ }
8666
+ const batches = [
8667
+ ...splitEvery(batchSize, funding),
8668
+ // We leave one coin for the funding coin
8669
+ ...splitEvery(batchSize - 1, dust)
8670
+ ];
8671
+ const txs = batches.map((batch) => {
8672
+ const request2 = new ScriptTransactionRequest({
8673
+ scriptData: "0x"
8674
+ });
8675
+ request2.addResources(batch);
8676
+ return request2;
8677
+ });
8678
+ const submitAll = /* @__PURE__ */ __name(async (opts = {}) => {
8679
+ const txResponses = [];
8680
+ let previousTx;
8681
+ for (let i = 0; i < txs.length; i++) {
8682
+ let currentTx = txs[i];
8683
+ const step = i + 1;
8684
+ if (previousTx) {
8685
+ const coin = createOuputCoin({
8686
+ transactionId: previousTx.transactionId,
8687
+ outputs: previousTx.outputs,
8688
+ baseAssetId
8689
+ });
8690
+ currentTx.addResource(coin);
8691
+ }
8692
+ if ("populateTransactionPredicateData" in account && typeof account.populateTransactionPredicateData === "function") {
8693
+ currentTx = account.populateTransactionPredicateData(currentTx);
8694
+ currentTx = await account.provider.estimatePredicates(currentTx);
8695
+ }
8696
+ const fee = calculateGasFee({
8697
+ gasPrice,
8698
+ gas: currentTx.calculateMinGas(chainInfo),
8699
+ priceFactor: chainInfo.consensusParameters.feeParameters.gasPriceFactor,
8700
+ tip: currentTx.tip
8701
+ });
8702
+ currentTx.maxFee = fee;
8703
+ currentTx.gasLimit = bn21(1e3);
8704
+ opts.onTransactionStart?.({
8705
+ tx: currentTx,
8706
+ step,
8707
+ assetId,
8708
+ transactionId: currentTx.getTransactionId(chainId)
8709
+ });
8710
+ const response = await account.sendTransaction(currentTx);
8711
+ const result = await response.waitForResult();
8712
+ txResponses.push(result);
8713
+ previousTx = {
8714
+ transactionId: response.id,
8715
+ outputs: result.transaction.outputs
8716
+ };
8717
+ }
8718
+ return {
8719
+ txResponses,
8720
+ errors: []
8721
+ };
8722
+ }, "submitAll");
8723
+ return {
8724
+ txs,
8725
+ totalFeeCost: txs.reduce((acc, request2) => acc.add(request2.maxFee), bn21(0)),
8726
+ submitAll
8727
+ };
8728
+ }, "consolidateCoins");
8729
+
8495
8730
  // src/utils/formatTransferToContractScriptData.ts
8496
8731
  import { ASSET_ID_LEN, BigNumberCoder as BigNumberCoder3, CONTRACT_ID_LEN, WORD_SIZE } from "@fuel-ts/abi-coder";
8497
- import { Address as Address3 } from "@fuel-ts/address";
8732
+ import { Address as Address4 } from "@fuel-ts/address";
8498
8733
  import { arrayify as arrayify16, concat as concat4 } from "@fuel-ts/utils";
8499
8734
  import * as asm from "@fuels/vm-asm";
8500
8735
  var formatTransferToContractScriptData = /* @__PURE__ */ __name((transferParams) => {
@@ -8502,7 +8737,7 @@ var formatTransferToContractScriptData = /* @__PURE__ */ __name((transferParams)
8502
8737
  return transferParams.reduce((acc, transferParam) => {
8503
8738
  const { assetId, amount, contractId } = transferParam;
8504
8739
  const encoded = numberCoder.encode(amount);
8505
- const scriptData = concat4([new Address3(contractId).toBytes(), encoded, arrayify16(assetId)]);
8740
+ const scriptData = concat4([new Address4(contractId).toBytes(), encoded, arrayify16(assetId)]);
8506
8741
  return concat4([acc, scriptData]);
8507
8742
  }, new Uint8Array());
8508
8743
  }, "formatTransferToContractScriptData");
@@ -8573,7 +8808,7 @@ var Account = class extends AbstractAccount {
8573
8808
  super();
8574
8809
  this._provider = provider;
8575
8810
  this._connector = connector;
8576
- this.address = new Address4(address);
8811
+ this.address = new Address5(address);
8577
8812
  }
8578
8813
  /**
8579
8814
  * The provider used to interact with the network.
@@ -8584,7 +8819,7 @@ var Account = class extends AbstractAccount {
8584
8819
  */
8585
8820
  get provider() {
8586
8821
  if (!this._provider) {
8587
- throw new FuelError21(ErrorCode19.MISSING_PROVIDER, "Provider not set");
8822
+ throw new FuelError22(ErrorCode20.MISSING_PROVIDER, "Provider not set");
8588
8823
  }
8589
8824
  return this._provider;
8590
8825
  }
@@ -8611,10 +8846,24 @@ var Account = class extends AbstractAccount {
8611
8846
  *
8612
8847
  * @param quantities - Quantities of resources to be obtained.
8613
8848
  * @param resourcesIdsToIgnore - IDs of resources to be excluded from the query (optional).
8849
+ * @param skipAutoConsolidation - Whether to skip the automatic consolidatation of coins process (optional).
8614
8850
  * @returns A promise that resolves to an array of Resources.
8615
8851
  */
8616
- async getResourcesToSpend(quantities, resourcesIdsToIgnore) {
8617
- return this.provider.getResourcesToSpend(this.address, quantities, resourcesIdsToIgnore);
8852
+ async getResourcesToSpend(quantities, resourcesIdsToIgnore, { skipAutoConsolidation } = {}) {
8853
+ const getResourcesToSpend = /* @__PURE__ */ __name(() => this.provider.getResourcesToSpend(this.address, quantities, resourcesIdsToIgnore), "getResourcesToSpend");
8854
+ try {
8855
+ return await getResourcesToSpend();
8856
+ } catch (error) {
8857
+ const shouldRetry = await consolidateCoinsIfRequired({
8858
+ error,
8859
+ account: this,
8860
+ skipAutoConsolidation
8861
+ });
8862
+ if (!shouldRetry) {
8863
+ throw error;
8864
+ }
8865
+ return await getResourcesToSpend();
8866
+ }
8618
8867
  }
8619
8868
  /**
8620
8869
  * Retrieves coins owned by the account.
@@ -8663,7 +8912,7 @@ var Account = class extends AbstractAccount {
8663
8912
  * @deprecated Use provider.assembleTx instead
8664
8913
  * Check the migration guide https://docs.fuel.network/docs/fuels-ts/transactions/assemble-tx-migration-guide/ for more information.
8665
8914
  */
8666
- async fund(request2, params) {
8915
+ async fund(request2, params, { skipAutoConsolidation } = {}) {
8667
8916
  const {
8668
8917
  addedSignatures,
8669
8918
  estimatedPredicates,
@@ -8675,9 +8924,9 @@ var Account = class extends AbstractAccount {
8675
8924
  const chainId = await this.provider.getChainId();
8676
8925
  const fee = request2.maxFee;
8677
8926
  const baseAssetId = await this.provider.getBaseAssetId();
8678
- const requiredInBaseAsset = requiredQuantities.find((quantity) => quantity.assetId === baseAssetId)?.amount || bn21(0);
8927
+ const requiredInBaseAsset = requiredQuantities.find((quantity) => quantity.assetId === baseAssetId)?.amount || bn22(0);
8679
8928
  const requiredQuantitiesWithFee = addAmountToCoinQuantities({
8680
- amount: bn21(fee),
8929
+ amount: bn22(fee),
8681
8930
  assetId: baseAssetId,
8682
8931
  coinQuantities: requiredQuantities
8683
8932
  });
@@ -8685,7 +8934,7 @@ var Account = class extends AbstractAccount {
8685
8934
  requiredQuantitiesWithFee.forEach(({ amount, assetId }) => {
8686
8935
  quantitiesDict[assetId] = {
8687
8936
  required: amount,
8688
- owned: bn21(0)
8937
+ owned: bn22(0)
8689
8938
  };
8690
8939
  });
8691
8940
  request2.inputs.filter(isRequestInputResource).forEach((input) => {
@@ -8709,7 +8958,8 @@ var Account = class extends AbstractAccount {
8709
8958
  while (needsToBeFunded && fundingAttempts < MAX_FUNDING_ATTEMPTS) {
8710
8959
  const resources = await this.getResourcesToSpend(
8711
8960
  missingQuantities,
8712
- cacheRequestInputsResourcesFromOwner(request2.inputs, this.address)
8961
+ cacheRequestInputsResourcesFromOwner(request2.inputs, this.address),
8962
+ { skipAutoConsolidation }
8713
8963
  );
8714
8964
  request2.addResources(resources);
8715
8965
  request2.updatePredicateGasUsed(estimatedPredicates);
@@ -8746,8 +8996,8 @@ var Account = class extends AbstractAccount {
8746
8996
  fundingAttempts += 1;
8747
8997
  }
8748
8998
  if (needsToBeFunded) {
8749
- throw new FuelError21(
8750
- ErrorCode19.INSUFFICIENT_FUNDS_OR_MAX_COINS,
8999
+ throw new FuelError22(
9000
+ ErrorCode20.INSUFFICIENT_FUNDS,
8751
9001
  `The account ${this.address} does not have enough base asset funds to cover the transaction execution.`
8752
9002
  );
8753
9003
  }
@@ -8775,16 +9025,20 @@ var Account = class extends AbstractAccount {
8775
9025
  * @param amount - The amount of coins to transfer.
8776
9026
  * @param assetId - The asset ID of the coins to transfer (optional).
8777
9027
  * @param txParams - The transaction parameters (optional).
9028
+ * @param skipAutoConsolidation - Whether to skip the automatic consolidatation of coins process (optional).
8778
9029
  * @returns A promise that resolves to the prepared transaction request.
8779
9030
  */
8780
- async createTransfer(destination, amount, assetId, txParams = {}) {
9031
+ async createTransfer(destination, amount, assetId, txParams = {}, { skipAutoConsolidation } = {}) {
8781
9032
  let request2 = new ScriptTransactionRequest(txParams);
8782
9033
  request2 = this.addTransfer(request2, {
8783
9034
  destination,
8784
9035
  amount,
8785
9036
  assetId: assetId || await this.provider.getBaseAssetId()
8786
9037
  });
8787
- const { gasPrice, transactionRequest } = await this.assembleTx(request2);
9038
+ const { gasPrice, transactionRequest } = await this.assembleTx({
9039
+ transactionRequest: request2,
9040
+ skipAutoConsolidation
9041
+ });
8788
9042
  request2 = await setAndValidateGasAndFeeForAssembledTx({
8789
9043
  gasPrice,
8790
9044
  provider: this.provider,
@@ -8801,10 +9055,13 @@ var Account = class extends AbstractAccount {
8801
9055
  * @param amount - The amount of coins to transfer.
8802
9056
  * @param assetId - The asset ID of the coins to transfer (optional).
8803
9057
  * @param txParams - The transaction parameters (optional).
9058
+ * @param skipAutoConsolidation - Whether to skip the automatic consolidatation of coins process (optional).
8804
9059
  * @returns A promise that resolves to the transaction response.
8805
9060
  */
8806
- async transfer(destination, amount, assetId, txParams = {}) {
8807
- const request2 = await this.createTransfer(destination, amount, assetId, txParams);
9061
+ async transfer(destination, amount, assetId, txParams = {}, { skipAutoConsolidation } = {}) {
9062
+ const request2 = await this.createTransfer(destination, amount, assetId, txParams, {
9063
+ skipAutoConsolidation
9064
+ });
8808
9065
  return this.sendTransaction(request2, { estimateTxDependencies: false });
8809
9066
  }
8810
9067
  /**
@@ -8812,12 +9069,16 @@ var Account = class extends AbstractAccount {
8812
9069
  *
8813
9070
  * @param transferParams - An array of `TransferParams` objects representing the transfers to be made.
8814
9071
  * @param txParams - Optional transaction parameters.
9072
+ * @param skipAutoConsolidation - Whether to skip the automatic consolidatation of coins process (optional).
8815
9073
  * @returns A promise that resolves to a `TransactionResponse` object representing the transaction result.
8816
9074
  */
8817
- async batchTransfer(transferParams, txParams = {}) {
9075
+ async batchTransfer(transferParams, txParams = {}, { skipAutoConsolidation } = {}) {
8818
9076
  let request2 = new ScriptTransactionRequest(txParams);
8819
9077
  request2 = this.addBatchTransfer(request2, transferParams);
8820
- const { gasPrice, transactionRequest } = await this.assembleTx(request2);
9078
+ const { gasPrice, transactionRequest } = await this.assembleTx({
9079
+ transactionRequest: request2,
9080
+ skipAutoConsolidation
9081
+ });
8821
9082
  request2 = await setAndValidateGasAndFeeForAssembledTx({
8822
9083
  gasPrice,
8823
9084
  provider: this.provider,
@@ -8837,7 +9098,7 @@ var Account = class extends AbstractAccount {
8837
9098
  addTransfer(request2, transferParams) {
8838
9099
  const { destination, amount, assetId } = transferParams;
8839
9100
  this.validateTransferAmount(amount);
8840
- request2.addCoinOutput(new Address4(destination), amount, assetId);
9101
+ request2.addCoinOutput(new Address5(destination), amount, assetId);
8841
9102
  return request2;
8842
9103
  }
8843
9104
  /**
@@ -8864,24 +9125,27 @@ var Account = class extends AbstractAccount {
8864
9125
  * @param amount - The amount of coins to transfer.
8865
9126
  * @param assetId - The asset ID of the coins to transfer (optional).
8866
9127
  * @param txParams - The transaction parameters (optional).
9128
+ * @param skipAutoConsolidation - Whether to skip the automatic consolidatation of coins process (optional).
8867
9129
  * @returns A promise that resolves to the transaction response.
8868
9130
  */
8869
- async transferToContract(contractId, amount, assetId, txParams = {}) {
8870
- return this.batchTransferToContracts([{ amount, assetId, contractId }], txParams);
9131
+ async transferToContract(contractId, amount, assetId, txParams = {}, { skipAutoConsolidation } = {}) {
9132
+ return this.batchTransferToContracts([{ amount, assetId, contractId }], txParams, {
9133
+ skipAutoConsolidation
9134
+ });
8871
9135
  }
8872
- async batchTransferToContracts(contractTransferParams, txParams = {}) {
9136
+ async batchTransferToContracts(contractTransferParams, txParams = {}, { skipAutoConsolidation } = {}) {
8873
9137
  let request2 = new ScriptTransactionRequest({
8874
9138
  ...txParams
8875
9139
  });
8876
9140
  const quantities = [];
8877
9141
  const defaultAssetId = await this.provider.getBaseAssetId();
8878
9142
  const transferParams = contractTransferParams.map((transferParam) => {
8879
- const amount = bn21(transferParam.amount);
8880
- const contractAddress = new Address4(transferParam.contractId);
9143
+ const amount = bn22(transferParam.amount);
9144
+ const contractAddress = new Address5(transferParam.contractId);
8881
9145
  const assetId = transferParam.assetId ? hexlify18(transferParam.assetId) : defaultAssetId;
8882
9146
  if (amount.lte(0)) {
8883
- throw new FuelError21(
8884
- ErrorCode19.INVALID_TRANSFER_AMOUNT,
9147
+ throw new FuelError22(
9148
+ ErrorCode20.INVALID_TRANSFER_AMOUNT,
8885
9149
  "Transfer amount must be a positive number."
8886
9150
  );
8887
9151
  }
@@ -8896,7 +9160,11 @@ var Account = class extends AbstractAccount {
8896
9160
  const { script, scriptData } = await assembleTransferToContractScript(transferParams);
8897
9161
  request2.script = script;
8898
9162
  request2.scriptData = scriptData;
8899
- const { gasPrice, transactionRequest } = await this.assembleTx(request2, quantities);
9163
+ const { gasPrice, transactionRequest } = await this.assembleTx({
9164
+ transactionRequest: request2,
9165
+ quantities,
9166
+ skipAutoConsolidation
9167
+ });
8900
9168
  request2 = await setAndValidateGasAndFeeForAssembledTx({
8901
9169
  gasPrice,
8902
9170
  provider: this.provider,
@@ -8912,15 +9180,16 @@ var Account = class extends AbstractAccount {
8912
9180
  * @param recipient - Address of the recipient on the base chain.
8913
9181
  * @param amount - Amount of base asset.
8914
9182
  * @param txParams - The transaction parameters (optional).
9183
+ * @param skipAutoConsolidation - Whether to skip the automatic consolidatation of coins process (optional).
8915
9184
  * @returns A promise that resolves to the transaction response.
8916
9185
  */
8917
- async withdrawToBaseLayer(recipient, amount, txParams = {}) {
8918
- const recipientAddress = new Address4(recipient);
9186
+ async withdrawToBaseLayer(recipient, amount, txParams = {}, { skipAutoConsolidation } = {}) {
9187
+ const recipientAddress = new Address5(recipient);
8919
9188
  const recipientDataArray = arrayify17(
8920
9189
  "0x".concat(recipientAddress.toHexString().substring(2).padStart(64, "0"))
8921
9190
  );
8922
9191
  const amountDataArray = arrayify17(
8923
- "0x".concat(bn21(amount).toHex().substring(2).padStart(16, "0"))
9192
+ "0x".concat(bn22(amount).toHex().substring(2).padStart(16, "0"))
8924
9193
  );
8925
9194
  const script = new Uint8Array([
8926
9195
  ...arrayify17(withdrawScript.bytes),
@@ -8930,8 +9199,12 @@ var Account = class extends AbstractAccount {
8930
9199
  const params = { script, ...txParams };
8931
9200
  const baseAssetId = await this.provider.getBaseAssetId();
8932
9201
  let request2 = new ScriptTransactionRequest(params);
8933
- const quantities = [{ amount: bn21(amount), assetId: baseAssetId }];
8934
- const { gasPrice, transactionRequest } = await this.assembleTx(request2, quantities);
9202
+ const quantities = [{ amount: bn22(amount), assetId: baseAssetId }];
9203
+ const { gasPrice, transactionRequest } = await this.assembleTx({
9204
+ transactionRequest: request2,
9205
+ quantities,
9206
+ skipAutoConsolidation
9207
+ });
8935
9208
  request2 = await setAndValidateGasAndFeeForAssembledTx({
8936
9209
  gasPrice,
8937
9210
  provider: this.provider,
@@ -8941,6 +9214,25 @@ var Account = class extends AbstractAccount {
8941
9214
  });
8942
9215
  return this.sendTransaction(request2);
8943
9216
  }
9217
+ /**
9218
+ * Start the consolidation process
9219
+ *
9220
+ * @param owner - The B256 address of the owner.
9221
+ * @param assetId - The asset ID that requires consolidation.
9222
+ */
9223
+ async startConsolidation(opts) {
9224
+ if (this._connector) {
9225
+ await this._connector.startConsolidation(opts);
9226
+ return false;
9227
+ }
9228
+ const { owner, assetId } = opts;
9229
+ if (owner !== this.address.toB256()) {
9230
+ return false;
9231
+ }
9232
+ const { submitAll } = await consolidateCoins({ account: this, assetId });
9233
+ await submitAll();
9234
+ return true;
9235
+ }
8944
9236
  /**
8945
9237
  * Consolidates base asset UTXOs into fewer, larger ones.
8946
9238
  *
@@ -8960,6 +9252,7 @@ var Account = class extends AbstractAccount {
8960
9252
  const isBaseAsset = baseAssetId === assetId;
8961
9253
  let submitAll;
8962
9254
  const consolidationParams = {
9255
+ assetId,
8963
9256
  coins,
8964
9257
  mode: params.mode,
8965
9258
  outputNum: params.outputNum
@@ -8967,10 +9260,7 @@ var Account = class extends AbstractAccount {
8967
9260
  if (isBaseAsset) {
8968
9261
  ({ submitAll } = await this.assembleBaseAssetConsolidationTxs(consolidationParams));
8969
9262
  } else {
8970
- throw new FuelError21(
8971
- ErrorCode19.UNSUPPORTED_FEATURE,
8972
- "Consolidation for non-base assets is not supported yet."
8973
- );
9263
+ ({ submitAll } = await this.assembleNonBaseAssetConsolidationTxs(consolidationParams));
8974
9264
  }
8975
9265
  return submitAll();
8976
9266
  }
@@ -8991,7 +9281,7 @@ var Account = class extends AbstractAccount {
8991
9281
  this.validateConsolidationTxsCoins(coins, baseAssetId);
8992
9282
  const chainInfo = await this.provider.getChain();
8993
9283
  const maxInputsNumber = chainInfo.consensusParameters.txParameters.maxInputs.toNumber();
8994
- let totalFeeCost = bn21(0);
9284
+ let totalFeeCost = bn22(0);
8995
9285
  const txs = [];
8996
9286
  const coinsBatches = splitCoinsIntoBatches(coins, maxInputsNumber);
8997
9287
  const gasPrice = await this.provider.estimateGasPrice(10);
@@ -9015,10 +9305,10 @@ var Account = class extends AbstractAccount {
9015
9305
  });
9016
9306
  request2.maxFee = fee;
9017
9307
  if (consolidateMoreThanOneCoin) {
9018
- const total = request2.inputs.filter(isRequestInputCoin).reduce((acc, input) => acc.add(input.amount), bn21(0));
9308
+ const total = request2.inputs.filter(isRequestInputCoin).reduce((acc, input) => acc.add(input.amount), bn22(0));
9019
9309
  const amountPerNewUtxo = total.div(outputNum + 1);
9020
9310
  request2.outputs.forEach((output) => {
9021
- if (output.type === OutputType9.Coin) {
9311
+ if (output.type === OutputType10.Coin) {
9022
9312
  output.amount = amountPerNewUtxo;
9023
9313
  }
9024
9314
  });
@@ -9029,6 +9319,70 @@ var Account = class extends AbstractAccount {
9029
9319
  const submitAll = this.prepareSubmitAll({ txs, mode });
9030
9320
  return { txs, totalFeeCost, submitAll };
9031
9321
  }
9322
+ async assembleNonBaseAssetConsolidationTxs(params) {
9323
+ const { assetId, coins, mode = "parallel", outputNum = 1 } = params;
9324
+ this.validateConsolidationTxsCoins(coins, assetId);
9325
+ const chainInfo = await this.provider.getChain();
9326
+ const maxInputsNumber = chainInfo.consensusParameters.txParameters.maxInputs.toNumber();
9327
+ const baseAssetId = chainInfo.consensusParameters.baseAssetId;
9328
+ const { coins: baseAssetCoins } = await this.provider.getCoins(this.address, baseAssetId);
9329
+ let totalFeeCost = bn22(0);
9330
+ const txs = [];
9331
+ const gasPrice = await this.provider.estimateGasPrice(10);
9332
+ const consolidateMoreThanOneCoin = outputNum > 1;
9333
+ const assetCoinBatches = splitCoinsIntoBatches(coins, maxInputsNumber);
9334
+ assetCoinBatches.filter((batch) => batch.length > 1).forEach((coinBatch) => {
9335
+ const request2 = new ScriptTransactionRequest({
9336
+ script: "0x"
9337
+ });
9338
+ request2.addResources(coinBatch);
9339
+ if (consolidateMoreThanOneCoin) {
9340
+ Array.from({ length: outputNum - 1 }).forEach(() => {
9341
+ request2.addCoinOutput(this.address, 0, assetId);
9342
+ });
9343
+ }
9344
+ const minGas = request2.calculateMinGas(chainInfo);
9345
+ const fee = calculateGasFee({
9346
+ gasPrice,
9347
+ gas: minGas,
9348
+ priceFactor: chainInfo.consensusParameters.feeParameters.gasPriceFactor,
9349
+ tip: request2.tip
9350
+ });
9351
+ request2.maxFee = fee;
9352
+ if (consolidateMoreThanOneCoin) {
9353
+ const total = request2.inputs.filter(isRequestInputCoin).reduce((acc, input) => acc.add(input.amount), bn22(0));
9354
+ const amountPerNewUtxo = total.div(outputNum + 1);
9355
+ request2.outputs.forEach((output) => {
9356
+ if (output.type === OutputType10.Coin) {
9357
+ output.amount = amountPerNewUtxo;
9358
+ }
9359
+ });
9360
+ }
9361
+ totalFeeCost = totalFeeCost.add(fee);
9362
+ const baseAssetResources = [];
9363
+ let fundingFeeTotal = bn22(0);
9364
+ while (fundingFeeTotal.lt(fee)) {
9365
+ const baseAssetCoin = baseAssetCoins.pop();
9366
+ if (!baseAssetCoin) {
9367
+ break;
9368
+ }
9369
+ baseAssetResources.push(baseAssetCoin);
9370
+ fundingFeeTotal = fundingFeeTotal.add(baseAssetCoin.amount);
9371
+ }
9372
+ const { inputs } = request2;
9373
+ request2.inputs = inputs.slice(0, maxInputsNumber - baseAssetResources.length);
9374
+ const removedCoins = coinBatch.slice(maxInputsNumber - baseAssetResources.length);
9375
+ request2.addResources(baseAssetResources);
9376
+ const lastCoinBatch = assetCoinBatches[assetCoinBatches.length - 1];
9377
+ lastCoinBatch.push(...removedCoins);
9378
+ if (lastCoinBatch.length > maxInputsNumber) {
9379
+ assetCoinBatches.push(lastCoinBatch.slice(maxInputsNumber));
9380
+ }
9381
+ txs.push(request2);
9382
+ });
9383
+ const submitAll = this.prepareSubmitAll({ txs, mode });
9384
+ return { txs, totalFeeCost, submitAll };
9385
+ }
9032
9386
  /**
9033
9387
  * Prepares a function to submit all transactions either sequentially or in parallel.
9034
9388
  *
@@ -9087,7 +9441,7 @@ var Account = class extends AbstractAccount {
9087
9441
  const baseAssetId = await this.provider.getBaseAssetId();
9088
9442
  const coinOutputsQuantities = txRequestClone.getCoinOutputsQuantities();
9089
9443
  const requiredQuantities = mergeQuantities(coinOutputsQuantities, quantities);
9090
- const transactionFeeForDryRun = [{ assetId: baseAssetId, amount: bn21("100000000000000000") }];
9444
+ const transactionFeeForDryRun = [{ assetId: baseAssetId, amount: bn22("100000000000000000") }];
9091
9445
  const findAssetInput = /* @__PURE__ */ __name((assetId) => txRequestClone.inputs.find((input) => {
9092
9446
  if (input.type === InputType8.Coin) {
9093
9447
  return input.assetId === assetId;
@@ -9135,7 +9489,7 @@ var Account = class extends AbstractAccount {
9135
9489
  */
9136
9490
  async signMessage(message) {
9137
9491
  if (!this._connector) {
9138
- throw new FuelError21(ErrorCode19.MISSING_CONNECTOR, "A connector is required to sign messages.");
9492
+ throw new FuelError22(ErrorCode20.MISSING_CONNECTOR, "A connector is required to sign messages.");
9139
9493
  }
9140
9494
  return this._connector.signMessage(this.address.toString(), message);
9141
9495
  }
@@ -9147,8 +9501,8 @@ var Account = class extends AbstractAccount {
9147
9501
  */
9148
9502
  async signTransaction(transactionRequestLike, connectorOptions = {}) {
9149
9503
  if (!this._connector) {
9150
- throw new FuelError21(
9151
- ErrorCode19.MISSING_CONNECTOR,
9504
+ throw new FuelError22(
9505
+ ErrorCode20.MISSING_CONNECTOR,
9152
9506
  "A connector is required to sign transactions."
9153
9507
  );
9154
9508
  }
@@ -9215,8 +9569,8 @@ var Account = class extends AbstractAccount {
9215
9569
  return coins.map((coin) => ({
9216
9570
  id: hexlify18(randomBytes2(UTXO_ID_LEN3)),
9217
9571
  owner: this.address,
9218
- blockCreated: bn21(1),
9219
- txCreatedIdx: bn21(1),
9572
+ blockCreated: bn22(1),
9573
+ txCreatedIdx: bn22(1),
9220
9574
  ...coin
9221
9575
  }));
9222
9576
  }
@@ -9243,73 +9597,50 @@ var Account = class extends AbstractAccount {
9243
9597
  } : void 0;
9244
9598
  }
9245
9599
  /** @hidden * */
9246
- async assembleTx(transactionRequest, quantities = []) {
9247
- const outputQuantities = transactionRequest.outputs.filter((o) => o.type === OutputType9.Coin).map(({ amount, assetId }) => ({ assetId: String(assetId), amount: bn21(amount) }));
9248
- transactionRequest.gasLimit = bn21(0);
9249
- transactionRequest.maxFee = bn21(0);
9250
- const { assembledRequest, gasPrice } = await this.provider.assembleTx({
9251
- request: transactionRequest,
9252
- accountCoinQuantities: mergeQuantities(outputQuantities, quantities),
9253
- feePayerAccount: this
9254
- });
9255
- return { transactionRequest: assembledRequest, gasPrice };
9600
+ async assembleTx(opts) {
9601
+ const { transactionRequest, quantities = [], skipAutoConsolidation } = opts;
9602
+ const outputQuantities = transactionRequest.outputs.filter((o) => o.type === OutputType10.Coin).map(({ amount, assetId }) => ({ assetId: String(assetId), amount: bn22(amount) }));
9603
+ transactionRequest.gasLimit = bn22(0);
9604
+ transactionRequest.maxFee = bn22(0);
9605
+ const assembleTx = /* @__PURE__ */ __name(async () => {
9606
+ const { assembledRequest, gasPrice } = await this.provider.assembleTx({
9607
+ request: transactionRequest,
9608
+ accountCoinQuantities: mergeQuantities(outputQuantities, quantities),
9609
+ feePayerAccount: this
9610
+ });
9611
+ return { transactionRequest: assembledRequest, gasPrice };
9612
+ }, "assembleTx");
9613
+ try {
9614
+ return await assembleTx();
9615
+ } catch (error) {
9616
+ const shouldRetry = await consolidateCoinsIfRequired({
9617
+ error,
9618
+ account: this,
9619
+ skipAutoConsolidation
9620
+ });
9621
+ if (!shouldRetry) {
9622
+ throw error;
9623
+ }
9624
+ return await assembleTx();
9625
+ }
9256
9626
  }
9257
9627
  /** @hidden * */
9258
9628
  validateTransferAmount(amount) {
9259
- if (bn21(amount).lte(0)) {
9260
- throw new FuelError21(
9261
- ErrorCode19.INVALID_TRANSFER_AMOUNT,
9629
+ if (bn22(amount).lte(0)) {
9630
+ throw new FuelError22(
9631
+ ErrorCode20.INVALID_TRANSFER_AMOUNT,
9262
9632
  "Transfer amount must be a positive number."
9263
9633
  );
9264
9634
  }
9265
9635
  }
9266
9636
  /** @hidden * */
9267
- async estimateAndFundTransaction(transactionRequest, txParams, costParams) {
9268
- let request2 = transactionRequest;
9269
- const txCost = await this.getTransactionCost(request2, costParams);
9270
- request2 = this.validateGasLimitAndMaxFee({
9271
- transactionRequest: request2,
9272
- gasUsed: txCost.gasUsed,
9273
- maxFee: txCost.maxFee,
9274
- txParams
9275
- });
9276
- request2 = await this.fund(request2, txCost);
9277
- return request2;
9278
- }
9279
- /** @hidden * */
9280
- validateGasLimitAndMaxFee({
9281
- gasUsed,
9282
- maxFee,
9283
- transactionRequest,
9284
- txParams: { gasLimit: setGasLimit, maxFee: setMaxFee }
9285
- }) {
9286
- const request2 = transactionRequestify(transactionRequest);
9287
- if (!isDefined4(setGasLimit)) {
9288
- request2.gasLimit = gasUsed;
9289
- } else if (gasUsed.gt(setGasLimit)) {
9290
- throw new FuelError21(
9291
- ErrorCode19.GAS_LIMIT_TOO_LOW,
9292
- `Gas limit '${setGasLimit}' is lower than the required: '${gasUsed}'.`
9293
- );
9294
- }
9295
- if (!isDefined4(setMaxFee)) {
9296
- request2.maxFee = maxFee;
9297
- } else if (maxFee.gt(setMaxFee)) {
9298
- throw new FuelError21(
9299
- ErrorCode19.MAX_FEE_TOO_LOW,
9300
- `Max fee '${setMaxFee}' is lower than the required: '${maxFee}'.`
9301
- );
9302
- }
9303
- return request2;
9304
- }
9305
- /** @hidden * */
9306
9637
  validateConsolidationTxsCoins(coins, assetId) {
9307
9638
  if (coins.length <= 1) {
9308
- throw new FuelError21(ErrorCode19.NO_COINS_TO_CONSOLIDATE, "No coins to consolidate.");
9639
+ throw new FuelError22(ErrorCode20.NO_COINS_TO_CONSOLIDATE, "No coins to consolidate.");
9309
9640
  }
9310
9641
  if (!coins.every((c) => c.assetId === assetId)) {
9311
- throw new FuelError21(
9312
- ErrorCode19.COINS_ASSET_ID_MISMATCH,
9642
+ throw new FuelError22(
9643
+ ErrorCode20.COINS_ASSET_ID_MISMATCH,
9313
9644
  "All coins to consolidate must be from the same asset id."
9314
9645
  );
9315
9646
  }
@@ -9338,7 +9669,7 @@ import { hashMessage } from "@fuel-ts/hasher";
9338
9669
  import { hexlify as hexlify21 } from "@fuel-ts/utils";
9339
9670
 
9340
9671
  // src/signer/signer.ts
9341
- import { Address as Address5 } from "@fuel-ts/address";
9672
+ import { Address as Address6 } from "@fuel-ts/address";
9342
9673
  import { randomBytes as randomBytes3 } from "@fuel-ts/crypto";
9343
9674
  import { hash as hash2 } from "@fuel-ts/hasher";
9344
9675
  import { toBytes as toBytes2 } from "@fuel-ts/math";
@@ -9368,7 +9699,7 @@ var Signer = class _Signer {
9368
9699
  this.privateKey = hexlify19(privateKeyBytes);
9369
9700
  this.publicKey = hexlify19(secp256k1.getPublicKey(privateKeyBytes, false).slice(1));
9370
9701
  this.compressedPublicKey = hexlify19(secp256k1.getPublicKey(privateKeyBytes, true));
9371
- this.address = new Address5(this.publicKey);
9702
+ this.address = new Address6(this.publicKey);
9372
9703
  }
9373
9704
  /**
9374
9705
  * Sign data using the Signer instance
@@ -9426,7 +9757,7 @@ var Signer = class _Signer {
9426
9757
  * @returns Address from signature
9427
9758
  */
9428
9759
  static recoverAddress(data, signature) {
9429
- return new Address5(_Signer.recoverPublicKey(data, signature));
9760
+ return new Address6(_Signer.recoverPublicKey(data, signature));
9430
9761
  }
9431
9762
  /**
9432
9763
  * Generate a random privateKey
@@ -9450,7 +9781,7 @@ var Signer = class _Signer {
9450
9781
  };
9451
9782
 
9452
9783
  // src/wallet/keystore-wallet.ts
9453
- import { Address as Address6 } from "@fuel-ts/address";
9784
+ import { Address as Address7 } from "@fuel-ts/address";
9454
9785
  import {
9455
9786
  bufferFromString,
9456
9787
  keccak256,
@@ -9461,7 +9792,7 @@ import {
9461
9792
  encryptJsonWalletData,
9462
9793
  randomUUID
9463
9794
  } from "@fuel-ts/crypto";
9464
- import { ErrorCode as ErrorCode20, FuelError as FuelError22 } from "@fuel-ts/errors";
9795
+ import { ErrorCode as ErrorCode21, FuelError as FuelError23 } from "@fuel-ts/errors";
9465
9796
  import { hexlify as hexlify20 } from "@fuel-ts/utils";
9466
9797
  var DEFAULT_KDF_PARAMS_LOG_N = 13;
9467
9798
  var DEFAULT_KDF_PARAMS_R = 8;
@@ -9476,7 +9807,7 @@ var removeHexPrefix = /* @__PURE__ */ __name((hexString) => {
9476
9807
  }, "removeHexPrefix");
9477
9808
  async function encryptKeystoreWallet(privateKey, address, password) {
9478
9809
  const privateKeyBuffer = bufferFromString(removeHexPrefix(privateKey), "hex");
9479
- const ownerAddress = new Address6(address);
9810
+ const ownerAddress = new Address7(address);
9480
9811
  const salt = randomBytes4(DEFAULT_KEY_SIZE);
9481
9812
  const key = scrypt({
9482
9813
  password: bufferFromString(password),
@@ -9539,8 +9870,8 @@ async function decryptKeystoreWallet(jsonWallet, password) {
9539
9870
  const macHashUint8Array = keccak256(data);
9540
9871
  const macHash = stringFromBuffer(macHashUint8Array, "hex");
9541
9872
  if (mac !== macHash) {
9542
- throw new FuelError22(
9543
- ErrorCode20.INVALID_PASSWORD,
9873
+ throw new FuelError23(
9874
+ ErrorCode21.INVALID_PASSWORD,
9544
9875
  "Failed to decrypt the keystore wallet, the provided password is incorrect."
9545
9876
  );
9546
9877
  }
@@ -9679,14 +10010,14 @@ var BaseWalletUnlocked = class extends Account {
9679
10010
 
9680
10011
  // src/hdwallet/hdwallet.ts
9681
10012
  import { computeHmac as computeHmac2, ripemd160 } from "@fuel-ts/crypto";
9682
- import { ErrorCode as ErrorCode23, FuelError as FuelError25 } from "@fuel-ts/errors";
10013
+ import { ErrorCode as ErrorCode24, FuelError as FuelError26 } from "@fuel-ts/errors";
9683
10014
  import { sha256 as sha2564 } from "@fuel-ts/hasher";
9684
- import { bn as bn22, toBytes as toBytes3, toHex } from "@fuel-ts/math";
10015
+ import { bn as bn23, toBytes as toBytes3, toHex } from "@fuel-ts/math";
9685
10016
  import { arrayify as arrayify21, hexlify as hexlify23, concat as concat7, dataSlice as dataSlice2, encodeBase58 as encodeBase582, decodeBase58 } from "@fuel-ts/utils";
9686
10017
 
9687
10018
  // src/mnemonic/mnemonic.ts
9688
10019
  import { randomBytes as randomBytes5, pbkdf2, computeHmac } from "@fuel-ts/crypto";
9689
- import { ErrorCode as ErrorCode22, FuelError as FuelError24 } from "@fuel-ts/errors";
10020
+ import { ErrorCode as ErrorCode23, FuelError as FuelError25 } from "@fuel-ts/errors";
9690
10021
  import { sha256 as sha2563 } from "@fuel-ts/hasher";
9691
10022
  import { arrayify as arrayify20, hexlify as hexlify22, concat as concat6, dataSlice, encodeBase58, toUtf8Bytes } from "@fuel-ts/utils";
9692
10023
 
@@ -11749,7 +12080,7 @@ var Language = /* @__PURE__ */ ((Language2) => {
11749
12080
  })(Language || {});
11750
12081
 
11751
12082
  // src/mnemonic/utils.ts
11752
- import { ErrorCode as ErrorCode21, FuelError as FuelError23 } from "@fuel-ts/errors";
12083
+ import { ErrorCode as ErrorCode22, FuelError as FuelError24 } from "@fuel-ts/errors";
11753
12084
  import { sha256 as sha2562 } from "@fuel-ts/hasher";
11754
12085
  import { arrayify as arrayify19 } from "@fuel-ts/utils";
11755
12086
  function getLowerMask(bits) {
@@ -11803,8 +12134,8 @@ function mnemonicWordsToEntropy(words, wordlist) {
11803
12134
  for (let i = 0; i < words.length; i += 1) {
11804
12135
  const index = wordlist.indexOf(words[i].normalize("NFKD"));
11805
12136
  if (index === -1) {
11806
- throw new FuelError23(
11807
- ErrorCode21.INVALID_MNEMONIC,
12137
+ throw new FuelError24(
12138
+ ErrorCode22.INVALID_MNEMONIC,
11808
12139
  `Invalid mnemonic: the word '${words[i]}' is not found in the provided wordlist.`
11809
12140
  );
11810
12141
  }
@@ -11820,8 +12151,8 @@ function mnemonicWordsToEntropy(words, wordlist) {
11820
12151
  const checksumMask = getUpperMask(checksumBits);
11821
12152
  const checksum = arrayify19(sha2562(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
11822
12153
  if (checksum !== (entropy[entropy.length - 1] & checksumMask)) {
11823
- throw new FuelError23(
11824
- ErrorCode21.INVALID_CHECKSUM,
12154
+ throw new FuelError24(
12155
+ ErrorCode22.INVALID_CHECKSUM,
11825
12156
  "Checksum validation failed for the provided mnemonic."
11826
12157
  );
11827
12158
  }
@@ -11836,8 +12167,8 @@ var TestnetPRV = "0x04358394";
11836
12167
  var MNEMONIC_SIZES = [12, 15, 18, 21, 24];
11837
12168
  function assertWordList(wordlist) {
11838
12169
  if (wordlist.length !== 2048) {
11839
- throw new FuelError24(
11840
- ErrorCode22.INVALID_WORD_LIST,
12170
+ throw new FuelError25(
12171
+ ErrorCode23.INVALID_WORD_LIST,
11841
12172
  `Expected word list length of 2048, but got ${wordlist.length}.`
11842
12173
  );
11843
12174
  }
@@ -11845,8 +12176,8 @@ function assertWordList(wordlist) {
11845
12176
  __name(assertWordList, "assertWordList");
11846
12177
  function assertEntropy(entropy) {
11847
12178
  if (entropy.length % 4 !== 0 || entropy.length < 16 || entropy.length > 32) {
11848
- throw new FuelError24(
11849
- ErrorCode22.INVALID_ENTROPY,
12179
+ throw new FuelError25(
12180
+ ErrorCode23.INVALID_ENTROPY,
11850
12181
  `Entropy should be between 16 and 32 bytes and a multiple of 4, but got ${entropy.length} bytes.`
11851
12182
  );
11852
12183
  }
@@ -11857,7 +12188,7 @@ function assertMnemonic(words) {
11857
12188
  const errorMsg = `Invalid mnemonic size. Expected one of [${MNEMONIC_SIZES.join(
11858
12189
  ", "
11859
12190
  )}] words, but got ${words.length}.`;
11860
- throw new FuelError24(ErrorCode22.INVALID_MNEMONIC, errorMsg);
12191
+ throw new FuelError25(ErrorCode23.INVALID_MNEMONIC, errorMsg);
11861
12192
  }
11862
12193
  }
11863
12194
  __name(assertMnemonic, "assertMnemonic");
@@ -11979,8 +12310,8 @@ var Mnemonic = class _Mnemonic {
11979
12310
  static masterKeysFromSeed(seed) {
11980
12311
  const seedArray = arrayify20(seed);
11981
12312
  if (seedArray.length < 16 || seedArray.length > 64) {
11982
- throw new FuelError24(
11983
- ErrorCode22.INVALID_SEED,
12313
+ throw new FuelError25(
12314
+ ErrorCode23.INVALID_SEED,
11984
12315
  `Seed length should be between 16 and 64 bytes, but received ${seedArray.length} bytes.`
11985
12316
  );
11986
12317
  }
@@ -12061,7 +12392,7 @@ __name(isValidExtendedKey, "isValidExtendedKey");
12061
12392
  function parsePath(path, depth = 0) {
12062
12393
  const components = path.split("/");
12063
12394
  if (components.length === 0 || components[0] === "m" && depth !== 0) {
12064
- throw new FuelError25(ErrorCode23.HD_WALLET_ERROR, `invalid path - ${path}`);
12395
+ throw new FuelError26(ErrorCode24.HD_WALLET_ERROR, `invalid path - ${path}`);
12065
12396
  }
12066
12397
  if (components[0] === "m") {
12067
12398
  components.shift();
@@ -12094,8 +12425,8 @@ var HDWallet = class _HDWallet {
12094
12425
  this.privateKey = hexlify23(config.privateKey);
12095
12426
  } else {
12096
12427
  if (!config.publicKey) {
12097
- throw new FuelError25(
12098
- ErrorCode23.HD_WALLET_ERROR,
12428
+ throw new FuelError26(
12429
+ ErrorCode24.HD_WALLET_ERROR,
12099
12430
  "Both public and private Key cannot be missing. At least one should be provided."
12100
12431
  );
12101
12432
  }
@@ -12124,8 +12455,8 @@ var HDWallet = class _HDWallet {
12124
12455
  const data = new Uint8Array(37);
12125
12456
  if (index & HARDENED_INDEX) {
12126
12457
  if (!privateKey) {
12127
- throw new FuelError25(
12128
- ErrorCode23.HD_WALLET_ERROR,
12458
+ throw new FuelError26(
12459
+ ErrorCode24.HD_WALLET_ERROR,
12129
12460
  "Cannot derive a hardened index without a private Key."
12130
12461
  );
12131
12462
  }
@@ -12139,7 +12470,7 @@ var HDWallet = class _HDWallet {
12139
12470
  const IR = bytes.slice(32);
12140
12471
  if (privateKey) {
12141
12472
  const N = "0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141";
12142
- const ki = bn22(IL).add(privateKey).mod(N).toBytes(32);
12473
+ const ki = bn23(IL).add(privateKey).mod(N).toBytes(32);
12143
12474
  return new _HDWallet({
12144
12475
  privateKey: ki,
12145
12476
  chainCode: IR,
@@ -12177,8 +12508,8 @@ var HDWallet = class _HDWallet {
12177
12508
  */
12178
12509
  toExtendedKey(isPublic = false, testnet = false) {
12179
12510
  if (this.depth >= 256) {
12180
- throw new FuelError25(
12181
- ErrorCode23.HD_WALLET_ERROR,
12511
+ throw new FuelError26(
12512
+ ErrorCode24.HD_WALLET_ERROR,
12182
12513
  `Exceeded max depth of 255. Current depth: ${this.depth}.`
12183
12514
  );
12184
12515
  }
@@ -12209,10 +12540,10 @@ var HDWallet = class _HDWallet {
12209
12540
  const bytes = arrayify21(decoded);
12210
12541
  const validChecksum = base58check(bytes.slice(0, 78)) === extendedKey;
12211
12542
  if (bytes.length !== 82 || !isValidExtendedKey(bytes)) {
12212
- throw new FuelError25(ErrorCode23.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
12543
+ throw new FuelError26(ErrorCode24.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
12213
12544
  }
12214
12545
  if (!validChecksum) {
12215
- throw new FuelError25(ErrorCode23.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
12546
+ throw new FuelError26(ErrorCode24.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
12216
12547
  }
12217
12548
  const depth = bytes[4];
12218
12549
  const parentFingerprint = hexlify23(bytes.slice(5, 9));
@@ -12220,14 +12551,14 @@ var HDWallet = class _HDWallet {
12220
12551
  const chainCode = hexlify23(bytes.slice(13, 45));
12221
12552
  const key = bytes.slice(45, 78);
12222
12553
  if (depth === 0 && parentFingerprint !== "0x00000000" || depth === 0 && index !== 0) {
12223
- throw new FuelError25(
12224
- ErrorCode23.HD_WALLET_ERROR,
12554
+ throw new FuelError26(
12555
+ ErrorCode24.HD_WALLET_ERROR,
12225
12556
  "Inconsistency detected: Depth is zero but fingerprint/index is non-zero."
12226
12557
  );
12227
12558
  }
12228
12559
  if (isPublicExtendedKey(bytes)) {
12229
12560
  if (key[0] !== 3) {
12230
- throw new FuelError25(ErrorCode23.HD_WALLET_ERROR, "Invalid public extended key.");
12561
+ throw new FuelError26(ErrorCode24.HD_WALLET_ERROR, "Invalid public extended key.");
12231
12562
  }
12232
12563
  return new _HDWallet({
12233
12564
  publicKey: key,
@@ -12238,7 +12569,7 @@ var HDWallet = class _HDWallet {
12238
12569
  });
12239
12570
  }
12240
12571
  if (key[0] !== 0) {
12241
- throw new FuelError25(ErrorCode23.HD_WALLET_ERROR, "Invalid private extended key.");
12572
+ throw new FuelError26(ErrorCode24.HD_WALLET_ERROR, "Invalid private extended key.");
12242
12573
  }
12243
12574
  return new _HDWallet({
12244
12575
  privateKey: key.slice(1),
@@ -12413,9 +12744,9 @@ var Wallet = class {
12413
12744
  };
12414
12745
 
12415
12746
  // src/wallet-manager/wallet-manager.ts
12416
- import { Address as Address9 } from "@fuel-ts/address";
12747
+ import { Address as Address10 } from "@fuel-ts/address";
12417
12748
  import { encrypt, decrypt } from "@fuel-ts/crypto";
12418
- import { ErrorCode as ErrorCode26, FuelError as FuelError28 } from "@fuel-ts/errors";
12749
+ import { ErrorCode as ErrorCode27, FuelError as FuelError29 } from "@fuel-ts/errors";
12419
12750
  import { EventEmitter } from "events";
12420
12751
 
12421
12752
  // src/wallet-manager/storages/memory-storage.ts
@@ -12440,8 +12771,8 @@ var MemoryStorage = class {
12440
12771
  };
12441
12772
 
12442
12773
  // src/wallet-manager/vaults/mnemonic-vault.ts
12443
- import { Address as Address7 } from "@fuel-ts/address";
12444
- import { ErrorCode as ErrorCode24, FuelError as FuelError26 } from "@fuel-ts/errors";
12774
+ import { Address as Address8 } from "@fuel-ts/address";
12775
+ import { ErrorCode as ErrorCode25, FuelError as FuelError27 } from "@fuel-ts/errors";
12445
12776
  var MnemonicVault = class {
12446
12777
  static {
12447
12778
  __name(this, "MnemonicVault");
@@ -12492,7 +12823,7 @@ var MnemonicVault = class {
12492
12823
  }
12493
12824
  exportAccount(address) {
12494
12825
  let numberOfAccounts = 0;
12495
- const ownerAddress = new Address7(address);
12826
+ const ownerAddress = new Address8(address);
12496
12827
  do {
12497
12828
  const wallet = Wallet.fromMnemonic(this.#secret, this.getDerivePath(numberOfAccounts));
12498
12829
  if (wallet.address.equals(ownerAddress)) {
@@ -12500,8 +12831,8 @@ var MnemonicVault = class {
12500
12831
  }
12501
12832
  numberOfAccounts += 1;
12502
12833
  } while (numberOfAccounts < this.numberOfAccounts);
12503
- throw new FuelError26(
12504
- ErrorCode24.WALLET_MANAGER_ERROR,
12834
+ throw new FuelError27(
12835
+ ErrorCode25.WALLET_MANAGER_ERROR,
12505
12836
  `Account with address '${address}' not found in derived wallets.`
12506
12837
  );
12507
12838
  }
@@ -12512,8 +12843,8 @@ var MnemonicVault = class {
12512
12843
  };
12513
12844
 
12514
12845
  // src/wallet-manager/vaults/privatekey-vault.ts
12515
- import { Address as Address8 } from "@fuel-ts/address";
12516
- import { ErrorCode as ErrorCode25, FuelError as FuelError27 } from "@fuel-ts/errors";
12846
+ import { Address as Address9 } from "@fuel-ts/address";
12847
+ import { ErrorCode as ErrorCode26, FuelError as FuelError28 } from "@fuel-ts/errors";
12517
12848
  var PrivateKeyVault = class {
12518
12849
  static {
12519
12850
  __name(this, "PrivateKeyVault");
@@ -12552,13 +12883,13 @@ var PrivateKeyVault = class {
12552
12883
  return this.getPublicAccount(wallet.privateKey);
12553
12884
  }
12554
12885
  exportAccount(address) {
12555
- const ownerAddress = new Address8(address);
12886
+ const ownerAddress = new Address9(address);
12556
12887
  const privateKey = this.#privateKeys.find(
12557
12888
  (pk) => Wallet.fromPrivateKey(pk).address.equals(ownerAddress)
12558
12889
  );
12559
12890
  if (!privateKey) {
12560
- throw new FuelError27(
12561
- ErrorCode25.WALLET_MANAGER_ERROR,
12891
+ throw new FuelError28(
12892
+ ErrorCode26.WALLET_MANAGER_ERROR,
12562
12893
  `No private key found for address '${address}'.`
12563
12894
  );
12564
12895
  }
@@ -12580,7 +12911,7 @@ var ERROR_MESSAGES = {
12580
12911
  };
12581
12912
  function assert(condition, message) {
12582
12913
  if (!condition) {
12583
- throw new FuelError28(ErrorCode26.WALLET_MANAGER_ERROR, message);
12914
+ throw new FuelError29(ErrorCode27.WALLET_MANAGER_ERROR, message);
12584
12915
  }
12585
12916
  }
12586
12917
  __name(assert, "assert");
@@ -12649,7 +12980,7 @@ var WalletManager = class _WalletManager extends EventEmitter {
12649
12980
  * Create a Wallet instance for the specific account
12650
12981
  */
12651
12982
  getWallet(address) {
12652
- const ownerAddress = new Address9(address);
12983
+ const ownerAddress = new Address10(address);
12653
12984
  const vaultState = this.#vaults.find(
12654
12985
  (vs) => vs.vault.getAccounts().find((a) => a.address.equals(ownerAddress))
12655
12986
  );
@@ -12660,7 +12991,7 @@ var WalletManager = class _WalletManager extends EventEmitter {
12660
12991
  * Export specific account privateKey
12661
12992
  */
12662
12993
  exportPrivateKey(address) {
12663
- const ownerAddress = new Address9(address);
12994
+ const ownerAddress = new Address10(address);
12664
12995
  assert(!this.#isLocked, ERROR_MESSAGES.wallet_not_unlocked);
12665
12996
  const vaultState = this.#vaults.find(
12666
12997
  (vs) => vs.vault.getAccounts().find((a) => a.address.equals(ownerAddress))
@@ -12801,29 +13132,29 @@ var WalletManager = class _WalletManager extends EventEmitter {
12801
13132
  };
12802
13133
 
12803
13134
  // src/wallet-manager/types.ts
12804
- import { ErrorCode as ErrorCode27, FuelError as FuelError29 } from "@fuel-ts/errors";
13135
+ import { ErrorCode as ErrorCode28, FuelError as FuelError30 } from "@fuel-ts/errors";
12805
13136
  var Vault = class {
12806
13137
  static {
12807
13138
  __name(this, "Vault");
12808
13139
  }
12809
13140
  static type;
12810
13141
  constructor(_options) {
12811
- throw new FuelError29(ErrorCode27.NOT_IMPLEMENTED, "Not implemented.");
13142
+ throw new FuelError30(ErrorCode28.NOT_IMPLEMENTED, "Not implemented.");
12812
13143
  }
12813
13144
  serialize() {
12814
- throw new FuelError29(ErrorCode27.NOT_IMPLEMENTED, "Not implemented.");
13145
+ throw new FuelError30(ErrorCode28.NOT_IMPLEMENTED, "Not implemented.");
12815
13146
  }
12816
13147
  getAccounts() {
12817
- throw new FuelError29(ErrorCode27.NOT_IMPLEMENTED, "Not implemented.");
13148
+ throw new FuelError30(ErrorCode28.NOT_IMPLEMENTED, "Not implemented.");
12818
13149
  }
12819
13150
  addAccount() {
12820
- throw new FuelError29(ErrorCode27.NOT_IMPLEMENTED, "Not implemented.");
13151
+ throw new FuelError30(ErrorCode28.NOT_IMPLEMENTED, "Not implemented.");
12821
13152
  }
12822
13153
  exportAccount(_address) {
12823
- throw new FuelError29(ErrorCode27.NOT_IMPLEMENTED, "Not implemented.");
13154
+ throw new FuelError30(ErrorCode28.NOT_IMPLEMENTED, "Not implemented.");
12824
13155
  }
12825
13156
  getWallet(_address) {
12826
- throw new FuelError29(ErrorCode27.NOT_IMPLEMENTED, "Not implemented.");
13157
+ throw new FuelError30(ErrorCode28.NOT_IMPLEMENTED, "Not implemented.");
12827
13158
  }
12828
13159
  };
12829
13160
  var StorageAbstract = class {
@@ -12834,12 +13165,12 @@ var StorageAbstract = class {
12834
13165
 
12835
13166
  // src/predicate/predicate.ts
12836
13167
  import { Interface as Interface5 } from "@fuel-ts/abi-coder";
12837
- import { Address as Address10 } from "@fuel-ts/address";
12838
- import { ErrorCode as ErrorCode29, FuelError as FuelError31 } from "@fuel-ts/errors";
13168
+ import { Address as Address11 } from "@fuel-ts/address";
13169
+ import { ErrorCode as ErrorCode30, FuelError as FuelError32 } from "@fuel-ts/errors";
12839
13170
  import { arrayify as arrayify24, hexlify as hexlify25 } from "@fuel-ts/utils";
12840
13171
 
12841
13172
  // src/utils/deployScriptOrPredicate.ts
12842
- import { FuelError as FuelError30, ErrorCode as ErrorCode28 } from "@fuel-ts/errors";
13173
+ import { FuelError as FuelError31, ErrorCode as ErrorCode29 } from "@fuel-ts/errors";
12843
13174
  import { arrayify as arrayify22 } from "@fuel-ts/utils";
12844
13175
 
12845
13176
  // src/utils/predicate-script-loader-instructions.ts
@@ -13046,7 +13377,7 @@ async function deployScriptOrPredicate({
13046
13377
  throw new Error();
13047
13378
  }
13048
13379
  } catch (err) {
13049
- throw new FuelError30(ErrorCode28.TRANSACTION_FAILED, "Failed to deploy predicate chunk");
13380
+ throw new FuelError31(ErrorCode29.TRANSACTION_FAILED, "Failed to deploy predicate chunk");
13050
13381
  }
13051
13382
  return loaderInstance;
13052
13383
  }, "waitForResult");
@@ -13101,7 +13432,7 @@ var Predicate = class _Predicate extends Account {
13101
13432
  abi,
13102
13433
  configurableConstants
13103
13434
  );
13104
- const address = new Address10(getPredicateRoot(predicateBytes));
13435
+ const address = new Address11(getPredicateRoot(predicateBytes));
13105
13436
  super(address, provider);
13106
13437
  this.initialBytecode = arrayify24(bytecode);
13107
13438
  this.bytes = predicateBytes;
@@ -13198,8 +13529,8 @@ var Predicate = class _Predicate extends Account {
13198
13529
  let predicateBytes = arrayify24(bytes);
13199
13530
  const abiInterface = new Interface5(jsonAbi);
13200
13531
  if (abiInterface.functions.main === void 0) {
13201
- throw new FuelError31(
13202
- ErrorCode29.ABI_MAIN_METHOD_MISSING,
13532
+ throw new FuelError32(
13533
+ ErrorCode30.ABI_MAIN_METHOD_MISSING,
13203
13534
  'Cannot use ABI without "main" function.'
13204
13535
  );
13205
13536
  }
@@ -13259,15 +13590,15 @@ var Predicate = class _Predicate extends Account {
13259
13590
  const mutatedBytes = bytes;
13260
13591
  try {
13261
13592
  if (Object.keys(abiInterface.configurables).length === 0) {
13262
- throw new FuelError31(
13263
- ErrorCode29.INVALID_CONFIGURABLE_CONSTANTS,
13593
+ throw new FuelError32(
13594
+ ErrorCode30.INVALID_CONFIGURABLE_CONSTANTS,
13264
13595
  "Predicate has no configurable constants to be set"
13265
13596
  );
13266
13597
  }
13267
13598
  Object.entries(configurableConstants).forEach(([key, value]) => {
13268
13599
  if (!abiInterface?.configurables[key]) {
13269
- throw new FuelError31(
13270
- ErrorCode29.CONFIGURABLE_NOT_FOUND,
13600
+ throw new FuelError32(
13601
+ ErrorCode30.CONFIGURABLE_NOT_FOUND,
13271
13602
  `No configurable constant named '${key}' found in the Predicate`
13272
13603
  );
13273
13604
  }
@@ -13276,8 +13607,8 @@ var Predicate = class _Predicate extends Account {
13276
13607
  mutatedBytes.set(encoded, offset);
13277
13608
  });
13278
13609
  } catch (err) {
13279
- throw new FuelError31(
13280
- ErrorCode29.INVALID_CONFIGURABLE_CONSTANTS,
13610
+ throw new FuelError32(
13611
+ ErrorCode30.INVALID_CONFIGURABLE_CONSTANTS,
13281
13612
  `Error setting configurable constants: ${err.message}.`
13282
13613
  );
13283
13614
  }
@@ -13330,10 +13661,10 @@ var Predicate = class _Predicate extends Account {
13330
13661
  };
13331
13662
 
13332
13663
  // src/connectors/fuel.ts
13333
- import { ErrorCode as ErrorCode30, FuelError as FuelError34 } from "@fuel-ts/errors";
13664
+ import { ErrorCode as ErrorCode31, FuelError as FuelError35 } from "@fuel-ts/errors";
13334
13665
 
13335
13666
  // src/connectors/fuel-connector.ts
13336
- import { FuelError as FuelError32 } from "@fuel-ts/errors";
13667
+ import { FuelError as FuelError33 } from "@fuel-ts/errors";
13337
13668
  import { EventEmitter as EventEmitter2 } from "events";
13338
13669
 
13339
13670
  // src/connectors/types/connector-types.ts
@@ -13358,6 +13689,7 @@ var FuelConnectorMethods = /* @__PURE__ */ ((FuelConnectorMethods2) => {
13358
13689
  FuelConnectorMethods2["addABI"] = "addABI";
13359
13690
  FuelConnectorMethods2["getABI"] = "getABI";
13360
13691
  FuelConnectorMethods2["hasABI"] = "hasABI";
13692
+ FuelConnectorMethods2["startConsolidation"] = "startConsolidation";
13361
13693
  return FuelConnectorMethods2;
13362
13694
  })(FuelConnectorMethods || {});
13363
13695
  var FuelConnectorEventTypes = /* @__PURE__ */ ((FuelConnectorEventTypes2) => {
@@ -13370,6 +13702,7 @@ var FuelConnectorEventTypes = /* @__PURE__ */ ((FuelConnectorEventTypes2) => {
13370
13702
  FuelConnectorEventTypes2["currentNetwork"] = "currentNetwork";
13371
13703
  FuelConnectorEventTypes2["assets"] = "assets";
13372
13704
  FuelConnectorEventTypes2["abis"] = "abis";
13705
+ FuelConnectorEventTypes2["consolidateCoins"] = "consolidateCoins";
13373
13706
  return FuelConnectorEventTypes2;
13374
13707
  })(FuelConnectorEventTypes || {});
13375
13708
  var FuelConnectorEventType = "FuelConnector";
@@ -13415,7 +13748,7 @@ var FuelConnector = class extends EventEmitter2 {
13415
13748
  * @returns Always true.
13416
13749
  */
13417
13750
  async ping() {
13418
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13751
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13419
13752
  }
13420
13753
  /**
13421
13754
  * Should return the current version of the connector
@@ -13424,7 +13757,7 @@ var FuelConnector = class extends EventEmitter2 {
13424
13757
  * @returns boolean - connection status.
13425
13758
  */
13426
13759
  async version() {
13427
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13760
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13428
13761
  }
13429
13762
  /**
13430
13763
  * Should return true if the connector is connected
@@ -13433,7 +13766,7 @@ var FuelConnector = class extends EventEmitter2 {
13433
13766
  * @returns The connection status.
13434
13767
  */
13435
13768
  async isConnected() {
13436
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13769
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13437
13770
  }
13438
13771
  /**
13439
13772
  * Should return all the accounts authorized for the
@@ -13442,7 +13775,7 @@ var FuelConnector = class extends EventEmitter2 {
13442
13775
  * @returns The accounts addresses strings
13443
13776
  */
13444
13777
  async accounts() {
13445
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13778
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13446
13779
  }
13447
13780
  /**
13448
13781
  * Should start the connection process and return
@@ -13454,7 +13787,7 @@ var FuelConnector = class extends EventEmitter2 {
13454
13787
  * @returns boolean - connection status.
13455
13788
  */
13456
13789
  async connect() {
13457
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13790
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13458
13791
  }
13459
13792
  /**
13460
13793
  * Should disconnect the current connection and
@@ -13464,7 +13797,7 @@ var FuelConnector = class extends EventEmitter2 {
13464
13797
  * @returns The connection status.
13465
13798
  */
13466
13799
  async disconnect() {
13467
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13800
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13468
13801
  }
13469
13802
  /**
13470
13803
  * Should start the sign message process and return
@@ -13476,7 +13809,7 @@ var FuelConnector = class extends EventEmitter2 {
13476
13809
  * @returns Message signature
13477
13810
  */
13478
13811
  async signMessage(_address, _message) {
13479
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13812
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13480
13813
  }
13481
13814
  /**
13482
13815
  * Should start the sign transaction process and return
@@ -13488,7 +13821,7 @@ var FuelConnector = class extends EventEmitter2 {
13488
13821
  * @returns Transaction signature
13489
13822
  */
13490
13823
  async signTransaction(_address, _transaction, _params) {
13491
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13824
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13492
13825
  }
13493
13826
  /**
13494
13827
  * Should start the send transaction process and return
@@ -13504,7 +13837,7 @@ var FuelConnector = class extends EventEmitter2 {
13504
13837
  * @returns The transaction id or transaction response
13505
13838
  */
13506
13839
  async sendTransaction(_address, _transaction, _params) {
13507
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13840
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13508
13841
  }
13509
13842
  /**
13510
13843
  * Should return the current account selected inside the connector, if the account
@@ -13515,7 +13848,7 @@ var FuelConnector = class extends EventEmitter2 {
13515
13848
  * @returns The current account selected otherwise null.
13516
13849
  */
13517
13850
  async currentAccount() {
13518
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13851
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13519
13852
  }
13520
13853
  /**
13521
13854
  * Should add the assets metadata to the connector and return true if the asset
@@ -13529,7 +13862,7 @@ var FuelConnector = class extends EventEmitter2 {
13529
13862
  * @returns True if the asset was added successfully
13530
13863
  */
13531
13864
  async addAssets(_assets) {
13532
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13865
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13533
13866
  }
13534
13867
  /**
13535
13868
  * Should add the asset metadata to the connector and return true if the asset
@@ -13543,7 +13876,7 @@ var FuelConnector = class extends EventEmitter2 {
13543
13876
  * @returns True if the asset was added successfully
13544
13877
  */
13545
13878
  async addAsset(_asset) {
13546
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13879
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13547
13880
  }
13548
13881
  /**
13549
13882
  * Should return all the assets added to the connector. If a connection is already established.
@@ -13551,7 +13884,7 @@ var FuelConnector = class extends EventEmitter2 {
13551
13884
  * @returns Array of assets metadata from the connector vinculated to the all accounts from a specific Wallet.
13552
13885
  */
13553
13886
  async assets() {
13554
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13887
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13555
13888
  }
13556
13889
  /**
13557
13890
  * Should start the add network process and return true if the network was added successfully.
@@ -13562,7 +13895,7 @@ var FuelConnector = class extends EventEmitter2 {
13562
13895
  * @returns Return true if the network was added successfully
13563
13896
  */
13564
13897
  async addNetwork(_networkUrl) {
13565
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13898
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13566
13899
  }
13567
13900
  /**
13568
13901
  * Should start the select network process and return true if the network has change successfully.
@@ -13573,7 +13906,7 @@ var FuelConnector = class extends EventEmitter2 {
13573
13906
  * @returns Return true if the network was added successfully
13574
13907
  */
13575
13908
  async selectNetwork(_network) {
13576
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13909
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13577
13910
  }
13578
13911
  /**
13579
13912
  * Should return all the networks available from the connector. If the connection is already established.
@@ -13581,7 +13914,7 @@ var FuelConnector = class extends EventEmitter2 {
13581
13914
  * @returns Return all the networks added to the connector.
13582
13915
  */
13583
13916
  async networks() {
13584
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13917
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13585
13918
  }
13586
13919
  /**
13587
13920
  * Should return the current network selected inside the connector. Even if the connection is not established.
@@ -13589,7 +13922,7 @@ var FuelConnector = class extends EventEmitter2 {
13589
13922
  * @returns Return the current network selected inside the connector.
13590
13923
  */
13591
13924
  async currentNetwork() {
13592
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13925
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13593
13926
  }
13594
13927
  /**
13595
13928
  * Should add the ABI to the connector and return true if the ABI was added successfully.
@@ -13599,7 +13932,7 @@ var FuelConnector = class extends EventEmitter2 {
13599
13932
  * @returns Return true if the ABI was added successfully.
13600
13933
  */
13601
13934
  async addABI(_contractId, _abi) {
13602
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13935
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13603
13936
  }
13604
13937
  /**
13605
13938
  * Should return the ABI from the connector vinculated to the all accounts from a specific Wallet.
@@ -13608,7 +13941,7 @@ var FuelConnector = class extends EventEmitter2 {
13608
13941
  * @returns The ABI if it exists, otherwise return null.
13609
13942
  */
13610
13943
  async getABI(_id) {
13611
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13944
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13612
13945
  }
13613
13946
  /**
13614
13947
  * Should return true if the abi exists in the connector vinculated to the all accounts from a specific Wallet.
@@ -13617,7 +13950,16 @@ var FuelConnector = class extends EventEmitter2 {
13617
13950
  * @returns Returns true if the abi exists or false if not.
13618
13951
  */
13619
13952
  async hasABI(_id) {
13620
- throw new FuelError32(FuelError32.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13953
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13954
+ }
13955
+ /**
13956
+ * Start the consolidation of coins process
13957
+ *
13958
+ * @param owner - The B256 address of the owner.
13959
+ * @param assetId - The asset ID that requires consolidation.
13960
+ */
13961
+ async startConsolidation(_opts) {
13962
+ throw new FuelError33(FuelError33.CODES.NOT_IMPLEMENTED, "Method not implemented.");
13621
13963
  }
13622
13964
  /**
13623
13965
  * Event listener for the connector.
@@ -13663,7 +14005,7 @@ function dispatchFuelConnectorEvent(connector) {
13663
14005
  __name(dispatchFuelConnectorEvent, "dispatchFuelConnectorEvent");
13664
14006
 
13665
14007
  // src/connectors/utils/promises.ts
13666
- import { FuelError as FuelError33 } from "@fuel-ts/errors";
14008
+ import { FuelError as FuelError34 } from "@fuel-ts/errors";
13667
14009
  function deferPromise() {
13668
14010
  const defer = {};
13669
14011
  defer.promise = new Promise((resolve, reject) => {
@@ -13676,7 +14018,7 @@ __name(deferPromise, "deferPromise");
13676
14018
  async function withTimeout(promise, timeout = 1050) {
13677
14019
  const timeoutPromise = new Promise((resolve, reject) => {
13678
14020
  setTimeout(() => {
13679
- reject(new FuelError33(FuelError33.CODES.TIMEOUT_EXCEEDED, "Promise timed out"));
14021
+ reject(new FuelError34(FuelError34.CODES.TIMEOUT_EXCEEDED, "Promise timed out"));
13680
14022
  }, timeout);
13681
14023
  });
13682
14024
  return Promise.race([timeoutPromise, promise]);
@@ -13717,7 +14059,7 @@ var Fuel = class _Fuel extends FuelConnector {
13717
14059
  this._targetUnsubscribe = this.setupConnectorListener();
13718
14060
  await connectResponse;
13719
14061
  } catch (error) {
13720
- throw new FuelError34(ErrorCode30.INVALID_PROVIDER, "Error initializing Fuel Connector");
14062
+ throw new FuelError35(ErrorCode31.INVALID_PROVIDER, "Error initializing Fuel Connector");
13721
14063
  }
13722
14064
  }
13723
14065
  async init() {
@@ -13783,8 +14125,8 @@ var Fuel = class _Fuel extends FuelConnector {
13783
14125
  const hasConnector = await this.hasConnector();
13784
14126
  await this.pingConnector();
13785
14127
  if (!this._currentConnector || !hasConnector) {
13786
- throw new FuelError34(
13787
- ErrorCode30.MISSING_CONNECTOR,
14128
+ throw new FuelError35(
14129
+ ErrorCode31.MISSING_CONNECTOR,
13788
14130
  `No connector selected for calling ${method}. Use hasConnector before executing other methods.`
13789
14131
  );
13790
14132
  }
@@ -13848,7 +14190,7 @@ var Fuel = class _Fuel extends FuelConnector {
13848
14190
  cacheTime: PING_CACHE_TIME
13849
14191
  })();
13850
14192
  } catch {
13851
- throw new FuelError34(ErrorCode30.INVALID_PROVIDER, "Current connector is not available.");
14193
+ throw new FuelError35(ErrorCode31.INVALID_PROVIDER, "Current connector is not available.");
13852
14194
  }
13853
14195
  }
13854
14196
  /**
@@ -13997,7 +14339,7 @@ var Fuel = class _Fuel extends FuelConnector {
13997
14339
  const currentNetwork = await this.currentNetwork();
13998
14340
  provider = new Provider(currentNetwork.url);
13999
14341
  } else {
14000
- throw new FuelError34(ErrorCode30.INVALID_PROVIDER, "Provider is not valid.");
14342
+ throw new FuelError35(ErrorCode31.INVALID_PROVIDER, "Provider is not valid.");
14001
14343
  }
14002
14344
  return provider;
14003
14345
  }
@@ -14107,6 +14449,8 @@ export {
14107
14449
  calculateMinGasForTxUpload,
14108
14450
  calculateTXFeeForSummary,
14109
14451
  coinQuantityfy,
14452
+ consolidateCoins,
14453
+ consolidateCoinsIfRequired,
14110
14454
  deferPromise,
14111
14455
  deployScriptOrPredicate,
14112
14456
  deserializeChain,
@@ -14125,6 +14469,7 @@ export {
14125
14469
  extractTxError,
14126
14470
  fuelAssetsBaseUrl,
14127
14471
  gasUsedByInputs,
14472
+ getAllCoins,
14128
14473
  getAllDecodedLogs,
14129
14474
  getAssetAmountInRequestInputs,
14130
14475
  getAssetById,