@fuel-ts/account 0.93.0 → 0.94.1

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 (82) hide show
  1. package/README.md +9 -29
  2. package/dist/account.d.ts +2 -2
  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.map +1 -1
  13. package/dist/connectors/fuel.d.ts.map +1 -1
  14. package/dist/connectors/utils/promises.d.ts.map +1 -1
  15. package/dist/index.global.js +1628 -930
  16. package/dist/index.global.js.map +1 -1
  17. package/dist/index.js +978 -603
  18. package/dist/index.js.map +1 -1
  19. package/dist/index.mjs +706 -343
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/predicate/predicate.d.ts +15 -9
  22. package/dist/predicate/predicate.d.ts.map +1 -1
  23. package/dist/providers/__generated__/operations.d.ts +614 -1
  24. package/dist/providers/__generated__/operations.d.ts.map +1 -1
  25. package/dist/providers/fuel-graphql-subscriber.d.ts +2 -3
  26. package/dist/providers/fuel-graphql-subscriber.d.ts.map +1 -1
  27. package/dist/providers/provider.d.ts +12 -6
  28. package/dist/providers/provider.d.ts.map +1 -1
  29. package/dist/providers/resource-cache.d.ts +14 -0
  30. package/dist/providers/resource-cache.d.ts.map +1 -0
  31. package/dist/providers/transaction-request/blob-transaction-request.d.ts +48 -0
  32. package/dist/providers/transaction-request/blob-transaction-request.d.ts.map +1 -0
  33. package/dist/providers/transaction-request/index.d.ts +1 -0
  34. package/dist/providers/transaction-request/index.d.ts.map +1 -1
  35. package/dist/providers/transaction-request/transaction-request.d.ts +4 -3
  36. package/dist/providers/transaction-request/transaction-request.d.ts.map +1 -1
  37. package/dist/providers/transaction-request/types.d.ts +5 -2
  38. package/dist/providers/transaction-request/types.d.ts.map +1 -1
  39. package/dist/providers/transaction-request/utils.d.ts +9 -0
  40. package/dist/providers/transaction-request/utils.d.ts.map +1 -1
  41. package/dist/providers/transaction-response/transaction-response.d.ts +10 -5
  42. package/dist/providers/transaction-response/transaction-response.d.ts.map +1 -1
  43. package/dist/providers/transaction-summary/assemble-transaction-summary.d.ts +1 -1
  44. package/dist/providers/transaction-summary/assemble-transaction-summary.d.ts.map +1 -1
  45. package/dist/providers/transaction-summary/call.d.ts +4 -3
  46. package/dist/providers/transaction-summary/call.d.ts.map +1 -1
  47. package/dist/providers/transaction-summary/get-transaction-summary.d.ts.map +1 -1
  48. package/dist/providers/transaction-summary/input.d.ts +6 -1
  49. package/dist/providers/transaction-summary/input.d.ts.map +1 -1
  50. package/dist/providers/transaction-summary/operations.d.ts +4 -2
  51. package/dist/providers/transaction-summary/operations.d.ts.map +1 -1
  52. package/dist/providers/transaction-summary/types.d.ts +5 -2
  53. package/dist/providers/transaction-summary/types.d.ts.map +1 -1
  54. package/dist/providers/utils/gas.d.ts +6 -0
  55. package/dist/providers/utils/gas.d.ts.map +1 -1
  56. package/dist/test-utils/launchNode.d.ts +0 -18
  57. package/dist/test-utils/launchNode.d.ts.map +1 -1
  58. package/dist/test-utils/setup-test-provider-and-wallets.d.ts.map +1 -1
  59. package/dist/test-utils/test-asset-id.d.ts +8 -0
  60. package/dist/test-utils/test-asset-id.d.ts.map +1 -0
  61. package/dist/test-utils/test-message.d.ts +4 -2
  62. package/dist/test-utils/test-message.d.ts.map +1 -1
  63. package/dist/test-utils/wallet-config.d.ts +3 -3
  64. package/dist/test-utils/wallet-config.d.ts.map +1 -1
  65. package/dist/test-utils.d.ts +1 -3
  66. package/dist/test-utils.d.ts.map +1 -1
  67. package/dist/test-utils.global.js +40829 -40167
  68. package/dist/test-utils.global.js.map +1 -1
  69. package/dist/test-utils.js +1500 -1200
  70. package/dist/test-utils.js.map +1 -1
  71. package/dist/test-utils.mjs +1209 -910
  72. package/dist/test-utils.mjs.map +1 -1
  73. package/dist/wallet/keystore-wallet.d.ts.map +1 -1
  74. package/package.json +17 -19
  75. package/dist/providers/memory-cache.d.ts +0 -11
  76. package/dist/providers/memory-cache.d.ts.map +0 -1
  77. package/dist/test-utils/asset-id.d.ts +0 -8
  78. package/dist/test-utils/asset-id.d.ts.map +0 -1
  79. package/dist/test-utils/generateTestWallet.d.ts +0 -4
  80. package/dist/test-utils/generateTestWallet.d.ts.map +0 -1
  81. package/dist/test-utils/seedTestWallet.d.ts +0 -4
  82. 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 isDefined3 } 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,16 +381,11 @@ 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, isDefined as isDefined2 } 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";
@@ -85,14 +393,6 @@ import { clone as clone3 } from "ramda";
85
393
 
86
394
  // src/providers/__generated__/operations.ts
87
395
  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
