@fuel-ts/account 0.92.1 → 0.94.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) 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 -1
  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 +1645 -985
  19. package/dist/index.global.js.map +1 -1
  20. package/dist/index.js +1034 -673
  21. package/dist/index.js.map +1 -1
  22. package/dist/index.mjs +771 -423
  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 +614 -1
  27. package/dist/providers/__generated__/operations.d.ts.map +1 -1
  28. package/dist/providers/fuel-graphql-subscriber.d.ts +3 -3
  29. package/dist/providers/fuel-graphql-subscriber.d.ts.map +1 -1
  30. package/dist/providers/provider.d.ts +19 -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 +10 -5
  45. package/dist/providers/transaction-response/transaction-response.d.ts.map +1 -1
  46. package/dist/providers/transaction-summary/assemble-transaction-summary.d.ts +1 -1
  47. package/dist/providers/transaction-summary/assemble-transaction-summary.d.ts.map +1 -1
  48. package/dist/providers/transaction-summary/call.d.ts +4 -3
  49. package/dist/providers/transaction-summary/call.d.ts.map +1 -1
  50. package/dist/providers/transaction-summary/get-transaction-summary.d.ts.map +1 -1
  51. package/dist/providers/transaction-summary/input.d.ts +6 -1
  52. package/dist/providers/transaction-summary/input.d.ts.map +1 -1
  53. package/dist/providers/transaction-summary/operations.d.ts +4 -2
  54. package/dist/providers/transaction-summary/operations.d.ts.map +1 -1
  55. package/dist/providers/transaction-summary/types.d.ts +5 -2
  56. package/dist/providers/transaction-summary/types.d.ts.map +1 -1
  57. package/dist/providers/utils/gas.d.ts +6 -0
  58. package/dist/providers/utils/gas.d.ts.map +1 -1
  59. package/dist/test-utils/launchNode.d.ts +0 -16
  60. package/dist/test-utils/launchNode.d.ts.map +1 -1
  61. package/dist/test-utils/setup-test-provider-and-wallets.d.ts.map +1 -1
  62. package/dist/test-utils/test-asset-id.d.ts +8 -0
  63. package/dist/test-utils/test-asset-id.d.ts.map +1 -0
  64. package/dist/test-utils/test-message.d.ts +4 -2
  65. package/dist/test-utils/test-message.d.ts.map +1 -1
  66. package/dist/test-utils/wallet-config.d.ts +3 -3
  67. package/dist/test-utils/wallet-config.d.ts.map +1 -1
  68. package/dist/test-utils.d.ts +1 -3
  69. package/dist/test-utils.d.ts.map +1 -1
  70. package/dist/test-utils.global.js +43613 -42984
  71. package/dist/test-utils.global.js.map +1 -1
  72. package/dist/test-utils.js +1560 -1271
  73. package/dist/test-utils.js.map +1 -1
  74. package/dist/test-utils.mjs +1282 -994
  75. package/dist/test-utils.mjs.map +1 -1
  76. package/dist/wallet/base-wallet-unlocked.d.ts +1 -2
  77. package/dist/wallet/base-wallet-unlocked.d.ts.map +1 -1
  78. package/dist/wallet/keystore-wallet.d.ts.map +1 -1
  79. package/package.json +19 -21
  80. package/dist/providers/memory-cache.d.ts +0 -11
  81. package/dist/providers/memory-cache.d.ts.map +0 -1
  82. package/dist/test-utils/asset-id.d.ts +0 -8
  83. package/dist/test-utils/asset-id.d.ts.map +0 -1
  84. package/dist/test-utils/generateTestWallet.d.ts +0 -4
  85. package/dist/test-utils/generateTestWallet.d.ts.map +0 -1
  86. package/dist/test-utils/seedTestWallet.d.ts +0 -4
  87. package/dist/test-utils/seedTestWallet.d.ts.map +0 -1
@@ -18,23 +18,336 @@ 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
+ setTimeout(
315
+ () => (
316
+ // Resolve with the cleanup method.
317
+ resolve({
318
+ cleanup,
319
+ ip: realIp,
320
+ port: realPort,
321
+ url: `http://${realIp}:${realPort}/v1/graphql`,
322
+ snapshotDir: snapshotDirToUse,
323
+ pid: child.pid
324
+ })
325
+ ),
326
+ 500
327
+ );
328
+ }
329
+ if (/error/i.test(text)) {
330
+ console.log(text);
331
+ reject(new FuelError(FuelError.CODES.NODE_LAUNCH_FAILED, text));
332
+ }
333
+ });
334
+ process.on("exit", cleanup);
335
+ process.on("SIGINT", cleanup);
336
+ process.on("SIGUSR1", cleanup);
337
+ process.on("SIGUSR2", cleanup);
338
+ process.on("beforeExit", cleanup);
339
+ process.on("uncaughtException", cleanup);
340
+ child.on("error", reject);
341
+ })
342
+ );
343
+
344
+ // src/test-utils/setup-test-provider-and-wallets.ts
345
+ import { defaultSnapshotConfigs as defaultSnapshotConfigs3 } from "@fuel-ts/utils";
346
+ import { mergeDeepRight } from "ramda";
34
347
 
35
348
  // src/providers/coin-quantity.ts
36
349
  import { bn } from "@fuel-ts/math";
37
- import { hexlify } from "@fuel-ts/utils";
350
+ import { hexlify as hexlify3 } from "@fuel-ts/utils";
38
351
  var coinQuantityfy = (coinQuantityLike) => {
39
352
  let assetId;
40
353
  let amount;
@@ -50,7 +363,7 @@ var coinQuantityfy = (coinQuantityLike) => {
50
363
  }
51
364
  const bnAmount = bn(amount);
52
365
  return {
53
- assetId: hexlify(assetId),
366
+ assetId: hexlify3(assetId),
54
367
  amount: bnAmount.lt(1) ? bn(1) : bnAmount,
55
368
  max: max ? bn(max) : void 0
56
369
  };
@@ -68,31 +381,18 @@ var addAmountToCoinQuantities = (params) => {
68
381
  };
69
382
 
70
383
  // 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";
73
- 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";
384
+ import { Address as Address3 } from "@fuel-ts/address";
385
+ import { ErrorCode as ErrorCode13, FuelError as FuelError15 } from "@fuel-ts/errors";
386
+ import { BN as BN2, bn as bn17 } from "@fuel-ts/math";
387
+ import { InputType as InputType7, InputMessageCoder, TransactionCoder as TransactionCoder5 } from "@fuel-ts/transactions";
388
+ import { arrayify as arrayify12, hexlify as hexlify14, DateTime as DateTime2, isDefined as isDefined2 } from "@fuel-ts/utils";
81
389
  import { checkFuelCoreVersionCompatibility } from "@fuel-ts/versions";
82
390
  import { equalBytes } from "@noble/curves/abstract/utils";
83
391
  import { GraphQLClient } from "graphql-request";
84
- import { clone as clone3 } from "ramda";
85
-
86
- // src/providers/__generated__/operations.ts
87
- import gql from "graphql-tag";
88
- var TransactionStatusSubscriptionFragmentDoc = gql`
89
- fragment transactionStatusSubscriptionFragment on TransactionStatus {
90
- type: __typename
91
- ... on SqueezedOutStatus {
92
- reason
93
- }
94
- }
95
- `;
392
+ import { clone as clone3 } from "ramda";
393
+
394
+ // src/providers/__generated__/operations.ts
395
+ import gql from "graphql-tag";
96
396
  var SubmittedStatusFragmentDoc = gql`
97
397
  fragment SubmittedStatusFragment on SubmittedStatus {
98
398
  type: __typename
@@ -149,6 +449,47 @@ var SuccessStatusFragmentDoc = gql`
149
449
  totalFee
150
450
  }
151
451
  ${ReceiptFragmentDoc}`;
452
+ var MalleableTransactionFieldsFragmentDoc = gql`
453
+ fragment malleableTransactionFieldsFragment on Transaction {
454
+ receiptsRoot
455
+ inputs {
456
+ type: __typename
457
+ ... on InputCoin {
458
+ txPointer
459
+ }
460
+ ... on InputContract {
461
+ txPointer
462
+ }
463
+ }
464
+ outputs {
465
+ type: __typename
466
+ ... on CoinOutput {
467
+ to
468
+ amount
469
+ assetId
470
+ }
471
+ ... on ContractOutput {
472
+ inputIndex
473
+ balanceRoot
474
+ stateRoot
475
+ }
476
+ ... on ChangeOutput {
477
+ to
478
+ amount
479
+ assetId
480
+ }
481
+ ... on VariableOutput {
482
+ to
483
+ amount
484
+ assetId
485
+ }
486
+ ... on ContractCreated {
487
+ contract
488
+ stateRoot
489
+ }
490
+ }
491
+ }
492
+ `;
152
493
  var FailureStatusFragmentDoc = gql`
