@fuel-ts/account 0.0.0-pr-2930-20240813211727 → 0.0.0-pr-2942-20240816061339

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.

Potentially problematic release.


This version of @fuel-ts/account might be problematic. Click here for more details.

Files changed (85) hide show
  1. package/README.md +9 -29
  2. package/dist/account.d.ts +15 -4
  3. package/dist/account.d.ts.map +1 -1
  4. package/dist/configs.d.ts +0 -2
  5. package/dist/configs.d.ts.map +1 -1
  6. package/dist/configs.global.js +0 -2
  7. package/dist/configs.global.js.map +1 -1
  8. package/dist/configs.js +0 -6
  9. package/dist/configs.js.map +1 -1
  10. package/dist/configs.mjs +0 -4
  11. package/dist/configs.mjs.map +1 -1
  12. package/dist/connectors/fuel-connector.d.ts +24 -1
  13. package/dist/connectors/fuel-connector.d.ts.map +1 -1
  14. package/dist/connectors/fuel.d.ts +14 -4
  15. package/dist/connectors/fuel.d.ts.map +1 -1
  16. package/dist/connectors/types/connector-metadata.d.ts.map +1 -1
  17. package/dist/connectors/utils/promises.d.ts.map +1 -1
  18. package/dist/index.global.js +1387 -1033
  19. package/dist/index.global.js.map +1 -1
  20. package/dist/index.js +705 -528
  21. package/dist/index.js.map +1 -1
  22. package/dist/index.mjs +533 -367
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/predicate/predicate.d.ts +15 -9
  25. package/dist/predicate/predicate.d.ts.map +1 -1
  26. package/dist/providers/__generated__/operations.d.ts +119 -0
  27. package/dist/providers/__generated__/operations.d.ts.map +1 -1
  28. package/dist/providers/fuel-graphql-subscriber.d.ts +1 -0
  29. package/dist/providers/fuel-graphql-subscriber.d.ts.map +1 -1
  30. package/dist/providers/provider.d.ts +14 -47
  31. package/dist/providers/provider.d.ts.map +1 -1
  32. package/dist/providers/resource-cache.d.ts +14 -0
  33. package/dist/providers/resource-cache.d.ts.map +1 -0
  34. package/dist/providers/transaction-request/blob-transaction-request.d.ts +48 -0
  35. package/dist/providers/transaction-request/blob-transaction-request.d.ts.map +1 -0
  36. package/dist/providers/transaction-request/index.d.ts +1 -0
  37. package/dist/providers/transaction-request/index.d.ts.map +1 -1
  38. package/dist/providers/transaction-request/transaction-request.d.ts +4 -3
  39. package/dist/providers/transaction-request/transaction-request.d.ts.map +1 -1
  40. package/dist/providers/transaction-request/types.d.ts +5 -2
  41. package/dist/providers/transaction-request/types.d.ts.map +1 -1
  42. package/dist/providers/transaction-request/utils.d.ts +9 -0
  43. package/dist/providers/transaction-request/utils.d.ts.map +1 -1
  44. package/dist/providers/transaction-response/transaction-response.d.ts +3 -0
  45. package/dist/providers/transaction-response/transaction-response.d.ts.map +1 -1
  46. package/dist/providers/transaction-summary/assemble-transaction-summary.d.ts.map +1 -1
  47. package/dist/providers/transaction-summary/call.d.ts +4 -3
  48. package/dist/providers/transaction-summary/call.d.ts.map +1 -1
  49. package/dist/providers/transaction-summary/input.d.ts +1 -1
  50. package/dist/providers/transaction-summary/input.d.ts.map +1 -1
  51. package/dist/providers/transaction-summary/operations.d.ts +3 -1
  52. package/dist/providers/transaction-summary/operations.d.ts.map +1 -1
  53. package/dist/providers/transaction-summary/types.d.ts +3 -1
  54. package/dist/providers/transaction-summary/types.d.ts.map +1 -1
  55. package/dist/providers/utils/gas.d.ts +6 -0
  56. package/dist/providers/utils/gas.d.ts.map +1 -1
  57. package/dist/test-utils/launchNode.d.ts +0 -16
  58. package/dist/test-utils/launchNode.d.ts.map +1 -1
  59. package/dist/test-utils/setup-test-provider-and-wallets.d.ts.map +1 -1
  60. package/dist/test-utils/test-asset-id.d.ts +8 -0
  61. package/dist/test-utils/test-asset-id.d.ts.map +1 -0
  62. package/dist/test-utils/test-message.d.ts +4 -2
  63. package/dist/test-utils/test-message.d.ts.map +1 -1
  64. package/dist/test-utils/wallet-config.d.ts +3 -3
  65. package/dist/test-utils/wallet-config.d.ts.map +1 -1
  66. package/dist/test-utils.d.ts +1 -3
  67. package/dist/test-utils.d.ts.map +1 -1
  68. package/dist/test-utils.global.js +39070 -38743
  69. package/dist/test-utils.global.js.map +1 -1
  70. package/dist/test-utils.js +1314 -1201
  71. package/dist/test-utils.js.map +1 -1
  72. package/dist/test-utils.mjs +1031 -919
  73. package/dist/test-utils.mjs.map +1 -1
  74. package/dist/wallet/base-wallet-unlocked.d.ts +1 -2
  75. package/dist/wallet/base-wallet-unlocked.d.ts.map +1 -1
  76. package/dist/wallet/keystore-wallet.d.ts.map +1 -1
  77. package/package.json +19 -21
  78. package/dist/providers/memory-cache.d.ts +0 -11
  79. package/dist/providers/memory-cache.d.ts.map +0 -1
  80. package/dist/test-utils/asset-id.d.ts +0 -8
  81. package/dist/test-utils/asset-id.d.ts.map +0 -1
  82. package/dist/test-utils/generateTestWallet.d.ts +0 -4
  83. package/dist/test-utils/generateTestWallet.d.ts.map +0 -1
  84. package/dist/test-utils/seedTestWallet.d.ts +0 -4
  85. package/dist/test-utils/seedTestWallet.d.ts.map +0 -1
@@ -18,23 +18,330 @@ var __privateMethod = (obj, member, method) => {
18
18
  return method;
19
19
  };
20
20
 
21
- // src/wallet/base-wallet-unlocked.ts
22
- import { hashMessage } from "@fuel-ts/hasher";
23
- import { hexlify as hexlify16 } from "@fuel-ts/utils";
21
+ // src/test-utils/launchNode.ts
22
+ import { BYTES_32 } from "@fuel-ts/abi-coder";
23
+ import { randomBytes as randomBytes2, randomUUID } from "@fuel-ts/crypto";
24
+ import { FuelError } from "@fuel-ts/errors";
25
+ import { defaultConsensusKey, hexlify as hexlify2, defaultSnapshotConfigs } from "@fuel-ts/utils";
26
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "fs";
27
+ import os from "os";
28
+ import path from "path";
29
+ import { getPortPromise } from "portfinder";
24
30
 
25
- // src/account.ts
26
- import { UTXO_ID_LEN as UTXO_ID_LEN3 } from "@fuel-ts/abi-coder";
27
- import { Address as Address3 } from "@fuel-ts/address";
28
- import { randomBytes as randomBytes2 } from "@fuel-ts/crypto";
29
- import { ErrorCode as ErrorCode15, FuelError as FuelError15 } from "@fuel-ts/errors";
30
- import { AbstractAccount } from "@fuel-ts/interfaces";
31
- import { bn as bn19 } from "@fuel-ts/math";
32
- import { arrayify as arrayify14, hexlify as hexlify13, isDefined as isDefined2 } from "@fuel-ts/utils";
33
- import { clone as clone4 } from "ramda";
31
+ // src/signer/signer.ts
32
+ import { Address } from "@fuel-ts/address";
33
+ import { randomBytes } from "@fuel-ts/crypto";
34
+ import { hash } from "@fuel-ts/hasher";
35
+ import { toBytes } from "@fuel-ts/math";
36
+ import { hexlify, concat, arrayify } from "@fuel-ts/utils";
37
+ import { secp256k1 } from "@noble/curves/secp256k1";
38
+ var Signer = class {
39
+ address;
40
+ publicKey;
41
+ compressedPublicKey;
42
+ privateKey;
43
+ /**
44
+ * Create a Signer instance from a given private key
45
+ *
46
+ * @param privateKey - The private key to use for signing
47
+ * @returns A new Signer instance
48
+ */
49
+ constructor(privateKey) {
50
+ if (typeof privateKey === "string") {
51
+ if (privateKey.match(/^[0-9a-f]*$/i) && privateKey.length === 64) {
52
+ privateKey = `0x${privateKey}`;
53
+ }
54
+ }
55
+ const privateKeyBytes = toBytes(privateKey, 32);
56
+ this.privateKey = hexlify(privateKeyBytes);
57
+ this.publicKey = hexlify(secp256k1.getPublicKey(privateKeyBytes, false).slice(1));
58
+ this.compressedPublicKey = hexlify(secp256k1.getPublicKey(privateKeyBytes, true));
59
+ this.address = Address.fromPublicKey(this.publicKey);
60
+ }
61
+ /**
62
+ * Sign data using the Signer instance
63
+ *
64
+ * Signature is a 64 byte array of the concatenated r and s values with the compressed recoveryParam byte.
65
+ * @ignore
66
+ * [Read more](FuelLabs/fuel-specs/specs/protocol/cryptographic_primitives.md#public-key-cryptography)
67
+ *
68
+ * @param data - The data to be sign
69
+ * @returns hashed signature
70
+ */
71
+ sign(data) {
72
+ const signature = secp256k1.sign(arrayify(data), arrayify(this.privateKey));
73
+ const r = toBytes(`0x${signature.r.toString(16)}`, 32);
74
+ const s = toBytes(`0x${signature.s.toString(16)}`, 32);
75
+ s[0] |= (signature.recovery || 0) << 7;
76
+ return hexlify(concat([r, s]));
77
+ }
78
+ /**
79
+ * Add point on the current elliptic curve
80
+ *
81
+ * @param point - Point to add on the curve
82
+ * @returns compressed point on the curve
83
+ */
84
+ addPoint(point) {
85
+ const p0 = secp256k1.ProjectivePoint.fromHex(arrayify(this.compressedPublicKey));
86
+ const p1 = secp256k1.ProjectivePoint.fromHex(arrayify(point));
87
+ const result = p0.add(p1);
88
+ return `0x${result.toHex(true)}`;
89
+ }
90
+ /**
91
+ * Recover the public key from a signature performed with [`sign`](#sign).
92
+ *
93
+ * @param data - Data
94
+ * @param signature - hashed signature
95
+ * @returns public key from signature from the
96
+ */
97
+ static recoverPublicKey(data, signature) {
98
+ const signedMessageBytes = arrayify(signature);
99
+ const r = signedMessageBytes.slice(0, 32);
100
+ const s = signedMessageBytes.slice(32, 64);
101
+ const recoveryParam = (s[0] & 128) >> 7;
102
+ s[0] &= 127;
103
+ const sig = new secp256k1.Signature(BigInt(hexlify(r)), BigInt(hexlify(s))).addRecoveryBit(
104
+ recoveryParam
105
+ );
106
+ const publicKey = sig.recoverPublicKey(arrayify(data)).toRawBytes(false).slice(1);
107
+ return hexlify(publicKey);
108
+ }
109
+ /**
110
+ * Recover the address from a signature performed with [`sign`](#sign).
111
+ *
112
+ * @param data - Data
113
+ * @param signature - Signature
114
+ * @returns Address from signature
115
+ */
116
+ static recoverAddress(data, signature) {
117
+ return Address.fromPublicKey(Signer.recoverPublicKey(data, signature));
118
+ }
119
+ /**
120
+ * Generate a random privateKey
121
+ *
122
+ * @param entropy - Adds extra entropy to generate the privateKey
123
+ * @returns random 32-byte hashed
124
+ */
125
+ static generatePrivateKey(entropy) {
126
+ return entropy ? hash(concat([randomBytes(32), arrayify(entropy)])) : randomBytes(32);
127
+ }
128
+ /**
129
+ * Extended publicKey from a compact publicKey
130
+ *
131
+ * @param publicKey - Compact publicKey
132
+ * @returns extended publicKey
133
+ */
134
+ static extendPublicKey(publicKey) {
135
+ const point = secp256k1.ProjectivePoint.fromHex(arrayify(publicKey));
136
+ return hexlify(point.toRawBytes(false).slice(1));
137
+ }
138
+ };
139
+
140
+ // src/test-utils/launchNode.ts
141
+ var getFlagValueFromArgs = (args, flag) => {
142
+ const flagIndex = args.indexOf(flag);
143
+ if (flagIndex === -1) {
144
+ return void 0;
145
+ }
146
+ return args[flagIndex + 1];
147
+ };
148
+ var extractRemainingArgs = (args, flagsToRemove) => {
149
+ const newArgs = [...args];
150
+ flagsToRemove.forEach((flag) => {
151
+ const flagIndex = newArgs.indexOf(flag);
152
+ if (flagIndex !== -1) {
153
+ newArgs.splice(flagIndex, 2);
154
+ }
155
+ });
156
+ return newArgs;
157
+ };
158
+ function getFinalStateConfigJSON({ stateConfig, chainConfig }) {
159
+ const defaultCoins = defaultSnapshotConfigs.stateConfig.coins.map((coin) => ({
160
+ ...coin,
161
+ amount: "18446744073709551615"
162
+ }));
163
+ const defaultMessages = defaultSnapshotConfigs.stateConfig.messages.map((message) => ({
164
+ ...message,
165
+ amount: "18446744073709551615"
166
+ }));
167
+ const coins = defaultCoins.concat(stateConfig.coins.map((coin) => ({ ...coin, amount: coin.amount.toString() }))).filter((coin, index, self) => self.findIndex((c) => c.tx_id === coin.tx_id) === index);
168
+ const messages = defaultMessages.concat(stateConfig.messages.map((msg) => ({ ...msg, amount: msg.amount.toString() }))).filter((msg, index, self) => self.findIndex((m) => m.nonce === msg.nonce) === index);
169
+ if (!process.env.GENESIS_SECRET) {
170
+ const pk = Signer.generatePrivateKey();
171
+ const signer = new Signer(pk);
172
+ process.env.GENESIS_SECRET = hexlify2(pk);
173
+ coins.push({
174
+ tx_id: hexlify2(randomBytes2(BYTES_32)),
175
+ owner: signer.address.toHexString(),
176
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
177
+ amount: "18446744073709551615",
178
+ asset_id: chainConfig.consensus_parameters.V1.base_asset_id,
179
+ output_index: 0,
180
+ tx_pointer_block_height: 0,
181
+ tx_pointer_tx_idx: 0
182
+ });
183
+ }
184
+ const json = JSON.stringify({
185
+ ...stateConfig,
186
+ coins,
187
+ messages
188
+ });
189
+ const regexMakeNumber = /("amount":)"(\d+)"/gm;
190
+ return json.replace(regexMakeNumber, "$1$2");
191
+ }
192
+ var launchNode = async ({
193
+ ip,
194
+ port,
195
+ args = [],
196
+ fuelCorePath = process.env.FUEL_CORE_PATH || void 0,
197
+ loggingEnabled = true,
198
+ basePath,
199
+ snapshotConfig = defaultSnapshotConfigs
200
+ } = {}) => (
201
+ // eslint-disable-next-line no-async-promise-executor
202
+ new Promise(async (resolve, reject) => {
203
+ const remainingArgs = extractRemainingArgs(args, [
204
+ "--snapshot",
205
+ "--consensus-key",
206
+ "--db-type",
207
+ "--poa-instant",
208
+ "--min-gas-price",
209
+ "--native-executor-version"
210
+ ]);
211
+ const snapshotDir = getFlagValueFromArgs(args, "--snapshot");
212
+ const consensusKey = getFlagValueFromArgs(args, "--consensus-key") || defaultConsensusKey;
213
+ const dbTypeFlagValue = getFlagValueFromArgs(args, "--db-type");
214
+ const useInMemoryDb = dbTypeFlagValue === "in-memory" || dbTypeFlagValue === void 0;
215
+ const poaInstantFlagValue = getFlagValueFromArgs(args, "--poa-instant");
216
+ const poaInstant = poaInstantFlagValue === "true" || poaInstantFlagValue === void 0;
217
+ const nativeExecutorVersion = getFlagValueFromArgs(args, "--native-executor-version") || "0";
218
+ const minGasPrice = getFlagValueFromArgs(args, "--min-gas-price") || "1";
219
+ const graphQLStartSubstring = "Binding GraphQL provider to";
220
+ const command = fuelCorePath || "fuel-core";
221
+ const ipToUse = ip || "0.0.0.0";
222
+ const portToUse = port || (await getPortPromise({
223
+ port: 4e3,
224
+ // tries 4000 first, then 4001, then 4002, etc.
225
+ stopPort: 5e3
226
+ // don't try ports above 5000
227
+ })).toString();
228
+ let snapshotDirToUse;
229
+ const prefix = basePath || os.tmpdir();
230
+ const suffix = basePath ? "" : randomUUID();
231
+ const tempDir = path.join(prefix, ".fuels", suffix, "snapshotDir");
232
+ if (snapshotDir) {
233
+ snapshotDirToUse = snapshotDir;
234
+ } else {
235
+ if (!existsSync(tempDir)) {
236
+ mkdirSync(tempDir, { recursive: true });
237
+ }
238
+ const { metadata } = snapshotConfig;
239
+ const metadataPath = path.join(tempDir, "metadata.json");
240
+ const chainConfigPath = path.join(tempDir, metadata.chain_config);
241
+ const stateConfigPath = path.join(tempDir, metadata.table_encoding.Json.filepath);
242
+ const stateTransitionPath = path.join(tempDir, "state_transition_bytecode.wasm");
243
+ writeFileSync(chainConfigPath, JSON.stringify(snapshotConfig.chainConfig), "utf8");
244
+ writeFileSync(stateConfigPath, getFinalStateConfigJSON(snapshotConfig), "utf8");
245
+ writeFileSync(metadataPath, JSON.stringify(metadata), "utf8");
246
+ writeFileSync(stateTransitionPath, JSON.stringify(""));
247
+ snapshotDirToUse = tempDir;
248
+ }
249
+ const { spawn } = await import("child_process");
250
+ const child = spawn(
251
+ command,
252
+ [
253
+ "run",
254
+ ["--ip", ipToUse],
255
+ ["--port", portToUse],
256
+ useInMemoryDb ? ["--db-type", "in-memory"] : ["--db-path", tempDir],
257
+ ["--min-gas-price", minGasPrice],
258
+ poaInstant ? ["--poa-instant", "true"] : [],
259
+ ["--native-executor-version", nativeExecutorVersion],
260
+ ["--consensus-key", consensusKey],
261
+ ["--snapshot", snapshotDirToUse],
262
+ "--vm-backtrace",
263
+ "--utxo-validation",
264
+ "--debug",
265
+ ...remainingArgs
266
+ ].flat(),
267
+ { stdio: "pipe", detached: true }
268
+ );
269
+ if (loggingEnabled) {
270
+ child.stderr.on("data", (chunk) => {
271
+ console.log(chunk.toString());
272
+ });
273
+ }
274
+ const removeSideffects = () => {
275
+ child.stderr.removeAllListeners();
276
+ if (existsSync(tempDir)) {
277
+ rmSync(tempDir, { recursive: true });
278
+ }
279
+ };
280
+ child.on("error", removeSideffects);
281
+ child.on("exit", removeSideffects);
282
+ const childState = {
283
+ isDead: false
284
+ };
285
+ const cleanup = () => {
286
+ if (childState.isDead) {
287
+ return;
288
+ }
289
+ childState.isDead = true;
290
+ removeSideffects();
291
+ if (child.pid !== void 0) {
292
+ try {
293
+ process.kill(-child.pid);
294
+ } catch (e) {
295
+ const error = e;
296
+ if (error.code === "ESRCH") {
297
+ console.log(
298
+ `fuel-core node under pid ${child.pid} does not exist. The node might have been killed before cleanup was called. Exiting cleanly.`
299
+ );
300
+ } else {
301
+ throw e;
302
+ }
303
+ }
304
+ } else {
305
+ console.error("No PID available for the child process, unable to kill launched node");
306
+ }
307
+ };
308
+ child.stderr.on("data", (chunk) => {
309
+ const text = typeof chunk === "string" ? chunk : chunk.toString();
310
+ if (text.indexOf(graphQLStartSubstring) !== -1) {
311
+ const rows = text.split("\n");
312
+ const rowWithUrl = rows.find((row) => row.indexOf(graphQLStartSubstring) !== -1);
313
+ const [realIp, realPort] = rowWithUrl.split(" ").at(-1).trim().split(":");
314
+ resolve({
315
+ cleanup,
316
+ ip: realIp,
317
+ port: realPort,
318
+ url: `http://${realIp}:${realPort}/v1/graphql`,
319
+ snapshotDir: snapshotDirToUse,
320
+ pid: child.pid
321
+ });
322
+ }
323
+ if (/error/i.test(text)) {
324
+ console.log(text);
325
+ reject(new FuelError(FuelError.CODES.NODE_LAUNCH_FAILED, text));
326
+ }
327
+ });
328
+ process.on("exit", cleanup);
329
+ process.on("SIGINT", cleanup);
330
+ process.on("SIGUSR1", cleanup);
331
+ process.on("SIGUSR2", cleanup);
332
+ process.on("beforeExit", cleanup);
333
+ process.on("uncaughtException", cleanup);
334
+ child.on("error", reject);
335
+ })
336
+ );
337
+
338
+ // src/test-utils/setup-test-provider-and-wallets.ts
339
+ import { defaultSnapshotConfigs as defaultSnapshotConfigs3 } from "@fuel-ts/utils";
340
+ import { mergeDeepRight } from "ramda";
34
341
 
35
342
  // src/providers/coin-quantity.ts
36
343
  import { bn } from "@fuel-ts/math";