- `;
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);
1550
+ }
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;
1186
1562
  }
1187
- return list;
1188
- }, []);
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,30 +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(
3200
+ throw new FuelError10(
2745
3201
  ErrorCode8.UNSUPPORTED_TRANSACTION_TYPE,
2746
3202
  `Unsupported transaction type: ${type}.`
2747
3203
  );
2748
3204
  }
2749
3205
  }
2750
3206
  };
3207
+ var isTransactionTypeScript = (request) => request.type === TransactionType5.Script;
3208
+ var isTransactionTypeCreate = (request) => request.type === TransactionType5.Create;
2751
3209
 
2752
3210
  // src/providers/transaction-response/transaction-response.ts
2753
- import { ErrorCode as ErrorCode12, FuelError as FuelError12 } from "@fuel-ts/errors";
3211
+ import { ErrorCode as ErrorCode12, FuelError as FuelError14 } from "@fuel-ts/errors";
2754
3212
  import { bn as bn16 } from "@fuel-ts/math";
2755
- import { TransactionCoder as TransactionCoder4 } from "@fuel-ts/transactions";
2756
- 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";
2757
3215
 
2758
3216
  // src/providers/transaction-summary/assemble-transaction-summary.ts
2759
3217
  import { bn as bn15 } from "@fuel-ts/math";
2760
3218
  import { PolicyType as PolicyType3 } from "@fuel-ts/transactions";
2761
- import { DateTime, hexlify as hexlify11 } from "@fuel-ts/utils";
3219
+ import { DateTime, hexlify as hexlify13 } from "@fuel-ts/utils";
2762
3220
 
2763
3221
  // src/providers/transaction-summary/calculate-tx-fee-for-summary.ts
2764
3222
  import { bn as bn12 } from "@fuel-ts/math";
2765
3223
  import { PolicyType as PolicyType2, TransactionCoder as TransactionCoder3, TransactionType as TransactionType6 } from "@fuel-ts/transactions";
2766
- import { arrayify as arrayify9 } from "@fuel-ts/utils";
3224
+ import { arrayify as arrayify10 } from "@fuel-ts/utils";
2767
3225
  var calculateTXFeeForSummary = (params) => {
2768
3226
  const {
2769
3227
  gasPrice,
@@ -2777,7 +3235,7 @@ var calculateTXFeeForSummary = (params) => {
2777
3235
  }
2778
3236
  const gasPerByte = bn12(feeParams.gasPerByte);
2779
3237
  const gasPriceFactor = bn12(feeParams.gasPriceFactor);
2780
- const transactionBytes = arrayify9(rawPayload);
3238
+ const transactionBytes = arrayify10(rawPayload);
2781
3239
  const [transaction] = new TransactionCoder3().decode(transactionBytes, 0);
2782
3240
  const { type, witnesses, inputs, policies } = transaction;
2783
3241
  let metadataGas = bn12(0);
@@ -2787,7 +3245,7 @@ var calculateTXFeeForSummary = (params) => {
2787
3245
  }
2788
3246
  if (type === TransactionType6.Create) {
2789
3247
  const { bytecodeWitnessIndex, storageSlots } = transaction;
2790
- const contractBytesSize = bn12(arrayify9(witnesses[bytecodeWitnessIndex].data).length);
3248
+ const contractBytesSize = bn12(arrayify10(witnesses[bytecodeWitnessIndex].data).length);
2791
3249
  metadataGas = calculateMetadataGasForTxCreate({
2792
3250
  contractBytesSize,
2793
3251
  gasCosts,
@@ -2832,7 +3290,7 @@ var calculateTXFeeForSummary = (params) => {
2832
3290
 
2833
3291
  // src/providers/transaction-summary/operations.ts
2834
3292
  import { ZeroBytes32 as ZeroBytes328 } from "@fuel-ts/address/configs";
2835
- import { ErrorCode as ErrorCode10, FuelError as FuelError10 } from "@fuel-ts/errors";
3293
+ import { ErrorCode as ErrorCode10, FuelError as FuelError12 } from "@fuel-ts/errors";
2836
3294
  import { bn as bn13 } from "@fuel-ts/math";
2837
3295
  import { ReceiptType as ReceiptType4, TransactionType as TransactionType7 } from "@fuel-ts/transactions";
2838
3296
 
@@ -2870,7 +3328,8 @@ var getFunctionCall = ({ abi, receipt }) => {
2870
3328
  };
2871
3329
 
2872
3330
  // src/providers/transaction-summary/input.ts
2873
- 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";
2874
3333
  import { InputType as InputType6 } from "@fuel-ts/transactions";
2875
3334
  function getInputsByTypes(inputs, types) {
2876
3335
  return inputs.filter((i) => types.includes(i.type));
@@ -2887,17 +3346,47 @@ function getInputsMessage(inputs) {
2887
3346
  function getInputsCoinAndMessage(inputs) {
2888
3347
  return getInputsByTypes(inputs, [InputType6.Coin, InputType6.Message]);
2889
3348
  }
3349
+ function isInputCoin(input) {
3350
+ return input.type === InputType6.Coin;
3351
+ }
2890
3352
  function getInputsContract(inputs) {
2891
3353
  return getInputsByType(inputs, InputType6.Contract);
2892
3354
  }
2893
- function getInputFromAssetId(inputs, assetId) {
3355
+ function findCoinInput(inputs, assetId) {
2894
3356
  const coinInputs = getInputsCoin(inputs);
2895
- const messageInputs = getInputsMessage(inputs);
2896
- const coinInput = coinInputs.find((i) => i.assetId === assetId);
2897
- const messageInput = messageInputs.find(
2898
- (_) => assetId === "0x0000000000000000000000000000000000000000000000000000000000000000"
2899
- );
2900
- 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;
2901
3390
  }
2902
3391
  function getInputContractFromIndex(inputs, inputIndex) {
2903
3392
  if (inputIndex == null) {
@@ -2908,7 +3397,7 @@ function getInputContractFromIndex(inputs, inputIndex) {
2908
3397
  return void 0;
2909
3398
  }
2910
3399
  if (contractInput.type !== InputType6.Contract) {
2911
- throw new FuelError9(
3400
+ throw new FuelError11(
2912
3401
  ErrorCode9.INVALID_TRANSACTION_INPUT,
2913
3402
  `Contract input should be of type 'contract'.`
2914
3403
  );
@@ -2955,8 +3444,10 @@ function getTransactionTypeName(transactionType) {
2955
3444
  return "Create" /* Create */;
2956
3445
  case TransactionType7.Script:
2957
3446
  return "Script" /* Script */;
3447
+ case TransactionType7.Blob:
3448
+ return "Blob" /* Blob */;
2958
3449
  default:
2959
- throw new FuelError10(
3450
+ throw new FuelError12(
2960
3451
  ErrorCode10.UNSUPPORTED_TRANSACTION_TYPE,
2961
3452
  `Unsupported transaction type: ${transactionType}.`
2962
3453
  );
@@ -2981,47 +3472,60 @@ function isTypeUpgrade(transactionType) {
2981
3472
  function isTypeUpload(transactionType) {
2982
3473
  return isType(transactionType, "Upload" /* Upload */);
2983
3474
  }
3475
+ function isTypeBlob(transactionType) {
3476
+ return isType(transactionType, "Blob" /* Blob */);
3477
+ }
2984
3478
  function getReceiptsCall(receipts) {
2985
3479
  return getReceiptsByType(receipts, ReceiptType4.Call);
2986
3480
  }
2987
3481
  function getReceiptsMessageOut(receipts) {
2988
3482
  return getReceiptsByType(receipts, ReceiptType4.MessageOut);
2989
3483
  }
2990
- var mergeAssets = (op1, op2) => {
3484
+ function mergeAssets(op1, op2) {
2991
3485
  const assets1 = op1.assetsSent || [];
2992
3486
  const assets2 = op2.assetsSent || [];
2993
- const filteredAssets = assets2.filter(
2994
- (asset2) => !assets1.some((asset1) => asset1.assetId === asset2.assetId)
2995
- );
2996
- const mergedAssets = assets1.map((asset1) => {
2997
- const matchingAsset = assets2.find((asset2) => asset2.assetId === asset1.assetId);
2998
- if (!matchingAsset) {
2999
- 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 });
3000
3497
  }
3001
- const mergedAmount = bn13(asset1.amount).add(matchingAsset.amount);
3002
- return { ...asset1, amount: mergedAmount };
3003
3498
  });
3004
- return mergedAssets.concat(filteredAssets);
3005
- };
3499
+ return Array.from(assetMap.values());
3500
+ }
3006
3501
  function isSameOperation(a, b) {
3007
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;
3008
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
+ }
3009
3523
  function addOperation(operations, toAdd) {
3010
- const allOperations = [...operations];
3011
- const index = allOperations.findIndex((op) => isSameOperation(op, toAdd));
3012
- if (allOperations[index]) {
3013
- const existentOperation = { ...allOperations[index] };
3014
- if (toAdd.assetsSent?.length) {
3015
- existentOperation.assetsSent = existentOperation.assetsSent?.length ? mergeAssets(existentOperation, toAdd) : toAdd.assetsSent;
3016
- }
3017
- if (toAdd.calls?.length) {
3018
- existentOperation.calls = [...existentOperation.calls || [], ...toAdd.calls];
3019
- }
3020
- allOperations[index] = existentOperation;
3021
- } else {
3022
- allOperations.push(toAdd);
3524
+ const existingIndex = operations.findIndex((op) => isSameOperation(op, toAdd));
3525
+ if (existingIndex === -1) {
3526
+ return [...operations, toAdd];
3023
3527
  }
3024
- return allOperations;
3528
+ return operations.map((op, index) => index === existingIndex ? mergeOperations(op, toAdd) : op);
3025
3529
  }
3026
3530
  function getWithdrawFromFuelOperations({
3027
3531
  inputs,
@@ -3031,7 +3535,7 @@ function getWithdrawFromFuelOperations({
3031
3535
  const messageOutReceipts = getReceiptsMessageOut(receipts);
3032
3536
  const withdrawFromFuelOperations = messageOutReceipts.reduce(
3033
3537
  (prevWithdrawFromFuelOps, receipt) => {
3034
- const input = getInputFromAssetId(inputs, baseAssetId);
3538
+ const input = getInputFromAssetId(inputs, baseAssetId, true);
3035
3539
  if (input) {
3036
3540
  const inputAddress = getInputAccountAddress(input);
3037
3541
  const newWithdrawFromFuelOps = addOperation(prevWithdrawFromFuelOps, {
@@ -3060,65 +3564,80 @@ function getWithdrawFromFuelOperations({
3060
3564
  );
3061
3565
  return withdrawFromFuelOperations;
3062
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
+ }
3063
3613
  function getContractCallOperations({
3064
3614
  inputs,
3065
3615
  outputs,
3066
3616
  receipts,
3067
3617
  abiMap,
3068
3618
  rawPayload,
3069
- maxInputs
3619
+ maxInputs,
3620
+ baseAssetId
3070
3621
  }) {
3071
3622
  const contractCallReceipts = getReceiptsCall(receipts);
3072
3623
  const contractOutputs = getOutputsContract(outputs);
3073
- const contractCallOperations = contractOutputs.reduce((prevOutputCallOps, output) => {
3624
+ return contractOutputs.flatMap((output) => {
3074
3625
  const contractInput = getInputContractFromIndex(inputs, output.inputIndex);
3075
- if (contractInput) {
3076
- const newCallOps = contractCallReceipts.reduce((prevContractCallOps, receipt) => {
3077
- if (receipt.to === contractInput.contractID) {
3078
- const input = getInputFromAssetId(inputs, receipt.assetId);
3079
- if (input) {
3080
- const inputAddress = getInputAccountAddress(input);
3081
- const calls = [];
3082
- const abi = abiMap?.[contractInput.contractID];
3083
- if (abi) {
3084
- calls.push(
3085
- getFunctionCall({
3086
- abi,
3087
- receipt,
3088
- rawPayload,
3089
- maxInputs
3090
- })
3091
- );
3092
- }
3093
- const newContractCallOps = addOperation(prevContractCallOps, {
3094
- name: "Contract call" /* contractCall */,
3095
- from: {
3096
- type: 1 /* account */,
3097
- address: inputAddress
3098
- },
3099
- to: {
3100
- type: 0 /* contract */,
3101
- address: receipt.to
3102
- },
3103
- // if no amount is forwarded to the contract, skip showing assetsSent
3104
- assetsSent: receipt.amount?.isZero() ? void 0 : [
3105
- {
3106
- amount: receipt.amount,
3107
- assetId: receipt.assetId
3108
- }
3109
- ],
3110
- calls
3111
- });
3112
- return newContractCallOps;
3113
- }
3114
- }
3115
- return prevContractCallOps;
3116
- }, prevOutputCallOps);
3117
- return newCallOps;
3626
+ if (!contractInput) {
3627
+ return [];
3118
3628
  }
3119
- return prevOutputCallOps;
3120
- }, []);
3121
- 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
+ });
3122
3641
  }
3123
3642
  function extractTransferOperationFromReceipt(receipt, contractInputs, changeOutputs) {
3124
3643
  const { to: toAddress, assetId, amount } = receipt;
@@ -3150,32 +3669,40 @@ function extractTransferOperationFromReceipt(receipt, contractInputs, changeOutp
3150
3669
  function getTransferOperations({
3151
3670
  inputs,
3152
3671
  outputs,
3153
- receipts
3672
+ receipts,
3673
+ baseAssetId
3154
3674
  }) {
3155
3675
  let operations = [];
3156
3676
  const coinOutputs = getOutputsCoin(outputs);
3157
3677
  const contractInputs = getInputsContract(inputs);
3158
3678
  const changeOutputs = getOutputsChange(outputs);
3159
- coinOutputs.forEach((output) => {
3160
- const { amount, assetId, to } = output;
3161
- const changeOutput = changeOutputs.find((change) => change.assetId === assetId);
3162
- 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) {
3163
3695
  operations = addOperation(operations, {
3164
3696
  name: "Transfer asset" /* transfer */,
3165
3697
  from: {
3166
3698
  type: 1 /* account */,
3167
- address: changeOutput.to
3699
+ address: selectedPayer
3168
3700
  },
3169
3701
  to: {
3170
3702
  type: 1 /* account */,
3171
3703
  address: to
3172
3704
  },
3173
- assetsSent: [
3174
- {
3175
- assetId,
3176
- amount
3177
- }
3178
- ]
3705
+ assetsSent: [{ assetId, amount }]
3179
3706
  });
3180
3707
  }
3181
3708
  });
@@ -3248,21 +3775,19 @@ function getOperations({
3248
3775
  baseAssetId
3249
3776
  }) {
3250
3777
  if (isTypeCreate(transactionType)) {
3251
- return [
3252
- ...getContractCreatedOperations({ inputs, outputs }),
3253
- ...getTransferOperations({ inputs, outputs, receipts })
3254
- ];
3778
+ return [...getContractCreatedOperations({ inputs, outputs })];
3255
3779
  }
3256
3780
  if (isTypeScript(transactionType)) {
3257
3781
  return [
3258
- ...getTransferOperations({ inputs, outputs, receipts }),
3782
+ ...getTransferOperations({ inputs, outputs, receipts, baseAssetId }),
3259
3783
  ...getContractCallOperations({
3260
3784
  inputs,
3261
3785
  outputs,
3262
3786
  receipts,
3263
3787
  abiMap,
3264
3788
  rawPayload,
3265
- maxInputs
3789
+ maxInputs,
3790
+ baseAssetId
3266
3791
  }),
3267
3792
  ...getWithdrawFromFuelOperations({ inputs, receipts, baseAssetId })
3268
3793
  ];
@@ -3321,7 +3846,7 @@ var extractBurnedAssetsFromReceipts = (receipts) => {
3321
3846
  };
3322
3847
 
3323
3848
  // src/providers/transaction-summary/status.ts
3324
- import { ErrorCode as ErrorCode11, FuelError as FuelError11 } from "@fuel-ts/errors";
3849
+ import { ErrorCode as ErrorCode11, FuelError as FuelError13 } from "@fuel-ts/errors";
3325
3850
  import { bn as bn14 } from "@fuel-ts/math";
3326
3851
  var getTransactionStatusName = (gqlStatus) => {
3327
3852
  switch (gqlStatus) {
@@ -3334,7 +3859,7 @@ var getTransactionStatusName = (gqlStatus) => {
3334
3859
  case "SqueezedOutStatus":
3335
3860
  return "squeezedout" /* squeezedout */;
3336
3861
  default:
3337
- throw new FuelError11(
3862
+ throw new FuelError13(
3338
3863
  ErrorCode11.INVALID_TRANSACTION_STATUS,
3339
3864
  `Invalid transaction status: ${gqlStatus}.`
3340
3865
  );
@@ -3404,7 +3929,7 @@ function assembleTransactionSummary(params) {
3404
3929
  baseAssetId
3405
3930
  } = params;
3406
3931
  const gasUsed = getGasUsedFromReceipts(receipts);
3407
- const rawPayload = hexlify11(transactionBytes);
3932
+ const rawPayload = hexlify13(transactionBytes);
3408
3933
  const operations = getOperations({
3409
3934
  transactionType: transaction.type,
3410
3935
  inputs: transaction.inputs || [],
@@ -3456,6 +3981,7 @@ function assembleTransactionSummary(params) {
3456
3981
  isTypeScript: isTypeScript(transaction.type),
3457
3982
  isTypeUpgrade: isTypeUpgrade(transaction.type),
3458
3983
  isTypeUpload: isTypeUpload(transaction.type),
3984
+ isTypeBlob: isTypeBlob(transaction.type),
3459
3985
  isStatusFailure,
3460
3986
  isStatusSuccess,
3461
3987
  isStatusPending,
@@ -3481,6 +4007,36 @@ function getDecodedLogs(receipts, mainAbi, externalAbis = {}) {
3481
4007
  }
3482
4008
 
3483
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
+ }
3484
4040
  var TransactionResponse = class {
3485
4041
  /** Transaction ID */
3486
4042
  id;
@@ -3490,17 +4046,20 @@ var TransactionResponse = class {
3490
4046
  gasUsed = bn16(0);
3491
4047
  /** The graphql Transaction with receipts object. */
3492
4048
  gqlTransaction;
4049
+ request;
4050
+ status;
3493
4051
  abis;
3494
4052
  /**
3495
4053
  * Constructor for `TransactionResponse`.
3496
4054
  *
3497
- * @param id - The transaction ID.
4055
+ * @param tx - The transaction ID or TransactionRequest.
3498
4056
  * @param provider - The provider.
3499
4057
  */
3500
- constructor(id, provider, abis) {
3501
- this.id = id;
4058
+ constructor(tx, provider, abis) {
4059
+ this.id = typeof tx === "string" ? tx : tx.getTransactionId(provider.getChainId());
3502
4060
  this.provider = provider;
3503
4061
  this.abis = abis;
4062
+ this.request = typeof tx === "string" ? void 0 : tx;
3504
4063
  }
3505
4064
  /**
3506
4065
  * Async constructor for `TransactionResponse`. This method can be used to create
@@ -3515,6 +4074,54 @@ var TransactionResponse = class {
3515
4074
  await response.fetch();
3516
4075
  return response;
3517
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
+ }
3518
4125
  /**
3519
4126
  * Fetch the transaction with receipts from the provider.
3520
4127
  *
@@ -3525,11 +4132,12 @@ var TransactionResponse = class {
3525
4132
  transactionId: this.id
3526
4133
  });
3527
4134
  if (!response.transaction) {
3528
- const subscription = this.provider.operations.statusChange({
4135
+ const subscription = await this.provider.operations.statusChange({
3529
4136
  transactionId: this.id
3530
4137
  });
3531
4138
  for await (const { statusChange } of subscription) {
3532
4139
  if (statusChange) {
4140
+ this.status = statusChange;
3533
4141
  break;
3534
4142
  }
3535
4143
  }
@@ -3546,7 +4154,7 @@ var TransactionResponse = class {
3546
4154
  */
3547
4155
  decodeTransaction(transactionWithReceipts) {
3548
4156
  return new TransactionCoder4().decode(
3549
- arrayify10(transactionWithReceipts.rawPayload),
4157
+ arrayify11(transactionWithReceipts.rawPayload),
3550
4158
  0
3551
4159
  )?.[0];
3552
4160
  }
@@ -3558,28 +4166,17 @@ var TransactionResponse = class {
3558
4166
  * @returns
3559
4167
  */
3560
4168
  async getTransactionSummary(contractsAbiMap) {
3561
- let transaction = this.gqlTransaction;
3562
- if (!transaction) {
3563
- transaction = await this.fetch();
3564
- }
3565
- const decodedTransaction = this.decodeTransaction(
3566
- transaction
3567
- );
3568
- let txReceipts = [];
3569
- if (transaction?.status && "receipts" in transaction.status) {
3570
- txReceipts = transaction.status.receipts;
3571
- }
3572
- const receipts = txReceipts.map(processGqlReceipt) || [];
4169
+ const { tx: transaction, bytes: transactionBytes } = await this.getTransaction();
3573
4170
  const { gasPerByte, gasPriceFactor, gasCosts, maxGasPerTx } = this.provider.getGasConfig();
3574
4171
  const gasPrice = await this.provider.getLatestGasPrice();
3575
4172
  const maxInputs = this.provider.getChain().consensusParameters.txParameters.maxInputs;
3576
4173
  const baseAssetId = this.provider.getBaseAssetId();
3577
4174
  const transactionSummary = assembleTransactionSummary({
3578
4175
  id: this.id,
3579
- receipts,
3580
- transaction: decodedTransaction,
3581
- transactionBytes: arrayify10(transaction.rawPayload),
3582
- gqlTransactionStatus: transaction.status,
4176
+ receipts: this.getReceipts(),
4177
+ transaction,
4178
+ transactionBytes,
4179
+ gqlTransactionStatus: this.status ?? this.gqlTransaction?.status,
3583
4180
  gasPerByte,
3584
4181
  gasPriceFactor,
3585
4182
  abiMap: contractsAbiMap,
@@ -3596,12 +4193,14 @@ var TransactionResponse = class {
3596
4193
  if (status && status !== "SubmittedStatus") {
3597
4194
  return;
3598
4195
  }
3599
- const subscription = this.provider.operations.statusChange({
4196
+ const subscription = await this.provider.operations.statusChange({
3600
4197
  transactionId: this.id
3601
4198
  });
3602
4199
  for await (const { statusChange } of subscription) {
4200
+ this.status = statusChange;
3603
4201
  if (statusChange.type === "SqueezedOutStatus") {
3604
- throw new FuelError12(
4202
+ this.unsetResourceCache();
4203
+ throw new FuelError14(
3605
4204
  ErrorCode12.TRANSACTION_SQUEEZED_OUT,
3606
4205
  `Transaction Squeezed Out with reason: ${statusChange.reason}`
3607
4206
  );
@@ -3610,7 +4209,6 @@ var TransactionResponse = class {
3610
4209
  break;
3611
4210
  }
3612
4211
  }
3613
- await this.fetch();
3614
4212
  }
3615
4213
  /**
3616
4214
  * Assembles the result of a transaction by retrieving the transaction summary,
@@ -3627,7 +4225,6 @@ var TransactionResponse = class {
3627
4225
  async assembleResult(contractsAbiMap) {
3628
4226
  const transactionSummary = await this.getTransactionSummary(contractsAbiMap);
3629
4227
  const transactionResult = {
3630
- gqlTransaction: this.gqlTransaction,
3631
4228
  ...transactionSummary
3632
4229
  };
3633
4230
  let logs = [];
@@ -3639,9 +4236,11 @@ var TransactionResponse = class {
3639
4236
  );
3640
4237
  transactionResult.logs = logs;
3641
4238
  }
3642
- const { gqlTransaction, receipts } = transactionResult;
3643
- if (gqlTransaction.status?.type === "FailureStatus") {
3644
- 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;
3645
4244
  throw extractTxError({
3646
4245
  receipts,
3647
4246
  statusReason: reason,
@@ -3667,6 +4266,9 @@ var TransactionResponse = class {
3667
4266
  async wait(contractsAbiMap) {
3668
4267
  return this.waitForResult(contractsAbiMap);
3669
4268
  }
4269
+ unsetResourceCache() {
4270
+ this.provider.cache?.unset(this.id);
4271
+ }
3670
4272
  };
3671
4273
 
3672
4274
  // src/providers/utils/auto-retry-fetch.ts
@@ -3710,7 +4312,7 @@ function autoRetryFetch(fetchFn, options, retryAttemptNum = 0) {
3710
4312
  var MAX_RETRIES = 10;
3711
4313
  var RESOURCES_PAGE_SIZE_LIMIT = 512;
3712
4314
  var BLOCKS_PAGE_SIZE_LIMIT = 5;
3713
- var DEFAULT_UTXOS_CACHE_TTL = 2e4;
4315
+ var DEFAULT_RESOURCE_CACHE_TTL = 2e4;
3714
4316
  var processGqlChain = (chain) => {
3715
4317
  const { name, daHeight, consensusParameters, latestBlock } = chain;
3716
4318
  const {
@@ -3793,22 +4395,22 @@ var _Provider = class {
3793
4395
  __publicField(this, "cache");
3794
4396
  __publicField(this, "options", {
3795
4397
  timeout: void 0,
3796
- cacheUtxo: void 0,
4398
+ resourceCacheTTL: void 0,
3797
4399
  fetch: void 0,
3798
4400
  retryOptions: void 0
3799
4401
  });
3800
4402
  this.options = { ...this.options, ...options };
3801
4403
  this.url = url;
3802
4404
  this.operations = this.createOperations();
3803
- const { cacheUtxo } = this.options;
3804
- if (isDefined2(cacheUtxo)) {
3805
- if (cacheUtxo !== -1) {
3806
- this.cache = new MemoryCache(cacheUtxo);
4405
+ const { resourceCacheTTL } = this.options;
4406
+ if (isDefined2(resourceCacheTTL)) {
4407
+ if (resourceCacheTTL !== -1) {
4408
+ this.cache = new ResourceCache(resourceCacheTTL);
3807
4409
  } else {
3808
4410
  this.cache = void 0;
3809
4411
  }
3810
4412
  } else {
3811
- this.cache = new MemoryCache(DEFAULT_UTXOS_CACHE_TTL);
4413
+ this.cache = new ResourceCache(DEFAULT_RESOURCE_CACHE_TTL);
3812
4414
  }
3813
4415
  }
3814
4416
  /** @hidden */
@@ -3853,7 +4455,7 @@ var _Provider = class {
3853
4455
  getChain() {
3854
4456
  const chain = _Provider.chainInfoCache[this.url];
3855
4457
  if (!chain) {
3856
- throw new FuelError13(
4458
+ throw new FuelError15(
3857
4459
  ErrorCode13.CHAIN_INFO_CACHE_EMPTY,
3858
4460
  "Chain info cache is empty. Make sure you have called `Provider.create` to initialize the provider."
3859
4461
  );
@@ -3868,7 +4470,7 @@ var _Provider = class {
3868
4470
  getNode() {
3869
4471
  const node = _Provider.nodeInfoCache[this.url];
3870
4472
  if (!node) {
3871
- throw new FuelError13(
4473
+ throw new FuelError15(
3872
4474
  ErrorCode13.NODE_INFO_CACHE_EMPTY,
3873
4475
  "Node info cache is empty. Make sure you have called `Provider.create` to initialize the provider."
3874
4476
  );
@@ -3911,9 +4513,9 @@ var _Provider = class {
3911
4513
  * @returns A promise that resolves to the Chain and NodeInfo.
3912
4514
  */
3913
4515
  async fetchChainAndNodeInfo() {
3914
- const chain = await this.fetchChain();
3915
4516
  const nodeInfo = await this.fetchNode();
3916
4517
  _Provider.ensureClientVersionIsSupported(nodeInfo);
4518
+ const chain = await this.fetchChain();
3917
4519
  return {
3918
4520
  chain,
3919
4521
  nodeInfo
@@ -3947,8 +4549,8 @@ Supported fuel-core version: ${supportedVersion}.`
3947
4549
  if ("response" in response) {
3948
4550
  const graphQlResponse = response.response;
3949
4551
  if (Array.isArray(graphQlResponse?.errors)) {
3950
- throw new FuelError13(
3951
- FuelError13.CODES.INVALID_REQUEST,
4552
+ throw new FuelError15(
4553
+ FuelError15.CODES.INVALID_REQUEST,
3952
4554
  graphQlResponse.errors.map((err) => err.message).join("\n\n")
3953
4555
  );
3954
4556
  }
@@ -3959,7 +4561,7 @@ Supported fuel-core version: ${supportedVersion}.`
3959
4561
  const opDefinition = query.definitions.find((x) => x.kind === "OperationDefinition");
3960
4562
  const isSubscription = opDefinition?.operation === "subscription";
3961
4563
  if (isSubscription) {
3962
- return new FuelGraphqlSubscriber({
4564
+ return FuelGraphqlSubscriber.create({
3963
4565
  url: this.url,
3964
4566
  query,
3965
4567
  fetchFn: (url, requestInit) => fetchFn(url, requestInit, this.options),
@@ -4040,6 +4642,21 @@ Supported fuel-core version: ${supportedVersion}.`
4040
4642
  } = this.getChain();
4041
4643
  return baseAssetId;
4042
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
+ }
4043
4660
  /**
4044
4661
  * Submits a transaction to the chain to be executed.
4045
4662
  *
@@ -4056,16 +4673,18 @@ Supported fuel-core version: ${supportedVersion}.`
4056
4673
  if (estimateTxDependencies) {
4057
4674
  await this.estimateTxDependencies(transactionRequest);
4058
4675
  }
4059
- const encodedTransaction = hexlify12(transactionRequest.toTransactionBytes());
4676
+ const { consensusParameters } = this.getChain();
4677
+ this.validateTransaction(transactionRequest, consensusParameters);
4678
+ const encodedTransaction = hexlify14(transactionRequest.toTransactionBytes());
4060
4679
  let abis;
4061
- if (transactionRequest.type === TransactionType8.Script) {
4680
+ if (isTransactionTypeScript(transactionRequest)) {
4062
4681
  abis = transactionRequest.abis;
4063
4682
  }
4064
4683
  const {
4065
4684
  submit: { id: transactionId }
4066
4685
  } = await this.operations.submit({ encodedTransaction });
4067
- __privateMethod(this, _cacheInputs, cacheInputs_fn).call(this, transactionRequest.inputs);
4068
- return new TransactionResponse(transactionId, this, abis);
4686
+ __privateMethod(this, _cacheInputs, cacheInputs_fn).call(this, transactionRequest.inputs, transactionId);
4687
+ return new TransactionResponse(transactionRequest, this, abis);
4069
4688
  }
4070
4689
  /**
4071
4690
  * Executes a transaction without actually submitting it to the chain.
@@ -4082,7 +4701,7 @@ Supported fuel-core version: ${supportedVersion}.`
4082
4701
  if (estimateTxDependencies) {
4083
4702
  return this.estimateTxDependencies(transactionRequest);
4084
4703
  }
4085
- const encodedTransaction = hexlify12(transactionRequest.toTransactionBytes());
4704
+ const encodedTransaction = hexlify14(transactionRequest.toTransactionBytes());
4086
4705
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
4087
4706
  encodedTransactions: encodedTransaction,
4088
4707
  utxoValidation: utxoValidation || false
@@ -4102,13 +4721,13 @@ Supported fuel-core version: ${supportedVersion}.`
4102
4721
  async estimatePredicates(transactionRequest) {
4103
4722
  const shouldEstimatePredicates = Boolean(
4104
4723
  transactionRequest.inputs.find(
4105
- (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()
4106
4725
  )
4107
4726
  );
4108
4727
  if (!shouldEstimatePredicates) {
4109
4728
  return transactionRequest;
4110
4729
  }
4111
- const encodedTransaction = hexlify12(transactionRequest.toTransactionBytes());
4730
+ const encodedTransaction = hexlify14(transactionRequest.toTransactionBytes());
4112
4731
  const response = await this.operations.estimatePredicates({
4113
4732
  encodedTransaction
4114
4733
  });
@@ -4134,7 +4753,7 @@ Supported fuel-core version: ${supportedVersion}.`
4134
4753
  * @returns A promise that resolves to the estimate transaction dependencies.
4135
4754
  */