153
494
  fragment FailureStatusFragment on FailureStatus {
154
495
  type: __typename
@@ -170,6 +511,32 @@ var SqueezedOutStatusFragmentDoc = gql`
170
511
  reason
171
512
  }
172
513
  `;
514
+ var TransactionStatusSubscriptionFragmentDoc = gql`
515
+ fragment transactionStatusSubscriptionFragment on TransactionStatus {
516
+ ... on SubmittedStatus {
517
+ ...SubmittedStatusFragment
518
+ }
519
+ ... on SuccessStatus {
520
+ ...SuccessStatusFragment
521
+ transaction {
522
+ ...malleableTransactionFieldsFragment
523
+ }
524
+ }
525
+ ... on FailureStatus {
526
+ ...FailureStatusFragment
527
+ transaction {
528
+ ...malleableTransactionFieldsFragment
529
+ }
530
+ }
531
+ ... on SqueezedOutStatus {
532
+ ...SqueezedOutStatusFragment
533
+ }
534
+ }
535
+ ${SubmittedStatusFragmentDoc}
536
+ ${SuccessStatusFragmentDoc}
537
+ ${MalleableTransactionFieldsFragmentDoc}
538
+ ${FailureStatusFragmentDoc}
539
+ ${SqueezedOutStatusFragmentDoc}`;
173
540
  var TransactionStatusFragmentDoc = gql`
174
541
  fragment transactionStatusFragment on TransactionStatus {
175
542
  ... on SubmittedStatus {
@@ -510,6 +877,12 @@ var GasCostsFragmentDoc = gql`
510
877
  alocDependentCost {
511
878
  ...DependentCostFragment
512
879
  }
880
+ bldd {
881
+ ...DependentCostFragment
882
+ }
883
+ bsiz {
884
+ ...DependentCostFragment
885
+ }
513
886
  cfe {
514
887
  ...DependentCostFragment
515
888
  }
@@ -528,6 +901,9 @@ var GasCostsFragmentDoc = gql`
528
901
  csiz {
529
902
  ...DependentCostFragment
530
903
  }
904
+ ed19DependentCost {
905
+ ...DependentCostFragment
906
+ }
531
907
  k256 {
532
908
  ...DependentCostFragment
533
909
  }
@@ -1056,15 +1432,14 @@ function getSdk(requester) {
1056
1432
  }
1057
1433
 
1058
1434
  // src/providers/fuel-graphql-subscriber.ts
1059
- import { ErrorCode, FuelError } from "@fuel-ts/errors";
1435
+ import { ErrorCode, FuelError as FuelError2 } from "@fuel-ts/errors";
1060
1436
  import { print } from "graphql";
1061
1437
  var _FuelGraphqlSubscriber = class {
1062
- constructor(options) {
1063
- this.options = options;
1438
+ constructor(stream) {
1439
+ this.stream = stream;
1064
1440
  }
1065
- stream;
1066
- async setStream() {
1067
- const { url, query, variables, fetchFn } = this.options;
1441
+ static async create(options) {
1442
+ const { url, query, variables, fetchFn } = options;
1068
1443
  const response = await fetchFn(`${url}-sub`, {
1069
1444
  method: "POST",
1070
1445
  body: JSON.stringify({
@@ -1076,20 +1451,17 @@ var _FuelGraphqlSubscriber = class {
1076
1451
  Accept: "text/event-stream"
1077
1452
  }
1078
1453
  });
1079
- this.stream = response.body.getReader();
1454
+ return new _FuelGraphqlSubscriber(response.body.getReader());
1080
1455
  }
1081
1456
  events = [];
1082
1457
  parsingLeftover = "";
1083
1458
  async next() {
1084
- if (!this.stream) {
1085
- await this.setStream();
1086
- }
1087
1459
  while (true) {
1088
1460
  if (this.events.length > 0) {
1089
1461
  const { data, errors } = this.events.shift();
1090
1462
  if (Array.isArray(errors)) {
1091
- throw new FuelError(
1092
- FuelError.CODES.INVALID_REQUEST,
1463
+ throw new FuelError2(
1464
+ FuelError2.CODES.INVALID_REQUEST,
1093
1465
  errors.map((err) => err.message).join("\n\n")
1094
1466
  );
1095
1467
  }
@@ -1110,7 +1482,7 @@ var _FuelGraphqlSubscriber = class {
1110
1482
  try {
1111
1483
  this.events.push(JSON.parse(match.replace(/^data:/, "")));
1112
1484
  } catch (e) {
1113
- throw new FuelError(
1485
+ throw new FuelError2(
1114
1486
  ErrorCode.STREAM_PARSING_ERROR,
1115
1487
  `Error while parsing stream data response: ${text}`
1116
1488
  );
@@ -1134,95 +1506,98 @@ var _FuelGraphqlSubscriber = class {
1134
1506
  var FuelGraphqlSubscriber = _FuelGraphqlSubscriber;
1135
1507
  __publicField(FuelGraphqlSubscriber, "textDecoder", new TextDecoder());
1136
1508
 
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 {
1509
+ // src/providers/resource-cache.ts
1510
+ import { ErrorCode as ErrorCode2, FuelError as FuelError3 } from "@fuel-ts/errors";
1511
+ import { hexlify as hexlify4 } from "@fuel-ts/utils";
1512
+ var cache = /* @__PURE__ */ new Map();
1513
+ var ResourceCache = class {
1143
1514
  ttl;
1144
- constructor(ttlInMs = DEFAULT_TTL_IN_MS) {
1145
- this.ttl = ttlInMs;
1146
- if (typeof ttlInMs !== "number" || this.ttl <= 0) {
1147
- throw new FuelError2(
1515
+ constructor(ttl) {
1516
+ this.ttl = ttl;
1517
+ if (typeof ttl !== "number" || this.ttl <= 0) {
1518
+ throw new FuelError3(
1148
1519
  ErrorCode2.INVALID_TTL,
1149
1520
  `Invalid TTL: ${this.ttl}. Use a value greater than zero.`
1150
1521
  );
1151
1522
  }
1152
1523
  }
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
1524
+ // Add resources to the cache
1525
+ set(transactionId, resources) {
1526
+ const currentTime = Date.now();
1527
+ const existingResources = cache.get(transactionId) || {
1528
+ utxos: /* @__PURE__ */ new Set(),
1529
+ messages: /* @__PURE__ */ new Set(),
1530
+ timestamp: currentTime
1169
1531
  };
1170
- return expiresAt;
1532
+ resources.utxos.forEach((utxo) => existingResources.utxos.add(hexlify4(utxo)));
1533
+ resources.messages.forEach((message) => existingResources.messages.add(hexlify4(message)));
1534
+ cache.set(transactionId, existingResources);
1171
1535
  }
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
- }, []);
1536
+ // Remove resources from the cache for a given transaction ID
1537
+ unset(transactionId) {
1538
+ cache.delete(transactionId);
1180
1539
  }
1540
+ // Get all cached resources and remove expired ones
1181
1541
  getActiveData() {
1182
- return Object.keys(cache).reduce((list, key) => {
1183
- const data = this.get(key);
1184
- if (data) {
1185
- list.push(data);
1542
+ const allResources = { utxos: [], messages: [] };
1543
+ const currentTime = Date.now();
1544
+ cache.forEach((resource, transactionId) => {
1545
+ if (currentTime - resource.timestamp < this.ttl) {
1546
+ allResources.utxos.push(...resource.utxos);
1547
+ allResources.messages.push(...resource.messages);
1548
+ } else {
1549
+ cache.delete(transactionId);
1186
1550
  }
1187
- return list;
1188
- }, []);
1551
+ });
1552
+ return allResources;
1553
+ }
1554
+ // Check if a UTXO ID or message nonce is already cached and not expired
1555
+ isCached(key) {
1556
+ const currentTime = Date.now();
1557
+ for (const [transactionId, resourceData] of cache.entries()) {
1558
+ if (currentTime - resourceData.timestamp > this.ttl) {
1559
+ cache.delete(transactionId);
1560
+ } else if (resourceData.utxos.has(key) || resourceData.messages.has(key)) {
1561
+ return true;
1562
+ }
1563
+ }
1564
+ return false;
1189
1565
  }
1190
- del(value) {
1191
- const key = hexlify2(value);
1192
- delete cache[key];
1566
+ clear() {
1567
+ cache.clear();
1193
1568
  }
1194
1569
  };
1195
1570
 
1196
1571
  // src/providers/transaction-request/input.ts
1197
- import { BYTES_32, UTXO_ID_LEN } from "@fuel-ts/abi-coder";
1572
+ import { BYTES_32 as BYTES_322, UTXO_ID_LEN } from "@fuel-ts/abi-coder";
1198
1573
  import { ZeroBytes32 } from "@fuel-ts/address/configs";
1199
- import { ErrorCode as ErrorCode3, FuelError as FuelError3 } from "@fuel-ts/errors";
1574
+ import { ErrorCode as ErrorCode3, FuelError as FuelError4 } from "@fuel-ts/errors";
1200
1575
  import { bn as bn2, toNumber } from "@fuel-ts/math";
1201
1576
  import { InputType } from "@fuel-ts/transactions";
1202
- import { arrayify, hexlify as hexlify3 } from "@fuel-ts/utils";
1577
+ import { arrayify as arrayify2, hexlify as hexlify5 } from "@fuel-ts/utils";
1203
1578
  var inputify = (value) => {
1204
1579
  const { type } = value;
1205
1580
  switch (value.type) {
1206
1581
  case InputType.Coin: {
1207
- const predicate = arrayify(value.predicate ?? "0x");
1208
- const predicateData = arrayify(value.predicateData ?? "0x");
1582
+ const predicate = arrayify2(value.predicate ?? "0x");
1583
+ const predicateData = arrayify2(value.predicateData ?? "0x");
1209
1584
  return {
1210
1585
  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),
1586
+ txID: hexlify5(arrayify2(value.id).slice(0, BYTES_322)),
1587
+ outputIndex: toNumber(arrayify2(value.id).slice(BYTES_322, UTXO_ID_LEN)),
1588
+ owner: hexlify5(value.owner),
1214
1589
  amount: bn2(value.amount),
1215
- assetId: hexlify3(value.assetId),
1590
+ assetId: hexlify5(value.assetId),
1216
1591
  txPointer: {
1217
- blockHeight: toNumber(arrayify(value.txPointer).slice(0, 8)),
1218
- txIndex: toNumber(arrayify(value.txPointer).slice(8, 16))
1592
+ blockHeight: toNumber(arrayify2(value.txPointer).slice(0, 8)),
1593
+ txIndex: toNumber(arrayify2(value.txPointer).slice(8, 16))
1219
1594
  },
1220
1595
  witnessIndex: value.witnessIndex,
1221
1596
  predicateGasUsed: bn2(value.predicateGasUsed),
1222
1597
  predicateLength: bn2(predicate.length),
1223
1598
  predicateDataLength: bn2(predicateData.length),
1224
- predicate: hexlify3(predicate),
1225
- predicateData: hexlify3(predicateData)
1599
+ predicate: hexlify5(predicate),
1600
+ predicateData: hexlify5(predicateData)
1226
1601
  };
1227
1602
  }
1228
1603
  case InputType.Contract: {
@@ -1233,34 +1608,34 @@ var inputify = (value) => {
1233
1608
  balanceRoot: ZeroBytes32,
1234
1609
  stateRoot: ZeroBytes32,
1235
1610
  txPointer: {
1236
- blockHeight: toNumber(arrayify(value.txPointer).slice(0, 8)),
1237
- txIndex: toNumber(arrayify(value.txPointer).slice(8, 16))
1611
+ blockHeight: toNumber(arrayify2(value.txPointer).slice(0, 8)),
1612
+ txIndex: toNumber(arrayify2(value.txPointer).slice(8, 16))
1238
1613
  },
1239
- contractID: hexlify3(value.contractId)
1614
+ contractID: hexlify5(value.contractId)
1240
1615
  };
1241
1616
  }
1242
1617
  case InputType.Message: {
1243
- const predicate = arrayify(value.predicate ?? "0x");
1244
- const predicateData = arrayify(value.predicateData ?? "0x");
1245
- const data = arrayify(value.data ?? "0x");
1618
+ const predicate = arrayify2(value.predicate ?? "0x");
1619
+ const predicateData = arrayify2(value.predicateData ?? "0x");
1620
+ const data = arrayify2(value.data ?? "0x");
1246
1621
  return {
1247
1622
  type: InputType.Message,
1248
- sender: hexlify3(value.sender),
1249
- recipient: hexlify3(value.recipient),
1623
+ sender: hexlify5(value.sender),
1624
+ recipient: hexlify5(value.recipient),
1250
1625
  amount: bn2(value.amount),
1251
- nonce: hexlify3(value.nonce),
1626
+ nonce: hexlify5(value.nonce),
1252
1627
  witnessIndex: value.witnessIndex,
1253
1628
  predicateGasUsed: bn2(value.predicateGasUsed),
1254
1629
  predicateLength: bn2(predicate.length),
1255
1630
  predicateDataLength: bn2(predicateData.length),
1256
- predicate: hexlify3(predicate),
1257
- predicateData: hexlify3(predicateData),
1258
- data: hexlify3(data),
1631
+ predicate: hexlify5(predicate),
1632
+ predicateData: hexlify5(predicateData),
1633
+ data: hexlify5(data),
1259
1634
  dataLength: data.length
1260
1635
  };
1261
1636
  }
1262
1637
  default: {
1263
- throw new FuelError3(
1638
+ throw new FuelError4(
1264
1639
  ErrorCode3.INVALID_TRANSACTION_INPUT,
1265
1640
  `Invalid transaction input type: ${type}.`
1266
1641
  );
@@ -1270,19 +1645,19 @@ var inputify = (value) => {
1270
1645
 
1271
1646
  // src/providers/transaction-request/output.ts
1272
1647
  import { ZeroBytes32 as ZeroBytes322 } from "@fuel-ts/address/configs";
1273
- import { ErrorCode as ErrorCode4, FuelError as FuelError4 } from "@fuel-ts/errors";
1648
+ import { ErrorCode as ErrorCode4, FuelError as FuelError5 } from "@fuel-ts/errors";
1274
1649
  import { bn as bn3 } from "@fuel-ts/math";
1275
1650
  import { OutputType } from "@fuel-ts/transactions";
1276
- import { hexlify as hexlify4 } from "@fuel-ts/utils";
1651
+ import { hexlify as hexlify6 } from "@fuel-ts/utils";
1277
1652
  var outputify = (value) => {
1278
1653
  const { type } = value;
1279
1654
  switch (type) {
1280
1655
  case OutputType.Coin: {
1281
1656
  return {
1282
1657
  type: OutputType.Coin,
1283
- to: hexlify4(value.to),
1658
+ to: hexlify6(value.to),
1284
1659
  amount: bn3(value.amount),
1285
- assetId: hexlify4(value.assetId)
1660
+ assetId: hexlify6(value.assetId)
1286
1661
  };
1287
1662
  }
1288
1663
  case OutputType.Contract: {
@@ -1296,9 +1671,9 @@ var outputify = (value) => {
1296
1671
  case OutputType.Change: {
1297
1672
  return {
1298
1673
  type: OutputType.Change,
1299
- to: hexlify4(value.to),
1674
+ to: hexlify6(value.to),
1300
1675
  amount: bn3(0),
1301
- assetId: hexlify4(value.assetId)
1676
+ assetId: hexlify6(value.assetId)
1302
1677
  };
1303
1678
  }
1304
1679
  case OutputType.Variable: {
@@ -1312,12 +1687,12 @@ var outputify = (value) => {
1312
1687
  case OutputType.ContractCreated: {
1313
1688
  return {
1314
1689
  type: OutputType.ContractCreated,
1315
- contractId: hexlify4(value.contractId),
1316
- stateRoot: hexlify4(value.stateRoot)
1690
+ contractId: hexlify6(value.contractId),
1691
+ stateRoot: hexlify6(value.stateRoot)
1317
1692
  };
1318
1693
  }
1319
1694
  default: {
1320
- throw new FuelError4(
1695
+ throw new FuelError5(
1321
1696
  ErrorCode4.INVALID_TRANSACTION_INPUT,
1322
1697
  `Invalid transaction output type: ${type}.`
1323
1698
  );
@@ -1327,9 +1702,10 @@ var outputify = (value) => {
1327
1702
 
1328
1703
  // src/providers/transaction-request/transaction-request.ts
1329
1704
  import { UTXO_ID_LEN as UTXO_ID_LEN2 } from "@fuel-ts/abi-coder";
1330
- import { Address, addressify } from "@fuel-ts/address";
1705
+ import { Address as Address2, addressify } from "@fuel-ts/address";
1331
1706
  import { ZeroBytes32 as ZeroBytes324 } from "@fuel-ts/address/configs";
1332
- import { randomBytes } from "@fuel-ts/crypto";
1707
+ import { randomBytes as randomBytes3 } from "@fuel-ts/crypto";
1708
+ import { FuelError as FuelError9 } from "@fuel-ts/errors";
1333
1709
  import { bn as bn8 } from "@fuel-ts/math";
1334
1710
  import {
1335
1711
  PolicyType,
@@ -1338,14 +1714,14 @@ import {
1338
1714
  OutputType as OutputType2,
1339
1715
  TransactionType
1340
1716
  } from "@fuel-ts/transactions";
1341
- import { concat, hexlify as hexlify7, isDefined } from "@fuel-ts/utils";
1717
+ import { concat as concat2, hexlify as hexlify9, isDefined } from "@fuel-ts/utils";
1342
1718
 
1343
1719
  // src/providers/resource.ts
1344
1720
  var isCoin = (resource) => "id" in resource;
1345
1721
 
1346
1722
  // src/providers/utils/receipts.ts
1347
1723
  import { ZeroBytes32 as ZeroBytes323 } from "@fuel-ts/address/configs";
1348
- import { ErrorCode as ErrorCode5, FuelError as FuelError5 } from "@fuel-ts/errors";
1724
+ import { ErrorCode as ErrorCode5, FuelError as FuelError6 } from "@fuel-ts/errors";
1349
1725
  import { bn as bn4 } from "@fuel-ts/math";
1350
1726
  import {
1351
1727
  ReceiptBurnCoder,
@@ -1354,7 +1730,7 @@ import {
1354
1730
  ReceiptType
1355
1731
  } from "@fuel-ts/transactions";
1356
1732
  import { FAILED_TRANSFER_TO_ADDRESS_SIGNAL } from "@fuel-ts/transactions/configs";
1357
- import { arrayify as arrayify2 } from "@fuel-ts/utils";
1733
+ import { arrayify as arrayify3 } from "@fuel-ts/utils";
1358
1734
  var doesReceiptHaveMissingOutputVariables = (receipt) => receipt.type === ReceiptType.Revert && receipt.val.toString("hex") === FAILED_TRANSFER_TO_ADDRESS_SIGNAL;
1359
1735
  var doesReceiptHaveMissingContractId = (receipt) => receipt.type === ReceiptType.Panic && receipt.contractId !== "0x0000000000000000000000000000000000000000000000000000000000000000";
1360
1736
  var getReceiptsWithMissingData = (receipts) => receipts.reduce(
@@ -1498,7 +1874,7 @@ function assembleReceiptByType(receipt) {
1498
1874
  const recipient = hexOrZero(receipt.recipient);
1499
1875
  const nonce = hexOrZero(receipt.nonce);
1500
1876
  const amount = bn4(receipt.amount);
1501
- const data = receipt.data ? arrayify2(receipt.data) : Uint8Array.from([]);
1877
+ const data = receipt.data ? arrayify3(receipt.data) : Uint8Array.from([]);
1502
1878
  const digest = hexOrZero(receipt.digest);
1503
1879
  const messageId = ReceiptMessageOutCoder.getMessageId({
1504
1880
  sender,
@@ -1550,17 +1926,17 @@ function assembleReceiptByType(receipt) {
1550
1926
  return burnReceipt;
1551
1927
  }
1552
1928
  default:
1553
- throw new FuelError5(ErrorCode5.INVALID_RECEIPT_TYPE, `Invalid receipt type: ${receiptType}.`);
1929
+ throw new FuelError6(ErrorCode5.INVALID_RECEIPT_TYPE, `Invalid receipt type: ${receiptType}.`);
1554
1930
  }
1555
1931
  }
1556
1932
 
1557
1933
  // src/providers/utils/block-explorer.ts
1558
- import { ErrorCode as ErrorCode6, FuelError as FuelError6 } from "@fuel-ts/errors";
1934
+ import { ErrorCode as ErrorCode6, FuelError as FuelError7 } from "@fuel-ts/errors";
1559
1935
 
1560
1936
  // src/providers/utils/gas.ts
1561
1937
  import { bn as bn5 } from "@fuel-ts/math";
1562
1938
  import { ReceiptType as ReceiptType2 } from "@fuel-ts/transactions";
1563
- import { arrayify as arrayify3 } from "@fuel-ts/utils";
1939
+ import { arrayify as arrayify4 } from "@fuel-ts/utils";
1564
1940
  var getGasUsedFromReceipts = (receipts) => {
1565
1941
  const scriptResult = receipts.filter(
1566
1942
  (receipt) => receipt.type === ReceiptType2.ScriptResult
@@ -1597,7 +1973,7 @@ function gasUsedByInputs(inputs, txBytesSize, gasCosts) {
1597
1973
  const totalGas = chargeableInputs.reduce((total, input) => {
1598
1974
  if ("predicate" in input && input.predicate && input.predicate !== "0x") {
1599
1975
  return total.add(
1600
- vmInitializationCost.add(resolveGasDependentCosts(arrayify3(input.predicate).length, gasCosts.contractRoot)).add(bn5(input.predicateGasUsed))
1976
+ vmInitializationCost.add(resolveGasDependentCosts(arrayify4(input.predicate).length, gasCosts.contractRoot)).add(bn5(input.predicateGasUsed))
1601
1977
  );
1602
1978
  }
1603
1979
  return total.add(gasCosts.ecr1);
@@ -1648,19 +2024,28 @@ function calculateMetadataGasForTxScript({
1648
2024
  }) {
1649
2025
  return resolveGasDependentCosts(txBytesSize, gasCosts.s256);
1650
2026
  }
2027
+ function calculateMetadataGasForTxBlob({
2028
+ gasCosts,
2029
+ txBytesSize,
2030
+ witnessBytesSize
2031
+ }) {
2032
+ const txId = resolveGasDependentCosts(txBytesSize, gasCosts.s256);
2033
+ const blobLen = resolveGasDependentCosts(witnessBytesSize, gasCosts.s256);
2034
+ return txId.add(blobLen);
2035
+ }
1651
2036
  var calculateGasFee = (params) => {
1652
2037
  const { gas, gasPrice, priceFactor, tip } = params;
1653
2038
  return gas.mul(gasPrice).div(priceFactor).add(bn5(tip));
1654
2039
  };
1655
2040
 
1656
2041
  // src/providers/utils/json.ts
1657
- import { hexlify as hexlify5 } from "@fuel-ts/utils";
2042
+ import { hexlify as hexlify7 } from "@fuel-ts/utils";
1658
2043
  import { clone } from "ramda";
1659
2044
  function normalize(object) {
1660
2045
  Object.keys(object).forEach((key) => {
1661
2046
  switch (object[key]?.constructor.name) {
1662
2047
  case "Uint8Array":
1663
- object[key] = hexlify5(object[key]);
2048
+ object[key] = hexlify7(object[key]);
1664
2049
  break;
1665
2050
  case "Array":
1666
2051
  object[key] = normalize(object[key]);
@@ -1685,7 +2070,7 @@ function normalizeJSON(root) {
1685
2070
  }
1686
2071
 
1687
2072
  // src/providers/utils/extract-tx-error.ts
1688
- import { ErrorCode as ErrorCode7, FuelError as FuelError7 } from "@fuel-ts/errors";
2073
+ import { ErrorCode as ErrorCode7, FuelError as FuelError8 } from "@fuel-ts/errors";
1689
2074
  import { bn as bn6 } from "@fuel-ts/math";
1690
2075
  import { ReceiptType as ReceiptType3 } from "@fuel-ts/transactions";
1691
2076
  import {
@@ -1706,7 +2091,7 @@ You can read more about this error at:
1706
2091
 
1707
2092
  ${PANIC_DOC_URL}#variant.${statusReason}`;
1708
2093
  }