37
- import { hexlify } from "@fuel-ts/utils";
344
+ import { hexlify as hexlify3 } from "@fuel-ts/utils";
38
345
  var coinQuantityfy = (coinQuantityLike) => {
39
346
  let assetId;
40
347
  let amount;
@@ -50,7 +357,7 @@ var coinQuantityfy = (coinQuantityLike) => {
50
357
  }
51
358
  const bnAmount = bn(amount);
52
359
  return {
53
- assetId: hexlify(assetId),
360
+ assetId: hexlify3(assetId),
54
361
  amount: bnAmount.lt(1) ? bn(1) : bnAmount,
55
362
  max: max ? bn(max) : void 0
56
363
  };
@@ -68,16 +375,11 @@ var addAmountToCoinQuantities = (params) => {
68
375
  };
69
376
 
70
377
  // src/providers/provider.ts
71
- import { Address as Address2 } from "@fuel-ts/address";
72
- import { ErrorCode as ErrorCode13, FuelError as FuelError13 } from "@fuel-ts/errors";
378
+ import { Address as Address3 } from "@fuel-ts/address";
379
+ import { ErrorCode as ErrorCode13, FuelError as FuelError15 } from "@fuel-ts/errors";
73
380
  import { BN, bn as bn17 } from "@fuel-ts/math";
74
- import {
75
- InputType as InputType7,
76
- TransactionType as TransactionType8,
77
- InputMessageCoder,
78
- TransactionCoder as TransactionCoder5
79
- } from "@fuel-ts/transactions";
80
- import { arrayify as arrayify11, hexlify as hexlify12, DateTime as DateTime2 } from "@fuel-ts/utils";
381
+ import { InputType as InputType7, InputMessageCoder, TransactionCoder as TransactionCoder5 } from "@fuel-ts/transactions";
382
+ import { arrayify as arrayify12, hexlify as hexlify14, DateTime as DateTime2, isDefined as isDefined2 } from "@fuel-ts/utils";
81
383
  import { checkFuelCoreVersionCompatibility } from "@fuel-ts/versions";
82
384
  import { equalBytes } from "@noble/curves/abstract/utils";
83
385
  import { GraphQLClient } from "graphql-request";
@@ -510,6 +812,12 @@ var GasCostsFragmentDoc = gql`
510
812
  alocDependentCost {
511
813
  ...DependentCostFragment
512
814
  }
815
+ bldd {
816
+ ...DependentCostFragment
817
+ }
818
+ bsiz {
819
+ ...DependentCostFragment
820
+ }
513
821
  cfe {
514
822
  ...DependentCostFragment
515
823
  }
@@ -528,6 +836,9 @@ var GasCostsFragmentDoc = gql`
528
836
  csiz {
529
837
  ...DependentCostFragment
530
838
  }
839
+ ed19DependentCost {
840
+ ...DependentCostFragment
841
+ }
531
842
  k256 {
532
843
  ...DependentCostFragment
533
844
  }
@@ -1056,7 +1367,7 @@ function getSdk(requester) {
1056
1367
  }
1057
1368
 
1058
1369
  // src/providers/fuel-graphql-subscriber.ts
1059
- import { ErrorCode, FuelError } from "@fuel-ts/errors";
1370
+ import { ErrorCode, FuelError as FuelError2 } from "@fuel-ts/errors";
1060
1371
  import { print } from "graphql";
1061
1372
  var _FuelGraphqlSubscriber = class {
1062
1373
  constructor(options) {
@@ -1088,8 +1399,8 @@ var _FuelGraphqlSubscriber = class {
1088
1399
  if (this.events.length > 0) {
1089
1400
  const { data, errors } = this.events.shift();
1090
1401
  if (Array.isArray(errors)) {
1091
- throw new FuelError(
1092
- FuelError.CODES.INVALID_REQUEST,
1402
+ throw new FuelError2(
1403
+ FuelError2.CODES.INVALID_REQUEST,
1093
1404
  errors.map((err) => err.message).join("\n\n")
1094
1405
  );
1095
1406
  }
@@ -1110,7 +1421,7 @@ var _FuelGraphqlSubscriber = class {
1110
1421
  try {
1111
1422
  this.events.push(JSON.parse(match.replace(/^data:/, "")));
1112
1423
  } catch (e) {
1113
- throw new FuelError(
1424
+ throw new FuelError2(
1114
1425
  ErrorCode.STREAM_PARSING_ERROR,
1115
1426
  `Error while parsing stream data response: ${text}`
1116
1427
  );
@@ -1134,95 +1445,98 @@ var _FuelGraphqlSubscriber = class {
1134
1445
  var FuelGraphqlSubscriber = _FuelGraphqlSubscriber;
1135
1446
  __publicField(FuelGraphqlSubscriber, "textDecoder", new TextDecoder());
1136
1447
 
1137
- // src/providers/memory-cache.ts
1138
- import { ErrorCode as ErrorCode2, FuelError as FuelError2 } from "@fuel-ts/errors";
1139
- import { hexlify as hexlify2 } from "@fuel-ts/utils";
1140
- var cache = {};
1141
- var DEFAULT_TTL_IN_MS = 30 * 1e3;
1142
- var MemoryCache = class {
1448
+ // src/providers/resource-cache.ts
1449
+ import { ErrorCode as ErrorCode2, FuelError as FuelError3 } from "@fuel-ts/errors";
1450
+ import { hexlify as hexlify4 } from "@fuel-ts/utils";
1451
+ var cache = /* @__PURE__ */ new Map();
1452
+ var ResourceCache = class {
1143
1453
  ttl;
1144
- constructor(ttlInMs = DEFAULT_TTL_IN_MS) {
1145
- this.ttl = ttlInMs;
1146
- if (typeof ttlInMs !== "number" || this.ttl <= 0) {
1147
- throw new FuelError2(
1454
+ constructor(ttl) {
1455
+ this.ttl = ttl;
1456
+ if (typeof ttl !== "number" || this.ttl <= 0) {
1457
+ throw new FuelError3(
1148
1458
  ErrorCode2.INVALID_TTL,
1149
1459
  `Invalid TTL: ${this.ttl}. Use a value greater than zero.`
1150
1460
  );
1151
1461
  }
1152
1462
  }
1153
- get(value, isAutoExpiring = true) {
1154
- const key = hexlify2(value);
1155
- if (cache[key]) {
1156
- if (!isAutoExpiring || cache[key].expires > Date.now()) {
1157
- return cache[key].value;
1158
- }
1159
- this.del(value);
1160
- }
1161
- return void 0;
1162
- }
1163
- set(value) {
1164
- const expiresAt = Date.now() + this.ttl;
1165
- const key = hexlify2(value);
1166
- cache[key] = {
1167
- expires: expiresAt,
1168
- value
1463
+ // Add resources to the cache
1464
+ set(transactionId, resources) {
1465
+ const currentTime = Date.now();
1466
+ const existingResources = cache.get(transactionId) || {
1467
+ utxos: /* @__PURE__ */ new Set(),
1468
+ messages: /* @__PURE__ */ new Set(),
1469
+ timestamp: currentTime
1169
1470
  };
1170
- return expiresAt;
1471
+ resources.utxos.forEach((utxo) => existingResources.utxos.add(hexlify4(utxo)));
1472
+ resources.messages.forEach((message) => existingResources.messages.add(hexlify4(message)));
1473
+ cache.set(transactionId, existingResources);
1171
1474
  }
1172
- getAllData() {
1173
- return Object.keys(cache).reduce((list, key) => {
1174
- const data = this.get(key, false);
1175
- if (data) {
1176
- list.push(data);
1177
- }
1178
- return list;
1179
- }, []);
1475
+ // Remove resources from the cache for a given transaction ID
1476
+ unset(transactionId) {
1477
+ cache.delete(transactionId);
1180
1478
  }
1479
+ // Get all cached resources and remove expired ones
1181
1480
  getActiveData() {
1182
- return Object.keys(cache).reduce((list, key) => {
1183
- const data = this.get(key);
1184
- if (data) {
1185
- list.push(data);
1481
+ const allResources = { utxos: [], messages: [] };
1482
+ const currentTime = Date.now();
1483
+ cache.forEach((resource, transactionId) => {
1484
+ if (currentTime - resource.timestamp < this.ttl) {
1485
+ allResources.utxos.push(...resource.utxos);
1486
+ allResources.messages.push(...resource.messages);
1487
+ } else {
1488
+ cache.delete(transactionId);
1489
+ }
1490
+ });
1491
+ return allResources;
1492
+ }
1493
+ // Check if a UTXO ID or message nonce is already cached and not expired
1494
+ isCached(key) {
1495
+ const currentTime = Date.now();
1496
+ for (const [transactionId, resourceData] of cache.entries()) {
1497
+ if (currentTime - resourceData.timestamp > this.ttl) {
1498
+ cache.delete(transactionId);
1499
+ } else if (resourceData.utxos.has(key) || resourceData.messages.has(key)) {
1500
+ return true;
1186
1501
  }
1187
- return list;
1188
- }, []);
1502
+ }
1503
+ return false;
1189
1504
  }
1190
- del(value) {
1191
- const key = hexlify2(value);
1192
- delete cache[key];
1505
+ clear() {
1506
+ cache.clear();
1193
1507
  }
1194
1508
  };
1195
1509
 
1196
1510
  // src/providers/transaction-request/input.ts
1197
- import { BYTES_32, UTXO_ID_LEN } from "@fuel-ts/abi-coder";
1511
+ import { BYTES_32 as BYTES_322, UTXO_ID_LEN } from "@fuel-ts/abi-coder";
1198
1512
  import { ZeroBytes32 } from "@fuel-ts/address/configs";
1199
- import { ErrorCode as ErrorCode3, FuelError as FuelError3 } from "@fuel-ts/errors";
1513
+ import { ErrorCode as ErrorCode3, FuelError as FuelError4 } from "@fuel-ts/errors";
1200
1514
  import { bn as bn2, toNumber } from "@fuel-ts/math";
1201
1515
  import { InputType } from "@fuel-ts/transactions";
1202
- import { arrayify, hexlify as hexlify3 } from "@fuel-ts/utils";
1516
+ import { arrayify as arrayify2, hexlify as hexlify5 } from "@fuel-ts/utils";
1203
1517
  var inputify = (value) => {
1204
1518
  const { type } = value;
1205
1519
  switch (value.type) {
1206
1520
  case InputType.Coin: {
1207
- const predicate = arrayify(value.predicate ?? "0x");
1208
- const predicateData = arrayify(value.predicateData ?? "0x");
1521
+ const predicate = arrayify2(value.predicate ?? "0x");
1522
+ const predicateData = arrayify2(value.predicateData ?? "0x");
1209
1523
  return {
1210
1524
  type: InputType.Coin,
1211
- txID: hexlify3(arrayify(value.id).slice(0, BYTES_32)),
1212
- outputIndex: toNumber(arrayify(value.id).slice(BYTES_32, UTXO_ID_LEN)),
1213
- owner: hexlify3(value.owner),
1525
+ txID: hexlify5(arrayify2(value.id).slice(0, BYTES_322)),
1526
+ outputIndex: toNumber(arrayify2(value.id).slice(BYTES_322, UTXO_ID_LEN)),
1527
+ owner: hexlify5(value.owner),
1214
1528
  amount: bn2(value.amount),
1215
- assetId: hexlify3(value.assetId),
1529
+ assetId: hexlify5(value.assetId),
1216
1530
  txPointer: {
1217
- blockHeight: toNumber(arrayify(value.txPointer).slice(0, 8)),
1218
- txIndex: toNumber(arrayify(value.txPointer).slice(8, 16))
1531
+ blockHeight: toNumber(arrayify2(value.txPointer).slice(0, 8)),
1532
+ txIndex: toNumber(arrayify2(value.txPointer).slice(8, 16))
1219
1533
  },
1220
1534
  witnessIndex: value.witnessIndex,
1221
1535
  predicateGasUsed: bn2(value.predicateGasUsed),
1222
1536
  predicateLength: bn2(predicate.length),
1223
1537
  predicateDataLength: bn2(predicateData.length),
1224
- predicate: hexlify3(predicate),
1225
- predicateData: hexlify3(predicateData)
1538
+ predicate: hexlify5(predicate),
1539
+ predicateData: hexlify5(predicateData)
1226
1540
  };
1227
1541
  }
1228
1542
  case InputType.Contract: {
@@ -1233,34 +1547,34 @@ var inputify = (value) => {
1233
1547
  balanceRoot: ZeroBytes32,
1234
1548
  stateRoot: ZeroBytes32,
1235
1549
  txPointer: {
1236
- blockHeight: toNumber(arrayify(value.txPointer).slice(0, 8)),
1237
- txIndex: toNumber(arrayify(value.txPointer).slice(8, 16))
1550
+ blockHeight: toNumber(arrayify2(value.txPointer).slice(0, 8)),
1551
+ txIndex: toNumber(arrayify2(value.txPointer).slice(8, 16))
1238
1552
  },
1239
- contractID: hexlify3(value.contractId)
1553
+ contractID: hexlify5(value.contractId)
1240
1554
  };
1241
1555
  }
1242
1556
  case InputType.Message: {
1243
- const predicate = arrayify(value.predicate ?? "0x");
1244
- const predicateData = arrayify(value.predicateData ?? "0x");
1245
- const data = arrayify(value.data ?? "0x");
1557
+ const predicate = arrayify2(value.predicate ?? "0x");
1558
+ const predicateData = arrayify2(value.predicateData ?? "0x");
1559
+ const data = arrayify2(value.data ?? "0x");
1246
1560
  return {
1247
1561
  type: InputType.Message,
1248
- sender: hexlify3(value.sender),
1249
- recipient: hexlify3(value.recipient),
1562
+ sender: hexlify5(value.sender),
1563
+ recipient: hexlify5(value.recipient),
1250
1564
  amount: bn2(value.amount),
1251
- nonce: hexlify3(value.nonce),
1565
+ nonce: hexlify5(value.nonce),
1252
1566
  witnessIndex: value.witnessIndex,
1253
1567
  predicateGasUsed: bn2(value.predicateGasUsed),
1254
1568
  predicateLength: bn2(predicate.length),
1255
1569
  predicateDataLength: bn2(predicateData.length),
1256
- predicate: hexlify3(predicate),
1257
- predicateData: hexlify3(predicateData),
1258
- data: hexlify3(data),
1570
+ predicate: hexlify5(predicate),
1571
+ predicateData: hexlify5(predicateData),
1572
+ data: hexlify5(data),
1259
1573
  dataLength: data.length
1260
1574
  };
1261
1575
  }
1262
1576
  default: {
1263
- throw new FuelError3(
1577
+ throw new FuelError4(
1264
1578
  ErrorCode3.INVALID_TRANSACTION_INPUT,
1265
1579
  `Invalid transaction input type: ${type}.`
1266
1580
  );
@@ -1270,19 +1584,19 @@ var inputify = (value) => {
1270
1584
 
1271
1585
  // src/providers/transaction-request/output.ts
1272
1586
  import { ZeroBytes32 as ZeroBytes322 } from "@fuel-ts/address/configs";
1273
- import { ErrorCode as ErrorCode4, FuelError as FuelError4 } from "@fuel-ts/errors";
1587
+ import { ErrorCode as ErrorCode4, FuelError as FuelError5 } from "@fuel-ts/errors";
1274
1588
  import { bn as bn3 } from "@fuel-ts/math";
1275
1589
  import { OutputType } from "@fuel-ts/transactions";
1276
- import { hexlify as hexlify4 } from "@fuel-ts/utils";
1590
+ import { hexlify as hexlify6 } from "@fuel-ts/utils";
1277
1591
  var outputify = (value) => {
1278
1592
  const { type } = value;
1279
1593
  switch (type) {
1280
1594
  case OutputType.Coin: {
1281
1595
  return {
1282
1596
  type: OutputType.Coin,
1283
- to: hexlify4(value.to),
1597
+ to: hexlify6(value.to),
1284
1598
  amount: bn3(value.amount),
1285
- assetId: hexlify4(value.assetId)
1599
+ assetId: hexlify6(value.assetId)
1286
1600
  };
1287
1601
  }
1288
1602
  case OutputType.Contract: {
@@ -1296,9 +1610,9 @@ var outputify = (value) => {
1296
1610
  case OutputType.Change: {
1297
1611
  return {
1298
1612
  type: OutputType.Change,
1299
- to: hexlify4(value.to),
1613
+ to: hexlify6(value.to),
1300
1614
  amount: bn3(0),
1301
- assetId: hexlify4(value.assetId)
1615
+ assetId: hexlify6(value.assetId)
1302
1616
  };
1303
1617
  }
1304
1618
  case OutputType.Variable: {
@@ -1312,12 +1626,12 @@ var outputify = (value) => {
1312
1626
  case OutputType.ContractCreated: {
1313
1627
  return {
1314
1628
  type: OutputType.ContractCreated,
1315
- contractId: hexlify4(value.contractId),
1316
- stateRoot: hexlify4(value.stateRoot)
1629
+ contractId: hexlify6(value.contractId),
1630
+ stateRoot: hexlify6(value.stateRoot)
1317
1631
  };
1318
1632
  }
1319
1633
  default: {
1320
- throw new FuelError4(
1634
+ throw new FuelError5(
1321
1635
  ErrorCode4.INVALID_TRANSACTION_INPUT,
1322
1636
  `Invalid transaction output type: ${type}.`
1323
1637
  );
@@ -1327,9 +1641,10 @@ var outputify = (value) => {
1327
1641
 
1328
1642
  // src/providers/transaction-request/transaction-request.ts
1329
1643
  import { UTXO_ID_LEN as UTXO_ID_LEN2 } from "@fuel-ts/abi-coder";
1330
- import { Address, addressify } from "@fuel-ts/address";
1644
+ import { Address as Address2, addressify } from "@fuel-ts/address";
1331
1645
  import { ZeroBytes32 as ZeroBytes324 } from "@fuel-ts/address/configs";
1332
- import { randomBytes } from "@fuel-ts/crypto";
1646
+ import { randomBytes as randomBytes3 } from "@fuel-ts/crypto";
1647
+ import { FuelError as FuelError9 } from "@fuel-ts/errors";
1333
1648
  import { bn as bn8 } from "@fuel-ts/math";
1334
1649
  import {
1335
1650
  PolicyType,
@@ -1338,14 +1653,14 @@ import {
1338
1653
  OutputType as OutputType2,
1339
1654
  TransactionType
1340
1655
  } from "@fuel-ts/transactions";
1341
- import { concat, hexlify as hexlify7, isDefined } from "@fuel-ts/utils";
1656
+ import { concat as concat2, hexlify as hexlify9, isDefined } from "@fuel-ts/utils";
1342
1657
 
1343
1658
  // src/providers/resource.ts
1344
1659
  var isCoin = (resource) => "id" in resource;
1345
1660
 
1346
1661
  // src/providers/utils/receipts.ts
1347
1662
  import { ZeroBytes32 as ZeroBytes323 } from "@fuel-ts/address/configs";
1348
- import { ErrorCode as ErrorCode5, FuelError as FuelError5 } from "@fuel-ts/errors";
1663
+ import { ErrorCode as ErrorCode5, FuelError as FuelError6 } from "@fuel-ts/errors";
1349
1664
  import { bn as bn4 } from "@fuel-ts/math";
1350
1665
  import {
1351
1666
  ReceiptBurnCoder,
@@ -1354,7 +1669,7 @@ import {
1354
1669
  ReceiptType
1355
1670
  } from "@fuel-ts/transactions";
1356
1671
  import { FAILED_TRANSFER_TO_ADDRESS_SIGNAL } from "@fuel-ts/transactions/configs";
1357
- import { arrayify as arrayify2 } from "@fuel-ts/utils";
1672
+ import { arrayify as arrayify3 } from "@fuel-ts/utils";
1358
1673
  var doesReceiptHaveMissingOutputVariables = (receipt) => receipt.type === ReceiptType.Revert && receipt.val.toString("hex") === FAILED_TRANSFER_TO_ADDRESS_SIGNAL;
1359
1674
  var doesReceiptHaveMissingContractId = (receipt) => receipt.type === ReceiptType.Panic && receipt.contractId !== "0x0000000000000000000000000000000000000000000000000000000000000000";
1360
1675
  var getReceiptsWithMissingData = (receipts) => receipts.reduce(
@@ -1498,7 +1813,7 @@ function assembleReceiptByType(receipt) {
1498
1813
  const recipient = hexOrZero(receipt.recipient);
1499
1814
  const nonce = hexOrZero(receipt.nonce);
1500
1815
  const amount = bn4(receipt.amount);
1501
- const data = receipt.data ? arrayify2(receipt.data) : Uint8Array.from([]);
1816
+ const data = receipt.data ? arrayify3(receipt.data) : Uint8Array.from([]);
1502
1817
  const digest = hexOrZero(receipt.digest);
1503
1818
  const messageId = ReceiptMessageOutCoder.getMessageId({
1504
1819
  sender,
@@ -1550,17 +1865,17 @@ function assembleReceiptByType(receipt) {
1550
1865
  return burnReceipt;
1551
1866
  }
1552
1867
  default:
1553
- throw new FuelError5(ErrorCode5.INVALID_RECEIPT_TYPE, `Invalid receipt type: ${receiptType}.`);
1868
+ throw new FuelError6(ErrorCode5.INVALID_RECEIPT_TYPE, `Invalid receipt type: ${receiptType}.`);
1554
1869
  }
1555
1870
  }
1556
1871
 
1557
1872
  // src/providers/utils/block-explorer.ts
1558
- import { ErrorCode as ErrorCode6, FuelError as FuelError6 } from "@fuel-ts/errors";
1873
+ import { ErrorCode as ErrorCode6, FuelError as FuelError7 } from "@fuel-ts/errors";
1559
1874
 
1560
1875
  // src/providers/utils/gas.ts
1561
1876
  import { bn as bn5 } from "@fuel-ts/math";
1562
1877
  import { ReceiptType as ReceiptType2 } from "@fuel-ts/transactions";
1563
- import { arrayify as arrayify3 } from "@fuel-ts/utils";
1878
+ import { arrayify as arrayify4 } from "@fuel-ts/utils";
1564
1879
  var getGasUsedFromReceipts = (receipts) => {
1565
1880
  const scriptResult = receipts.filter(
1566
1881
  (receipt) => receipt.type === ReceiptType2.ScriptResult
@@ -1597,7 +1912,7 @@ function gasUsedByInputs(inputs, txBytesSize, gasCosts) {
1597
1912
  const totalGas = chargeableInputs.reduce((total, input) => {
1598
1913
  if ("predicate" in input && input.predicate && input.predicate !== "0x") {
1599
1914
  return total.add(
1600
- vmInitializationCost.add(resolveGasDependentCosts(arrayify3(input.predicate).length, gasCosts.contractRoot)).add(bn5(input.predicateGasUsed))
1915
+ vmInitializationCost.add(resolveGasDependentCosts(arrayify4(input.predicate).length, gasCosts.contractRoot)).add(bn5(input.predicateGasUsed))
1601
1916
  );
1602
1917
  }
1603
1918
  return total.add(gasCosts.ecr1);
@@ -1648,19 +1963,28 @@ function calculateMetadataGasForTxScript({
1648
1963
  }) {
1649
1964
  return resolveGasDependentCosts(txBytesSize, gasCosts.s256);
1650
1965
  }
1966
+ function calculateMetadataGasForTxBlob({
1967
+ gasCosts,
1968
+ txBytesSize,
1969
+ witnessBytesSize
1970
+ }) {
1971
+ const txId = resolveGasDependentCosts(txBytesSize, gasCosts.s256);
1972
+ const blobLen = resolveGasDependentCosts(witnessBytesSize, gasCosts.s256);
1973
+ return txId.add(blobLen);
1974
+ }
1651
1975
  var calculateGasFee = (params) => {
1652
1976
  const { gas, gasPrice, priceFactor, tip } = params;
1653
1977
  return gas.mul(gasPrice).div(priceFactor).add(bn5(tip));
1654
1978
  };
1655
1979
 
1656
1980
  // src/providers/utils/json.ts
1657
- import { hexlify as hexlify5 } from "@fuel-ts/utils";
1981
+ import { hexlify as hexlify7 } from "@fuel-ts/utils";
1658
1982
  import { clone } from "ramda";
1659
1983
  function normalize(object) {
1660
1984
  Object.keys(object).forEach((key) => {
1661
1985
  switch (object[key]?.constructor.name) {
1662
1986
  case "Uint8Array":
1663
- object[key] = hexlify5(object[key]);
1987
+ object[key] = hexlify7(object[key]);
1664
1988
  break;
1665
1989
  case "Array":
1666
1990
  object[key] = normalize(object[key]);
@@ -1685,7 +2009,7 @@ function normalizeJSON(root) {
1685
2009
  }
1686
2010
 
1687
2011
  // src/providers/utils/extract-tx-error.ts
1688
- import { ErrorCode as ErrorCode7, FuelError as FuelError7 } from "@fuel-ts/errors";
2012
+ import { ErrorCode as ErrorCode7, FuelError as FuelError8 } from "@fuel-ts/errors";
1689
2013
  import { bn as bn6 } from "@fuel-ts/math";
1690
2014
  import { ReceiptType as ReceiptType3 } from "@fuel-ts/transactions";
1691
2015
  import {
@@ -1706,7 +2030,7 @@ You can read more about this error at:
1706
2030
 
1707
2031
  ${PANIC_DOC_URL}#variant.${statusReason}`;
1708
2032
  }
1709
- return new FuelError7(ErrorCode7.SCRIPT_REVERTED, errorMessage, {
2033
+ return new FuelError8(ErrorCode7.SCRIPT_REVERTED, errorMessage, {
1710
2034
  ...metadata,
1711
2035
  reason: statusReason
1712
2036
  });
@@ -1745,7 +2069,7 @@ var assembleRevertError = (receipts, logs, metadata) => {
1745
2069
  errorMessage = `The transaction reverted because it's missing an "OutputChange".`;
1746
2070
  break;
1747
2071
  default:
1748
- throw new FuelError7(
2072
+ throw new FuelError8(
1749
2073
  ErrorCode7.UNKNOWN,
1750
2074
  `The transaction reverted with an unknown reason: ${revertReceipt.val}`,
1751
2075
  {
@@ -1755,7 +2079,7 @@ var assembleRevertError = (receipts, logs, metadata) => {
1755
2079
  );
1756
2080
  }
1757
2081
  }
1758
- return new FuelError7(ErrorCode7.SCRIPT_REVERTED, errorMessage, {
2082
+ return new FuelError8(ErrorCode7.SCRIPT_REVERTED, errorMessage, {
1759
2083
  ...metadata,
1760
2084
  reason
1761
2085
  });
@@ -1820,11 +2144,11 @@ var cacheRequestInputsResourcesFromOwner = (inputs, owner) => inputs.reduce(
1820
2144
  );
1821
2145
 
1822
2146
  // src/providers/transaction-request/witness.ts
1823
- import { arrayify as arrayify4, hexlify as hexlify6 } from "@fuel-ts/utils";
2147
+ import { arrayify as arrayify5, hexlify as hexlify8 } from "@fuel-ts/utils";
1824
2148
  var witnessify = (value) => {
1825
- const data = arrayify4(value);
2149
+ const data = arrayify5(value);
1826
2150
  return {
1827
- data: hexlify6(data),
2151
+ data: hexlify8(data),
1828
2152
  dataLength: data.length
1829
2153
  };
1830
2154
  };
@@ -1957,7 +2281,7 @@ var BaseTransactionRequest = class {
1957
2281
  * @returns The index of the created witness.
1958
2282
  */
1959
2283
  addEmptyWitness() {
1960
- this.addWitness(concat([ZeroBytes324, ZeroBytes324]));
2284
+ this.addWitness(concat2([ZeroBytes324, ZeroBytes324]));
1961
2285
  return this.witnesses.length - 1;
1962
2286
  }
1963
2287
  /**
@@ -1967,7 +2291,7 @@ var BaseTransactionRequest = class {
1967
2291
  * @param signature - The signature to update the witness with.
1968
2292
  */
1969
2293
  updateWitnessByOwner(address, signature) {
1970
- const ownerAddress = Address.fromAddressOrString(address);
2294
+ const ownerAddress = Address2.fromAddressOrString(address);
1971
2295
  const witnessIndex = this.getCoinInputWitnessIndexByOwner(ownerAddress);
1972
2296
  if (typeof witnessIndex === "number") {
1973
2297
  this.updateWitness(witnessIndex, signature);
@@ -2041,9 +2365,9 @@ var BaseTransactionRequest = class {
2041
2365
  const found = this.inputs.find((input) => {
2042
2366
  switch (input.type) {
2043
2367
  case InputType3.Coin:
2044
- return hexlify7(input.owner) === ownerAddress.toB256();
2368
+ return hexlify9(input.owner) === ownerAddress.toB256();
2045
2369
  case InputType3.Message:
2046
- return hexlify7(input.recipient) === ownerAddress.toB256();
2370
+ return hexlify9(input.recipient) === ownerAddress.toB256();
2047
2371
  default:
2048
2372
  return false;
2049
2373
  }
@@ -2178,7 +2502,7 @@ var BaseTransactionRequest = class {
2178
2502
  */
2179
2503
  addChangeOutput(to, assetId) {
2180
2504
  const changeOutput = this.getChangeOutputs().find(
2181
- (output) => hexlify7(output.assetId) === assetId
2505
+ (output) => hexlify9(output.assetId) === assetId
2182
2506
  );
2183
2507
  if (!changeOutput) {
2184
2508
  this.pushOutput({
@@ -2198,7 +2522,7 @@ var BaseTransactionRequest = class {
2198
2522
  * @hidden
2199
2523
  */
2200
2524
  metadataGas(_gasCosts) {
2201
- throw new Error("Not implemented");
2525
+ throw new FuelError9(FuelError9.CODES.NOT_IMPLEMENTED, "Not implemented");
2202
2526
  }
2203
2527
  /**
2204
2528
  * @hidden
@@ -2256,15 +2580,15 @@ var BaseTransactionRequest = class {
2256
2580
  usedQuantity = bn8("1000000000000000000");
2257
2581
  }
2258
2582
  if (assetInput && "assetId" in assetInput) {
2259
- assetInput.id = hexlify7(randomBytes(UTXO_ID_LEN2));
2583
+ assetInput.id = hexlify9(randomBytes3(UTXO_ID_LEN2));
2260
2584
  assetInput.amount = usedQuantity;
2261
2585
  } else {
2262
2586
  this.addResources([
2263
2587
  {
2264
- id: hexlify7(randomBytes(UTXO_ID_LEN2)),
2588
+ id: hexlify9(randomBytes3(UTXO_ID_LEN2)),
2265
2589
  amount: usedQuantity,
2266
2590
  assetId,
2267
- owner: resourcesOwner || Address.fromRandom(),
2591
+ owner: resourcesOwner || Address2.fromRandom(),
2268
2592
  blockCreated: bn8(1),
2269
2593
  txCreatedIdx: bn8(1)
2270
2594
  }
@@ -2273,6 +2597,7 @@ var BaseTransactionRequest = class {
2273
2597
  };
2274
2598
  updateAssetInput(baseAssetId, bn8(1e11));
2275
2599
  quantities.forEach((q) => updateAssetInput(q.assetId, q.amount));
2600
+ return this;
2276
2601
  }
2277
2602
  /**
2278
2603
  * Retrieves an array of CoinQuantity for each coin output present in the transaction.
@@ -2312,27 +2637,24 @@ var BaseTransactionRequest = class {
2312
2637
  this.inputs.filter(isRequestInputResource).forEach((i) => {
2313
2638
  const owner = getRequestInputResourceOwner(i);
2314
2639
  const correspondingInput = inputsToExtractGasUsed.find(
2315
- (x) => isRequestInputResourceFromOwner(x, Address.fromString(String(owner)))
2640
+ (x) => isRequestInputResourceFromOwner(x, Address2.fromString(String(owner)))
2316
2641
  );
2317
2642
  if (correspondingInput && "predicateGasUsed" in correspondingInput && bn8(correspondingInput.predicateGasUsed).gt(0)) {
2318
2643
  i.predicateGasUsed = correspondingInput.predicateGasUsed;
2319
2644
  }
2320
2645
  });
2321
2646
  }
2647
+ byteLength() {
2648
+ return this.toTransactionBytes().byteLength;
2649
+ }
2322
2650
  };
2323
2651
 
2324
- // src/providers/transaction-request/create-transaction-request.ts
2325
- import { ZeroBytes32 as ZeroBytes326 } from "@fuel-ts/address/configs";
2326
- import { bn as bn10 } from "@fuel-ts/math";
2327
- import { TransactionType as TransactionType3, OutputType as OutputType4 } from "@fuel-ts/transactions";
2328
- import { arrayify as arrayify6, hexlify as hexlify9 } from "@fuel-ts/utils";
2329
-
2330
2652
  // src/providers/transaction-request/hash-transaction.ts
2331
2653
  import { ZeroBytes32 as ZeroBytes325 } from "@fuel-ts/address/configs";
2332
2654
  import { uint64ToBytesBE, sha256 } from "@fuel-ts/hasher";
2333
2655
  import { bn as bn9 } from "@fuel-ts/math";
2334
2656
  import { TransactionType as TransactionType2, InputType as InputType4, OutputType as OutputType3, TransactionCoder as TransactionCoder2 } from "@fuel-ts/transactions";
2335
- import { concat as concat2 } from "@fuel-ts/utils";
2657
+ import { concat as concat3 } from "@fuel-ts/utils";
2336
2658
  import { clone as clone2 } from "ramda";
2337
2659
  function hashTransaction(transactionRequest, chainId) {
2338
2660
  const transaction = transactionRequest.toTransaction();
@@ -2394,15 +2716,85 @@ function hashTransaction(transactionRequest, chainId) {
2394
2716
  transaction.witnessesCount = 0;
2395
2717
  transaction.witnesses = [];
2396
2718
  const chainIdBytes = uint64ToBytesBE(chainId);
2397
- const concatenatedData = concat2([chainIdBytes, new TransactionCoder2().encode(transaction)]);
2719
+ const concatenatedData = concat3([chainIdBytes, new TransactionCoder2().encode(transaction)]);
2398
2720
  return sha256(concatenatedData);
2399
2721
  }
2400
2722
 
2723
+ // src/providers/transaction-request/blob-transaction-request.ts
2724
+ var BlobTransactionRequest = class extends BaseTransactionRequest {
2725
+ static from(obj) {
2726
+ if (obj instanceof this) {
2727
+ return obj;
2728
+ }
2729
+ return new this(obj);
2730
+ }
2731
+ /** Type of the transaction */
2732
+ type = TransactionType.Blob;
2733
+ /** Blob ID */
2734
+ blobId;
2735
+ /** Witness index of contract bytecode to create */
2736
+ witnessIndex;
2737
+ /**
2738
+ * Creates an instance `BlobTransactionRequest`.
2739
+ *
2740
+ * @param blobTransactionRequestLike - The initial values for the instance
2741
+ */
2742
+ constructor({ witnessIndex, blobId, ...rest }) {
2743
+ super(rest);
2744
+ this.blobId = blobId;
2745
+ this.witnessIndex = witnessIndex ?? 0;
2746
+ }
2747
+ /**
2748
+ * Converts the transaction request to a `TransactionBlob`.
2749
+ *
2750
+ * @returns The transaction create object.
2751
+ */
2752
+ toTransaction() {
2753
+ const baseTransaction = this.getBaseTransaction();
2754
+ const { witnessIndex, blobId } = this;
2755
+ return {
2756
+ type: TransactionType.Blob,
2757
+ ...baseTransaction,
2758
+ blobId,
2759
+ witnessIndex
2760
+ };
2761
+ }
2762
+ /**
2763
+ * Gets the Transaction Request by hashing the transaction.
2764
+ *
2765
+ * @param chainId - The chain ID.
2766
+ *
2767
+ * @returns - A hash of the transaction, which is the transaction ID.
2768
+ */
2769
+ getTransactionId(chainId) {
2770
+ return hashTransaction(this, chainId);
2771
+ }
2772
+ /**
2773
+ * Calculates the metadata gas cost for a blob transaction.
2774
+ *
2775
+ * @param gasCosts - gas costs passed from the chain.
2776
+ * @returns metadata gas cost for the blob transaction.
2777
+ */
2778
+ metadataGas(gasCosts) {
2779
+ return calculateMetadataGasForTxBlob({
2780
+ gasCosts,
2781
+ txBytesSize: this.byteSize(),
2782
+ witnessBytesSize: this.witnesses[this.witnessIndex].length
2783
+ });
2784
+ }
2785
+ };
2786
+
2787
+ // src/providers/transaction-request/create-transaction-request.ts
2788
+ import { ZeroBytes32 as ZeroBytes326 } from "@fuel-ts/address/configs";
2789
+ import { bn as bn10 } from "@fuel-ts/math";
2790
+ import { TransactionType as TransactionType3, OutputType as OutputType4 } from "@fuel-ts/transactions";
2791
+ import { arrayify as arrayify7, hexlify as hexlify11 } from "@fuel-ts/utils";
2792
+
2401
2793
  // src/providers/transaction-request/storage-slot.ts
2402
- import { arrayify as arrayify5, hexlify as hexlify8 } from "@fuel-ts/utils";
2794
+ import { arrayify as arrayify6, hexlify as hexlify10 } from "@fuel-ts/utils";
2403
2795
  var getStorageValue = (value) => {
2404
2796
  const v = new Uint8Array(32);
2405
- v.set(arrayify5(value));
2797
+ v.set(arrayify6(value));
2406
2798
  return v;
2407
2799
  };
2408
2800
  var storageSlotify = (storageSlot) => {
@@ -2416,8 +2808,8 @@ var storageSlotify = (storageSlot) => {
2416
2808
  value = storageSlot.value;
2417
2809
  }
2418
2810
  return {
2419
- key: hexlify8(key),
2420
- value: hexlify8(getStorageValue(value))
2811
+ key: hexlify10(key),
2812
+ value: hexlify10(getStorageValue(value))
2421
2813
  };
2422
2814
  };
2423
2815
 
@@ -2445,7 +2837,7 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
2445
2837
  constructor({ bytecodeWitnessIndex, salt, storageSlots, ...rest }) {
2446
2838
  super(rest);
2447
2839
  this.bytecodeWitnessIndex = bytecodeWitnessIndex ?? 0;
2448
- this.salt = hexlify9(salt ?? ZeroBytes326);
2840
+ this.salt = hexlify11(salt ?? ZeroBytes326);
2449
2841
  this.storageSlots = [...storageSlots ?? []];
2450
2842
  }
2451
2843
  /**
@@ -2462,7 +2854,7 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
2462
2854
  ...baseTransaction,
2463
2855
  bytecodeWitnessIndex,
2464
2856
  storageSlotsCount: bn10(storageSlots.length),
2465
- salt: this.salt ? hexlify9(this.salt) : ZeroBytes326,
2857
+ salt: this.salt ? hexlify11(this.salt) : ZeroBytes326,
2466
2858
  storageSlots
2467
2859
  };
2468
2860
  }
@@ -2501,7 +2893,7 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
2501
2893
  }
2502
2894
  metadataGas(gasCosts) {
2503
2895
  return calculateMetadataGasForTxCreate({
2504
- contractBytesSize: bn10(arrayify6(this.witnesses[this.bytecodeWitnessIndex] || "0x").length),
2896
+ contractBytesSize: bn10(arrayify7(this.witnesses[this.bytecodeWitnessIndex] || "0x").length),
2505
2897
  gasCosts,
2506
2898
  stateRootSize: this.storageSlots.length,
2507
2899
  txBytesSize: this.byteSize()
@@ -2515,17 +2907,17 @@ import { addressify as addressify2 } from "@fuel-ts/address";
2515
2907
  import { ZeroBytes32 as ZeroBytes327 } from "@fuel-ts/address/configs";
2516
2908
  import { bn as bn11 } from "@fuel-ts/math";
2517
2909
  import { InputType as InputType5, OutputType as OutputType5, TransactionType as TransactionType4 } from "@fuel-ts/transactions";
2518
- import { arrayify as arrayify8, hexlify as hexlify10 } from "@fuel-ts/utils";
2910
+ import { arrayify as arrayify9, hexlify as hexlify12 } from "@fuel-ts/utils";
2519
2911
 
2520
2912
  // src/providers/transaction-request/scripts.ts
2521
- import { arrayify as arrayify7 } from "@fuel-ts/utils";
2913
+ import { arrayify as arrayify8 } from "@fuel-ts/utils";
2522
2914
  var returnZeroScript = {
2523
2915
  /*
2524
2916
  Opcode::RET(REG_ZERO)
2525
2917
  Opcode::NOOP
2526
2918
  */
2527
2919
  // TODO: Don't use hardcoded scripts: https://github.com/FuelLabs/fuels-ts/issues/281
2528
- bytes: arrayify7("0x24000000"),
2920
+ bytes: arrayify8("0x24000000"),
2529
2921
  encodeScriptData: () => new Uint8Array(0)
2530
2922
  };
2531
2923
  var withdrawScript = {
@@ -2539,7 +2931,7 @@ var withdrawScript = {
2539
2931
  00000000 00000000 [amount value]
2540
2932
  */
2541
2933
  // TODO: Don't use hardcoded scripts: https://github.com/FuelLabs/fuels-ts/issues/281
2542
- bytes: arrayify7("0x5040C0105D44C0064C40001124000000"),
2934
+ bytes: arrayify8("0x5040C0105D44C0064C40001124000000"),
2543
2935
  encodeScriptData: () => new Uint8Array(0)
2544
2936
  };
2545
2937
 
@@ -2568,8 +2960,8 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
2568
2960
  constructor({ script, scriptData, gasLimit, ...rest } = {}) {
2569
2961
  super(rest);
2570
2962
  this.gasLimit = bn11(gasLimit);
2571
- this.script = arrayify8(script ?? returnZeroScript.bytes);
2572
- this.scriptData = arrayify8(scriptData ?? returnZeroScript.encodeScriptData());
2963
+ this.script = arrayify9(script ?? returnZeroScript.bytes);
2964
+ this.scriptData = arrayify9(scriptData ?? returnZeroScript.encodeScriptData());
2573
2965
  this.abis = rest.abis;
2574
2966
  }
2575
2967
  /**
@@ -2578,8 +2970,8 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
2578
2970
  * @returns The transaction script object.
2579
2971
  */
2580
2972
  toTransaction() {
2581
- const script = arrayify8(this.script ?? "0x");
2582
- const scriptData = arrayify8(this.scriptData ?? "0x");
2973
+ const script = arrayify9(this.script ?? "0x");
2974
+ const scriptData = arrayify9(this.scriptData ?? "0x");
2583
2975
  return {
2584
2976
  type: TransactionType4.Script,
2585
2977
  scriptGasLimit: this.gasLimit,
@@ -2587,8 +2979,8 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
2587
2979
  scriptLength: bn11(script.length),
2588
2980
  scriptDataLength: bn11(scriptData.length),
2589
2981
  receiptsRoot: ZeroBytes327,
2590
- script: hexlify10(script),
2591
- scriptData: hexlify10(scriptData)
2982
+ script: hexlify12(script),
2983
+ scriptData: hexlify12(scriptData)
2592
2984
  };
2593
2985
  }
2594
2986
  /**
@@ -2726,10 +3118,10 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
2726
3118
  };
2727
3119
 
2728
3120
  // src/providers/transaction-request/utils.ts
2729
- import { ErrorCode as ErrorCode8, FuelError as FuelError8 } from "@fuel-ts/errors";
3121
+ import { ErrorCode as ErrorCode8, FuelError as FuelError10 } from "@fuel-ts/errors";
2730
3122
  import { TransactionType as TransactionType5 } from "@fuel-ts/transactions";
2731
3123
  var transactionRequestify = (obj) => {
2732
- if (obj instanceof ScriptTransactionRequest || obj instanceof CreateTransactionRequest) {
3124
+ if (obj instanceof ScriptTransactionRequest || obj instanceof CreateTransactionRequest || obj instanceof BlobTransactionRequest) {
2733
3125
  return obj;
2734
3126
  }
2735
3127
  const { type } = obj;
@@ -2740,27 +3132,35 @@ var transactionRequestify = (obj) => {
2740
3132
  case TransactionType5.Create: {
2741
3133
  return CreateTransactionRequest.from(obj);
2742
3134
  }
3135
+ case TransactionType5.Blob: {
3136
+ return BlobTransactionRequest.from(obj);
3137
+ }
2743
3138
  default: {
2744
- throw new FuelError8(ErrorCode8.INVALID_TRANSACTION_TYPE, `Invalid transaction type: ${type}.`);
3139
+ throw new FuelError10(
3140
+ ErrorCode8.UNSUPPORTED_TRANSACTION_TYPE,
3141
+ `Unsupported transaction type: ${type}.`
3142
+ );
2745
3143
  }
2746
3144
  }
2747
3145
  };
3146
+ var isTransactionTypeScript = (request) => request.type === TransactionType5.Script;
3147
+ var isTransactionTypeCreate = (request) => request.type === TransactionType5.Create;
2748
3148
 
2749
3149
  // src/providers/transaction-response/transaction-response.ts
2750
- import { ErrorCode as ErrorCode12, FuelError as FuelError12 } from "@fuel-ts/errors";
3150
+ import { ErrorCode as ErrorCode12, FuelError as FuelError14 } from "@fuel-ts/errors";
2751
3151
  import { bn as bn16 } from "@fuel-ts/math";
2752
3152
  import { TransactionCoder as TransactionCoder4 } from "@fuel-ts/transactions";
2753
- import { arrayify as arrayify10 } from "@fuel-ts/utils";
3153
+ import { arrayify as arrayify11, sleep } from "@fuel-ts/utils";
2754
3154
 
2755
3155
  // src/providers/transaction-summary/assemble-transaction-summary.ts
2756
3156
  import { bn as bn15 } from "@fuel-ts/math";
2757
3157
  import { PolicyType as PolicyType3 } from "@fuel-ts/transactions";
2758
- import { DateTime, hexlify as hexlify11 } from "@fuel-ts/utils";
3158
+ import { DateTime, hexlify as hexlify13 } from "@fuel-ts/utils";
2759
3159
 
2760
3160
  // src/providers/transaction-summary/calculate-tx-fee-for-summary.ts
2761
3161
  import { bn as bn12 } from "@fuel-ts/math";
2762
3162
  import { PolicyType as PolicyType2, TransactionCoder as TransactionCoder3, TransactionType as TransactionType6 } from "@fuel-ts/transactions";
2763
- import { arrayify as arrayify9 } from "@fuel-ts/utils";
3163
+ import { arrayify as arrayify10 } from "@fuel-ts/utils";
2764
3164
  var calculateTXFeeForSummary = (params) => {
2765
3165
  const {
2766
3166
  gasPrice,
@@ -2774,7 +3174,7 @@ var calculateTXFeeForSummary = (params) => {
2774
3174
  }
2775
3175
  const gasPerByte = bn12(feeParams.gasPerByte);
2776
3176
  const gasPriceFactor = bn12(feeParams.gasPriceFactor);
2777
- const transactionBytes = arrayify9(rawPayload);
3177
+ const transactionBytes = arrayify10(rawPayload);
2778
3178
  const [transaction] = new TransactionCoder3().decode(transactionBytes, 0);
2779
3179
  const { type, witnesses, inputs, policies } = transaction;
2780
3180
  let metadataGas = bn12(0);
@@ -2784,7 +3184,7 @@ var calculateTXFeeForSummary = (params) => {
2784
3184
  }
2785
3185
  if (type === TransactionType6.Create) {
2786
3186
  const { bytecodeWitnessIndex, storageSlots } = transaction;
2787
- const contractBytesSize = bn12(arrayify9(witnesses[bytecodeWitnessIndex].data).length);
3187
+ const contractBytesSize = bn12(arrayify10(witnesses[bytecodeWitnessIndex].data).length);
2788
3188
  metadataGas = calculateMetadataGasForTxCreate({
2789
3189
  contractBytesSize,
2790
3190
  gasCosts,
@@ -2829,7 +3229,7 @@ var calculateTXFeeForSummary = (params) => {
2829
3229
 
2830
3230
  // src/providers/transaction-summary/operations.ts
2831
3231
  import { ZeroBytes32 as ZeroBytes328 } from "@fuel-ts/address/configs";
2832
- import { ErrorCode as ErrorCode10, FuelError as FuelError10 } from "@fuel-ts/errors";
3232
+ import { ErrorCode as ErrorCode10, FuelError as FuelError12 } from "@fuel-ts/errors";
2833
3233
  import { bn as bn13 } from "@fuel-ts/math";
2834
3234
  import { ReceiptType as ReceiptType4, TransactionType as TransactionType7 } from "@fuel-ts/transactions";
2835
3235
 
@@ -2867,7 +3267,7 @@ var getFunctionCall = ({ abi, receipt }) => {
2867
3267
  };
2868
3268
 
2869
3269
  // src/providers/transaction-summary/input.ts
2870
- import { ErrorCode as ErrorCode9, FuelError as FuelError9 } from "@fuel-ts/errors";
3270
+ import { ErrorCode as ErrorCode9, FuelError as FuelError11 } from "@fuel-ts/errors";
2871
3271
  import { InputType as InputType6 } from "@fuel-ts/transactions";
2872
3272
  function getInputsByTypes(inputs, types) {
2873
3273
  return inputs.filter((i) => types.includes(i.type));
@@ -2887,14 +3287,22 @@ function getInputsCoinAndMessage(inputs) {
2887
3287
  function getInputsContract(inputs) {
2888
3288
  return getInputsByType(inputs, InputType6.Contract);
2889
3289
  }
2890
- function getInputFromAssetId(inputs, assetId) {
3290
+ function findCoinInput(inputs, assetId) {
2891
3291
  const coinInputs = getInputsCoin(inputs);
2892
- const messageInputs = getInputsMessage(inputs);
2893
- const coinInput = coinInputs.find((i) => i.assetId === assetId);
2894
- const messageInput = messageInputs.find(
2895
- (_) => assetId === "0x0000000000000000000000000000000000000000000000000000000000000000"
2896
- );
2897
- return coinInput || messageInput;
3292
+ return coinInputs.find((i) => i.assetId === assetId);
3293
+ }
3294
+ function findMessageInput(inputs) {
3295
+ return getInputsMessage(inputs)?.[0];
3296
+ }
3297
+ function getInputFromAssetId(inputs, assetId, isBaseAsset = false) {
3298
+ const coinInput = findCoinInput(inputs, assetId);
3299
+ if (coinInput) {
3300
+ return coinInput;
3301
+ }
3302
+ if (isBaseAsset) {
3303
+ return findMessageInput(inputs);
3304
+ }
3305
+ return void 0;
2898
3306
  }
2899
3307
  function getInputContractFromIndex(inputs, inputIndex) {
2900
3308
  if (inputIndex == null) {
@@ -2905,7 +3313,7 @@ function getInputContractFromIndex(inputs, inputIndex) {
2905
3313
  return void 0;
2906
3314
  }
2907
3315
  if (contractInput.type !== InputType6.Contract) {
2908
- throw new FuelError9(
3316
+ throw new FuelError11(
2909
3317
  ErrorCode9.INVALID_TRANSACTION_INPUT,
2910
3318
  `Contract input should be of type 'contract'.`
2911
3319
  );
@@ -2952,10 +3360,12 @@ function getTransactionTypeName(transactionType) {
2952
3360
  return "Create" /* Create */;
2953
3361
  case TransactionType7.Script:
2954
3362
  return "Script" /* Script */;
3363
+ case TransactionType7.Blob:
3364
+ return "Blob" /* Blob */;
2955
3365
  default:
2956
- throw new FuelError10(
2957
- ErrorCode10.INVALID_TRANSACTION_TYPE,
2958
- `Invalid transaction type: ${transactionType}.`
3366
+ throw new FuelError12(
3367
+ ErrorCode10.UNSUPPORTED_TRANSACTION_TYPE,
3368
+ `Unsupported transaction type: ${transactionType}.`
2959
3369
  );
2960
3370
  }
2961
3371
  }
@@ -2978,47 +3388,60 @@ function isTypeUpgrade(transactionType) {
2978
3388
  function isTypeUpload(transactionType) {
2979
3389
  return isType(transactionType, "Upload" /* Upload */);
2980
3390
  }
3391
+ function isTypeBlob(transactionType) {
3392
+ return isType(transactionType, "Blob" /* Blob */);
3393
+ }
2981
3394
  function getReceiptsCall(receipts) {
2982
3395
  return getReceiptsByType(receipts, ReceiptType4.Call);
2983
3396
  }
2984
3397
  function getReceiptsMessageOut(receipts) {
2985
3398
  return getReceiptsByType(receipts, ReceiptType4.MessageOut);
2986
3399
  }
2987
- var mergeAssets = (op1, op2) => {
3400
+ function mergeAssets(op1, op2) {
2988
3401
  const assets1 = op1.assetsSent || [];
2989
3402
  const assets2 = op2.assetsSent || [];
2990
- const filteredAssets = assets2.filter(
2991
- (asset2) => !assets1.some((asset1) => asset1.assetId === asset2.assetId)
2992
- );
2993
- const mergedAssets = assets1.map((asset1) => {
2994
- const matchingAsset = assets2.find((asset2) => asset2.assetId === asset1.assetId);
2995
- if (!matchingAsset) {
2996
- return asset1;
3403
+ const assetMap = /* @__PURE__ */ new Map();
3404
+ assets1.forEach((asset) => {
3405
+ assetMap.set(asset.assetId, { ...asset });
3406
+ });
3407
+ assets2.forEach((asset) => {
3408
+ const existingAsset = assetMap.get(asset.assetId);
3409
+ if (existingAsset) {
3410
+ existingAsset.amount = bn13(existingAsset.amount).add(asset.amount);
3411
+ } else {
3412
+ assetMap.set(asset.assetId, { ...asset });
2997
3413
  }
2998
- const mergedAmount = bn13(asset1.amount).add(matchingAsset.amount);
2999
- return { ...asset1, amount: mergedAmount };
3000
3414
  });
3001
- return mergedAssets.concat(filteredAssets);
3002
- };
3415
+ return Array.from(assetMap.values());
3416
+ }
3003
3417
  function isSameOperation(a, b) {
3004
3418
  return a.name === b.name && a.from?.address === b.from?.address && a.to?.address === b.to?.address && a.from?.type === b.from?.type && a.to?.type === b.to?.type;
3005
3419
  }
3420
+ function mergeAssetsSent(existing, toAdd) {
3421
+ if (!toAdd.assetsSent?.length) {
3422
+ return existing.assetsSent;
3423
+ }
3424
+ return existing.assetsSent?.length ? mergeAssets(existing, toAdd) : toAdd.assetsSent;
3425
+ }
3426
+ function mergeCalls(existing, toAdd) {
3427
+ if (!toAdd.calls?.length) {
3428
+ return existing.calls;
3429
+ }
3430
+ return [...existing.calls || [], ...toAdd.calls];
3431
+ }
3432
+ function mergeOperations(existing, toAdd) {
3433
+ return {
3434
+ ...existing,
3435
+ assetsSent: mergeAssetsSent(existing, toAdd),
3436
+ calls: mergeCalls(existing, toAdd)
3437
+ };
3438
+ }
3006
3439
  function addOperation(operations, toAdd) {
3007
- const allOperations = [...operations];
3008
- const index = allOperations.findIndex((op) => isSameOperation(op, toAdd));
3009
- if (allOperations[index]) {
3010
- const existentOperation = { ...allOperations[index] };
3011
- if (toAdd.assetsSent?.length) {
3012
- existentOperation.assetsSent = existentOperation.assetsSent?.length ? mergeAssets(existentOperation, toAdd) : toAdd.assetsSent;
3013
- }
3014
- if (toAdd.calls?.length) {
3015
- existentOperation.calls = [...existentOperation.calls || [], ...toAdd.calls];
3016
- }
3017
- allOperations[index] = existentOperation;
3018
- } else {
3019
- allOperations.push(toAdd);
3440
+ const existingIndex = operations.findIndex((op) => isSameOperation(op, toAdd));
3441
+ if (existingIndex === -1) {
3442
+ return [...operations, toAdd];
3020
3443
  }
3021
- return allOperations;
3444
+ return operations.map((op, index) => index === existingIndex ? mergeOperations(op, toAdd) : op);
3022
3445
  }
3023
3446
  function getWithdrawFromFuelOperations({
3024
3447
  inputs,
@@ -3028,7 +3451,7 @@ function getWithdrawFromFuelOperations({
3028
3451
  const messageOutReceipts = getReceiptsMessageOut(receipts);
3029
3452
  const withdrawFromFuelOperations = messageOutReceipts.reduce(
3030
3453
  (prevWithdrawFromFuelOps, receipt) => {
3031
- const input = getInputFromAssetId(inputs, baseAssetId);
3454
+ const input = getInputFromAssetId(inputs, baseAssetId, true);
3032
3455
  if (input) {
3033
3456
  const inputAddress = getInputAccountAddress(input);
3034
3457
  const newWithdrawFromFuelOps = addOperation(prevWithdrawFromFuelOps, {
@@ -3057,65 +3480,80 @@ function getWithdrawFromFuelOperations({
3057
3480
  );
3058
3481
  return withdrawFromFuelOperations;
3059
3482
  }
3483
+ function getContractCalls(contractInput, abiMap, receipt, rawPayload, maxInputs) {
3484
+ const abi = abiMap?.[contractInput.contractID];
3485
+ if (!abi) {
3486
+ return [];
3487
+ }
3488
+ return [
3489
+ getFunctionCall({
3490
+ abi,
3491
+ receipt,
3492
+ rawPayload,
3493
+ maxInputs
3494
+ })
3495
+ ];
3496
+ }
3497
+ function getAssetsSent(receipt) {
3498
+ return receipt.amount?.isZero() ? void 0 : [
3499
+ {
3500
+ amount: receipt.amount,
3501
+ assetId: receipt.assetId
3502
+ }
3503
+ ];
3504
+ }
3505
+ function processCallReceipt(receipt, contractInput, inputs, abiMap, rawPayload, maxInputs, baseAssetId) {
3506
+ const assetId = receipt.assetId === ZeroBytes328 ? baseAssetId : receipt.assetId;
3507
+ const input = getInputFromAssetId(inputs, assetId, assetId === baseAssetId);
3508
+ if (!input) {
3509
+ return [];
3510
+ }
3511
+ const inputAddress = getInputAccountAddress(input);
3512
+ const calls = getContractCalls(contractInput, abiMap, receipt, rawPayload, maxInputs);
3513
+ return [
3514
+ {
3515
+ name: "Contract call" /* contractCall */,
3516
+ from: {
3517
+ type: 1 /* account */,
3518
+ address: inputAddress
3519
+ },
3520
+ to: {
3521
+ type: 0 /* contract */,
3522
+ address: receipt.to
3523
+ },
3524
+ assetsSent: getAssetsSent(receipt),
3525
+ calls
3526
+ }
3527
+ ];
3528
+ }
3060
3529
  function getContractCallOperations({
3061
3530
  inputs,
3062
3531
  outputs,
3063
3532
  receipts,
3064
3533
  abiMap,
3065
3534
  rawPayload,
3066
- maxInputs
3535
+ maxInputs,
3536
+ baseAssetId
3067
3537
  }) {
3068
3538
  const contractCallReceipts = getReceiptsCall(receipts);
3069
3539
  const contractOutputs = getOutputsContract(outputs);
3070
- const contractCallOperations = contractOutputs.reduce((prevOutputCallOps, output) => {
3540
+ return contractOutputs.flatMap((output) => {
3071
3541
  const contractInput = getInputContractFromIndex(inputs, output.inputIndex);
3072
- if (contractInput) {
3073
- const newCallOps = contractCallReceipts.reduce((prevContractCallOps, receipt) => {
3074
- if (receipt.to === contractInput.contractID) {
3075
- const input = getInputFromAssetId(inputs, receipt.assetId);
3076
- if (input) {
3077
- const inputAddress = getInputAccountAddress(input);
3078
- const calls = [];
3079
- const abi = abiMap?.[contractInput.contractID];
3080
- if (abi) {
3081
- calls.push(
3082
- getFunctionCall({
3083
- abi,
3084
- receipt,
3085
- rawPayload,
3086
- maxInputs
3087
- })
3088
- );
3089
- }
3090
- const newContractCallOps = addOperation(prevContractCallOps, {
3091
- name: "Contract call" /* contractCall */,
3092
- from: {
3093
- type: 1 /* account */,
3094
- address: inputAddress
3095
- },
3096
- to: {
3097
- type: 0 /* contract */,
3098
- address: receipt.to
3099
- },
3100
- // if no amount is forwarded to the contract, skip showing assetsSent
3101
- assetsSent: receipt.amount?.isZero() ? void 0 : [
3102
- {
3103
- amount: receipt.amount,
3104
- assetId: receipt.assetId
3105
- }
3106
- ],
3107
- calls
3108
- });
3109
- return newContractCallOps;
3110
- }
3111
- }
3112
- return prevContractCallOps;
3113
- }, prevOutputCallOps);
3114
- return newCallOps;
3542
+ if (!contractInput) {
3543
+ return [];
3115
3544
  }
3116
- return prevOutputCallOps;
3117
- }, []);
3118
- return contractCallOperations;
3545
+ return contractCallReceipts.filter((receipt) => receipt.to === contractInput.contractID).flatMap(
3546
+ (receipt) => processCallReceipt(
3547
+ receipt,
3548
+ contractInput,
3549
+ inputs,
3550
+ abiMap,
3551
+ rawPayload,
3552
+ maxInputs,
3553
+ baseAssetId
3554
+ )
3555
+ );
3556
+ });
3119
3557
  }
3120
3558
  function extractTransferOperationFromReceipt(receipt, contractInputs, changeOutputs) {
3121
3559
  const { to: toAddress, assetId, amount } = receipt;
@@ -3259,7 +3697,8 @@ function getOperations({
3259
3697
  receipts,
3260
3698
  abiMap,
3261
3699
  rawPayload,
3262
- maxInputs
3700
+ maxInputs,
3701
+ baseAssetId
3263
3702
  }),
3264
3703
  ...getWithdrawFromFuelOperations({ inputs, receipts, baseAssetId })
3265
3704
  ];
@@ -3318,7 +3757,7 @@ var extractBurnedAssetsFromReceipts = (receipts) => {
3318
3757
  };
3319
3758
 
3320
3759
  // src/providers/transaction-summary/status.ts
3321
- import { ErrorCode as ErrorCode11, FuelError as FuelError11 } from "@fuel-ts/errors";
3760
+ import { ErrorCode as ErrorCode11, FuelError as FuelError13 } from "@fuel-ts/errors";
3322
3761
  import { bn as bn14 } from "@fuel-ts/math";
3323
3762
  var getTransactionStatusName = (gqlStatus) => {
3324
3763
  switch (gqlStatus) {
@@ -3331,7 +3770,7 @@ var getTransactionStatusName = (gqlStatus) => {
3331
3770
  case "SqueezedOutStatus":
3332
3771
  return "squeezedout" /* squeezedout */;
3333
3772
  default:
3334
- throw new FuelError11(
3773
+ throw new FuelError13(
3335
3774
  ErrorCode11.INVALID_TRANSACTION_STATUS,
3336
3775
  `Invalid transaction status: ${gqlStatus}.`
3337
3776
  );
@@ -3401,7 +3840,7 @@ function assembleTransactionSummary(params) {
3401
3840
  baseAssetId
3402
3841
  } = params;
3403
3842
  const gasUsed = getGasUsedFromReceipts(receipts);
3404
- const rawPayload = hexlify11(transactionBytes);
3843
+ const rawPayload = hexlify13(transactionBytes);
3405
3844
  const operations = getOperations({
3406
3845
  transactionType: transaction.type,
3407
3846
  inputs: transaction.inputs || [],
@@ -3453,6 +3892,7 @@ function assembleTransactionSummary(params) {
3453
3892
  isTypeScript: isTypeScript(transaction.type),
3454
3893
  isTypeUpgrade: isTypeUpgrade(transaction.type),
3455
3894
  isTypeUpload: isTypeUpload(transaction.type),
3895
+ isTypeBlob: isTypeBlob(transaction.type),
3456
3896
  isStatusFailure,
3457
3897
  isStatusSuccess,
3458
3898
  isStatusPending,
@@ -3488,6 +3928,8 @@ var TransactionResponse = class {
3488
3928
  /** The graphql Transaction with receipts object. */
3489
3929
  gqlTransaction;
3490
3930
  abis;
3931
+ /** The expected status from the getTransactionWithReceipts response */
3932
+ expectedStatus;
3491
3933
  /**
3492
3934
  * Constructor for `TransactionResponse`.
3493
3935
  *
@@ -3527,11 +3969,16 @@ var TransactionResponse = class {
3527
3969
  });
3528
3970
  for await (const { statusChange } of subscription) {
3529
3971
  if (statusChange) {
3972
+ this.expectedStatus = statusChange.type;
3530
3973
  break;
3531
3974
  }
3532
3975
  }
3533
3976
  return this.fetch();
3534
3977
  }
3978
+ if (this.expectedStatus && response.transaction.status?.type !== this.expectedStatus) {
3979
+ await sleep(100);
3980
+ return this.fetch();
3981
+ }
3535
3982
  this.gqlTransaction = response.transaction;
3536
3983
  return response.transaction;
3537
3984
  }
@@ -3543,7 +3990,7 @@ var TransactionResponse = class {
3543
3990
  */
3544
3991
  decodeTransaction(transactionWithReceipts) {
3545
3992
  return new TransactionCoder4().decode(
3546
- arrayify10(transactionWithReceipts.rawPayload),
3993
+ arrayify11(transactionWithReceipts.rawPayload),
3547
3994
  0
3548
3995
  )?.[0];
3549
3996
  }
@@ -3575,7 +4022,7 @@ var TransactionResponse = class {
3575
4022
  id: this.id,
3576
4023
  receipts,
3577
4024
  transaction: decodedTransaction,
3578
- transactionBytes: arrayify10(transaction.rawPayload),
4025
+ transactionBytes: arrayify11(transaction.rawPayload),
3579
4026
  gqlTransactionStatus: transaction.status,
3580
4027
  gasPerByte,
3581
4028
  gasPriceFactor,
@@ -3598,12 +4045,14 @@ var TransactionResponse = class {
3598
4045
  });
3599
4046
  for await (const { statusChange } of subscription) {
3600
4047
  if (statusChange.type === "SqueezedOutStatus") {
3601
- throw new FuelError12(
4048
+ this.unsetResourceCache();
4049
+ throw new FuelError14(
3602
4050
  ErrorCode12.TRANSACTION_SQUEEZED_OUT,
3603
4051
  `Transaction Squeezed Out with reason: ${statusChange.reason}`
3604
4052
  );
3605
4053
  }
3606
4054
  if (statusChange.type !== "SubmittedStatus") {
4055
+ this.expectedStatus = statusChange.type;
3607
4056
  break;
3608
4057
  }
3609
4058
  }
@@ -3638,6 +4087,7 @@ var TransactionResponse = class {
3638
4087
  }
3639
4088
  const { gqlTransaction, receipts } = transactionResult;
3640
4089
  if (gqlTransaction.status?.type === "FailureStatus") {
4090
+ this.unsetResourceCache();
3641
4091
  const { reason } = gqlTransaction.status;
3642
4092
  throw extractTxError({
3643
4093
  receipts,
@@ -3664,10 +4114,13 @@ var TransactionResponse = class {
3664
4114
  async wait(contractsAbiMap) {
3665
4115
  return this.waitForResult(contractsAbiMap);
3666
4116
  }
4117
+ unsetResourceCache() {
4118
+ this.provider.cache?.unset(this.id);
4119
+ }
3667
4120
  };
3668
4121
 
3669
4122
  // src/providers/utils/auto-retry-fetch.ts
3670
- import { sleep } from "@fuel-ts/utils";
4123
+ import { sleep as sleep2 } from "@fuel-ts/utils";
3671
4124
  function getWaitDelay(options, retryAttemptNum) {
3672
4125
  const duration = options.baseDelay ?? 150;
3673
4126
  switch (options.backoff) {
@@ -3697,30 +4150,17 @@ function autoRetryFetch(fetchFn, options, retryAttemptNum = 0) {
3697
4150
  throw error;
3698
4151
  }
3699
4152
  const delay = getWaitDelay(options, retryNum);
3700
- await sleep(delay);
4153
+ await sleep2(delay);
3701
4154
  return autoRetryFetch(fetchFn, options, retryNum)(...args);
3702
4155
  }
3703
4156
  };
3704
4157
  }
3705
4158
 
3706
- // src/providers/utils/merge-quantities.ts
3707
- var mergeQuantities = (...coinQuantities) => {
3708
- const resultMap = {};
3709
- function addToMap({ amount, assetId }) {
3710
- if (resultMap[assetId]) {
3711
- resultMap[assetId] = resultMap[assetId].add(amount);
3712
- } else {
3713
- resultMap[assetId] = amount;
3714
- }
3715
- }
3716
- coinQuantities.forEach((arr) => arr.forEach(addToMap));
3717
- return Object.entries(resultMap).map(([assetId, amount]) => ({ assetId, amount }));
3718
- };
3719
-
3720
4159
  // src/providers/provider.ts
3721
4160
  var MAX_RETRIES = 10;
3722
4161
  var RESOURCES_PAGE_SIZE_LIMIT = 512;
3723
4162
  var BLOCKS_PAGE_SIZE_LIMIT = 5;
4163
+ var DEFAULT_RESOURCE_CACHE_TTL = 2e4;
3724
4164
  var processGqlChain = (chain) => {
3725
4165
  const { name, daHeight, consensusParameters, latestBlock } = chain;
3726
4166
  const {
@@ -3803,14 +4243,23 @@ var _Provider = class {
3803
4243
  __publicField(this, "cache");
3804
4244
  __publicField(this, "options", {
3805
4245
  timeout: void 0,
3806
- cacheUtxo: void 0,
4246
+ resourceCacheTTL: void 0,
3807
4247
  fetch: void 0,
3808
4248
  retryOptions: void 0
3809
4249
  });
3810
4250
  this.options = { ...this.options, ...options };
3811
4251
  this.url = url;
3812
4252
  this.operations = this.createOperations();
3813
- this.cache = options.cacheUtxo ? new MemoryCache(options.cacheUtxo) : void 0;
4253
+ const { resourceCacheTTL } = this.options;
4254
+ if (isDefined2(resourceCacheTTL)) {
4255
+ if (resourceCacheTTL !== -1) {
4256
+ this.cache = new ResourceCache(resourceCacheTTL);
4257
+ } else {
4258
+ this.cache = void 0;
4259
+ }
4260
+ } else {
4261
+ this.cache = new ResourceCache(DEFAULT_RESOURCE_CACHE_TTL);
4262
+ }
3814
4263
  }
3815
4264
  /** @hidden */
3816
4265
  static clearChainAndNodeCaches() {
@@ -3854,7 +4303,7 @@ var _Provider = class {
3854
4303
  getChain() {
3855
4304
  const chain = _Provider.chainInfoCache[this.url];
3856
4305
  if (!chain) {
3857
- throw new FuelError13(
4306
+ throw new FuelError15(
3858
4307
  ErrorCode13.CHAIN_INFO_CACHE_EMPTY,
3859
4308
  "Chain info cache is empty. Make sure you have called `Provider.create` to initialize the provider."
3860
4309
  );
@@ -3869,7 +4318,7 @@ var _Provider = class {
3869
4318
  getNode() {
3870
4319
  const node = _Provider.nodeInfoCache[this.url];
3871
4320
  if (!node) {
3872
- throw new FuelError13(
4321
+ throw new FuelError15(
3873
4322
  ErrorCode13.NODE_INFO_CACHE_EMPTY,
3874
4323
  "Node info cache is empty. Make sure you have called `Provider.create` to initialize the provider."
3875
4324
  );
@@ -3948,8 +4397,8 @@ Supported fuel-core version: ${supportedVersion}.`
3948
4397
  if ("response" in response) {
3949
4398
  const graphQlResponse = response.response;
3950
4399
  if (Array.isArray(graphQlResponse?.errors)) {
3951
- throw new FuelError13(
3952
- FuelError13.CODES.INVALID_REQUEST,
4400
+ throw new FuelError15(
4401
+ FuelError15.CODES.INVALID_REQUEST,
3953
4402
  graphQlResponse.errors.map((err) => err.message).join("\n\n")
3954
4403
  );
3955
4404
  }
@@ -4041,6 +4490,21 @@ Supported fuel-core version: ${supportedVersion}.`
4041
4490
  } = this.getChain();
4042
4491
  return baseAssetId;
4043
4492
  }
4493
+ validateTransaction(tx, consensusParameters) {
4494
+ const { maxOutputs, maxInputs } = consensusParameters.txParameters;
4495
+ if (bn17(tx.inputs.length).gt(maxInputs)) {
4496
+ throw new FuelError15(
4497
+ ErrorCode13.MAX_INPUTS_EXCEEDED,
4498
+ "The transaction exceeds the maximum allowed number of inputs."
4499
+ );
4500
+ }
4501
+ if (bn17(tx.outputs.length).gt(maxOutputs)) {
4502
+ throw new FuelError15(
4503
+ ErrorCode13.MAX_OUTPUTS_EXCEEDED,
4504
+ "The transaction exceeds the maximum allowed number of outputs."
4505
+ );
4506
+ }
4507
+ }
4044
4508
  /**
4045
4509
  * Submits a transaction to the chain to be executed.
4046
4510
  *
@@ -4052,38 +4516,22 @@ Supported fuel-core version: ${supportedVersion}.`
4052
4516
  * @returns A promise that resolves to the transaction response object.
4053
4517
  */
4054
4518
  // #region Provider-sendTransaction
4055
- async sendTransaction(transactionRequestLike, { estimateTxDependencies = true, awaitExecution = false } = {}) {
4519
+ async sendTransaction(transactionRequestLike, { estimateTxDependencies = true } = {}) {
4056
4520
  const transactionRequest = transactionRequestify(transactionRequestLike);
4057
- __privateMethod(this, _cacheInputs, cacheInputs_fn).call(this, transactionRequest.inputs);
4058
4521
  if (estimateTxDependencies) {
4059
4522
  await this.estimateTxDependencies(transactionRequest);
4060
4523
  }
4061
- const encodedTransaction = hexlify12(transactionRequest.toTransactionBytes());
4524
+ const { consensusParameters } = this.getChain();
4525
+ this.validateTransaction(transactionRequest, consensusParameters);
4526
+ const encodedTransaction = hexlify14(transactionRequest.toTransactionBytes());
4062
4527
  let abis;
4063
- if (transactionRequest.type === TransactionType8.Script) {
4528
+ if (isTransactionTypeScript(transactionRequest)) {
4064
4529
  abis = transactionRequest.abis;
4065
4530
  }
4066
- if (awaitExecution) {
4067
- const subscription = this.operations.submitAndAwait({ encodedTransaction });
4068
- for await (const { submitAndAwait } of subscription) {
4069
- if (submitAndAwait.type === "SqueezedOutStatus") {
4070
- throw new FuelError13(
4071
- ErrorCode13.TRANSACTION_SQUEEZED_OUT,
4072
- `Transaction Squeezed Out with reason: ${submitAndAwait.reason}`
4073
- );
4074
- }
4075
- if (submitAndAwait.type !== "SubmittedStatus") {
4076
- break;
4077
- }
4078
- }
4079
- const transactionId2 = transactionRequest.getTransactionId(this.getChainId());
4080
- const response = new TransactionResponse(transactionId2, this, abis);
4081
- await response.fetch();
4082
- return response;
4083
- }
4084
4531
  const {
4085
4532
  submit: { id: transactionId }
4086
4533
  } = await this.operations.submit({ encodedTransaction });
4534
+ __privateMethod(this, _cacheInputs, cacheInputs_fn).call(this, transactionRequest.inputs, transactionId);
4087
4535
  return new TransactionResponse(transactionId, this, abis);
4088
4536
  }
4089
4537
  /**
@@ -4101,7 +4549,7 @@ Supported fuel-core version: ${supportedVersion}.`
4101
4549
  if (estimateTxDependencies) {
4102
4550
  return this.estimateTxDependencies(transactionRequest);
4103
4551
  }
4104
- const encodedTransaction = hexlify12(transactionRequest.toTransactionBytes());
4552
+ const encodedTransaction = hexlify14(transactionRequest.toTransactionBytes());
4105
4553
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
4106
4554
  encodedTransactions: encodedTransaction,
4107
4555
  utxoValidation: utxoValidation || false
@@ -4121,13 +4569,13 @@ Supported fuel-core version: ${supportedVersion}.`
4121
4569
  async estimatePredicates(transactionRequest) {
4122
4570
  const shouldEstimatePredicates = Boolean(
4123
4571
  transactionRequest.inputs.find(
4124
- (input) => "predicate" in input && input.predicate && !equalBytes(arrayify11(input.predicate), arrayify11("0x")) && new BN(input.predicateGasUsed).isZero()
4572
+ (input) => "predicate" in input && input.predicate && !equalBytes(arrayify12(input.predicate), arrayify12("0x")) && new BN(input.predicateGasUsed).isZero()
4125
4573
  )
4126
4574
  );
4127
4575
  if (!shouldEstimatePredicates) {
4128
4576
  return transactionRequest;
4129
4577
  }
4130
- const encodedTransaction = hexlify12(transactionRequest.toTransactionBytes());
4578
+ const encodedTransaction = hexlify14(transactionRequest.toTransactionBytes());
4131
4579
  const response = await this.operations.estimatePredicates({
4132
4580
  encodedTransaction
4133
4581
  });
@@ -4153,7 +4601,7 @@ Supported fuel-core version: ${supportedVersion}.`
4153
4601
  * @returns A promise that resolves to the estimate transaction dependencies.
4154
4602
  */
4155
4603
  async estimateTxDependencies(transactionRequest) {
4156
- if (transactionRequest.type === TransactionType8.Create) {
4604
+ if (isTransactionTypeCreate(transactionRequest)) {
4157
4605
  return {
4158
4606
  receipts: [],
4159
4607
  outputVariables: 0,
@@ -4168,18 +4616,18 @@ Supported fuel-core version: ${supportedVersion}.`
4168
4616
  const {
4169
4617
  dryRun: [{ receipts: rawReceipts, status }]
4170
4618
  } = await this.operations.dryRun({
4171
- encodedTransactions: [hexlify12(transactionRequest.toTransactionBytes())],
4619
+ encodedTransactions: [hexlify14(transactionRequest.toTransactionBytes())],
4172
4620
  utxoValidation: false
4173
4621
  });
4174
4622
  receipts = rawReceipts.map(processGqlReceipt);
4175
4623
  dryRunStatus = status;
4176
4624
  const { missingOutputVariables, missingOutputContractIds } = getReceiptsWithMissingData(receipts);
4177
4625
  const hasMissingOutputs = missingOutputVariables.length !== 0 || missingOutputContractIds.length !== 0;
4178
- if (hasMissingOutputs) {
4626
+ if (hasMissingOutputs && isTransactionTypeScript(transactionRequest)) {
4179
4627
  outputVariables += missingOutputVariables.length;
4180
4628
  transactionRequest.addVariableOutputs(missingOutputVariables.length);
4181
4629
  missingOutputContractIds.forEach(({ contractId }) => {
4182
- transactionRequest.addContractInputAndOutput(Address2.fromString(contractId));
4630
+ transactionRequest.addContractInputAndOutput(Address3.fromString(contractId));
4183
4631
  missingContractIds.push(contractId);
4184
4632
  });
4185
4633
  const { maxFee } = await this.estimateTxGasAndFee({
@@ -4217,8 +4665,8 @@ Supported fuel-core version: ${supportedVersion}.`
4217
4665
  const allRequests = clone3(transactionRequests);
4218
4666
  const serializedTransactionsMap = /* @__PURE__ */ new Map();
4219
4667
  allRequests.forEach((req, index) => {
4220
- if (req.type === TransactionType8.Script) {
4221
- serializedTransactionsMap.set(index, hexlify12(req.toTransactionBytes()));
4668
+ if (isTransactionTypeScript(req)) {
4669
+ serializedTransactionsMap.set(index, hexlify14(req.toTransactionBytes()));
4222
4670
  }
4223
4671
  });
4224
4672
  let transactionsToProcess = Array.from(serializedTransactionsMap.keys());
@@ -4243,18 +4691,18 @@ Supported fuel-core version: ${supportedVersion}.`
4243
4691
  );
4244
4692
  const hasMissingOutputs = missingOutputVariables.length > 0 || missingOutputContractIds.length > 0;
4245
4693
  const request = allRequests[requestIdx];
4246
- if (hasMissingOutputs && request?.type === TransactionType8.Script) {
4694
+ if (hasMissingOutputs && isTransactionTypeScript(request)) {
4247
4695
  result.outputVariables += missingOutputVariables.length;
4248
4696
  request.addVariableOutputs(missingOutputVariables.length);
4249
4697
  missingOutputContractIds.forEach(({ contractId }) => {
4250
- request.addContractInputAndOutput(Address2.fromString(contractId));
4698
+ request.addContractInputAndOutput(Address3.fromString(contractId));
4251
4699
  result.missingContractIds.push(contractId);
4252
4700
  });
4253
4701
  const { maxFee } = await this.estimateTxGasAndFee({
4254
4702
  transactionRequest: request
4255
4703
  });
4256
4704
  request.maxFee = maxFee;
4257
- serializedTransactionsMap.set(requestIdx, hexlify12(request.toTransactionBytes()));
4705
+ serializedTransactionsMap.set(requestIdx, hexlify14(request.toTransactionBytes()));
4258
4706
  nextRoundTransactions.push(requestIdx);
4259
4707
  }
4260
4708
  }
@@ -4275,7 +4723,7 @@ Supported fuel-core version: ${supportedVersion}.`
4275
4723
  if (estimateTxDependencies) {
4276
4724
  return this.estimateMultipleTxDependencies(transactionRequests);
4277
4725
  }
4278
- const encodedTransactions = transactionRequests.map((tx) => hexlify12(tx.toTransactionBytes()));
4726
+ const encodedTransactions = transactionRequests.map((tx) => hexlify14(tx.toTransactionBytes()));
4279
4727
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
4280
4728
  encodedTransactions,
4281
4729
  utxoValidation: utxoValidation || false
@@ -4307,7 +4755,7 @@ Supported fuel-core version: ${supportedVersion}.`
4307
4755
  tip: transactionRequest.tip
4308
4756
  }).add(1);
4309
4757
  let gasLimit = bn17(0);
4310
- if (transactionRequest.type === TransactionType8.Script) {
4758
+ if (isTransactionTypeScript(transactionRequest)) {
4311
4759
  gasLimit = transactionRequest.gasLimit;
4312
4760
  if (transactionRequest.gasLimit.eq(0)) {
4313
4761
  transactionRequest.gasLimit = minGas;
@@ -4349,7 +4797,7 @@ Supported fuel-core version: ${supportedVersion}.`
4349
4797
  if (estimateTxDependencies) {
4350
4798
  return this.estimateTxDependencies(transactionRequest);
4351
4799
  }
4352
- const encodedTransactions = [hexlify12(transactionRequest.toTransactionBytes())];
4800
+ const encodedTransactions = [hexlify14(transactionRequest.toTransactionBytes())];
4353
4801
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
4354
4802
  encodedTransactions,
4355
4803
  utxoValidation: true
@@ -4362,6 +4810,8 @@ Supported fuel-core version: ${supportedVersion}.`
4362
4810
  return { receipts: callResult[0].receipts };
4363
4811
  }
4364
4812
  /**
4813
+ * @hidden
4814
+ *
4365
4815
  * Returns a transaction cost to enable user
4366
4816
  * to set gasLimit and also reserve balance amounts
4367
4817
  * on the transaction.
@@ -4371,23 +4821,16 @@ Supported fuel-core version: ${supportedVersion}.`
4371
4821
  *
4372
4822
  * @returns A promise that resolves to the transaction cost object.
4373
4823
  */
4374
- async getTransactionCost(transactionRequestLike, { resourcesOwner, signatureCallback, quantitiesToContract = [] } = {}) {
4824
+ async getTransactionCost(transactionRequestLike, { signatureCallback } = {}) {
4375
4825
  const txRequestClone = clone3(transactionRequestify(transactionRequestLike));
4376
- const isScriptTransaction = txRequestClone.type === TransactionType8.Script;
4377
- const baseAssetId = this.getBaseAssetId();
4378
4826
  const updateMaxFee = txRequestClone.maxFee.eq(0);
4379
- const coinOutputsQuantities = txRequestClone.getCoinOutputsQuantities();
4380
- const allQuantities = mergeQuantities(coinOutputsQuantities, quantitiesToContract);
4381
- txRequestClone.fundWithFakeUtxos(allQuantities, baseAssetId, resourcesOwner?.address);
4827
+ const isScriptTransaction = isTransactionTypeScript(txRequestClone);
4382
4828
  if (isScriptTransaction) {
4383
4829
  txRequestClone.gasLimit = bn17(0);
4384
4830
  }
4385
- if (resourcesOwner && "populateTransactionPredicateData" in resourcesOwner) {
4386
- resourcesOwner.populateTransactionPredicateData(txRequestClone);
4387
- }
4388
4831
  const signedRequest = clone3(txRequestClone);
4389
4832
  let addedSignatures = 0;
4390
- if (signatureCallback && isScriptTransaction) {
4833
+ if (signatureCallback && isTransactionTypeScript(signedRequest)) {
4391
4834
  const lengthBefore = signedRequest.witnesses.length;
4392
4835
  await signatureCallback(signedRequest);
4393
4836
  addedSignatures = signedRequest.witnesses.length - lengthBefore;
@@ -4420,7 +4863,6 @@ Supported fuel-core version: ${supportedVersion}.`
4420
4863
  }));
4421
4864
  }
4422
4865
  return {
4423
- requiredQuantities: allQuantities,
4424
4866
  receipts,
4425
4867
  gasUsed,
4426
4868
  gasPrice,
@@ -4436,34 +4878,6 @@ Supported fuel-core version: ${supportedVersion}.`
4436
4878
  updateMaxFee
4437
4879
  };
4438
4880
  }
4439
- /**
4440
- * Get the required quantities and associated resources for a transaction.
4441
- *
4442
- * @param owner - address to add resources from.
4443
- * @param transactionRequestLike - transaction request to populate resources for.
4444
- * @param quantitiesToContract - quantities for the contract (optional).
4445
- *
4446
- * @returns a promise resolving to the required quantities for the transaction.
4447
- */
4448
- async getResourcesForTransaction(owner, transactionRequestLike, quantitiesToContract = []) {
4449
- const ownerAddress = Address2.fromAddressOrString(owner);
4450
- const transactionRequest = transactionRequestify(clone3(transactionRequestLike));
4451
- const transactionCost = await this.getTransactionCost(transactionRequest, {
4452
- quantitiesToContract
4453
- });
4454
- transactionRequest.addResources(
4455
- await this.getResourcesToSpend(ownerAddress, transactionCost.requiredQuantities)
4456
- );
4457
- const { requiredQuantities, ...txCost } = await this.getTransactionCost(transactionRequest, {
4458
- quantitiesToContract
4459
- });
4460
- const resources = await this.getResourcesToSpend(ownerAddress, requiredQuantities);
4461
- return {
4462
- resources,
4463
- requiredQuantities,
4464
- ...txCost
4465
- };
4466
- }
4467
4881
  /**
4468
4882
  * Returns coins for the given owner.
4469
4883
  *
@@ -4474,7 +4888,7 @@ Supported fuel-core version: ${supportedVersion}.`
4474
4888
  * @returns A promise that resolves to the coins.
4475
4889
  */
4476
4890
  async getCoins(owner, assetId, paginationArgs) {
4477
- const ownerAddress = Address2.fromAddressOrString(owner);
4891
+ const ownerAddress = Address3.fromAddressOrString(owner);
4478
4892
  const {
4479
4893
  coins: { edges, pageInfo }
4480
4894
  } = await this.operations.getCoins({
@@ -4482,13 +4896,13 @@ Supported fuel-core version: ${supportedVersion}.`
4482
4896
  paginationLimit: RESOURCES_PAGE_SIZE_LIMIT,
4483
4897
  inputArgs: paginationArgs
4484
4898
  }),
4485
- filter: { owner: ownerAddress.toB256(), assetId: assetId && hexlify12(assetId) }
4899
+ filter: { owner: ownerAddress.toB256(), assetId: assetId && hexlify14(assetId) }
4486
4900
  });
4487
4901
  const coins = edges.map(({ node }) => ({
4488
4902
  id: node.utxoId,
4489
4903
  assetId: node.assetId,
4490
4904
  amount: bn17(node.amount),
4491
- owner: Address2.fromAddressOrString(node.owner),
4905
+ owner: Address3.fromAddressOrString(node.owner),
4492
4906
  blockCreated: bn17(node.blockCreated),
4493
4907
  txCreatedIdx: bn17(node.txCreatedIdx)
4494
4908
  }));
@@ -4506,21 +4920,20 @@ Supported fuel-core version: ${supportedVersion}.`
4506
4920
  * @returns A promise that resolves to the resources.
4507
4921
  */
4508
4922
  async getResourcesToSpend(owner, quantities, excludedIds) {
4509
- const ownerAddress = Address2.fromAddressOrString(owner);
4923
+ const ownerAddress = Address3.fromAddressOrString(owner);
4510
4924
  const excludeInput = {
4511
- messages: excludedIds?.messages?.map((nonce) => hexlify12(nonce)) || [],
4512
- utxos: excludedIds?.utxos?.map((id) => hexlify12(id)) || []
4925
+ messages: excludedIds?.messages?.map((nonce) => hexlify14(nonce)) || [],
4926
+ utxos: excludedIds?.utxos?.map((id) => hexlify14(id)) || []
4513
4927
  };
4514
4928
  if (this.cache) {
4515
- const uniqueUtxos = new Set(
4516
- excludeInput.utxos.concat(this.cache?.getActiveData().map((id) => hexlify12(id)))
4517
- );
4518
- excludeInput.utxos = Array.from(uniqueUtxos);
4929
+ const cached = this.cache.getActiveData();
4930
+ excludeInput.messages.push(...cached.messages);
4931
+ excludeInput.utxos.push(...cached.utxos);
4519
4932
  }
4520
4933
  const coinsQuery = {
4521
4934
  owner: ownerAddress.toB256(),
4522
4935
  queryPerAsset: quantities.map(coinQuantityfy).map(({ assetId, amount, max: maxPerAsset }) => ({
4523
- assetId: hexlify12(assetId),
4936
+ assetId: hexlify14(assetId),
4524
4937
  amount: amount.toString(10),
4525
4938
  max: maxPerAsset ? maxPerAsset.toString(10) : void 0
4526
4939
  })),
@@ -4534,8 +4947,8 @@ Supported fuel-core version: ${supportedVersion}.`
4534
4947
  amount: bn17(coin.amount),
4535
4948
  assetId: coin.assetId,
4536
4949
  daHeight: bn17(coin.daHeight),
4537
- sender: Address2.fromAddressOrString(coin.sender),
4538
- recipient: Address2.fromAddressOrString(coin.recipient),
4950
+ sender: Address3.fromAddressOrString(coin.sender),
4951
+ recipient: Address3.fromAddressOrString(coin.recipient),
4539
4952
  nonce: coin.nonce
4540
4953
  };
4541
4954
  case "Coin":
@@ -4543,7 +4956,7 @@ Supported fuel-core version: ${supportedVersion}.`
4543
4956
  id: coin.utxoId,
4544
4957
  amount: bn17(coin.amount),
4545
4958
  assetId: coin.assetId,
4546
- owner: Address2.fromAddressOrString(coin.owner),
4959
+ owner: Address3.fromAddressOrString(coin.owner),
4547
4960
  blockCreated: bn17(coin.blockCreated),
4548
4961
  txCreatedIdx: bn17(coin.txCreatedIdx)
4549
4962
  };
@@ -4629,7 +5042,7 @@ Supported fuel-core version: ${supportedVersion}.`
4629
5042
  time: block.header.time,
4630
5043
  transactionIds: block.transactions.map((tx) => tx.id),
4631
5044
  transactions: block.transactions.map(
4632
- (tx) => new TransactionCoder5().decode(arrayify11(tx.rawPayload), 0)?.[0]
5045
+ (tx) => new TransactionCoder5().decode(arrayify12(tx.rawPayload), 0)?.[0]
4633
5046
  )
4634
5047
  };
4635
5048
  }
@@ -4645,7 +5058,7 @@ Supported fuel-core version: ${supportedVersion}.`
4645
5058
  return null;
4646
5059
  }
4647
5060
  return new TransactionCoder5().decode(
4648
- arrayify11(transaction.rawPayload),
5061
+ arrayify12(transaction.rawPayload),
4649
5062
  0
4650
5063
  )?.[0];
4651
5064
  }
@@ -4660,7 +5073,7 @@ Supported fuel-core version: ${supportedVersion}.`
4660
5073
  } = await this.operations.getTransactions(paginationArgs);
4661
5074
  const coder = new TransactionCoder5();
4662
5075
  const transactions = edges.map(
4663
- ({ node: { rawPayload } }) => coder.decode(arrayify11(rawPayload), 0)[0]
5076
+ ({ node: { rawPayload } }) => coder.decode(arrayify12(rawPayload), 0)[0]
4664
5077
  );
4665
5078
  return { transactions, pageInfo };
4666
5079
  }
@@ -4686,8 +5099,8 @@ Supported fuel-core version: ${supportedVersion}.`
4686
5099
  */
4687
5100
  async getContractBalance(contractId, assetId) {
4688
5101
  const { contractBalance } = await this.operations.getContractBalance({
4689
- contract: Address2.fromAddressOrString(contractId).toB256(),
4690
- asset: hexlify12(assetId)
5102
+ contract: Address3.fromAddressOrString(contractId).toB256(),
5103
+ asset: hexlify14(assetId)
4691
5104
  });
4692
5105
  return bn17(contractBalance.amount, 10);
4693
5106
  }
@@ -4700,8 +5113,8 @@ Supported fuel-core version: ${supportedVersion}.`
4700
5113
  */
4701
5114
  async getBalance(owner, assetId) {
4702
5115
  const { balance } = await this.operations.getBalance({
4703
- owner: Address2.fromAddressOrString(owner).toB256(),
4704
- assetId: hexlify12(assetId)
5116
+ owner: Address3.fromAddressOrString(owner).toB256(),
5117
+ assetId: hexlify14(assetId)
4705
5118
  });
4706
5119
  return bn17(balance.amount, 10);
4707
5120
  }
@@ -4721,7 +5134,7 @@ Supported fuel-core version: ${supportedVersion}.`
4721
5134
  * but the current Fuel-Core implementation does not support pagination yet.
4722
5135
  */
4723
5136
  first: 1e4,
4724
- filter: { owner: Address2.fromAddressOrString(owner).toB256() }
5137
+ filter: { owner: Address3.fromAddressOrString(owner).toB256() }
4725
5138
  });
4726
5139
  const balances = edges.map(({ node }) => ({
4727
5140
  assetId: node.assetId,
@@ -4744,7 +5157,7 @@ Supported fuel-core version: ${supportedVersion}.`
4744
5157
  inputArgs: paginationArgs,
4745
5158
  paginationLimit: RESOURCES_PAGE_SIZE_LIMIT
4746
5159
  }),
4747
- owner: Address2.fromAddressOrString(address).toB256()
5160
+ owner: Address3.fromAddressOrString(address).toB256()
4748
5161
  });
4749
5162
  const messages = edges.map(({ node }) => ({
4750
5163
  messageId: InputMessageCoder.getMessageId({
@@ -4754,8 +5167,8 @@ Supported fuel-core version: ${supportedVersion}.`
4754
5167
  amount: bn17(node.amount),
4755
5168
  data: node.data
4756
5169
  }),
4757
- sender: Address2.fromAddressOrString(node.sender),
4758
- recipient: Address2.fromAddressOrString(node.recipient),
5170
+ sender: Address3.fromAddressOrString(node.sender),
5171
+ recipient: Address3.fromAddressOrString(node.recipient),
4759
5172
  nonce: node.nonce,
4760
5173
  amount: bn17(node.amount),
4761
5174
  data: InputMessageCoder.decodeData(node.data),
@@ -4781,7 +5194,7 @@ Supported fuel-core version: ${supportedVersion}.`
4781
5194
  nonce
4782
5195
  };
4783
5196
  if (commitBlockId && commitBlockHeight) {
4784
- throw new FuelError13(
5197
+ throw new FuelError15(
4785
5198
  ErrorCode13.INVALID_INPUT_PARAMETERS,
4786
5199
  "commitBlockId and commitBlockHeight cannot be used together"
4787
5200
  );
@@ -4853,8 +5266,8 @@ Supported fuel-core version: ${supportedVersion}.`
4853
5266
  eventInboxRoot: commitBlockHeader.eventInboxRoot,
4854
5267
  stateTransitionBytecodeVersion: Number(commitBlockHeader.stateTransitionBytecodeVersion)
4855
5268
  },
4856
- sender: Address2.fromAddressOrString(sender),
4857
- recipient: Address2.fromAddressOrString(recipient),
5269
+ sender: Address3.fromAddressOrString(sender),
5270
+ recipient: Address3.fromAddressOrString(recipient),
4858
5271
  nonce,
4859
5272
  amount: bn17(amount),
4860
5273
  data
@@ -4950,25 +5363,25 @@ Supported fuel-core version: ${supportedVersion}.`
4950
5363
  const { paginationLimit, inputArgs = {} } = params;
4951
5364
  const { first, last, after, before } = inputArgs;
4952
5365
  if (after && before) {
4953
- throw new FuelError13(
5366
+ throw new FuelError15(
4954
5367
  ErrorCode13.INVALID_INPUT_PARAMETERS,
4955
5368
  'Pagination arguments "after" and "before" cannot be used together'
4956
5369
  );
4957
5370
  }
4958
5371
  if ((first || 0) > paginationLimit || (last || 0) > paginationLimit) {
4959
- throw new FuelError13(
5372
+ throw new FuelError15(
4960
5373
  ErrorCode13.INVALID_INPUT_PARAMETERS,
4961
5374
  `Pagination limit for this query cannot exceed ${paginationLimit} items`
4962
5375
  );
4963
5376
  }
4964
5377
  if (first && before) {
4965
- throw new FuelError13(
5378
+ throw new FuelError15(
4966
5379
  ErrorCode13.INVALID_INPUT_PARAMETERS,
4967
5380
  'The use of pagination argument "first" with "before" is not supported'
4968
5381
  );
4969
5382
  }
4970
5383
  if (last && after) {
4971
- throw new FuelError13(
5384
+ throw new FuelError15(
4972
5385
  ErrorCode13.INVALID_INPUT_PARAMETERS,
4973
5386
  'The use of pagination argument "last" with "after" is not supported'
4974
5387
  );
@@ -5000,15 +5413,22 @@ Supported fuel-core version: ${supportedVersion}.`
5000
5413
  };
5001
5414
  var Provider = _Provider;
5002
5415
  _cacheInputs = new WeakSet();
5003
- cacheInputs_fn = function(inputs) {
5416
+ cacheInputs_fn = function(inputs, transactionId) {
5004
5417
  if (!this.cache) {
5005
5418
  return;
5006
5419
  }
5007
- inputs.forEach((input) => {
5008
- if (input.type === InputType7.Coin) {
5009
- this.cache?.set(input.id);
5010
- }
5011
- });
5420
+ const inputsToCache = inputs.reduce(
5421
+ (acc, input) => {
5422
+ if (input.type === InputType7.Coin) {
5423
+ acc.utxos.push(input.id);
5424
+ } else if (input.type === InputType7.Message) {
5425
+ acc.messages.push(input.nonce);
5426
+ }
5427
+ return acc;
5428
+ },
5429
+ { utxos: [], messages: [] }
5430
+ );
5431
+ this.cache.set(transactionId, inputsToCache);
5012
5432
  };
5013
5433
  /** @hidden */
5014
5434
  __publicField(Provider, "chainInfoCache", {});
@@ -5016,10 +5436,10 @@ __publicField(Provider, "chainInfoCache", {});
5016
5436
  __publicField(Provider, "nodeInfoCache", {});
5017
5437
 
5018
5438
  // src/providers/transaction-summary/get-transaction-summary.ts
5019
- import { ErrorCode as ErrorCode14, FuelError as FuelError14 } from "@fuel-ts/errors";
5439
+ import { ErrorCode as ErrorCode14, FuelError as FuelError16 } from "@fuel-ts/errors";
5020
5440
  import { bn as bn18 } from "@fuel-ts/math";
5021
5441
  import { TransactionCoder as TransactionCoder6 } from "@fuel-ts/transactions";
5022
- import { arrayify as arrayify12 } from "@fuel-ts/utils";
5442
+ import { arrayify as arrayify13 } from "@fuel-ts/utils";
5023
5443
 
5024
5444
  // src/providers/chains.ts
5025
5445
  var CHAIN_IDS = {
@@ -5092,19 +5512,75 @@ var rawAssets = [
5092
5512
  ];
5093
5513
  var assets = resolveIconPaths(rawAssets, fuelAssetsBaseUrl);
5094
5514
 
5515
+ // src/test-utils/test-asset-id.ts
5516
+ import { randomBytes as randomBytes4 } from "@fuel-ts/crypto";
5517
+ import { hexlify as hexlify15 } from "@fuel-ts/utils";
5518
+ var _TestAssetId = class {
5519
+ constructor(value) {
5520
+ this.value = value;
5521
+ }
5522
+ static random(count = 1) {
5523
+ const assetIds = [];
5524
+ for (let i = 0; i < count; i++) {
5525
+ assetIds.push(new _TestAssetId(hexlify15(randomBytes4(32))));
5526
+ }
5527
+ return assetIds;
5528
+ }
5529
+ };
5530
+ var TestAssetId = _TestAssetId;
5531
+ __publicField(TestAssetId, "A", new _TestAssetId(
5532
+ "0x0101010101010101010101010101010101010101010101010101010101010101"
5533
+ ));
5534
+ __publicField(TestAssetId, "B", new _TestAssetId(
5535
+ "0x0202020202020202020202020202020202020202020202020202020202020202"
5536
+ ));
5537
+
5538
+ // src/test-utils/wallet-config.ts
5539
+ import { randomBytes as randomBytes8 } from "@fuel-ts/crypto";
5540
+ import { FuelError as FuelError22 } from "@fuel-ts/errors";
5541
+ import { defaultSnapshotConfigs as defaultSnapshotConfigs2, hexlify as hexlify21 } from "@fuel-ts/utils";
5542
+
5543
+ // src/wallet/base-wallet-unlocked.ts
5544
+ import { hashMessage } from "@fuel-ts/hasher";
5545
+ import { hexlify as hexlify18 } from "@fuel-ts/utils";
5546
+
5547
+ // src/account.ts
5548
+ import { UTXO_ID_LEN as UTXO_ID_LEN3 } from "@fuel-ts/abi-coder";
5549
+ import { Address as Address4 } from "@fuel-ts/address";
5550
+ import { randomBytes as randomBytes5 } from "@fuel-ts/crypto";
5551
+ import { ErrorCode as ErrorCode15, FuelError as FuelError17 } from "@fuel-ts/errors";
5552
+ import { AbstractAccount } from "@fuel-ts/interfaces";
5553
+ import { bn as bn19 } from "@fuel-ts/math";
5554
+ import { arrayify as arrayify15, hexlify as hexlify16, isDefined as isDefined3 } from "@fuel-ts/utils";
5555
+ import { clone as clone4 } from "ramda";
5556
+
5557
+ // src/providers/utils/merge-quantities.ts
5558
+ var mergeQuantities = (...coinQuantities) => {
5559
+ const resultMap = {};
5560
+ function addToMap({ amount, assetId }) {
5561
+ if (resultMap[assetId]) {
5562
+ resultMap[assetId] = resultMap[assetId].add(amount);
5563
+ } else {
5564
+ resultMap[assetId] = amount;
5565
+ }
5566
+ }
5567
+ coinQuantities.forEach((arr) => arr.forEach(addToMap));
5568
+ return Object.entries(resultMap).map(([assetId, amount]) => ({ assetId, amount }));
5569
+ };
5570
+
5095
5571
  // src/utils/formatTransferToContractScriptData.ts
5096
5572
  import { BigNumberCoder as BigNumberCoder2 } from "@fuel-ts/abi-coder";
5097
5573
  import { BN as BN2 } from "@fuel-ts/math";
5098
- import { arrayify as arrayify13 } from "@fuel-ts/utils";
5574
+ import { arrayify as arrayify14 } from "@fuel-ts/utils";
5099
5575
  import * as asm from "@fuels/vm-asm";
5100
5576
  var formatTransferToContractScriptData = (params) => {
5101
5577
  const { assetId, amountToTransfer, hexlifiedContractId } = params;
5102
5578
  const numberCoder = new BigNumberCoder2("u64");
5103
5579
  const encoded = numberCoder.encode(new BN2(amountToTransfer).toNumber());
5104
5580
  const scriptData = Uint8Array.from([
5105
- ...arrayify13(hexlifiedContractId),
5581
+ ...arrayify14(hexlifiedContractId),
5106
5582
  ...encoded,
5107
- ...arrayify13(assetId)
5583
+ ...arrayify14(assetId)
5108
5584
  ]);
5109
5585
  return scriptData;
5110
5586
  };
@@ -5129,7 +5605,7 @@ var assembleTransferToContractScript = async (params) => {
5129
5605
  };
5130
5606
 
5131
5607
  // src/account.ts
5132
- var MAX_FUNDING_ATTEMPTS = 2;
5608
+ var MAX_FUNDING_ATTEMPTS = 5;
5133
5609
  var Account = class extends AbstractAccount {
5134
5610
  /**
5135
5611
  * The address associated with the account.
@@ -5154,7 +5630,7 @@ var Account = class extends AbstractAccount {
5154
5630
  super();
5155
5631
  this._provider = provider;
5156
5632
  this._connector = connector;
5157
- this.address = Address3.fromDynamicInput(address);
5633
+ this.address = Address4.fromDynamicInput(address);
5158
5634
  }
5159
5635
  /**
5160
5636
  * The provider used to interact with the network.
@@ -5165,7 +5641,7 @@ var Account = class extends AbstractAccount {
5165
5641
  */
5166
5642
  get provider() {
5167
5643
  if (!this._provider) {
5168
- throw new FuelError15(ErrorCode15.MISSING_PROVIDER, "Provider not set");
5644
+ throw new FuelError17(ErrorCode15.MISSING_PROVIDER, "Provider not set");
5169
5645
  }
5170
5646
  return this._provider;
5171
5647
  }
@@ -5242,7 +5718,7 @@ var Account = class extends AbstractAccount {
5242
5718
  * @returns A promise that resolves to the funded transaction request.
5243
5719
  */
5244
5720
  async fund(request, params) {
5245
- const { addedSignatures, estimatedPredicates, requiredQuantities, updateMaxFee } = params;
5721
+ const { addedSignatures, estimatedPredicates, requiredQuantities, updateMaxFee, gasPrice } = params;
5246
5722
  const fee = request.maxFee;
5247
5723
  const baseAssetId = this.provider.getBaseAssetId();
5248
5724
  const requiredInBaseAsset = requiredQuantities.find((quantity) => quantity.assetId === baseAssetId)?.amount || bn19(0);
@@ -5290,10 +5766,12 @@ var Account = class extends AbstractAccount {
5290
5766
  );
5291
5767
  }
5292
5768
  if (!updateMaxFee) {
5769
+ needsToBeFunded = false;
5293
5770
  break;
5294
5771
  }
5295
5772
  const { maxFee: newFee } = await this.provider.estimateTxGasAndFee({
5296
- transactionRequest: requestToReestimate2
5773
+ transactionRequest: requestToReestimate2,
5774
+ gasPrice
5297
5775
  });
5298
5776
  const totalBaseAssetOnInputs = getAssetAmountInRequestInputs(
5299
5777
  request.inputs,
@@ -5313,6 +5791,12 @@ var Account = class extends AbstractAccount {
5313
5791
  }
5314
5792
  fundingAttempts += 1;
5315
5793
  }
5794
+ if (needsToBeFunded) {
5795
+ throw new FuelError17(
5796
+ ErrorCode15.NOT_ENOUGH_FUNDS,
5797
+ `The account ${this.address} does not have enough base asset funds to cover the transaction execution.`
5798
+ );
5799
+ }
5316
5800
  request.updatePredicateGasUsed(estimatedPredicates);
5317
5801
  const requestToReestimate = clone4(request);
5318
5802
  if (addedSignatures) {
@@ -5379,7 +5863,7 @@ var Account = class extends AbstractAccount {
5379
5863
  const { destination, amount, assetId } = transferParams;
5380
5864
  this.validateTransferAmount(amount);
5381
5865
  request.addCoinOutput(
5382
- Address3.fromAddressOrString(destination),
5866
+ Address4.fromAddressOrString(destination),
5383
5867
  amount,
5384
5868
  assetId ?? this.provider.getBaseAssetId()
5385
5869
  );
@@ -5414,12 +5898,12 @@ var Account = class extends AbstractAccount {
5414
5898
  */
5415
5899
  async transferToContract(contractId, amount, assetId, txParams = {}) {
5416
5900
  if (bn19(amount).lte(0)) {
5417
- throw new FuelError15(
5901
+ throw new FuelError17(
5418
5902
  ErrorCode15.INVALID_TRANSFER_AMOUNT,
5419
5903
  "Transfer amount must be a positive number."
5420
5904
  );
5421
5905
  }
5422
- const contractAddress = Address3.fromAddressOrString(contractId);
5906
+ const contractAddress = Address4.fromAddressOrString(contractId);
5423
5907
  const assetIdToTransfer = assetId ?? this.provider.getBaseAssetId();
5424
5908
  const { script, scriptData } = await assembleTransferToContractScript({
5425
5909
  hexlifiedContractId: contractAddress.toB256(),
@@ -5432,9 +5916,8 @@ var Account = class extends AbstractAccount {
5432
5916
  scriptData
5433
5917
  });
5434
5918
  request.addContractInputAndOutput(contractAddress);
5435
- const txCost = await this.provider.getTransactionCost(request, {
5436
- resourcesOwner: this,
5437
- quantitiesToContract: [{ amount: bn19(amount), assetId: String(assetIdToTransfer) }]
5919
+ const txCost = await this.getTransactionCost(request, {
5920
+ quantities: [{ amount: bn19(amount), assetId: String(assetIdToTransfer) }]
5438
5921
  });
5439
5922
  request = this.validateGasLimitAndMaxFee({
5440
5923
  transactionRequest: request,
@@ -5454,23 +5937,23 @@ var Account = class extends AbstractAccount {
5454
5937
  * @returns A promise that resolves to the transaction response.
5455
5938
  */
5456
5939
  async withdrawToBaseLayer(recipient, amount, txParams = {}) {
5457
- const recipientAddress = Address3.fromAddressOrString(recipient);
5458
- const recipientDataArray = arrayify14(
5940
+ const recipientAddress = Address4.fromAddressOrString(recipient);
5941
+ const recipientDataArray = arrayify15(
5459
5942
  "0x".concat(recipientAddress.toHexString().substring(2).padStart(64, "0"))
5460
5943
  );
5461
- const amountDataArray = arrayify14(
5944
+ const amountDataArray = arrayify15(
5462
5945
  "0x".concat(bn19(amount).toHex().substring(2).padStart(16, "0"))
5463
5946
  );
5464
5947
  const script = new Uint8Array([
5465
- ...arrayify14(withdrawScript.bytes),
5948
+ ...arrayify15(withdrawScript.bytes),
5466
5949
  ...recipientDataArray,
5467
5950
  ...amountDataArray
5468
5951
  ]);
5469
5952
  const params = { script, ...txParams };
5470
5953
  const baseAssetId = this.provider.getBaseAssetId();
5471
5954
  let request = new ScriptTransactionRequest(params);
5472
- const quantitiesToContract = [{ amount: bn19(amount), assetId: baseAssetId }];
5473
- const txCost = await this.provider.getTransactionCost(request, { quantitiesToContract });
5955
+ const quantities = [{ amount: bn19(amount), assetId: baseAssetId }];
5956
+ const txCost = await this.getTransactionCost(request, { quantities });
5474
5957
  request = this.validateGasLimitAndMaxFee({
5475
5958
  transactionRequest: request,
5476
5959
  gasUsed: txCost.gasUsed,
@@ -5480,6 +5963,34 @@ var Account = class extends AbstractAccount {
5480
5963
  await this.fund(request, txCost);
5481
5964
  return this.sendTransaction(request);
5482
5965
  }
5966
+ /**
5967
+ * Returns a transaction cost to enable user
5968
+ * to set gasLimit and also reserve balance amounts
5969
+ * on the transaction.
5970
+ *
5971
+ * @param transactionRequestLike - The transaction request object.
5972
+ * @param transactionCostParams - The transaction cost parameters (optional).
5973
+ *
5974
+ * @returns A promise that resolves to the transaction cost object.
5975
+ */
5976
+ async getTransactionCost(transactionRequestLike, { signatureCallback, quantities = [] } = {}) {
5977
+ const txRequestClone = clone4(transactionRequestify(transactionRequestLike));
5978
+ const baseAssetId = this.provider.getBaseAssetId();
5979
+ const coinOutputsQuantities = txRequestClone.getCoinOutputsQuantities();
5980
+ const requiredQuantities = mergeQuantities(coinOutputsQuantities, quantities);
5981
+ const transactionFeeForDryRun = [{ assetId: baseAssetId, amount: bn19("100000000000000000") }];
5982
+ const resources = this.generateFakeResources(
5983
+ mergeQuantities(requiredQuantities, transactionFeeForDryRun)
5984
+ );
5985
+ txRequestClone.addResources(resources);
5986
+ const txCost = await this.provider.getTransactionCost(txRequestClone, {
5987
+ signatureCallback
5988
+ });
5989
+ return {
5990
+ ...txCost,
5991
+ requiredQuantities
5992
+ };
5993
+ }
5483
5994
  /**
5484
5995
  * Sign a message from the account via the connector.
5485
5996
  *
@@ -5490,7 +6001,7 @@ var Account = class extends AbstractAccount {
5490
6001
  */
5491
6002
  async signMessage(message) {
5492
6003
  if (!this._connector) {
5493
- throw new FuelError15(ErrorCode15.MISSING_CONNECTOR, "A connector is required to sign messages.");
6004
+ throw new FuelError17(ErrorCode15.MISSING_CONNECTOR, "A connector is required to sign messages.");
5494
6005
  }
5495
6006
  return this._connector.signMessage(this.address.toString(), message);
5496
6007
  }
@@ -5502,7 +6013,7 @@ var Account = class extends AbstractAccount {
5502
6013
  */
5503
6014
  async signTransaction(transactionRequestLike) {
5504
6015
  if (!this._connector) {
5505
- throw new FuelError15(
6016
+ throw new FuelError17(
5506
6017
  ErrorCode15.MISSING_CONNECTOR,
5507
6018
  "A connector is required to sign transactions."
5508
6019
  );
@@ -5516,7 +6027,7 @@ var Account = class extends AbstractAccount {
5516
6027
  * @param sendTransactionParams - The provider send transaction parameters (optional).
5517
6028
  * @returns A promise that resolves to the transaction response.
5518
6029
  */
5519
- async sendTransaction(transactionRequestLike, { estimateTxDependencies = true, awaitExecution } = {}) {
6030
+ async sendTransaction(transactionRequestLike, { estimateTxDependencies = true } = {}) {
5520
6031
  if (this._connector) {
5521
6032
  return this.provider.getTransactionResponse(
5522
6033
  await this._connector.sendTransaction(this.address.toString(), transactionRequestLike)
@@ -5527,7 +6038,6 @@ var Account = class extends AbstractAccount {
5527
6038
  await this.provider.estimateTxDependencies(transactionRequest);
5528
6039
  }
5529
6040
  return this.provider.sendTransaction(transactionRequest, {
5530
- awaitExecution,
5531
6041
  estimateTxDependencies: false
5532
6042
  });
5533
6043
  }
@@ -5553,7 +6063,7 @@ var Account = class extends AbstractAccount {
5553
6063
  */
5554
6064
  generateFakeResources(coins) {
5555
6065
  return coins.map((coin) => ({
5556
- id: hexlify13(randomBytes2(UTXO_ID_LEN3)),
6066
+ id: hexlify16(randomBytes5(UTXO_ID_LEN3)),
5557
6067
  owner: this.address,
5558
6068
  blockCreated: bn19(1),
5559
6069
  txCreatedIdx: bn19(1),
@@ -5563,7 +6073,7 @@ var Account = class extends AbstractAccount {
5563
6073
  /** @hidden * */
5564
6074
  validateTransferAmount(amount) {
5565
6075
  if (bn19(amount).lte(0)) {
5566
- throw new FuelError15(
6076
+ throw new FuelError17(
5567
6077
  ErrorCode15.INVALID_TRANSFER_AMOUNT,
5568
6078
  "Transfer amount must be a positive number."
5569
6079
  );
@@ -5572,9 +6082,7 @@ var Account = class extends AbstractAccount {
5572
6082
  /** @hidden * */
5573
6083
  async estimateAndFundTransaction(transactionRequest, txParams) {
5574
6084
  let request = transactionRequest;
5575
- const txCost = await this.provider.getTransactionCost(request, {
5576
- resourcesOwner: this
5577
- });
6085
+ const txCost = await this.getTransactionCost(request);
5578
6086
  request = this.validateGasLimitAndMaxFee({
5579
6087
  transactionRequest: request,
5580
6088
  gasUsed: txCost.gasUsed,
@@ -5592,132 +6100,23 @@ var Account = class extends AbstractAccount {
5592
6100
  txParams: { gasLimit: setGasLimit, maxFee: setMaxFee }
5593
6101
  }) {
5594
6102
  const request = transactionRequestify(transactionRequest);
5595
- if (!isDefined2(setGasLimit)) {
6103
+ if (!isDefined3(setGasLimit)) {
5596
6104
  request.gasLimit = gasUsed;
5597
- } else if (gasUsed.gt(setGasLimit)) {
5598
- throw new FuelError15(
5599
- ErrorCode15.GAS_LIMIT_TOO_LOW,
5600
- `Gas limit '${setGasLimit}' is lower than the required: '${gasUsed}'.`
5601
- );
5602
- }
5603
- if (!isDefined2(setMaxFee)) {
5604
- request.maxFee = maxFee;
5605
- } else if (maxFee.gt(setMaxFee)) {
5606
- throw new FuelError15(
5607
- ErrorCode15.MAX_FEE_TOO_LOW,
5608
- `Max fee '${setMaxFee}' is lower than the required: '${maxFee}'.`
5609
- );
5610
- }
5611
- return request;
5612
- }
5613
- };
5614
-
5615
- // src/signer/signer.ts
5616
- import { Address as Address4 } from "@fuel-ts/address";
5617
- import { randomBytes as randomBytes3 } from "@fuel-ts/crypto";
5618
- import { hash } from "@fuel-ts/hasher";
5619
- import { toBytes } from "@fuel-ts/math";
5620
- import { hexlify as hexlify14, concat as concat3, arrayify as arrayify15 } from "@fuel-ts/utils";
5621
- import { secp256k1 } from "@noble/curves/secp256k1";
5622
- var Signer = class {
5623
- address;
5624
- publicKey;
5625
- compressedPublicKey;
5626
- privateKey;
5627
- /**
5628
- * Create a Signer instance from a given private key
5629
- *
5630
- * @param privateKey - The private key to use for signing
5631
- * @returns A new Signer instance
5632
- */
5633
- constructor(privateKey) {
5634
- if (typeof privateKey === "string") {
5635
- if (privateKey.match(/^[0-9a-f]*$/i) && privateKey.length === 64) {
5636
- privateKey = `0x${privateKey}`;
5637
- }
5638
- }
5639
- const privateKeyBytes = toBytes(privateKey, 32);
5640
- this.privateKey = hexlify14(privateKeyBytes);
5641
- this.publicKey = hexlify14(secp256k1.getPublicKey(privateKeyBytes, false).slice(1));
5642
- this.compressedPublicKey = hexlify14(secp256k1.getPublicKey(privateKeyBytes, true));
5643
- this.address = Address4.fromPublicKey(this.publicKey);
5644
- }
5645
- /**
5646
- * Sign data using the Signer instance
5647
- *
5648
- * Signature is a 64 byte array of the concatenated r and s values with the compressed recoveryParam byte.
5649
- * @ignore
5650
- * [Read more](FuelLabs/fuel-specs/specs/protocol/cryptographic_primitives.md#public-key-cryptography)
5651
- *
5652
- * @param data - The data to be sign
5653
- * @returns hashed signature
5654
- */
5655
- sign(data) {
5656
- const signature = secp256k1.sign(arrayify15(data), arrayify15(this.privateKey));
5657
- const r = toBytes(`0x${signature.r.toString(16)}`, 32);
5658
- const s = toBytes(`0x${signature.s.toString(16)}`, 32);
5659
- s[0] |= (signature.recovery || 0) << 7;
5660
- return hexlify14(concat3([r, s]));
5661
- }
5662
- /**
5663
- * Add point on the current elliptic curve
5664
- *
5665
- * @param point - Point to add on the curve
5666
- * @returns compressed point on the curve
5667
- */
5668
- addPoint(point) {
5669
- const p0 = secp256k1.ProjectivePoint.fromHex(arrayify15(this.compressedPublicKey));
5670
- const p1 = secp256k1.ProjectivePoint.fromHex(arrayify15(point));
5671
- const result = p0.add(p1);
5672
- return `0x${result.toHex(true)}`;
5673
- }
5674
- /**
5675
- * Recover the public key from a signature performed with [`sign`](#sign).
5676
- *
5677
- * @param data - Data
5678
- * @param signature - hashed signature
5679
- * @returns public key from signature from the
5680
- */
5681
- static recoverPublicKey(data, signature) {
5682
- const signedMessageBytes = arrayify15(signature);
5683
- const r = signedMessageBytes.slice(0, 32);
5684
- const s = signedMessageBytes.slice(32, 64);
5685
- const recoveryParam = (s[0] & 128) >> 7;
5686
- s[0] &= 127;
5687
- const sig = new secp256k1.Signature(BigInt(hexlify14(r)), BigInt(hexlify14(s))).addRecoveryBit(
5688
- recoveryParam
5689
- );
5690
- const publicKey = sig.recoverPublicKey(arrayify15(data)).toRawBytes(false).slice(1);
5691
- return hexlify14(publicKey);
5692
- }
5693
- /**
5694
- * Recover the address from a signature performed with [`sign`](#sign).
5695
- *
5696
- * @param data - Data
5697
- * @param signature - Signature
5698
- * @returns Address from signature
5699
- */
5700
- static recoverAddress(data, signature) {
5701
- return Address4.fromPublicKey(Signer.recoverPublicKey(data, signature));
5702
- }
5703
- /**
5704
- * Generate a random privateKey
5705
- *
5706
- * @param entropy - Adds extra entropy to generate the privateKey
5707
- * @returns random 32-byte hashed
5708
- */
5709
- static generatePrivateKey(entropy) {
5710
- return entropy ? hash(concat3([randomBytes3(32), arrayify15(entropy)])) : randomBytes3(32);
5711
- }
5712
- /**
5713
- * Extended publicKey from a compact publicKey
5714
- *
5715
- * @param publicKey - Compact publicKey
5716
- * @returns extended publicKey
5717
- */
5718
- static extendPublicKey(publicKey) {
5719
- const point = secp256k1.ProjectivePoint.fromHex(arrayify15(publicKey));
5720
- return hexlify14(point.toRawBytes(false).slice(1));
6105
+ } else if (gasUsed.gt(setGasLimit)) {
6106
+ throw new FuelError17(
6107
+ ErrorCode15.GAS_LIMIT_TOO_LOW,
6108
+ `Gas limit '${setGasLimit}' is lower than the required: '${gasUsed}'.`
6109
+ );
6110
+ }
6111
+ if (!isDefined3(setMaxFee)) {
6112
+ request.maxFee = maxFee;
6113
+ } else if (maxFee.gt(setMaxFee)) {
6114
+ throw new FuelError17(
6115
+ ErrorCode15.MAX_FEE_TOO_LOW,
6116
+ `Max fee '${setMaxFee}' is lower than the required: '${maxFee}'.`
6117
+ );
6118
+ }
6119
+ return request;
5721
6120
  }
5722
6121
  };
5723
6122
 
@@ -5726,15 +6125,15 @@ import { Address as Address5 } from "@fuel-ts/address";
5726
6125
  import {
5727
6126
  bufferFromString,
5728
6127
  keccak256,
5729
- randomBytes as randomBytes4,
6128
+ randomBytes as randomBytes6,
5730
6129
  scrypt,
5731
6130
  stringFromBuffer,
5732
6131
  decryptJsonWalletData,
5733
- encryptJsonWalletData
6132
+ encryptJsonWalletData,
6133
+ randomUUID as randomUUID2
5734
6134
  } from "@fuel-ts/crypto";
5735
- import { ErrorCode as ErrorCode16, FuelError as FuelError16 } from "@fuel-ts/errors";
5736
- import { hexlify as hexlify15 } from "@fuel-ts/utils";
5737
- import { v4 as uuidv4 } from "uuid";
6135
+ import { ErrorCode as ErrorCode16, FuelError as FuelError18 } from "@fuel-ts/errors";
6136
+ import { hexlify as hexlify17 } from "@fuel-ts/utils";
5738
6137
  var DEFAULT_KDF_PARAMS_LOG_N = 13;
5739
6138
  var DEFAULT_KDF_PARAMS_R = 8;
5740
6139
  var DEFAULT_KDF_PARAMS_P = 1;
@@ -5749,7 +6148,7 @@ var removeHexPrefix = (hexString) => {
5749
6148
  async function encryptKeystoreWallet(privateKey, address, password) {
5750
6149
  const privateKeyBuffer = bufferFromString(removeHexPrefix(privateKey), "hex");
5751
6150
  const ownerAddress = Address5.fromAddressOrString(address);
5752
- const salt = randomBytes4(DEFAULT_KEY_SIZE);
6151
+ const salt = randomBytes6(DEFAULT_KEY_SIZE);
5753
6152
  const key = scrypt({
5754
6153
  password: bufferFromString(password),
5755
6154
  salt,
@@ -5758,13 +6157,13 @@ async function encryptKeystoreWallet(privateKey, address, password) {
5758
6157
  r: DEFAULT_KDF_PARAMS_R,
5759
6158
  p: DEFAULT_KDF_PARAMS_P
5760
6159
  });
5761
- const iv = randomBytes4(DEFAULT_IV_SIZE);
6160
+ const iv = randomBytes6(DEFAULT_IV_SIZE);
5762
6161
  const ciphertext = await encryptJsonWalletData(privateKeyBuffer, key, iv);
5763
6162
  const data = Uint8Array.from([...key.subarray(16, 32), ...ciphertext]);
5764
6163
  const macHashUint8Array = keccak256(data);
5765
6164
  const mac = stringFromBuffer(macHashUint8Array, "hex");
5766
6165
  const keystore = {
5767
- id: uuidv4(),
6166
+ id: randomUUID2(),
5768
6167
  version: 3,
5769
6168
  address: removeHexPrefix(ownerAddress.toHexString()),
5770
6169
  crypto: {
@@ -5810,13 +6209,13 @@ async function decryptKeystoreWallet(jsonWallet, password) {
5810
6209
  const macHashUint8Array = keccak256(data);
5811
6210
  const macHash = stringFromBuffer(macHashUint8Array, "hex");
5812
6211
  if (mac !== macHash) {
5813
- throw new FuelError16(
6212
+ throw new FuelError18(
5814
6213
  ErrorCode16.INVALID_PASSWORD,
5815
6214
  "Failed to decrypt the keystore wallet, the provided password is incorrect."
5816
6215
  );
5817
6216
  }
5818
6217
  const buffer = await decryptJsonWalletData(ciphertextBuffer, key, ivBuffer);
5819
- const privateKey = hexlify15(buffer);
6218
+ const privateKey = hexlify17(buffer);
5820
6219
  return privateKey;
5821
6220
  }
5822
6221
 
@@ -5861,7 +6260,7 @@ var BaseWalletUnlocked = class extends Account {
5861
6260
  */
5862
6261
  async signMessage(message) {
5863
6262
  const signedMessage = await this.signer().sign(hashMessage(message));
5864
- return hexlify16(signedMessage);
6263
+ return hexlify18(signedMessage);
5865
6264
  }
5866
6265
  /**
5867
6266
  * Signs a transaction with the wallet's private key.
@@ -5874,7 +6273,7 @@ var BaseWalletUnlocked = class extends Account {
5874
6273
  const chainId = this.provider.getChainId();
5875
6274
  const hashedTransaction = transactionRequest.getTransactionId(chainId);
5876
6275
  const signature = await this.signer().sign(hashedTransaction);
5877
- return hexlify16(signature);
6276
+ return hexlify18(signature);
5878
6277
  }
5879
6278
  /**
5880
6279
  * Populates a transaction with the witnesses signature.
@@ -5893,17 +6292,16 @@ var BaseWalletUnlocked = class extends Account {
5893
6292
  *
5894
6293
  * @param transactionRequestLike - The transaction request to send.
5895
6294
  * @param estimateTxDependencies - Whether to estimate the transaction dependencies.
5896
- * @param awaitExecution - Whether to wait for the transaction to be executed.
5897
6295
  * @returns A promise that resolves to the TransactionResponse object.
5898
6296
  */
5899
- async sendTransaction(transactionRequestLike, { estimateTxDependencies = false, awaitExecution } = {}) {
6297
+ async sendTransaction(transactionRequestLike, { estimateTxDependencies = false } = {}) {
5900
6298
  const transactionRequest = transactionRequestify(transactionRequestLike);
5901
6299
  if (estimateTxDependencies) {
5902
6300
  await this.provider.estimateTxDependencies(transactionRequest);
5903
6301
  }
5904
6302
  return this.provider.sendTransaction(
5905
6303
  await this.populateTransactionWitnessesSignature(transactionRequest),
5906
- { awaitExecution, estimateTxDependencies: false }
6304
+ { estimateTxDependencies: false }
5907
6305
  );
5908
6306
  }
5909
6307
  /**
@@ -5942,16 +6340,16 @@ __publicField(BaseWalletUnlocked, "defaultPath", "m/44'/1179993420'/0'/0/0");
5942
6340
 
5943
6341
  // src/hdwallet/hdwallet.ts
5944
6342
  import { computeHmac as computeHmac2, ripemd160 } from "@fuel-ts/crypto";
5945
- import { ErrorCode as ErrorCode19, FuelError as FuelError19 } from "@fuel-ts/errors";
6343
+ import { ErrorCode as ErrorCode19, FuelError as FuelError21 } from "@fuel-ts/errors";
5946
6344
  import { sha256 as sha2564 } from "@fuel-ts/hasher";
5947
6345
  import { bn as bn20, toBytes as toBytes2, toHex } from "@fuel-ts/math";
5948
- import { arrayify as arrayify18, hexlify as hexlify18, concat as concat5, dataSlice as dataSlice2, encodeBase58 as encodeBase582, decodeBase58 } from "@fuel-ts/utils";
6346
+ import { arrayify as arrayify18, hexlify as hexlify20, concat as concat5, dataSlice as dataSlice2, encodeBase58 as encodeBase582, decodeBase58 } from "@fuel-ts/utils";
5949
6347
 
5950
6348
  // src/mnemonic/mnemonic.ts
5951
- import { randomBytes as randomBytes5, pbkdf2, computeHmac } from "@fuel-ts/crypto";
5952
- import { ErrorCode as ErrorCode18, FuelError as FuelError18 } from "@fuel-ts/errors";
6349
+ import { randomBytes as randomBytes7, pbkdf2, computeHmac } from "@fuel-ts/crypto";
6350
+ import { ErrorCode as ErrorCode18, FuelError as FuelError20 } from "@fuel-ts/errors";
5953
6351
  import { sha256 as sha2563 } from "@fuel-ts/hasher";
5954
- import { arrayify as arrayify17, hexlify as hexlify17, concat as concat4, dataSlice, encodeBase58, toUtf8Bytes } from "@fuel-ts/utils";
6352
+ import { arrayify as arrayify17, hexlify as hexlify19, concat as concat4, dataSlice, encodeBase58, toUtf8Bytes } from "@fuel-ts/utils";
5955
6353
 
5956
6354
  // src/wordlists/words/english.ts
5957
6355
  var english = [
@@ -8006,7 +8404,7 @@ var english = [
8006
8404
  ];
8007
8405
 
8008
8406
  // src/mnemonic/utils.ts
8009
- import { ErrorCode as ErrorCode17, FuelError as FuelError17 } from "@fuel-ts/errors";
8407
+ import { ErrorCode as ErrorCode17, FuelError as FuelError19 } from "@fuel-ts/errors";
8010
8408
  import { sha256 as sha2562 } from "@fuel-ts/hasher";
8011
8409
  import { arrayify as arrayify16 } from "@fuel-ts/utils";
8012
8410
  function getLowerMask(bits) {
@@ -8055,7 +8453,7 @@ function mnemonicWordsToEntropy(words, wordlist) {
8055
8453
  for (let i = 0; i < words.length; i += 1) {
8056
8454
  const index = wordlist.indexOf(words[i].normalize("NFKD"));
8057
8455
  if (index === -1) {
8058
- throw new FuelError17(
8456
+ throw new FuelError19(
8059
8457
  ErrorCode17.INVALID_MNEMONIC,
8060
8458
  `Invalid mnemonic: the word '${words[i]}' is not found in the provided wordlist.`
8061
8459
  );
@@ -8072,7 +8470,7 @@ function mnemonicWordsToEntropy(words, wordlist) {
8072
8470
  const checksumMask = getUpperMask(checksumBits);
8073
8471
  const checksum = arrayify16(sha2562(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
8074
8472
  if (checksum !== (entropy[entropy.length - 1] & checksumMask)) {
8075
- throw new FuelError17(
8473
+ throw new FuelError19(
8076
8474
  ErrorCode17.INVALID_CHECKSUM,
8077
8475
  "Checksum validation failed for the provided mnemonic."
8078
8476
  );
@@ -8087,7 +8485,7 @@ var TestnetPRV = "0x04358394";
8087
8485
  var MNEMONIC_SIZES = [12, 15, 18, 21, 24];
8088
8486
  function assertWordList(wordlist) {
8089
8487
  if (wordlist.length !== 2048) {
8090
- throw new FuelError18(
8488
+ throw new FuelError20(
8091
8489
  ErrorCode18.INVALID_WORD_LIST,
8092
8490
  `Expected word list length of 2048, but got ${wordlist.length}.`
8093
8491
  );
@@ -8095,7 +8493,7 @@ function assertWordList(wordlist) {
8095
8493
  }
8096
8494
  function assertEntropy(entropy) {
8097
8495
  if (entropy.length % 4 !== 0 || entropy.length < 16 || entropy.length > 32) {
8098
- throw new FuelError18(
8496
+ throw new FuelError20(
8099
8497
  ErrorCode18.INVALID_ENTROPY,
8100
8498
  `Entropy should be between 16 and 32 bytes and a multiple of 4, but got ${entropy.length} bytes.`
8101
8499
  );
@@ -8106,7 +8504,7 @@ function assertMnemonic(words) {
8106
8504
  const errorMsg = `Invalid mnemonic size. Expected one of [${MNEMONIC_SIZES.join(
8107
8505
  ", "
8108
8506
  )}] words, but got ${words.length}.`;
8109
- throw new FuelError18(ErrorCode18.INVALID_MNEMONIC, errorMsg);
8507
+ throw new FuelError20(ErrorCode18.INVALID_MNEMONIC, errorMsg);
8110
8508
  }
8111
8509
  }
8112
8510
  var Mnemonic = class {
@@ -8145,7 +8543,7 @@ var Mnemonic = class {
8145
8543
  static mnemonicToEntropy(phrase, wordlist = english) {
8146
8544
  const words = getWords(phrase);
8147
8545
  assertMnemonic(words);
8148
- return hexlify17(mnemonicWordsToEntropy(words, wordlist));
8546
+ return hexlify19(mnemonicWordsToEntropy(words, wordlist));
8149
8547
  }
8150
8548
  /**
8151
8549
  * @param entropy - Entropy source to the mnemonic phrase.
@@ -8224,7 +8622,7 @@ var Mnemonic = class {
8224
8622
  static masterKeysFromSeed(seed) {
8225
8623
  const seedArray = arrayify17(seed);
8226
8624
  if (seedArray.length < 16 || seedArray.length > 64) {
8227
- throw new FuelError18(
8625
+ throw new FuelError20(
8228
8626
  ErrorCode18.INVALID_SEED,
8229
8627
  `Seed length should be between 16 and 64 bytes, but received ${seedArray.length} bytes.`
8230
8628
  );
@@ -8270,7 +8668,7 @@ var Mnemonic = class {
8270
8668
  * @returns A randomly generated mnemonic
8271
8669
  */
8272
8670
  static generate(size = 32, extraEntropy = "") {
8273
- const entropy = extraEntropy ? sha2563(concat4([randomBytes5(size), arrayify17(extraEntropy)])) : randomBytes5(size);
8671
+ const entropy = extraEntropy ? sha2563(concat4([randomBytes7(size), arrayify17(extraEntropy)])) : randomBytes7(size);
8274
8672
  return Mnemonic.entropyToMnemonic(entropy);
8275
8673
  }
8276
8674
  };
@@ -8278,10 +8676,10 @@ var mnemonic_default = Mnemonic;
8278
8676
 
8279
8677
  // src/hdwallet/hdwallet.ts
8280
8678
  var HARDENED_INDEX = 2147483648;
8281
- var MainnetPRV2 = hexlify18("0x0488ade4");
8282
- var MainnetPUB = hexlify18("0x0488b21e");
8283
- var TestnetPRV2 = hexlify18("0x04358394");
8284
- var TestnetPUB = hexlify18("0x043587cf");
8679
+ var MainnetPRV2 = hexlify20("0x0488ade4");
8680
+ var MainnetPUB = hexlify20("0x0488b21e");
8681
+ var TestnetPRV2 = hexlify20("0x04358394");
8682
+ var TestnetPUB = hexlify20("0x043587cf");
8285
8683
  function base58check(data) {
8286
8684
  return encodeBase582(concat5([data, dataSlice2(sha2564(sha2564(data)), 0, 4)]));
8287
8685
  }
@@ -8292,17 +8690,17 @@ function getExtendedKeyPrefix(isPublic = false, testnet = false) {
8292
8690
  return testnet ? TestnetPRV2 : MainnetPRV2;
8293
8691
  }
8294
8692
  function isPublicExtendedKey(extendedKey) {
8295
- return [MainnetPUB, TestnetPUB].includes(hexlify18(extendedKey.slice(0, 4)));
8693
+ return [MainnetPUB, TestnetPUB].includes(hexlify20(extendedKey.slice(0, 4)));
8296
8694
  }
8297
8695
  function isValidExtendedKey(extendedKey) {
8298
8696
  return [MainnetPRV2, TestnetPRV2, MainnetPUB, TestnetPUB].includes(
8299
- hexlify18(extendedKey.slice(0, 4))
8697
+ hexlify20(extendedKey.slice(0, 4))
8300
8698
  );
8301
8699
  }
8302
8700
  function parsePath(path2, depth = 0) {
8303
8701
  const components = path2.split("/");
8304
8702
  if (components.length === 0 || components[0] === "m" && depth !== 0) {
8305
- throw new FuelError19(ErrorCode19.HD_WALLET_ERROR, `invalid path - ${path2}`);
8703
+ throw new FuelError21(ErrorCode19.HD_WALLET_ERROR, `invalid path - ${path2}`);
8306
8704
  }
8307
8705
  if (components[0] === "m") {
8308
8706
  components.shift();
@@ -8314,8 +8712,8 @@ function parsePath(path2, depth = 0) {
8314
8712
  var HDWallet = class {
8315
8713
  depth = 0;
8316
8714
  index = 0;
8317
- fingerprint = hexlify18("0x00000000");
8318
- parentFingerprint = hexlify18("0x00000000");
8715
+ fingerprint = hexlify20("0x00000000");
8716
+ parentFingerprint = hexlify20("0x00000000");
8319
8717
  privateKey;
8320
8718
  publicKey;
8321
8719
  chainCode;
@@ -8327,16 +8725,16 @@ var HDWallet = class {
8327
8725
  constructor(config) {
8328
8726
  if (config.privateKey) {
8329
8727
  const signer = new Signer(config.privateKey);
8330
- this.publicKey = hexlify18(signer.compressedPublicKey);
8331
- this.privateKey = hexlify18(config.privateKey);
8728
+ this.publicKey = hexlify20(signer.compressedPublicKey);
8729
+ this.privateKey = hexlify20(config.privateKey);
8332
8730
  } else {
8333
8731
  if (!config.publicKey) {
8334
- throw new FuelError19(
8732
+ throw new FuelError21(
8335
8733
  ErrorCode19.HD_WALLET_ERROR,
8336
8734
  "Both public and private Key cannot be missing. At least one should be provided."
8337
8735
  );
8338
8736
  }
8339
- this.publicKey = hexlify18(config.publicKey);
8737
+ this.publicKey = hexlify20(config.publicKey);
8340
8738
  }
8341
8739
  this.parentFingerprint = config.parentFingerprint || this.parentFingerprint;
8342
8740
  this.fingerprint = dataSlice2(ripemd160(sha2564(this.publicKey)), 0, 4);
@@ -8361,7 +8759,7 @@ var HDWallet = class {
8361
8759
  const data = new Uint8Array(37);
8362
8760
  if (index & HARDENED_INDEX) {
8363
8761
  if (!privateKey) {
8364
- throw new FuelError19(
8762
+ throw new FuelError21(
8365
8763
  ErrorCode19.HD_WALLET_ERROR,
8366
8764
  "Cannot derive a hardened index without a private Key."
8367
8765
  );
@@ -8385,7 +8783,7 @@ var HDWallet = class {
8385
8783
  parentFingerprint: this.fingerprint
8386
8784
  });
8387
8785
  }
8388
- const signer = new Signer(hexlify18(IL));
8786
+ const signer = new Signer(hexlify20(IL));
8389
8787
  const Ki = signer.addPoint(publicKey);
8390
8788
  return new HDWallet({
8391
8789
  publicKey: Ki,
@@ -8414,13 +8812,13 @@ var HDWallet = class {
8414
8812
  */
8415
8813
  toExtendedKey(isPublic = false, testnet = false) {
8416
8814
  if (this.depth >= 256) {
8417
- throw new FuelError19(
8815
+ throw new FuelError21(
8418
8816
  ErrorCode19.HD_WALLET_ERROR,
8419
8817
  `Exceeded max depth of 255. Current depth: ${this.depth}.`
8420
8818
  );
8421
8819
  }
8422
8820
  const prefix = getExtendedKeyPrefix(this.privateKey == null || isPublic, testnet);
8423
- const depth = hexlify18(Uint8Array.from([this.depth]));
8821
+ const depth = hexlify20(Uint8Array.from([this.depth]));
8424
8822
  const parentFingerprint = this.parentFingerprint;
8425
8823
  const index = toHex(this.index, 4);
8426
8824
  const chainCode = this.chainCode;
@@ -8442,29 +8840,29 @@ var HDWallet = class {
8442
8840
  });
8443
8841
  }
8444
8842
  static fromExtendedKey(extendedKey) {
8445
- const decoded = hexlify18(toBytes2(decodeBase58(extendedKey)));
8843
+ const decoded = hexlify20(toBytes2(decodeBase58(extendedKey)));
8446
8844
  const bytes = arrayify18(decoded);
8447
8845
  const validChecksum = base58check(bytes.slice(0, 78)) === extendedKey;
8448
8846
  if (bytes.length !== 82 || !isValidExtendedKey(bytes)) {
8449
- throw new FuelError19(ErrorCode19.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
8847
+ throw new FuelError21(ErrorCode19.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
8450
8848
  }
8451
8849
  if (!validChecksum) {
8452
- throw new FuelError19(ErrorCode19.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
8850
+ throw new FuelError21(ErrorCode19.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
8453
8851
  }
8454
8852
  const depth = bytes[4];
8455
- const parentFingerprint = hexlify18(bytes.slice(5, 9));
8456
- const index = parseInt(hexlify18(bytes.slice(9, 13)).substring(2), 16);
8457
- const chainCode = hexlify18(bytes.slice(13, 45));
8853
+ const parentFingerprint = hexlify20(bytes.slice(5, 9));
8854
+ const index = parseInt(hexlify20(bytes.slice(9, 13)).substring(2), 16);
8855
+ const chainCode = hexlify20(bytes.slice(13, 45));
8458
8856
  const key = bytes.slice(45, 78);
8459
8857
  if (depth === 0 && parentFingerprint !== "0x00000000" || depth === 0 && index !== 0) {
8460
- throw new FuelError19(
8858
+ throw new FuelError21(
8461
8859
  ErrorCode19.HD_WALLET_ERROR,
8462
8860
  "Inconsistency detected: Depth is zero but fingerprint/index is non-zero."
8463
8861
  );
8464
8862
  }
8465
8863
  if (isPublicExtendedKey(bytes)) {
8466
8864
  if (key[0] !== 3) {
8467
- throw new FuelError19(ErrorCode19.HD_WALLET_ERROR, "Invalid public extended key.");
8865
+ throw new FuelError21(ErrorCode19.HD_WALLET_ERROR, "Invalid public extended key.");
8468
8866
  }
8469
8867
  return new HDWallet({
8470
8868
  publicKey: key,
@@ -8475,7 +8873,7 @@ var HDWallet = class {
8475
8873
  });
8476
8874
  }
8477
8875
  if (key[0] !== 0) {
8478
- throw new FuelError19(ErrorCode19.HD_WALLET_ERROR, "Invalid private extended key.");
8876
+ throw new FuelError21(ErrorCode19.HD_WALLET_ERROR, "Invalid private extended key.");
8479
8877
  }
8480
8878
  return new HDWallet({
8481
8879
  privateKey: key.slice(1),
@@ -8640,292 +9038,7 @@ __publicField(Wallet, "fromExtendedKey", WalletUnlocked.fromExtendedKey);
8640
9038
  */
8641
9039
  __publicField(Wallet, "fromEncryptedJson", WalletUnlocked.fromEncryptedJson);
8642
9040
 
8643
- // src/test-utils/seedTestWallet.ts
8644
- import { randomBytes as randomBytes6 } from "@fuel-ts/crypto";
8645
- var seedTestWallet = async (wallet, quantities, utxosAmount = 1) => {
8646
- const accountsToBeFunded = Array.isArray(wallet) ? wallet : [wallet];
8647
- const [{ provider }] = accountsToBeFunded;
8648
- const genesisWallet = new WalletUnlocked(process.env.GENESIS_SECRET || randomBytes6(32), provider);
8649
- const request = new ScriptTransactionRequest();
8650
- quantities.map(coinQuantityfy).forEach(
8651
- ({ amount, assetId }) => accountsToBeFunded.forEach(({ address }) => {
8652
- for (let i = 0; i < utxosAmount; i++) {
8653
- request.addCoinOutput(address, amount.div(utxosAmount), assetId);
8654
- }
8655
- })
8656
- );
8657
- const txCost = await genesisWallet.provider.getTransactionCost(request);
8658
- request.gasLimit = txCost.gasUsed;
8659
- request.maxFee = txCost.maxFee;
8660
- await genesisWallet.fund(request, txCost);
8661
- await genesisWallet.sendTransaction(request, { awaitExecution: true });
8662
- };
8663
-
8664
- // src/test-utils/generateTestWallet.ts
8665
- var generateTestWallet = async (provider, quantities) => {
8666
- const wallet = Wallet.generate({ provider });
8667
- if (quantities) {
8668
- await seedTestWallet(wallet, quantities);
8669
- }
8670
- return wallet;
8671
- };
8672
-
8673
- // src/test-utils/launchNode.ts
8674
- import { BYTES_32 as BYTES_322 } from "@fuel-ts/abi-coder";
8675
- import { randomBytes as randomBytes7 } from "@fuel-ts/crypto";
8676
- import { FuelError as FuelError20 } from "@fuel-ts/errors";
8677
- import { defaultConsensusKey, hexlify as hexlify19, defaultSnapshotConfigs } from "@fuel-ts/utils";
8678
- import { randomUUID } from "crypto";
8679
- import { existsSync, mkdirSync, rmSync, writeFileSync } from "fs";
8680
- import os from "os";
8681
- import path from "path";
8682
- import { getPortPromise } from "portfinder";
8683
- var getFlagValueFromArgs = (args, flag) => {
8684
- const flagIndex = args.indexOf(flag);
8685
- if (flagIndex === -1) {
8686
- return void 0;
8687
- }
8688
- return args[flagIndex + 1];
8689
- };
8690
- var extractRemainingArgs = (args, flagsToRemove) => {
8691
- const newArgs = [...args];
8692
- flagsToRemove.forEach((flag) => {
8693
- const flagIndex = newArgs.indexOf(flag);
8694
- if (flagIndex !== -1) {
8695
- newArgs.splice(flagIndex, 2);
8696
- }
8697
- });
8698
- return newArgs;
8699
- };
8700
- function getFinalStateConfigJSON({ stateConfig, chainConfig }) {
8701
- const defaultCoins = defaultSnapshotConfigs.stateConfig.coins.map((coin) => ({
8702
- ...coin,
8703
- amount: "18446744073709551615"
8704
- }));
8705
- const defaultMessages = defaultSnapshotConfigs.stateConfig.messages.map((message) => ({
8706
- ...message,
8707
- amount: "18446744073709551615"
8708
- }));
8709
- const coins = defaultCoins.concat(stateConfig.coins.map((coin) => ({ ...coin, amount: coin.amount.toString() }))).filter((coin, index, self) => self.findIndex((c) => c.tx_id === coin.tx_id) === index);
8710
- const messages = defaultMessages.concat(stateConfig.messages.map((msg) => ({ ...msg, amount: msg.amount.toString() }))).filter((msg, index, self) => self.findIndex((m) => m.nonce === msg.nonce) === index);
8711
- if (!process.env.GENESIS_SECRET) {
8712
- const pk = Signer.generatePrivateKey();
8713
- const signer = new Signer(pk);
8714
- process.env.GENESIS_SECRET = hexlify19(pk);
8715
- coins.push({
8716
- tx_id: hexlify19(randomBytes7(BYTES_322)),
8717
- owner: signer.address.toHexString(),
8718
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
8719
- amount: "18446744073709551615",
8720
- asset_id: chainConfig.consensus_parameters.V1.base_asset_id,
8721
- output_index: 0,
8722
- tx_pointer_block_height: 0,
8723
- tx_pointer_tx_idx: 0
8724
- });
8725
- }
8726
- const json = JSON.stringify({
8727
- ...stateConfig,
8728
- coins,
8729
- messages
8730
- });
8731
- const regexMakeNumber = /("amount":)"(\d+)"/gm;
8732
- return json.replace(regexMakeNumber, "$1$2");
8733
- }
8734
- var launchNode = async ({
8735
- ip,
8736
- port,
8737
- args = [],
8738
- fuelCorePath = process.env.FUEL_CORE_PATH || void 0,
8739
- loggingEnabled = true,
8740
- basePath,
8741
- snapshotConfig = defaultSnapshotConfigs
8742
- } = {}) => (
8743
- // eslint-disable-next-line no-async-promise-executor
8744
- new Promise(async (resolve, reject) => {
8745
- const remainingArgs = extractRemainingArgs(args, [
8746
- "--snapshot",
8747
- "--consensus-key",
8748
- "--db-type",
8749
- "--poa-instant"
8750
- ]);
8751
- const snapshotDir = getFlagValueFromArgs(args, "--snapshot");
8752
- const consensusKey = getFlagValueFromArgs(args, "--consensus-key") || defaultConsensusKey;
8753
- const dbTypeFlagValue = getFlagValueFromArgs(args, "--db-type");
8754
- const useInMemoryDb = dbTypeFlagValue === "in-memory" || dbTypeFlagValue === void 0;
8755
- const poaInstantFlagValue = getFlagValueFromArgs(args, "--poa-instant");
8756
- const poaInstant = poaInstantFlagValue === "true" || poaInstantFlagValue === void 0;
8757
- const nativeExecutorVersion = getFlagValueFromArgs(args, "--native-executor-version") || "0";
8758
- const graphQLStartSubstring = "Binding GraphQL provider to";
8759
- const command = fuelCorePath || "fuel-core";
8760
- const ipToUse = ip || "0.0.0.0";
8761
- const portToUse = port || (await getPortPromise({
8762
- port: 4e3,
8763
- // tries 4000 first, then 4001, then 4002, etc.
8764
- stopPort: 5e3
8765
- // don't try ports above 5000
8766
- })).toString();
8767
- let snapshotDirToUse;
8768
- const prefix = basePath || os.tmpdir();
8769
- const suffix = basePath ? "" : randomUUID();
8770
- const tempDir = path.join(prefix, ".fuels", suffix, "snapshotDir");
8771
- if (snapshotDir) {
8772
- snapshotDirToUse = snapshotDir;
8773
- } else {
8774
- if (!existsSync(tempDir)) {
8775
- mkdirSync(tempDir, { recursive: true });
8776
- }
8777
- const { metadata } = snapshotConfig;
8778
- const metadataPath = path.join(tempDir, "metadata.json");
8779
- const chainConfigPath = path.join(tempDir, metadata.chain_config);
8780
- const stateConfigPath = path.join(tempDir, metadata.table_encoding.Json.filepath);
8781
- const stateTransitionPath = path.join(tempDir, "state_transition_bytecode.wasm");
8782
- writeFileSync(chainConfigPath, JSON.stringify(snapshotConfig.chainConfig), "utf8");
8783
- writeFileSync(stateConfigPath, getFinalStateConfigJSON(snapshotConfig), "utf8");
8784
- writeFileSync(metadataPath, JSON.stringify(metadata), "utf8");
8785
- writeFileSync(stateTransitionPath, JSON.stringify(""));
8786
- snapshotDirToUse = tempDir;
8787
- }
8788
- const { spawn } = await import("child_process");
8789
- const child = spawn(
8790
- command,
8791
- [
8792
- "run",
8793
- ["--ip", ipToUse],
8794
- ["--port", portToUse],
8795
- useInMemoryDb ? ["--db-type", "in-memory"] : ["--db-path", tempDir],
8796
- ["--min-gas-price", "1"],
8797
- poaInstant ? ["--poa-instant", "true"] : [],
8798
- ["--native-executor-version", nativeExecutorVersion],
8799
- ["--consensus-key", consensusKey],
8800
- ["--snapshot", snapshotDirToUse],
8801
- "--vm-backtrace",
8802
- "--utxo-validation",
8803
- "--debug",
8804
- ...remainingArgs
8805
- ].flat(),
8806
- { stdio: "pipe", detached: true }
8807
- );
8808
- if (loggingEnabled) {
8809
- child.stderr.on("data", (chunk) => {
8810
- console.log(chunk.toString());
8811
- });
8812
- }
8813
- const removeSideffects = () => {
8814
- child.stderr.removeAllListeners();
8815
- if (existsSync(tempDir)) {
8816
- rmSync(tempDir, { recursive: true });
8817
- }
8818
- };
8819
- child.on("error", removeSideffects);
8820
- child.on("exit", removeSideffects);
8821
- const childState = {
8822
- isDead: false
8823
- };
8824
- const cleanup = () => {
8825
- if (childState.isDead) {
8826
- return;
8827
- }
8828
- childState.isDead = true;
8829
- removeSideffects();
8830
- if (child.pid !== void 0) {
8831
- try {
8832
- process.kill(-child.pid);
8833
- } catch (e) {
8834
- const error = e;
8835
- if (error.code === "ESRCH") {
8836
- console.log(
8837
- `fuel-core node under pid ${child.pid} does not exist. The node might have been killed before cleanup was called. Exiting cleanly.`
8838
- );
8839
- } else {
8840
- throw e;
8841
- }
8842
- }
8843
- } else {
8844
- console.error("No PID available for the child process, unable to kill launched node");
8845
- }
8846
- };
8847
- child.stderr.on("data", (chunk) => {
8848
- const text = typeof chunk === "string" ? chunk : chunk.toString();
8849
- if (text.indexOf(graphQLStartSubstring) !== -1) {
8850
- const rows = text.split("\n");
8851
- const rowWithUrl = rows.find((row) => row.indexOf(graphQLStartSubstring) !== -1);
8852
- const [realIp, realPort] = rowWithUrl.split(" ").at(-1).trim().split(":");
8853
- resolve({
8854
- cleanup,
8855
- ip: realIp,
8856
- port: realPort,
8857
- url: `http://${realIp}:${realPort}/v1/graphql`,
8858
- snapshotDir: snapshotDirToUse,
8859
- pid: child.pid
8860
- });
8861
- }
8862
- if (/error/i.test(text)) {
8863
- console.log(text);
8864
- reject(new FuelError20(FuelError20.CODES.NODE_LAUNCH_FAILED, text));
8865
- }
8866
- });
8867
- process.on("exit", cleanup);
8868
- process.on("SIGINT", cleanup);
8869
- process.on("SIGUSR1", cleanup);
8870
- process.on("SIGUSR2", cleanup);
8871
- process.on("beforeExit", cleanup);
8872
- process.on("uncaughtException", cleanup);
8873
- child.on("error", reject);
8874
- })
8875
- );
8876
- var generateWallets = async (count, provider) => {
8877
- const baseAssetId = provider.getBaseAssetId();
8878
- const wallets = [];
8879
- for (let i = 0; i < count; i += 1) {
8880
- const wallet = await generateTestWallet(provider, [[1e5, baseAssetId]]);
8881
- wallets.push(wallet);
8882
- }
8883
- return wallets;
8884
- };
8885
- var launchNodeAndGetWallets = async ({
8886
- launchNodeOptions,
8887
- walletCount = 10
8888
- } = {}) => {
8889
- const { cleanup: closeNode, ip, port } = await launchNode(launchNodeOptions || {});
8890
- const provider = await Provider.create(`http://${ip}:${port}/v1/graphql`);
8891
- const wallets = await generateWallets(walletCount, provider);
8892
- const cleanup = () => {
8893
- closeNode();
8894
- };
8895
- return { wallets, stop: cleanup, provider };
8896
- };
8897
-
8898
- // src/test-utils/setup-test-provider-and-wallets.ts
8899
- import { defaultSnapshotConfigs as defaultSnapshotConfigs3 } from "@fuel-ts/utils";
8900
- import { mergeDeepRight } from "ramda";
8901
-
8902
- // src/test-utils/asset-id.ts
8903
- import { randomBytes as randomBytes8 } from "@fuel-ts/crypto";
8904
- import { hexlify as hexlify20 } from "@fuel-ts/utils";
8905
- var _AssetId = class {
8906
- constructor(value) {
8907
- this.value = value;
8908
- }
8909
- static random(count = 1) {
8910
- const assetIds = [];
8911
- for (let i = 0; i < count; i++) {
8912
- assetIds.push(new _AssetId(hexlify20(randomBytes8(32))));
8913
- }
8914
- return assetIds;
8915
- }
8916
- };
8917
- var AssetId = _AssetId;
8918
- __publicField(AssetId, "A", new _AssetId(
8919
- "0x0101010101010101010101010101010101010101010101010101010101010101"
8920
- ));
8921
- __publicField(AssetId, "B", new _AssetId(
8922
- "0x0202020202020202020202020202020202020202020202020202020202020202"
8923
- ));
8924
-
8925
9041
  // src/test-utils/wallet-config.ts
8926
- import { randomBytes as randomBytes9 } from "@fuel-ts/crypto";
8927
- import { FuelError as FuelError21 } from "@fuel-ts/errors";
8928
- import { defaultSnapshotConfigs as defaultSnapshotConfigs2, hexlify as hexlify21 } from "@fuel-ts/utils";
8929
9042
  var WalletsConfig = class {
8930
9043
  initialState;
8931
9044
  options;
@@ -8933,7 +9046,7 @@ var WalletsConfig = class {
8933
9046
  generateWallets = () => {
8934
9047
  const generatedWallets = [];
8935
9048
  for (let index = 1; index <= this.options.count; index++) {
8936
- generatedWallets.push(new WalletUnlocked(randomBytes9(32)));
9049
+ generatedWallets.push(new WalletUnlocked(randomBytes8(32)));
8937
9050
  }
8938
9051
  return generatedWallets;
8939
9052
  };
@@ -8978,7 +9091,7 @@ var WalletsConfig = class {
8978
9091
  if (Array.isArray(assets2)) {
8979
9092
  assetIds = assetIds.concat(assets2.map((a) => a.value));
8980
9093
  } else {
8981
- assetIds = assetIds.concat(AssetId.random(assets2 - 1).map((a) => a.value));
9094
+ assetIds = assetIds.concat(TestAssetId.random(assets2 - 1).map((a) => a.value));
8982
9095
  }
8983
9096
  wallets.map((wallet) => wallet.address.toHexString()).forEach((walletAddress) => {
8984
9097
  assetIds.forEach((assetId) => {
@@ -8990,7 +9103,7 @@ var WalletsConfig = class {
8990
9103
  tx_pointer_block_height: 0,
8991
9104
  tx_pointer_tx_idx: 0,
8992
9105
  output_index: 0,
8993
- tx_id: hexlify21(randomBytes9(32))
9106
+ tx_id: hexlify21(randomBytes8(32))
8994
9107
  });
8995
9108
  }
8996
9109
  });
@@ -9004,27 +9117,27 @@ var WalletsConfig = class {
9004
9117
  amountPerCoin
9005
9118
  }) {
9006
9119
  if (Array.isArray(wallets) && wallets.length === 0 || typeof wallets === "number" && wallets <= 0) {
9007
- throw new FuelError21(
9008
- FuelError21.CODES.INVALID_INPUT_PARAMETERS,
9120
+ throw new FuelError22(
9121
+ FuelError22.CODES.INVALID_INPUT_PARAMETERS,
9009
9122
  "Number of wallets must be greater than zero."
9010
9123
  );
9011
9124
  }
9012
9125
  if (Array.isArray(assets2) && assets2.length === 0 || typeof assets2 === "number" && assets2 <= 0) {
9013
- throw new FuelError21(
9014
- FuelError21.CODES.INVALID_INPUT_PARAMETERS,
9126
+ throw new FuelError22(
9127
+ FuelError22.CODES.INVALID_INPUT_PARAMETERS,
9015
9128
  "Number of assets per wallet must be greater than zero."
9016
9129
  );
9017
9130
  }
9018
9131
  if (coinsPerAsset <= 0) {
9019
- throw new FuelError21(
9020
- FuelError21.CODES.INVALID_INPUT_PARAMETERS,
9132
+ throw new FuelError22(
9133
+ FuelError22.CODES.INVALID_INPUT_PARAMETERS,
9021
9134
  "Number of coins per asset must be greater than zero."
9022
9135
  );
9023
9136
  }
9024
- if (amountPerCoin <= 0) {
9025
- throw new FuelError21(
9026
- FuelError21.CODES.INVALID_INPUT_PARAMETERS,
9027
- "Amount per coin must be greater than zero."
9137
+ if (amountPerCoin < 0) {
9138
+ throw new FuelError22(
9139
+ FuelError22.CODES.INVALID_INPUT_PARAMETERS,
9140
+ "Amount per coin must be greater than or equal to zero."
9028
9141
  );
9029
9142
  }
9030
9143
  }
@@ -9033,7 +9146,7 @@ var WalletsConfig = class {
9033
9146
  // src/test-utils/setup-test-provider-and-wallets.ts
9034
9147
  var defaultWalletConfigOptions = {
9035
9148
  count: 2,
9036
- assets: [AssetId.A, AssetId.B],
9149
+ assets: [TestAssetId.A, TestAssetId.B],
9037
9150
  coinsPerAsset: 1,
9038
9151
  amountPerCoin: 1e10,
9039
9152
  messages: []
@@ -9059,7 +9172,7 @@ async function setupTestProviderAndWallets({
9059
9172
  defaultSnapshotConfigs3,
9060
9173
  walletsConfig.apply(nodeOptions?.snapshotConfig)
9061
9174
  ),
9062
- port: "0"
9175
+ port: nodeOptions.port || "0"
9063
9176
  };
9064
9177
  let cleanup;
9065
9178
  let url;
@@ -9095,7 +9208,7 @@ async function setupTestProviderAndWallets({
9095
9208
 
9096
9209
  // src/test-utils/test-message.ts
9097
9210
  import { Address as Address6 } from "@fuel-ts/address";
9098
- import { randomBytes as randomBytes10 } from "@fuel-ts/crypto";
9211
+ import { randomBytes as randomBytes9 } from "@fuel-ts/crypto";
9099
9212
  import { bn as bn21 } from "@fuel-ts/math";
9100
9213
  import { hexlify as hexlify22 } from "@fuel-ts/utils";
9101
9214
  var TestMessage = class {
@@ -9114,9 +9227,10 @@ var TestMessage = class {
9114
9227
  constructor({
9115
9228
  sender = Address6.fromRandom(),
9116
9229
  recipient = Address6.fromRandom(),
9117
- nonce = hexlify22(randomBytes10(32)),
9230
+ nonce = hexlify22(randomBytes9(32)),
9118
9231
  amount = 1e6,
9119
- data = "02",
9232
+ data = "",
9233
+ // Will default to empty data in order to be a spendable message
9120
9234
  da_height = 0
9121
9235
  } = {}) {
9122
9236
  this.sender = sender;
@@ -9127,24 +9241,22 @@ var TestMessage = class {
9127
9241
  this.da_height = da_height;
9128
9242
  }
9129
9243
  toChainMessage(recipient) {
9244
+ const data = /^0x/.test(this.data) ? this.data.replace(/^0x/, "") : this.data;
9130
9245
  return {
9131
9246
  sender: this.sender.toB256(),
9132
9247
  recipient: recipient?.toB256() ?? this.recipient.toB256(),
9133
9248
  nonce: this.nonce,
9134
9249
  amount: bn21(this.amount).toNumber(),
9135
- data: this.data,
9250
+ data,
9136
9251
  da_height: this.da_height
9137
9252
  };
9138
9253
  }
9139
9254
  };
9140
9255
  export {
9141
- AssetId,
9256
+ TestAssetId,
9142
9257
  TestMessage,
9143
9258
  WalletsConfig,
9144
- generateTestWallet,
9145
9259
  launchNode,
9146
- launchNodeAndGetWallets,
9147
- seedTestWallet,
9148
9260
  setupTestProviderAndWallets
9149
9261
  };
9150
9262
  //# sourceMappingURL=test-utils.mjs.map