4136
4755
  async estimateTxDependencies(transactionRequest) {
4137
- if (transactionRequest.type === TransactionType8.Create) {
4756
+ if (isTransactionTypeCreate(transactionRequest)) {
4138
4757
  return {
4139
4758
  receipts: [],
4140
4759
  outputVariables: 0,
@@ -4149,18 +4768,18 @@ Supported fuel-core version: ${supportedVersion}.`
4149
4768
  const {
4150
4769
  dryRun: [{ receipts: rawReceipts, status }]
4151
4770
  } = await this.operations.dryRun({
4152
- encodedTransactions: [hexlify12(transactionRequest.toTransactionBytes())],
4771
+ encodedTransactions: [hexlify14(transactionRequest.toTransactionBytes())],
4153
4772
  utxoValidation: false
4154
4773
  });
4155
4774
  receipts = rawReceipts.map(processGqlReceipt);
4156
4775
  dryRunStatus = status;
4157
4776
  const { missingOutputVariables, missingOutputContractIds } = getReceiptsWithMissingData(receipts);
4158
4777
  const hasMissingOutputs = missingOutputVariables.length !== 0 || missingOutputContractIds.length !== 0;
4159
- if (hasMissingOutputs) {
4778
+ if (hasMissingOutputs && isTransactionTypeScript(transactionRequest)) {
4160
4779
  outputVariables += missingOutputVariables.length;
4161
4780
  transactionRequest.addVariableOutputs(missingOutputVariables.length);
4162
4781
  missingOutputContractIds.forEach(({ contractId }) => {
4163
- transactionRequest.addContractInputAndOutput(Address2.fromString(contractId));
4782
+ transactionRequest.addContractInputAndOutput(Address3.fromString(contractId));
4164
4783
  missingContractIds.push(contractId);
4165
4784
  });
4166
4785
  const { maxFee } = await this.estimateTxGasAndFee({
@@ -4198,8 +4817,8 @@ Supported fuel-core version: ${supportedVersion}.`
4198
4817
  const allRequests = clone3(transactionRequests);
4199
4818
  const serializedTransactionsMap = /* @__PURE__ */ new Map();
4200
4819
  allRequests.forEach((req, index) => {
4201
- if (req.type === TransactionType8.Script) {
4202
- serializedTransactionsMap.set(index, hexlify12(req.toTransactionBytes()));
4820
+ if (isTransactionTypeScript(req)) {
4821
+ serializedTransactionsMap.set(index, hexlify14(req.toTransactionBytes()));
4203
4822
  }
4204
4823
  });
4205
4824
  let transactionsToProcess = Array.from(serializedTransactionsMap.keys());
@@ -4224,18 +4843,18 @@ Supported fuel-core version: ${supportedVersion}.`
4224
4843
  );
4225
4844
  const hasMissingOutputs = missingOutputVariables.length > 0 || missingOutputContractIds.length > 0;
4226
4845
  const request = allRequests[requestIdx];
4227
- if (hasMissingOutputs && request?.type === TransactionType8.Script) {
4846
+ if (hasMissingOutputs && isTransactionTypeScript(request)) {
4228
4847
  result.outputVariables += missingOutputVariables.length;
4229
4848
  request.addVariableOutputs(missingOutputVariables.length);
4230
4849
  missingOutputContractIds.forEach(({ contractId }) => {
4231
- request.addContractInputAndOutput(Address2.fromString(contractId));
4850
+ request.addContractInputAndOutput(Address3.fromString(contractId));
4232
4851
  result.missingContractIds.push(contractId);
4233
4852
  });
4234
4853
  const { maxFee } = await this.estimateTxGasAndFee({
4235
4854
  transactionRequest: request
4236
4855
  });
4237
4856
  request.maxFee = maxFee;
4238
- serializedTransactionsMap.set(requestIdx, hexlify12(request.toTransactionBytes()));
4857
+ serializedTransactionsMap.set(requestIdx, hexlify14(request.toTransactionBytes()));
4239
4858
  nextRoundTransactions.push(requestIdx);
4240
4859
  }
4241
4860
  }
@@ -4256,7 +4875,7 @@ Supported fuel-core version: ${supportedVersion}.`
4256
4875
  if (estimateTxDependencies) {
4257
4876
  return this.estimateMultipleTxDependencies(transactionRequests);
4258
4877
  }
4259
- const encodedTransactions = transactionRequests.map((tx) => hexlify12(tx.toTransactionBytes()));
4878
+ const encodedTransactions = transactionRequests.map((tx) => hexlify14(tx.toTransactionBytes()));
4260
4879
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
4261
4880
  encodedTransactions,
4262
4881
  utxoValidation: utxoValidation || false
@@ -4288,7 +4907,7 @@ Supported fuel-core version: ${supportedVersion}.`
4288
4907
  tip: transactionRequest.tip
4289
4908
  }).add(1);
4290
4909
  let gasLimit = bn17(0);
4291
- if (transactionRequest.type === TransactionType8.Script) {
4910
+ if (isTransactionTypeScript(transactionRequest)) {
4292
4911
  gasLimit = transactionRequest.gasLimit;
4293
4912
  if (transactionRequest.gasLimit.eq(0)) {
4294
4913
  transactionRequest.gasLimit = minGas;
@@ -4330,7 +4949,7 @@ Supported fuel-core version: ${supportedVersion}.`
4330
4949
  if (estimateTxDependencies) {
4331
4950
  return this.estimateTxDependencies(transactionRequest);
4332
4951
  }
4333
- const encodedTransactions = [hexlify12(transactionRequest.toTransactionBytes())];
4952
+ const encodedTransactions = [hexlify14(transactionRequest.toTransactionBytes())];
4334
4953
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
4335
4954
  encodedTransactions,
4336
4955
  utxoValidation: true
@@ -4356,14 +4975,14 @@ Supported fuel-core version: ${supportedVersion}.`
4356
4975
  */
4357
4976
  async getTransactionCost(transactionRequestLike, { signatureCallback } = {}) {
4358
4977
  const txRequestClone = clone3(transactionRequestify(transactionRequestLike));
4359
- const isScriptTransaction = txRequestClone.type === TransactionType8.Script;
4360
4978
  const updateMaxFee = txRequestClone.maxFee.eq(0);
4979
+ const isScriptTransaction = isTransactionTypeScript(txRequestClone);
4361
4980
  if (isScriptTransaction) {
4362
4981
  txRequestClone.gasLimit = bn17(0);
4363
4982
  }
4364
4983
  const signedRequest = clone3(txRequestClone);
4365
4984
  let addedSignatures = 0;
4366
- if (signatureCallback && isScriptTransaction) {
4985
+ if (signatureCallback && isTransactionTypeScript(signedRequest)) {
4367
4986
  const lengthBefore = signedRequest.witnesses.length;
4368
4987
  await signatureCallback(signedRequest);
4369
4988
  addedSignatures = signedRequest.witnesses.length - lengthBefore;
@@ -4421,7 +5040,7 @@ Supported fuel-core version: ${supportedVersion}.`
4421
5040
  * @returns A promise that resolves to the coins.
4422
5041
  */
4423
5042
  async getCoins(owner, assetId, paginationArgs) {
4424
- const ownerAddress = Address2.fromAddressOrString(owner);
5043
+ const ownerAddress = Address3.fromAddressOrString(owner);
4425
5044
  const {
4426
5045
  coins: { edges, pageInfo }
4427
5046
  } = await this.operations.getCoins({
@@ -4429,13 +5048,13 @@ Supported fuel-core version: ${supportedVersion}.`
4429
5048
  paginationLimit: RESOURCES_PAGE_SIZE_LIMIT,
4430
5049
  inputArgs: paginationArgs
4431
5050
  }),
4432
- filter: { owner: ownerAddress.toB256(), assetId: assetId && hexlify12(assetId) }
5051
+ filter: { owner: ownerAddress.toB256(), assetId: assetId && hexlify14(assetId) }
4433
5052
  });
4434
5053
  const coins = edges.map(({ node }) => ({
4435
5054
  id: node.utxoId,
4436
5055
  assetId: node.assetId,
4437
5056
  amount: bn17(node.amount),
4438
- owner: Address2.fromAddressOrString(node.owner),
5057
+ owner: Address3.fromAddressOrString(node.owner),
4439
5058
  blockCreated: bn17(node.blockCreated),
4440
5059
  txCreatedIdx: bn17(node.txCreatedIdx)
4441
5060
  }));
@@ -4453,21 +5072,20 @@ Supported fuel-core version: ${supportedVersion}.`
4453
5072
  * @returns A promise that resolves to the resources.
4454
5073
  */
4455
5074
  async getResourcesToSpend(owner, quantities, excludedIds) {
4456
- const ownerAddress = Address2.fromAddressOrString(owner);
5075
+ const ownerAddress = Address3.fromAddressOrString(owner);
4457
5076
  const excludeInput = {
4458
- messages: excludedIds?.messages?.map((nonce) => hexlify12(nonce)) || [],
4459
- utxos: excludedIds?.utxos?.map((id) => hexlify12(id)) || []
5077
+ messages: excludedIds?.messages?.map((nonce) => hexlify14(nonce)) || [],
5078
+ utxos: excludedIds?.utxos?.map((id) => hexlify14(id)) || []
4460
5079
  };
4461
5080
  if (this.cache) {
4462
- const uniqueUtxos = new Set(
4463
- excludeInput.utxos.concat(this.cache?.getActiveData().map((id) => hexlify12(id)))
4464
- );
4465
- excludeInput.utxos = Array.from(uniqueUtxos);
5081
+ const cached = this.cache.getActiveData();
5082
+ excludeInput.messages.push(...cached.messages);
5083
+ excludeInput.utxos.push(...cached.utxos);
4466
5084
  }
4467
5085
  const coinsQuery = {
4468
5086
  owner: ownerAddress.toB256(),
4469
5087
  queryPerAsset: quantities.map(coinQuantityfy).map(({ assetId, amount, max: maxPerAsset }) => ({
4470
- assetId: hexlify12(assetId),
5088
+ assetId: hexlify14(assetId),
4471
5089
  amount: amount.toString(10),
4472
5090
  max: maxPerAsset ? maxPerAsset.toString(10) : void 0
4473
5091
  })),
@@ -4481,8 +5099,8 @@ Supported fuel-core version: ${supportedVersion}.`
4481
5099
  amount: bn17(coin.amount),
4482
5100
  assetId: coin.assetId,
4483
5101
  daHeight: bn17(coin.daHeight),
4484
- sender: Address2.fromAddressOrString(coin.sender),
4485
- recipient: Address2.fromAddressOrString(coin.recipient),
5102
+ sender: Address3.fromAddressOrString(coin.sender),
5103
+ recipient: Address3.fromAddressOrString(coin.recipient),
4486
5104
  nonce: coin.nonce
4487
5105
  };
4488
5106
  case "Coin":
@@ -4490,7 +5108,7 @@ Supported fuel-core version: ${supportedVersion}.`
4490
5108
  id: coin.utxoId,
4491
5109
  amount: bn17(coin.amount),
4492
5110
  assetId: coin.assetId,
4493
- owner: Address2.fromAddressOrString(coin.owner),
5111
+ owner: Address3.fromAddressOrString(coin.owner),
4494
5112
  blockCreated: bn17(coin.blockCreated),
4495
5113
  txCreatedIdx: bn17(coin.txCreatedIdx)
4496
5114
  };
@@ -4576,7 +5194,7 @@ Supported fuel-core version: ${supportedVersion}.`
4576
5194
  time: block.header.time,
4577
5195
  transactionIds: block.transactions.map((tx) => tx.id),
4578
5196
  transactions: block.transactions.map(
4579
- (tx) => new TransactionCoder5().decode(arrayify11(tx.rawPayload), 0)?.[0]
5197
+ (tx) => new TransactionCoder5().decode(arrayify12(tx.rawPayload), 0)?.[0]
4580
5198
  )
4581
5199
  };
4582
5200
  }
@@ -4592,7 +5210,7 @@ Supported fuel-core version: ${supportedVersion}.`
4592
5210
  return null;
4593
5211
  }
4594
5212
  return new TransactionCoder5().decode(
4595
- arrayify11(transaction.rawPayload),
5213
+ arrayify12(transaction.rawPayload),
4596
5214
  0
4597
5215
  )?.[0];
4598
5216
  }
@@ -4607,7 +5225,7 @@ Supported fuel-core version: ${supportedVersion}.`
4607
5225
  } = await this.operations.getTransactions(paginationArgs);
4608
5226
  const coder = new TransactionCoder5();
4609
5227
  const transactions = edges.map(
4610
- ({ node: { rawPayload } }) => coder.decode(arrayify11(rawPayload), 0)[0]
5228
+ ({ node: { rawPayload } }) => coder.decode(arrayify12(rawPayload), 0)[0]
4611
5229
  );
4612
5230
  return { transactions, pageInfo };
4613
5231
  }
@@ -4633,8 +5251,8 @@ Supported fuel-core version: ${supportedVersion}.`
4633
5251
  */
4634
5252
  async getContractBalance(contractId, assetId) {
4635
5253
  const { contractBalance } = await this.operations.getContractBalance({
4636
- contract: Address2.fromAddressOrString(contractId).toB256(),
4637
- asset: hexlify12(assetId)
5254
+ contract: Address3.fromAddressOrString(contractId).toB256(),
5255
+ asset: hexlify14(assetId)
4638
5256
  });
4639
5257
  return bn17(contractBalance.amount, 10);
4640
5258
  }
@@ -4647,8 +5265,8 @@ Supported fuel-core version: ${supportedVersion}.`
4647
5265
  */
4648
5266
  async getBalance(owner, assetId) {
4649
5267
  const { balance } = await this.operations.getBalance({
4650
- owner: Address2.fromAddressOrString(owner).toB256(),
4651
- assetId: hexlify12(assetId)
5268
+ owner: Address3.fromAddressOrString(owner).toB256(),
5269
+ assetId: hexlify14(assetId)
4652
5270
  });
4653
5271
  return bn17(balance.amount, 10);
4654
5272
  }
@@ -4668,7 +5286,7 @@ Supported fuel-core version: ${supportedVersion}.`
4668
5286
  * but the current Fuel-Core implementation does not support pagination yet.
4669
5287
  */
4670
5288
  first: 1e4,
4671
- filter: { owner: Address2.fromAddressOrString(owner).toB256() }
5289
+ filter: { owner: Address3.fromAddressOrString(owner).toB256() }
4672
5290
  });
4673
5291
  const balances = edges.map(({ node }) => ({
4674
5292
  assetId: node.assetId,
@@ -4691,7 +5309,7 @@ Supported fuel-core version: ${supportedVersion}.`
4691
5309
  inputArgs: paginationArgs,
4692
5310
  paginationLimit: RESOURCES_PAGE_SIZE_LIMIT
4693
5311
  }),
4694
- owner: Address2.fromAddressOrString(address).toB256()
5312
+ owner: Address3.fromAddressOrString(address).toB256()
4695
5313
  });
4696
5314
  const messages = edges.map(({ node }) => ({
4697
5315
  messageId: InputMessageCoder.getMessageId({
@@ -4701,8 +5319,8 @@ Supported fuel-core version: ${supportedVersion}.`
4701
5319
  amount: bn17(node.amount),
4702
5320
  data: node.data
4703
5321
  }),
4704
- sender: Address2.fromAddressOrString(node.sender),
4705
- recipient: Address2.fromAddressOrString(node.recipient),
5322
+ sender: Address3.fromAddressOrString(node.sender),
5323
+ recipient: Address3.fromAddressOrString(node.recipient),
4706
5324
  nonce: node.nonce,
4707
5325
  amount: bn17(node.amount),
4708
5326
  data: InputMessageCoder.decodeData(node.data),
@@ -4728,7 +5346,7 @@ Supported fuel-core version: ${supportedVersion}.`
4728
5346
  nonce
4729
5347
  };
4730
5348
  if (commitBlockId && commitBlockHeight) {
4731
- throw new FuelError13(
5349
+ throw new FuelError15(
4732
5350
  ErrorCode13.INVALID_INPUT_PARAMETERS,
4733
5351
  "commitBlockId and commitBlockHeight cannot be used together"
4734
5352
  );
@@ -4800,8 +5418,8 @@ Supported fuel-core version: ${supportedVersion}.`
4800
5418
  eventInboxRoot: commitBlockHeader.eventInboxRoot,
4801
5419
  stateTransitionBytecodeVersion: Number(commitBlockHeader.stateTransitionBytecodeVersion)
4802
5420
  },
4803
- sender: Address2.fromAddressOrString(sender),
4804
- recipient: Address2.fromAddressOrString(recipient),
5421
+ sender: Address3.fromAddressOrString(sender),
5422
+ recipient: Address3.fromAddressOrString(recipient),
4805
5423
  nonce,
4806
5424
  amount: bn17(amount),
4807
5425
  data
@@ -4897,25 +5515,25 @@ Supported fuel-core version: ${supportedVersion}.`
4897
5515
  const { paginationLimit, inputArgs = {} } = params;
4898
5516
  const { first, last, after, before } = inputArgs;
4899
5517
  if (after && before) {
4900
- throw new FuelError13(
5518
+ throw new FuelError15(
4901
5519
  ErrorCode13.INVALID_INPUT_PARAMETERS,
4902
5520
  'Pagination arguments "after" and "before" cannot be used together'
4903
5521
  );
4904
5522
  }
4905
5523
  if ((first || 0) > paginationLimit || (last || 0) > paginationLimit) {
4906
- throw new FuelError13(
5524
+ throw new FuelError15(
4907
5525
  ErrorCode13.INVALID_INPUT_PARAMETERS,
4908
5526
  `Pagination limit for this query cannot exceed ${paginationLimit} items`
4909
5527
  );
4910
5528
  }
4911
5529
  if (first && before) {
4912
- throw new FuelError13(
5530
+ throw new FuelError15(
4913
5531
  ErrorCode13.INVALID_INPUT_PARAMETERS,
4914
5532
  'The use of pagination argument "first" with "before" is not supported'
4915
5533
  );
4916
5534
  }
4917
5535
  if (last && after) {
4918
- throw new FuelError13(
5536
+ throw new FuelError15(
4919
5537
  ErrorCode13.INVALID_INPUT_PARAMETERS,
4920
5538
  'The use of pagination argument "last" with "after" is not supported'
4921
5539
  );
@@ -4947,15 +5565,22 @@ Supported fuel-core version: ${supportedVersion}.`
4947
5565
  };
4948
5566
  var Provider = _Provider;
4949
5567
  _cacheInputs = new WeakSet();
4950
- cacheInputs_fn = function(inputs) {
5568
+ cacheInputs_fn = function(inputs, transactionId) {
4951
5569
  if (!this.cache) {
4952
5570
  return;
4953
5571
  }
4954
- inputs.forEach((input) => {
4955
- if (input.type === InputType7.Coin) {
4956
- this.cache?.set(input.id);
4957
- }
4958
- });
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);
4959
5584
  };
4960
5585
  /** @hidden */
4961
5586
  __publicField(Provider, "chainInfoCache", {});
@@ -4963,10 +5588,10 @@ __publicField(Provider, "chainInfoCache", {});
4963
5588
  __publicField(Provider, "nodeInfoCache", {});
4964
5589
 
4965
5590
  // src/providers/transaction-summary/get-transaction-summary.ts
4966
- import { ErrorCode as ErrorCode14, FuelError as FuelError14 } from "@fuel-ts/errors";
5591
+ import { ErrorCode as ErrorCode14, FuelError as FuelError16 } from "@fuel-ts/errors";
4967
5592
  import { bn as bn18 } from "@fuel-ts/math";
4968
5593
  import { TransactionCoder as TransactionCoder6 } from "@fuel-ts/transactions";
4969
- import { arrayify as arrayify12 } from "@fuel-ts/utils";
5594
+ import { arrayify as arrayify13 } from "@fuel-ts/utils";
4970
5595
 
4971
5596
  // src/providers/chains.ts
4972
5597
  var CHAIN_IDS = {
@@ -5039,6 +5664,48 @@ var rawAssets = [
5039
5664
  ];
5040
5665
  var assets = resolveIconPaths(rawAssets, fuelAssetsBaseUrl);
5041
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
+
5042
5709
  // src/providers/utils/merge-quantities.ts
5043
5710
  var mergeQuantities = (...coinQuantities) => {
5044
5711
  const resultMap = {};
@@ -5055,17 +5722,17 @@ var mergeQuantities = (...coinQuantities) => {
5055
5722
 
5056
5723
  // src/utils/formatTransferToContractScriptData.ts
5057
5724
  import { BigNumberCoder as BigNumberCoder2 } from "@fuel-ts/abi-coder";
5058
- import { BN as BN2 } from "@fuel-ts/math";
5059
- 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";
5060
5727
  import * as asm from "@fuels/vm-asm";
5061
5728
  var formatTransferToContractScriptData = (params) => {
5062
5729
  const { assetId, amountToTransfer, hexlifiedContractId } = params;
5063
5730
  const numberCoder = new BigNumberCoder2("u64");
5064
- const encoded = numberCoder.encode(new BN2(amountToTransfer).toNumber());
5731
+ const encoded = numberCoder.encode(new BN3(amountToTransfer).toNumber());
5065
5732
  const scriptData = Uint8Array.from([
5066
- ...arrayify13(hexlifiedContractId),
5733
+ ...arrayify14(hexlifiedContractId),
5067
5734
  ...encoded,
5068
- ...arrayify13(assetId)
5735
+ ...arrayify14(assetId)
5069
5736
  ]);
5070
5737
  return scriptData;
5071
5738
  };
@@ -5090,7 +5757,7 @@ var assembleTransferToContractScript = async (params) => {
5090
5757
  };
5091
5758
 
5092
5759
  // src/account.ts
5093
- var MAX_FUNDING_ATTEMPTS = 2;
5760
+ var MAX_FUNDING_ATTEMPTS = 5;
5094
5761
  var Account = class extends AbstractAccount {
5095
5762
  /**
5096
5763
  * The address associated with the account.
@@ -5115,7 +5782,7 @@ var Account = class extends AbstractAccount {
5115
5782
  super();
5116
5783
  this._provider = provider;
5117
5784
  this._connector = connector;
5118
- this.address = Address3.fromDynamicInput(address);
5785
+ this.address = Address4.fromDynamicInput(address);
5119
5786
  }
5120
5787
  /**
5121
5788
  * The provider used to interact with the network.
@@ -5126,7 +5793,7 @@ var Account = class extends AbstractAccount {
5126
5793
  */
5127
5794
  get provider() {
5128
5795
  if (!this._provider) {
5129
- throw new FuelError15(ErrorCode15.MISSING_PROVIDER, "Provider not set");
5796
+ throw new FuelError17(ErrorCode15.MISSING_PROVIDER, "Provider not set");
5130
5797
  }
5131
5798
  return this._provider;
5132
5799
  }
@@ -5203,7 +5870,7 @@ var Account = class extends AbstractAccount {
5203
5870
  * @returns A promise that resolves to the funded transaction request.
5204
5871
  */
5205
5872
  async fund(request, params) {
5206
- const { addedSignatures, estimatedPredicates, requiredQuantities, updateMaxFee } = params;
5873
+ const { addedSignatures, estimatedPredicates, requiredQuantities, updateMaxFee, gasPrice } = params;
5207
5874
  const fee = request.maxFee;
5208
5875
  const baseAssetId = this.provider.getBaseAssetId();
5209
5876
  const requiredInBaseAsset = requiredQuantities.find((quantity) => quantity.assetId === baseAssetId)?.amount || bn19(0);
@@ -5251,10 +5918,12 @@ var Account = class extends AbstractAccount {
5251
5918
  );
5252
5919
  }
5253
5920
  if (!updateMaxFee) {
5921
+ needsToBeFunded = false;
5254
5922
  break;
5255
5923
  }
5256
5924
  const { maxFee: newFee } = await this.provider.estimateTxGasAndFee({
5257
- transactionRequest: requestToReestimate2
5925
+ transactionRequest: requestToReestimate2,
5926
+ gasPrice
5258
5927
  });
5259
5928
  const totalBaseAssetOnInputs = getAssetAmountInRequestInputs(
5260
5929
  request.inputs,
@@ -5274,6 +5943,12 @@ var Account = class extends AbstractAccount {
5274
5943
  }
5275
5944
  fundingAttempts += 1;
5276
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
+ }
5277
5952
  request.updatePredicateGasUsed(estimatedPredicates);
5278
5953
  const requestToReestimate = clone4(request);
5279
5954
  if (addedSignatures) {
@@ -5340,7 +6015,7 @@ var Account = class extends AbstractAccount {
5340
6015
  const { destination, amount, assetId } = transferParams;
5341
6016
  this.validateTransferAmount(amount);
5342
6017
  request.addCoinOutput(
5343
- Address3.fromAddressOrString(destination),
6018
+ Address4.fromAddressOrString(destination),
5344
6019
  amount,
5345
6020
  assetId ?? this.provider.getBaseAssetId()
5346
6021
  );
@@ -5375,12 +6050,12 @@ var Account = class extends AbstractAccount {
5375
6050
  */
5376
6051
  async transferToContract(contractId, amount, assetId, txParams = {}) {
5377
6052
  if (bn19(amount).lte(0)) {
5378
- throw new FuelError15(
6053
+ throw new FuelError17(
5379
6054
  ErrorCode15.INVALID_TRANSFER_AMOUNT,
5380
6055
  "Transfer amount must be a positive number."
5381
6056
  );
5382
6057
  }
5383
- const contractAddress = Address3.fromAddressOrString(contractId);
6058
+ const contractAddress = Address4.fromAddressOrString(contractId);
5384
6059
  const assetIdToTransfer = assetId ?? this.provider.getBaseAssetId();
5385
6060
  const { script, scriptData } = await assembleTransferToContractScript({
5386
6061
  hexlifiedContractId: contractAddress.toB256(),
@@ -5414,15 +6089,15 @@ var Account = class extends AbstractAccount {
5414
6089
  * @returns A promise that resolves to the transaction response.
5415
6090
  */
5416
6091
  async withdrawToBaseLayer(recipient, amount, txParams = {}) {
5417
- const recipientAddress = Address3.fromAddressOrString(recipient);
5418
- const recipientDataArray = arrayify14(
6092
+ const recipientAddress = Address4.fromAddressOrString(recipient);
6093
+ const recipientDataArray = arrayify15(
5419
6094
  "0x".concat(recipientAddress.toHexString().substring(2).padStart(64, "0"))
5420
6095
  );
5421
- const amountDataArray = arrayify14(
6096
+ const amountDataArray = arrayify15(
5422
6097
  "0x".concat(bn19(amount).toHex().substring(2).padStart(16, "0"))
5423
6098
  );
5424
6099
  const script = new Uint8Array([
5425
- ...arrayify14(withdrawScript.bytes),
6100
+ ...arrayify15(withdrawScript.bytes),
5426
6101
  ...recipientDataArray,
5427
6102
  ...amountDataArray
5428
6103
  ]);
@@ -5456,10 +6131,34 @@ var Account = class extends AbstractAccount {
5456
6131
  const coinOutputsQuantities = txRequestClone.getCoinOutputsQuantities();
5457
6132
  const requiredQuantities = mergeQuantities(coinOutputsQuantities, quantities);
5458
6133
  const transactionFeeForDryRun = [{ assetId: baseAssetId, amount: bn19("100000000000000000") }];
5459
- const resources = this.generateFakeResources(
5460
- mergeQuantities(requiredQuantities, transactionFeeForDryRun)
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)
5461
6161
  );
5462
- txRequestClone.addResources(resources);
5463
6162
  const txCost = await this.provider.getTransactionCost(txRequestClone, {
5464
6163
  signatureCallback
5465
6164
  });
@@ -5478,7 +6177,7 @@ var Account = class extends AbstractAccount {
5478
6177
  */
5479
6178
  async signMessage(message) {
5480
6179
  if (!this._connector) {
5481
- 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.");
5482
6181
  }
5483
6182
  return this._connector.signMessage(this.address.toString(), message);
5484
6183
  }
@@ -5490,7 +6189,7 @@ var Account = class extends AbstractAccount {
5490
6189
  */
5491
6190
  async signTransaction(transactionRequestLike) {
5492
6191
  if (!this._connector) {
5493
- throw new FuelError15(
6192
+ throw new FuelError17(
5494
6193
  ErrorCode15.MISSING_CONNECTOR,
5495
6194
  "A connector is required to sign transactions."
5496
6195
  );
@@ -5540,7 +6239,7 @@ var Account = class extends AbstractAccount {
5540
6239
  */
5541
6240
  generateFakeResources(coins) {
5542
6241
  return coins.map((coin) => ({
5543
- id: hexlify13(randomBytes2(UTXO_ID_LEN3)),
6242
+ id: hexlify16(randomBytes5(UTXO_ID_LEN3)),
5544
6243
  owner: this.address,
5545
6244
  blockCreated: bn19(1),
5546
6245
  txCreatedIdx: bn19(1),
@@ -5550,7 +6249,7 @@ var Account = class extends AbstractAccount {
5550
6249
  /** @hidden * */
5551
6250
  validateTransferAmount(amount) {
5552
6251
  if (bn19(amount).lte(0)) {
5553
- throw new FuelError15(
6252
+ throw new FuelError17(
5554
6253
  ErrorCode15.INVALID_TRANSFER_AMOUNT,
5555
6254
  "Transfer amount must be a positive number."
5556
6255
  );
@@ -5579,130 +6278,21 @@ var Account = class extends AbstractAccount {
5579
6278
  const request = transactionRequestify(transactionRequest);
5580
6279
  if (!isDefined3(setGasLimit)) {
5581
6280
  request.gasLimit = gasUsed;
5582
- } else if (gasUsed.gt(setGasLimit)) {
5583
- throw new FuelError15(
5584
- ErrorCode15.GAS_LIMIT_TOO_LOW,
5585
- `Gas limit '${setGasLimit}' is lower than the required: '${gasUsed}'.`
5586
- );
5587
- }
5588
- if (!isDefined3(setMaxFee)) {
5589
- request.maxFee = maxFee;
5590
- } else if (maxFee.gt(setMaxFee)) {
5591
- throw new FuelError15(
5592
- ErrorCode15.MAX_FEE_TOO_LOW,
5593
- `Max fee '${setMaxFee}' is lower than the required: '${maxFee}'.`
5594
- );
5595
- }
5596
- return request;
5597
- }
5598
- };
5599
-
5600
- // src/signer/signer.ts
5601
- import { Address as Address4 } from "@fuel-ts/address";
5602
- import { randomBytes as randomBytes3 } from "@fuel-ts/crypto";
5603
- import { hash } from "@fuel-ts/hasher";
5604
- import { toBytes } from "@fuel-ts/math";
5605
- import { hexlify as hexlify14, concat as concat3, arrayify as arrayify15 } from "@fuel-ts/utils";
5606
- import { secp256k1 } from "@noble/curves/secp256k1";
5607
- var Signer = class {
5608
- address;
5609
- publicKey;
5610
- compressedPublicKey;
5611
- privateKey;
5612
- /**
5613
- * Create a Signer instance from a given private key
5614
- *
5615
- * @param privateKey - The private key to use for signing
5616
- * @returns A new Signer instance
5617
- */
5618
- constructor(privateKey) {
5619
- if (typeof privateKey === "string") {
5620
- if (privateKey.match(/^[0-9a-f]*$/i) && privateKey.length === 64) {
5621
- privateKey = `0x${privateKey}`;
5622
- }
5623
- }
5624
- const privateKeyBytes = toBytes(privateKey, 32);
5625
- this.privateKey = hexlify14(privateKeyBytes);
5626
- this.publicKey = hexlify14(secp256k1.getPublicKey(privateKeyBytes, false).slice(1));
5627
- this.compressedPublicKey = hexlify14(secp256k1.getPublicKey(privateKeyBytes, true));
5628
- this.address = Address4.fromPublicKey(this.publicKey);
5629
- }
5630
- /**
5631
- * Sign data using the Signer instance
5632
- *
5633
- * Signature is a 64 byte array of the concatenated r and s values with the compressed recoveryParam byte.
5634
- * @ignore
5635
- * [Read more](FuelLabs/fuel-specs/specs/protocol/cryptographic_primitives.md#public-key-cryptography)
5636
- *
5637
- * @param data - The data to be sign
5638
- * @returns hashed signature
5639
- */
5640
- sign(data) {
5641
- const signature = secp256k1.sign(arrayify15(data), arrayify15(this.privateKey));
5642
- const r = toBytes(`0x${signature.r.toString(16)}`, 32);
5643
- const s = toBytes(`0x${signature.s.toString(16)}`, 32);
5644
- s[0] |= (signature.recovery || 0) << 7;
5645
- return hexlify14(concat3([r, s]));
5646
- }
5647
- /**
5648
- * Add point on the current elliptic curve
5649
- *
5650
- * @param point - Point to add on the curve
5651
- * @returns compressed point on the curve
5652
- */
5653
- addPoint(point) {
5654
- const p0 = secp256k1.ProjectivePoint.fromHex(arrayify15(this.compressedPublicKey));
5655
- const p1 = secp256k1.ProjectivePoint.fromHex(arrayify15(point));
5656
- const result = p0.add(p1);
5657
- return `0x${result.toHex(true)}`;
5658
- }
5659
- /**
5660
- * Recover the public key from a signature performed with [`sign`](#sign).
5661
- *
5662
- * @param data - Data
5663
- * @param signature - hashed signature
5664
- * @returns public key from signature from the
5665
- */
5666
- static recoverPublicKey(data, signature) {
5667
- const signedMessageBytes = arrayify15(signature);
5668
- const r = signedMessageBytes.slice(0, 32);
5669
- const s = signedMessageBytes.slice(32, 64);
5670
- const recoveryParam = (s[0] & 128) >> 7;
5671
- s[0] &= 127;
5672
- const sig = new secp256k1.Signature(BigInt(hexlify14(r)), BigInt(hexlify14(s))).addRecoveryBit(
5673
- recoveryParam
5674
- );
5675
- const publicKey = sig.recoverPublicKey(arrayify15(data)).toRawBytes(false).slice(1);
5676
- return hexlify14(publicKey);
5677
- }
5678
- /**
5679
- * Recover the address from a signature performed with [`sign`](#sign).
5680
- *
5681
- * @param data - Data
5682
- * @param signature - Signature
5683
- * @returns Address from signature
5684
- */
5685
- static recoverAddress(data, signature) {
5686
- return Address4.fromPublicKey(Signer.recoverPublicKey(data, signature));
5687
- }
5688
- /**
5689
- * Generate a random privateKey
5690
- *
5691
- * @param entropy - Adds extra entropy to generate the privateKey
5692
- * @returns random 32-byte hashed
5693
- */
5694
- static generatePrivateKey(entropy) {
5695
- return entropy ? hash(concat3([randomBytes3(32), arrayify15(entropy)])) : randomBytes3(32);
5696
- }
5697
- /**
5698
- * Extended publicKey from a compact publicKey
5699
- *
5700
- * @param publicKey - Compact publicKey
5701
- * @returns extended publicKey
5702
- */
5703
- static extendPublicKey(publicKey) {
5704
- const point = secp256k1.ProjectivePoint.fromHex(arrayify15(publicKey));
5705
- return hexlify14(point.toRawBytes(false).slice(1));
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;
5706
6296
  }
5707
6297
  };
5708
6298
 
@@ -5711,15 +6301,15 @@ import { Address as Address5 } from "@fuel-ts/address";
5711
6301
  import {
5712
6302
  bufferFromString,
5713
6303
  keccak256,
5714
- randomBytes as randomBytes4,
6304
+ randomBytes as randomBytes6,
5715
6305
  scrypt,
5716
6306
  stringFromBuffer,
5717
6307
  decryptJsonWalletData,
5718
- encryptJsonWalletData
6308
+ encryptJsonWalletData,
6309
+ randomUUID as randomUUID2
5719
6310
  } from "@fuel-ts/crypto";
5720
- import { ErrorCode as ErrorCode16, FuelError as FuelError16 } from "@fuel-ts/errors";
5721
- import { hexlify as hexlify15 } from "@fuel-ts/utils";
5722
- 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";
5723
6313
  var DEFAULT_KDF_PARAMS_LOG_N = 13;
5724
6314
  var DEFAULT_KDF_PARAMS_R = 8;
5725
6315
  var DEFAULT_KDF_PARAMS_P = 1;
@@ -5734,7 +6324,7 @@ var removeHexPrefix = (hexString) => {
5734
6324
  async function encryptKeystoreWallet(privateKey, address, password) {
5735
6325
  const privateKeyBuffer = bufferFromString(removeHexPrefix(privateKey), "hex");
5736
6326
  const ownerAddress = Address5.fromAddressOrString(address);
5737
- const salt = randomBytes4(DEFAULT_KEY_SIZE);
6327
+ const salt = randomBytes6(DEFAULT_KEY_SIZE);
5738
6328
  const key = scrypt({
5739
6329
  password: bufferFromString(password),
5740
6330
  salt,
@@ -5743,13 +6333,13 @@ async function encryptKeystoreWallet(privateKey, address, password) {
5743
6333
  r: DEFAULT_KDF_PARAMS_R,
5744
6334
  p: DEFAULT_KDF_PARAMS_P
5745
6335
  });
5746
- const iv = randomBytes4(DEFAULT_IV_SIZE);
6336
+ const iv = randomBytes6(DEFAULT_IV_SIZE);
5747
6337
  const ciphertext = await encryptJsonWalletData(privateKeyBuffer, key, iv);
5748
6338
  const data = Uint8Array.from([...key.subarray(16, 32), ...ciphertext]);
5749
6339
  const macHashUint8Array = keccak256(data);
5750
6340
  const mac = stringFromBuffer(macHashUint8Array, "hex");
5751
6341
  const keystore = {
5752
- id: uuidv4(),
6342
+ id: randomUUID2(),
5753
6343
  version: 3,
5754
6344
  address: removeHexPrefix(ownerAddress.toHexString()),
5755
6345
  crypto: {
@@ -5795,13 +6385,13 @@ async function decryptKeystoreWallet(jsonWallet, password) {
5795
6385
  const macHashUint8Array = keccak256(data);
5796
6386
  const macHash = stringFromBuffer(macHashUint8Array, "hex");
5797
6387
  if (mac !== macHash) {
5798
- throw new FuelError16(
6388
+ throw new FuelError18(
5799
6389
  ErrorCode16.INVALID_PASSWORD,
5800
6390
  "Failed to decrypt the keystore wallet, the provided password is incorrect."
5801
6391
  );
5802
6392
  }
5803
6393
  const buffer = await decryptJsonWalletData(ciphertextBuffer, key, ivBuffer);
5804
- const privateKey = hexlify15(buffer);
6394
+ const privateKey = hexlify17(buffer);
5805
6395
  return privateKey;
5806
6396
  }
5807
6397
 
@@ -5846,7 +6436,7 @@ var BaseWalletUnlocked = class extends Account {
5846
6436
  */
5847
6437
  async signMessage(message) {
5848
6438
  const signedMessage = await this.signer().sign(hashMessage(message));
5849
- return hexlify16(signedMessage);
6439
+ return hexlify18(signedMessage);
5850
6440
  }
5851
6441
  /**
5852
6442
  * Signs a transaction with the wallet's private key.
@@ -5859,7 +6449,7 @@ var BaseWalletUnlocked = class extends Account {
5859
6449
  const chainId = this.provider.getChainId();
5860
6450
  const hashedTransaction = transactionRequest.getTransactionId(chainId);
5861
6451
  const signature = await this.signer().sign(hashedTransaction);
5862
- return hexlify16(signature);
6452
+ return hexlify18(signature);
5863
6453
  }
5864
6454
  /**
5865
6455
  * Populates a transaction with the witnesses signature.
@@ -5926,16 +6516,16 @@ __publicField(BaseWalletUnlocked, "defaultPath", "m/44'/1179993420'/0'/0/0");
5926
6516
 
5927
6517
  // src/hdwallet/hdwallet.ts
5928
6518
  import { computeHmac as computeHmac2, ripemd160 } from "@fuel-ts/crypto";
5929
- import { ErrorCode as ErrorCode19, FuelError as FuelError19 } from "@fuel-ts/errors";
6519
+ import { ErrorCode as ErrorCode19, FuelError as FuelError21 } from "@fuel-ts/errors";
5930
6520
  import { sha256 as sha2564 } from "@fuel-ts/hasher";
5931
6521
  import { bn as bn20, toBytes as toBytes2, toHex } from "@fuel-ts/math";
5932
- 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";
5933
6523
 
5934
6524
  // src/mnemonic/mnemonic.ts
5935
- import { randomBytes as randomBytes5, pbkdf2, computeHmac } from "@fuel-ts/crypto";
5936
- 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";
5937
6527
  import { sha256 as sha2563 } from "@fuel-ts/hasher";
5938
- 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";
5939
6529
 
5940
6530
  // src/wordlists/words/english.ts
5941
6531
  var english = [
@@ -7990,7 +8580,7 @@ var english = [
7990
8580
  ];
7991
8581
 
7992
8582
  // src/mnemonic/utils.ts
7993
- import { ErrorCode as ErrorCode17, FuelError as FuelError17 } from "@fuel-ts/errors";
8583
+ import { ErrorCode as ErrorCode17, FuelError as FuelError19 } from "@fuel-ts/errors";
7994
8584
  import { sha256 as sha2562 } from "@fuel-ts/hasher";
7995
8585
  import { arrayify as arrayify16 } from "@fuel-ts/utils";
7996
8586
  function getLowerMask(bits) {
@@ -8039,7 +8629,7 @@ function mnemonicWordsToEntropy(words, wordlist) {
8039
8629
  for (let i = 0; i < words.length; i += 1) {
8040
8630
  const index = wordlist.indexOf(words[i].normalize("NFKD"));
8041
8631
  if (index === -1) {
8042
- throw new FuelError17(
8632
+ throw new FuelError19(
8043
8633
  ErrorCode17.INVALID_MNEMONIC,
8044
8634
  `Invalid mnemonic: the word '${words[i]}' is not found in the provided wordlist.`
8045
8635
  );
@@ -8056,7 +8646,7 @@ function mnemonicWordsToEntropy(words, wordlist) {
8056
8646
  const checksumMask = getUpperMask(checksumBits);
8057
8647
  const checksum = arrayify16(sha2562(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
8058
8648
  if (checksum !== (entropy[entropy.length - 1] & checksumMask)) {
8059
- throw new FuelError17(
8649
+ throw new FuelError19(
8060
8650
  ErrorCode17.INVALID_CHECKSUM,
8061
8651
  "Checksum validation failed for the provided mnemonic."
8062
8652
  );
@@ -8071,7 +8661,7 @@ var TestnetPRV = "0x04358394";
8071
8661
  var MNEMONIC_SIZES = [12, 15, 18, 21, 24];
8072
8662
  function assertWordList(wordlist) {
8073
8663
  if (wordlist.length !== 2048) {
8074
- throw new FuelError18(
8664
+ throw new FuelError20(
8075
8665
  ErrorCode18.INVALID_WORD_LIST,
8076
8666
  `Expected word list length of 2048, but got ${wordlist.length}.`
8077
8667
  );
@@ -8079,7 +8669,7 @@ function assertWordList(wordlist) {
8079
8669
  }
8080
8670
  function assertEntropy(entropy) {
8081
8671
  if (entropy.length % 4 !== 0 || entropy.length < 16 || entropy.length > 32) {
8082
- throw new FuelError18(
8672
+ throw new FuelError20(
8083
8673
  ErrorCode18.INVALID_ENTROPY,
8084
8674
  `Entropy should be between 16 and 32 bytes and a multiple of 4, but got ${entropy.length} bytes.`
8085
8675
  );
@@ -8090,7 +8680,7 @@ function assertMnemonic(words) {
8090
8680
  const errorMsg = `Invalid mnemonic size. Expected one of [${MNEMONIC_SIZES.join(
8091
8681
  ", "
8092
8682
  )}] words, but got ${words.length}.`;
8093
- throw new FuelError18(ErrorCode18.INVALID_MNEMONIC, errorMsg);
8683
+ throw new FuelError20(ErrorCode18.INVALID_MNEMONIC, errorMsg);
8094
8684
  }
8095
8685
  }
8096
8686
  var Mnemonic = class {
@@ -8129,7 +8719,7 @@ var Mnemonic = class {
8129
8719
  static mnemonicToEntropy(phrase, wordlist = english) {
8130
8720
  const words = getWords(phrase);
8131
8721
  assertMnemonic(words);
8132
- return hexlify17(mnemonicWordsToEntropy(words, wordlist));
8722
+ return hexlify19(mnemonicWordsToEntropy(words, wordlist));
8133
8723
  }
8134
8724
  /**
8135
8725
  * @param entropy - Entropy source to the mnemonic phrase.
@@ -8208,7 +8798,7 @@ var Mnemonic = class {
8208
8798
  static masterKeysFromSeed(seed) {
8209
8799
  const seedArray = arrayify17(seed);
8210
8800
  if (seedArray.length < 16 || seedArray.length > 64) {
8211
- throw new FuelError18(
8801
+ throw new FuelError20(
8212
8802
  ErrorCode18.INVALID_SEED,
8213
8803
  `Seed length should be between 16 and 64 bytes, but received ${seedArray.length} bytes.`
8214
8804
  );
@@ -8254,7 +8844,7 @@ var Mnemonic = class {
8254
8844
  * @returns A randomly generated mnemonic
8255
8845
  */
8256
8846
  static generate(size = 32, extraEntropy = "") {
8257
- const entropy = extraEntropy ? sha2563(concat4([randomBytes5(size), arrayify17(extraEntropy)])) : randomBytes5(size);
8847
+ const entropy = extraEntropy ? sha2563(concat4([randomBytes7(size), arrayify17(extraEntropy)])) : randomBytes7(size);
8258
8848
  return Mnemonic.entropyToMnemonic(entropy);
8259
8849
  }
8260
8850
  };
@@ -8262,10 +8852,10 @@ var mnemonic_default = Mnemonic;
8262
8852
 
8263
8853
  // src/hdwallet/hdwallet.ts
8264
8854
  var HARDENED_INDEX = 2147483648;
8265
- var MainnetPRV2 = hexlify18("0x0488ade4");
8266
- var MainnetPUB = hexlify18("0x0488b21e");
8267
- var TestnetPRV2 = hexlify18("0x04358394");
8268
- var TestnetPUB = hexlify18("0x043587cf");
8855
+ var MainnetPRV2 = hexlify20("0x0488ade4");
8856
+ var MainnetPUB = hexlify20("0x0488b21e");
8857
+ var TestnetPRV2 = hexlify20("0x04358394");
8858
+ var TestnetPUB = hexlify20("0x043587cf");
8269
8859
  function base58check(data) {
8270
8860
  return encodeBase582(concat5([data, dataSlice2(sha2564(sha2564(data)), 0, 4)]));
8271
8861
  }
@@ -8276,17 +8866,17 @@ function getExtendedKeyPrefix(isPublic = false, testnet = false) {
8276
8866
  return testnet ? TestnetPRV2 : MainnetPRV2;
8277
8867
  }
8278
8868
  function isPublicExtendedKey(extendedKey) {
8279
- return [MainnetPUB, TestnetPUB].includes(hexlify18(extendedKey.slice(0, 4)));
8869
+ return [MainnetPUB, TestnetPUB].includes(hexlify20(extendedKey.slice(0, 4)));
8280
8870
  }
8281
8871
  function isValidExtendedKey(extendedKey) {
8282
8872
  return [MainnetPRV2, TestnetPRV2, MainnetPUB, TestnetPUB].includes(
8283
- hexlify18(extendedKey.slice(0, 4))
8873
+ hexlify20(extendedKey.slice(0, 4))
8284
8874
  );
8285
8875
  }
8286
8876
  function parsePath(path2, depth = 0) {
8287
8877
  const components = path2.split("/");
8288
8878
  if (components.length === 0 || components[0] === "m" && depth !== 0) {
8289
- throw new FuelError19(ErrorCode19.HD_WALLET_ERROR, `invalid path - ${path2}`);
8879
+ throw new FuelError21(ErrorCode19.HD_WALLET_ERROR, `invalid path - ${path2}`);
8290
8880
  }
8291
8881
  if (components[0] === "m") {
8292
8882
  components.shift();
@@ -8298,8 +8888,8 @@ function parsePath(path2, depth = 0) {
8298
8888
  var HDWallet = class {
8299
8889
  depth = 0;
8300
8890
  index = 0;
8301
- fingerprint = hexlify18("0x00000000");
8302
- parentFingerprint = hexlify18("0x00000000");
8891
+ fingerprint = hexlify20("0x00000000");
8892
+ parentFingerprint = hexlify20("0x00000000");
8303
8893
  privateKey;
8304
8894
  publicKey;
8305
8895
  chainCode;
@@ -8311,16 +8901,16 @@ var HDWallet = class {
8311
8901
  constructor(config) {
8312
8902
  if (config.privateKey) {
8313
8903
  const signer = new Signer(config.privateKey);
8314
- this.publicKey = hexlify18(signer.compressedPublicKey);
8315
- this.privateKey = hexlify18(config.privateKey);
8904
+ this.publicKey = hexlify20(signer.compressedPublicKey);
8905
+ this.privateKey = hexlify20(config.privateKey);
8316
8906
  } else {
8317
8907
  if (!config.publicKey) {
8318
- throw new FuelError19(
8908
+ throw new FuelError21(
8319
8909
  ErrorCode19.HD_WALLET_ERROR,
8320
8910
  "Both public and private Key cannot be missing. At least one should be provided."
8321
8911
  );
8322
8912
  }
8323
- this.publicKey = hexlify18(config.publicKey);
8913
+ this.publicKey = hexlify20(config.publicKey);
8324
8914
  }
8325
8915
  this.parentFingerprint = config.parentFingerprint || this.parentFingerprint;
8326
8916
  this.fingerprint = dataSlice2(ripemd160(sha2564(this.publicKey)), 0, 4);
@@ -8345,7 +8935,7 @@ var HDWallet = class {
8345
8935
  const data = new Uint8Array(37);
8346
8936
  if (index & HARDENED_INDEX) {
8347
8937
  if (!privateKey) {
8348
- throw new FuelError19(
8938
+ throw new FuelError21(
8349
8939
  ErrorCode19.HD_WALLET_ERROR,
8350
8940
  "Cannot derive a hardened index without a private Key."
8351
8941
  );
@@ -8369,7 +8959,7 @@ var HDWallet = class {
8369
8959
  parentFingerprint: this.fingerprint
8370
8960
  });
8371
8961
  }
8372
- const signer = new Signer(hexlify18(IL));
8962
+ const signer = new Signer(hexlify20(IL));
8373
8963
  const Ki = signer.addPoint(publicKey);
8374
8964
  return new HDWallet({
8375
8965
  publicKey: Ki,
@@ -8398,13 +8988,13 @@ var HDWallet = class {
8398
8988
  */
8399
8989
  toExtendedKey(isPublic = false, testnet = false) {
8400
8990
  if (this.depth >= 256) {
8401
- throw new FuelError19(
8991
+ throw new FuelError21(
8402
8992
  ErrorCode19.HD_WALLET_ERROR,
8403
8993
  `Exceeded max depth of 255. Current depth: ${this.depth}.`
8404
8994
  );
8405
8995
  }
8406
8996
  const prefix = getExtendedKeyPrefix(this.privateKey == null || isPublic, testnet);
8407
- const depth = hexlify18(Uint8Array.from([this.depth]));
8997
+ const depth = hexlify20(Uint8Array.from([this.depth]));
8408
8998
  const parentFingerprint = this.parentFingerprint;
8409
8999
  const index = toHex(this.index, 4);
8410
9000
  const chainCode = this.chainCode;
@@ -8426,29 +9016,29 @@ var HDWallet = class {
8426
9016
  });
8427
9017
  }
8428
9018
  static fromExtendedKey(extendedKey) {
8429
- const decoded = hexlify18(toBytes2(decodeBase58(extendedKey)));
9019
+ const decoded = hexlify20(toBytes2(decodeBase58(extendedKey)));
8430
9020
  const bytes = arrayify18(decoded);
8431
9021
  const validChecksum = base58check(bytes.slice(0, 78)) === extendedKey;
8432
9022
  if (bytes.length !== 82 || !isValidExtendedKey(bytes)) {
8433
- 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.");
8434
9024
  }
8435
9025
  if (!validChecksum) {
8436
- 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.");
8437
9027
  }
8438
9028
  const depth = bytes[4];
8439
- const parentFingerprint = hexlify18(bytes.slice(5, 9));
8440
- const index = parseInt(hexlify18(bytes.slice(9, 13)).substring(2), 16);
8441
- 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));
8442
9032
  const key = bytes.slice(45, 78);
8443
9033
  if (depth === 0 && parentFingerprint !== "0x00000000" || depth === 0 && index !== 0) {
8444
- throw new FuelError19(
9034
+ throw new FuelError21(
8445
9035
  ErrorCode19.HD_WALLET_ERROR,
8446
9036
  "Inconsistency detected: Depth is zero but fingerprint/index is non-zero."
8447
9037
  );
8448
9038
  }
8449
9039
  if (isPublicExtendedKey(bytes)) {
8450
9040
  if (key[0] !== 3) {
8451
- throw new FuelError19(ErrorCode19.HD_WALLET_ERROR, "Invalid public extended key.");
9041
+ throw new FuelError21(ErrorCode19.HD_WALLET_ERROR, "Invalid public extended key.");
8452
9042
  }
8453
9043
  return new HDWallet({
8454
9044
  publicKey: key,
@@ -8459,7 +9049,7 @@ var HDWallet = class {
8459
9049
  });
8460
9050
  }
8461
9051
  if (key[0] !== 0) {
8462
- throw new FuelError19(ErrorCode19.HD_WALLET_ERROR, "Invalid private extended key.");
9052
+ throw new FuelError21(ErrorCode19.HD_WALLET_ERROR, "Invalid private extended key.");
8463
9053
  }
8464
9054
  return new HDWallet({
8465
9055
  privateKey: key.slice(1),
@@ -8624,297 +9214,7 @@ __publicField(Wallet, "fromExtendedKey", WalletUnlocked.fromExtendedKey);
8624
9214
  */
8625
9215
  __publicField(Wallet, "fromEncryptedJson", WalletUnlocked.fromEncryptedJson);
8626
9216
 
8627
- // src/test-utils/seedTestWallet.ts
8628
- import { randomBytes as randomBytes6 } from "@fuel-ts/crypto";
8629
- var seedTestWallet = async (wallet, quantities, utxosAmount = 1) => {
8630
- const accountsToBeFunded = Array.isArray(wallet) ? wallet : [wallet];
8631
- const [{ provider }] = accountsToBeFunded;
8632
- const genesisWallet = new WalletUnlocked(process.env.GENESIS_SECRET || randomBytes6(32), provider);
8633
- const request = new ScriptTransactionRequest();
8634
- quantities.map(coinQuantityfy).forEach(
8635
- ({ amount, assetId }) => accountsToBeFunded.forEach(({ address }) => {
8636
- for (let i = 0; i < utxosAmount; i++) {
8637
- request.addCoinOutput(address, amount.div(utxosAmount), assetId);
8638
- }
8639
- })
8640
- );
8641
- const txCost = await genesisWallet.getTransactionCost(request);
8642
- request.gasLimit = txCost.gasUsed;
8643
- request.maxFee = txCost.maxFee;
8644
- await genesisWallet.fund(request, txCost);
8645
- const submit = await genesisWallet.sendTransaction(request);
8646
- await submit.waitForResult();
8647
- };
8648
-
8649
- // src/test-utils/generateTestWallet.ts
8650
- var generateTestWallet = async (provider, quantities) => {
8651
- const wallet = Wallet.generate({ provider });
8652
- if (quantities) {
8653
- await seedTestWallet(wallet, quantities);
8654
- }
8655
- return wallet;
8656
- };
8657
-
8658
- // src/test-utils/launchNode.ts
8659
- import { BYTES_32 as BYTES_322 } from "@fuel-ts/abi-coder";
8660
- import { randomBytes as randomBytes7 } from "@fuel-ts/crypto";
8661
- import { FuelError as FuelError20 } from "@fuel-ts/errors";
8662
- import { defaultConsensusKey, hexlify as hexlify19, defaultSnapshotConfigs } from "@fuel-ts/utils";
8663
- import { randomUUID } from "crypto";
8664
- import { existsSync, mkdirSync, rmSync, writeFileSync } from "fs";
8665
- import os from "os";
8666
- import path from "path";
8667
- import { getPortPromise } from "portfinder";
8668
- var getFlagValueFromArgs = (args, flag) => {
8669
- const flagIndex = args.indexOf(flag);
8670
- if (flagIndex === -1) {
8671
- return void 0;
8672
- }
8673
- return args[flagIndex + 1];
8674
- };
8675
- var extractRemainingArgs = (args, flagsToRemove) => {
8676
- const newArgs = [...args];
8677
- flagsToRemove.forEach((flag) => {
8678
- const flagIndex = newArgs.indexOf(flag);
8679
- if (flagIndex !== -1) {
8680
- newArgs.splice(flagIndex, 2);
8681
- }
8682
- });
8683
- return newArgs;
8684
- };
8685
- function getFinalStateConfigJSON({ stateConfig, chainConfig }) {
8686
- const defaultCoins = defaultSnapshotConfigs.stateConfig.coins.map((coin) => ({
8687
- ...coin,
8688
- amount: "18446744073709551615"
8689
- }));
8690
- const defaultMessages = defaultSnapshotConfigs.stateConfig.messages.map((message) => ({
8691
- ...message,
8692
- amount: "18446744073709551615"
8693
- }));
8694
- 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);
8695
- 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);
8696
- if (!process.env.GENESIS_SECRET) {
8697
- const pk = Signer.generatePrivateKey();
8698
- const signer = new Signer(pk);
8699
- process.env.GENESIS_SECRET = hexlify19(pk);
8700
- coins.push({
8701
- tx_id: hexlify19(randomBytes7(BYTES_322)),
8702
- owner: signer.address.toHexString(),
8703
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
8704
- amount: "18446744073709551615",
8705
- asset_id: chainConfig.consensus_parameters.V1.base_asset_id,
8706
- output_index: 0,
8707
- tx_pointer_block_height: 0,
8708
- tx_pointer_tx_idx: 0
8709
- });
8710
- }
8711
- const json = JSON.stringify({
8712
- ...stateConfig,
8713
- coins,
8714
- messages
8715
- });
8716
- const regexMakeNumber = /("amount":)"(\d+)"/gm;
8717
- return json.replace(regexMakeNumber, "$1$2");
8718
- }
8719
- var launchNode = async ({
8720
- ip,
8721
- port,
8722
- args = [],
8723
- fuelCorePath = process.env.FUEL_CORE_PATH || void 0,
8724
- loggingEnabled = true,
8725
- basePath,
8726
- snapshotConfig = defaultSnapshotConfigs
8727
- } = {}) => (
8728
- // eslint-disable-next-line no-async-promise-executor
8729
- new Promise(async (resolve, reject) => {
8730
- const remainingArgs = extractRemainingArgs(args, [
8731
- "--snapshot",
8732
- "--consensus-key",
8733
- "--db-type",
8734
- "--poa-instant",
8735
- "--min-gas-price",
8736
- "--native-executor-version"
8737
- ]);
8738
- const snapshotDir = getFlagValueFromArgs(args, "--snapshot");
8739
- const consensusKey = getFlagValueFromArgs(args, "--consensus-key") || defaultConsensusKey;
8740
- const dbTypeFlagValue = getFlagValueFromArgs(args, "--db-type");
8741
- const useInMemoryDb = dbTypeFlagValue === "in-memory" || dbTypeFlagValue === void 0;
8742
- const poaInstantFlagValue = getFlagValueFromArgs(args, "--poa-instant");
8743
- const poaInstant = poaInstantFlagValue === "true" || poaInstantFlagValue === void 0;
8744
- const nativeExecutorVersion = getFlagValueFromArgs(args, "--native-executor-version") || "0";
8745
- const minGasPrice = getFlagValueFromArgs(args, "--min-gas-price") || "1";
8746
- const graphQLStartSubstring = "Binding GraphQL provider to";
8747
- const command = fuelCorePath || "fuel-core";
8748
- const ipToUse = ip || "0.0.0.0";
8749
- const portToUse = port || (await getPortPromise({
8750
- port: 4e3,
8751
- // tries 4000 first, then 4001, then 4002, etc.
8752
- stopPort: 5e3
8753
- // don't try ports above 5000
8754
- })).toString();
8755
- let snapshotDirToUse;
8756
- const prefix = basePath || os.tmpdir();
8757
- const suffix = basePath ? "" : randomUUID();
8758
- const tempDir = path.join(prefix, ".fuels", suffix, "snapshotDir");
8759
- if (snapshotDir) {
8760
- snapshotDirToUse = snapshotDir;
8761
- } else {
8762
- if (!existsSync(tempDir)) {
8763
- mkdirSync(tempDir, { recursive: true });
8764
- }
8765
- const { metadata } = snapshotConfig;
8766
- const metadataPath = path.join(tempDir, "metadata.json");
8767
- const chainConfigPath = path.join(tempDir, metadata.chain_config);
8768
- const stateConfigPath = path.join(tempDir, metadata.table_encoding.Json.filepath);
8769
- const stateTransitionPath = path.join(tempDir, "state_transition_bytecode.wasm");
8770
- writeFileSync(chainConfigPath, JSON.stringify(snapshotConfig.chainConfig), "utf8");
8771
- writeFileSync(stateConfigPath, getFinalStateConfigJSON(snapshotConfig), "utf8");
8772
- writeFileSync(metadataPath, JSON.stringify(metadata), "utf8");
8773
- writeFileSync(stateTransitionPath, JSON.stringify(""));
8774
- snapshotDirToUse = tempDir;
8775
- }
8776
- const { spawn } = await import("child_process");
8777
- const child = spawn(
8778
- command,
8779
- [
8780
- "run",
8781
- ["--ip", ipToUse],
8782
- ["--port", portToUse],
8783
- useInMemoryDb ? ["--db-type", "in-memory"] : ["--db-path", tempDir],
8784
- ["--min-gas-price", minGasPrice],
8785
- poaInstant ? ["--poa-instant", "true"] : [],
8786
- ["--native-executor-version", nativeExecutorVersion],
8787
- ["--consensus-key", consensusKey],
8788
- ["--snapshot", snapshotDirToUse],
8789
- "--vm-backtrace",
8790
- "--utxo-validation",
8791
- "--debug",
8792
- ...remainingArgs
8793
- ].flat(),
8794
- { stdio: "pipe", detached: true }
8795
- );
8796
- if (loggingEnabled) {
8797
- child.stderr.on("data", (chunk) => {
8798
- console.log(chunk.toString());
8799
- });
8800
- }
8801
- const removeSideffects = () => {
8802
- child.stderr.removeAllListeners();
8803
- if (existsSync(tempDir)) {
8804
- rmSync(tempDir, { recursive: true });
8805
- }
8806
- };
8807
- child.on("error", removeSideffects);
8808
- child.on("exit", removeSideffects);
8809
- const childState = {
8810
- isDead: false
8811
- };
8812
- const cleanup = () => {
8813
- if (childState.isDead) {
8814
- return;
8815
- }
8816
- childState.isDead = true;
8817
- removeSideffects();
8818
- if (child.pid !== void 0) {
8819
- try {
8820
- process.kill(-child.pid);
8821
- } catch (e) {
8822
- const error = e;
8823
- if (error.code === "ESRCH") {
8824
- console.log(
8825
- `fuel-core node under pid ${child.pid} does not exist. The node might have been killed before cleanup was called. Exiting cleanly.`
8826
- );
8827
- } else {
8828
- throw e;
8829
- }
8830
- }
8831
- } else {
8832
- console.error("No PID available for the child process, unable to kill launched node");
8833
- }
8834
- };
8835
- child.stderr.on("data", (chunk) => {
8836
- const text = typeof chunk === "string" ? chunk : chunk.toString();
8837
- if (text.indexOf(graphQLStartSubstring) !== -1) {
8838
- const rows = text.split("\n");
8839
- const rowWithUrl = rows.find((row) => row.indexOf(graphQLStartSubstring) !== -1);
8840
- const [realIp, realPort] = rowWithUrl.split(" ").at(-1).trim().split(":");
8841
- resolve({
8842
- cleanup,
8843
- ip: realIp,
8844
- port: realPort,
8845
- url: `http://${realIp}:${realPort}/v1/graphql`,
8846
- snapshotDir: snapshotDirToUse,
8847
- pid: child.pid
8848
- });
8849
- }
8850
- if (/error/i.test(text)) {
8851
- console.log(text);
8852
- reject(new FuelError20(FuelError20.CODES.NODE_LAUNCH_FAILED, text));
8853
- }
8854
- });
8855
- process.on("exit", cleanup);
8856
- process.on("SIGINT", cleanup);
8857
- process.on("SIGUSR1", cleanup);
8858
- process.on("SIGUSR2", cleanup);
8859
- process.on("beforeExit", cleanup);
8860
- process.on("uncaughtException", cleanup);
8861
- child.on("error", reject);
8862
- })
8863
- );
8864
- var generateWallets = async (count, provider) => {
8865
- const baseAssetId = provider.getBaseAssetId();
8866
- const wallets = [];
8867
- for (let i = 0; i < count; i += 1) {
8868
- const wallet = await generateTestWallet(provider, [[1e5, baseAssetId]]);
8869
- wallets.push(wallet);
8870
- }
8871
- return wallets;
8872
- };
8873
- var launchNodeAndGetWallets = async ({
8874
- launchNodeOptions,
8875
- providerOptions,
8876
- walletCount = 10
8877
- } = {}) => {
8878
- const { cleanup: closeNode, ip, port } = await launchNode(launchNodeOptions || {});
8879
- const provider = await Provider.create(`http://${ip}:${port}/v1/graphql`, providerOptions);
8880
- const wallets = await generateWallets(walletCount, provider);
8881
- const cleanup = () => {
8882
- closeNode();
8883
- };
8884
- return { wallets, stop: cleanup, provider };
8885
- };
8886
-
8887
- // src/test-utils/setup-test-provider-and-wallets.ts
8888
- import { defaultSnapshotConfigs as defaultSnapshotConfigs3 } from "@fuel-ts/utils";
8889
- import { mergeDeepRight } from "ramda";
8890
-
8891
- // src/test-utils/asset-id.ts
8892
- import { randomBytes as randomBytes8 } from "@fuel-ts/crypto";
8893
- import { hexlify as hexlify20 } from "@fuel-ts/utils";
8894
- var _AssetId = class {
8895
- constructor(value) {
8896
- this.value = value;
8897
- }
8898
- static random(count = 1) {
8899
- const assetIds = [];
8900
- for (let i = 0; i < count; i++) {
8901
- assetIds.push(new _AssetId(hexlify20(randomBytes8(32))));
8902
- }
8903
- return assetIds;
8904
- }
8905
- };
8906
- var AssetId = _AssetId;
8907
- __publicField(AssetId, "A", new _AssetId(
8908
- "0x0101010101010101010101010101010101010101010101010101010101010101"
8909
- ));
8910
- __publicField(AssetId, "B", new _AssetId(
8911
- "0x0202020202020202020202020202020202020202020202020202020202020202"
8912
- ));
8913
-
8914
9217
  // src/test-utils/wallet-config.ts
8915
- import { randomBytes as randomBytes9 } from "@fuel-ts/crypto";
8916
- import { FuelError as FuelError21 } from "@fuel-ts/errors";
8917
- import { defaultSnapshotConfigs as defaultSnapshotConfigs2, hexlify as hexlify21 } from "@fuel-ts/utils";
8918
9218
  var WalletsConfig = class {
8919
9219
  initialState;
8920
9220
  options;
@@ -8922,7 +9222,7 @@ var WalletsConfig = class {
8922
9222
  generateWallets = () => {
8923
9223
  const generatedWallets = [];
8924
9224
  for (let index = 1; index <= this.options.count; index++) {
8925
- generatedWallets.push(new WalletUnlocked(randomBytes9(32)));
9225
+ generatedWallets.push(new WalletUnlocked(randomBytes8(32)));
8926
9226
  }
8927
9227
  return generatedWallets;
8928
9228
  };
@@ -8967,7 +9267,7 @@ var WalletsConfig = class {
8967
9267
  if (Array.isArray(assets2)) {
8968
9268
  assetIds = assetIds.concat(assets2.map((a) => a.value));
8969
9269
  } else {
8970
- assetIds = assetIds.concat(AssetId.random(assets2 - 1).map((a) => a.value));
9270
+ assetIds = assetIds.concat(TestAssetId.random(assets2 - 1).map((a) => a.value));
8971
9271
  }
8972
9272
  wallets.map((wallet) => wallet.address.toHexString()).forEach((walletAddress) => {
8973
9273
  assetIds.forEach((assetId) => {
@@ -8979,7 +9279,7 @@ var WalletsConfig = class {
8979
9279
  tx_pointer_block_height: 0,
8980
9280
  tx_pointer_tx_idx: 0,
8981
9281
  output_index: 0,
8982
- tx_id: hexlify21(randomBytes9(32))
9282
+ tx_id: hexlify21(randomBytes8(32))
8983
9283
  });
8984
9284
  }
8985
9285
  });
@@ -8993,27 +9293,27 @@ var WalletsConfig = class {
8993
9293
  amountPerCoin
8994
9294
  }) {
8995
9295
  if (Array.isArray(wallets) && wallets.length === 0 || typeof wallets === "number" && wallets <= 0) {
8996
- throw new FuelError21(
8997
- FuelError21.CODES.INVALID_INPUT_PARAMETERS,
9296
+ throw new FuelError22(
9297
+ FuelError22.CODES.INVALID_INPUT_PARAMETERS,
8998
9298
  "Number of wallets must be greater than zero."
8999
9299
  );
9000
9300
  }
9001
9301
  if (Array.isArray(assets2) && assets2.length === 0 || typeof assets2 === "number" && assets2 <= 0) {
9002
- throw new FuelError21(
9003
- FuelError21.CODES.INVALID_INPUT_PARAMETERS,
9302
+ throw new FuelError22(
9303
+ FuelError22.CODES.INVALID_INPUT_PARAMETERS,
9004
9304
  "Number of assets per wallet must be greater than zero."
9005
9305
  );
9006
9306
  }
9007
9307
  if (coinsPerAsset <= 0) {
9008
- throw new FuelError21(
9009
- FuelError21.CODES.INVALID_INPUT_PARAMETERS,
9308
+ throw new FuelError22(
9309
+ FuelError22.CODES.INVALID_INPUT_PARAMETERS,
9010
9310
  "Number of coins per asset must be greater than zero."
9011
9311
  );
9012
9312
  }
9013
- if (amountPerCoin <= 0) {
9014
- throw new FuelError21(
9015
- FuelError21.CODES.INVALID_INPUT_PARAMETERS,
9016
- "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."
9017
9317
  );
9018
9318
  }
9019
9319
  }
@@ -9022,7 +9322,7 @@ var WalletsConfig = class {
9022
9322
  // src/test-utils/setup-test-provider-and-wallets.ts
9023
9323
  var defaultWalletConfigOptions = {
9024
9324
  count: 2,
9025
- assets: [AssetId.A, AssetId.B],
9325
+ assets: [TestAssetId.A, TestAssetId.B],
9026
9326
  coinsPerAsset: 1,
9027
9327
  amountPerCoin: 1e10,
9028
9328
  messages: []
@@ -9048,7 +9348,7 @@ async function setupTestProviderAndWallets({
9048
9348
  defaultSnapshotConfigs3,
9049
9349
  walletsConfig.apply(nodeOptions?.snapshotConfig)
9050
9350
  ),
9051
- port: "0"
9351
+ port: nodeOptions.port || "0"
9052
9352
  };
9053
9353
  let cleanup;
9054
9354
  let url;
@@ -9084,7 +9384,7 @@ async function setupTestProviderAndWallets({
9084
9384
 
9085
9385
  // src/test-utils/test-message.ts
9086
9386
  import { Address as Address6 } from "@fuel-ts/address";
9087
- import { randomBytes as randomBytes10 } from "@fuel-ts/crypto";
9387
+ import { randomBytes as randomBytes9 } from "@fuel-ts/crypto";
9088
9388
  import { bn as bn21 } from "@fuel-ts/math";
9089
9389
  import { hexlify as hexlify22 } from "@fuel-ts/utils";
9090
9390
  var TestMessage = class {
@@ -9103,9 +9403,10 @@ var TestMessage = class {
9103
9403
  constructor({
9104
9404
  sender = Address6.fromRandom(),
9105
9405
  recipient = Address6.fromRandom(),
9106
- nonce = hexlify22(randomBytes10(32)),
9406
+ nonce = hexlify22(randomBytes9(32)),
9107
9407
  amount = 1e6,
9108
- data = "02",
9408
+ data = "",
9409
+ // Will default to empty data in order to be a spendable message
9109
9410
  da_height = 0
9110
9411
  } = {}) {
9111
9412
  this.sender = sender;
@@ -9116,24 +9417,22 @@ var TestMessage = class {
9116
9417
  this.da_height = da_height;
9117
9418
  }
9118
9419
  toChainMessage(recipient) {
9420
+ const data = /^0x/.test(this.data) ? this.data.replace(/^0x/, "") : this.data;
9119
9421
  return {
9120
9422
  sender: this.sender.toB256(),
9121
9423
  recipient: recipient?.toB256() ?? this.recipient.toB256(),
9122
9424
  nonce: this.nonce,
9123
9425
  amount: bn21(this.amount).toNumber(),
9124
- data: this.data,
9426
+ data,
9125
9427
  da_height: this.da_height
9126
9428
  };
9127
9429
  }
9128
9430
  };
9129
9431
  export {
9130
- AssetId,
9432
+ TestAssetId,
9131
9433
  TestMessage,
9132
9434
  WalletsConfig,
9133
- generateTestWallet,
9134
9435
  launchNode,
9135
- launchNodeAndGetWallets,
9136
- seedTestWallet,
9137
9436
  setupTestProviderAndWallets
9138
9437
  };
9139
9438
  //# sourceMappingURL=test-utils.mjs.map