1709
- return new FuelError7(ErrorCode7.SCRIPT_REVERTED, errorMessage, {
2094
+ return new FuelError8(ErrorCode7.SCRIPT_REVERTED, errorMessage, {
1710
2095
  ...metadata,
1711
2096
  reason: statusReason
1712
2097
  });
@@ -1745,7 +2130,7 @@ var assembleRevertError = (receipts, logs, metadata) => {
1745
2130
  errorMessage = `The transaction reverted because it's missing an "OutputChange".`;
1746
2131
  break;
1747
2132
  default:
1748
- throw new FuelError7(
2133
+ throw new FuelError8(
1749
2134
  ErrorCode7.UNKNOWN,
1750
2135
  `The transaction reverted with an unknown reason: ${revertReceipt.val}`,
1751
2136
  {
@@ -1755,7 +2140,7 @@ var assembleRevertError = (receipts, logs, metadata) => {
1755
2140
  );
1756
2141
  }
1757
2142
  }
1758
- return new FuelError7(ErrorCode7.SCRIPT_REVERTED, errorMessage, {
2143
+ return new FuelError8(ErrorCode7.SCRIPT_REVERTED, errorMessage, {
1759
2144
  ...metadata,
1760
2145
  reason
1761
2146
  });
@@ -1820,11 +2205,11 @@ var cacheRequestInputsResourcesFromOwner = (inputs, owner) => inputs.reduce(
1820
2205
  );
1821
2206
 
1822
2207
  // src/providers/transaction-request/witness.ts
1823
- import { arrayify as arrayify4, hexlify as hexlify6 } from "@fuel-ts/utils";
2208
+ import { arrayify as arrayify5, hexlify as hexlify8 } from "@fuel-ts/utils";
1824
2209
  var witnessify = (value) => {
1825
- const data = arrayify4(value);
2210
+ const data = arrayify5(value);
1826
2211
  return {
1827
- data: hexlify6(data),
2212
+ data: hexlify8(data),
1828
2213
  dataLength: data.length
1829
2214
  };
1830
2215
  };
@@ -1957,7 +2342,7 @@ var BaseTransactionRequest = class {
1957
2342
  * @returns The index of the created witness.
1958
2343
  */
1959
2344
  addEmptyWitness() {
1960
- this.addWitness(concat([ZeroBytes324, ZeroBytes324]));
2345
+ this.addWitness(concat2([ZeroBytes324, ZeroBytes324]));
1961
2346
  return this.witnesses.length - 1;
1962
2347
  }
1963
2348
  /**
@@ -1967,7 +2352,7 @@ var BaseTransactionRequest = class {
1967
2352
  * @param signature - The signature to update the witness with.
1968
2353
  */
1969
2354
  updateWitnessByOwner(address, signature) {
1970
- const ownerAddress = Address.fromAddressOrString(address);
2355
+ const ownerAddress = Address2.fromAddressOrString(address);
1971
2356
  const witnessIndex = this.getCoinInputWitnessIndexByOwner(ownerAddress);
1972
2357
  if (typeof witnessIndex === "number") {
1973
2358
  this.updateWitness(witnessIndex, signature);
@@ -2041,9 +2426,9 @@ var BaseTransactionRequest = class {
2041
2426
  const found = this.inputs.find((input) => {
2042
2427
  switch (input.type) {
2043
2428
  case InputType3.Coin:
2044
- return hexlify7(input.owner) === ownerAddress.toB256();
2429
+ return hexlify9(input.owner) === ownerAddress.toB256();
2045
2430
  case InputType3.Message:
2046
- return hexlify7(input.recipient) === ownerAddress.toB256();
2431
+ return hexlify9(input.recipient) === ownerAddress.toB256();
2047
2432
  default:
2048
2433
  return false;
2049
2434
  }
@@ -2178,7 +2563,7 @@ var BaseTransactionRequest = class {
2178
2563
  */
2179
2564
  addChangeOutput(to, assetId) {
2180
2565
  const changeOutput = this.getChangeOutputs().find(
2181
- (output) => hexlify7(output.assetId) === assetId
2566
+ (output) => hexlify9(output.assetId) === assetId
2182
2567
  );
2183
2568
  if (!changeOutput) {
2184
2569
  this.pushOutput({
@@ -2198,7 +2583,7 @@ var BaseTransactionRequest = class {
2198
2583
  * @hidden
2199
2584
  */
2200
2585
  metadataGas(_gasCosts) {
2201
- throw new Error("Not implemented");
2586
+ throw new FuelError9(FuelError9.CODES.NOT_IMPLEMENTED, "Not implemented");
2202
2587
  }
2203
2588
  /**
2204
2589
  * @hidden
@@ -2256,15 +2641,15 @@ var BaseTransactionRequest = class {
2256
2641
  usedQuantity = bn8("1000000000000000000");
2257
2642
  }
2258
2643
  if (assetInput && "assetId" in assetInput) {
2259
- assetInput.id = hexlify7(randomBytes(UTXO_ID_LEN2));
2644
+ assetInput.id = hexlify9(randomBytes3(UTXO_ID_LEN2));
2260
2645
  assetInput.amount = usedQuantity;
2261
2646
  } else {
2262
2647
  this.addResources([
2263
2648
  {
2264
- id: hexlify7(randomBytes(UTXO_ID_LEN2)),
2649
+ id: hexlify9(randomBytes3(UTXO_ID_LEN2)),
2265
2650
  amount: usedQuantity,
2266
2651
  assetId,
2267
- owner: resourcesOwner || Address.fromRandom(),
2652
+ owner: resourcesOwner || Address2.fromRandom(),
2268
2653
  blockCreated: bn8(1),
2269
2654
  txCreatedIdx: bn8(1)
2270
2655
  }
@@ -2273,6 +2658,7 @@ var BaseTransactionRequest = class {
2273
2658
  };
2274
2659
  updateAssetInput(baseAssetId, bn8(1e11));
2275
2660
  quantities.forEach((q) => updateAssetInput(q.assetId, q.amount));
2661
+ return this;
2276
2662
  }
2277
2663
  /**
2278
2664
  * Retrieves an array of CoinQuantity for each coin output present in the transaction.
@@ -2312,27 +2698,24 @@ var BaseTransactionRequest = class {
2312
2698
  this.inputs.filter(isRequestInputResource).forEach((i) => {
2313
2699
  const owner = getRequestInputResourceOwner(i);
2314
2700
  const correspondingInput = inputsToExtractGasUsed.find(
2315
- (x) => isRequestInputResourceFromOwner(x, Address.fromString(String(owner)))
2701
+ (x) => isRequestInputResourceFromOwner(x, Address2.fromString(String(owner)))
2316
2702
  );
2317
2703
  if (correspondingInput && "predicateGasUsed" in correspondingInput && bn8(correspondingInput.predicateGasUsed).gt(0)) {
2318
2704
  i.predicateGasUsed = correspondingInput.predicateGasUsed;
2319
2705
  }
2320
2706
  });
2321
2707
  }
2708
+ byteLength() {
2709
+ return this.toTransactionBytes().byteLength;
2710
+ }
2322
2711
  };
2323
2712
 
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
2713
  // src/providers/transaction-request/hash-transaction.ts
2331
2714
  import { ZeroBytes32 as ZeroBytes325 } from "@fuel-ts/address/configs";
2332
2715
  import { uint64ToBytesBE, sha256 } from "@fuel-ts/hasher";
2333
2716
  import { bn as bn9 } from "@fuel-ts/math";
2334
2717
  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";
2718
+ import { concat as concat3 } from "@fuel-ts/utils";
2336
2719
  import { clone as clone2 } from "ramda";
2337
2720
  function hashTransaction(transactionRequest, chainId) {
2338
2721
  const transaction = transactionRequest.toTransaction();
@@ -2394,15 +2777,85 @@ function hashTransaction(transactionRequest, chainId) {
2394
2777
  transaction.witnessesCount = 0;
2395
2778
  transaction.witnesses = [];
2396
2779
  const chainIdBytes = uint64ToBytesBE(chainId);
2397
- const concatenatedData = concat2([chainIdBytes, new TransactionCoder2().encode(transaction)]);
2780
+ const concatenatedData = concat3([chainIdBytes, new TransactionCoder2().encode(transaction)]);
2398
2781
  return sha256(concatenatedData);
2399
2782
  }
2400
2783
 
2784
+ // src/providers/transaction-request/blob-transaction-request.ts
2785
+ var BlobTransactionRequest = class extends BaseTransactionRequest {
2786
+ static from(obj) {
2787
+ if (obj instanceof this) {
2788
+ return obj;
2789
+ }
2790
+ return new this(obj);
2791
+ }
2792
+ /** Type of the transaction */
2793
+ type = TransactionType.Blob;
2794
+ /** Blob ID */
2795
+ blobId;
2796
+ /** Witness index of contract bytecode to create */
2797
+ witnessIndex;
2798
+ /**
2799
+ * Creates an instance `BlobTransactionRequest`.
2800
+ *
2801
+ * @param blobTransactionRequestLike - The initial values for the instance
2802
+ */
2803
+ constructor({ witnessIndex, blobId, ...rest }) {
2804
+ super(rest);
2805
+ this.blobId = blobId;
2806
+ this.witnessIndex = witnessIndex ?? 0;
2807
+ }
2808
+ /**
2809
+ * Converts the transaction request to a `TransactionBlob`.
2810
+ *
2811
+ * @returns The transaction create object.
2812
+ */
2813
+ toTransaction() {
2814
+ const baseTransaction = this.getBaseTransaction();
2815
+ const { witnessIndex, blobId } = this;
2816
+ return {
2817
+ type: TransactionType.Blob,
2818
+ ...baseTransaction,
2819
+ blobId,
2820
+ witnessIndex
2821
+ };
2822
+ }
2823
+ /**
2824
+ * Gets the Transaction Request by hashing the transaction.
2825
+ *
2826
+ * @param chainId - The chain ID.
2827
+ *
2828
+ * @returns - A hash of the transaction, which is the transaction ID.
2829
+ */
2830
+ getTransactionId(chainId) {
2831
+ return hashTransaction(this, chainId);
2832
+ }
2833
+ /**
2834
+ * Calculates the metadata gas cost for a blob transaction.
2835
+ *
2836
+ * @param gasCosts - gas costs passed from the chain.
2837
+ * @returns metadata gas cost for the blob transaction.
2838
+ */
2839
+ metadataGas(gasCosts) {
2840
+ return calculateMetadataGasForTxBlob({
2841
+ gasCosts,
2842
+ txBytesSize: this.byteSize(),
2843
+ witnessBytesSize: this.witnesses[this.witnessIndex].length
2844
+ });
2845
+ }
2846
+ };
2847
+
2848
+ // src/providers/transaction-request/create-transaction-request.ts
2849
+ import { ZeroBytes32 as ZeroBytes326 } from "@fuel-ts/address/configs";
2850
+ import { bn as bn10 } from "@fuel-ts/math";
2851
+ import { TransactionType as TransactionType3, OutputType as OutputType4 } from "@fuel-ts/transactions";
2852
+ import { arrayify as arrayify7, hexlify as hexlify11 } from "@fuel-ts/utils";
2853
+
2401
2854
  // src/providers/transaction-request/storage-slot.ts
2402
- import { arrayify as arrayify5, hexlify as hexlify8 } from "@fuel-ts/utils";
2855
+ import { arrayify as arrayify6, hexlify as hexlify10 } from "@fuel-ts/utils";
2403
2856
  var getStorageValue = (value) => {
2404
2857
  const v = new Uint8Array(32);
2405
- v.set(arrayify5(value));
2858
+ v.set(arrayify6(value));
2406
2859
  return v;
2407
2860
  };
2408
2861
  var storageSlotify = (storageSlot) => {
@@ -2416,8 +2869,8 @@ var storageSlotify = (storageSlot) => {
2416
2869
  value = storageSlot.value;
2417
2870
  }
2418
2871
  return {
2419
- key: hexlify8(key),
2420
- value: hexlify8(getStorageValue(value))
2872
+ key: hexlify10(key),
2873
+ value: hexlify10(getStorageValue(value))
2421
2874
  };
2422
2875
  };
2423
2876
 
@@ -2445,7 +2898,7 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
2445
2898
  constructor({ bytecodeWitnessIndex, salt, storageSlots, ...rest }) {
2446
2899
  super(rest);
2447
2900
  this.bytecodeWitnessIndex = bytecodeWitnessIndex ?? 0;
2448
- this.salt = hexlify9(salt ?? ZeroBytes326);
2901
+ this.salt = hexlify11(salt ?? ZeroBytes326);
2449
2902
  this.storageSlots = [...storageSlots ?? []];
2450
2903
  }
2451
2904
  /**
@@ -2462,7 +2915,7 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
2462
2915
  ...baseTransaction,
2463
2916
  bytecodeWitnessIndex,
2464
2917
  storageSlotsCount: bn10(storageSlots.length),
2465
- salt: this.salt ? hexlify9(this.salt) : ZeroBytes326,
2918
+ salt: this.salt ? hexlify11(this.salt) : ZeroBytes326,
2466
2919
  storageSlots
2467
2920
  };
2468
2921
  }
@@ -2501,7 +2954,7 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
2501
2954
  }
2502
2955
  metadataGas(gasCosts) {
2503
2956
  return calculateMetadataGasForTxCreate({
2504
- contractBytesSize: bn10(arrayify6(this.witnesses[this.bytecodeWitnessIndex] || "0x").length),
2957
+ contractBytesSize: bn10(arrayify7(this.witnesses[this.bytecodeWitnessIndex] || "0x").length),
2505
2958
  gasCosts,
2506
2959
  stateRootSize: this.storageSlots.length,
2507
2960
  txBytesSize: this.byteSize()
@@ -2515,17 +2968,17 @@ import { addressify as addressify2 } from "@fuel-ts/address";
2515
2968
  import { ZeroBytes32 as ZeroBytes327 } from "@fuel-ts/address/configs";
2516
2969
  import { bn as bn11 } from "@fuel-ts/math";
2517
2970
  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";
2971
+ import { arrayify as arrayify9, hexlify as hexlify12 } from "@fuel-ts/utils";
2519
2972
 
2520
2973
  // src/providers/transaction-request/scripts.ts
2521
- import { arrayify as arrayify7 } from "@fuel-ts/utils";
2974
+ import { arrayify as arrayify8 } from "@fuel-ts/utils";
2522
2975
  var returnZeroScript = {
2523
2976
  /*
2524
2977
  Opcode::RET(REG_ZERO)
2525
2978
  Opcode::NOOP
2526
2979
  */
2527
2980
  // TODO: Don't use hardcoded scripts: https://github.com/FuelLabs/fuels-ts/issues/281
2528
- bytes: arrayify7("0x24000000"),
2981
+ bytes: arrayify8("0x24000000"),
2529
2982
  encodeScriptData: () => new Uint8Array(0)
2530
2983
  };
2531
2984
  var withdrawScript = {
@@ -2539,7 +2992,7 @@ var withdrawScript = {
2539
2992
  00000000 00000000 [amount value]
2540
2993
  */
2541
2994
  // TODO: Don't use hardcoded scripts: https://github.com/FuelLabs/fuels-ts/issues/281
2542
- bytes: arrayify7("0x5040C0105D44C0064C40001124000000"),
2995
+ bytes: arrayify8("0x5040C0105D44C0064C40001124000000"),
2543
2996
  encodeScriptData: () => new Uint8Array(0)
2544
2997
  };
2545
2998
 
@@ -2568,8 +3021,8 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
2568
3021
  constructor({ script, scriptData, gasLimit, ...rest } = {}) {
2569
3022
  super(rest);
2570
3023
  this.gasLimit = bn11(gasLimit);
2571
- this.script = arrayify8(script ?? returnZeroScript.bytes);
2572
- this.scriptData = arrayify8(scriptData ?? returnZeroScript.encodeScriptData());
3024
+ this.script = arrayify9(script ?? returnZeroScript.bytes);
3025
+ this.scriptData = arrayify9(scriptData ?? returnZeroScript.encodeScriptData());
2573
3026
  this.abis = rest.abis;
2574
3027
  }
2575
3028
  /**
@@ -2578,8 +3031,8 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
2578
3031
  * @returns The transaction script object.
2579
3032
  */
2580
3033
  toTransaction() {
2581
- const script = arrayify8(this.script ?? "0x");
2582
- const scriptData = arrayify8(this.scriptData ?? "0x");
3034
+ const script = arrayify9(this.script ?? "0x");
3035
+ const scriptData = arrayify9(this.scriptData ?? "0x");
2583
3036
  return {
2584
3037
  type: TransactionType4.Script,
2585
3038
  scriptGasLimit: this.gasLimit,
@@ -2587,8 +3040,8 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
2587
3040
  scriptLength: bn11(script.length),
2588
3041
  scriptDataLength: bn11(scriptData.length),
2589
3042
  receiptsRoot: ZeroBytes327,
2590
- script: hexlify10(script),
2591
- scriptData: hexlify10(scriptData)
3043
+ script: hexlify12(script),
3044
+ scriptData: hexlify12(scriptData)
2592
3045
  };
2593
3046
  }
2594
3047
  /**
@@ -2726,10 +3179,10 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
2726
3179
  };
2727
3180
 
2728
3181
  // src/providers/transaction-request/utils.ts
2729
- import { ErrorCode as ErrorCode8, FuelError as FuelError8 } from "@fuel-ts/errors";
3182
+ import { ErrorCode as ErrorCode8, FuelError as FuelError10 } from "@fuel-ts/errors";
2730
3183
  import { TransactionType as TransactionType5 } from "@fuel-ts/transactions";
2731
3184
  var transactionRequestify = (obj) => {
2732
- if (obj instanceof ScriptTransactionRequest || obj instanceof CreateTransactionRequest) {
3185
+ if (obj instanceof ScriptTransactionRequest || obj instanceof CreateTransactionRequest || obj instanceof BlobTransactionRequest) {
2733
3186
  return obj;
2734
3187
  }
2735
3188
  const { type } = obj;
@@ -2740,27 +3193,35 @@ var transactionRequestify = (obj) => {
2740
3193
  case TransactionType5.Create: {
2741
3194
  return CreateTransactionRequest.from(obj);
2742
3195
  }
3196
+ case TransactionType5.Blob: {
3197
+ return BlobTransactionRequest.from(obj);
3198
+ }
2743
3199
  default: {
2744
- throw new FuelError8(ErrorCode8.INVALID_TRANSACTION_TYPE, `Invalid transaction type: ${type}.`);
3200
+ throw new FuelError10(
3201
+ ErrorCode8.UNSUPPORTED_TRANSACTION_TYPE,
3202
+ `Unsupported transaction type: ${type}.`
3203
+ );
2745
3204
  }
2746
3205
  }
2747
3206
  };
3207
+ var isTransactionTypeScript = (request) => request.type === TransactionType5.Script;
3208
+ var isTransactionTypeCreate = (request) => request.type === TransactionType5.Create;
2748
3209
 
2749
3210
  // src/providers/transaction-response/transaction-response.ts
2750
- import { ErrorCode as ErrorCode12, FuelError as FuelError12 } from "@fuel-ts/errors";
3211
+ import { ErrorCode as ErrorCode12, FuelError as FuelError14 } from "@fuel-ts/errors";
2751
3212
  import { bn as bn16 } from "@fuel-ts/math";
2752
- import { TransactionCoder as TransactionCoder4 } from "@fuel-ts/transactions";
2753
- import { arrayify as arrayify10 } from "@fuel-ts/utils";
3213
+ import { OutputType as OutputType7, TransactionCoder as TransactionCoder4, TxPointerCoder } from "@fuel-ts/transactions";
3214
+ import { arrayify as arrayify11, assertUnreachable } from "@fuel-ts/utils";
2754
3215
 
2755
3216
  // src/providers/transaction-summary/assemble-transaction-summary.ts
2756
3217
  import { bn as bn15 } from "@fuel-ts/math";
2757
3218
  import { PolicyType as PolicyType3 } from "@fuel-ts/transactions";
2758
- import { DateTime, hexlify as hexlify11 } from "@fuel-ts/utils";
3219
+ import { DateTime, hexlify as hexlify13 } from "@fuel-ts/utils";
2759
3220
 
2760
3221
  // src/providers/transaction-summary/calculate-tx-fee-for-summary.ts
2761
3222
  import { bn as bn12 } from "@fuel-ts/math";
2762
3223
  import { PolicyType as PolicyType2, TransactionCoder as TransactionCoder3, TransactionType as TransactionType6 } from "@fuel-ts/transactions";
2763
- import { arrayify as arrayify9 } from "@fuel-ts/utils";
3224
+ import { arrayify as arrayify10 } from "@fuel-ts/utils";
2764
3225
  var calculateTXFeeForSummary = (params) => {
2765
3226
  const {
2766
3227
  gasPrice,
@@ -2774,7 +3235,7 @@ var calculateTXFeeForSummary = (params) => {
2774
3235
  }
2775
3236
  const gasPerByte = bn12(feeParams.gasPerByte);
2776
3237
  const gasPriceFactor = bn12(feeParams.gasPriceFactor);
2777
- const transactionBytes = arrayify9(rawPayload);
3238
+ const transactionBytes = arrayify10(rawPayload);
2778
3239
  const [transaction] = new TransactionCoder3().decode(transactionBytes, 0);
2779
3240
  const { type, witnesses, inputs, policies } = transaction;
2780
3241
  let metadataGas = bn12(0);
@@ -2784,7 +3245,7 @@ var calculateTXFeeForSummary = (params) => {
2784
3245
  }
2785
3246
  if (type === TransactionType6.Create) {
2786
3247
  const { bytecodeWitnessIndex, storageSlots } = transaction;
2787
- const contractBytesSize = bn12(arrayify9(witnesses[bytecodeWitnessIndex].data).length);
3248
+ const contractBytesSize = bn12(arrayify10(witnesses[bytecodeWitnessIndex].data).length);
2788
3249
  metadataGas = calculateMetadataGasForTxCreate({
2789
3250
  contractBytesSize,
2790
3251
  gasCosts,
@@ -2829,7 +3290,7 @@ var calculateTXFeeForSummary = (params) => {
2829
3290
 
2830
3291
  // src/providers/transaction-summary/operations.ts
2831
3292
  import { ZeroBytes32 as ZeroBytes328 } from "@fuel-ts/address/configs";
2832
- import { ErrorCode as ErrorCode10, FuelError as FuelError10 } from "@fuel-ts/errors";
3293
+ import { ErrorCode as ErrorCode10, FuelError as FuelError12 } from "@fuel-ts/errors";
2833
3294
  import { bn as bn13 } from "@fuel-ts/math";
2834
3295
  import { ReceiptType as ReceiptType4, TransactionType as TransactionType7 } from "@fuel-ts/transactions";
2835
3296
 
@@ -2867,7 +3328,8 @@ var getFunctionCall = ({ abi, receipt }) => {
2867
3328
  };
2868
3329
 
2869
3330
  // src/providers/transaction-summary/input.ts
2870
- import { ErrorCode as ErrorCode9, FuelError as FuelError9 } from "@fuel-ts/errors";
3331
+ import { ErrorCode as ErrorCode9, FuelError as FuelError11 } from "@fuel-ts/errors";
3332
+ import { BN } from "@fuel-ts/math";
2871
3333
  import { InputType as InputType6 } from "@fuel-ts/transactions";
2872
3334
  function getInputsByTypes(inputs, types) {
2873
3335
  return inputs.filter((i) => types.includes(i.type));
@@ -2884,17 +3346,47 @@ function getInputsMessage(inputs) {
2884
3346
  function getInputsCoinAndMessage(inputs) {
2885
3347
  return getInputsByTypes(inputs, [InputType6.Coin, InputType6.Message]);
2886
3348
  }
3349
+ function isInputCoin(input) {
3350
+ return input.type === InputType6.Coin;
3351
+ }
2887
3352
  function getInputsContract(inputs) {
2888
3353
  return getInputsByType(inputs, InputType6.Contract);
2889
3354
  }
2890
- function getInputFromAssetId(inputs, assetId) {
3355
+ function findCoinInput(inputs, assetId) {
2891
3356
  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;
3357
+ return coinInputs.find((i) => i.assetId === assetId);
3358
+ }
3359
+ function aggregateInputsAmountsByAssetAndOwner(inputs, baseAssetID) {
3360
+ const aggregated = /* @__PURE__ */ new Map();
3361
+ getInputsCoinAndMessage(inputs).forEach((input) => {
3362
+ const assetId = isInputCoin(input) ? input.assetId : baseAssetID;
3363
+ const owner = isInputCoin(input) ? input.owner : input.recipient;
3364
+ let ownersMap = aggregated.get(assetId);
3365
+ if (!ownersMap) {
3366
+ ownersMap = /* @__PURE__ */ new Map();
3367
+ aggregated.set(assetId, ownersMap);
3368
+ }
3369
+ let ownerBalance = ownersMap.get(owner);
3370
+ if (!ownerBalance) {
3371
+ ownerBalance = new BN(0);
3372
+ ownersMap.set(owner, ownerBalance);
3373
+ }
3374
+ ownersMap.set(owner, ownerBalance.add(input.amount));
3375
+ });
3376
+ return aggregated;
3377
+ }
3378
+ function findMessageInput(inputs) {
3379
+ return getInputsMessage(inputs)?.[0];
3380
+ }
3381
+ function getInputFromAssetId(inputs, assetId, isBaseAsset = false) {
3382
+ const coinInput = findCoinInput(inputs, assetId);
3383
+ if (coinInput) {
3384
+ return coinInput;
3385
+ }
3386
+ if (isBaseAsset) {
3387
+ return findMessageInput(inputs);
3388
+ }
3389
+ return void 0;
2898
3390
  }
2899
3391
  function getInputContractFromIndex(inputs, inputIndex) {
2900
3392
  if (inputIndex == null) {
@@ -2905,7 +3397,7 @@ function getInputContractFromIndex(inputs, inputIndex) {
2905
3397
  return void 0;
2906
3398
  }
2907
3399
  if (contractInput.type !== InputType6.Contract) {
2908
- throw new FuelError9(
3400
+ throw new FuelError11(
2909
3401
  ErrorCode9.INVALID_TRANSACTION_INPUT,
2910
3402
  `Contract input should be of type 'contract'.`
2911
3403
  );
@@ -2952,10 +3444,12 @@ function getTransactionTypeName(transactionType) {
2952
3444
  return "Create" /* Create */;
2953
3445
  case TransactionType7.Script:
2954
3446
  return "Script" /* Script */;
3447
+ case TransactionType7.Blob:
3448
+ return "Blob" /* Blob */;
2955
3449
  default:
2956
- throw new FuelError10(
2957
- ErrorCode10.INVALID_TRANSACTION_TYPE,
2958
- `Invalid transaction type: ${transactionType}.`
3450
+ throw new FuelError12(
3451
+ ErrorCode10.UNSUPPORTED_TRANSACTION_TYPE,
3452
+ `Unsupported transaction type: ${transactionType}.`
2959
3453
  );
2960
3454
  }
2961
3455
  }
@@ -2978,47 +3472,60 @@ function isTypeUpgrade(transactionType) {
2978
3472
  function isTypeUpload(transactionType) {
2979
3473
  return isType(transactionType, "Upload" /* Upload */);
2980
3474
  }
3475
+ function isTypeBlob(transactionType) {
3476
+ return isType(transactionType, "Blob" /* Blob */);
3477
+ }
2981
3478
  function getReceiptsCall(receipts) {
2982
3479
  return getReceiptsByType(receipts, ReceiptType4.Call);
2983
3480
  }
2984
3481
  function getReceiptsMessageOut(receipts) {
2985
3482
  return getReceiptsByType(receipts, ReceiptType4.MessageOut);
2986
3483
  }
2987
- var mergeAssets = (op1, op2) => {
3484
+ function mergeAssets(op1, op2) {
2988
3485
  const assets1 = op1.assetsSent || [];
2989
3486
  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;
3487
+ const assetMap = /* @__PURE__ */ new Map();
3488
+ assets1.forEach((asset) => {
3489
+ assetMap.set(asset.assetId, { ...asset });
3490
+ });
3491
+ assets2.forEach((asset) => {
3492
+ const existingAsset = assetMap.get(asset.assetId);
3493
+ if (existingAsset) {
3494
+ existingAsset.amount = bn13(existingAsset.amount).add(asset.amount);
3495
+ } else {
3496
+ assetMap.set(asset.assetId, { ...asset });
2997
3497
  }
2998
- const mergedAmount = bn13(asset1.amount).add(matchingAsset.amount);
2999
- return { ...asset1, amount: mergedAmount };
3000
3498
  });
3001
- return mergedAssets.concat(filteredAssets);
3002
- };
3499
+ return Array.from(assetMap.values());
3500
+ }
3003
3501
  function isSameOperation(a, b) {
3004
3502
  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
3503
  }
3504
+ function mergeAssetsSent(existing, toAdd) {
3505
+ if (!toAdd.assetsSent?.length) {
3506
+ return existing.assetsSent;
3507
+ }
3508
+ return existing.assetsSent?.length ? mergeAssets(existing, toAdd) : toAdd.assetsSent;
3509
+ }
3510
+ function mergeCalls(existing, toAdd) {
3511
+ if (!toAdd.calls?.length) {
3512
+ return existing.calls;
3513
+ }
3514
+ return [...existing.calls || [], ...toAdd.calls];
3515
+ }
3516
+ function mergeOperations(existing, toAdd) {
3517
+ return {
3518
+ ...existing,
3519
+ assetsSent: mergeAssetsSent(existing, toAdd),
3520
+ calls: mergeCalls(existing, toAdd)
3521
+ };
3522
+ }
3006
3523
  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);
3524
+ const existingIndex = operations.findIndex((op) => isSameOperation(op, toAdd));
3525
+ if (existingIndex === -1) {
3526
+ return [...operations, toAdd];
3020
3527
  }
3021
- return allOperations;
3528
+ return operations.map((op, index) => index === existingIndex ? mergeOperations(op, toAdd) : op);
3022
3529
  }
3023
3530
  function getWithdrawFromFuelOperations({
3024
3531
  inputs,
@@ -3028,7 +3535,7 @@ function getWithdrawFromFuelOperations({
3028
3535
  const messageOutReceipts = getReceiptsMessageOut(receipts);
3029
3536
  const withdrawFromFuelOperations = messageOutReceipts.reduce(
3030
3537
  (prevWithdrawFromFuelOps, receipt) => {
3031
- const input = getInputFromAssetId(inputs, baseAssetId);
3538
+ const input = getInputFromAssetId(inputs, baseAssetId, true);
3032
3539
  if (input) {
3033
3540
  const inputAddress = getInputAccountAddress(input);
3034
3541
  const newWithdrawFromFuelOps = addOperation(prevWithdrawFromFuelOps, {
@@ -3057,65 +3564,80 @@ function getWithdrawFromFuelOperations({
3057
3564
  );
3058
3565
  return withdrawFromFuelOperations;
3059
3566
  }
3567
+ function getContractCalls(contractInput, abiMap, receipt, rawPayload, maxInputs) {
3568
+ const abi = abiMap?.[contractInput.contractID];
3569
+ if (!abi) {
3570
+ return [];
3571
+ }
3572
+ return [
3573
+ getFunctionCall({
3574
+ abi,
3575
+ receipt,
3576
+ rawPayload,
3577
+ maxInputs
3578
+ })
3579
+ ];
3580
+ }
3581
+ function getAssetsSent(receipt) {
3582
+ return receipt.amount?.isZero() ? void 0 : [
3583
+ {
3584
+ amount: receipt.amount,
3585
+ assetId: receipt.assetId
3586
+ }
3587
+ ];
3588
+ }
3589
+ function processCallReceipt(receipt, contractInput, inputs, abiMap, rawPayload, maxInputs, baseAssetId) {
3590
+ const assetId = receipt.assetId === ZeroBytes328 ? baseAssetId : receipt.assetId;
3591
+ const input = getInputFromAssetId(inputs, assetId, assetId === baseAssetId);
3592
+ if (!input) {
3593
+ return [];
3594
+ }
3595
+ const inputAddress = getInputAccountAddress(input);
3596
+ const calls = getContractCalls(contractInput, abiMap, receipt, rawPayload, maxInputs);
3597
+ return [
3598
+ {
3599
+ name: "Contract call" /* contractCall */,
3600
+ from: {
3601
+ type: 1 /* account */,
3602
+ address: inputAddress
3603
+ },
3604
+ to: {
3605
+ type: 0 /* contract */,
3606
+ address: receipt.to
3607
+ },
3608
+ assetsSent: getAssetsSent(receipt),
3609
+ calls
3610
+ }
3611
+ ];
3612
+ }
3060
3613
  function getContractCallOperations({
3061
3614
  inputs,
3062
3615
  outputs,
3063
3616
  receipts,
3064
3617
  abiMap,
3065
3618
  rawPayload,
3066
- maxInputs
3619
+ maxInputs,
3620
+ baseAssetId
3067
3621
  }) {
3068
3622
  const contractCallReceipts = getReceiptsCall(receipts);
3069
3623
  const contractOutputs = getOutputsContract(outputs);
3070
- const contractCallOperations = contractOutputs.reduce((prevOutputCallOps, output) => {
3624
+ return contractOutputs.flatMap((output) => {
3071
3625
  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;
3626
+ if (!contractInput) {
3627
+ return [];
3115
3628
  }
3116
- return prevOutputCallOps;
3117
- }, []);
3118
- return contractCallOperations;
3629
+ return contractCallReceipts.filter((receipt) => receipt.to === contractInput.contractID).flatMap(
3630
+ (receipt) => processCallReceipt(
3631
+ receipt,
3632
+ contractInput,
3633
+ inputs,
3634
+ abiMap,
3635
+ rawPayload,
3636
+ maxInputs,
3637
+ baseAssetId
3638
+ )
3639
+ );
3640
+ });
3119
3641
  }
3120
3642
  function extractTransferOperationFromReceipt(receipt, contractInputs, changeOutputs) {
3121
3643
  const { to: toAddress, assetId, amount } = receipt;
@@ -3147,32 +3669,40 @@ function extractTransferOperationFromReceipt(receipt, contractInputs, changeOutp
3147
3669
  function getTransferOperations({
3148
3670
  inputs,
3149
3671
  outputs,
3150
- receipts
3672
+ receipts,
3673
+ baseAssetId
3151
3674
  }) {
3152
3675
  let operations = [];
3153
3676
  const coinOutputs = getOutputsCoin(outputs);
3154
3677
  const contractInputs = getInputsContract(inputs);
3155
3678
  const changeOutputs = getOutputsChange(outputs);
3156
- coinOutputs.forEach((output) => {
3157
- const { amount, assetId, to } = output;
3158
- const changeOutput = changeOutputs.find((change) => change.assetId === assetId);
3159
- if (changeOutput) {
3679
+ const aggregated = aggregateInputsAmountsByAssetAndOwner(inputs, baseAssetId);
3680
+ coinOutputs.forEach(({ amount, assetId, to }) => {
3681
+ const txPayers = aggregated.get(assetId) || /* @__PURE__ */ new Map();
3682
+ let selectedPayer;
3683
+ let fallbackPayer;
3684
+ for (const [address, payedAmount] of txPayers) {
3685
+ if (!fallbackPayer) {
3686
+ fallbackPayer = address;
3687
+ }
3688
+ if (payedAmount.gte(amount)) {
3689
+ selectedPayer = address;
3690
+ break;
3691
+ }
3692
+ }
3693
+ selectedPayer = selectedPayer || fallbackPayer;
3694
+ if (selectedPayer) {
3160
3695
  operations = addOperation(operations, {
3161
3696
  name: "Transfer asset" /* transfer */,
3162
3697
  from: {
3163
3698
  type: 1 /* account */,
3164
- address: changeOutput.to
3699
+ address: selectedPayer
3165
3700
  },
3166
3701
  to: {
3167
3702
  type: 1 /* account */,
3168
3703
  address: to
3169
3704
  },
3170
- assetsSent: [
3171
- {
3172
- assetId,
3173
- amount
3174
- }
3175
- ]
3705
+ assetsSent: [{ assetId, amount }]
3176
3706
  });
3177
3707
  }
3178
3708
  });
@@ -3245,21 +3775,19 @@ function getOperations({
3245
3775
  baseAssetId
3246
3776
  }) {
3247
3777
  if (isTypeCreate(transactionType)) {
3248
- return [
3249
- ...getContractCreatedOperations({ inputs, outputs }),
3250
- ...getTransferOperations({ inputs, outputs, receipts })
3251
- ];
3778
+ return [...getContractCreatedOperations({ inputs, outputs })];
3252
3779
  }
3253
3780
  if (isTypeScript(transactionType)) {
3254
3781
  return [
3255
- ...getTransferOperations({ inputs, outputs, receipts }),
3782
+ ...getTransferOperations({ inputs, outputs, receipts, baseAssetId }),
3256
3783
  ...getContractCallOperations({
3257
3784
  inputs,
3258
3785
  outputs,
3259
3786
  receipts,
3260
3787
  abiMap,
3261
3788
  rawPayload,
3262
- maxInputs
3789
+ maxInputs,
3790
+ baseAssetId
3263
3791
  }),
3264
3792
  ...getWithdrawFromFuelOperations({ inputs, receipts, baseAssetId })
3265
3793
  ];
@@ -3318,7 +3846,7 @@ var extractBurnedAssetsFromReceipts = (receipts) => {
3318
3846
  };
3319
3847
 
3320
3848
  // src/providers/transaction-summary/status.ts
3321
- import { ErrorCode as ErrorCode11, FuelError as FuelError11 } from "@fuel-ts/errors";
3849
+ import { ErrorCode as ErrorCode11, FuelError as FuelError13 } from "@fuel-ts/errors";
3322
3850
  import { bn as bn14 } from "@fuel-ts/math";
3323
3851
  var getTransactionStatusName = (gqlStatus) => {
3324
3852
  switch (gqlStatus) {
@@ -3331,7 +3859,7 @@ var getTransactionStatusName = (gqlStatus) => {
3331
3859
  case "SqueezedOutStatus":
3332
3860
  return "squeezedout" /* squeezedout */;
3333
3861
  default:
3334
- throw new FuelError11(
3862
+ throw new FuelError13(
3335
3863
  ErrorCode11.INVALID_TRANSACTION_STATUS,
3336
3864
  `Invalid transaction status: ${gqlStatus}.`
3337
3865
  );
@@ -3401,7 +3929,7 @@ function assembleTransactionSummary(params) {
3401
3929
  baseAssetId
3402
3930
  } = params;
3403
3931
  const gasUsed = getGasUsedFromReceipts(receipts);
3404
- const rawPayload = hexlify11(transactionBytes);
3932
+ const rawPayload = hexlify13(transactionBytes);
3405
3933
  const operations = getOperations({
3406
3934
  transactionType: transaction.type,
3407
3935
  inputs: transaction.inputs || [],
@@ -3453,6 +3981,7 @@ function assembleTransactionSummary(params) {
3453
3981
  isTypeScript: isTypeScript(transaction.type),
3454
3982
  isTypeUpgrade: isTypeUpgrade(transaction.type),
3455
3983
  isTypeUpload: isTypeUpload(transaction.type),
3984
+ isTypeBlob: isTypeBlob(transaction.type),
3456
3985
  isStatusFailure,
3457
3986
  isStatusSuccess,
3458
3987
  isStatusPending,
@@ -3478,6 +4007,36 @@ function getDecodedLogs(receipts, mainAbi, externalAbis = {}) {
3478
4007
  }
3479
4008
 
3480
4009
  // src/providers/transaction-response/transaction-response.ts
4010
+ function mapGqlOutputsToTxOutputs(outputs) {
4011
+ return outputs.map((o) => {
4012
+ const obj = "amount" in o ? { ...o, amount: bn16(o.amount) } : o;
4013
+ switch (obj.type) {
4014
+ case "CoinOutput":
4015
+ return { ...obj, type: OutputType7.Coin };
4016
+ case "ContractOutput":
4017
+ return {
4018
+ ...obj,
4019
+ type: OutputType7.Contract,
4020
+ inputIndex: parseInt(obj.inputIndex, 10)
4021
+ };
4022
+ case "ChangeOutput":
4023
+ return {
4024
+ ...obj,
4025
+ type: OutputType7.Change
4026
+ };
4027
+ case "VariableOutput":
4028
+ return { ...obj, type: OutputType7.Variable };
4029
+ case "ContractCreated":
4030
+ return {
4031
+ ...obj,
4032
+ type: OutputType7.ContractCreated,
4033
+ contractId: obj.contract
4034
+ };
4035
+ default:
4036
+ return assertUnreachable(obj);
4037
+ }
4038
+ });
4039
+ }
3481
4040
  var TransactionResponse = class {
3482
4041
  /** Transaction ID */
3483
4042
  id;
@@ -3487,17 +4046,20 @@ var TransactionResponse = class {
3487
4046
  gasUsed = bn16(0);
3488
4047
  /** The graphql Transaction with receipts object. */
3489
4048
  gqlTransaction;
4049
+ request;
4050
+ status;
3490
4051
  abis;
3491
4052
  /**
3492
4053
  * Constructor for `TransactionResponse`.
3493
4054
  *
3494
- * @param id - The transaction ID.
4055
+ * @param tx - The transaction ID or TransactionRequest.
3495
4056
  * @param provider - The provider.
3496
4057
  */
3497
- constructor(id, provider, abis) {
3498
- this.id = id;
4058
+ constructor(tx, provider, abis) {
4059
+ this.id = typeof tx === "string" ? tx : tx.getTransactionId(provider.getChainId());
3499
4060
  this.provider = provider;
3500
4061
  this.abis = abis;
4062
+ this.request = typeof tx === "string" ? void 0 : tx;
3501
4063
  }
3502
4064
  /**
3503
4065
  * Async constructor for `TransactionResponse`. This method can be used to create
@@ -3512,6 +4074,54 @@ var TransactionResponse = class {
3512
4074
  await response.fetch();
3513
4075
  return response;
3514
4076
  }
4077
+ applyMalleableSubscriptionFields(transaction) {
4078
+ const status = this.status;
4079
+ if (!status) {
4080
+ return;
4081
+ }
4082
+ const tx = transaction;
4083
+ if (status.type === "SuccessStatus" || status.type === "FailureStatus") {
4084
+ tx.inputs = tx.inputs.map((input, idx) => {
4085
+ if ("txPointer" in input) {
4086
+ const correspondingInput = status.transaction.inputs?.[idx];
4087
+ return {
4088
+ ...input,
4089
+ txPointer: TxPointerCoder.decodeFromGqlScalar(correspondingInput.txPointer)
4090
+ };
4091
+ }
4092
+ return input;
4093
+ });
4094
+ tx.outputs = mapGqlOutputsToTxOutputs(status.transaction.outputs);
4095
+ if ("receiptsRoot" in status.transaction) {
4096
+ tx.receiptsRoot = status.transaction.receiptsRoot;
4097
+ }
4098
+ }
4099
+ }
4100
+ async getTransaction() {
4101
+ if (this.request) {
4102
+ const tx = this.request.toTransaction();
4103
+ this.applyMalleableSubscriptionFields(tx);
4104
+ return {
4105
+ tx,
4106
+ bytes: this.request.toTransactionBytes()
4107
+ };
4108
+ }
4109
+ const gqlTransaction = this.gqlTransaction ?? await this.fetch();
4110
+ return {
4111
+ tx: this.decodeTransaction(gqlTransaction),
4112
+ bytes: arrayify11(gqlTransaction.rawPayload)
4113
+ };
4114
+ }
4115
+ getReceipts() {
4116
+ const status = this.status ?? this.gqlTransaction?.status;
4117
+ switch (status?.type) {
4118
+ case "SuccessStatus":
4119
+ case "FailureStatus":
4120
+ return status.receipts.map(processGqlReceipt);
4121
+ default:
4122
+ return [];
4123
+ }
4124
+ }
3515
4125
  /**
3516
4126
  * Fetch the transaction with receipts from the provider.
3517
4127
  *
@@ -3522,11 +4132,12 @@ var TransactionResponse = class {
3522
4132
  transactionId: this.id
3523
4133
  });
3524
4134
  if (!response.transaction) {
3525
- const subscription = this.provider.operations.statusChange({
4135
+ const subscription = await this.provider.operations.statusChange({
3526
4136
  transactionId: this.id
3527
4137
  });
3528
4138
  for await (const { statusChange } of subscription) {
3529
4139
  if (statusChange) {
4140
+ this.status = statusChange;
3530
4141
  break;
3531
4142
  }
3532
4143
  }
@@ -3543,7 +4154,7 @@ var TransactionResponse = class {
3543
4154
  */
3544
4155
  decodeTransaction(transactionWithReceipts) {
3545
4156
  return new TransactionCoder4().decode(
3546
- arrayify10(transactionWithReceipts.rawPayload),
4157
+ arrayify11(transactionWithReceipts.rawPayload),
3547
4158
  0
3548
4159
  )?.[0];
3549
4160
  }
@@ -3555,28 +4166,17 @@ var TransactionResponse = class {
3555
4166
  * @returns
3556
4167
  */
3557
4168
  async getTransactionSummary(contractsAbiMap) {
3558
- let transaction = this.gqlTransaction;
3559
- if (!transaction) {
3560
- transaction = await this.fetch();
3561
- }
3562
- const decodedTransaction = this.decodeTransaction(
3563
- transaction
3564
- );
3565
- let txReceipts = [];
3566
- if (transaction?.status && "receipts" in transaction.status) {
3567
- txReceipts = transaction.status.receipts;
3568
- }
3569
- const receipts = txReceipts.map(processGqlReceipt) || [];
4169
+ const { tx: transaction, bytes: transactionBytes } = await this.getTransaction();
3570
4170
  const { gasPerByte, gasPriceFactor, gasCosts, maxGasPerTx } = this.provider.getGasConfig();
3571
4171
  const gasPrice = await this.provider.getLatestGasPrice();
3572
4172
  const maxInputs = this.provider.getChain().consensusParameters.txParameters.maxInputs;
3573
4173
  const baseAssetId = this.provider.getBaseAssetId();
3574
4174
  const transactionSummary = assembleTransactionSummary({
3575
4175
  id: this.id,
3576
- receipts,
3577
- transaction: decodedTransaction,
3578
- transactionBytes: arrayify10(transaction.rawPayload),
3579
- gqlTransactionStatus: transaction.status,
4176
+ receipts: this.getReceipts(),
4177
+ transaction,
4178
+ transactionBytes,
4179
+ gqlTransactionStatus: this.status ?? this.gqlTransaction?.status,
3580
4180
  gasPerByte,
3581
4181
  gasPriceFactor,
3582
4182
  abiMap: contractsAbiMap,
@@ -3593,12 +4193,14 @@ var TransactionResponse = class {
3593
4193
  if (status && status !== "SubmittedStatus") {
3594
4194
  return;
3595
4195
  }
3596
- const subscription = this.provider.operations.statusChange({
4196
+ const subscription = await this.provider.operations.statusChange({
3597
4197
  transactionId: this.id
3598
4198
  });
3599
4199
  for await (const { statusChange } of subscription) {
4200
+ this.status = statusChange;
3600
4201
  if (statusChange.type === "SqueezedOutStatus") {
3601
- throw new FuelError12(
4202
+ this.unsetResourceCache();
4203
+ throw new FuelError14(
3602
4204
  ErrorCode12.TRANSACTION_SQUEEZED_OUT,
3603
4205
  `Transaction Squeezed Out with reason: ${statusChange.reason}`
3604
4206
  );
@@ -3607,7 +4209,6 @@ var TransactionResponse = class {
3607
4209
  break;
3608
4210
  }
3609
4211
  }
3610
- await this.fetch();
3611
4212
  }
3612
4213
  /**
3613
4214
  * Assembles the result of a transaction by retrieving the transaction summary,
@@ -3624,7 +4225,6 @@ var TransactionResponse = class {
3624
4225
  async assembleResult(contractsAbiMap) {
3625
4226
  const transactionSummary = await this.getTransactionSummary(contractsAbiMap);
3626
4227
  const transactionResult = {
3627
- gqlTransaction: this.gqlTransaction,
3628
4228
  ...transactionSummary
3629
4229
  };
3630
4230
  let logs = [];
@@ -3636,9 +4236,11 @@ var TransactionResponse = class {
3636
4236
  );
3637
4237
  transactionResult.logs = logs;
3638
4238
  }
3639
- const { gqlTransaction, receipts } = transactionResult;
3640
- if (gqlTransaction.status?.type === "FailureStatus") {
3641
- const { reason } = gqlTransaction.status;
4239
+ const { receipts } = transactionResult;
4240
+ const status = this.status ?? this.gqlTransaction?.status;
4241
+ if (status?.type === "FailureStatus") {
4242
+ this.unsetResourceCache();
4243
+ const { reason } = status;
3642
4244
  throw extractTxError({
3643
4245
  receipts,
3644
4246
  statusReason: reason,
@@ -3664,6 +4266,9 @@ var TransactionResponse = class {
3664
4266
  async wait(contractsAbiMap) {
3665
4267
  return this.waitForResult(contractsAbiMap);
3666
4268
  }
4269
+ unsetResourceCache() {
4270
+ this.provider.cache?.unset(this.id);
4271
+ }
3667
4272
  };
3668
4273
 
3669
4274
  // src/providers/utils/auto-retry-fetch.ts
@@ -3703,24 +4308,11 @@ function autoRetryFetch(fetchFn, options, retryAttemptNum = 0) {
3703
4308
  };
3704
4309
  }
3705
4310
 
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
4311
  // src/providers/provider.ts
3721
4312
  var MAX_RETRIES = 10;
3722
4313
  var RESOURCES_PAGE_SIZE_LIMIT = 512;
3723
4314
  var BLOCKS_PAGE_SIZE_LIMIT = 5;
4315
+ var DEFAULT_RESOURCE_CACHE_TTL = 2e4;
3724
4316
  var processGqlChain = (chain) => {
3725
4317
  const { name, daHeight, consensusParameters, latestBlock } = chain;
3726
4318
  const {
@@ -3803,14 +4395,23 @@ var _Provider = class {
3803
4395
  __publicField(this, "cache");
3804
4396
  __publicField(this, "options", {
3805
4397
  timeout: void 0,
3806
- cacheUtxo: void 0,
4398
+ resourceCacheTTL: void 0,
3807
4399
  fetch: void 0,
3808
4400
  retryOptions: void 0
3809
4401
  });
3810
4402
  this.options = { ...this.options, ...options };
3811
4403
  this.url = url;
3812
4404
  this.operations = this.createOperations();
3813
- this.cache = options.cacheUtxo ? new MemoryCache(options.cacheUtxo) : void 0;
4405
+ const { resourceCacheTTL } = this.options;
4406
+ if (isDefined2(resourceCacheTTL)) {
4407
+ if (resourceCacheTTL !== -1) {
4408
+ this.cache = new ResourceCache(resourceCacheTTL);
4409
+ } else {
4410
+ this.cache = void 0;
4411
+ }
4412
+ } else {
4413
+ this.cache = new ResourceCache(DEFAULT_RESOURCE_CACHE_TTL);
4414
+ }
3814
4415
  }
3815
4416
  /** @hidden */
3816
4417
  static clearChainAndNodeCaches() {
@@ -3854,7 +4455,7 @@ var _Provider = class {
3854
4455
  getChain() {
3855
4456
  const chain = _Provider.chainInfoCache[this.url];
3856
4457
  if (!chain) {
3857
- throw new FuelError13(
4458
+ throw new FuelError15(
3858
4459
  ErrorCode13.CHAIN_INFO_CACHE_EMPTY,
3859
4460
  "Chain info cache is empty. Make sure you have called `Provider.create` to initialize the provider."
3860
4461
  );
@@ -3869,7 +4470,7 @@ var _Provider = class {
3869
4470
  getNode() {
3870
4471
  const node = _Provider.nodeInfoCache[this.url];
3871
4472
  if (!node) {
3872
- throw new FuelError13(
4473
+ throw new FuelError15(
3873
4474
  ErrorCode13.NODE_INFO_CACHE_EMPTY,
3874
4475
  "Node info cache is empty. Make sure you have called `Provider.create` to initialize the provider."
3875
4476
  );
@@ -3912,9 +4513,9 @@ var _Provider = class {
3912
4513
  * @returns A promise that resolves to the Chain and NodeInfo.
3913
4514
  */
3914
4515
  async fetchChainAndNodeInfo() {
3915
- const chain = await this.fetchChain();
3916
4516
  const nodeInfo = await this.fetchNode();
3917
4517
  _Provider.ensureClientVersionIsSupported(nodeInfo);
4518
+ const chain = await this.fetchChain();
3918
4519
  return {
3919
4520
  chain,
3920
4521
  nodeInfo
@@ -3948,8 +4549,8 @@ Supported fuel-core version: ${supportedVersion}.`
3948
4549
  if ("response" in response) {
3949
4550
  const graphQlResponse = response.response;
3950
4551
  if (Array.isArray(graphQlResponse?.errors)) {
3951
- throw new FuelError13(
3952
- FuelError13.CODES.INVALID_REQUEST,
4552
+ throw new FuelError15(
4553
+ FuelError15.CODES.INVALID_REQUEST,
3953
4554
  graphQlResponse.errors.map((err) => err.message).join("\n\n")
3954
4555
  );
3955
4556
  }
@@ -3960,7 +4561,7 @@ Supported fuel-core version: ${supportedVersion}.`
3960
4561
  const opDefinition = query.definitions.find((x) => x.kind === "OperationDefinition");
3961
4562
  const isSubscription = opDefinition?.operation === "subscription";
3962
4563
  if (isSubscription) {
3963
- return new FuelGraphqlSubscriber({
4564
+ return FuelGraphqlSubscriber.create({
3964
4565
  url: this.url,
3965
4566
  query,
3966
4567
  fetchFn: (url, requestInit) => fetchFn(url, requestInit, this.options),
@@ -4041,6 +4642,21 @@ Supported fuel-core version: ${supportedVersion}.`
4041
4642
  } = this.getChain();
4042
4643
  return baseAssetId;
4043
4644
  }
4645
+ validateTransaction(tx, consensusParameters) {
4646
+ const { maxOutputs, maxInputs } = consensusParameters.txParameters;
4647
+ if (bn17(tx.inputs.length).gt(maxInputs)) {
4648
+ throw new FuelError15(
4649
+ ErrorCode13.MAX_INPUTS_EXCEEDED,
4650
+ "The transaction exceeds the maximum allowed number of inputs."
4651
+ );
4652
+ }
4653
+ if (bn17(tx.outputs.length).gt(maxOutputs)) {
4654
+ throw new FuelError15(
4655
+ ErrorCode13.MAX_OUTPUTS_EXCEEDED,
4656
+ "The transaction exceeds the maximum allowed number of outputs."
4657
+ );
4658
+ }
4659
+ }
4044
4660
  /**
4045
4661
  * Submits a transaction to the chain to be executed.
4046
4662
  *
@@ -4052,39 +4668,23 @@ Supported fuel-core version: ${supportedVersion}.`
4052
4668
  * @returns A promise that resolves to the transaction response object.
4053
4669
  */
4054
4670
  // #region Provider-sendTransaction
4055
- async sendTransaction(transactionRequestLike, { estimateTxDependencies = true, awaitExecution = false } = {}) {
4671
+ async sendTransaction(transactionRequestLike, { estimateTxDependencies = true } = {}) {
4056
4672
  const transactionRequest = transactionRequestify(transactionRequestLike);
4057
- __privateMethod(this, _cacheInputs, cacheInputs_fn).call(this, transactionRequest.inputs);
4058
4673
  if (estimateTxDependencies) {
4059
4674
  await this.estimateTxDependencies(transactionRequest);
4060
4675
  }
4061
- const encodedTransaction = hexlify12(transactionRequest.toTransactionBytes());
4676
+ const { consensusParameters } = this.getChain();
4677
+ this.validateTransaction(transactionRequest, consensusParameters);
4678
+ const encodedTransaction = hexlify14(transactionRequest.toTransactionBytes());
4062
4679
  let abis;
4063
- if (transactionRequest.type === TransactionType8.Script) {
4680
+ if (isTransactionTypeScript(transactionRequest)) {
4064
4681
  abis = transactionRequest.abis;
4065
4682
  }
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
4683
  const {
4085
4684
  submit: { id: transactionId }
4086
4685
  } = await this.operations.submit({ encodedTransaction });
4087
- return new TransactionResponse(transactionId, this, abis);
4686
+ __privateMethod(this, _cacheInputs, cacheInputs_fn).call(this, transactionRequest.inputs, transactionId);
4687
+ return new TransactionResponse(transactionRequest, this, abis);
4088
4688
  }
4089
4689
  /**
4090
4690
  * Executes a transaction without actually submitting it to the chain.
@@ -4101,7 +4701,7 @@ Supported fuel-core version: ${supportedVersion}.`
4101
4701
  if (estimateTxDependencies) {
4102
4702
  return this.estimateTxDependencies(transactionRequest);
4103
4703
  }
4104
- const encodedTransaction = hexlify12(transactionRequest.toTransactionBytes());
4704
+ const encodedTransaction = hexlify14(transactionRequest.toTransactionBytes());
4105
4705
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
4106
4706
  encodedTransactions: encodedTransaction,
4107
4707
  utxoValidation: utxoValidation || false
@@ -4121,13 +4721,13 @@ Supported fuel-core version: ${supportedVersion}.`
4121
4721
  async estimatePredicates(transactionRequest) {
4122
4722
  const shouldEstimatePredicates = Boolean(
4123
4723
  transactionRequest.inputs.find(
4124
- (input) => "predicate" in input && input.predicate && !equalBytes(arrayify11(input.predicate), arrayify11("0x")) && new BN(input.predicateGasUsed).isZero()
4724
+ (input) => "predicate" in input && input.predicate && !equalBytes(arrayify12(input.predicate), arrayify12("0x")) && new BN2(input.predicateGasUsed).isZero()
4125
4725
  )
4126
4726
  );
4127
4727
  if (!shouldEstimatePredicates) {
4128
4728
  return transactionRequest;
4129
4729
  }
4130
- const encodedTransaction = hexlify12(transactionRequest.toTransactionBytes());
4730
+ const encodedTransaction = hexlify14(transactionRequest.toTransactionBytes());
4131
4731
  const response = await this.operations.estimatePredicates({
4132
4732
  encodedTransaction
4133
4733
  });
@@ -4153,7 +4753,7 @@ Supported fuel-core version: ${supportedVersion}.`
4153
4753
  * @returns A promise that resolves to the estimate transaction dependencies.
4154
4754
  */
4155
4755
  async estimateTxDependencies(transactionRequest) {
4156
- if (transactionRequest.type === TransactionType8.Create) {
4756
+ if (isTransactionTypeCreate(transactionRequest)) {
4157
4757
  return {
4158
4758
  receipts: [],
4159
4759
  outputVariables: 0,
@@ -4168,18 +4768,18 @@ Supported fuel-core version: ${supportedVersion}.`
4168
4768
  const {
4169
4769
  dryRun: [{ receipts: rawReceipts, status }]
4170
4770
  } = await this.operations.dryRun({
4171
- encodedTransactions: [hexlify12(transactionRequest.toTransactionBytes())],
4771
+ encodedTransactions: [hexlify14(transactionRequest.toTransactionBytes())],
4172
4772
  utxoValidation: false
4173
4773
  });
4174
4774
  receipts = rawReceipts.map(processGqlReceipt);
4175
4775
  dryRunStatus = status;
4176
4776
  const { missingOutputVariables, missingOutputContractIds } = getReceiptsWithMissingData(receipts);
4177
4777
  const hasMissingOutputs = missingOutputVariables.length !== 0 || missingOutputContractIds.length !== 0;
4178
- if (hasMissingOutputs) {
4778
+ if (hasMissingOutputs && isTransactionTypeScript(transactionRequest)) {
4179
4779
  outputVariables += missingOutputVariables.length;
4180
4780
  transactionRequest.addVariableOutputs(missingOutputVariables.length);
4181
4781
  missingOutputContractIds.forEach(({ contractId }) => {
4182
- transactionRequest.addContractInputAndOutput(Address2.fromString(contractId));
4782
+ transactionRequest.addContractInputAndOutput(Address3.fromString(contractId));
4183
4783
  missingContractIds.push(contractId);
4184
4784
  });
4185
4785
  const { maxFee } = await this.estimateTxGasAndFee({
@@ -4217,8 +4817,8 @@ Supported fuel-core version: ${supportedVersion}.`
4217
4817
  const allRequests = clone3(transactionRequests);
4218
4818
  const serializedTransactionsMap = /* @__PURE__ */ new Map();
4219
4819
  allRequests.forEach((req, index) => {
4220
- if (req.type === TransactionType8.Script) {
4221
- serializedTransactionsMap.set(index, hexlify12(req.toTransactionBytes()));
4820
+ if (isTransactionTypeScript(req)) {
4821
+ serializedTransactionsMap.set(index, hexlify14(req.toTransactionBytes()));
4222
4822
  }
4223
4823
  });
4224
4824
  let transactionsToProcess = Array.from(serializedTransactionsMap.keys());
@@ -4243,18 +4843,18 @@ Supported fuel-core version: ${supportedVersion}.`
4243
4843
  );
4244
4844
  const hasMissingOutputs = missingOutputVariables.length > 0 || missingOutputContractIds.length > 0;
4245
4845
  const request = allRequests[requestIdx];
4246
- if (hasMissingOutputs && request?.type === TransactionType8.Script) {
4846
+ if (hasMissingOutputs && isTransactionTypeScript(request)) {
4247
4847
  result.outputVariables += missingOutputVariables.length;
4248
4848
  request.addVariableOutputs(missingOutputVariables.length);
4249
4849
  missingOutputContractIds.forEach(({ contractId }) => {
4250
- request.addContractInputAndOutput(Address2.fromString(contractId));
4850
+ request.addContractInputAndOutput(Address3.fromString(contractId));
4251
4851
  result.missingContractIds.push(contractId);
4252
4852
  });
4253
4853
  const { maxFee } = await this.estimateTxGasAndFee({
4254
4854
  transactionRequest: request
4255
4855
  });
4256
4856
  request.maxFee = maxFee;
4257
- serializedTransactionsMap.set(requestIdx, hexlify12(request.toTransactionBytes()));
4857
+ serializedTransactionsMap.set(requestIdx, hexlify14(request.toTransactionBytes()));
4258
4858
  nextRoundTransactions.push(requestIdx);
4259
4859
  }
4260
4860
  }
@@ -4275,7 +4875,7 @@ Supported fuel-core version: ${supportedVersion}.`
4275
4875
  if (estimateTxDependencies) {
4276
4876
  return this.estimateMultipleTxDependencies(transactionRequests);
4277
4877
  }
4278
- const encodedTransactions = transactionRequests.map((tx) => hexlify12(tx.toTransactionBytes()));
4878
+ const encodedTransactions = transactionRequests.map((tx) => hexlify14(tx.toTransactionBytes()));
4279
4879
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
4280
4880
  encodedTransactions,
4281
4881
  utxoValidation: utxoValidation || false
@@ -4307,7 +4907,7 @@ Supported fuel-core version: ${supportedVersion}.`
4307
4907
  tip: transactionRequest.tip
4308
4908
  }).add(1);
4309
4909
  let gasLimit = bn17(0);
4310
- if (transactionRequest.type === TransactionType8.Script) {
4910
+ if (isTransactionTypeScript(transactionRequest)) {
4311
4911
  gasLimit = transactionRequest.gasLimit;
4312
4912
  if (transactionRequest.gasLimit.eq(0)) {
4313
4913
  transactionRequest.gasLimit = minGas;
@@ -4349,7 +4949,7 @@ Supported fuel-core version: ${supportedVersion}.`
4349
4949
  if (estimateTxDependencies) {
4350
4950
  return this.estimateTxDependencies(transactionRequest);
4351
4951
  }
4352
- const encodedTransactions = [hexlify12(transactionRequest.toTransactionBytes())];
4952
+ const encodedTransactions = [hexlify14(transactionRequest.toTransactionBytes())];
4353
4953
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
4354
4954
  encodedTransactions,
4355
4955
  utxoValidation: true
@@ -4362,6 +4962,8 @@ Supported fuel-core version: ${supportedVersion}.`
4362
4962
  return { receipts: callResult[0].receipts };
4363
4963
  }
4364
4964
  /**
4965
+ * @hidden
4966
+ *
4365
4967
  * Returns a transaction cost to enable user
4366
4968
  * to set gasLimit and also reserve balance amounts
4367
4969
  * on the transaction.
@@ -4371,23 +4973,16 @@ Supported fuel-core version: ${supportedVersion}.`
4371
4973
  *
4372
4974
  * @returns A promise that resolves to the transaction cost object.
4373
4975
  */
4374
- async getTransactionCost(transactionRequestLike, { resourcesOwner, signatureCallback, quantitiesToContract = [] } = {}) {
4976
+ async getTransactionCost(transactionRequestLike, { signatureCallback } = {}) {
4375
4977
  const txRequestClone = clone3(transactionRequestify(transactionRequestLike));
4376
- const isScriptTransaction = txRequestClone.type === TransactionType8.Script;
4377
- const baseAssetId = this.getBaseAssetId();
4378
4978
  const updateMaxFee = txRequestClone.maxFee.eq(0);
4379
- const coinOutputsQuantities = txRequestClone.getCoinOutputsQuantities();
4380
- const allQuantities = mergeQuantities(coinOutputsQuantities, quantitiesToContract);
4381
- txRequestClone.fundWithFakeUtxos(allQuantities, baseAssetId, resourcesOwner?.address);
4979
+ const isScriptTransaction = isTransactionTypeScript(txRequestClone);
4382
4980
  if (isScriptTransaction) {
4383
4981
  txRequestClone.gasLimit = bn17(0);
4384
4982
  }
4385
- if (resourcesOwner && "populateTransactionPredicateData" in resourcesOwner) {
4386
- resourcesOwner.populateTransactionPredicateData(txRequestClone);
4387
- }
4388
4983
  const signedRequest = clone3(txRequestClone);
4389
4984
  let addedSignatures = 0;
4390
- if (signatureCallback && isScriptTransaction) {
4985
+ if (signatureCallback && isTransactionTypeScript(signedRequest)) {
4391
4986
  const lengthBefore = signedRequest.witnesses.length;
4392
4987
  await signatureCallback(signedRequest);
4393
4988
  addedSignatures = signedRequest.witnesses.length - lengthBefore;
@@ -4420,7 +5015,6 @@ Supported fuel-core version: ${supportedVersion}.`
4420
5015
  }));
4421
5016
  }
4422
5017
  return {
4423
- requiredQuantities: allQuantities,
4424
5018
  receipts,
4425
5019
  gasUsed,
4426
5020
  gasPrice,
@@ -4436,34 +5030,6 @@ Supported fuel-core version: ${supportedVersion}.`
4436
5030
  updateMaxFee
4437
5031
  };
4438
5032
  }
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
5033
  /**
4468
5034
  * Returns coins for the given owner.
4469
5035
  *
@@ -4474,7 +5040,7 @@ Supported fuel-core version: ${supportedVersion}.`
4474
5040
  * @returns A promise that resolves to the coins.
4475
5041
  */
4476
5042
  async getCoins(owner, assetId, paginationArgs) {
4477
- const ownerAddress = Address2.fromAddressOrString(owner);
5043
+ const ownerAddress = Address3.fromAddressOrString(owner);
4478
5044
  const {
4479
5045
  coins: { edges, pageInfo }
4480
5046
  } = await this.operations.getCoins({
@@ -4482,13 +5048,13 @@ Supported fuel-core version: ${supportedVersion}.`
4482
5048
  paginationLimit: RESOURCES_PAGE_SIZE_LIMIT,
4483
5049
  inputArgs: paginationArgs
4484
5050
  }),
4485
- filter: { owner: ownerAddress.toB256(), assetId: assetId && hexlify12(assetId) }
5051
+ filter: { owner: ownerAddress.toB256(), assetId: assetId && hexlify14(assetId) }
4486
5052
  });
4487
5053
  const coins = edges.map(({ node }) => ({
4488
5054
  id: node.utxoId,
4489
5055
  assetId: node.assetId,
4490
5056
  amount: bn17(node.amount),
4491
- owner: Address2.fromAddressOrString(node.owner),
5057
+ owner: Address3.fromAddressOrString(node.owner),
4492
5058
  blockCreated: bn17(node.blockCreated),
4493
5059
  txCreatedIdx: bn17(node.txCreatedIdx)
4494
5060
  }));
@@ -4506,21 +5072,20 @@ Supported fuel-core version: ${supportedVersion}.`
4506
5072
  * @returns A promise that resolves to the resources.
4507
5073
  */
4508
5074
  async getResourcesToSpend(owner, quantities, excludedIds) {
4509
- const ownerAddress = Address2.fromAddressOrString(owner);
5075
+ const ownerAddress = Address3.fromAddressOrString(owner);
4510
5076
  const excludeInput = {
4511
- messages: excludedIds?.messages?.map((nonce) => hexlify12(nonce)) || [],
4512
- utxos: excludedIds?.utxos?.map((id) => hexlify12(id)) || []
5077
+ messages: excludedIds?.messages?.map((nonce) => hexlify14(nonce)) || [],
5078
+ utxos: excludedIds?.utxos?.map((id) => hexlify14(id)) || []
4513
5079
  };
4514
5080
  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);
5081
+ const cached = this.cache.getActiveData();
5082
+ excludeInput.messages.push(...cached.messages);
5083
+ excludeInput.utxos.push(...cached.utxos);
4519
5084
  }
4520
5085
  const coinsQuery = {
4521
5086
  owner: ownerAddress.toB256(),
4522
5087
  queryPerAsset: quantities.map(coinQuantityfy).map(({ assetId, amount, max: maxPerAsset }) => ({
4523
- assetId: hexlify12(assetId),
5088
+ assetId: hexlify14(assetId),
4524
5089
  amount: amount.toString(10),
4525
5090
  max: maxPerAsset ? maxPerAsset.toString(10) : void 0
4526
5091
  })),
@@ -4534,8 +5099,8 @@ Supported fuel-core version: ${supportedVersion}.`
4534
5099
  amount: bn17(coin.amount),
4535
5100
  assetId: coin.assetId,
4536
5101
  daHeight: bn17(coin.daHeight),
4537
- sender: Address2.fromAddressOrString(coin.sender),
4538
- recipient: Address2.fromAddressOrString(coin.recipient),
5102
+ sender: Address3.fromAddressOrString(coin.sender),
5103
+ recipient: Address3.fromAddressOrString(coin.recipient),
4539
5104
  nonce: coin.nonce
4540
5105
  };
4541
5106
  case "Coin":
@@ -4543,7 +5108,7 @@ Supported fuel-core version: ${supportedVersion}.`
4543
5108
  id: coin.utxoId,
4544
5109
  amount: bn17(coin.amount),
4545
5110
  assetId: coin.assetId,
4546
- owner: Address2.fromAddressOrString(coin.owner),
5111
+ owner: Address3.fromAddressOrString(coin.owner),
4547
5112
  blockCreated: bn17(coin.blockCreated),
4548
5113
  txCreatedIdx: bn17(coin.txCreatedIdx)
4549
5114
  };
@@ -4629,7 +5194,7 @@ Supported fuel-core version: ${supportedVersion}.`
4629
5194
  time: block.header.time,
4630
5195
  transactionIds: block.transactions.map((tx) => tx.id),
4631
5196
  transactions: block.transactions.map(
4632
- (tx) => new TransactionCoder5().decode(arrayify11(tx.rawPayload), 0)?.[0]
5197
+ (tx) => new TransactionCoder5().decode(arrayify12(tx.rawPayload), 0)?.[0]
4633
5198
  )
4634
5199
  };
4635
5200
  }
@@ -4645,7 +5210,7 @@ Supported fuel-core version: ${supportedVersion}.`
4645
5210
  return null;
4646
5211
  }
4647
5212
  return new TransactionCoder5().decode(
4648
- arrayify11(transaction.rawPayload),
5213
+ arrayify12(transaction.rawPayload),
4649
5214
  0
4650
5215
  )?.[0];
4651
5216
  }
@@ -4660,7 +5225,7 @@ Supported fuel-core version: ${supportedVersion}.`
4660
5225
  } = await this.operations.getTransactions(paginationArgs);
4661
5226
  const coder = new TransactionCoder5();
4662
5227
  const transactions = edges.map(
4663
- ({ node: { rawPayload } }) => coder.decode(arrayify11(rawPayload), 0)[0]
5228
+ ({ node: { rawPayload } }) => coder.decode(arrayify12(rawPayload), 0)[0]
4664
5229
  );
4665
5230
  return { transactions, pageInfo };
4666
5231
  }
@@ -4686,8 +5251,8 @@ Supported fuel-core version: ${supportedVersion}.`
4686
5251
  */
4687
5252
  async getContractBalance(contractId, assetId) {
4688
5253
  const { contractBalance } = await this.operations.getContractBalance({
4689
- contract: Address2.fromAddressOrString(contractId).toB256(),
4690
- asset: hexlify12(assetId)
5254
+ contract: Address3.fromAddressOrString(contractId).toB256(),
5255
+ asset: hexlify14(assetId)
4691
5256
  });
4692
5257
  return bn17(contractBalance.amount, 10);
4693
5258
  }
@@ -4700,8 +5265,8 @@ Supported fuel-core version: ${supportedVersion}.`
4700
5265
  */
4701
5266
  async getBalance(owner, assetId) {
4702
5267
  const { balance } = await this.operations.getBalance({
4703
- owner: Address2.fromAddressOrString(owner).toB256(),
4704
- assetId: hexlify12(assetId)
5268
+ owner: Address3.fromAddressOrString(owner).toB256(),
5269
+ assetId: hexlify14(assetId)
4705
5270
  });
4706
5271
  return bn17(balance.amount, 10);
4707
5272
  }
@@ -4721,7 +5286,7 @@ Supported fuel-core version: ${supportedVersion}.`
4721
5286
  * but the current Fuel-Core implementation does not support pagination yet.
4722
5287
  */
4723
5288
  first: 1e4,
4724
- filter: { owner: Address2.fromAddressOrString(owner).toB256() }
5289
+ filter: { owner: Address3.fromAddressOrString(owner).toB256() }
4725
5290
  });
4726
5291
  const balances = edges.map(({ node }) => ({
4727
5292
  assetId: node.assetId,
@@ -4744,7 +5309,7 @@ Supported fuel-core version: ${supportedVersion}.`
4744
5309
  inputArgs: paginationArgs,
4745
5310
  paginationLimit: RESOURCES_PAGE_SIZE_LIMIT
4746
5311
  }),
4747
- owner: Address2.fromAddressOrString(address).toB256()
5312
+ owner: Address3.fromAddressOrString(address).toB256()
4748
5313
  });
4749
5314
  const messages = edges.map(({ node }) => ({
4750
5315
  messageId: InputMessageCoder.getMessageId({
@@ -4754,8 +5319,8 @@ Supported fuel-core version: ${supportedVersion}.`
4754
5319
  amount: bn17(node.amount),
4755
5320
  data: node.data
4756
5321
  }),
4757
- sender: Address2.fromAddressOrString(node.sender),
4758
- recipient: Address2.fromAddressOrString(node.recipient),
5322
+ sender: Address3.fromAddressOrString(node.sender),
5323
+ recipient: Address3.fromAddressOrString(node.recipient),
4759
5324
  nonce: node.nonce,
4760
5325
  amount: bn17(node.amount),
4761
5326
  data: InputMessageCoder.decodeData(node.data),
@@ -4781,7 +5346,7 @@ Supported fuel-core version: ${supportedVersion}.`
4781
5346
  nonce
4782
5347
  };
4783
5348
  if (commitBlockId && commitBlockHeight) {
4784
- throw new FuelError13(
5349
+ throw new FuelError15(
4785
5350
  ErrorCode13.INVALID_INPUT_PARAMETERS,
4786
5351
  "commitBlockId and commitBlockHeight cannot be used together"
4787
5352
  );
@@ -4853,8 +5418,8 @@ Supported fuel-core version: ${supportedVersion}.`
4853
5418
  eventInboxRoot: commitBlockHeader.eventInboxRoot,
4854
5419
  stateTransitionBytecodeVersion: Number(commitBlockHeader.stateTransitionBytecodeVersion)
4855
5420
  },
4856
- sender: Address2.fromAddressOrString(sender),
4857
- recipient: Address2.fromAddressOrString(recipient),
5421
+ sender: Address3.fromAddressOrString(sender),
5422
+ recipient: Address3.fromAddressOrString(recipient),
4858
5423
  nonce,
4859
5424
  amount: bn17(amount),
4860
5425
  data
@@ -4950,25 +5515,25 @@ Supported fuel-core version: ${supportedVersion}.`
4950
5515
  const { paginationLimit, inputArgs = {} } = params;
4951
5516
  const { first, last, after, before } = inputArgs;
4952
5517
  if (after && before) {
4953
- throw new FuelError13(
5518
+ throw new FuelError15(
4954
5519
  ErrorCode13.INVALID_INPUT_PARAMETERS,
4955
5520
  'Pagination arguments "after" and "before" cannot be used together'
4956
5521
  );
4957
5522
  }
4958
5523
  if ((first || 0) > paginationLimit || (last || 0) > paginationLimit) {
4959
- throw new FuelError13(
5524
+ throw new FuelError15(
4960
5525
  ErrorCode13.INVALID_INPUT_PARAMETERS,
4961
5526
  `Pagination limit for this query cannot exceed ${paginationLimit} items`
4962
5527
  );
4963
5528
  }
4964
5529
  if (first && before) {
4965
- throw new FuelError13(
5530
+ throw new FuelError15(
4966
5531
  ErrorCode13.INVALID_INPUT_PARAMETERS,
4967
5532
  'The use of pagination argument "first" with "before" is not supported'
4968
5533
  );
4969
5534
  }
4970
5535
  if (last && after) {
4971
- throw new FuelError13(
5536
+ throw new FuelError15(
4972
5537
  ErrorCode13.INVALID_INPUT_PARAMETERS,
4973
5538
  'The use of pagination argument "last" with "after" is not supported'
4974
5539
  );
@@ -5000,15 +5565,22 @@ Supported fuel-core version: ${supportedVersion}.`
5000
5565
  };
5001
5566
  var Provider = _Provider;
5002
5567
  _cacheInputs = new WeakSet();
5003
- cacheInputs_fn = function(inputs) {
5568
+ cacheInputs_fn = function(inputs, transactionId) {
5004
5569
  if (!this.cache) {
5005
5570
  return;
5006
5571
  }
5007
- inputs.forEach((input) => {
5008
- if (input.type === InputType7.Coin) {
5009
- this.cache?.set(input.id);
5010
- }
5011
- });
5572
+ const inputsToCache = inputs.reduce(
5573
+ (acc, input) => {
5574
+ if (input.type === InputType7.Coin) {
5575
+ acc.utxos.push(input.id);
5576
+ } else if (input.type === InputType7.Message) {
5577
+ acc.messages.push(input.nonce);
5578
+ }
5579
+ return acc;
5580
+ },
5581
+ { utxos: [], messages: [] }
5582
+ );
5583
+ this.cache.set(transactionId, inputsToCache);
5012
5584
  };
5013
5585
  /** @hidden */
5014
5586
  __publicField(Provider, "chainInfoCache", {});
@@ -5016,10 +5588,10 @@ __publicField(Provider, "chainInfoCache", {});
5016
5588
  __publicField(Provider, "nodeInfoCache", {});
5017
5589
 
5018
5590
  // src/providers/transaction-summary/get-transaction-summary.ts
5019
- import { ErrorCode as ErrorCode14, FuelError as FuelError14 } from "@fuel-ts/errors";
5591
+ import { ErrorCode as ErrorCode14, FuelError as FuelError16 } from "@fuel-ts/errors";
5020
5592
  import { bn as bn18 } from "@fuel-ts/math";
5021
5593
  import { TransactionCoder as TransactionCoder6 } from "@fuel-ts/transactions";
5022
- import { arrayify as arrayify12 } from "@fuel-ts/utils";
5594
+ import { arrayify as arrayify13 } from "@fuel-ts/utils";
5023
5595
 
5024
5596
  // src/providers/chains.ts
5025
5597
  var CHAIN_IDS = {
@@ -5092,19 +5664,75 @@ var rawAssets = [
5092
5664
  ];
5093
5665
  var assets = resolveIconPaths(rawAssets, fuelAssetsBaseUrl);
5094
5666
 
5667
+ // src/test-utils/test-asset-id.ts
5668
+ import { randomBytes as randomBytes4 } from "@fuel-ts/crypto";
5669
+ import { hexlify as hexlify15 } from "@fuel-ts/utils";
5670
+ var _TestAssetId = class {
5671
+ constructor(value) {
5672
+ this.value = value;
5673
+ }
5674
+ static random(count = 1) {
5675
+ const assetIds = [];
5676
+ for (let i = 0; i < count; i++) {
5677
+ assetIds.push(new _TestAssetId(hexlify15(randomBytes4(32))));
5678
+ }
5679
+ return assetIds;
5680
+ }
5681
+ };
5682
+ var TestAssetId = _TestAssetId;
5683
+ __publicField(TestAssetId, "A", new _TestAssetId(
5684
+ "0x0101010101010101010101010101010101010101010101010101010101010101"
5685
+ ));
5686
+ __publicField(TestAssetId, "B", new _TestAssetId(
5687
+ "0x0202020202020202020202020202020202020202020202020202020202020202"
5688
+ ));
5689
+
5690
+ // src/test-utils/wallet-config.ts
5691
+ import { randomBytes as randomBytes8 } from "@fuel-ts/crypto";
5692
+ import { FuelError as FuelError22 } from "@fuel-ts/errors";
5693
+ import { defaultSnapshotConfigs as defaultSnapshotConfigs2, hexlify as hexlify21 } from "@fuel-ts/utils";
5694
+
5695
+ // src/wallet/base-wallet-unlocked.ts
5696
+ import { hashMessage } from "@fuel-ts/hasher";
5697
+ import { hexlify as hexlify18 } from "@fuel-ts/utils";
5698
+
5699
+ // src/account.ts
5700
+ import { UTXO_ID_LEN as UTXO_ID_LEN3 } from "@fuel-ts/abi-coder";
5701
+ import { Address as Address4 } from "@fuel-ts/address";
5702
+ import { randomBytes as randomBytes5 } from "@fuel-ts/crypto";
5703
+ import { ErrorCode as ErrorCode15, FuelError as FuelError17 } from "@fuel-ts/errors";
5704
+ import { AbstractAccount } from "@fuel-ts/interfaces";
5705
+ import { bn as bn19 } from "@fuel-ts/math";
5706
+ import { arrayify as arrayify15, hexlify as hexlify16, isDefined as isDefined3 } from "@fuel-ts/utils";
5707
+ import { clone as clone4 } from "ramda";
5708
+
5709
+ // src/providers/utils/merge-quantities.ts
5710
+ var mergeQuantities = (...coinQuantities) => {
5711
+ const resultMap = {};
5712
+ function addToMap({ amount, assetId }) {
5713
+ if (resultMap[assetId]) {
5714
+ resultMap[assetId] = resultMap[assetId].add(amount);
5715
+ } else {
5716
+ resultMap[assetId] = amount;
5717
+ }
5718
+ }
5719
+ coinQuantities.forEach((arr) => arr.forEach(addToMap));
5720
+ return Object.entries(resultMap).map(([assetId, amount]) => ({ assetId, amount }));
5721
+ };
5722
+
5095
5723
  // src/utils/formatTransferToContractScriptData.ts
5096
5724
  import { BigNumberCoder as BigNumberCoder2 } from "@fuel-ts/abi-coder";
5097
- import { BN as BN2 } from "@fuel-ts/math";
5098
- import { arrayify as arrayify13 } from "@fuel-ts/utils";
5725
+ import { BN as BN3 } from "@fuel-ts/math";
5726
+ import { arrayify as arrayify14 } from "@fuel-ts/utils";
5099
5727
  import * as asm from "@fuels/vm-asm";
5100
5728
  var formatTransferToContractScriptData = (params) => {
5101
5729
  const { assetId, amountToTransfer, hexlifiedContractId } = params;
5102
5730
  const numberCoder = new BigNumberCoder2("u64");
5103
- const encoded = numberCoder.encode(new BN2(amountToTransfer).toNumber());
5731
+ const encoded = numberCoder.encode(new BN3(amountToTransfer).toNumber());
5104
5732
  const scriptData = Uint8Array.from([
5105
- ...arrayify13(hexlifiedContractId),
5733
+ ...arrayify14(hexlifiedContractId),
5106
5734
  ...encoded,
5107
- ...arrayify13(assetId)
5735
+ ...arrayify14(assetId)
5108
5736
  ]);
5109
5737
  return scriptData;
5110
5738
  };
@@ -5129,7 +5757,7 @@ var assembleTransferToContractScript = async (params) => {
5129
5757
  };
5130
5758
 
5131
5759
  // src/account.ts
5132
- var MAX_FUNDING_ATTEMPTS = 2;
5760
+ var MAX_FUNDING_ATTEMPTS = 5;
5133
5761
  var Account = class extends AbstractAccount {
5134
5762
  /**
5135
5763
  * The address associated with the account.
@@ -5154,7 +5782,7 @@ var Account = class extends AbstractAccount {
5154
5782
  super();
5155
5783
  this._provider = provider;
5156
5784
  this._connector = connector;
5157
- this.address = Address3.fromDynamicInput(address);
5785
+ this.address = Address4.fromDynamicInput(address);
5158
5786
  }
5159
5787
  /**
5160
5788
  * The provider used to interact with the network.
@@ -5165,7 +5793,7 @@ var Account = class extends AbstractAccount {
5165
5793
  */
5166
5794
  get provider() {
5167
5795
  if (!this._provider) {
5168
- throw new FuelError15(ErrorCode15.MISSING_PROVIDER, "Provider not set");
5796
+ throw new FuelError17(ErrorCode15.MISSING_PROVIDER, "Provider not set");
5169
5797
  }
5170
5798
  return this._provider;
5171
5799
  }
@@ -5242,7 +5870,7 @@ var Account = class extends AbstractAccount {
5242
5870
  * @returns A promise that resolves to the funded transaction request.
5243
5871
  */
5244
5872
  async fund(request, params) {
5245
- const { addedSignatures, estimatedPredicates, requiredQuantities, updateMaxFee } = params;
5873
+ const { addedSignatures, estimatedPredicates, requiredQuantities, updateMaxFee, gasPrice } = params;
5246
5874
  const fee = request.maxFee;
5247
5875
  const baseAssetId = this.provider.getBaseAssetId();
5248
5876
  const requiredInBaseAsset = requiredQuantities.find((quantity) => quantity.assetId === baseAssetId)?.amount || bn19(0);
@@ -5290,10 +5918,12 @@ var Account = class extends AbstractAccount {
5290
5918
  );
5291
5919
  }
5292
5920
  if (!updateMaxFee) {
5921
+ needsToBeFunded = false;
5293
5922
  break;
5294
5923
  }
5295
5924
  const { maxFee: newFee } = await this.provider.estimateTxGasAndFee({
5296
- transactionRequest: requestToReestimate2
5925
+ transactionRequest: requestToReestimate2,
5926
+ gasPrice
5297
5927
  });
5298
5928
  const totalBaseAssetOnInputs = getAssetAmountInRequestInputs(
5299
5929
  request.inputs,
@@ -5313,6 +5943,12 @@ var Account = class extends AbstractAccount {
5313
5943
  }
5314
5944
  fundingAttempts += 1;
5315
5945
  }
5946
+ if (needsToBeFunded) {
5947
+ throw new FuelError17(
5948
+ ErrorCode15.NOT_ENOUGH_FUNDS,
5949
+ `The account ${this.address} does not have enough base asset funds to cover the transaction execution.`
5950
+ );
5951
+ }
5316
5952
  request.updatePredicateGasUsed(estimatedPredicates);
5317
5953
  const requestToReestimate = clone4(request);
5318
5954
  if (addedSignatures) {
@@ -5379,7 +6015,7 @@ var Account = class extends AbstractAccount {
5379
6015
  const { destination, amount, assetId } = transferParams;
5380
6016
  this.validateTransferAmount(amount);
5381
6017
  request.addCoinOutput(
5382
- Address3.fromAddressOrString(destination),
6018
+ Address4.fromAddressOrString(destination),
5383
6019
  amount,
5384
6020
  assetId ?? this.provider.getBaseAssetId()
5385
6021
  );
@@ -5414,12 +6050,12 @@ var Account = class extends AbstractAccount {
5414
6050
  */
5415
6051
  async transferToContract(contractId, amount, assetId, txParams = {}) {
5416
6052
  if (bn19(amount).lte(0)) {
5417
- throw new FuelError15(
6053
+ throw new FuelError17(
5418
6054
  ErrorCode15.INVALID_TRANSFER_AMOUNT,
5419
6055
  "Transfer amount must be a positive number."
5420
6056
  );
5421
6057
  }
5422
- const contractAddress = Address3.fromAddressOrString(contractId);
6058
+ const contractAddress = Address4.fromAddressOrString(contractId);
5423
6059
  const assetIdToTransfer = assetId ?? this.provider.getBaseAssetId();
5424
6060
  const { script, scriptData } = await assembleTransferToContractScript({
5425
6061
  hexlifiedContractId: contractAddress.toB256(),
@@ -5432,9 +6068,8 @@ var Account = class extends AbstractAccount {
5432
6068
  scriptData
5433
6069
  });
5434
6070
  request.addContractInputAndOutput(contractAddress);
5435
- const txCost = await this.provider.getTransactionCost(request, {
5436
- resourcesOwner: this,
5437
- quantitiesToContract: [{ amount: bn19(amount), assetId: String(assetIdToTransfer) }]
6071
+ const txCost = await this.getTransactionCost(request, {
6072
+ quantities: [{ amount: bn19(amount), assetId: String(assetIdToTransfer) }]
5438
6073
  });
5439
6074
  request = this.validateGasLimitAndMaxFee({
5440
6075
  transactionRequest: request,
@@ -5454,23 +6089,23 @@ var Account = class extends AbstractAccount {
5454
6089
  * @returns A promise that resolves to the transaction response.
5455
6090
  */
5456
6091
  async withdrawToBaseLayer(recipient, amount, txParams = {}) {
5457
- const recipientAddress = Address3.fromAddressOrString(recipient);
5458
- const recipientDataArray = arrayify14(
6092
+ const recipientAddress = Address4.fromAddressOrString(recipient);
6093
+ const recipientDataArray = arrayify15(
5459
6094
  "0x".concat(recipientAddress.toHexString().substring(2).padStart(64, "0"))
5460
6095
  );
5461
- const amountDataArray = arrayify14(
6096
+ const amountDataArray = arrayify15(
5462
6097
  "0x".concat(bn19(amount).toHex().substring(2).padStart(16, "0"))
5463
6098
  );
5464
6099
  const script = new Uint8Array([
5465
- ...arrayify14(withdrawScript.bytes),
6100
+ ...arrayify15(withdrawScript.bytes),
5466
6101
  ...recipientDataArray,
5467
6102
  ...amountDataArray
5468
6103
  ]);
5469
6104
  const params = { script, ...txParams };
5470
6105
  const baseAssetId = this.provider.getBaseAssetId();
5471
6106
  let request = new ScriptTransactionRequest(params);
5472
- const quantitiesToContract = [{ amount: bn19(amount), assetId: baseAssetId }];
5473
- const txCost = await this.provider.getTransactionCost(request, { quantitiesToContract });
6107
+ const quantities = [{ amount: bn19(amount), assetId: baseAssetId }];
6108
+ const txCost = await this.getTransactionCost(request, { quantities });
5474
6109
  request = this.validateGasLimitAndMaxFee({
5475
6110
  transactionRequest: request,
5476
6111
  gasUsed: txCost.gasUsed,
@@ -5480,6 +6115,58 @@ var Account = class extends AbstractAccount {
5480
6115
  await this.fund(request, txCost);
5481
6116
  return this.sendTransaction(request);
5482
6117
  }
6118
+ /**
6119
+ * Returns a transaction cost to enable user
6120
+ * to set gasLimit and also reserve balance amounts
6121
+ * on the transaction.
6122
+ *
6123
+ * @param transactionRequestLike - The transaction request object.
6124
+ * @param transactionCostParams - The transaction cost parameters (optional).
6125
+ *
6126
+ * @returns A promise that resolves to the transaction cost object.
6127
+ */
6128
+ async getTransactionCost(transactionRequestLike, { signatureCallback, quantities = [] } = {}) {
6129
+ const txRequestClone = clone4(transactionRequestify(transactionRequestLike));
6130
+ const baseAssetId = this.provider.getBaseAssetId();
6131
+ const coinOutputsQuantities = txRequestClone.getCoinOutputsQuantities();
6132
+ const requiredQuantities = mergeQuantities(coinOutputsQuantities, quantities);
6133
+ const transactionFeeForDryRun = [{ assetId: baseAssetId, amount: bn19("100000000000000000") }];
6134
+ const findAssetInput = (assetId) => txRequestClone.inputs.find((input) => {
6135
+ if ("assetId" in input) {
6136
+ return input.assetId === assetId;
6137
+ }
6138
+ if ("recipient" in input) {
6139
+ return baseAssetId === assetId;
6140
+ }
6141
+ return false;
6142
+ });
6143
+ const updateAssetInput = (assetId, quantity) => {
6144
+ const assetInput = findAssetInput(assetId);
6145
+ const usedQuantity = quantity;
6146
+ if (assetInput && "amount" in assetInput) {
6147
+ assetInput.amount = usedQuantity;
6148
+ } else {
6149
+ txRequestClone.addResources(
6150
+ this.generateFakeResources([
6151
+ {
6152
+ amount: quantity,
6153
+ assetId
6154
+ }
6155
+ ])
6156
+ );
6157
+ }
6158
+ };
6159
+ mergeQuantities(requiredQuantities, transactionFeeForDryRun).forEach(
6160
+ ({ amount, assetId }) => updateAssetInput(assetId, amount)
6161
+ );
6162
+ const txCost = await this.provider.getTransactionCost(txRequestClone, {
6163
+ signatureCallback
6164
+ });
6165
+ return {
6166
+ ...txCost,
6167
+ requiredQuantities
6168
+ };
6169
+ }
5483
6170
  /**
5484
6171
  * Sign a message from the account via the connector.
5485
6172
  *
@@ -5490,7 +6177,7 @@ var Account = class extends AbstractAccount {
5490
6177
  */
5491
6178
  async signMessage(message) {
5492
6179
  if (!this._connector) {
5493
- throw new FuelError15(ErrorCode15.MISSING_CONNECTOR, "A connector is required to sign messages.");
6180
+ throw new FuelError17(ErrorCode15.MISSING_CONNECTOR, "A connector is required to sign messages.");
5494
6181
  }
5495
6182
  return this._connector.signMessage(this.address.toString(), message);
5496
6183
  }
@@ -5502,7 +6189,7 @@ var Account = class extends AbstractAccount {
5502
6189
  */
5503
6190
  async signTransaction(transactionRequestLike) {
5504
6191
  if (!this._connector) {
5505
- throw new FuelError15(
6192
+ throw new FuelError17(
5506
6193
  ErrorCode15.MISSING_CONNECTOR,
5507
6194
  "A connector is required to sign transactions."
5508
6195
  );
@@ -5516,7 +6203,7 @@ var Account = class extends AbstractAccount {
5516
6203
  * @param sendTransactionParams - The provider send transaction parameters (optional).
5517
6204
  * @returns A promise that resolves to the transaction response.
5518
6205
  */
5519
- async sendTransaction(transactionRequestLike, { estimateTxDependencies = true, awaitExecution } = {}) {
6206
+ async sendTransaction(transactionRequestLike, { estimateTxDependencies = true } = {}) {
5520
6207
  if (this._connector) {
5521
6208
  return this.provider.getTransactionResponse(
5522
6209
  await this._connector.sendTransaction(this.address.toString(), transactionRequestLike)
@@ -5527,7 +6214,6 @@ var Account = class extends AbstractAccount {
5527
6214
  await this.provider.estimateTxDependencies(transactionRequest);
5528
6215
  }
5529
6216
  return this.provider.sendTransaction(transactionRequest, {
5530
- awaitExecution,
5531
6217
  estimateTxDependencies: false
5532
6218
  });
5533
6219
  }
@@ -5553,7 +6239,7 @@ var Account = class extends AbstractAccount {
5553
6239
  */
5554
6240
  generateFakeResources(coins) {
5555
6241
  return coins.map((coin) => ({
5556
- id: hexlify13(randomBytes2(UTXO_ID_LEN3)),
6242
+ id: hexlify16(randomBytes5(UTXO_ID_LEN3)),
5557
6243
  owner: this.address,
5558
6244
  blockCreated: bn19(1),
5559
6245
  txCreatedIdx: bn19(1),
@@ -5563,7 +6249,7 @@ var Account = class extends AbstractAccount {
5563
6249
  /** @hidden * */
5564
6250
  validateTransferAmount(amount) {
5565
6251
  if (bn19(amount).lte(0)) {
5566
- throw new FuelError15(
6252
+ throw new FuelError17(
5567
6253
  ErrorCode15.INVALID_TRANSFER_AMOUNT,
5568
6254
  "Transfer amount must be a positive number."
5569
6255
  );
@@ -5572,9 +6258,7 @@ var Account = class extends AbstractAccount {
5572
6258
  /** @hidden * */
5573
6259
  async estimateAndFundTransaction(transactionRequest, txParams) {
5574
6260
  let request = transactionRequest;
5575
- const txCost = await this.provider.getTransactionCost(request, {
5576
- resourcesOwner: this
5577
- });
6261
+ const txCost = await this.getTransactionCost(request);
5578
6262
  request = this.validateGasLimitAndMaxFee({
5579
6263
  transactionRequest: request,
5580
6264
  gasUsed: txCost.gasUsed,
@@ -5586,138 +6270,29 @@ var Account = class extends AbstractAccount {
5586
6270
  }
5587
6271
  /** @hidden * */
5588
6272
  validateGasLimitAndMaxFee({
5589
- gasUsed,
5590
- maxFee,
5591
- transactionRequest,
5592
- txParams: { gasLimit: setGasLimit, maxFee: setMaxFee }
5593
- }) {
5594
- const request = transactionRequestify(transactionRequest);
5595
- if (!isDefined2(setGasLimit)) {
5596
- 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));
6273
+ gasUsed,
6274
+ maxFee,
6275
+ transactionRequest,
6276
+ txParams: { gasLimit: setGasLimit, maxFee: setMaxFee }
6277
+ }) {
6278
+ const request = transactionRequestify(transactionRequest);
6279
+ if (!isDefined3(setGasLimit)) {
6280
+ request.gasLimit = gasUsed;
6281
+ } else if (gasUsed.gt(setGasLimit)) {
6282
+ throw new FuelError17(
6283
+ ErrorCode15.GAS_LIMIT_TOO_LOW,
6284
+ `Gas limit '${setGasLimit}' is lower than the required: '${gasUsed}'.`
6285
+ );
6286
+ }
6287
+ if (!isDefined3(setMaxFee)) {
6288
+ request.maxFee = maxFee;
6289
+ } else if (maxFee.gt(setMaxFee)) {
6290
+ throw new FuelError17(
6291
+ ErrorCode15.MAX_FEE_TOO_LOW,
6292
+ `Max fee '${setMaxFee}' is lower than the required: '${maxFee}'.`
6293
+ );
6294
+ }
6295
+ return request;
5721
6296
  }
5722
6297
  };
5723
6298
 
@@ -5726,15 +6301,15 @@ import { Address as Address5 } from "@fuel-ts/address";
5726
6301
  import {
5727
6302
  bufferFromString,
5728
6303
  keccak256,
5729
- randomBytes as randomBytes4,
6304
+ randomBytes as randomBytes6,
5730
6305
  scrypt,
5731
6306
  stringFromBuffer,
5732
6307
  decryptJsonWalletData,
5733
- encryptJsonWalletData
6308
+ encryptJsonWalletData,
6309
+ randomUUID as randomUUID2
5734
6310
  } 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";
6311
+ import { ErrorCode as ErrorCode16, FuelError as FuelError18 } from "@fuel-ts/errors";
6312
+ import { hexlify as hexlify17 } from "@fuel-ts/utils";
5738
6313
  var DEFAULT_KDF_PARAMS_LOG_N = 13;
5739
6314
  var DEFAULT_KDF_PARAMS_R = 8;
5740
6315
  var DEFAULT_KDF_PARAMS_P = 1;
@@ -5749,7 +6324,7 @@ var removeHexPrefix = (hexString) => {
5749
6324
  async function encryptKeystoreWallet(privateKey, address, password) {
5750
6325
  const privateKeyBuffer = bufferFromString(removeHexPrefix(privateKey), "hex");
5751
6326
  const ownerAddress = Address5.fromAddressOrString(address);
5752
- const salt = randomBytes4(DEFAULT_KEY_SIZE);
6327
+ const salt = randomBytes6(DEFAULT_KEY_SIZE);
5753
6328
  const key = scrypt({
5754
6329
  password: bufferFromString(password),
5755
6330
  salt,
@@ -5758,13 +6333,13 @@ async function encryptKeystoreWallet(privateKey, address, password) {
5758
6333
  r: DEFAULT_KDF_PARAMS_R,
5759
6334
  p: DEFAULT_KDF_PARAMS_P
5760
6335
  });
5761
- const iv = randomBytes4(DEFAULT_IV_SIZE);
6336
+ const iv = randomBytes6(DEFAULT_IV_SIZE);
5762
6337
  const ciphertext = await encryptJsonWalletData(privateKeyBuffer, key, iv);
5763
6338
  const data = Uint8Array.from([...key.subarray(16, 32), ...ciphertext]);
5764
6339
  const macHashUint8Array = keccak256(data);
5765
6340
  const mac = stringFromBuffer(macHashUint8Array, "hex");
5766
6341
  const keystore = {
5767
- id: uuidv4(),
6342
+ id: randomUUID2(),
5768
6343
  version: 3,
5769
6344
  address: removeHexPrefix(ownerAddress.toHexString()),
5770
6345
  crypto: {
@@ -5810,13 +6385,13 @@ async function decryptKeystoreWallet(jsonWallet, password) {
5810
6385
  const macHashUint8Array = keccak256(data);
5811
6386
  const macHash = stringFromBuffer(macHashUint8Array, "hex");
5812
6387
  if (mac !== macHash) {
5813
- throw new FuelError16(
6388
+ throw new FuelError18(
5814
6389
  ErrorCode16.INVALID_PASSWORD,
5815
6390
  "Failed to decrypt the keystore wallet, the provided password is incorrect."
5816
6391
  );
5817
6392
  }
5818
6393
  const buffer = await decryptJsonWalletData(ciphertextBuffer, key, ivBuffer);
5819
- const privateKey = hexlify15(buffer);
6394
+ const privateKey = hexlify17(buffer);
5820
6395
  return privateKey;
5821
6396
  }
5822
6397
 
@@ -5861,7 +6436,7 @@ var BaseWalletUnlocked = class extends Account {
5861
6436
  */
5862
6437
  async signMessage(message) {
5863
6438
  const signedMessage = await this.signer().sign(hashMessage(message));
5864
- return hexlify16(signedMessage);
6439
+ return hexlify18(signedMessage);
5865
6440
  }
5866
6441
  /**
5867
6442
  * Signs a transaction with the wallet's private key.
@@ -5874,7 +6449,7 @@ var BaseWalletUnlocked = class extends Account {
5874
6449
  const chainId = this.provider.getChainId();
5875
6450
  const hashedTransaction = transactionRequest.getTransactionId(chainId);
5876
6451
  const signature = await this.signer().sign(hashedTransaction);
5877
- return hexlify16(signature);
6452
+ return hexlify18(signature);
5878
6453
  }
5879
6454
  /**
5880
6455
  * Populates a transaction with the witnesses signature.
@@ -5893,17 +6468,16 @@ var BaseWalletUnlocked = class extends Account {
5893
6468
  *
5894
6469
  * @param transactionRequestLike - The transaction request to send.
5895
6470
  * @param estimateTxDependencies - Whether to estimate the transaction dependencies.
5896
- * @param awaitExecution - Whether to wait for the transaction to be executed.
5897
6471
  * @returns A promise that resolves to the TransactionResponse object.
5898
6472
  */
5899
- async sendTransaction(transactionRequestLike, { estimateTxDependencies = false, awaitExecution } = {}) {
6473
+ async sendTransaction(transactionRequestLike, { estimateTxDependencies = false } = {}) {
5900
6474
  const transactionRequest = transactionRequestify(transactionRequestLike);
5901
6475
  if (estimateTxDependencies) {
5902
6476
  await this.provider.estimateTxDependencies(transactionRequest);
5903
6477
  }
5904
6478
  return this.provider.sendTransaction(
5905
6479
  await this.populateTransactionWitnessesSignature(transactionRequest),
5906
- { awaitExecution, estimateTxDependencies: false }
6480
+ { estimateTxDependencies: false }
5907
6481
  );
5908
6482
  }
5909
6483
  /**
@@ -5942,16 +6516,16 @@ __publicField(BaseWalletUnlocked, "defaultPath", "m/44'/1179993420'/0'/0/0");
5942
6516
 
5943
6517
  // src/hdwallet/hdwallet.ts
5944
6518
  import { computeHmac as computeHmac2, ripemd160 } from "@fuel-ts/crypto";
5945
- import { ErrorCode as ErrorCode19, FuelError as FuelError19 } from "@fuel-ts/errors";
6519
+ import { ErrorCode as ErrorCode19, FuelError as FuelError21 } from "@fuel-ts/errors";
5946
6520
  import { sha256 as sha2564 } from "@fuel-ts/hasher";
5947
6521
  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";
6522
+ import { arrayify as arrayify18, hexlify as hexlify20, concat as concat5, dataSlice as dataSlice2, encodeBase58 as encodeBase582, decodeBase58 } from "@fuel-ts/utils";
5949
6523
 
5950
6524
  // 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";
6525
+ import { randomBytes as randomBytes7, pbkdf2, computeHmac } from "@fuel-ts/crypto";
6526
+ import { ErrorCode as ErrorCode18, FuelError as FuelError20 } from "@fuel-ts/errors";
5953
6527
  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";
6528
+ import { arrayify as arrayify17, hexlify as hexlify19, concat as concat4, dataSlice, encodeBase58, toUtf8Bytes } from "@fuel-ts/utils";
5955
6529
 
5956
6530
  // src/wordlists/words/english.ts
5957
6531
  var english = [
@@ -8006,7 +8580,7 @@ var english = [
8006
8580
  ];
8007
8581
 
8008
8582
  // src/mnemonic/utils.ts
8009
- import { ErrorCode as ErrorCode17, FuelError as FuelError17 } from "@fuel-ts/errors";
8583
+ import { ErrorCode as ErrorCode17, FuelError as FuelError19 } from "@fuel-ts/errors";
8010
8584
  import { sha256 as sha2562 } from "@fuel-ts/hasher";
8011
8585
  import { arrayify as arrayify16 } from "@fuel-ts/utils";
8012
8586
  function getLowerMask(bits) {
@@ -8055,7 +8629,7 @@ function mnemonicWordsToEntropy(words, wordlist) {
8055
8629
  for (let i = 0; i < words.length; i += 1) {
8056
8630
  const index = wordlist.indexOf(words[i].normalize("NFKD"));
8057
8631
  if (index === -1) {
8058
- throw new FuelError17(
8632
+ throw new FuelError19(
8059
8633
  ErrorCode17.INVALID_MNEMONIC,
8060
8634
  `Invalid mnemonic: the word '${words[i]}' is not found in the provided wordlist.`
8061
8635
  );
@@ -8072,7 +8646,7 @@ function mnemonicWordsToEntropy(words, wordlist) {
8072
8646
  const checksumMask = getUpperMask(checksumBits);
8073
8647
  const checksum = arrayify16(sha2562(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
8074
8648
  if (checksum !== (entropy[entropy.length - 1] & checksumMask)) {
8075
- throw new FuelError17(
8649
+ throw new FuelError19(
8076
8650
  ErrorCode17.INVALID_CHECKSUM,
8077
8651
  "Checksum validation failed for the provided mnemonic."
8078
8652
  );
@@ -8087,7 +8661,7 @@ var TestnetPRV = "0x04358394";
8087
8661
  var MNEMONIC_SIZES = [12, 15, 18, 21, 24];
8088
8662
  function assertWordList(wordlist) {
8089
8663
  if (wordlist.length !== 2048) {
8090
- throw new FuelError18(
8664
+ throw new FuelError20(
8091
8665
  ErrorCode18.INVALID_WORD_LIST,
8092
8666
  `Expected word list length of 2048, but got ${wordlist.length}.`
8093
8667
  );
@@ -8095,7 +8669,7 @@ function assertWordList(wordlist) {
8095
8669
  }
8096
8670
  function assertEntropy(entropy) {
8097
8671
  if (entropy.length % 4 !== 0 || entropy.length < 16 || entropy.length > 32) {
8098
- throw new FuelError18(
8672
+ throw new FuelError20(
8099
8673
  ErrorCode18.INVALID_ENTROPY,
8100
8674
  `Entropy should be between 16 and 32 bytes and a multiple of 4, but got ${entropy.length} bytes.`
8101
8675
  );
@@ -8106,7 +8680,7 @@ function assertMnemonic(words) {
8106
8680
  const errorMsg = `Invalid mnemonic size. Expected one of [${MNEMONIC_SIZES.join(
8107
8681
  ", "
8108
8682
  )}] words, but got ${words.length}.`;
8109
- throw new FuelError18(ErrorCode18.INVALID_MNEMONIC, errorMsg);
8683
+ throw new FuelError20(ErrorCode18.INVALID_MNEMONIC, errorMsg);
8110
8684
  }
8111
8685
  }
8112
8686
  var Mnemonic = class {
@@ -8145,7 +8719,7 @@ var Mnemonic = class {
8145
8719
  static mnemonicToEntropy(phrase, wordlist = english) {
8146
8720
  const words = getWords(phrase);
8147
8721
  assertMnemonic(words);
8148
- return hexlify17(mnemonicWordsToEntropy(words, wordlist));
8722
+ return hexlify19(mnemonicWordsToEntropy(words, wordlist));
8149
8723
  }
8150
8724
  /**
8151
8725
  * @param entropy - Entropy source to the mnemonic phrase.
@@ -8224,7 +8798,7 @@ var Mnemonic = class {
8224
8798
  static masterKeysFromSeed(seed) {
8225
8799
  const seedArray = arrayify17(seed);
8226
8800
  if (seedArray.length < 16 || seedArray.length > 64) {
8227
- throw new FuelError18(
8801
+ throw new FuelError20(
8228
8802
  ErrorCode18.INVALID_SEED,
8229
8803
  `Seed length should be between 16 and 64 bytes, but received ${seedArray.length} bytes.`
8230
8804
  );
@@ -8270,7 +8844,7 @@ var Mnemonic = class {
8270
8844
  * @returns A randomly generated mnemonic
8271
8845
  */
8272
8846
  static generate(size = 32, extraEntropy = "") {
8273
- const entropy = extraEntropy ? sha2563(concat4([randomBytes5(size), arrayify17(extraEntropy)])) : randomBytes5(size);
8847
+ const entropy = extraEntropy ? sha2563(concat4([randomBytes7(size), arrayify17(extraEntropy)])) : randomBytes7(size);
8274
8848
  return Mnemonic.entropyToMnemonic(entropy);
8275
8849
  }
8276
8850
  };
@@ -8278,10 +8852,10 @@ var mnemonic_default = Mnemonic;
8278
8852
 
8279
8853
  // src/hdwallet/hdwallet.ts
8280
8854
  var HARDENED_INDEX = 2147483648;
8281
- var MainnetPRV2 = hexlify18("0x0488ade4");
8282
- var MainnetPUB = hexlify18("0x0488b21e");
8283
- var TestnetPRV2 = hexlify18("0x04358394");
8284
- var TestnetPUB = hexlify18("0x043587cf");
8855
+ var MainnetPRV2 = hexlify20("0x0488ade4");
8856
+ var MainnetPUB = hexlify20("0x0488b21e");
8857
+ var TestnetPRV2 = hexlify20("0x04358394");
8858
+ var TestnetPUB = hexlify20("0x043587cf");
8285
8859
  function base58check(data) {
8286
8860
  return encodeBase582(concat5([data, dataSlice2(sha2564(sha2564(data)), 0, 4)]));
8287
8861
  }
@@ -8292,17 +8866,17 @@ function getExtendedKeyPrefix(isPublic = false, testnet = false) {
8292
8866
  return testnet ? TestnetPRV2 : MainnetPRV2;
8293
8867
  }
8294
8868
  function isPublicExtendedKey(extendedKey) {
8295
- return [MainnetPUB, TestnetPUB].includes(hexlify18(extendedKey.slice(0, 4)));
8869
+ return [MainnetPUB, TestnetPUB].includes(hexlify20(extendedKey.slice(0, 4)));
8296
8870
  }
8297
8871
  function isValidExtendedKey(extendedKey) {
8298
8872
  return [MainnetPRV2, TestnetPRV2, MainnetPUB, TestnetPUB].includes(
8299
- hexlify18(extendedKey.slice(0, 4))
8873
+ hexlify20(extendedKey.slice(0, 4))
8300
8874
  );
8301
8875
  }
8302
8876
  function parsePath(path2, depth = 0) {
8303
8877
  const components = path2.split("/");
8304
8878
  if (components.length === 0 || components[0] === "m" && depth !== 0) {
8305
- throw new FuelError19(ErrorCode19.HD_WALLET_ERROR, `invalid path - ${path2}`);
8879
+ throw new FuelError21(ErrorCode19.HD_WALLET_ERROR, `invalid path - ${path2}`);
8306
8880
  }
8307
8881
  if (components[0] === "m") {
8308
8882
  components.shift();
@@ -8314,8 +8888,8 @@ function parsePath(path2, depth = 0) {
8314
8888
  var HDWallet = class {
8315
8889
  depth = 0;
8316
8890
  index = 0;
8317
- fingerprint = hexlify18("0x00000000");
8318
- parentFingerprint = hexlify18("0x00000000");
8891
+ fingerprint = hexlify20("0x00000000");
8892
+ parentFingerprint = hexlify20("0x00000000");
8319
8893
  privateKey;
8320
8894
  publicKey;
8321
8895
  chainCode;
@@ -8327,16 +8901,16 @@ var HDWallet = class {
8327
8901
  constructor(config) {
8328
8902
  if (config.privateKey) {
8329
8903
  const signer = new Signer(config.privateKey);
8330
- this.publicKey = hexlify18(signer.compressedPublicKey);
8331
- this.privateKey = hexlify18(config.privateKey);
8904
+ this.publicKey = hexlify20(signer.compressedPublicKey);
8905
+ this.privateKey = hexlify20(config.privateKey);
8332
8906
  } else {
8333
8907
  if (!config.publicKey) {
8334
- throw new FuelError19(
8908
+ throw new FuelError21(
8335
8909
  ErrorCode19.HD_WALLET_ERROR,
8336
8910
  "Both public and private Key cannot be missing. At least one should be provided."
8337
8911
  );
8338
8912
  }
8339
- this.publicKey = hexlify18(config.publicKey);
8913
+ this.publicKey = hexlify20(config.publicKey);
8340
8914
  }
8341
8915
  this.parentFingerprint = config.parentFingerprint || this.parentFingerprint;
8342
8916
  this.fingerprint = dataSlice2(ripemd160(sha2564(this.publicKey)), 0, 4);
@@ -8361,7 +8935,7 @@ var HDWallet = class {
8361
8935
  const data = new Uint8Array(37);
8362
8936
  if (index & HARDENED_INDEX) {
8363
8937
  if (!privateKey) {
8364
- throw new FuelError19(
8938
+ throw new FuelError21(
8365
8939
  ErrorCode19.HD_WALLET_ERROR,
8366
8940
  "Cannot derive a hardened index without a private Key."
8367
8941
  );
@@ -8385,7 +8959,7 @@ var HDWallet = class {
8385
8959
  parentFingerprint: this.fingerprint
8386
8960
  });
8387
8961
  }
8388
- const signer = new Signer(hexlify18(IL));
8962
+ const signer = new Signer(hexlify20(IL));
8389
8963
  const Ki = signer.addPoint(publicKey);
8390
8964
  return new HDWallet({
8391
8965
  publicKey: Ki,
@@ -8414,13 +8988,13 @@ var HDWallet = class {
8414
8988
  */
8415
8989
  toExtendedKey(isPublic = false, testnet = false) {
8416
8990
  if (this.depth >= 256) {
8417
- throw new FuelError19(
8991
+ throw new FuelError21(
8418
8992
  ErrorCode19.HD_WALLET_ERROR,
8419
8993
  `Exceeded max depth of 255. Current depth: ${this.depth}.`
8420
8994
  );
8421
8995
  }
8422
8996
  const prefix = getExtendedKeyPrefix(this.privateKey == null || isPublic, testnet);
8423
- const depth = hexlify18(Uint8Array.from([this.depth]));
8997
+ const depth = hexlify20(Uint8Array.from([this.depth]));
8424
8998
  const parentFingerprint = this.parentFingerprint;
8425
8999
  const index = toHex(this.index, 4);
8426
9000
  const chainCode = this.chainCode;
@@ -8442,29 +9016,29 @@ var HDWallet = class {
8442
9016
  });
8443
9017
  }
8444
9018
  static fromExtendedKey(extendedKey) {
8445
- const decoded = hexlify18(toBytes2(decodeBase58(extendedKey)));
9019
+ const decoded = hexlify20(toBytes2(decodeBase58(extendedKey)));
8446
9020
  const bytes = arrayify18(decoded);
8447
9021
  const validChecksum = base58check(bytes.slice(0, 78)) === extendedKey;
8448
9022
  if (bytes.length !== 82 || !isValidExtendedKey(bytes)) {
8449
- throw new FuelError19(ErrorCode19.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
9023
+ throw new FuelError21(ErrorCode19.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
8450
9024
  }
8451
9025
  if (!validChecksum) {
8452
- throw new FuelError19(ErrorCode19.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
9026
+ throw new FuelError21(ErrorCode19.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
8453
9027
  }
8454
9028
  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));
9029
+ const parentFingerprint = hexlify20(bytes.slice(5, 9));
9030
+ const index = parseInt(hexlify20(bytes.slice(9, 13)).substring(2), 16);
9031
+ const chainCode = hexlify20(bytes.slice(13, 45));
8458
9032
  const key = bytes.slice(45, 78);
8459
9033
  if (depth === 0 && parentFingerprint !== "0x00000000" || depth === 0 && index !== 0) {
8460
- throw new FuelError19(
9034
+ throw new FuelError21(
8461
9035
  ErrorCode19.HD_WALLET_ERROR,
8462
9036
  "Inconsistency detected: Depth is zero but fingerprint/index is non-zero."
8463
9037
  );
8464
9038
  }
8465
9039
  if (isPublicExtendedKey(bytes)) {
8466
9040
  if (key[0] !== 3) {
8467
- throw new FuelError19(ErrorCode19.HD_WALLET_ERROR, "Invalid public extended key.");
9041
+ throw new FuelError21(ErrorCode19.HD_WALLET_ERROR, "Invalid public extended key.");
8468
9042
  }
8469
9043
  return new HDWallet({
8470
9044
  publicKey: key,
@@ -8475,7 +9049,7 @@ var HDWallet = class {
8475
9049
  });
8476
9050
  }
8477
9051
  if (key[0] !== 0) {
8478
- throw new FuelError19(ErrorCode19.HD_WALLET_ERROR, "Invalid private extended key.");
9052
+ throw new FuelError21(ErrorCode19.HD_WALLET_ERROR, "Invalid private extended key.");
8479
9053
  }
8480
9054
  return new HDWallet({
8481
9055
  privateKey: key.slice(1),
@@ -8640,292 +9214,7 @@ __publicField(Wallet, "fromExtendedKey", WalletUnlocked.fromExtendedKey);
8640
9214
  */
8641
9215
  __publicField(Wallet, "fromEncryptedJson", WalletUnlocked.fromEncryptedJson);
8642
9216
 
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
9217
  // 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
9218
  var WalletsConfig = class {
8930
9219
  initialState;
8931
9220
  options;
@@ -8933,7 +9222,7 @@ var WalletsConfig = class {
8933
9222
  generateWallets = () => {
8934
9223
  const generatedWallets = [];
8935
9224
  for (let index = 1; index <= this.options.count; index++) {
8936
- generatedWallets.push(new WalletUnlocked(randomBytes9(32)));
9225
+ generatedWallets.push(new WalletUnlocked(randomBytes8(32)));
8937
9226
  }
8938
9227
  return generatedWallets;
8939
9228
  };
@@ -8978,7 +9267,7 @@ var WalletsConfig = class {
8978
9267
  if (Array.isArray(assets2)) {
8979
9268
  assetIds = assetIds.concat(assets2.map((a) => a.value));
8980
9269
  } else {
8981
- assetIds = assetIds.concat(AssetId.random(assets2 - 1).map((a) => a.value));
9270
+ assetIds = assetIds.concat(TestAssetId.random(assets2 - 1).map((a) => a.value));
8982
9271
  }
8983
9272
  wallets.map((wallet) => wallet.address.toHexString()).forEach((walletAddress) => {
8984
9273
  assetIds.forEach((assetId) => {
@@ -8990,7 +9279,7 @@ var WalletsConfig = class {
8990
9279
  tx_pointer_block_height: 0,
8991
9280
  tx_pointer_tx_idx: 0,
8992
9281
  output_index: 0,
8993
- tx_id: hexlify21(randomBytes9(32))
9282
+ tx_id: hexlify21(randomBytes8(32))
8994
9283
  });
8995
9284
  }
8996
9285
  });
@@ -9004,27 +9293,27 @@ var WalletsConfig = class {
9004
9293
  amountPerCoin
9005
9294
  }) {
9006
9295
  if (Array.isArray(wallets) && wallets.length === 0 || typeof wallets === "number" && wallets <= 0) {
9007
- throw new FuelError21(
9008
- FuelError21.CODES.INVALID_INPUT_PARAMETERS,
9296
+ throw new FuelError22(
9297
+ FuelError22.CODES.INVALID_INPUT_PARAMETERS,
9009
9298
  "Number of wallets must be greater than zero."
9010
9299
  );
9011
9300
  }
9012
9301
  if (Array.isArray(assets2) && assets2.length === 0 || typeof assets2 === "number" && assets2 <= 0) {
9013
- throw new FuelError21(
9014
- FuelError21.CODES.INVALID_INPUT_PARAMETERS,
9302
+ throw new FuelError22(
9303
+ FuelError22.CODES.INVALID_INPUT_PARAMETERS,
9015
9304
  "Number of assets per wallet must be greater than zero."
9016
9305
  );
9017
9306
  }
9018
9307
  if (coinsPerAsset <= 0) {
9019
- throw new FuelError21(
9020
- FuelError21.CODES.INVALID_INPUT_PARAMETERS,
9308
+ throw new FuelError22(
9309
+ FuelError22.CODES.INVALID_INPUT_PARAMETERS,
9021
9310
  "Number of coins per asset must be greater than zero."
9022
9311
  );
9023
9312
  }
9024
- if (amountPerCoin <= 0) {
9025
- throw new FuelError21(
9026
- FuelError21.CODES.INVALID_INPUT_PARAMETERS,
9027
- "Amount per coin must be greater than zero."
9313
+ if (amountPerCoin < 0) {
9314
+ throw new FuelError22(
9315
+ FuelError22.CODES.INVALID_INPUT_PARAMETERS,
9316
+ "Amount per coin must be greater than or equal to zero."
9028
9317
  );
9029
9318
  }
9030
9319
  }
@@ -9033,7 +9322,7 @@ var WalletsConfig = class {
9033
9322
  // src/test-utils/setup-test-provider-and-wallets.ts
9034
9323
  var defaultWalletConfigOptions = {
9035
9324
  count: 2,
9036
- assets: [AssetId.A, AssetId.B],
9325
+ assets: [TestAssetId.A, TestAssetId.B],
9037
9326
  coinsPerAsset: 1,
9038
9327
  amountPerCoin: 1e10,
9039
9328
  messages: []
@@ -9059,7 +9348,7 @@ async function setupTestProviderAndWallets({
9059
9348
  defaultSnapshotConfigs3,
9060
9349
  walletsConfig.apply(nodeOptions?.snapshotConfig)
9061
9350
  ),
9062
- port: "0"
9351
+ port: nodeOptions.port || "0"
9063
9352
  };
9064
9353
  let cleanup;
9065
9354
  let url;
@@ -9095,7 +9384,7 @@ async function setupTestProviderAndWallets({
9095
9384
 
9096
9385
  // src/test-utils/test-message.ts
9097
9386
  import { Address as Address6 } from "@fuel-ts/address";
9098
- import { randomBytes as randomBytes10 } from "@fuel-ts/crypto";
9387
+ import { randomBytes as randomBytes9 } from "@fuel-ts/crypto";
9099
9388
  import { bn as bn21 } from "@fuel-ts/math";
9100
9389
  import { hexlify as hexlify22 } from "@fuel-ts/utils";
9101
9390
  var TestMessage = class {
@@ -9114,9 +9403,10 @@ var TestMessage = class {
9114
9403
  constructor({
9115
9404
  sender = Address6.fromRandom(),
9116
9405
  recipient = Address6.fromRandom(),
9117
- nonce = hexlify22(randomBytes10(32)),
9406
+ nonce = hexlify22(randomBytes9(32)),
9118
9407
  amount = 1e6,
9119
- data = "02",
9408
+ data = "",
9409
+ // Will default to empty data in order to be a spendable message
9120
9410
  da_height = 0
9121
9411
  } = {}) {
9122
9412
  this.sender = sender;
@@ -9127,24 +9417,22 @@ var TestMessage = class {
9127
9417
  this.da_height = da_height;
9128
9418
  }
9129
9419
  toChainMessage(recipient) {
9420
+ const data = /^0x/.test(this.data) ? this.data.replace(/^0x/, "") : this.data;
9130
9421
  return {
9131
9422
  sender: this.sender.toB256(),
9132
9423
  recipient: recipient?.toB256() ?? this.recipient.toB256(),
9133
9424
  nonce: this.nonce,
9134
9425
  amount: bn21(this.amount).toNumber(),
9135
- data: this.data,
9426
+ data,
9136
9427
  da_height: this.da_height
9137
9428
  };
9138
9429
  }
9139
9430
  };
9140
9431
  export {
9141
- AssetId,
9432
+ TestAssetId,
9142
9433
  TestMessage,
9143
9434
  WalletsConfig,
9144
- generateTestWallet,
9145
9435
  launchNode,
9146
- launchNodeAndGetWallets,
9147
- seedTestWallet,
9148
9436
  setupTestProviderAndWallets
9149
9437
  };
9150
9438
  //# sourceMappingURL=test-utils.mjs.map