@fuel-ts/account 0.92.1 → 0.94.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +9 -29
  2. package/dist/account.d.ts +15 -4
  3. package/dist/account.d.ts.map +1 -1
  4. package/dist/configs.d.ts +0 -2
  5. package/dist/configs.d.ts.map +1 -1
  6. package/dist/configs.global.js +0 -2
  7. package/dist/configs.global.js.map +1 -1
  8. package/dist/configs.js +0 -6
  9. package/dist/configs.js.map +1 -1
  10. package/dist/configs.mjs +0 -4
  11. package/dist/configs.mjs.map +1 -1
  12. package/dist/connectors/fuel-connector.d.ts +24 -1
  13. package/dist/connectors/fuel-connector.d.ts.map +1 -1
  14. package/dist/connectors/fuel.d.ts +14 -1
  15. package/dist/connectors/fuel.d.ts.map +1 -1
  16. package/dist/connectors/types/connector-metadata.d.ts.map +1 -1
  17. package/dist/connectors/utils/promises.d.ts.map +1 -1
  18. package/dist/index.global.js +1645 -985
  19. package/dist/index.global.js.map +1 -1
  20. package/dist/index.js +1034 -673
  21. package/dist/index.js.map +1 -1
  22. package/dist/index.mjs +771 -423
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/predicate/predicate.d.ts +15 -9
  25. package/dist/predicate/predicate.d.ts.map +1 -1
  26. package/dist/providers/__generated__/operations.d.ts +614 -1
  27. package/dist/providers/__generated__/operations.d.ts.map +1 -1
  28. package/dist/providers/fuel-graphql-subscriber.d.ts +3 -3
  29. package/dist/providers/fuel-graphql-subscriber.d.ts.map +1 -1
  30. package/dist/providers/provider.d.ts +19 -47
  31. package/dist/providers/provider.d.ts.map +1 -1
  32. package/dist/providers/resource-cache.d.ts +14 -0
  33. package/dist/providers/resource-cache.d.ts.map +1 -0
  34. package/dist/providers/transaction-request/blob-transaction-request.d.ts +48 -0
  35. package/dist/providers/transaction-request/blob-transaction-request.d.ts.map +1 -0
  36. package/dist/providers/transaction-request/index.d.ts +1 -0
  37. package/dist/providers/transaction-request/index.d.ts.map +1 -1
  38. package/dist/providers/transaction-request/transaction-request.d.ts +4 -3
  39. package/dist/providers/transaction-request/transaction-request.d.ts.map +1 -1
  40. package/dist/providers/transaction-request/types.d.ts +5 -2
  41. package/dist/providers/transaction-request/types.d.ts.map +1 -1
  42. package/dist/providers/transaction-request/utils.d.ts +9 -0
  43. package/dist/providers/transaction-request/utils.d.ts.map +1 -1
  44. package/dist/providers/transaction-response/transaction-response.d.ts +10 -5
  45. package/dist/providers/transaction-response/transaction-response.d.ts.map +1 -1
  46. package/dist/providers/transaction-summary/assemble-transaction-summary.d.ts +1 -1
  47. package/dist/providers/transaction-summary/assemble-transaction-summary.d.ts.map +1 -1
  48. package/dist/providers/transaction-summary/call.d.ts +4 -3
  49. package/dist/providers/transaction-summary/call.d.ts.map +1 -1
  50. package/dist/providers/transaction-summary/get-transaction-summary.d.ts.map +1 -1
  51. package/dist/providers/transaction-summary/input.d.ts +6 -1
  52. package/dist/providers/transaction-summary/input.d.ts.map +1 -1
  53. package/dist/providers/transaction-summary/operations.d.ts +4 -2
  54. package/dist/providers/transaction-summary/operations.d.ts.map +1 -1
  55. package/dist/providers/transaction-summary/types.d.ts +5 -2
  56. package/dist/providers/transaction-summary/types.d.ts.map +1 -1
  57. package/dist/providers/utils/gas.d.ts +6 -0
  58. package/dist/providers/utils/gas.d.ts.map +1 -1
  59. package/dist/test-utils/launchNode.d.ts +0 -16
  60. package/dist/test-utils/launchNode.d.ts.map +1 -1
  61. package/dist/test-utils/setup-test-provider-and-wallets.d.ts.map +1 -1
  62. package/dist/test-utils/test-asset-id.d.ts +8 -0
  63. package/dist/test-utils/test-asset-id.d.ts.map +1 -0
  64. package/dist/test-utils/test-message.d.ts +4 -2
  65. package/dist/test-utils/test-message.d.ts.map +1 -1
  66. package/dist/test-utils/wallet-config.d.ts +3 -3
  67. package/dist/test-utils/wallet-config.d.ts.map +1 -1
  68. package/dist/test-utils.d.ts +1 -3
  69. package/dist/test-utils.d.ts.map +1 -1
  70. package/dist/test-utils.global.js +43613 -42984
  71. package/dist/test-utils.global.js.map +1 -1
  72. package/dist/test-utils.js +1560 -1271
  73. package/dist/test-utils.js.map +1 -1
  74. package/dist/test-utils.mjs +1282 -994
  75. package/dist/test-utils.mjs.map +1 -1
  76. package/dist/wallet/base-wallet-unlocked.d.ts +1 -2
  77. package/dist/wallet/base-wallet-unlocked.d.ts.map +1 -1
  78. package/dist/wallet/keystore-wallet.d.ts.map +1 -1
  79. package/package.json +19 -21
  80. package/dist/providers/memory-cache.d.ts +0 -11
  81. package/dist/providers/memory-cache.d.ts.map +0 -1
  82. package/dist/test-utils/asset-id.d.ts +0 -8
  83. package/dist/test-utils/asset-id.d.ts.map +0 -1
  84. package/dist/test-utils/generateTestWallet.d.ts +0 -4
  85. package/dist/test-utils/generateTestWallet.d.ts.map +0 -1
  86. package/dist/test-utils/seedTestWallet.d.ts +0 -4
  87. package/dist/test-utils/seedTestWallet.d.ts.map +0 -1
@@ -48,34 +48,344 @@ var __privateMethod = (obj, member, method) => {
48
48
  // src/test-utils.ts
49
49
  var test_utils_exports = {};
50
50
  __export(test_utils_exports, {
51
- AssetId: () => AssetId,
51
+ TestAssetId: () => TestAssetId,
52
52
  TestMessage: () => TestMessage,
53
53
  WalletsConfig: () => WalletsConfig,
54
- generateTestWallet: () => generateTestWallet,
55
54
  launchNode: () => launchNode,
56
- launchNodeAndGetWallets: () => launchNodeAndGetWallets,
57
- seedTestWallet: () => seedTestWallet,
58
55
  setupTestProviderAndWallets: () => setupTestProviderAndWallets
59
56
  });
60
57
  module.exports = __toCommonJS(test_utils_exports);
61
58
 
62
- // src/wallet/base-wallet-unlocked.ts
63
- var import_hasher3 = require("@fuel-ts/hasher");
64
- var import_utils32 = require("@fuel-ts/utils");
65
-
66
- // src/account.ts
67
- var import_abi_coder7 = require("@fuel-ts/abi-coder");
68
- var import_address4 = require("@fuel-ts/address");
59
+ // src/test-utils/launchNode.ts
60
+ var import_abi_coder = require("@fuel-ts/abi-coder");
69
61
  var import_crypto2 = require("@fuel-ts/crypto");
70
- var import_errors16 = require("@fuel-ts/errors");
71
- var import_interfaces = require("@fuel-ts/interfaces");
72
- var import_math20 = require("@fuel-ts/math");
73
- var import_utils29 = require("@fuel-ts/utils");
74
- var import_ramda4 = require("ramda");
62
+ var import_errors = require("@fuel-ts/errors");
63
+ var import_utils2 = require("@fuel-ts/utils");
64
+ var import_fs = require("fs");
65
+ var import_os = __toESM(require("os"));
66
+ var import_path = __toESM(require("path"));
67
+ var import_portfinder = require("portfinder");
75
68
 
76
- // src/providers/coin-quantity.ts
69
+ // src/signer/signer.ts
70
+ var import_address = require("@fuel-ts/address");
71
+ var import_crypto = require("@fuel-ts/crypto");
72
+ var import_hasher = require("@fuel-ts/hasher");
77
73
  var import_math = require("@fuel-ts/math");
78
74
  var import_utils = require("@fuel-ts/utils");
75
+ var import_secp256k1 = require("@noble/curves/secp256k1");
76
+ var Signer = class {
77
+ address;
78
+ publicKey;
79
+ compressedPublicKey;
80
+ privateKey;
81
+ /**
82
+ * Create a Signer instance from a given private key
83
+ *
84
+ * @param privateKey - The private key to use for signing
85
+ * @returns A new Signer instance
86
+ */
87
+ constructor(privateKey) {
88
+ if (typeof privateKey === "string") {
89
+ if (privateKey.match(/^[0-9a-f]*$/i) && privateKey.length === 64) {
90
+ privateKey = `0x${privateKey}`;
91
+ }
92
+ }
93
+ const privateKeyBytes = (0, import_math.toBytes)(privateKey, 32);
94
+ this.privateKey = (0, import_utils.hexlify)(privateKeyBytes);
95
+ this.publicKey = (0, import_utils.hexlify)(import_secp256k1.secp256k1.getPublicKey(privateKeyBytes, false).slice(1));
96
+ this.compressedPublicKey = (0, import_utils.hexlify)(import_secp256k1.secp256k1.getPublicKey(privateKeyBytes, true));
97
+ this.address = import_address.Address.fromPublicKey(this.publicKey);
98
+ }
99
+ /**
100
+ * Sign data using the Signer instance
101
+ *
102
+ * Signature is a 64 byte array of the concatenated r and s values with the compressed recoveryParam byte.
103
+ * @ignore
104
+ * [Read more](FuelLabs/fuel-specs/specs/protocol/cryptographic_primitives.md#public-key-cryptography)
105
+ *
106
+ * @param data - The data to be sign
107
+ * @returns hashed signature
108
+ */
109
+ sign(data) {
110
+ const signature = import_secp256k1.secp256k1.sign((0, import_utils.arrayify)(data), (0, import_utils.arrayify)(this.privateKey));
111
+ const r = (0, import_math.toBytes)(`0x${signature.r.toString(16)}`, 32);
112
+ const s = (0, import_math.toBytes)(`0x${signature.s.toString(16)}`, 32);
113
+ s[0] |= (signature.recovery || 0) << 7;
114
+ return (0, import_utils.hexlify)((0, import_utils.concat)([r, s]));
115
+ }
116
+ /**
117
+ * Add point on the current elliptic curve
118
+ *
119
+ * @param point - Point to add on the curve
120
+ * @returns compressed point on the curve
121
+ */
122
+ addPoint(point) {
123
+ const p0 = import_secp256k1.secp256k1.ProjectivePoint.fromHex((0, import_utils.arrayify)(this.compressedPublicKey));
124
+ const p1 = import_secp256k1.secp256k1.ProjectivePoint.fromHex((0, import_utils.arrayify)(point));
125
+ const result = p0.add(p1);
126
+ return `0x${result.toHex(true)}`;
127
+ }
128
+ /**
129
+ * Recover the public key from a signature performed with [`sign`](#sign).
130
+ *
131
+ * @param data - Data
132
+ * @param signature - hashed signature
133
+ * @returns public key from signature from the
134
+ */
135
+ static recoverPublicKey(data, signature) {
136
+ const signedMessageBytes = (0, import_utils.arrayify)(signature);
137
+ const r = signedMessageBytes.slice(0, 32);
138
+ const s = signedMessageBytes.slice(32, 64);
139
+ const recoveryParam = (s[0] & 128) >> 7;
140
+ s[0] &= 127;
141
+ const sig = new import_secp256k1.secp256k1.Signature(BigInt((0, import_utils.hexlify)(r)), BigInt((0, import_utils.hexlify)(s))).addRecoveryBit(
142
+ recoveryParam
143
+ );
144
+ const publicKey = sig.recoverPublicKey((0, import_utils.arrayify)(data)).toRawBytes(false).slice(1);
145
+ return (0, import_utils.hexlify)(publicKey);
146
+ }
147
+ /**
148
+ * Recover the address from a signature performed with [`sign`](#sign).
149
+ *
150
+ * @param data - Data
151
+ * @param signature - Signature
152
+ * @returns Address from signature
153
+ */
154
+ static recoverAddress(data, signature) {
155
+ return import_address.Address.fromPublicKey(Signer.recoverPublicKey(data, signature));
156
+ }
157
+ /**
158
+ * Generate a random privateKey
159
+ *
160
+ * @param entropy - Adds extra entropy to generate the privateKey
161
+ * @returns random 32-byte hashed
162
+ */
163
+ static generatePrivateKey(entropy) {
164
+ return entropy ? (0, import_hasher.hash)((0, import_utils.concat)([(0, import_crypto.randomBytes)(32), (0, import_utils.arrayify)(entropy)])) : (0, import_crypto.randomBytes)(32);
165
+ }
166
+ /**
167
+ * Extended publicKey from a compact publicKey
168
+ *
169
+ * @param publicKey - Compact publicKey
170
+ * @returns extended publicKey
171
+ */
172
+ static extendPublicKey(publicKey) {
173
+ const point = import_secp256k1.secp256k1.ProjectivePoint.fromHex((0, import_utils.arrayify)(publicKey));
174
+ return (0, import_utils.hexlify)(point.toRawBytes(false).slice(1));
175
+ }
176
+ };
177
+
178
+ // src/test-utils/launchNode.ts
179
+ var getFlagValueFromArgs = (args, flag) => {
180
+ const flagIndex = args.indexOf(flag);
181
+ if (flagIndex === -1) {
182
+ return void 0;
183
+ }
184
+ return args[flagIndex + 1];
185
+ };
186
+ var extractRemainingArgs = (args, flagsToRemove) => {
187
+ const newArgs = [...args];
188
+ flagsToRemove.forEach((flag) => {
189
+ const flagIndex = newArgs.indexOf(flag);
190
+ if (flagIndex !== -1) {
191
+ newArgs.splice(flagIndex, 2);
192
+ }
193
+ });
194
+ return newArgs;
195
+ };
196
+ function getFinalStateConfigJSON({ stateConfig, chainConfig }) {
197
+ const defaultCoins = import_utils2.defaultSnapshotConfigs.stateConfig.coins.map((coin) => ({
198
+ ...coin,
199
+ amount: "18446744073709551615"
200
+ }));
201
+ const defaultMessages = import_utils2.defaultSnapshotConfigs.stateConfig.messages.map((message) => ({
202
+ ...message,
203
+ amount: "18446744073709551615"
204
+ }));
205
+ 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);
206
+ 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);
207
+ if (!process.env.GENESIS_SECRET) {
208
+ const pk = Signer.generatePrivateKey();
209
+ const signer = new Signer(pk);
210
+ process.env.GENESIS_SECRET = (0, import_utils2.hexlify)(pk);
211
+ coins.push({
212
+ tx_id: (0, import_utils2.hexlify)((0, import_crypto2.randomBytes)(import_abi_coder.BYTES_32)),
213
+ owner: signer.address.toHexString(),
214
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
215
+ amount: "18446744073709551615",
216
+ asset_id: chainConfig.consensus_parameters.V1.base_asset_id,
217
+ output_index: 0,
218
+ tx_pointer_block_height: 0,
219
+ tx_pointer_tx_idx: 0
220
+ });
221
+ }
222
+ const json = JSON.stringify({
223
+ ...stateConfig,
224
+ coins,
225
+ messages
226
+ });
227
+ const regexMakeNumber = /("amount":)"(\d+)"/gm;
228
+ return json.replace(regexMakeNumber, "$1$2");
229
+ }
230
+ var launchNode = async ({
231
+ ip,
232
+ port,
233
+ args = [],
234
+ fuelCorePath = process.env.FUEL_CORE_PATH || void 0,
235
+ loggingEnabled = true,
236
+ basePath,
237
+ snapshotConfig = import_utils2.defaultSnapshotConfigs
238
+ } = {}) => (
239
+ // eslint-disable-next-line no-async-promise-executor
240
+ new Promise(async (resolve, reject) => {
241
+ const remainingArgs = extractRemainingArgs(args, [
242
+ "--snapshot",
243
+ "--consensus-key",
244
+ "--db-type",
245
+ "--poa-instant",
246
+ "--min-gas-price",
247
+ "--native-executor-version"
248
+ ]);
249
+ const snapshotDir = getFlagValueFromArgs(args, "--snapshot");
250
+ const consensusKey = getFlagValueFromArgs(args, "--consensus-key") || import_utils2.defaultConsensusKey;
251
+ const dbTypeFlagValue = getFlagValueFromArgs(args, "--db-type");
252
+ const useInMemoryDb = dbTypeFlagValue === "in-memory" || dbTypeFlagValue === void 0;
253
+ const poaInstantFlagValue = getFlagValueFromArgs(args, "--poa-instant");
254
+ const poaInstant = poaInstantFlagValue === "true" || poaInstantFlagValue === void 0;
255
+ const nativeExecutorVersion = getFlagValueFromArgs(args, "--native-executor-version") || "0";
256
+ const minGasPrice = getFlagValueFromArgs(args, "--min-gas-price") || "1";
257
+ const graphQLStartSubstring = "Binding GraphQL provider to";
258
+ const command = fuelCorePath || "fuel-core";
259
+ const ipToUse = ip || "0.0.0.0";
260
+ const portToUse = port || (await (0, import_portfinder.getPortPromise)({
261
+ port: 4e3,
262
+ // tries 4000 first, then 4001, then 4002, etc.
263
+ stopPort: 5e3
264
+ // don't try ports above 5000
265
+ })).toString();
266
+ let snapshotDirToUse;
267
+ const prefix = basePath || import_os.default.tmpdir();
268
+ const suffix = basePath ? "" : (0, import_crypto2.randomUUID)();
269
+ const tempDir = import_path.default.join(prefix, ".fuels", suffix, "snapshotDir");
270
+ if (snapshotDir) {
271
+ snapshotDirToUse = snapshotDir;
272
+ } else {
273
+ if (!(0, import_fs.existsSync)(tempDir)) {
274
+ (0, import_fs.mkdirSync)(tempDir, { recursive: true });
275
+ }
276
+ const { metadata } = snapshotConfig;
277
+ const metadataPath = import_path.default.join(tempDir, "metadata.json");
278
+ const chainConfigPath = import_path.default.join(tempDir, metadata.chain_config);
279
+ const stateConfigPath = import_path.default.join(tempDir, metadata.table_encoding.Json.filepath);
280
+ const stateTransitionPath = import_path.default.join(tempDir, "state_transition_bytecode.wasm");
281
+ (0, import_fs.writeFileSync)(chainConfigPath, JSON.stringify(snapshotConfig.chainConfig), "utf8");
282
+ (0, import_fs.writeFileSync)(stateConfigPath, getFinalStateConfigJSON(snapshotConfig), "utf8");
283
+ (0, import_fs.writeFileSync)(metadataPath, JSON.stringify(metadata), "utf8");
284
+ (0, import_fs.writeFileSync)(stateTransitionPath, JSON.stringify(""));
285
+ snapshotDirToUse = tempDir;
286
+ }
287
+ const { spawn } = await import("child_process");
288
+ const child = spawn(
289
+ command,
290
+ [
291
+ "run",
292
+ ["--ip", ipToUse],
293
+ ["--port", portToUse],
294
+ useInMemoryDb ? ["--db-type", "in-memory"] : ["--db-path", tempDir],
295
+ ["--min-gas-price", minGasPrice],
296
+ poaInstant ? ["--poa-instant", "true"] : [],
297
+ ["--native-executor-version", nativeExecutorVersion],
298
+ ["--consensus-key", consensusKey],
299
+ ["--snapshot", snapshotDirToUse],
300
+ "--vm-backtrace",
301
+ "--utxo-validation",
302
+ "--debug",
303
+ ...remainingArgs
304
+ ].flat(),
305
+ { stdio: "pipe", detached: true }
306
+ );
307
+ if (loggingEnabled) {
308
+ child.stderr.on("data", (chunk) => {
309
+ console.log(chunk.toString());
310
+ });
311
+ }
312
+ const removeSideffects = () => {
313
+ child.stderr.removeAllListeners();
314
+ if ((0, import_fs.existsSync)(tempDir)) {
315
+ (0, import_fs.rmSync)(tempDir, { recursive: true });
316
+ }
317
+ };
318
+ child.on("error", removeSideffects);
319
+ child.on("exit", removeSideffects);
320
+ const childState = {
321
+ isDead: false
322
+ };
323
+ const cleanup = () => {
324
+ if (childState.isDead) {
325
+ return;
326
+ }
327
+ childState.isDead = true;
328
+ removeSideffects();
329
+ if (child.pid !== void 0) {
330
+ try {
331
+ process.kill(-child.pid);
332
+ } catch (e) {
333
+ const error = e;
334
+ if (error.code === "ESRCH") {
335
+ console.log(
336
+ `fuel-core node under pid ${child.pid} does not exist. The node might have been killed before cleanup was called. Exiting cleanly.`
337
+ );
338
+ } else {
339
+ throw e;
340
+ }
341
+ }
342
+ } else {
343
+ console.error("No PID available for the child process, unable to kill launched node");
344
+ }
345
+ };
346
+ child.stderr.on("data", (chunk) => {
347
+ const text = typeof chunk === "string" ? chunk : chunk.toString();
348
+ if (text.indexOf(graphQLStartSubstring) !== -1) {
349
+ const rows = text.split("\n");
350
+ const rowWithUrl = rows.find((row) => row.indexOf(graphQLStartSubstring) !== -1);
351
+ const [realIp, realPort] = rowWithUrl.split(" ").at(-1).trim().split(":");
352
+ setTimeout(
353
+ () => (
354
+ // Resolve with the cleanup method.
355
+ resolve({
356
+ cleanup,
357
+ ip: realIp,
358
+ port: realPort,
359
+ url: `http://${realIp}:${realPort}/v1/graphql`,
360
+ snapshotDir: snapshotDirToUse,
361
+ pid: child.pid
362
+ })
363
+ ),
364
+ 500
365
+ );
366
+ }
367
+ if (/error/i.test(text)) {
368
+ console.log(text);
369
+ reject(new import_errors.FuelError(import_errors.FuelError.CODES.NODE_LAUNCH_FAILED, text));
370
+ }
371
+ });
372
+ process.on("exit", cleanup);
373
+ process.on("SIGINT", cleanup);
374
+ process.on("SIGUSR1", cleanup);
375
+ process.on("SIGUSR2", cleanup);
376
+ process.on("beforeExit", cleanup);
377
+ process.on("uncaughtException", cleanup);
378
+ child.on("error", reject);
379
+ })
380
+ );
381
+
382
+ // src/test-utils/setup-test-provider-and-wallets.ts
383
+ var import_utils41 = require("@fuel-ts/utils");
384
+ var import_ramda5 = require("ramda");
385
+
386
+ // src/providers/coin-quantity.ts
387
+ var import_math2 = require("@fuel-ts/math");
388
+ var import_utils3 = require("@fuel-ts/utils");
79
389
  var coinQuantityfy = (coinQuantityLike) => {
80
390
  let assetId;
81
391
  let amount;
@@ -89,11 +399,11 @@ var coinQuantityfy = (coinQuantityLike) => {
89
399
  assetId = coinQuantityLike.assetId;
90
400
  max = coinQuantityLike.max ?? void 0;
91
401
  }
92
- const bnAmount = (0, import_math.bn)(amount);
402
+ const bnAmount = (0, import_math2.bn)(amount);
93
403
  return {
94
- assetId: (0, import_utils.hexlify)(assetId),
95
- amount: bnAmount.lt(1) ? (0, import_math.bn)(1) : bnAmount,
96
- max: max ? (0, import_math.bn)(max) : void 0
404
+ assetId: (0, import_utils3.hexlify)(assetId),
405
+ amount: bnAmount.lt(1) ? (0, import_math2.bn)(1) : bnAmount,
406
+ max: max ? (0, import_math2.bn)(max) : void 0
97
407
  };
98
408
  };
99
409
  var addAmountToCoinQuantities = (params) => {
@@ -109,26 +419,18 @@ var addAmountToCoinQuantities = (params) => {
109
419
  };
110
420
 
111
421
  // src/providers/provider.ts
112
- var import_address3 = require("@fuel-ts/address");
113
- var import_errors14 = require("@fuel-ts/errors");
114
- var import_math17 = require("@fuel-ts/math");
422
+ var import_address4 = require("@fuel-ts/address");
423
+ var import_errors16 = require("@fuel-ts/errors");
424
+ var import_math19 = require("@fuel-ts/math");
115
425
  var import_transactions20 = require("@fuel-ts/transactions");
116
- var import_utils23 = require("@fuel-ts/utils");
426
+ var import_utils26 = require("@fuel-ts/utils");
117
427
  var import_versions = require("@fuel-ts/versions");
118
- var import_utils24 = require("@noble/curves/abstract/utils");
428
+ var import_utils27 = require("@noble/curves/abstract/utils");
119
429
  var import_graphql_request = require("graphql-request");
120
430
  var import_ramda3 = require("ramda");
121
431
 
122
432
  // src/providers/__generated__/operations.ts
123
433
  var import_graphql_tag = __toESM(require("graphql-tag"));
124
- var TransactionStatusSubscriptionFragmentDoc = import_graphql_tag.default`
125
- fragment transactionStatusSubscriptionFragment on TransactionStatus {
126
- type: __typename
127
- ... on SqueezedOutStatus {
128
- reason
129
- }
130
- }
131
- `;
132
434
  var SubmittedStatusFragmentDoc = import_graphql_tag.default`
133
435
  fragment SubmittedStatusFragment on SubmittedStatus {
134
436
  type: __typename
@@ -185,6 +487,47 @@ var SuccessStatusFragmentDoc = import_graphql_tag.default`
185
487
  totalFee
186
488
  }
187
489
  ${ReceiptFragmentDoc}`;
490
+ var MalleableTransactionFieldsFragmentDoc = import_graphql_tag.default`
491
+ fragment malleableTransactionFieldsFragment on Transaction {
492
+ receiptsRoot
493
+ inputs {
494
+ type: __typename
495
+ ... on InputCoin {
496
+ txPointer
497
+ }
498
+ ... on InputContract {
499
+ txPointer
500
+ }
501
+ }
502
+ outputs {
503
+ type: __typename
504
+ ... on CoinOutput {
505
+ to
506
+ amount
507
+ assetId
508
+ }
509
+ ... on ContractOutput {
510
+ inputIndex
511
+ balanceRoot
512
+ stateRoot
513
+ }
514
+ ... on ChangeOutput {
515
+ to
516
+ amount
517
+ assetId
518
+ }
519
+ ... on VariableOutput {
520
+ to
521
+ amount
522
+ assetId
523
+ }
524
+ ... on ContractCreated {
525
+ contract
526
+ stateRoot
527
+ }
528
+ }
529
+ }
530
+ `;
188
531
  var FailureStatusFragmentDoc = import_graphql_tag.default`
189
532
  fragment FailureStatusFragment on FailureStatus {
190
533
  type: __typename
@@ -206,6 +549,32 @@ var SqueezedOutStatusFragmentDoc = import_graphql_tag.default`
206
549
  reason
207
550
  }
208
551
  `;
552
+ var TransactionStatusSubscriptionFragmentDoc = import_graphql_tag.default`
553
+ fragment transactionStatusSubscriptionFragment on TransactionStatus {
554
+ ... on SubmittedStatus {
555
+ ...SubmittedStatusFragment
556
+ }
557
+ ... on SuccessStatus {
558
+ ...SuccessStatusFragment
559
+ transaction {
560
+ ...malleableTransactionFieldsFragment
561
+ }
562
+ }
563
+ ... on FailureStatus {
564
+ ...FailureStatusFragment
565
+ transaction {
566
+ ...malleableTransactionFieldsFragment
567
+ }
568
+ }
569
+ ... on SqueezedOutStatus {
570
+ ...SqueezedOutStatusFragment
571
+ }
572
+ }
573
+ ${SubmittedStatusFragmentDoc}
574
+ ${SuccessStatusFragmentDoc}
575
+ ${MalleableTransactionFieldsFragmentDoc}
576
+ ${FailureStatusFragmentDoc}
577
+ ${SqueezedOutStatusFragmentDoc}`;
209
578
  var TransactionStatusFragmentDoc = import_graphql_tag.default`
210
579
  fragment transactionStatusFragment on TransactionStatus {
211
580
  ... on SubmittedStatus {
@@ -546,6 +915,12 @@ var GasCostsFragmentDoc = import_graphql_tag.default`
546
915
  alocDependentCost {
547
916
  ...DependentCostFragment
548
917
  }
918
+ bldd {
919
+ ...DependentCostFragment
920
+ }
921
+ bsiz {
922
+ ...DependentCostFragment
923
+ }
549
924
  cfe {
550
925
  ...DependentCostFragment
551
926
  }
@@ -564,6 +939,9 @@ var GasCostsFragmentDoc = import_graphql_tag.default`
564
939
  csiz {
565
940
  ...DependentCostFragment
566
941
  }
942
+ ed19DependentCost {
943
+ ...DependentCostFragment
944
+ }
567
945
  k256 {
568
946
  ...DependentCostFragment
569
947
  }
@@ -1092,15 +1470,14 @@ function getSdk(requester) {
1092
1470
  }
1093
1471
 
1094
1472
  // src/providers/fuel-graphql-subscriber.ts
1095
- var import_errors = require("@fuel-ts/errors");
1473
+ var import_errors2 = require("@fuel-ts/errors");
1096
1474
  var import_graphql = require("graphql");
1097
1475
  var _FuelGraphqlSubscriber = class {
1098
- constructor(options) {
1099
- this.options = options;
1476
+ constructor(stream) {
1477
+ this.stream = stream;
1100
1478
  }
1101
- stream;
1102
- async setStream() {
1103
- const { url, query, variables, fetchFn } = this.options;
1479
+ static async create(options) {
1480
+ const { url, query, variables, fetchFn } = options;
1104
1481
  const response = await fetchFn(`${url}-sub`, {
1105
1482
  method: "POST",
1106
1483
  body: JSON.stringify({
@@ -1112,20 +1489,17 @@ var _FuelGraphqlSubscriber = class {
1112
1489
  Accept: "text/event-stream"
1113
1490
  }
1114
1491
  });
1115
- this.stream = response.body.getReader();
1492
+ return new _FuelGraphqlSubscriber(response.body.getReader());
1116
1493
  }
1117
1494
  events = [];
1118
1495
  parsingLeftover = "";
1119
1496
  async next() {
1120
- if (!this.stream) {
1121
- await this.setStream();
1122
- }
1123
1497
  while (true) {
1124
1498
  if (this.events.length > 0) {
1125
1499
  const { data, errors } = this.events.shift();
1126
1500
  if (Array.isArray(errors)) {
1127
- throw new import_errors.FuelError(
1128
- import_errors.FuelError.CODES.INVALID_REQUEST,
1501
+ throw new import_errors2.FuelError(
1502
+ import_errors2.FuelError.CODES.INVALID_REQUEST,
1129
1503
  errors.map((err) => err.message).join("\n\n")
1130
1504
  );
1131
1505
  }
@@ -1146,8 +1520,8 @@ var _FuelGraphqlSubscriber = class {
1146
1520
  try {
1147
1521
  this.events.push(JSON.parse(match.replace(/^data:/, "")));
1148
1522
  } catch (e) {
1149
- throw new import_errors.FuelError(
1150
- import_errors.ErrorCode.STREAM_PARSING_ERROR,
1523
+ throw new import_errors2.FuelError(
1524
+ import_errors2.ErrorCode.STREAM_PARSING_ERROR,
1151
1525
  `Error while parsing stream data response: ${text}`
1152
1526
  );
1153
1527
  }
@@ -1170,95 +1544,98 @@ var _FuelGraphqlSubscriber = class {
1170
1544
  var FuelGraphqlSubscriber = _FuelGraphqlSubscriber;
1171
1545
  __publicField(FuelGraphqlSubscriber, "textDecoder", new TextDecoder());
1172
1546
 
1173
- // src/providers/memory-cache.ts
1174
- var import_errors2 = require("@fuel-ts/errors");
1175
- var import_utils2 = require("@fuel-ts/utils");
1176
- var cache = {};
1177
- var DEFAULT_TTL_IN_MS = 30 * 1e3;
1178
- var MemoryCache = class {
1547
+ // src/providers/resource-cache.ts
1548
+ var import_errors3 = require("@fuel-ts/errors");
1549
+ var import_utils4 = require("@fuel-ts/utils");
1550
+ var cache = /* @__PURE__ */ new Map();
1551
+ var ResourceCache = class {
1179
1552
  ttl;
1180
- constructor(ttlInMs = DEFAULT_TTL_IN_MS) {
1181
- this.ttl = ttlInMs;
1182
- if (typeof ttlInMs !== "number" || this.ttl <= 0) {
1183
- throw new import_errors2.FuelError(
1184
- import_errors2.ErrorCode.INVALID_TTL,
1553
+ constructor(ttl) {
1554
+ this.ttl = ttl;
1555
+ if (typeof ttl !== "number" || this.ttl <= 0) {
1556
+ throw new import_errors3.FuelError(
1557
+ import_errors3.ErrorCode.INVALID_TTL,
1185
1558
  `Invalid TTL: ${this.ttl}. Use a value greater than zero.`
1186
1559
  );
1187
1560
  }
1188
1561
  }
1189
- get(value, isAutoExpiring = true) {
1190
- const key = (0, import_utils2.hexlify)(value);
1191
- if (cache[key]) {
1192
- if (!isAutoExpiring || cache[key].expires > Date.now()) {
1193
- return cache[key].value;
1194
- }
1195
- this.del(value);
1196
- }
1197
- return void 0;
1198
- }
1199
- set(value) {
1200
- const expiresAt = Date.now() + this.ttl;
1201
- const key = (0, import_utils2.hexlify)(value);
1202
- cache[key] = {
1203
- expires: expiresAt,
1204
- value
1562
+ // Add resources to the cache
1563
+ set(transactionId, resources) {
1564
+ const currentTime = Date.now();
1565
+ const existingResources = cache.get(transactionId) || {
1566
+ utxos: /* @__PURE__ */ new Set(),
1567
+ messages: /* @__PURE__ */ new Set(),
1568
+ timestamp: currentTime
1205
1569
  };
1206
- return expiresAt;
1570
+ resources.utxos.forEach((utxo) => existingResources.utxos.add((0, import_utils4.hexlify)(utxo)));
1571
+ resources.messages.forEach((message) => existingResources.messages.add((0, import_utils4.hexlify)(message)));
1572
+ cache.set(transactionId, existingResources);
1207
1573
  }
1208
- getAllData() {
1209
- return Object.keys(cache).reduce((list, key) => {
1210
- const data = this.get(key, false);
1211
- if (data) {
1212
- list.push(data);
1213
- }
1214
- return list;
1215
- }, []);
1574
+ // Remove resources from the cache for a given transaction ID
1575
+ unset(transactionId) {
1576
+ cache.delete(transactionId);
1216
1577
  }
1578
+ // Get all cached resources and remove expired ones
1217
1579
  getActiveData() {
1218
- return Object.keys(cache).reduce((list, key) => {
1219
- const data = this.get(key);
1220
- if (data) {
1221
- list.push(data);
1580
+ const allResources = { utxos: [], messages: [] };
1581
+ const currentTime = Date.now();
1582
+ cache.forEach((resource, transactionId) => {
1583
+ if (currentTime - resource.timestamp < this.ttl) {
1584
+ allResources.utxos.push(...resource.utxos);
1585
+ allResources.messages.push(...resource.messages);
1586
+ } else {
1587
+ cache.delete(transactionId);
1588
+ }
1589
+ });
1590
+ return allResources;
1591
+ }
1592
+ // Check if a UTXO ID or message nonce is already cached and not expired
1593
+ isCached(key) {
1594
+ const currentTime = Date.now();
1595
+ for (const [transactionId, resourceData] of cache.entries()) {
1596
+ if (currentTime - resourceData.timestamp > this.ttl) {
1597
+ cache.delete(transactionId);
1598
+ } else if (resourceData.utxos.has(key) || resourceData.messages.has(key)) {
1599
+ return true;
1222
1600
  }
1223
- return list;
1224
- }, []);
1601
+ }
1602
+ return false;
1225
1603
  }
1226
- del(value) {
1227
- const key = (0, import_utils2.hexlify)(value);
1228
- delete cache[key];
1604
+ clear() {
1605
+ cache.clear();
1229
1606
  }
1230
1607
  };
1231
1608
 
1232
1609
  // src/providers/transaction-request/input.ts
1233
- var import_abi_coder = require("@fuel-ts/abi-coder");
1610
+ var import_abi_coder2 = require("@fuel-ts/abi-coder");
1234
1611
  var import_configs = require("@fuel-ts/address/configs");
1235
- var import_errors3 = require("@fuel-ts/errors");
1236
- var import_math2 = require("@fuel-ts/math");
1612
+ var import_errors4 = require("@fuel-ts/errors");
1613
+ var import_math3 = require("@fuel-ts/math");
1237
1614
  var import_transactions = require("@fuel-ts/transactions");
1238
- var import_utils3 = require("@fuel-ts/utils");
1615
+ var import_utils5 = require("@fuel-ts/utils");
1239
1616
  var inputify = (value) => {
1240
1617
  const { type } = value;
1241
1618
  switch (value.type) {
1242
1619
  case import_transactions.InputType.Coin: {
1243
- const predicate = (0, import_utils3.arrayify)(value.predicate ?? "0x");
1244
- const predicateData = (0, import_utils3.arrayify)(value.predicateData ?? "0x");
1620
+ const predicate = (0, import_utils5.arrayify)(value.predicate ?? "0x");
1621
+ const predicateData = (0, import_utils5.arrayify)(value.predicateData ?? "0x");
1245
1622
  return {
1246
1623
  type: import_transactions.InputType.Coin,
1247
- txID: (0, import_utils3.hexlify)((0, import_utils3.arrayify)(value.id).slice(0, import_abi_coder.BYTES_32)),
1248
- outputIndex: (0, import_math2.toNumber)((0, import_utils3.arrayify)(value.id).slice(import_abi_coder.BYTES_32, import_abi_coder.UTXO_ID_LEN)),
1249
- owner: (0, import_utils3.hexlify)(value.owner),
1250
- amount: (0, import_math2.bn)(value.amount),
1251
- assetId: (0, import_utils3.hexlify)(value.assetId),
1624
+ txID: (0, import_utils5.hexlify)((0, import_utils5.arrayify)(value.id).slice(0, import_abi_coder2.BYTES_32)),
1625
+ outputIndex: (0, import_math3.toNumber)((0, import_utils5.arrayify)(value.id).slice(import_abi_coder2.BYTES_32, import_abi_coder2.UTXO_ID_LEN)),
1626
+ owner: (0, import_utils5.hexlify)(value.owner),
1627
+ amount: (0, import_math3.bn)(value.amount),
1628
+ assetId: (0, import_utils5.hexlify)(value.assetId),
1252
1629
  txPointer: {
1253
- blockHeight: (0, import_math2.toNumber)((0, import_utils3.arrayify)(value.txPointer).slice(0, 8)),
1254
- txIndex: (0, import_math2.toNumber)((0, import_utils3.arrayify)(value.txPointer).slice(8, 16))
1630
+ blockHeight: (0, import_math3.toNumber)((0, import_utils5.arrayify)(value.txPointer).slice(0, 8)),
1631
+ txIndex: (0, import_math3.toNumber)((0, import_utils5.arrayify)(value.txPointer).slice(8, 16))
1255
1632
  },
1256
1633
  witnessIndex: value.witnessIndex,
1257
- predicateGasUsed: (0, import_math2.bn)(value.predicateGasUsed),
1258
- predicateLength: (0, import_math2.bn)(predicate.length),
1259
- predicateDataLength: (0, import_math2.bn)(predicateData.length),
1260
- predicate: (0, import_utils3.hexlify)(predicate),
1261
- predicateData: (0, import_utils3.hexlify)(predicateData)
1634
+ predicateGasUsed: (0, import_math3.bn)(value.predicateGasUsed),
1635
+ predicateLength: (0, import_math3.bn)(predicate.length),
1636
+ predicateDataLength: (0, import_math3.bn)(predicateData.length),
1637
+ predicate: (0, import_utils5.hexlify)(predicate),
1638
+ predicateData: (0, import_utils5.hexlify)(predicateData)
1262
1639
  };
1263
1640
  }
1264
1641
  case import_transactions.InputType.Contract: {
@@ -1269,35 +1646,35 @@ var inputify = (value) => {
1269
1646
  balanceRoot: import_configs.ZeroBytes32,
1270
1647
  stateRoot: import_configs.ZeroBytes32,
1271
1648
  txPointer: {
1272
- blockHeight: (0, import_math2.toNumber)((0, import_utils3.arrayify)(value.txPointer).slice(0, 8)),
1273
- txIndex: (0, import_math2.toNumber)((0, import_utils3.arrayify)(value.txPointer).slice(8, 16))
1649
+ blockHeight: (0, import_math3.toNumber)((0, import_utils5.arrayify)(value.txPointer).slice(0, 8)),
1650
+ txIndex: (0, import_math3.toNumber)((0, import_utils5.arrayify)(value.txPointer).slice(8, 16))
1274
1651
  },
1275
- contractID: (0, import_utils3.hexlify)(value.contractId)
1652
+ contractID: (0, import_utils5.hexlify)(value.contractId)
1276
1653
  };
1277
1654
  }
1278
1655
  case import_transactions.InputType.Message: {
1279
- const predicate = (0, import_utils3.arrayify)(value.predicate ?? "0x");
1280
- const predicateData = (0, import_utils3.arrayify)(value.predicateData ?? "0x");
1281
- const data = (0, import_utils3.arrayify)(value.data ?? "0x");
1656
+ const predicate = (0, import_utils5.arrayify)(value.predicate ?? "0x");
1657
+ const predicateData = (0, import_utils5.arrayify)(value.predicateData ?? "0x");
1658
+ const data = (0, import_utils5.arrayify)(value.data ?? "0x");
1282
1659
  return {
1283
1660
  type: import_transactions.InputType.Message,
1284
- sender: (0, import_utils3.hexlify)(value.sender),
1285
- recipient: (0, import_utils3.hexlify)(value.recipient),
1286
- amount: (0, import_math2.bn)(value.amount),
1287
- nonce: (0, import_utils3.hexlify)(value.nonce),
1661
+ sender: (0, import_utils5.hexlify)(value.sender),
1662
+ recipient: (0, import_utils5.hexlify)(value.recipient),
1663
+ amount: (0, import_math3.bn)(value.amount),
1664
+ nonce: (0, import_utils5.hexlify)(value.nonce),
1288
1665
  witnessIndex: value.witnessIndex,
1289
- predicateGasUsed: (0, import_math2.bn)(value.predicateGasUsed),
1290
- predicateLength: (0, import_math2.bn)(predicate.length),
1291
- predicateDataLength: (0, import_math2.bn)(predicateData.length),
1292
- predicate: (0, import_utils3.hexlify)(predicate),
1293
- predicateData: (0, import_utils3.hexlify)(predicateData),
1294
- data: (0, import_utils3.hexlify)(data),
1666
+ predicateGasUsed: (0, import_math3.bn)(value.predicateGasUsed),
1667
+ predicateLength: (0, import_math3.bn)(predicate.length),
1668
+ predicateDataLength: (0, import_math3.bn)(predicateData.length),
1669
+ predicate: (0, import_utils5.hexlify)(predicate),
1670
+ predicateData: (0, import_utils5.hexlify)(predicateData),
1671
+ data: (0, import_utils5.hexlify)(data),
1295
1672
  dataLength: data.length
1296
1673
  };
1297
1674
  }
1298
1675
  default: {
1299
- throw new import_errors3.FuelError(
1300
- import_errors3.ErrorCode.INVALID_TRANSACTION_INPUT,
1676
+ throw new import_errors4.FuelError(
1677
+ import_errors4.ErrorCode.INVALID_TRANSACTION_INPUT,
1301
1678
  `Invalid transaction input type: ${type}.`
1302
1679
  );
1303
1680
  }
@@ -1306,19 +1683,19 @@ var inputify = (value) => {
1306
1683
 
1307
1684
  // src/providers/transaction-request/output.ts
1308
1685
  var import_configs2 = require("@fuel-ts/address/configs");
1309
- var import_errors4 = require("@fuel-ts/errors");
1310
- var import_math3 = require("@fuel-ts/math");
1686
+ var import_errors5 = require("@fuel-ts/errors");
1687
+ var import_math4 = require("@fuel-ts/math");
1311
1688
  var import_transactions2 = require("@fuel-ts/transactions");
1312
- var import_utils4 = require("@fuel-ts/utils");
1689
+ var import_utils6 = require("@fuel-ts/utils");
1313
1690
  var outputify = (value) => {
1314
1691
  const { type } = value;
1315
1692
  switch (type) {
1316
1693
  case import_transactions2.OutputType.Coin: {
1317
1694
  return {
1318
1695
  type: import_transactions2.OutputType.Coin,
1319
- to: (0, import_utils4.hexlify)(value.to),
1320
- amount: (0, import_math3.bn)(value.amount),
1321
- assetId: (0, import_utils4.hexlify)(value.assetId)
1696
+ to: (0, import_utils6.hexlify)(value.to),
1697
+ amount: (0, import_math4.bn)(value.amount),
1698
+ assetId: (0, import_utils6.hexlify)(value.assetId)
1322
1699
  };
1323
1700
  }
1324
1701
  case import_transactions2.OutputType.Contract: {
@@ -1332,29 +1709,29 @@ var outputify = (value) => {
1332
1709
  case import_transactions2.OutputType.Change: {
1333
1710
  return {
1334
1711
  type: import_transactions2.OutputType.Change,
1335
- to: (0, import_utils4.hexlify)(value.to),
1336
- amount: (0, import_math3.bn)(0),
1337
- assetId: (0, import_utils4.hexlify)(value.assetId)
1712
+ to: (0, import_utils6.hexlify)(value.to),
1713
+ amount: (0, import_math4.bn)(0),
1714
+ assetId: (0, import_utils6.hexlify)(value.assetId)
1338
1715
  };
1339
1716
  }
1340
1717
  case import_transactions2.OutputType.Variable: {
1341
1718
  return {
1342
1719
  type: import_transactions2.OutputType.Variable,
1343
1720
  to: import_configs2.ZeroBytes32,
1344
- amount: (0, import_math3.bn)(0),
1721
+ amount: (0, import_math4.bn)(0),
1345
1722
  assetId: import_configs2.ZeroBytes32
1346
1723
  };
1347
1724
  }
1348
1725
  case import_transactions2.OutputType.ContractCreated: {
1349
1726
  return {
1350
1727
  type: import_transactions2.OutputType.ContractCreated,
1351
- contractId: (0, import_utils4.hexlify)(value.contractId),
1352
- stateRoot: (0, import_utils4.hexlify)(value.stateRoot)
1728
+ contractId: (0, import_utils6.hexlify)(value.contractId),
1729
+ stateRoot: (0, import_utils6.hexlify)(value.stateRoot)
1353
1730
  };
1354
1731
  }
1355
1732
  default: {
1356
- throw new import_errors4.FuelError(
1357
- import_errors4.ErrorCode.INVALID_TRANSACTION_INPUT,
1733
+ throw new import_errors5.FuelError(
1734
+ import_errors5.ErrorCode.INVALID_TRANSACTION_INPUT,
1358
1735
  `Invalid transaction output type: ${type}.`
1359
1736
  );
1360
1737
  }
@@ -1362,24 +1739,25 @@ var outputify = (value) => {
1362
1739
  };
1363
1740
 
1364
1741
  // src/providers/transaction-request/transaction-request.ts
1365
- var import_abi_coder2 = require("@fuel-ts/abi-coder");
1366
- var import_address = require("@fuel-ts/address");
1742
+ var import_abi_coder3 = require("@fuel-ts/abi-coder");
1743
+ var import_address2 = require("@fuel-ts/address");
1367
1744
  var import_configs6 = require("@fuel-ts/address/configs");
1368
- var import_crypto = require("@fuel-ts/crypto");
1369
- var import_math8 = require("@fuel-ts/math");
1745
+ var import_crypto3 = require("@fuel-ts/crypto");
1746
+ var import_errors9 = require("@fuel-ts/errors");
1747
+ var import_math9 = require("@fuel-ts/math");
1370
1748
  var import_transactions7 = require("@fuel-ts/transactions");
1371
- var import_utils9 = require("@fuel-ts/utils");
1749
+ var import_utils11 = require("@fuel-ts/utils");
1372
1750
 
1373
1751
  // src/providers/resource.ts
1374
1752
  var isCoin = (resource) => "id" in resource;
1375
1753
 
1376
1754
  // src/providers/utils/receipts.ts
1377
1755
  var import_configs3 = require("@fuel-ts/address/configs");
1378
- var import_errors5 = require("@fuel-ts/errors");
1379
- var import_math4 = require("@fuel-ts/math");
1756
+ var import_errors6 = require("@fuel-ts/errors");
1757
+ var import_math5 = require("@fuel-ts/math");
1380
1758
  var import_transactions3 = require("@fuel-ts/transactions");
1381
1759
  var import_configs4 = require("@fuel-ts/transactions/configs");
1382
- var import_utils5 = require("@fuel-ts/utils");
1760
+ var import_utils7 = require("@fuel-ts/utils");
1383
1761
  var doesReceiptHaveMissingOutputVariables = (receipt) => receipt.type === import_transactions3.ReceiptType.Revert && receipt.val.toString("hex") === import_configs4.FAILED_TRANSFER_TO_ADDRESS_SIGNAL;
1384
1762
  var doesReceiptHaveMissingContractId = (receipt) => receipt.type === import_transactions3.ReceiptType.Panic && receipt.contractId !== "0x0000000000000000000000000000000000000000000000000000000000000000";
1385
1763
  var getReceiptsWithMissingData = (receipts) => receipts.reduce(
@@ -1406,13 +1784,13 @@ function assembleReceiptByType(receipt) {
1406
1784
  type: import_transactions3.ReceiptType.Call,
1407
1785
  from: hexOrZero(receipt.id || receipt.contractId),
1408
1786
  to: hexOrZero(receipt?.to),
1409
- amount: (0, import_math4.bn)(receipt.amount),
1787
+ amount: (0, import_math5.bn)(receipt.amount),
1410
1788
  assetId: hexOrZero(receipt.assetId),
1411
- gas: (0, import_math4.bn)(receipt.gas),
1412
- param1: (0, import_math4.bn)(receipt.param1),
1413
- param2: (0, import_math4.bn)(receipt.param2),
1414
- pc: (0, import_math4.bn)(receipt.pc),
1415
- is: (0, import_math4.bn)(receipt.is)
1789
+ gas: (0, import_math5.bn)(receipt.gas),
1790
+ param1: (0, import_math5.bn)(receipt.param1),
1791
+ param2: (0, import_math5.bn)(receipt.param2),
1792
+ pc: (0, import_math5.bn)(receipt.pc),
1793
+ is: (0, import_math5.bn)(receipt.is)
1416
1794
  };
1417
1795
  return callReceipt;
1418
1796
  }
@@ -1420,9 +1798,9 @@ function assembleReceiptByType(receipt) {
1420
1798
  const returnReceipt = {
1421
1799
  type: import_transactions3.ReceiptType.Return,
1422
1800
  id: hexOrZero(receipt.id || receipt.contractId),
1423
- val: (0, import_math4.bn)(receipt.val),
1424
- pc: (0, import_math4.bn)(receipt.pc),
1425
- is: (0, import_math4.bn)(receipt.is)
1801
+ val: (0, import_math5.bn)(receipt.val),
1802
+ pc: (0, import_math5.bn)(receipt.pc),
1803
+ is: (0, import_math5.bn)(receipt.is)
1426
1804
  };
1427
1805
  return returnReceipt;
1428
1806
  }
@@ -1430,11 +1808,11 @@ function assembleReceiptByType(receipt) {
1430
1808
  const returnDataReceipt = {
1431
1809
  type: import_transactions3.ReceiptType.ReturnData,
1432
1810
  id: hexOrZero(receipt.id || receipt.contractId),
1433
- ptr: (0, import_math4.bn)(receipt.ptr),
1434
- len: (0, import_math4.bn)(receipt.len),
1811
+ ptr: (0, import_math5.bn)(receipt.ptr),
1812
+ len: (0, import_math5.bn)(receipt.len),
1435
1813
  digest: hexOrZero(receipt.digest),
1436
- pc: (0, import_math4.bn)(receipt.pc),
1437
- is: (0, import_math4.bn)(receipt.is)
1814
+ pc: (0, import_math5.bn)(receipt.pc),
1815
+ is: (0, import_math5.bn)(receipt.is)
1438
1816
  };
1439
1817
  return returnDataReceipt;
1440
1818
  }
@@ -1442,9 +1820,9 @@ function assembleReceiptByType(receipt) {
1442
1820
  const panicReceipt = {
1443
1821
  type: import_transactions3.ReceiptType.Panic,
1444
1822
  id: hexOrZero(receipt.id),
1445
- reason: (0, import_math4.bn)(receipt.reason),
1446
- pc: (0, import_math4.bn)(receipt.pc),
1447
- is: (0, import_math4.bn)(receipt.is),
1823
+ reason: (0, import_math5.bn)(receipt.reason),
1824
+ pc: (0, import_math5.bn)(receipt.pc),
1825
+ is: (0, import_math5.bn)(receipt.is),
1448
1826
  contractId: hexOrZero(receipt.contractId)
1449
1827
  };
1450
1828
  return panicReceipt;
@@ -1453,9 +1831,9 @@ function assembleReceiptByType(receipt) {
1453
1831
  const revertReceipt = {
1454
1832
  type: import_transactions3.ReceiptType.Revert,
1455
1833
  id: hexOrZero(receipt.id || receipt.contractId),
1456
- val: (0, import_math4.bn)(receipt.ra),
1457
- pc: (0, import_math4.bn)(receipt.pc),
1458
- is: (0, import_math4.bn)(receipt.is)
1834
+ val: (0, import_math5.bn)(receipt.ra),
1835
+ pc: (0, import_math5.bn)(receipt.pc),
1836
+ is: (0, import_math5.bn)(receipt.is)
1459
1837
  };
1460
1838
  return revertReceipt;
1461
1839
  }
@@ -1463,12 +1841,12 @@ function assembleReceiptByType(receipt) {
1463
1841
  const logReceipt = {
1464
1842
  type: import_transactions3.ReceiptType.Log,
1465
1843
  id: hexOrZero(receipt.id || receipt.contractId),
1466
- val0: (0, import_math4.bn)(receipt.ra),
1467
- val1: (0, import_math4.bn)(receipt.rb),
1468
- val2: (0, import_math4.bn)(receipt.rc),
1469
- val3: (0, import_math4.bn)(receipt.rd),
1470
- pc: (0, import_math4.bn)(receipt.pc),
1471
- is: (0, import_math4.bn)(receipt.is)
1844
+ val0: (0, import_math5.bn)(receipt.ra),
1845
+ val1: (0, import_math5.bn)(receipt.rb),
1846
+ val2: (0, import_math5.bn)(receipt.rc),
1847
+ val3: (0, import_math5.bn)(receipt.rd),
1848
+ pc: (0, import_math5.bn)(receipt.pc),
1849
+ is: (0, import_math5.bn)(receipt.is)
1472
1850
  };
1473
1851
  return logReceipt;
1474
1852
  }
@@ -1476,13 +1854,13 @@ function assembleReceiptByType(receipt) {
1476
1854
  const logDataReceipt = {
1477
1855
  type: import_transactions3.ReceiptType.LogData,
1478
1856
  id: hexOrZero(receipt.id || receipt.contractId),
1479
- val0: (0, import_math4.bn)(receipt.ra),
1480
- val1: (0, import_math4.bn)(receipt.rb),
1481
- ptr: (0, import_math4.bn)(receipt.ptr),
1482
- len: (0, import_math4.bn)(receipt.len),
1857
+ val0: (0, import_math5.bn)(receipt.ra),
1858
+ val1: (0, import_math5.bn)(receipt.rb),
1859
+ ptr: (0, import_math5.bn)(receipt.ptr),
1860
+ len: (0, import_math5.bn)(receipt.len),
1483
1861
  digest: hexOrZero(receipt.digest),
1484
- pc: (0, import_math4.bn)(receipt.pc),
1485
- is: (0, import_math4.bn)(receipt.is)
1862
+ pc: (0, import_math5.bn)(receipt.pc),
1863
+ is: (0, import_math5.bn)(receipt.is)
1486
1864
  };
1487
1865
  return logDataReceipt;
1488
1866
  }
@@ -1491,10 +1869,10 @@ function assembleReceiptByType(receipt) {
1491
1869
  type: import_transactions3.ReceiptType.Transfer,
1492
1870
  from: hexOrZero(receipt.id || receipt.contractId),
1493
1871
  to: hexOrZero(receipt.toAddress || receipt?.to),
1494
- amount: (0, import_math4.bn)(receipt.amount),
1872
+ amount: (0, import_math5.bn)(receipt.amount),
1495
1873
  assetId: hexOrZero(receipt.assetId),
1496
- pc: (0, import_math4.bn)(receipt.pc),
1497
- is: (0, import_math4.bn)(receipt.is)
1874
+ pc: (0, import_math5.bn)(receipt.pc),
1875
+ is: (0, import_math5.bn)(receipt.is)
1498
1876
  };
1499
1877
  return transferReceipt;
1500
1878
  }
@@ -1503,18 +1881,18 @@ function assembleReceiptByType(receipt) {
1503
1881
  type: import_transactions3.ReceiptType.TransferOut,
1504
1882
  from: hexOrZero(receipt.id || receipt.contractId),
1505
1883
  to: hexOrZero(receipt.toAddress || receipt.to),
1506
- amount: (0, import_math4.bn)(receipt.amount),
1884
+ amount: (0, import_math5.bn)(receipt.amount),
1507
1885
  assetId: hexOrZero(receipt.assetId),
1508
- pc: (0, import_math4.bn)(receipt.pc),
1509
- is: (0, import_math4.bn)(receipt.is)
1886
+ pc: (0, import_math5.bn)(receipt.pc),
1887
+ is: (0, import_math5.bn)(receipt.is)
1510
1888
  };
1511
1889
  return transferOutReceipt;
1512
1890
  }
1513
1891
  case "SCRIPT_RESULT" /* ScriptResult */: {
1514
1892
  const scriptResultReceipt = {
1515
1893
  type: import_transactions3.ReceiptType.ScriptResult,
1516
- result: (0, import_math4.bn)(receipt.result),
1517
- gasUsed: (0, import_math4.bn)(receipt.gasUsed)
1894
+ result: (0, import_math5.bn)(receipt.result),
1895
+ gasUsed: (0, import_math5.bn)(receipt.gasUsed)
1518
1896
  };
1519
1897
  return scriptResultReceipt;
1520
1898
  }
@@ -1522,8 +1900,8 @@ function assembleReceiptByType(receipt) {
1522
1900
  const sender = hexOrZero(receipt.sender);
1523
1901
  const recipient = hexOrZero(receipt.recipient);
1524
1902
  const nonce = hexOrZero(receipt.nonce);
1525
- const amount = (0, import_math4.bn)(receipt.amount);
1526
- const data = receipt.data ? (0, import_utils5.arrayify)(receipt.data) : Uint8Array.from([]);
1903
+ const amount = (0, import_math5.bn)(receipt.amount);
1904
+ const data = receipt.data ? (0, import_utils7.arrayify)(receipt.data) : Uint8Array.from([]);
1527
1905
  const digest = hexOrZero(receipt.digest);
1528
1906
  const messageId = import_transactions3.ReceiptMessageOutCoder.getMessageId({
1529
1907
  sender,
@@ -1553,9 +1931,9 @@ function assembleReceiptByType(receipt) {
1553
1931
  subId,
1554
1932
  contractId,
1555
1933
  assetId,
1556
- val: (0, import_math4.bn)(receipt.val),
1557
- pc: (0, import_math4.bn)(receipt.pc),
1558
- is: (0, import_math4.bn)(receipt.is)
1934
+ val: (0, import_math5.bn)(receipt.val),
1935
+ pc: (0, import_math5.bn)(receipt.pc),
1936
+ is: (0, import_math5.bn)(receipt.is)
1559
1937
  };
1560
1938
  return mintReceipt;
1561
1939
  }
@@ -1568,38 +1946,38 @@ function assembleReceiptByType(receipt) {
1568
1946
  subId,
1569
1947
  contractId,
1570
1948
  assetId,
1571
- val: (0, import_math4.bn)(receipt.val),
1572
- pc: (0, import_math4.bn)(receipt.pc),
1573
- is: (0, import_math4.bn)(receipt.is)
1949
+ val: (0, import_math5.bn)(receipt.val),
1950
+ pc: (0, import_math5.bn)(receipt.pc),
1951
+ is: (0, import_math5.bn)(receipt.is)
1574
1952
  };
1575
1953
  return burnReceipt;
1576
1954
  }
1577
1955
  default:
1578
- throw new import_errors5.FuelError(import_errors5.ErrorCode.INVALID_RECEIPT_TYPE, `Invalid receipt type: ${receiptType}.`);
1956
+ throw new import_errors6.FuelError(import_errors6.ErrorCode.INVALID_RECEIPT_TYPE, `Invalid receipt type: ${receiptType}.`);
1579
1957
  }
1580
1958
  }
1581
1959
 
1582
1960
  // src/providers/utils/block-explorer.ts
1583
- var import_errors6 = require("@fuel-ts/errors");
1961
+ var import_errors7 = require("@fuel-ts/errors");
1584
1962
 
1585
1963
  // src/providers/utils/gas.ts
1586
- var import_math5 = require("@fuel-ts/math");
1964
+ var import_math6 = require("@fuel-ts/math");
1587
1965
  var import_transactions4 = require("@fuel-ts/transactions");
1588
- var import_utils6 = require("@fuel-ts/utils");
1966
+ var import_utils8 = require("@fuel-ts/utils");
1589
1967
  var getGasUsedFromReceipts = (receipts) => {
1590
1968
  const scriptResult = receipts.filter(
1591
1969
  (receipt) => receipt.type === import_transactions4.ReceiptType.ScriptResult
1592
1970
  );
1593
- const gasUsed = scriptResult.reduce((prev, receipt) => prev.add(receipt.gasUsed), (0, import_math5.bn)(0));
1971
+ const gasUsed = scriptResult.reduce((prev, receipt) => prev.add(receipt.gasUsed), (0, import_math6.bn)(0));
1594
1972
  return gasUsed;
1595
1973
  };
1596
1974
  function resolveGasDependentCosts(byteSize, gasDependentCost) {
1597
- const base = (0, import_math5.bn)(gasDependentCost.base);
1598
- let dependentValue = (0, import_math5.bn)(0);
1975
+ const base = (0, import_math6.bn)(gasDependentCost.base);
1976
+ let dependentValue = (0, import_math6.bn)(0);
1599
1977
  if ("unitsPerGas" in gasDependentCost) {
1600
- dependentValue = (0, import_math5.bn)(byteSize).div((0, import_math5.bn)(gasDependentCost.unitsPerGas));
1978
+ dependentValue = (0, import_math6.bn)(byteSize).div((0, import_math6.bn)(gasDependentCost.unitsPerGas));
1601
1979
  } else {
1602
- dependentValue = (0, import_math5.bn)(byteSize).mul((0, import_math5.bn)(gasDependentCost.gasPerUnit));
1980
+ dependentValue = (0, import_math6.bn)(byteSize).mul((0, import_math6.bn)(gasDependentCost.gasPerUnit));
1603
1981
  }
1604
1982
  return base.add(dependentValue);
1605
1983
  }
@@ -1622,17 +2000,17 @@ function gasUsedByInputs(inputs, txBytesSize, gasCosts) {
1622
2000
  const totalGas = chargeableInputs.reduce((total, input) => {
1623
2001
  if ("predicate" in input && input.predicate && input.predicate !== "0x") {
1624
2002
  return total.add(
1625
- vmInitializationCost.add(resolveGasDependentCosts((0, import_utils6.arrayify)(input.predicate).length, gasCosts.contractRoot)).add((0, import_math5.bn)(input.predicateGasUsed))
2003
+ vmInitializationCost.add(resolveGasDependentCosts((0, import_utils8.arrayify)(input.predicate).length, gasCosts.contractRoot)).add((0, import_math6.bn)(input.predicateGasUsed))
1626
2004
  );
1627
2005
  }
1628
2006
  return total.add(gasCosts.ecr1);
1629
- }, (0, import_math5.bn)(0));
2007
+ }, (0, import_math6.bn)(0));
1630
2008
  return totalGas;
1631
2009
  }
1632
2010
  function getMinGas(params) {
1633
2011
  const { gasCosts, gasPerByte, inputs, metadataGas, txBytesSize } = params;
1634
2012
  const vmInitGas = resolveGasDependentCosts(txBytesSize, gasCosts.vmInitialization);
1635
- const bytesGas = (0, import_math5.bn)(txBytesSize).mul(gasPerByte);
2013
+ const bytesGas = (0, import_math6.bn)(txBytesSize).mul(gasPerByte);
1636
2014
  const inputsGas = gasUsedByInputs(inputs, txBytesSize, gasCosts);
1637
2015
  const minGas = vmInitGas.add(bytesGas).add(inputsGas).add(metadataGas).maxU64();
1638
2016
  return minGas;
@@ -1643,12 +2021,12 @@ function getMaxGas(params) {
1643
2021
  witnessesLength,
1644
2022
  witnessLimit,
1645
2023
  minGas,
1646
- gasLimit = (0, import_math5.bn)(0),
2024
+ gasLimit = (0, import_math6.bn)(0),
1647
2025
  maxGasPerTx
1648
2026
  } = params;
1649
- let remainingAllowedWitnessGas = (0, import_math5.bn)(0);
2027
+ let remainingAllowedWitnessGas = (0, import_math6.bn)(0);
1650
2028
  if (witnessLimit?.gt(0) && witnessLimit.gte(witnessesLength)) {
1651
- remainingAllowedWitnessGas = (0, import_math5.bn)(witnessLimit).sub(witnessesLength).mul(gasPerByte);
2029
+ remainingAllowedWitnessGas = (0, import_math6.bn)(witnessLimit).sub(witnessesLength).mul(gasPerByte);
1652
2030
  }
1653
2031
  const maxGas = remainingAllowedWitnessGas.add(minGas).add(gasLimit);
1654
2032
  return maxGas.gte(maxGasPerTx) ? maxGasPerTx : maxGas;
@@ -1662,7 +2040,7 @@ function calculateMetadataGasForTxCreate({
1662
2040
  const contractRootGas = resolveGasDependentCosts(contractBytesSize, gasCosts.contractRoot);
1663
2041
  const stateRootGas = resolveGasDependentCosts(stateRootSize, gasCosts.stateRoot);
1664
2042
  const txIdGas = resolveGasDependentCosts(txBytesSize, gasCosts.s256);
1665
- const contractIdInputSize = (0, import_math5.bn)(4 + 32 + 32 + 32);
2043
+ const contractIdInputSize = (0, import_math6.bn)(4 + 32 + 32 + 32);
1666
2044
  const contractIdGas = resolveGasDependentCosts(contractIdInputSize, gasCosts.s256);
1667
2045
  const metadataGas = contractRootGas.add(stateRootGas).add(txIdGas).add(contractIdGas);
1668
2046
  return metadataGas.maxU64();
@@ -1673,19 +2051,28 @@ function calculateMetadataGasForTxScript({
1673
2051
  }) {
1674
2052
  return resolveGasDependentCosts(txBytesSize, gasCosts.s256);
1675
2053
  }
2054
+ function calculateMetadataGasForTxBlob({
2055
+ gasCosts,
2056
+ txBytesSize,
2057
+ witnessBytesSize
2058
+ }) {
2059
+ const txId = resolveGasDependentCosts(txBytesSize, gasCosts.s256);
2060
+ const blobLen = resolveGasDependentCosts(witnessBytesSize, gasCosts.s256);
2061
+ return txId.add(blobLen);
2062
+ }
1676
2063
  var calculateGasFee = (params) => {
1677
2064
  const { gas, gasPrice, priceFactor, tip } = params;
1678
- return gas.mul(gasPrice).div(priceFactor).add((0, import_math5.bn)(tip));
2065
+ return gas.mul(gasPrice).div(priceFactor).add((0, import_math6.bn)(tip));
1679
2066
  };
1680
2067
 
1681
2068
  // src/providers/utils/json.ts
1682
- var import_utils7 = require("@fuel-ts/utils");
2069
+ var import_utils9 = require("@fuel-ts/utils");
1683
2070
  var import_ramda = require("ramda");
1684
2071
  function normalize(object) {
1685
2072
  Object.keys(object).forEach((key) => {
1686
2073
  switch (object[key]?.constructor.name) {
1687
2074
  case "Uint8Array":
1688
- object[key] = (0, import_utils7.hexlify)(object[key]);
2075
+ object[key] = (0, import_utils9.hexlify)(object[key]);
1689
2076
  break;
1690
2077
  case "Array":
1691
2078
  object[key] = normalize(object[key]);
@@ -1710,8 +2097,8 @@ function normalizeJSON(root) {
1710
2097
  }
1711
2098
 
1712
2099
  // src/providers/utils/extract-tx-error.ts
1713
- var import_errors7 = require("@fuel-ts/errors");
1714
- var import_math6 = require("@fuel-ts/math");
2100
+ var import_errors8 = require("@fuel-ts/errors");
2101
+ var import_math7 = require("@fuel-ts/math");
1715
2102
  var import_transactions5 = require("@fuel-ts/transactions");
1716
2103
  var import_configs5 = require("@fuel-ts/transactions/configs");
1717
2104
  var assemblePanicError = (statusReason, metadata) => {
@@ -1723,7 +2110,7 @@ You can read more about this error at:
1723
2110
 
1724
2111
  ${import_configs5.PANIC_DOC_URL}#variant.${statusReason}`;
1725
2112
  }
1726
- return new import_errors7.FuelError(import_errors7.ErrorCode.SCRIPT_REVERTED, errorMessage, {
2113
+ return new import_errors8.FuelError(import_errors8.ErrorCode.SCRIPT_REVERTED, errorMessage, {
1727
2114
  ...metadata,
1728
2115
  reason: statusReason
1729
2116
  });
@@ -1734,7 +2121,7 @@ var assembleRevertError = (receipts, logs, metadata) => {
1734
2121
  const revertReceipt = receipts.find(({ type }) => type === import_transactions5.ReceiptType.Revert);
1735
2122
  let reason = "";
1736
2123
  if (revertReceipt) {
1737
- const reasonHex = (0, import_math6.bn)(revertReceipt.val).toHex();
2124
+ const reasonHex = (0, import_math7.bn)(revertReceipt.val).toHex();
1738
2125
  switch (reasonHex) {
1739
2126
  case import_configs5.FAILED_REQUIRE_SIGNAL: {
1740
2127
  reason = "require";
@@ -1762,8 +2149,8 @@ var assembleRevertError = (receipts, logs, metadata) => {
1762
2149
  errorMessage = `The transaction reverted because it's missing an "OutputChange".`;
1763
2150
  break;
1764
2151
  default:
1765
- throw new import_errors7.FuelError(
1766
- import_errors7.ErrorCode.UNKNOWN,
2152
+ throw new import_errors8.FuelError(
2153
+ import_errors8.ErrorCode.UNKNOWN,
1767
2154
  `The transaction reverted with an unknown reason: ${revertReceipt.val}`,
1768
2155
  {
1769
2156
  ...metadata,
@@ -1772,7 +2159,7 @@ var assembleRevertError = (receipts, logs, metadata) => {
1772
2159
  );
1773
2160
  }
1774
2161
  }
1775
- return new import_errors7.FuelError(import_errors7.ErrorCode.SCRIPT_REVERTED, errorMessage, {
2162
+ return new import_errors8.FuelError(import_errors8.ErrorCode.SCRIPT_REVERTED, errorMessage, {
1776
2163
  ...metadata,
1777
2164
  reason
1778
2165
  });
@@ -1805,7 +2192,7 @@ var NoWitnessAtIndexError = class extends Error {
1805
2192
  };
1806
2193
 
1807
2194
  // src/providers/transaction-request/helpers.ts
1808
- var import_math7 = require("@fuel-ts/math");
2195
+ var import_math8 = require("@fuel-ts/math");
1809
2196
  var import_transactions6 = require("@fuel-ts/transactions");
1810
2197
  var isRequestInputCoin = (input) => input.type === import_transactions6.InputType.Coin;
1811
2198
  var isRequestInputMessage = (input) => input.type === import_transactions6.InputType.Message;
@@ -1820,7 +2207,7 @@ var getAssetAmountInRequestInputs = (inputs, assetId, baseAsset) => inputs.filte
1820
2207
  return acc.add(input.amount);
1821
2208
  }
1822
2209
  return acc;
1823
- }, (0, import_math7.bn)(0));
2210
+ }, (0, import_math8.bn)(0));
1824
2211
  var cacheRequestInputsResourcesFromOwner = (inputs, owner) => inputs.reduce(
1825
2212
  (acc, input) => {
1826
2213
  if (isRequestInputCoin(input) && input.owner === owner.toB256()) {
@@ -1837,11 +2224,11 @@ var cacheRequestInputsResourcesFromOwner = (inputs, owner) => inputs.reduce(
1837
2224
  );
1838
2225
 
1839
2226
  // src/providers/transaction-request/witness.ts
1840
- var import_utils8 = require("@fuel-ts/utils");
2227
+ var import_utils10 = require("@fuel-ts/utils");
1841
2228
  var witnessify = (value) => {
1842
- const data = (0, import_utils8.arrayify)(value);
2229
+ const data = (0, import_utils10.arrayify)(value);
1843
2230
  return {
1844
- data: (0, import_utils8.hexlify)(data),
2231
+ data: (0, import_utils10.hexlify)(data),
1845
2232
  dataLength: data.length
1846
2233
  };
1847
2234
  };
@@ -1876,10 +2263,10 @@ var BaseTransactionRequest = class {
1876
2263
  outputs,
1877
2264
  witnesses
1878
2265
  } = {}) {
1879
- this.tip = tip ? (0, import_math8.bn)(tip) : void 0;
2266
+ this.tip = tip ? (0, import_math9.bn)(tip) : void 0;
1880
2267
  this.maturity = maturity && maturity > 0 ? maturity : void 0;
1881
- this.witnessLimit = (0, import_utils9.isDefined)(witnessLimit) ? (0, import_math8.bn)(witnessLimit) : void 0;
1882
- this.maxFee = (0, import_math8.bn)(maxFee);
2268
+ this.witnessLimit = (0, import_utils11.isDefined)(witnessLimit) ? (0, import_math9.bn)(witnessLimit) : void 0;
2269
+ this.maxFee = (0, import_math9.bn)(maxFee);
1883
2270
  this.inputs = inputs ?? [];
1884
2271
  this.outputs = outputs ?? [];
1885
2272
  this.witnesses = witnesses ?? [];
@@ -1888,13 +2275,13 @@ var BaseTransactionRequest = class {
1888
2275
  let policyTypes = 0;
1889
2276
  const policies = [];
1890
2277
  const { tip, witnessLimit, maturity } = req;
1891
- if ((0, import_math8.bn)(tip).gt(0)) {
2278
+ if ((0, import_math9.bn)(tip).gt(0)) {
1892
2279
  policyTypes += import_transactions7.PolicyType.Tip;
1893
- policies.push({ data: (0, import_math8.bn)(tip), type: import_transactions7.PolicyType.Tip });
2280
+ policies.push({ data: (0, import_math9.bn)(tip), type: import_transactions7.PolicyType.Tip });
1894
2281
  }
1895
- if ((0, import_utils9.isDefined)(witnessLimit) && (0, import_math8.bn)(witnessLimit).gte(0)) {
2282
+ if ((0, import_utils11.isDefined)(witnessLimit) && (0, import_math9.bn)(witnessLimit).gte(0)) {
1896
2283
  policyTypes += import_transactions7.PolicyType.WitnessLimit;
1897
- policies.push({ data: (0, import_math8.bn)(witnessLimit), type: import_transactions7.PolicyType.WitnessLimit });
2284
+ policies.push({ data: (0, import_math9.bn)(witnessLimit), type: import_transactions7.PolicyType.WitnessLimit });
1898
2285
  }
1899
2286
  if (maturity && maturity > 0) {
1900
2287
  policyTypes += import_transactions7.PolicyType.Maturity;
@@ -1974,7 +2361,7 @@ var BaseTransactionRequest = class {
1974
2361
  * @returns The index of the created witness.
1975
2362
  */
1976
2363
  addEmptyWitness() {
1977
- this.addWitness((0, import_utils9.concat)([import_configs6.ZeroBytes32, import_configs6.ZeroBytes32]));
2364
+ this.addWitness((0, import_utils11.concat)([import_configs6.ZeroBytes32, import_configs6.ZeroBytes32]));
1978
2365
  return this.witnesses.length - 1;
1979
2366
  }
1980
2367
  /**
@@ -1984,7 +2371,7 @@ var BaseTransactionRequest = class {
1984
2371
  * @param signature - The signature to update the witness with.
1985
2372
  */
1986
2373
  updateWitnessByOwner(address, signature) {
1987
- const ownerAddress = import_address.Address.fromAddressOrString(address);
2374
+ const ownerAddress = import_address2.Address.fromAddressOrString(address);
1988
2375
  const witnessIndex = this.getCoinInputWitnessIndexByOwner(ownerAddress);
1989
2376
  if (typeof witnessIndex === "number") {
1990
2377
  this.updateWitness(witnessIndex, signature);
@@ -2054,13 +2441,13 @@ var BaseTransactionRequest = class {
2054
2441
  * Returns the witnessIndex of the found CoinInput.
2055
2442
  */
2056
2443
  getCoinInputWitnessIndexByOwner(owner) {
2057
- const ownerAddress = (0, import_address.addressify)(owner);
2444
+ const ownerAddress = (0, import_address2.addressify)(owner);
2058
2445
  const found = this.inputs.find((input) => {
2059
2446
  switch (input.type) {
2060
2447
  case import_transactions7.InputType.Coin:
2061
- return (0, import_utils9.hexlify)(input.owner) === ownerAddress.toB256();
2448
+ return (0, import_utils11.hexlify)(input.owner) === ownerAddress.toB256();
2062
2449
  case import_transactions7.InputType.Message:
2063
- return (0, import_utils9.hexlify)(input.recipient) === ownerAddress.toB256();
2450
+ return (0, import_utils11.hexlify)(input.recipient) === ownerAddress.toB256();
2064
2451
  default:
2065
2452
  return false;
2066
2453
  }
@@ -2164,7 +2551,7 @@ var BaseTransactionRequest = class {
2164
2551
  addCoinOutput(to, amount, assetId) {
2165
2552
  this.pushOutput({
2166
2553
  type: import_transactions7.OutputType.Coin,
2167
- to: (0, import_address.addressify)(to).toB256(),
2554
+ to: (0, import_address2.addressify)(to).toB256(),
2168
2555
  amount,
2169
2556
  assetId
2170
2557
  });
@@ -2180,7 +2567,7 @@ var BaseTransactionRequest = class {
2180
2567
  quantities.map(coinQuantityfy).forEach((quantity) => {
2181
2568
  this.pushOutput({
2182
2569
  type: import_transactions7.OutputType.Coin,
2183
- to: (0, import_address.addressify)(to).toB256(),
2570
+ to: (0, import_address2.addressify)(to).toB256(),
2184
2571
  amount: quantity.amount,
2185
2572
  assetId: quantity.assetId
2186
2573
  });
@@ -2195,12 +2582,12 @@ var BaseTransactionRequest = class {
2195
2582
  */
2196
2583
  addChangeOutput(to, assetId) {
2197
2584
  const changeOutput = this.getChangeOutputs().find(
2198
- (output) => (0, import_utils9.hexlify)(output.assetId) === assetId
2585
+ (output) => (0, import_utils11.hexlify)(output.assetId) === assetId
2199
2586
  );
2200
2587
  if (!changeOutput) {
2201
2588
  this.pushOutput({
2202
2589
  type: import_transactions7.OutputType.Change,
2203
- to: (0, import_address.addressify)(to).toB256(),
2590
+ to: (0, import_address2.addressify)(to).toB256(),
2204
2591
  assetId
2205
2592
  });
2206
2593
  }
@@ -2215,7 +2602,7 @@ var BaseTransactionRequest = class {
2215
2602
  * @hidden
2216
2603
  */
2217
2604
  metadataGas(_gasCosts) {
2218
- throw new Error("Not implemented");
2605
+ throw new import_errors9.FuelError(import_errors9.FuelError.CODES.NOT_IMPLEMENTED, "Not implemented");
2219
2606
  }
2220
2607
  /**
2221
2608
  * @hidden
@@ -2270,26 +2657,27 @@ var BaseTransactionRequest = class {
2270
2657
  const assetInput = findAssetInput(assetId);
2271
2658
  let usedQuantity = quantity;
2272
2659
  if (assetId === baseAssetId) {
2273
- usedQuantity = (0, import_math8.bn)("1000000000000000000");
2660
+ usedQuantity = (0, import_math9.bn)("1000000000000000000");
2274
2661
  }
2275
2662
  if (assetInput && "assetId" in assetInput) {
2276
- assetInput.id = (0, import_utils9.hexlify)((0, import_crypto.randomBytes)(import_abi_coder2.UTXO_ID_LEN));
2663
+ assetInput.id = (0, import_utils11.hexlify)((0, import_crypto3.randomBytes)(import_abi_coder3.UTXO_ID_LEN));
2277
2664
  assetInput.amount = usedQuantity;
2278
2665
  } else {
2279
2666
  this.addResources([
2280
2667
  {
2281
- id: (0, import_utils9.hexlify)((0, import_crypto.randomBytes)(import_abi_coder2.UTXO_ID_LEN)),
2668
+ id: (0, import_utils11.hexlify)((0, import_crypto3.randomBytes)(import_abi_coder3.UTXO_ID_LEN)),
2282
2669
  amount: usedQuantity,
2283
2670
  assetId,
2284
- owner: resourcesOwner || import_address.Address.fromRandom(),
2285
- blockCreated: (0, import_math8.bn)(1),
2286
- txCreatedIdx: (0, import_math8.bn)(1)
2671
+ owner: resourcesOwner || import_address2.Address.fromRandom(),
2672
+ blockCreated: (0, import_math9.bn)(1),
2673
+ txCreatedIdx: (0, import_math9.bn)(1)
2287
2674
  }
2288
2675
  ]);
2289
2676
  }
2290
2677
  };
2291
- updateAssetInput(baseAssetId, (0, import_math8.bn)(1e11));
2678
+ updateAssetInput(baseAssetId, (0, import_math9.bn)(1e11));
2292
2679
  quantities.forEach((q) => updateAssetInput(q.assetId, q.amount));
2680
+ return this;
2293
2681
  }
2294
2682
  /**
2295
2683
  * Retrieves an array of CoinQuantity for each coin output present in the transaction.
@@ -2299,7 +2687,7 @@ var BaseTransactionRequest = class {
2299
2687
  */
2300
2688
  getCoinOutputsQuantities() {
2301
2689
  const coinsQuantities = this.getCoinOutputs().map(({ amount, assetId }) => ({
2302
- amount: (0, import_math8.bn)(amount),
2690
+ amount: (0, import_math9.bn)(amount),
2303
2691
  assetId: assetId.toString()
2304
2692
  }));
2305
2693
  return coinsQuantities;
@@ -2329,27 +2717,24 @@ var BaseTransactionRequest = class {
2329
2717
  this.inputs.filter(isRequestInputResource).forEach((i) => {
2330
2718
  const owner = getRequestInputResourceOwner(i);
2331
2719
  const correspondingInput = inputsToExtractGasUsed.find(
2332
- (x) => isRequestInputResourceFromOwner(x, import_address.Address.fromString(String(owner)))
2720
+ (x) => isRequestInputResourceFromOwner(x, import_address2.Address.fromString(String(owner)))
2333
2721
  );
2334
- if (correspondingInput && "predicateGasUsed" in correspondingInput && (0, import_math8.bn)(correspondingInput.predicateGasUsed).gt(0)) {
2722
+ if (correspondingInput && "predicateGasUsed" in correspondingInput && (0, import_math9.bn)(correspondingInput.predicateGasUsed).gt(0)) {
2335
2723
  i.predicateGasUsed = correspondingInput.predicateGasUsed;
2336
2724
  }
2337
2725
  });
2338
2726
  }
2727
+ byteLength() {
2728
+ return this.toTransactionBytes().byteLength;
2729
+ }
2339
2730
  };
2340
2731
 
2341
- // src/providers/transaction-request/create-transaction-request.ts
2342
- var import_configs8 = require("@fuel-ts/address/configs");
2343
- var import_math10 = require("@fuel-ts/math");
2344
- var import_transactions9 = require("@fuel-ts/transactions");
2345
- var import_utils13 = require("@fuel-ts/utils");
2346
-
2347
2732
  // src/providers/transaction-request/hash-transaction.ts
2348
2733
  var import_configs7 = require("@fuel-ts/address/configs");
2349
- var import_hasher = require("@fuel-ts/hasher");
2350
- var import_math9 = require("@fuel-ts/math");
2734
+ var import_hasher2 = require("@fuel-ts/hasher");
2735
+ var import_math10 = require("@fuel-ts/math");
2351
2736
  var import_transactions8 = require("@fuel-ts/transactions");
2352
- var import_utils11 = require("@fuel-ts/utils");
2737
+ var import_utils13 = require("@fuel-ts/utils");
2353
2738
  var import_ramda2 = require("ramda");
2354
2739
  function hashTransaction(transactionRequest, chainId) {
2355
2740
  const transaction = transactionRequest.toTransaction();
@@ -2364,11 +2749,11 @@ function hashTransaction(transactionRequest, chainId) {
2364
2749
  blockHeight: 0,
2365
2750
  txIndex: 0
2366
2751
  };
2367
- inputClone.predicateGasUsed = (0, import_math9.bn)(0);
2752
+ inputClone.predicateGasUsed = (0, import_math10.bn)(0);
2368
2753
  return inputClone;
2369
2754
  }
2370
2755
  case import_transactions8.InputType.Message: {
2371
- inputClone.predicateGasUsed = (0, import_math9.bn)(0);
2756
+ inputClone.predicateGasUsed = (0, import_math10.bn)(0);
2372
2757
  return inputClone;
2373
2758
  }
2374
2759
  case import_transactions8.InputType.Contract: {
@@ -2395,12 +2780,12 @@ function hashTransaction(transactionRequest, chainId) {
2395
2780
  return outputClone;
2396
2781
  }
2397
2782
  case import_transactions8.OutputType.Change: {
2398
- outputClone.amount = (0, import_math9.bn)(0);
2783
+ outputClone.amount = (0, import_math10.bn)(0);
2399
2784
  return outputClone;
2400
2785
  }
2401
2786
  case import_transactions8.OutputType.Variable: {
2402
2787
  outputClone.to = import_configs7.ZeroBytes32;
2403
- outputClone.amount = (0, import_math9.bn)(0);
2788
+ outputClone.amount = (0, import_math10.bn)(0);
2404
2789
  outputClone.assetId = import_configs7.ZeroBytes32;
2405
2790
  return outputClone;
2406
2791
  }
@@ -2410,16 +2795,86 @@ function hashTransaction(transactionRequest, chainId) {
2410
2795
  });
2411
2796
  transaction.witnessesCount = 0;
2412
2797
  transaction.witnesses = [];
2413
- const chainIdBytes = (0, import_hasher.uint64ToBytesBE)(chainId);
2414
- const concatenatedData = (0, import_utils11.concat)([chainIdBytes, new import_transactions8.TransactionCoder().encode(transaction)]);
2415
- return (0, import_hasher.sha256)(concatenatedData);
2798
+ const chainIdBytes = (0, import_hasher2.uint64ToBytesBE)(chainId);
2799
+ const concatenatedData = (0, import_utils13.concat)([chainIdBytes, new import_transactions8.TransactionCoder().encode(transaction)]);
2800
+ return (0, import_hasher2.sha256)(concatenatedData);
2416
2801
  }
2417
2802
 
2803
+ // src/providers/transaction-request/blob-transaction-request.ts
2804
+ var BlobTransactionRequest = class extends BaseTransactionRequest {
2805
+ static from(obj) {
2806
+ if (obj instanceof this) {
2807
+ return obj;
2808
+ }
2809
+ return new this(obj);
2810
+ }
2811
+ /** Type of the transaction */
2812
+ type = import_transactions7.TransactionType.Blob;
2813
+ /** Blob ID */
2814
+ blobId;
2815
+ /** Witness index of contract bytecode to create */
2816
+ witnessIndex;
2817
+ /**
2818
+ * Creates an instance `BlobTransactionRequest`.
2819
+ *
2820
+ * @param blobTransactionRequestLike - The initial values for the instance
2821
+ */
2822
+ constructor({ witnessIndex, blobId, ...rest }) {
2823
+ super(rest);
2824
+ this.blobId = blobId;
2825
+ this.witnessIndex = witnessIndex ?? 0;
2826
+ }
2827
+ /**
2828
+ * Converts the transaction request to a `TransactionBlob`.
2829
+ *
2830
+ * @returns The transaction create object.
2831
+ */
2832
+ toTransaction() {
2833
+ const baseTransaction = this.getBaseTransaction();
2834
+ const { witnessIndex, blobId } = this;
2835
+ return {
2836
+ type: import_transactions7.TransactionType.Blob,
2837
+ ...baseTransaction,
2838
+ blobId,
2839
+ witnessIndex
2840
+ };
2841
+ }
2842
+ /**
2843
+ * Gets the Transaction Request by hashing the transaction.
2844
+ *
2845
+ * @param chainId - The chain ID.
2846
+ *
2847
+ * @returns - A hash of the transaction, which is the transaction ID.
2848
+ */
2849
+ getTransactionId(chainId) {
2850
+ return hashTransaction(this, chainId);
2851
+ }
2852
+ /**
2853
+ * Calculates the metadata gas cost for a blob transaction.
2854
+ *
2855
+ * @param gasCosts - gas costs passed from the chain.
2856
+ * @returns metadata gas cost for the blob transaction.
2857
+ */
2858
+ metadataGas(gasCosts) {
2859
+ return calculateMetadataGasForTxBlob({
2860
+ gasCosts,
2861
+ txBytesSize: this.byteSize(),
2862
+ witnessBytesSize: this.witnesses[this.witnessIndex].length
2863
+ });
2864
+ }
2865
+ };
2866
+
2867
+ // src/providers/transaction-request/create-transaction-request.ts
2868
+ var import_configs8 = require("@fuel-ts/address/configs");
2869
+ var import_math11 = require("@fuel-ts/math");
2870
+ var import_transactions9 = require("@fuel-ts/transactions");
2871
+ var import_utils16 = require("@fuel-ts/utils");
2872
+
2418
2873
  // src/providers/transaction-request/storage-slot.ts
2419
- var import_utils12 = require("@fuel-ts/utils");
2874
+ var import_utils15 = require("@fuel-ts/utils");
2420
2875
  var getStorageValue = (value) => {
2421
2876
  const v = new Uint8Array(32);
2422
- v.set((0, import_utils12.arrayify)(value));
2877
+ v.set((0, import_utils15.arrayify)(value));
2423
2878
  return v;
2424
2879
  };
2425
2880
  var storageSlotify = (storageSlot) => {
@@ -2433,8 +2888,8 @@ var storageSlotify = (storageSlot) => {
2433
2888
  value = storageSlot.value;
2434
2889
  }
2435
2890
  return {
2436
- key: (0, import_utils12.hexlify)(key),
2437
- value: (0, import_utils12.hexlify)(getStorageValue(value))
2891
+ key: (0, import_utils15.hexlify)(key),
2892
+ value: (0, import_utils15.hexlify)(getStorageValue(value))
2438
2893
  };
2439
2894
  };
2440
2895
 
@@ -2462,7 +2917,7 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
2462
2917
  constructor({ bytecodeWitnessIndex, salt, storageSlots, ...rest }) {
2463
2918
  super(rest);
2464
2919
  this.bytecodeWitnessIndex = bytecodeWitnessIndex ?? 0;
2465
- this.salt = (0, import_utils13.hexlify)(salt ?? import_configs8.ZeroBytes32);
2920
+ this.salt = (0, import_utils16.hexlify)(salt ?? import_configs8.ZeroBytes32);
2466
2921
  this.storageSlots = [...storageSlots ?? []];
2467
2922
  }
2468
2923
  /**
@@ -2478,8 +2933,8 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
2478
2933
  type: import_transactions9.TransactionType.Create,
2479
2934
  ...baseTransaction,
2480
2935
  bytecodeWitnessIndex,
2481
- storageSlotsCount: (0, import_math10.bn)(storageSlots.length),
2482
- salt: this.salt ? (0, import_utils13.hexlify)(this.salt) : import_configs8.ZeroBytes32,
2936
+ storageSlotsCount: (0, import_math11.bn)(storageSlots.length),
2937
+ salt: this.salt ? (0, import_utils16.hexlify)(this.salt) : import_configs8.ZeroBytes32,
2483
2938
  storageSlots
2484
2939
  };
2485
2940
  }
@@ -2518,7 +2973,7 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
2518
2973
  }
2519
2974
  metadataGas(gasCosts) {
2520
2975
  return calculateMetadataGasForTxCreate({
2521
- contractBytesSize: (0, import_math10.bn)((0, import_utils13.arrayify)(this.witnesses[this.bytecodeWitnessIndex] || "0x").length),
2976
+ contractBytesSize: (0, import_math11.bn)((0, import_utils16.arrayify)(this.witnesses[this.bytecodeWitnessIndex] || "0x").length),
2522
2977
  gasCosts,
2523
2978
  stateRootSize: this.storageSlots.length,
2524
2979
  txBytesSize: this.byteSize()
@@ -2527,22 +2982,22 @@ var CreateTransactionRequest = class extends BaseTransactionRequest {
2527
2982
  };
2528
2983
 
2529
2984
  // src/providers/transaction-request/script-transaction-request.ts
2530
- var import_abi_coder3 = require("@fuel-ts/abi-coder");
2531
- var import_address2 = require("@fuel-ts/address");
2985
+ var import_abi_coder4 = require("@fuel-ts/abi-coder");
2986
+ var import_address3 = require("@fuel-ts/address");
2532
2987
  var import_configs9 = require("@fuel-ts/address/configs");
2533
- var import_math11 = require("@fuel-ts/math");
2988
+ var import_math12 = require("@fuel-ts/math");
2534
2989
  var import_transactions10 = require("@fuel-ts/transactions");
2535
- var import_utils15 = require("@fuel-ts/utils");
2990
+ var import_utils18 = require("@fuel-ts/utils");
2536
2991
 
2537
2992
  // src/providers/transaction-request/scripts.ts
2538
- var import_utils14 = require("@fuel-ts/utils");
2993
+ var import_utils17 = require("@fuel-ts/utils");
2539
2994
  var returnZeroScript = {
2540
2995
  /*
2541
2996
  Opcode::RET(REG_ZERO)
2542
2997
  Opcode::NOOP
2543
2998
  */
2544
2999
  // TODO: Don't use hardcoded scripts: https://github.com/FuelLabs/fuels-ts/issues/281
2545
- bytes: (0, import_utils14.arrayify)("0x24000000"),
3000
+ bytes: (0, import_utils17.arrayify)("0x24000000"),
2546
3001
  encodeScriptData: () => new Uint8Array(0)
2547
3002
  };
2548
3003
  var withdrawScript = {
@@ -2556,7 +3011,7 @@ var withdrawScript = {
2556
3011
  00000000 00000000 [amount value]
2557
3012
  */
2558
3013
  // TODO: Don't use hardcoded scripts: https://github.com/FuelLabs/fuels-ts/issues/281
2559
- bytes: (0, import_utils14.arrayify)("0x5040C0105D44C0064C40001124000000"),
3014
+ bytes: (0, import_utils17.arrayify)("0x5040C0105D44C0064C40001124000000"),
2560
3015
  encodeScriptData: () => new Uint8Array(0)
2561
3016
  };
2562
3017
 
@@ -2584,9 +3039,9 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
2584
3039
  */
2585
3040
  constructor({ script, scriptData, gasLimit, ...rest } = {}) {
2586
3041
  super(rest);
2587
- this.gasLimit = (0, import_math11.bn)(gasLimit);
2588
- this.script = (0, import_utils15.arrayify)(script ?? returnZeroScript.bytes);
2589
- this.scriptData = (0, import_utils15.arrayify)(scriptData ?? returnZeroScript.encodeScriptData());
3042
+ this.gasLimit = (0, import_math12.bn)(gasLimit);
3043
+ this.script = (0, import_utils18.arrayify)(script ?? returnZeroScript.bytes);
3044
+ this.scriptData = (0, import_utils18.arrayify)(scriptData ?? returnZeroScript.encodeScriptData());
2590
3045
  this.abis = rest.abis;
2591
3046
  }
2592
3047
  /**
@@ -2595,17 +3050,17 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
2595
3050
  * @returns The transaction script object.
2596
3051
  */
2597
3052
  toTransaction() {
2598
- const script = (0, import_utils15.arrayify)(this.script ?? "0x");
2599
- const scriptData = (0, import_utils15.arrayify)(this.scriptData ?? "0x");
3053
+ const script = (0, import_utils18.arrayify)(this.script ?? "0x");
3054
+ const scriptData = (0, import_utils18.arrayify)(this.scriptData ?? "0x");
2600
3055
  return {
2601
3056
  type: import_transactions10.TransactionType.Script,
2602
3057
  scriptGasLimit: this.gasLimit,
2603
3058
  ...super.getBaseTransaction(),
2604
- scriptLength: (0, import_math11.bn)(script.length),
2605
- scriptDataLength: (0, import_math11.bn)(scriptData.length),
3059
+ scriptLength: (0, import_math12.bn)(script.length),
3060
+ scriptDataLength: (0, import_math12.bn)(scriptData.length),
2606
3061
  receiptsRoot: import_configs9.ZeroBytes32,
2607
- script: (0, import_utils15.hexlify)(script),
2608
- scriptData: (0, import_utils15.hexlify)(scriptData)
3062
+ script: (0, import_utils18.hexlify)(script),
3063
+ scriptData: (0, import_utils18.hexlify)(scriptData)
2609
3064
  };
2610
3065
  }
2611
3066
  /**
@@ -2697,7 +3152,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
2697
3152
  * @returns The current instance of the `ScriptTransactionRequest`.
2698
3153
  */
2699
3154
  addContractInputAndOutput(contract) {
2700
- const contractAddress = (0, import_address2.addressify)(contract);
3155
+ const contractAddress = (0, import_address3.addressify)(contract);
2701
3156
  if (this.getContractInputs().find((i) => i.contractId === contractAddress.toB256())) {
2702
3157
  return this;
2703
3158
  }
@@ -2730,7 +3185,7 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
2730
3185
  * @returns The current instance of the `ScriptTransactionRequest`.
2731
3186
  */
2732
3187
  setData(abi, args) {
2733
- const abiInterface = new import_abi_coder3.Interface(abi);
3188
+ const abiInterface = new import_abi_coder4.Interface(abi);
2734
3189
  this.scriptData = abiInterface.functions.main.encodeArguments(args);
2735
3190
  return this;
2736
3191
  }
@@ -2743,10 +3198,10 @@ var ScriptTransactionRequest = class extends BaseTransactionRequest {
2743
3198
  };
2744
3199
 
2745
3200
  // src/providers/transaction-request/utils.ts
2746
- var import_errors9 = require("@fuel-ts/errors");
3201
+ var import_errors11 = require("@fuel-ts/errors");
2747
3202
  var import_transactions11 = require("@fuel-ts/transactions");
2748
3203
  var transactionRequestify = (obj) => {
2749
- if (obj instanceof ScriptTransactionRequest || obj instanceof CreateTransactionRequest) {
3204
+ if (obj instanceof ScriptTransactionRequest || obj instanceof CreateTransactionRequest || obj instanceof BlobTransactionRequest) {
2750
3205
  return obj;
2751
3206
  }
2752
3207
  const { type } = obj;
@@ -2757,27 +3212,35 @@ var transactionRequestify = (obj) => {
2757
3212
  case import_transactions11.TransactionType.Create: {
2758
3213
  return CreateTransactionRequest.from(obj);
2759
3214
  }
3215
+ case import_transactions11.TransactionType.Blob: {
3216
+ return BlobTransactionRequest.from(obj);
3217
+ }
2760
3218
  default: {
2761
- throw new import_errors9.FuelError(import_errors9.ErrorCode.INVALID_TRANSACTION_TYPE, `Invalid transaction type: ${type}.`);
3219
+ throw new import_errors11.FuelError(
3220
+ import_errors11.ErrorCode.UNSUPPORTED_TRANSACTION_TYPE,
3221
+ `Unsupported transaction type: ${type}.`
3222
+ );
2762
3223
  }
2763
3224
  }
2764
3225
  };
3226
+ var isTransactionTypeScript = (request) => request.type === import_transactions11.TransactionType.Script;
3227
+ var isTransactionTypeCreate = (request) => request.type === import_transactions11.TransactionType.Create;
2765
3228
 
2766
3229
  // src/providers/transaction-response/transaction-response.ts
2767
- var import_errors13 = require("@fuel-ts/errors");
2768
- var import_math16 = require("@fuel-ts/math");
3230
+ var import_errors15 = require("@fuel-ts/errors");
3231
+ var import_math18 = require("@fuel-ts/math");
2769
3232
  var import_transactions19 = require("@fuel-ts/transactions");
2770
- var import_utils20 = require("@fuel-ts/utils");
3233
+ var import_utils23 = require("@fuel-ts/utils");
2771
3234
 
2772
3235
  // src/providers/transaction-summary/assemble-transaction-summary.ts
2773
- var import_math15 = require("@fuel-ts/math");
3236
+ var import_math17 = require("@fuel-ts/math");
2774
3237
  var import_transactions17 = require("@fuel-ts/transactions");
2775
- var import_utils18 = require("@fuel-ts/utils");
3238
+ var import_utils21 = require("@fuel-ts/utils");
2776
3239
 
2777
3240
  // src/providers/transaction-summary/calculate-tx-fee-for-summary.ts
2778
- var import_math12 = require("@fuel-ts/math");
3241
+ var import_math13 = require("@fuel-ts/math");
2779
3242
  var import_transactions12 = require("@fuel-ts/transactions");
2780
- var import_utils16 = require("@fuel-ts/utils");
3243
+ var import_utils19 = require("@fuel-ts/utils");
2781
3244
  var calculateTXFeeForSummary = (params) => {
2782
3245
  const {
2783
3246
  gasPrice,
@@ -2789,19 +3252,19 @@ var calculateTXFeeForSummary = (params) => {
2789
3252
  if (totalFee) {
2790
3253
  return totalFee;
2791
3254
  }
2792
- const gasPerByte = (0, import_math12.bn)(feeParams.gasPerByte);
2793
- const gasPriceFactor = (0, import_math12.bn)(feeParams.gasPriceFactor);
2794
- const transactionBytes = (0, import_utils16.arrayify)(rawPayload);
3255
+ const gasPerByte = (0, import_math13.bn)(feeParams.gasPerByte);
3256
+ const gasPriceFactor = (0, import_math13.bn)(feeParams.gasPriceFactor);
3257
+ const transactionBytes = (0, import_utils19.arrayify)(rawPayload);
2795
3258
  const [transaction] = new import_transactions12.TransactionCoder().decode(transactionBytes, 0);
2796
3259
  const { type, witnesses, inputs, policies } = transaction;
2797
- let metadataGas = (0, import_math12.bn)(0);
2798
- let gasLimit = (0, import_math12.bn)(0);
3260
+ let metadataGas = (0, import_math13.bn)(0);
3261
+ let gasLimit = (0, import_math13.bn)(0);
2799
3262
  if (type !== import_transactions12.TransactionType.Create && type !== import_transactions12.TransactionType.Script) {
2800
- return (0, import_math12.bn)(0);
3263
+ return (0, import_math13.bn)(0);
2801
3264
  }
2802
3265
  if (type === import_transactions12.TransactionType.Create) {
2803
3266
  const { bytecodeWitnessIndex, storageSlots } = transaction;
2804
- const contractBytesSize = (0, import_math12.bn)((0, import_utils16.arrayify)(witnesses[bytecodeWitnessIndex].data).length);
3267
+ const contractBytesSize = (0, import_math13.bn)((0, import_utils19.arrayify)(witnesses[bytecodeWitnessIndex].data).length);
2805
3268
  metadataGas = calculateMetadataGasForTxCreate({
2806
3269
  contractBytesSize,
2807
3270
  gasCosts,
@@ -2820,7 +3283,7 @@ var calculateTXFeeForSummary = (params) => {
2820
3283
  }
2821
3284
  const minGas = getMinGas({
2822
3285
  gasCosts,
2823
- gasPerByte: (0, import_math12.bn)(gasPerByte),
3286
+ gasPerByte: (0, import_math13.bn)(gasPerByte),
2824
3287
  inputs,
2825
3288
  metadataGas,
2826
3289
  txBytesSize: transactionBytes.length
@@ -2846,14 +3309,14 @@ var calculateTXFeeForSummary = (params) => {
2846
3309
 
2847
3310
  // src/providers/transaction-summary/operations.ts
2848
3311
  var import_configs10 = require("@fuel-ts/address/configs");
2849
- var import_errors11 = require("@fuel-ts/errors");
2850
- var import_math13 = require("@fuel-ts/math");
3312
+ var import_errors13 = require("@fuel-ts/errors");
3313
+ var import_math15 = require("@fuel-ts/math");
2851
3314
  var import_transactions15 = require("@fuel-ts/transactions");
2852
3315
 
2853
3316
  // src/providers/transaction-summary/call.ts
2854
- var import_abi_coder4 = require("@fuel-ts/abi-coder");
3317
+ var import_abi_coder5 = require("@fuel-ts/abi-coder");
2855
3318
  var getFunctionCall = ({ abi, receipt }) => {
2856
- const abiInterface = new import_abi_coder4.Interface(abi);
3319
+ const abiInterface = new import_abi_coder5.Interface(abi);
2857
3320
  const callFunctionSelector = receipt.param1.toHex(8);
2858
3321
  const functionFragment = abiInterface.getFunction(callFunctionSelector);
2859
3322
  const inputs = functionFragment.jsonFn.inputs;
@@ -2884,7 +3347,8 @@ var getFunctionCall = ({ abi, receipt }) => {
2884
3347
  };
2885
3348
 
2886
3349
  // src/providers/transaction-summary/input.ts
2887
- var import_errors10 = require("@fuel-ts/errors");
3350
+ var import_errors12 = require("@fuel-ts/errors");
3351
+ var import_math14 = require("@fuel-ts/math");
2888
3352
  var import_transactions13 = require("@fuel-ts/transactions");
2889
3353
  function getInputsByTypes(inputs, types) {
2890
3354
  return inputs.filter((i) => types.includes(i.type));
@@ -2901,17 +3365,47 @@ function getInputsMessage(inputs) {
2901
3365
  function getInputsCoinAndMessage(inputs) {
2902
3366
  return getInputsByTypes(inputs, [import_transactions13.InputType.Coin, import_transactions13.InputType.Message]);
2903
3367
  }
3368
+ function isInputCoin(input) {
3369
+ return input.type === import_transactions13.InputType.Coin;
3370
+ }
2904
3371
  function getInputsContract(inputs) {
2905
3372
  return getInputsByType(inputs, import_transactions13.InputType.Contract);
2906
3373
  }
2907
- function getInputFromAssetId(inputs, assetId) {
3374
+ function findCoinInput(inputs, assetId) {
2908
3375
  const coinInputs = getInputsCoin(inputs);
2909
- const messageInputs = getInputsMessage(inputs);
2910
- const coinInput = coinInputs.find((i) => i.assetId === assetId);
2911
- const messageInput = messageInputs.find(
2912
- (_) => assetId === "0x0000000000000000000000000000000000000000000000000000000000000000"
2913
- );
2914
- return coinInput || messageInput;
3376
+ return coinInputs.find((i) => i.assetId === assetId);
3377
+ }
3378
+ function aggregateInputsAmountsByAssetAndOwner(inputs, baseAssetID) {
3379
+ const aggregated = /* @__PURE__ */ new Map();
3380
+ getInputsCoinAndMessage(inputs).forEach((input) => {
3381
+ const assetId = isInputCoin(input) ? input.assetId : baseAssetID;
3382
+ const owner = isInputCoin(input) ? input.owner : input.recipient;
3383
+ let ownersMap = aggregated.get(assetId);
3384
+ if (!ownersMap) {
3385
+ ownersMap = /* @__PURE__ */ new Map();
3386
+ aggregated.set(assetId, ownersMap);
3387
+ }
3388
+ let ownerBalance = ownersMap.get(owner);
3389
+ if (!ownerBalance) {
3390
+ ownerBalance = new import_math14.BN(0);
3391
+ ownersMap.set(owner, ownerBalance);
3392
+ }
3393
+ ownersMap.set(owner, ownerBalance.add(input.amount));
3394
+ });
3395
+ return aggregated;
3396
+ }
3397
+ function findMessageInput(inputs) {
3398
+ return getInputsMessage(inputs)?.[0];
3399
+ }
3400
+ function getInputFromAssetId(inputs, assetId, isBaseAsset = false) {
3401
+ const coinInput = findCoinInput(inputs, assetId);
3402
+ if (coinInput) {
3403
+ return coinInput;
3404
+ }
3405
+ if (isBaseAsset) {
3406
+ return findMessageInput(inputs);
3407
+ }
3408
+ return void 0;
2915
3409
  }
2916
3410
  function getInputContractFromIndex(inputs, inputIndex) {
2917
3411
  if (inputIndex == null) {
@@ -2922,8 +3416,8 @@ function getInputContractFromIndex(inputs, inputIndex) {
2922
3416
  return void 0;
2923
3417
  }
2924
3418
  if (contractInput.type !== import_transactions13.InputType.Contract) {
2925
- throw new import_errors10.FuelError(
2926
- import_errors10.ErrorCode.INVALID_TRANSACTION_INPUT,
3419
+ throw new import_errors12.FuelError(
3420
+ import_errors12.ErrorCode.INVALID_TRANSACTION_INPUT,
2927
3421
  `Contract input should be of type 'contract'.`
2928
3422
  );
2929
3423
  }
@@ -2969,10 +3463,12 @@ function getTransactionTypeName(transactionType) {
2969
3463
  return "Create" /* Create */;
2970
3464
  case import_transactions15.TransactionType.Script:
2971
3465
  return "Script" /* Script */;
3466
+ case import_transactions15.TransactionType.Blob:
3467
+ return "Blob" /* Blob */;
2972
3468
  default:
2973
- throw new import_errors11.FuelError(
2974
- import_errors11.ErrorCode.INVALID_TRANSACTION_TYPE,
2975
- `Invalid transaction type: ${transactionType}.`
3469
+ throw new import_errors13.FuelError(
3470
+ import_errors13.ErrorCode.UNSUPPORTED_TRANSACTION_TYPE,
3471
+ `Unsupported transaction type: ${transactionType}.`
2976
3472
  );
2977
3473
  }
2978
3474
  }
@@ -2995,47 +3491,60 @@ function isTypeUpgrade(transactionType) {
2995
3491
  function isTypeUpload(transactionType) {
2996
3492
  return isType(transactionType, "Upload" /* Upload */);
2997
3493
  }
3494
+ function isTypeBlob(transactionType) {
3495
+ return isType(transactionType, "Blob" /* Blob */);
3496
+ }
2998
3497
  function getReceiptsCall(receipts) {
2999
3498
  return getReceiptsByType(receipts, import_transactions15.ReceiptType.Call);
3000
3499
  }
3001
3500
  function getReceiptsMessageOut(receipts) {
3002
3501
  return getReceiptsByType(receipts, import_transactions15.ReceiptType.MessageOut);
3003
3502
  }
3004
- var mergeAssets = (op1, op2) => {
3503
+ function mergeAssets(op1, op2) {
3005
3504
  const assets1 = op1.assetsSent || [];
3006
3505
  const assets2 = op2.assetsSent || [];
3007
- const filteredAssets = assets2.filter(
3008
- (asset2) => !assets1.some((asset1) => asset1.assetId === asset2.assetId)
3009
- );
3010
- const mergedAssets = assets1.map((asset1) => {
3011
- const matchingAsset = assets2.find((asset2) => asset2.assetId === asset1.assetId);
3012
- if (!matchingAsset) {
3013
- return asset1;
3506
+ const assetMap = /* @__PURE__ */ new Map();
3507
+ assets1.forEach((asset) => {
3508
+ assetMap.set(asset.assetId, { ...asset });
3509
+ });
3510
+ assets2.forEach((asset) => {
3511
+ const existingAsset = assetMap.get(asset.assetId);
3512
+ if (existingAsset) {
3513
+ existingAsset.amount = (0, import_math15.bn)(existingAsset.amount).add(asset.amount);
3514
+ } else {
3515
+ assetMap.set(asset.assetId, { ...asset });
3014
3516
  }
3015
- const mergedAmount = (0, import_math13.bn)(asset1.amount).add(matchingAsset.amount);
3016
- return { ...asset1, amount: mergedAmount };
3017
3517
  });
3018
- return mergedAssets.concat(filteredAssets);
3019
- };
3518
+ return Array.from(assetMap.values());
3519
+ }
3020
3520
  function isSameOperation(a, b) {
3021
3521
  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;
3022
3522
  }
3523
+ function mergeAssetsSent(existing, toAdd) {
3524
+ if (!toAdd.assetsSent?.length) {
3525
+ return existing.assetsSent;
3526
+ }
3527
+ return existing.assetsSent?.length ? mergeAssets(existing, toAdd) : toAdd.assetsSent;
3528
+ }
3529
+ function mergeCalls(existing, toAdd) {
3530
+ if (!toAdd.calls?.length) {
3531
+ return existing.calls;
3532
+ }
3533
+ return [...existing.calls || [], ...toAdd.calls];
3534
+ }
3535
+ function mergeOperations(existing, toAdd) {
3536
+ return {
3537
+ ...existing,
3538
+ assetsSent: mergeAssetsSent(existing, toAdd),
3539
+ calls: mergeCalls(existing, toAdd)
3540
+ };
3541
+ }
3023
3542
  function addOperation(operations, toAdd) {
3024
- const allOperations = [...operations];
3025
- const index = allOperations.findIndex((op) => isSameOperation(op, toAdd));
3026
- if (allOperations[index]) {
3027
- const existentOperation = { ...allOperations[index] };
3028
- if (toAdd.assetsSent?.length) {
3029
- existentOperation.assetsSent = existentOperation.assetsSent?.length ? mergeAssets(existentOperation, toAdd) : toAdd.assetsSent;
3030
- }
3031
- if (toAdd.calls?.length) {
3032
- existentOperation.calls = [...existentOperation.calls || [], ...toAdd.calls];
3033
- }
3034
- allOperations[index] = existentOperation;
3035
- } else {
3036
- allOperations.push(toAdd);
3543
+ const existingIndex = operations.findIndex((op) => isSameOperation(op, toAdd));
3544
+ if (existingIndex === -1) {
3545
+ return [...operations, toAdd];
3037
3546
  }
3038
- return allOperations;
3547
+ return operations.map((op, index) => index === existingIndex ? mergeOperations(op, toAdd) : op);
3039
3548
  }
3040
3549
  function getWithdrawFromFuelOperations({
3041
3550
  inputs,
@@ -3045,7 +3554,7 @@ function getWithdrawFromFuelOperations({
3045
3554
  const messageOutReceipts = getReceiptsMessageOut(receipts);
3046
3555
  const withdrawFromFuelOperations = messageOutReceipts.reduce(
3047
3556
  (prevWithdrawFromFuelOps, receipt) => {
3048
- const input = getInputFromAssetId(inputs, baseAssetId);
3557
+ const input = getInputFromAssetId(inputs, baseAssetId, true);
3049
3558
  if (input) {
3050
3559
  const inputAddress = getInputAccountAddress(input);
3051
3560
  const newWithdrawFromFuelOps = addOperation(prevWithdrawFromFuelOps, {
@@ -3074,65 +3583,80 @@ function getWithdrawFromFuelOperations({
3074
3583
  );
3075
3584
  return withdrawFromFuelOperations;
3076
3585
  }
3586
+ function getContractCalls(contractInput, abiMap, receipt, rawPayload, maxInputs) {
3587
+ const abi = abiMap?.[contractInput.contractID];
3588
+ if (!abi) {
3589
+ return [];
3590
+ }
3591
+ return [
3592
+ getFunctionCall({
3593
+ abi,
3594
+ receipt,
3595
+ rawPayload,
3596
+ maxInputs
3597
+ })
3598
+ ];
3599
+ }
3600
+ function getAssetsSent(receipt) {
3601
+ return receipt.amount?.isZero() ? void 0 : [
3602
+ {
3603
+ amount: receipt.amount,
3604
+ assetId: receipt.assetId
3605
+ }
3606
+ ];
3607
+ }
3608
+ function processCallReceipt(receipt, contractInput, inputs, abiMap, rawPayload, maxInputs, baseAssetId) {
3609
+ const assetId = receipt.assetId === import_configs10.ZeroBytes32 ? baseAssetId : receipt.assetId;
3610
+ const input = getInputFromAssetId(inputs, assetId, assetId === baseAssetId);
3611
+ if (!input) {
3612
+ return [];
3613
+ }
3614
+ const inputAddress = getInputAccountAddress(input);
3615
+ const calls = getContractCalls(contractInput, abiMap, receipt, rawPayload, maxInputs);
3616
+ return [
3617
+ {
3618
+ name: "Contract call" /* contractCall */,
3619
+ from: {
3620
+ type: 1 /* account */,
3621
+ address: inputAddress
3622
+ },
3623
+ to: {
3624
+ type: 0 /* contract */,
3625
+ address: receipt.to
3626
+ },
3627
+ assetsSent: getAssetsSent(receipt),
3628
+ calls
3629
+ }
3630
+ ];
3631
+ }
3077
3632
  function getContractCallOperations({
3078
3633
  inputs,
3079
3634
  outputs,
3080
3635
  receipts,
3081
3636
  abiMap,
3082
3637
  rawPayload,
3083
- maxInputs
3638
+ maxInputs,
3639
+ baseAssetId
3084
3640
  }) {
3085
3641
  const contractCallReceipts = getReceiptsCall(receipts);
3086
3642
  const contractOutputs = getOutputsContract(outputs);
3087
- const contractCallOperations = contractOutputs.reduce((prevOutputCallOps, output) => {
3643
+ return contractOutputs.flatMap((output) => {
3088
3644
  const contractInput = getInputContractFromIndex(inputs, output.inputIndex);
3089
- if (contractInput) {
3090
- const newCallOps = contractCallReceipts.reduce((prevContractCallOps, receipt) => {
3091
- if (receipt.to === contractInput.contractID) {
3092
- const input = getInputFromAssetId(inputs, receipt.assetId);
3093
- if (input) {
3094
- const inputAddress = getInputAccountAddress(input);
3095
- const calls = [];
3096
- const abi = abiMap?.[contractInput.contractID];
3097
- if (abi) {
3098
- calls.push(
3099
- getFunctionCall({
3100
- abi,
3101
- receipt,
3102
- rawPayload,
3103
- maxInputs
3104
- })
3105
- );
3106
- }
3107
- const newContractCallOps = addOperation(prevContractCallOps, {
3108
- name: "Contract call" /* contractCall */,
3109
- from: {
3110
- type: 1 /* account */,
3111
- address: inputAddress
3112
- },
3113
- to: {
3114
- type: 0 /* contract */,
3115
- address: receipt.to
3116
- },
3117
- // if no amount is forwarded to the contract, skip showing assetsSent
3118
- assetsSent: receipt.amount?.isZero() ? void 0 : [
3119
- {
3120
- amount: receipt.amount,
3121
- assetId: receipt.assetId
3122
- }
3123
- ],
3124
- calls
3125
- });
3126
- return newContractCallOps;
3127
- }
3128
- }
3129
- return prevContractCallOps;
3130
- }, prevOutputCallOps);
3131
- return newCallOps;
3645
+ if (!contractInput) {
3646
+ return [];
3132
3647
  }
3133
- return prevOutputCallOps;
3134
- }, []);
3135
- return contractCallOperations;
3648
+ return contractCallReceipts.filter((receipt) => receipt.to === contractInput.contractID).flatMap(
3649
+ (receipt) => processCallReceipt(
3650
+ receipt,
3651
+ contractInput,
3652
+ inputs,
3653
+ abiMap,
3654
+ rawPayload,
3655
+ maxInputs,
3656
+ baseAssetId
3657
+ )
3658
+ );
3659
+ });
3136
3660
  }
3137
3661
  function extractTransferOperationFromReceipt(receipt, contractInputs, changeOutputs) {
3138
3662
  const { to: toAddress, assetId, amount } = receipt;
@@ -3164,32 +3688,40 @@ function extractTransferOperationFromReceipt(receipt, contractInputs, changeOutp
3164
3688
  function getTransferOperations({
3165
3689
  inputs,
3166
3690
  outputs,
3167
- receipts
3691
+ receipts,
3692
+ baseAssetId
3168
3693
  }) {
3169
3694
  let operations = [];
3170
3695
  const coinOutputs = getOutputsCoin(outputs);
3171
3696
  const contractInputs = getInputsContract(inputs);
3172
3697
  const changeOutputs = getOutputsChange(outputs);
3173
- coinOutputs.forEach((output) => {
3174
- const { amount, assetId, to } = output;
3175
- const changeOutput = changeOutputs.find((change) => change.assetId === assetId);
3176
- if (changeOutput) {
3698
+ const aggregated = aggregateInputsAmountsByAssetAndOwner(inputs, baseAssetId);
3699
+ coinOutputs.forEach(({ amount, assetId, to }) => {
3700
+ const txPayers = aggregated.get(assetId) || /* @__PURE__ */ new Map();
3701
+ let selectedPayer;
3702
+ let fallbackPayer;
3703
+ for (const [address, payedAmount] of txPayers) {
3704
+ if (!fallbackPayer) {
3705
+ fallbackPayer = address;
3706
+ }
3707
+ if (payedAmount.gte(amount)) {
3708
+ selectedPayer = address;
3709
+ break;
3710
+ }
3711
+ }
3712
+ selectedPayer = selectedPayer || fallbackPayer;
3713
+ if (selectedPayer) {
3177
3714
  operations = addOperation(operations, {
3178
3715
  name: "Transfer asset" /* transfer */,
3179
3716
  from: {
3180
3717
  type: 1 /* account */,
3181
- address: changeOutput.to
3718
+ address: selectedPayer
3182
3719
  },
3183
3720
  to: {
3184
3721
  type: 1 /* account */,
3185
3722
  address: to
3186
3723
  },
3187
- assetsSent: [
3188
- {
3189
- assetId,
3190
- amount
3191
- }
3192
- ]
3724
+ assetsSent: [{ assetId, amount }]
3193
3725
  });
3194
3726
  }
3195
3727
  });
@@ -3262,21 +3794,19 @@ function getOperations({
3262
3794
  baseAssetId
3263
3795
  }) {
3264
3796
  if (isTypeCreate(transactionType)) {
3265
- return [
3266
- ...getContractCreatedOperations({ inputs, outputs }),
3267
- ...getTransferOperations({ inputs, outputs, receipts })
3268
- ];
3797
+ return [...getContractCreatedOperations({ inputs, outputs })];
3269
3798
  }
3270
3799
  if (isTypeScript(transactionType)) {
3271
3800
  return [
3272
- ...getTransferOperations({ inputs, outputs, receipts }),
3801
+ ...getTransferOperations({ inputs, outputs, receipts, baseAssetId }),
3273
3802
  ...getContractCallOperations({
3274
3803
  inputs,
3275
3804
  outputs,
3276
3805
  receipts,
3277
3806
  abiMap,
3278
3807
  rawPayload,
3279
- maxInputs
3808
+ maxInputs,
3809
+ baseAssetId
3280
3810
  }),
3281
3811
  ...getWithdrawFromFuelOperations({ inputs, receipts, baseAssetId })
3282
3812
  ];
@@ -3335,8 +3865,8 @@ var extractBurnedAssetsFromReceipts = (receipts) => {
3335
3865
  };
3336
3866
 
3337
3867
  // src/providers/transaction-summary/status.ts
3338
- var import_errors12 = require("@fuel-ts/errors");
3339
- var import_math14 = require("@fuel-ts/math");
3868
+ var import_errors14 = require("@fuel-ts/errors");
3869
+ var import_math16 = require("@fuel-ts/math");
3340
3870
  var getTransactionStatusName = (gqlStatus) => {
3341
3871
  switch (gqlStatus) {
3342
3872
  case "FailureStatus":
@@ -3348,8 +3878,8 @@ var getTransactionStatusName = (gqlStatus) => {
3348
3878
  case "SqueezedOutStatus":
3349
3879
  return "squeezedout" /* squeezedout */;
3350
3880
  default:
3351
- throw new import_errors12.FuelError(
3352
- import_errors12.ErrorCode.INVALID_TRANSACTION_STATUS,
3881
+ throw new import_errors14.FuelError(
3882
+ import_errors14.ErrorCode.INVALID_TRANSACTION_STATUS,
3353
3883
  `Invalid transaction status: ${gqlStatus}.`
3354
3884
  );
3355
3885
  }
@@ -3370,15 +3900,15 @@ var processGraphqlStatus = (gqlTransactionStatus) => {
3370
3900
  time = gqlTransactionStatus.time;
3371
3901
  blockId = gqlTransactionStatus.block.id;
3372
3902
  isStatusSuccess = true;
3373
- totalFee = (0, import_math14.bn)(gqlTransactionStatus.totalFee);
3374
- totalGas = (0, import_math14.bn)(gqlTransactionStatus.totalGas);
3903
+ totalFee = (0, import_math16.bn)(gqlTransactionStatus.totalFee);
3904
+ totalGas = (0, import_math16.bn)(gqlTransactionStatus.totalGas);
3375
3905
  break;
3376
3906
  case "FailureStatus":
3377
3907
  time = gqlTransactionStatus.time;
3378
3908
  blockId = gqlTransactionStatus.block.id;
3379
3909
  isStatusFailure = true;
3380
- totalFee = (0, import_math14.bn)(gqlTransactionStatus.totalFee);
3381
- totalGas = (0, import_math14.bn)(gqlTransactionStatus.totalGas);
3910
+ totalFee = (0, import_math16.bn)(gqlTransactionStatus.totalFee);
3911
+ totalGas = (0, import_math16.bn)(gqlTransactionStatus.totalGas);
3382
3912
  break;
3383
3913
  case "SubmittedStatus":
3384
3914
  time = gqlTransactionStatus.time;
@@ -3418,7 +3948,7 @@ function assembleTransactionSummary(params) {
3418
3948
  baseAssetId
3419
3949
  } = params;
3420
3950
  const gasUsed = getGasUsedFromReceipts(receipts);
3421
- const rawPayload = (0, import_utils18.hexlify)(transactionBytes);
3951
+ const rawPayload = (0, import_utils21.hexlify)(transactionBytes);
3422
3952
  const operations = getOperations({
3423
3953
  transactionType: transaction.type,
3424
3954
  inputs: transaction.inputs || [],
@@ -3430,7 +3960,7 @@ function assembleTransactionSummary(params) {
3430
3960
  baseAssetId
3431
3961
  });
3432
3962
  const typeName = getTransactionTypeName(transaction.type);
3433
- const tip = (0, import_math15.bn)(transaction.policies?.find((policy) => policy.type === import_transactions17.PolicyType.Tip)?.data);
3963
+ const tip = (0, import_math17.bn)(transaction.policies?.find((policy) => policy.type === import_transactions17.PolicyType.Tip)?.data);
3434
3964
  const { isStatusFailure, isStatusPending, isStatusSuccess, blockId, status, time, totalFee } = processGraphqlStatus(gqlTransactionStatus);
3435
3965
  const fee = calculateTXFeeForSummary({
3436
3966
  totalFee,
@@ -3450,7 +3980,7 @@ function assembleTransactionSummary(params) {
3450
3980
  const burnedAssets = extractBurnedAssetsFromReceipts(receipts);
3451
3981
  let date;
3452
3982
  if (time) {
3453
- date = import_utils18.DateTime.fromTai64(time);
3983
+ date = import_utils21.DateTime.fromTai64(time);
3454
3984
  }
3455
3985
  const transactionSummary = {
3456
3986
  id,
@@ -3470,6 +4000,7 @@ function assembleTransactionSummary(params) {
3470
4000
  isTypeScript: isTypeScript(transaction.type),
3471
4001
  isTypeUpgrade: isTypeUpgrade(transaction.type),
3472
4002
  isTypeUpload: isTypeUpload(transaction.type),
4003
+ isTypeBlob: isTypeBlob(transaction.type),
3473
4004
  isStatusFailure,
3474
4005
  isStatusSuccess,
3475
4006
  isStatusPending,
@@ -3480,13 +4011,13 @@ function assembleTransactionSummary(params) {
3480
4011
  }
3481
4012
 
3482
4013
  // src/providers/transaction-response/getDecodedLogs.ts
3483
- var import_abi_coder5 = require("@fuel-ts/abi-coder");
4014
+ var import_abi_coder6 = require("@fuel-ts/abi-coder");
3484
4015
  var import_transactions18 = require("@fuel-ts/transactions");
3485
4016
  function getDecodedLogs(receipts, mainAbi, externalAbis = {}) {
3486
4017
  return receipts.reduce((logs, receipt) => {
3487
4018
  if (receipt.type === import_transactions18.ReceiptType.LogData || receipt.type === import_transactions18.ReceiptType.Log) {
3488
- const interfaceToUse = new import_abi_coder5.Interface(externalAbis[receipt.id] || mainAbi);
3489
- const data = receipt.type === import_transactions18.ReceiptType.Log ? new import_abi_coder5.BigNumberCoder("u64").encode(receipt.val0) : receipt.data;
4019
+ const interfaceToUse = new import_abi_coder6.Interface(externalAbis[receipt.id] || mainAbi);
4020
+ const data = receipt.type === import_transactions18.ReceiptType.Log ? new import_abi_coder6.BigNumberCoder("u64").encode(receipt.val0) : receipt.data;
3490
4021
  const [decodedLog] = interfaceToUse.decodeLog(data, receipt.val1.toString());
3491
4022
  logs.push(decodedLog);
3492
4023
  }
@@ -3495,26 +4026,59 @@ function getDecodedLogs(receipts, mainAbi, externalAbis = {}) {
3495
4026
  }
3496
4027
 
3497
4028
  // src/providers/transaction-response/transaction-response.ts
4029
+ function mapGqlOutputsToTxOutputs(outputs) {
4030
+ return outputs.map((o) => {
4031
+ const obj = "amount" in o ? { ...o, amount: (0, import_math18.bn)(o.amount) } : o;
4032
+ switch (obj.type) {
4033
+ case "CoinOutput":
4034
+ return { ...obj, type: import_transactions19.OutputType.Coin };
4035
+ case "ContractOutput":
4036
+ return {
4037
+ ...obj,
4038
+ type: import_transactions19.OutputType.Contract,
4039
+ inputIndex: parseInt(obj.inputIndex, 10)
4040
+ };
4041
+ case "ChangeOutput":
4042
+ return {
4043
+ ...obj,
4044
+ type: import_transactions19.OutputType.Change
4045
+ };
4046
+ case "VariableOutput":
4047
+ return { ...obj, type: import_transactions19.OutputType.Variable };
4048
+ case "ContractCreated":
4049
+ return {
4050
+ ...obj,
4051
+ type: import_transactions19.OutputType.ContractCreated,
4052
+ contractId: obj.contract
4053
+ };
4054
+ default:
4055
+ return (0, import_utils23.assertUnreachable)(obj);
4056
+ }
4057
+ });
4058
+ }
3498
4059
  var TransactionResponse = class {
3499
4060
  /** Transaction ID */
3500
4061
  id;
3501
4062
  /** Current provider */
3502
4063
  provider;
3503
4064
  /** Gas used on the transaction */
3504
- gasUsed = (0, import_math16.bn)(0);
4065
+ gasUsed = (0, import_math18.bn)(0);
3505
4066
  /** The graphql Transaction with receipts object. */
3506
4067
  gqlTransaction;
4068
+ request;
4069
+ status;
3507
4070
  abis;
3508
4071
  /**
3509
4072
  * Constructor for `TransactionResponse`.
3510
4073
  *
3511
- * @param id - The transaction ID.
4074
+ * @param tx - The transaction ID or TransactionRequest.
3512
4075
  * @param provider - The provider.
3513
4076
  */
3514
- constructor(id, provider, abis) {
3515
- this.id = id;
4077
+ constructor(tx, provider, abis) {
4078
+ this.id = typeof tx === "string" ? tx : tx.getTransactionId(provider.getChainId());
3516
4079
  this.provider = provider;
3517
4080
  this.abis = abis;
4081
+ this.request = typeof tx === "string" ? void 0 : tx;
3518
4082
  }
3519
4083
  /**
3520
4084
  * Async constructor for `TransactionResponse`. This method can be used to create
@@ -3529,6 +4093,54 @@ var TransactionResponse = class {
3529
4093
  await response.fetch();
3530
4094
  return response;
3531
4095
  }
4096
+ applyMalleableSubscriptionFields(transaction) {
4097
+ const status = this.status;
4098
+ if (!status) {
4099
+ return;
4100
+ }
4101
+ const tx = transaction;
4102
+ if (status.type === "SuccessStatus" || status.type === "FailureStatus") {
4103
+ tx.inputs = tx.inputs.map((input, idx) => {
4104
+ if ("txPointer" in input) {
4105
+ const correspondingInput = status.transaction.inputs?.[idx];
4106
+ return {
4107
+ ...input,
4108
+ txPointer: import_transactions19.TxPointerCoder.decodeFromGqlScalar(correspondingInput.txPointer)
4109
+ };
4110
+ }
4111
+ return input;
4112
+ });
4113
+ tx.outputs = mapGqlOutputsToTxOutputs(status.transaction.outputs);
4114
+ if ("receiptsRoot" in status.transaction) {
4115
+ tx.receiptsRoot = status.transaction.receiptsRoot;
4116
+ }
4117
+ }
4118
+ }
4119
+ async getTransaction() {
4120
+ if (this.request) {
4121
+ const tx = this.request.toTransaction();
4122
+ this.applyMalleableSubscriptionFields(tx);
4123
+ return {
4124
+ tx,
4125
+ bytes: this.request.toTransactionBytes()
4126
+ };
4127
+ }
4128
+ const gqlTransaction = this.gqlTransaction ?? await this.fetch();
4129
+ return {
4130
+ tx: this.decodeTransaction(gqlTransaction),
4131
+ bytes: (0, import_utils23.arrayify)(gqlTransaction.rawPayload)
4132
+ };
4133
+ }
4134
+ getReceipts() {
4135
+ const status = this.status ?? this.gqlTransaction?.status;
4136
+ switch (status?.type) {
4137
+ case "SuccessStatus":
4138
+ case "FailureStatus":
4139
+ return status.receipts.map(processGqlReceipt);
4140
+ default:
4141
+ return [];
4142
+ }
4143
+ }
3532
4144
  /**
3533
4145
  * Fetch the transaction with receipts from the provider.
3534
4146
  *
@@ -3539,11 +4151,12 @@ var TransactionResponse = class {
3539
4151
  transactionId: this.id
3540
4152
  });
3541
4153
  if (!response.transaction) {
3542
- const subscription = this.provider.operations.statusChange({
4154
+ const subscription = await this.provider.operations.statusChange({
3543
4155
  transactionId: this.id
3544
4156
  });
3545
4157
  for await (const { statusChange } of subscription) {
3546
4158
  if (statusChange) {
4159
+ this.status = statusChange;
3547
4160
  break;
3548
4161
  }
3549
4162
  }
@@ -3560,7 +4173,7 @@ var TransactionResponse = class {
3560
4173
  */
3561
4174
  decodeTransaction(transactionWithReceipts) {
3562
4175
  return new import_transactions19.TransactionCoder().decode(
3563
- (0, import_utils20.arrayify)(transactionWithReceipts.rawPayload),
4176
+ (0, import_utils23.arrayify)(transactionWithReceipts.rawPayload),
3564
4177
  0
3565
4178
  )?.[0];
3566
4179
  }
@@ -3572,28 +4185,17 @@ var TransactionResponse = class {
3572
4185
  * @returns
3573
4186
  */
3574
4187
  async getTransactionSummary(contractsAbiMap) {
3575
- let transaction = this.gqlTransaction;
3576
- if (!transaction) {
3577
- transaction = await this.fetch();
3578
- }
3579
- const decodedTransaction = this.decodeTransaction(
3580
- transaction
3581
- );
3582
- let txReceipts = [];
3583
- if (transaction?.status && "receipts" in transaction.status) {
3584
- txReceipts = transaction.status.receipts;
3585
- }
3586
- const receipts = txReceipts.map(processGqlReceipt) || [];
4188
+ const { tx: transaction, bytes: transactionBytes } = await this.getTransaction();
3587
4189
  const { gasPerByte, gasPriceFactor, gasCosts, maxGasPerTx } = this.provider.getGasConfig();
3588
4190
  const gasPrice = await this.provider.getLatestGasPrice();
3589
4191
  const maxInputs = this.provider.getChain().consensusParameters.txParameters.maxInputs;
3590
4192
  const baseAssetId = this.provider.getBaseAssetId();
3591
4193
  const transactionSummary = assembleTransactionSummary({
3592
4194
  id: this.id,
3593
- receipts,
3594
- transaction: decodedTransaction,
3595
- transactionBytes: (0, import_utils20.arrayify)(transaction.rawPayload),
3596
- gqlTransactionStatus: transaction.status,
4195
+ receipts: this.getReceipts(),
4196
+ transaction,
4197
+ transactionBytes,
4198
+ gqlTransactionStatus: this.status ?? this.gqlTransaction?.status,
3597
4199
  gasPerByte,
3598
4200
  gasPriceFactor,
3599
4201
  abiMap: contractsAbiMap,
@@ -3610,13 +4212,15 @@ var TransactionResponse = class {
3610
4212
  if (status && status !== "SubmittedStatus") {
3611
4213
  return;
3612
4214
  }
3613
- const subscription = this.provider.operations.statusChange({
4215
+ const subscription = await this.provider.operations.statusChange({
3614
4216
  transactionId: this.id
3615
4217
  });
3616
4218
  for await (const { statusChange } of subscription) {
4219
+ this.status = statusChange;
3617
4220
  if (statusChange.type === "SqueezedOutStatus") {
3618
- throw new import_errors13.FuelError(
3619
- import_errors13.ErrorCode.TRANSACTION_SQUEEZED_OUT,
4221
+ this.unsetResourceCache();
4222
+ throw new import_errors15.FuelError(
4223
+ import_errors15.ErrorCode.TRANSACTION_SQUEEZED_OUT,
3620
4224
  `Transaction Squeezed Out with reason: ${statusChange.reason}`
3621
4225
  );
3622
4226
  }
@@ -3624,7 +4228,6 @@ var TransactionResponse = class {
3624
4228
  break;
3625
4229
  }
3626
4230
  }
3627
- await this.fetch();
3628
4231
  }
3629
4232
  /**
3630
4233
  * Assembles the result of a transaction by retrieving the transaction summary,
@@ -3641,7 +4244,6 @@ var TransactionResponse = class {
3641
4244
  async assembleResult(contractsAbiMap) {
3642
4245
  const transactionSummary = await this.getTransactionSummary(contractsAbiMap);
3643
4246
  const transactionResult = {
3644
- gqlTransaction: this.gqlTransaction,
3645
4247
  ...transactionSummary
3646
4248
  };
3647
4249
  let logs = [];
@@ -3653,9 +4255,11 @@ var TransactionResponse = class {
3653
4255
  );
3654
4256
  transactionResult.logs = logs;
3655
4257
  }
3656
- const { gqlTransaction, receipts } = transactionResult;
3657
- if (gqlTransaction.status?.type === "FailureStatus") {
3658
- const { reason } = gqlTransaction.status;
4258
+ const { receipts } = transactionResult;
4259
+ const status = this.status ?? this.gqlTransaction?.status;
4260
+ if (status?.type === "FailureStatus") {
4261
+ this.unsetResourceCache();
4262
+ const { reason } = status;
3659
4263
  throw extractTxError({
3660
4264
  receipts,
3661
4265
  statusReason: reason,
@@ -3681,10 +4285,13 @@ var TransactionResponse = class {
3681
4285
  async wait(contractsAbiMap) {
3682
4286
  return this.waitForResult(contractsAbiMap);
3683
4287
  }
4288
+ unsetResourceCache() {
4289
+ this.provider.cache?.unset(this.id);
4290
+ }
3684
4291
  };
3685
4292
 
3686
4293
  // src/providers/utils/auto-retry-fetch.ts
3687
- var import_utils22 = require("@fuel-ts/utils");
4294
+ var import_utils25 = require("@fuel-ts/utils");
3688
4295
  function getWaitDelay(options, retryAttemptNum) {
3689
4296
  const duration = options.baseDelay ?? 150;
3690
4297
  switch (options.backoff) {
@@ -3714,30 +4321,17 @@ function autoRetryFetch(fetchFn, options, retryAttemptNum = 0) {
3714
4321
  throw error;
3715
4322
  }
3716
4323
  const delay = getWaitDelay(options, retryNum);
3717
- await (0, import_utils22.sleep)(delay);
3718
- return autoRetryFetch(fetchFn, options, retryNum)(...args);
3719
- }
3720
- };
3721
- }
3722
-
3723
- // src/providers/utils/merge-quantities.ts
3724
- var mergeQuantities = (...coinQuantities) => {
3725
- const resultMap = {};
3726
- function addToMap({ amount, assetId }) {
3727
- if (resultMap[assetId]) {
3728
- resultMap[assetId] = resultMap[assetId].add(amount);
3729
- } else {
3730
- resultMap[assetId] = amount;
3731
- }
3732
- }
3733
- coinQuantities.forEach((arr) => arr.forEach(addToMap));
3734
- return Object.entries(resultMap).map(([assetId, amount]) => ({ assetId, amount }));
3735
- };
4324
+ await (0, import_utils25.sleep)(delay);
4325
+ return autoRetryFetch(fetchFn, options, retryNum)(...args);
4326
+ }
4327
+ };
4328
+ }
3736
4329
 
3737
4330
  // src/providers/provider.ts
3738
4331
  var MAX_RETRIES = 10;
3739
4332
  var RESOURCES_PAGE_SIZE_LIMIT = 512;
3740
4333
  var BLOCKS_PAGE_SIZE_LIMIT = 5;
4334
+ var DEFAULT_RESOURCE_CACHE_TTL = 2e4;
3741
4335
  var processGqlChain = (chain) => {
3742
4336
  const { name, daHeight, consensusParameters, latestBlock } = chain;
3743
4337
  const {
@@ -3753,47 +4347,47 @@ var processGqlChain = (chain) => {
3753
4347
  } = consensusParameters;
3754
4348
  return {
3755
4349
  name,
3756
- baseChainHeight: (0, import_math17.bn)(daHeight),
4350
+ baseChainHeight: (0, import_math19.bn)(daHeight),
3757
4351
  consensusParameters: {
3758
4352
  version,
3759
- chainId: (0, import_math17.bn)(chainId),
4353
+ chainId: (0, import_math19.bn)(chainId),
3760
4354
  baseAssetId,
3761
4355
  feeParameters: {
3762
4356
  version: feeParams.version,
3763
- gasPerByte: (0, import_math17.bn)(feeParams.gasPerByte),
3764
- gasPriceFactor: (0, import_math17.bn)(feeParams.gasPriceFactor)
4357
+ gasPerByte: (0, import_math19.bn)(feeParams.gasPerByte),
4358
+ gasPriceFactor: (0, import_math19.bn)(feeParams.gasPriceFactor)
3765
4359
  },
3766
4360
  contractParameters: {
3767
4361
  version: contractParams.version,
3768
- contractMaxSize: (0, import_math17.bn)(contractParams.contractMaxSize),
3769
- maxStorageSlots: (0, import_math17.bn)(contractParams.maxStorageSlots)
4362
+ contractMaxSize: (0, import_math19.bn)(contractParams.contractMaxSize),
4363
+ maxStorageSlots: (0, import_math19.bn)(contractParams.maxStorageSlots)
3770
4364
  },
3771
4365
  txParameters: {
3772
4366
  version: txParams.version,
3773
- maxInputs: (0, import_math17.bn)(txParams.maxInputs),
3774
- maxOutputs: (0, import_math17.bn)(txParams.maxOutputs),
3775
- maxWitnesses: (0, import_math17.bn)(txParams.maxWitnesses),
3776
- maxGasPerTx: (0, import_math17.bn)(txParams.maxGasPerTx),
3777
- maxSize: (0, import_math17.bn)(txParams.maxSize),
3778
- maxBytecodeSubsections: (0, import_math17.bn)(txParams.maxBytecodeSubsections)
4367
+ maxInputs: (0, import_math19.bn)(txParams.maxInputs),
4368
+ maxOutputs: (0, import_math19.bn)(txParams.maxOutputs),
4369
+ maxWitnesses: (0, import_math19.bn)(txParams.maxWitnesses),
4370
+ maxGasPerTx: (0, import_math19.bn)(txParams.maxGasPerTx),
4371
+ maxSize: (0, import_math19.bn)(txParams.maxSize),
4372
+ maxBytecodeSubsections: (0, import_math19.bn)(txParams.maxBytecodeSubsections)
3779
4373
  },
3780
4374
  predicateParameters: {
3781
4375
  version: predicateParams.version,
3782
- maxPredicateLength: (0, import_math17.bn)(predicateParams.maxPredicateLength),
3783
- maxPredicateDataLength: (0, import_math17.bn)(predicateParams.maxPredicateDataLength),
3784
- maxGasPerPredicate: (0, import_math17.bn)(predicateParams.maxGasPerPredicate),
3785
- maxMessageDataLength: (0, import_math17.bn)(predicateParams.maxMessageDataLength)
4376
+ maxPredicateLength: (0, import_math19.bn)(predicateParams.maxPredicateLength),
4377
+ maxPredicateDataLength: (0, import_math19.bn)(predicateParams.maxPredicateDataLength),
4378
+ maxGasPerPredicate: (0, import_math19.bn)(predicateParams.maxGasPerPredicate),
4379
+ maxMessageDataLength: (0, import_math19.bn)(predicateParams.maxMessageDataLength)
3786
4380
  },
3787
4381
  scriptParameters: {
3788
4382
  version: scriptParams.version,
3789
- maxScriptLength: (0, import_math17.bn)(scriptParams.maxScriptLength),
3790
- maxScriptDataLength: (0, import_math17.bn)(scriptParams.maxScriptDataLength)
4383
+ maxScriptLength: (0, import_math19.bn)(scriptParams.maxScriptLength),
4384
+ maxScriptDataLength: (0, import_math19.bn)(scriptParams.maxScriptDataLength)
3791
4385
  },
3792
4386
  gasCosts
3793
4387
  },
3794
4388
  latestBlock: {
3795
4389
  id: latestBlock.id,
3796
- height: (0, import_math17.bn)(latestBlock.height),
4390
+ height: (0, import_math19.bn)(latestBlock.height),
3797
4391
  time: latestBlock.header.time,
3798
4392
  transactions: latestBlock.transactions.map((i) => ({
3799
4393
  id: i.id
@@ -3820,14 +4414,23 @@ var _Provider = class {
3820
4414
  __publicField(this, "cache");
3821
4415
  __publicField(this, "options", {
3822
4416
  timeout: void 0,
3823
- cacheUtxo: void 0,
4417
+ resourceCacheTTL: void 0,
3824
4418
  fetch: void 0,
3825
4419
  retryOptions: void 0
3826
4420
  });
3827
4421
  this.options = { ...this.options, ...options };
3828
4422
  this.url = url;
3829
4423
  this.operations = this.createOperations();
3830
- this.cache = options.cacheUtxo ? new MemoryCache(options.cacheUtxo) : void 0;
4424
+ const { resourceCacheTTL } = this.options;
4425
+ if ((0, import_utils26.isDefined)(resourceCacheTTL)) {
4426
+ if (resourceCacheTTL !== -1) {
4427
+ this.cache = new ResourceCache(resourceCacheTTL);
4428
+ } else {
4429
+ this.cache = void 0;
4430
+ }
4431
+ } else {
4432
+ this.cache = new ResourceCache(DEFAULT_RESOURCE_CACHE_TTL);
4433
+ }
3831
4434
  }
3832
4435
  /** @hidden */
3833
4436
  static clearChainAndNodeCaches() {
@@ -3871,8 +4474,8 @@ var _Provider = class {
3871
4474
  getChain() {
3872
4475
  const chain = _Provider.chainInfoCache[this.url];
3873
4476
  if (!chain) {
3874
- throw new import_errors14.FuelError(
3875
- import_errors14.ErrorCode.CHAIN_INFO_CACHE_EMPTY,
4477
+ throw new import_errors16.FuelError(
4478
+ import_errors16.ErrorCode.CHAIN_INFO_CACHE_EMPTY,
3876
4479
  "Chain info cache is empty. Make sure you have called `Provider.create` to initialize the provider."
3877
4480
  );
3878
4481
  }
@@ -3886,8 +4489,8 @@ var _Provider = class {
3886
4489
  getNode() {
3887
4490
  const node = _Provider.nodeInfoCache[this.url];
3888
4491
  if (!node) {
3889
- throw new import_errors14.FuelError(
3890
- import_errors14.ErrorCode.NODE_INFO_CACHE_EMPTY,
4492
+ throw new import_errors16.FuelError(
4493
+ import_errors16.ErrorCode.NODE_INFO_CACHE_EMPTY,
3891
4494
  "Node info cache is empty. Make sure you have called `Provider.create` to initialize the provider."
3892
4495
  );
3893
4496
  }
@@ -3929,9 +4532,9 @@ var _Provider = class {
3929
4532
  * @returns A promise that resolves to the Chain and NodeInfo.
3930
4533
  */
3931
4534
  async fetchChainAndNodeInfo() {
3932
- const chain = await this.fetchChain();
3933
4535
  const nodeInfo = await this.fetchNode();
3934
4536
  _Provider.ensureClientVersionIsSupported(nodeInfo);
4537
+ const chain = await this.fetchChain();
3935
4538
  return {
3936
4539
  chain,
3937
4540
  nodeInfo
@@ -3965,8 +4568,8 @@ Supported fuel-core version: ${supportedVersion}.`
3965
4568
  if ("response" in response) {
3966
4569
  const graphQlResponse = response.response;
3967
4570
  if (Array.isArray(graphQlResponse?.errors)) {
3968
- throw new import_errors14.FuelError(
3969
- import_errors14.FuelError.CODES.INVALID_REQUEST,
4571
+ throw new import_errors16.FuelError(
4572
+ import_errors16.FuelError.CODES.INVALID_REQUEST,
3970
4573
  graphQlResponse.errors.map((err) => err.message).join("\n\n")
3971
4574
  );
3972
4575
  }
@@ -3977,7 +4580,7 @@ Supported fuel-core version: ${supportedVersion}.`
3977
4580
  const opDefinition = query.definitions.find((x) => x.kind === "OperationDefinition");
3978
4581
  const isSubscription = opDefinition?.operation === "subscription";
3979
4582
  if (isSubscription) {
3980
- return new FuelGraphqlSubscriber({
4583
+ return FuelGraphqlSubscriber.create({
3981
4584
  url: this.url,
3982
4585
  query,
3983
4586
  fetchFn: (url, requestInit) => fetchFn(url, requestInit, this.options),
@@ -4006,7 +4609,7 @@ Supported fuel-core version: ${supportedVersion}.`
4006
4609
  */
4007
4610
  async getBlockNumber() {
4008
4611
  const { chain } = await this.operations.getChain();
4009
- return (0, import_math17.bn)(chain.latestBlock.height, 10);
4612
+ return (0, import_math19.bn)(chain.latestBlock.height, 10);
4010
4613
  }
4011
4614
  /**
4012
4615
  * Returns the node information for the current provider network.
@@ -4016,8 +4619,8 @@ Supported fuel-core version: ${supportedVersion}.`
4016
4619
  async fetchNode() {
4017
4620
  const { nodeInfo } = await this.operations.getNodeInfo();
4018
4621
  const processedNodeInfo = {
4019
- maxDepth: (0, import_math17.bn)(nodeInfo.maxDepth),
4020
- maxTx: (0, import_math17.bn)(nodeInfo.maxTx),
4622
+ maxDepth: (0, import_math19.bn)(nodeInfo.maxDepth),
4623
+ maxTx: (0, import_math19.bn)(nodeInfo.maxTx),
4021
4624
  nodeVersion: nodeInfo.nodeVersion,
4022
4625
  utxoValidation: nodeInfo.utxoValidation,
4023
4626
  vmBacktrace: nodeInfo.vmBacktrace
@@ -4058,6 +4661,21 @@ Supported fuel-core version: ${supportedVersion}.`
4058
4661
  } = this.getChain();
4059
4662
  return baseAssetId;
4060
4663
  }
4664
+ validateTransaction(tx, consensusParameters) {
4665
+ const { maxOutputs, maxInputs } = consensusParameters.txParameters;
4666
+ if ((0, import_math19.bn)(tx.inputs.length).gt(maxInputs)) {
4667
+ throw new import_errors16.FuelError(
4668
+ import_errors16.ErrorCode.MAX_INPUTS_EXCEEDED,
4669
+ "The transaction exceeds the maximum allowed number of inputs."
4670
+ );
4671
+ }
4672
+ if ((0, import_math19.bn)(tx.outputs.length).gt(maxOutputs)) {
4673
+ throw new import_errors16.FuelError(
4674
+ import_errors16.ErrorCode.MAX_OUTPUTS_EXCEEDED,
4675
+ "The transaction exceeds the maximum allowed number of outputs."
4676
+ );
4677
+ }
4678
+ }
4061
4679
  /**
4062
4680
  * Submits a transaction to the chain to be executed.
4063
4681
  *
@@ -4069,39 +4687,23 @@ Supported fuel-core version: ${supportedVersion}.`
4069
4687
  * @returns A promise that resolves to the transaction response object.
4070
4688
  */
4071
4689
  // #region Provider-sendTransaction
4072
- async sendTransaction(transactionRequestLike, { estimateTxDependencies = true, awaitExecution = false } = {}) {
4690
+ async sendTransaction(transactionRequestLike, { estimateTxDependencies = true } = {}) {
4073
4691
  const transactionRequest = transactionRequestify(transactionRequestLike);
4074
- __privateMethod(this, _cacheInputs, cacheInputs_fn).call(this, transactionRequest.inputs);
4075
4692
  if (estimateTxDependencies) {
4076
4693
  await this.estimateTxDependencies(transactionRequest);
4077
4694
  }
4078
- const encodedTransaction = (0, import_utils23.hexlify)(transactionRequest.toTransactionBytes());
4695
+ const { consensusParameters } = this.getChain();
4696
+ this.validateTransaction(transactionRequest, consensusParameters);
4697
+ const encodedTransaction = (0, import_utils26.hexlify)(transactionRequest.toTransactionBytes());
4079
4698
  let abis;
4080
- if (transactionRequest.type === import_transactions20.TransactionType.Script) {
4699
+ if (isTransactionTypeScript(transactionRequest)) {
4081
4700
  abis = transactionRequest.abis;
4082
4701
  }
4083
- if (awaitExecution) {
4084
- const subscription = this.operations.submitAndAwait({ encodedTransaction });
4085
- for await (const { submitAndAwait } of subscription) {
4086
- if (submitAndAwait.type === "SqueezedOutStatus") {
4087
- throw new import_errors14.FuelError(
4088
- import_errors14.ErrorCode.TRANSACTION_SQUEEZED_OUT,
4089
- `Transaction Squeezed Out with reason: ${submitAndAwait.reason}`
4090
- );
4091
- }
4092
- if (submitAndAwait.type !== "SubmittedStatus") {
4093
- break;
4094
- }
4095
- }
4096
- const transactionId2 = transactionRequest.getTransactionId(this.getChainId());
4097
- const response = new TransactionResponse(transactionId2, this, abis);
4098
- await response.fetch();
4099
- return response;
4100
- }
4101
4702
  const {
4102
4703
  submit: { id: transactionId }
4103
4704
  } = await this.operations.submit({ encodedTransaction });
4104
- return new TransactionResponse(transactionId, this, abis);
4705
+ __privateMethod(this, _cacheInputs, cacheInputs_fn).call(this, transactionRequest.inputs, transactionId);
4706
+ return new TransactionResponse(transactionRequest, this, abis);
4105
4707
  }
4106
4708
  /**
4107
4709
  * Executes a transaction without actually submitting it to the chain.
@@ -4118,7 +4720,7 @@ Supported fuel-core version: ${supportedVersion}.`
4118
4720
  if (estimateTxDependencies) {
4119
4721
  return this.estimateTxDependencies(transactionRequest);
4120
4722
  }
4121
- const encodedTransaction = (0, import_utils23.hexlify)(transactionRequest.toTransactionBytes());
4723
+ const encodedTransaction = (0, import_utils26.hexlify)(transactionRequest.toTransactionBytes());
4122
4724
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
4123
4725
  encodedTransactions: encodedTransaction,
4124
4726
  utxoValidation: utxoValidation || false
@@ -4138,13 +4740,13 @@ Supported fuel-core version: ${supportedVersion}.`
4138
4740
  async estimatePredicates(transactionRequest) {
4139
4741
  const shouldEstimatePredicates = Boolean(
4140
4742
  transactionRequest.inputs.find(
4141
- (input) => "predicate" in input && input.predicate && !(0, import_utils24.equalBytes)((0, import_utils23.arrayify)(input.predicate), (0, import_utils23.arrayify)("0x")) && new import_math17.BN(input.predicateGasUsed).isZero()
4743
+ (input) => "predicate" in input && input.predicate && !(0, import_utils27.equalBytes)((0, import_utils26.arrayify)(input.predicate), (0, import_utils26.arrayify)("0x")) && new import_math19.BN(input.predicateGasUsed).isZero()
4142
4744
  )
4143
4745
  );
4144
4746
  if (!shouldEstimatePredicates) {
4145
4747
  return transactionRequest;
4146
4748
  }
4147
- const encodedTransaction = (0, import_utils23.hexlify)(transactionRequest.toTransactionBytes());
4749
+ const encodedTransaction = (0, import_utils26.hexlify)(transactionRequest.toTransactionBytes());
4148
4750
  const response = await this.operations.estimatePredicates({
4149
4751
  encodedTransaction
4150
4752
  });
@@ -4153,7 +4755,7 @@ Supported fuel-core version: ${supportedVersion}.`
4153
4755
  } = response;
4154
4756
  if (inputs) {
4155
4757
  inputs.forEach((input, index) => {
4156
- if ("predicateGasUsed" in input && (0, import_math17.bn)(input.predicateGasUsed).gt(0)) {
4758
+ if ("predicateGasUsed" in input && (0, import_math19.bn)(input.predicateGasUsed).gt(0)) {
4157
4759
  transactionRequest.inputs[index].predicateGasUsed = input.predicateGasUsed;
4158
4760
  }
4159
4761
  });
@@ -4170,7 +4772,7 @@ Supported fuel-core version: ${supportedVersion}.`
4170
4772
  * @returns A promise that resolves to the estimate transaction dependencies.
4171
4773
  */
4172
4774
  async estimateTxDependencies(transactionRequest) {
4173
- if (transactionRequest.type === import_transactions20.TransactionType.Create) {
4775
+ if (isTransactionTypeCreate(transactionRequest)) {
4174
4776
  return {
4175
4777
  receipts: [],
4176
4778
  outputVariables: 0,
@@ -4185,18 +4787,18 @@ Supported fuel-core version: ${supportedVersion}.`
4185
4787
  const {
4186
4788
  dryRun: [{ receipts: rawReceipts, status }]
4187
4789
  } = await this.operations.dryRun({
4188
- encodedTransactions: [(0, import_utils23.hexlify)(transactionRequest.toTransactionBytes())],
4790
+ encodedTransactions: [(0, import_utils26.hexlify)(transactionRequest.toTransactionBytes())],
4189
4791
  utxoValidation: false
4190
4792
  });
4191
4793
  receipts = rawReceipts.map(processGqlReceipt);
4192
4794
  dryRunStatus = status;
4193
4795
  const { missingOutputVariables, missingOutputContractIds } = getReceiptsWithMissingData(receipts);
4194
4796
  const hasMissingOutputs = missingOutputVariables.length !== 0 || missingOutputContractIds.length !== 0;
4195
- if (hasMissingOutputs) {
4797
+ if (hasMissingOutputs && isTransactionTypeScript(transactionRequest)) {
4196
4798
  outputVariables += missingOutputVariables.length;
4197
4799
  transactionRequest.addVariableOutputs(missingOutputVariables.length);
4198
4800
  missingOutputContractIds.forEach(({ contractId }) => {
4199
- transactionRequest.addContractInputAndOutput(import_address3.Address.fromString(contractId));
4801
+ transactionRequest.addContractInputAndOutput(import_address4.Address.fromString(contractId));
4200
4802
  missingContractIds.push(contractId);
4201
4803
  });
4202
4804
  const { maxFee } = await this.estimateTxGasAndFee({
@@ -4234,8 +4836,8 @@ Supported fuel-core version: ${supportedVersion}.`
4234
4836
  const allRequests = (0, import_ramda3.clone)(transactionRequests);
4235
4837
  const serializedTransactionsMap = /* @__PURE__ */ new Map();
4236
4838
  allRequests.forEach((req, index) => {
4237
- if (req.type === import_transactions20.TransactionType.Script) {
4238
- serializedTransactionsMap.set(index, (0, import_utils23.hexlify)(req.toTransactionBytes()));
4839
+ if (isTransactionTypeScript(req)) {
4840
+ serializedTransactionsMap.set(index, (0, import_utils26.hexlify)(req.toTransactionBytes()));
4239
4841
  }
4240
4842
  });
4241
4843
  let transactionsToProcess = Array.from(serializedTransactionsMap.keys());
@@ -4260,18 +4862,18 @@ Supported fuel-core version: ${supportedVersion}.`
4260
4862
  );
4261
4863
  const hasMissingOutputs = missingOutputVariables.length > 0 || missingOutputContractIds.length > 0;
4262
4864
  const request = allRequests[requestIdx];
4263
- if (hasMissingOutputs && request?.type === import_transactions20.TransactionType.Script) {
4865
+ if (hasMissingOutputs && isTransactionTypeScript(request)) {
4264
4866
  result.outputVariables += missingOutputVariables.length;
4265
4867
  request.addVariableOutputs(missingOutputVariables.length);
4266
4868
  missingOutputContractIds.forEach(({ contractId }) => {
4267
- request.addContractInputAndOutput(import_address3.Address.fromString(contractId));
4869
+ request.addContractInputAndOutput(import_address4.Address.fromString(contractId));
4268
4870
  result.missingContractIds.push(contractId);
4269
4871
  });
4270
4872
  const { maxFee } = await this.estimateTxGasAndFee({
4271
4873
  transactionRequest: request
4272
4874
  });
4273
4875
  request.maxFee = maxFee;
4274
- serializedTransactionsMap.set(requestIdx, (0, import_utils23.hexlify)(request.toTransactionBytes()));
4876
+ serializedTransactionsMap.set(requestIdx, (0, import_utils26.hexlify)(request.toTransactionBytes()));
4275
4877
  nextRoundTransactions.push(requestIdx);
4276
4878
  }
4277
4879
  }
@@ -4292,7 +4894,7 @@ Supported fuel-core version: ${supportedVersion}.`
4292
4894
  if (estimateTxDependencies) {
4293
4895
  return this.estimateMultipleTxDependencies(transactionRequests);
4294
4896
  }
4295
- const encodedTransactions = transactionRequests.map((tx) => (0, import_utils23.hexlify)(tx.toTransactionBytes()));
4897
+ const encodedTransactions = transactionRequests.map((tx) => (0, import_utils26.hexlify)(tx.toTransactionBytes()));
4296
4898
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
4297
4899
  encodedTransactions,
4298
4900
  utxoValidation: utxoValidation || false
@@ -4318,13 +4920,13 @@ Supported fuel-core version: ${supportedVersion}.`
4318
4920
  gasPrice = await this.estimateGasPrice(10);
4319
4921
  }
4320
4922
  const minFee = calculateGasFee({
4321
- gasPrice: (0, import_math17.bn)(gasPrice),
4923
+ gasPrice: (0, import_math19.bn)(gasPrice),
4322
4924
  gas: minGas,
4323
4925
  priceFactor: gasPriceFactor,
4324
4926
  tip: transactionRequest.tip
4325
4927
  }).add(1);
4326
- let gasLimit = (0, import_math17.bn)(0);
4327
- if (transactionRequest.type === import_transactions20.TransactionType.Script) {
4928
+ let gasLimit = (0, import_math19.bn)(0);
4929
+ if (isTransactionTypeScript(transactionRequest)) {
4328
4930
  gasLimit = transactionRequest.gasLimit;
4329
4931
  if (transactionRequest.gasLimit.eq(0)) {
4330
4932
  transactionRequest.gasLimit = minGas;
@@ -4336,7 +4938,7 @@ Supported fuel-core version: ${supportedVersion}.`
4336
4938
  }
4337
4939
  const maxGas = transactionRequest.calculateMaxGas(chainInfo, minGas);
4338
4940
  const maxFee = calculateGasFee({
4339
- gasPrice: (0, import_math17.bn)(gasPrice),
4941
+ gasPrice: (0, import_math19.bn)(gasPrice),
4340
4942
  gas: maxGas,
4341
4943
  priceFactor: gasPriceFactor,
4342
4944
  tip: transactionRequest.tip
@@ -4366,7 +4968,7 @@ Supported fuel-core version: ${supportedVersion}.`
4366
4968
  if (estimateTxDependencies) {
4367
4969
  return this.estimateTxDependencies(transactionRequest);
4368
4970
  }
4369
- const encodedTransactions = [(0, import_utils23.hexlify)(transactionRequest.toTransactionBytes())];
4971
+ const encodedTransactions = [(0, import_utils26.hexlify)(transactionRequest.toTransactionBytes())];
4370
4972
  const { dryRun: dryRunStatuses } = await this.operations.dryRun({
4371
4973
  encodedTransactions,
4372
4974
  utxoValidation: true
@@ -4379,6 +4981,8 @@ Supported fuel-core version: ${supportedVersion}.`
4379
4981
  return { receipts: callResult[0].receipts };
4380
4982
  }
4381
4983
  /**
4984
+ * @hidden
4985
+ *
4382
4986
  * Returns a transaction cost to enable user
4383
4987
  * to set gasLimit and also reserve balance amounts
4384
4988
  * on the transaction.
@@ -4388,23 +4992,16 @@ Supported fuel-core version: ${supportedVersion}.`
4388
4992
  *
4389
4993
  * @returns A promise that resolves to the transaction cost object.
4390
4994
  */
4391
- async getTransactionCost(transactionRequestLike, { resourcesOwner, signatureCallback, quantitiesToContract = [] } = {}) {
4995
+ async getTransactionCost(transactionRequestLike, { signatureCallback } = {}) {
4392
4996
  const txRequestClone = (0, import_ramda3.clone)(transactionRequestify(transactionRequestLike));
4393
- const isScriptTransaction = txRequestClone.type === import_transactions20.TransactionType.Script;
4394
- const baseAssetId = this.getBaseAssetId();
4395
4997
  const updateMaxFee = txRequestClone.maxFee.eq(0);
4396
- const coinOutputsQuantities = txRequestClone.getCoinOutputsQuantities();
4397
- const allQuantities = mergeQuantities(coinOutputsQuantities, quantitiesToContract);
4398
- txRequestClone.fundWithFakeUtxos(allQuantities, baseAssetId, resourcesOwner?.address);
4998
+ const isScriptTransaction = isTransactionTypeScript(txRequestClone);
4399
4999
  if (isScriptTransaction) {
4400
- txRequestClone.gasLimit = (0, import_math17.bn)(0);
4401
- }
4402
- if (resourcesOwner && "populateTransactionPredicateData" in resourcesOwner) {
4403
- resourcesOwner.populateTransactionPredicateData(txRequestClone);
5000
+ txRequestClone.gasLimit = (0, import_math19.bn)(0);
4404
5001
  }
4405
5002
  const signedRequest = (0, import_ramda3.clone)(txRequestClone);
4406
5003
  let addedSignatures = 0;
4407
- if (signatureCallback && isScriptTransaction) {
5004
+ if (signatureCallback && isTransactionTypeScript(signedRequest)) {
4408
5005
  const lengthBefore = signedRequest.witnesses.length;
4409
5006
  await signatureCallback(signedRequest);
4410
5007
  addedSignatures = signedRequest.witnesses.length - lengthBefore;
@@ -4418,7 +5015,7 @@ Supported fuel-core version: ${supportedVersion}.`
4418
5015
  let dryRunStatus;
4419
5016
  let missingContractIds = [];
4420
5017
  let outputVariables = 0;
4421
- let gasUsed = (0, import_math17.bn)(0);
5018
+ let gasUsed = (0, import_math19.bn)(0);
4422
5019
  txRequestClone.maxFee = maxFee;
4423
5020
  if (isScriptTransaction) {
4424
5021
  txRequestClone.gasLimit = gasLimit;
@@ -4437,7 +5034,6 @@ Supported fuel-core version: ${supportedVersion}.`
4437
5034
  }));
4438
5035
  }
4439
5036
  return {
4440
- requiredQuantities: allQuantities,
4441
5037
  receipts,
4442
5038
  gasUsed,
4443
5039
  gasPrice,
@@ -4453,34 +5049,6 @@ Supported fuel-core version: ${supportedVersion}.`
4453
5049
  updateMaxFee
4454
5050
  };
4455
5051
  }
4456
- /**
4457
- * Get the required quantities and associated resources for a transaction.
4458
- *
4459
- * @param owner - address to add resources from.
4460
- * @param transactionRequestLike - transaction request to populate resources for.
4461
- * @param quantitiesToContract - quantities for the contract (optional).
4462
- *
4463
- * @returns a promise resolving to the required quantities for the transaction.
4464
- */
4465
- async getResourcesForTransaction(owner, transactionRequestLike, quantitiesToContract = []) {
4466
- const ownerAddress = import_address3.Address.fromAddressOrString(owner);
4467
- const transactionRequest = transactionRequestify((0, import_ramda3.clone)(transactionRequestLike));
4468
- const transactionCost = await this.getTransactionCost(transactionRequest, {
4469
- quantitiesToContract
4470
- });
4471
- transactionRequest.addResources(
4472
- await this.getResourcesToSpend(ownerAddress, transactionCost.requiredQuantities)
4473
- );
4474
- const { requiredQuantities, ...txCost } = await this.getTransactionCost(transactionRequest, {
4475
- quantitiesToContract
4476
- });
4477
- const resources = await this.getResourcesToSpend(ownerAddress, requiredQuantities);
4478
- return {
4479
- resources,
4480
- requiredQuantities,
4481
- ...txCost
4482
- };
4483
- }
4484
5052
  /**
4485
5053
  * Returns coins for the given owner.
4486
5054
  *
@@ -4491,7 +5059,7 @@ Supported fuel-core version: ${supportedVersion}.`
4491
5059
  * @returns A promise that resolves to the coins.
4492
5060
  */
4493
5061
  async getCoins(owner, assetId, paginationArgs) {
4494
- const ownerAddress = import_address3.Address.fromAddressOrString(owner);
5062
+ const ownerAddress = import_address4.Address.fromAddressOrString(owner);
4495
5063
  const {
4496
5064
  coins: { edges, pageInfo }
4497
5065
  } = await this.operations.getCoins({
@@ -4499,15 +5067,15 @@ Supported fuel-core version: ${supportedVersion}.`
4499
5067
  paginationLimit: RESOURCES_PAGE_SIZE_LIMIT,
4500
5068
  inputArgs: paginationArgs
4501
5069
  }),
4502
- filter: { owner: ownerAddress.toB256(), assetId: assetId && (0, import_utils23.hexlify)(assetId) }
5070
+ filter: { owner: ownerAddress.toB256(), assetId: assetId && (0, import_utils26.hexlify)(assetId) }
4503
5071
  });
4504
5072
  const coins = edges.map(({ node }) => ({
4505
5073
  id: node.utxoId,
4506
5074
  assetId: node.assetId,
4507
- amount: (0, import_math17.bn)(node.amount),
4508
- owner: import_address3.Address.fromAddressOrString(node.owner),
4509
- blockCreated: (0, import_math17.bn)(node.blockCreated),
4510
- txCreatedIdx: (0, import_math17.bn)(node.txCreatedIdx)
5075
+ amount: (0, import_math19.bn)(node.amount),
5076
+ owner: import_address4.Address.fromAddressOrString(node.owner),
5077
+ blockCreated: (0, import_math19.bn)(node.blockCreated),
5078
+ txCreatedIdx: (0, import_math19.bn)(node.txCreatedIdx)
4511
5079
  }));
4512
5080
  return {
4513
5081
  coins,
@@ -4523,21 +5091,20 @@ Supported fuel-core version: ${supportedVersion}.`
4523
5091
  * @returns A promise that resolves to the resources.
4524
5092
  */
4525
5093
  async getResourcesToSpend(owner, quantities, excludedIds) {
4526
- const ownerAddress = import_address3.Address.fromAddressOrString(owner);
5094
+ const ownerAddress = import_address4.Address.fromAddressOrString(owner);
4527
5095
  const excludeInput = {
4528
- messages: excludedIds?.messages?.map((nonce) => (0, import_utils23.hexlify)(nonce)) || [],
4529
- utxos: excludedIds?.utxos?.map((id) => (0, import_utils23.hexlify)(id)) || []
5096
+ messages: excludedIds?.messages?.map((nonce) => (0, import_utils26.hexlify)(nonce)) || [],
5097
+ utxos: excludedIds?.utxos?.map((id) => (0, import_utils26.hexlify)(id)) || []
4530
5098
  };
4531
5099
  if (this.cache) {
4532
- const uniqueUtxos = new Set(
4533
- excludeInput.utxos.concat(this.cache?.getActiveData().map((id) => (0, import_utils23.hexlify)(id)))
4534
- );
4535
- excludeInput.utxos = Array.from(uniqueUtxos);
5100
+ const cached = this.cache.getActiveData();
5101
+ excludeInput.messages.push(...cached.messages);
5102
+ excludeInput.utxos.push(...cached.utxos);
4536
5103
  }
4537
5104
  const coinsQuery = {
4538
5105
  owner: ownerAddress.toB256(),
4539
5106
  queryPerAsset: quantities.map(coinQuantityfy).map(({ assetId, amount, max: maxPerAsset }) => ({
4540
- assetId: (0, import_utils23.hexlify)(assetId),
5107
+ assetId: (0, import_utils26.hexlify)(assetId),
4541
5108
  amount: amount.toString(10),
4542
5109
  max: maxPerAsset ? maxPerAsset.toString(10) : void 0
4543
5110
  })),
@@ -4548,21 +5115,21 @@ Supported fuel-core version: ${supportedVersion}.`
4548
5115
  switch (coin.type) {
4549
5116
  case "MessageCoin":
4550
5117
  return {
4551
- amount: (0, import_math17.bn)(coin.amount),
5118
+ amount: (0, import_math19.bn)(coin.amount),
4552
5119
  assetId: coin.assetId,
4553
- daHeight: (0, import_math17.bn)(coin.daHeight),
4554
- sender: import_address3.Address.fromAddressOrString(coin.sender),
4555
- recipient: import_address3.Address.fromAddressOrString(coin.recipient),
5120
+ daHeight: (0, import_math19.bn)(coin.daHeight),
5121
+ sender: import_address4.Address.fromAddressOrString(coin.sender),
5122
+ recipient: import_address4.Address.fromAddressOrString(coin.recipient),
4556
5123
  nonce: coin.nonce
4557
5124
  };
4558
5125
  case "Coin":
4559
5126
  return {
4560
5127
  id: coin.utxoId,
4561
- amount: (0, import_math17.bn)(coin.amount),
5128
+ amount: (0, import_math19.bn)(coin.amount),
4562
5129
  assetId: coin.assetId,
4563
- owner: import_address3.Address.fromAddressOrString(coin.owner),
4564
- blockCreated: (0, import_math17.bn)(coin.blockCreated),
4565
- txCreatedIdx: (0, import_math17.bn)(coin.txCreatedIdx)
5130
+ owner: import_address4.Address.fromAddressOrString(coin.owner),
5131
+ blockCreated: (0, import_math19.bn)(coin.blockCreated),
5132
+ txCreatedIdx: (0, import_math19.bn)(coin.txCreatedIdx)
4566
5133
  };
4567
5134
  default:
4568
5135
  return null;
@@ -4579,13 +5146,13 @@ Supported fuel-core version: ${supportedVersion}.`
4579
5146
  async getBlock(idOrHeight) {
4580
5147
  let variables;
4581
5148
  if (typeof idOrHeight === "number") {
4582
- variables = { height: (0, import_math17.bn)(idOrHeight).toString(10) };
5149
+ variables = { height: (0, import_math19.bn)(idOrHeight).toString(10) };
4583
5150
  } else if (idOrHeight === "latest") {
4584
5151
  variables = { height: (await this.getBlockNumber()).toString(10) };
4585
5152
  } else if (idOrHeight.length === 66) {
4586
5153
  variables = { blockId: idOrHeight };
4587
5154
  } else {
4588
- variables = { blockId: (0, import_math17.bn)(idOrHeight).toString(10) };
5155
+ variables = { blockId: (0, import_math19.bn)(idOrHeight).toString(10) };
4589
5156
  }
4590
5157
  const { block } = await this.operations.getBlock(variables);
4591
5158
  if (!block) {
@@ -4593,7 +5160,7 @@ Supported fuel-core version: ${supportedVersion}.`
4593
5160
  }
4594
5161
  return {
4595
5162
  id: block.id,
4596
- height: (0, import_math17.bn)(block.height),
5163
+ height: (0, import_math19.bn)(block.height),
4597
5164
  time: block.header.time,
4598
5165
  transactionIds: block.transactions.map((tx) => tx.id)
4599
5166
  };
@@ -4615,7 +5182,7 @@ Supported fuel-core version: ${supportedVersion}.`
4615
5182
  });
4616
5183
  const blocks = edges.map(({ node: block }) => ({
4617
5184
  id: block.id,
4618
- height: (0, import_math17.bn)(block.height),
5185
+ height: (0, import_math19.bn)(block.height),
4619
5186
  time: block.header.time,
4620
5187
  transactionIds: block.transactions.map((tx) => tx.id)
4621
5188
  }));
@@ -4630,7 +5197,7 @@ Supported fuel-core version: ${supportedVersion}.`
4630
5197
  async getBlockWithTransactions(idOrHeight) {
4631
5198
  let variables;
4632
5199
  if (typeof idOrHeight === "number") {
4633
- variables = { blockHeight: (0, import_math17.bn)(idOrHeight).toString(10) };
5200
+ variables = { blockHeight: (0, import_math19.bn)(idOrHeight).toString(10) };
4634
5201
  } else if (idOrHeight === "latest") {
4635
5202
  variables = { blockHeight: (await this.getBlockNumber()).toString() };
4636
5203
  } else {
@@ -4642,11 +5209,11 @@ Supported fuel-core version: ${supportedVersion}.`
4642
5209
  }
4643
5210
  return {
4644
5211
  id: block.id,
4645
- height: (0, import_math17.bn)(block.height, 10),
5212
+ height: (0, import_math19.bn)(block.height, 10),
4646
5213
  time: block.header.time,
4647
5214
  transactionIds: block.transactions.map((tx) => tx.id),
4648
5215
  transactions: block.transactions.map(
4649
- (tx) => new import_transactions20.TransactionCoder().decode((0, import_utils23.arrayify)(tx.rawPayload), 0)?.[0]
5216
+ (tx) => new import_transactions20.TransactionCoder().decode((0, import_utils26.arrayify)(tx.rawPayload), 0)?.[0]
4650
5217
  )
4651
5218
  };
4652
5219
  }
@@ -4662,7 +5229,7 @@ Supported fuel-core version: ${supportedVersion}.`
4662
5229
  return null;
4663
5230
  }
4664
5231
  return new import_transactions20.TransactionCoder().decode(
4665
- (0, import_utils23.arrayify)(transaction.rawPayload),
5232
+ (0, import_utils26.arrayify)(transaction.rawPayload),
4666
5233
  0
4667
5234
  )?.[0];
4668
5235
  }
@@ -4677,7 +5244,7 @@ Supported fuel-core version: ${supportedVersion}.`
4677
5244
  } = await this.operations.getTransactions(paginationArgs);
4678
5245
  const coder = new import_transactions20.TransactionCoder();
4679
5246
  const transactions = edges.map(
4680
- ({ node: { rawPayload } }) => coder.decode((0, import_utils23.arrayify)(rawPayload), 0)[0]
5247
+ ({ node: { rawPayload } }) => coder.decode((0, import_utils26.arrayify)(rawPayload), 0)[0]
4681
5248
  );
4682
5249
  return { transactions, pageInfo };
4683
5250
  }
@@ -4703,10 +5270,10 @@ Supported fuel-core version: ${supportedVersion}.`
4703
5270
  */
4704
5271
  async getContractBalance(contractId, assetId) {
4705
5272
  const { contractBalance } = await this.operations.getContractBalance({
4706
- contract: import_address3.Address.fromAddressOrString(contractId).toB256(),
4707
- asset: (0, import_utils23.hexlify)(assetId)
5273
+ contract: import_address4.Address.fromAddressOrString(contractId).toB256(),
5274
+ asset: (0, import_utils26.hexlify)(assetId)
4708
5275
  });
4709
- return (0, import_math17.bn)(contractBalance.amount, 10);
5276
+ return (0, import_math19.bn)(contractBalance.amount, 10);
4710
5277
  }
4711
5278
  /**
4712
5279
  * Returns the balance for the given owner for the given asset ID.
@@ -4717,10 +5284,10 @@ Supported fuel-core version: ${supportedVersion}.`
4717
5284
  */
4718
5285
  async getBalance(owner, assetId) {
4719
5286
  const { balance } = await this.operations.getBalance({
4720
- owner: import_address3.Address.fromAddressOrString(owner).toB256(),
4721
- assetId: (0, import_utils23.hexlify)(assetId)
5287
+ owner: import_address4.Address.fromAddressOrString(owner).toB256(),
5288
+ assetId: (0, import_utils26.hexlify)(assetId)
4722
5289
  });
4723
- return (0, import_math17.bn)(balance.amount, 10);
5290
+ return (0, import_math19.bn)(balance.amount, 10);
4724
5291
  }
4725
5292
  /**
4726
5293
  * Returns balances for the given owner.
@@ -4738,11 +5305,11 @@ Supported fuel-core version: ${supportedVersion}.`
4738
5305
  * but the current Fuel-Core implementation does not support pagination yet.
4739
5306
  */
4740
5307
  first: 1e4,
4741
- filter: { owner: import_address3.Address.fromAddressOrString(owner).toB256() }
5308
+ filter: { owner: import_address4.Address.fromAddressOrString(owner).toB256() }
4742
5309
  });
4743
5310
  const balances = edges.map(({ node }) => ({
4744
5311
  assetId: node.assetId,
4745
- amount: (0, import_math17.bn)(node.amount)
5312
+ amount: (0, import_math19.bn)(node.amount)
4746
5313
  }));
4747
5314
  return { balances };
4748
5315
  }
@@ -4761,22 +5328,22 @@ Supported fuel-core version: ${supportedVersion}.`
4761
5328
  inputArgs: paginationArgs,
4762
5329
  paginationLimit: RESOURCES_PAGE_SIZE_LIMIT
4763
5330
  }),
4764
- owner: import_address3.Address.fromAddressOrString(address).toB256()
5331
+ owner: import_address4.Address.fromAddressOrString(address).toB256()
4765
5332
  });
4766
5333
  const messages = edges.map(({ node }) => ({
4767
5334
  messageId: import_transactions20.InputMessageCoder.getMessageId({
4768
5335
  sender: node.sender,
4769
5336
  recipient: node.recipient,
4770
5337
  nonce: node.nonce,
4771
- amount: (0, import_math17.bn)(node.amount),
5338
+ amount: (0, import_math19.bn)(node.amount),
4772
5339
  data: node.data
4773
5340
  }),
4774
- sender: import_address3.Address.fromAddressOrString(node.sender),
4775
- recipient: import_address3.Address.fromAddressOrString(node.recipient),
5341
+ sender: import_address4.Address.fromAddressOrString(node.sender),
5342
+ recipient: import_address4.Address.fromAddressOrString(node.recipient),
4776
5343
  nonce: node.nonce,
4777
- amount: (0, import_math17.bn)(node.amount),
5344
+ amount: (0, import_math19.bn)(node.amount),
4778
5345
  data: import_transactions20.InputMessageCoder.decodeData(node.data),
4779
- daHeight: (0, import_math17.bn)(node.daHeight)
5346
+ daHeight: (0, import_math19.bn)(node.daHeight)
4780
5347
  }));
4781
5348
  return {
4782
5349
  messages,
@@ -4798,8 +5365,8 @@ Supported fuel-core version: ${supportedVersion}.`
4798
5365
  nonce
4799
5366
  };
4800
5367
  if (commitBlockId && commitBlockHeight) {
4801
- throw new import_errors14.FuelError(
4802
- import_errors14.ErrorCode.INVALID_INPUT_PARAMETERS,
5368
+ throw new import_errors16.FuelError(
5369
+ import_errors16.ErrorCode.INVALID_INPUT_PARAMETERS,
4803
5370
  "commitBlockId and commitBlockHeight cannot be used together"
4804
5371
  );
4805
5372
  }
@@ -4833,19 +5400,19 @@ Supported fuel-core version: ${supportedVersion}.`
4833
5400
  } = result.messageProof;
4834
5401
  return {
4835
5402
  messageProof: {
4836
- proofIndex: (0, import_math17.bn)(messageProof.proofIndex),
5403
+ proofIndex: (0, import_math19.bn)(messageProof.proofIndex),
4837
5404
  proofSet: messageProof.proofSet
4838
5405
  },
4839
5406
  blockProof: {
4840
- proofIndex: (0, import_math17.bn)(blockProof.proofIndex),
5407
+ proofIndex: (0, import_math19.bn)(blockProof.proofIndex),
4841
5408
  proofSet: blockProof.proofSet
4842
5409
  },
4843
5410
  messageBlockHeader: {
4844
5411
  id: messageBlockHeader.id,
4845
- daHeight: (0, import_math17.bn)(messageBlockHeader.daHeight),
5412
+ daHeight: (0, import_math19.bn)(messageBlockHeader.daHeight),
4846
5413
  transactionsCount: Number(messageBlockHeader.transactionsCount),
4847
5414
  transactionsRoot: messageBlockHeader.transactionsRoot,
4848
- height: (0, import_math17.bn)(messageBlockHeader.height),
5415
+ height: (0, import_math19.bn)(messageBlockHeader.height),
4849
5416
  prevRoot: messageBlockHeader.prevRoot,
4850
5417
  time: messageBlockHeader.time,
4851
5418
  applicationHash: messageBlockHeader.applicationHash,
@@ -4857,10 +5424,10 @@ Supported fuel-core version: ${supportedVersion}.`
4857
5424
  },
4858
5425
  commitBlockHeader: {
4859
5426
  id: commitBlockHeader.id,
4860
- daHeight: (0, import_math17.bn)(commitBlockHeader.daHeight),
5427
+ daHeight: (0, import_math19.bn)(commitBlockHeader.daHeight),
4861
5428
  transactionsCount: Number(commitBlockHeader.transactionsCount),
4862
5429
  transactionsRoot: commitBlockHeader.transactionsRoot,
4863
- height: (0, import_math17.bn)(commitBlockHeader.height),
5430
+ height: (0, import_math19.bn)(commitBlockHeader.height),
4864
5431
  prevRoot: commitBlockHeader.prevRoot,
4865
5432
  time: commitBlockHeader.time,
4866
5433
  applicationHash: commitBlockHeader.applicationHash,
@@ -4870,10 +5437,10 @@ Supported fuel-core version: ${supportedVersion}.`
4870
5437
  eventInboxRoot: commitBlockHeader.eventInboxRoot,
4871
5438
  stateTransitionBytecodeVersion: Number(commitBlockHeader.stateTransitionBytecodeVersion)
4872
5439
  },
4873
- sender: import_address3.Address.fromAddressOrString(sender),
4874
- recipient: import_address3.Address.fromAddressOrString(recipient),
5440
+ sender: import_address4.Address.fromAddressOrString(sender),
5441
+ recipient: import_address4.Address.fromAddressOrString(recipient),
4875
5442
  nonce,
4876
- amount: (0, import_math17.bn)(amount),
5443
+ amount: (0, import_math19.bn)(amount),
4877
5444
  data
4878
5445
  };
4879
5446
  }
@@ -4884,7 +5451,7 @@ Supported fuel-core version: ${supportedVersion}.`
4884
5451
  */
4885
5452
  async getLatestGasPrice() {
4886
5453
  const { latestGasPrice } = await this.operations.getLatestGasPrice();
4887
- return (0, import_math17.bn)(latestGasPrice.gasPrice);
5454
+ return (0, import_math19.bn)(latestGasPrice.gasPrice);
4888
5455
  }
4889
5456
  /**
4890
5457
  * Returns the estimate gas price for the given block horizon.
@@ -4896,7 +5463,7 @@ Supported fuel-core version: ${supportedVersion}.`
4896
5463
  const { estimateGasPrice } = await this.operations.estimateGasPrice({
4897
5464
  blockHorizon: String(blockHorizon)
4898
5465
  });
4899
- return (0, import_math17.bn)(estimateGasPrice.gasPrice);
5466
+ return (0, import_math19.bn)(estimateGasPrice.gasPrice);
4900
5467
  }
4901
5468
  /**
4902
5469
  * Returns Message Proof for given transaction id and the message id from MessageOut receipt.
@@ -4917,10 +5484,10 @@ Supported fuel-core version: ${supportedVersion}.`
4917
5484
  */
4918
5485
  async produceBlocks(amount, startTime) {
4919
5486
  const { produceBlocks: latestBlockHeight } = await this.operations.produceBlocks({
4920
- blocksToProduce: (0, import_math17.bn)(amount).toString(10),
4921
- startTimestamp: startTime ? import_utils23.DateTime.fromUnixMilliseconds(startTime).toTai64() : void 0
5487
+ blocksToProduce: (0, import_math19.bn)(amount).toString(10),
5488
+ startTimestamp: startTime ? import_utils26.DateTime.fromUnixMilliseconds(startTime).toTai64() : void 0
4922
5489
  });
4923
- return (0, import_math17.bn)(latestBlockHeight);
5490
+ return (0, import_math19.bn)(latestBlockHeight);
4924
5491
  }
4925
5492
  /**
4926
5493
  * Get the transaction response for the given transaction ID.
@@ -4967,26 +5534,26 @@ Supported fuel-core version: ${supportedVersion}.`
4967
5534
  const { paginationLimit, inputArgs = {} } = params;
4968
5535
  const { first, last, after, before } = inputArgs;
4969
5536
  if (after && before) {
4970
- throw new import_errors14.FuelError(
4971
- import_errors14.ErrorCode.INVALID_INPUT_PARAMETERS,
5537
+ throw new import_errors16.FuelError(
5538
+ import_errors16.ErrorCode.INVALID_INPUT_PARAMETERS,
4972
5539
  'Pagination arguments "after" and "before" cannot be used together'
4973
5540
  );
4974
5541
  }
4975
5542
  if ((first || 0) > paginationLimit || (last || 0) > paginationLimit) {
4976
- throw new import_errors14.FuelError(
4977
- import_errors14.ErrorCode.INVALID_INPUT_PARAMETERS,
5543
+ throw new import_errors16.FuelError(
5544
+ import_errors16.ErrorCode.INVALID_INPUT_PARAMETERS,
4978
5545
  `Pagination limit for this query cannot exceed ${paginationLimit} items`
4979
5546
  );
4980
5547
  }
4981
5548
  if (first && before) {
4982
- throw new import_errors14.FuelError(
4983
- import_errors14.ErrorCode.INVALID_INPUT_PARAMETERS,
5549
+ throw new import_errors16.FuelError(
5550
+ import_errors16.ErrorCode.INVALID_INPUT_PARAMETERS,
4984
5551
  'The use of pagination argument "first" with "before" is not supported'
4985
5552
  );
4986
5553
  }
4987
5554
  if (last && after) {
4988
- throw new import_errors14.FuelError(
4989
- import_errors14.ErrorCode.INVALID_INPUT_PARAMETERS,
5555
+ throw new import_errors16.FuelError(
5556
+ import_errors16.ErrorCode.INVALID_INPUT_PARAMETERS,
4990
5557
  'The use of pagination argument "last" with "after" is not supported'
4991
5558
  );
4992
5559
  }
@@ -5017,15 +5584,22 @@ Supported fuel-core version: ${supportedVersion}.`
5017
5584
  };
5018
5585
  var Provider = _Provider;
5019
5586
  _cacheInputs = new WeakSet();
5020
- cacheInputs_fn = function(inputs) {
5587
+ cacheInputs_fn = function(inputs, transactionId) {
5021
5588
  if (!this.cache) {
5022
5589
  return;
5023
5590
  }
5024
- inputs.forEach((input) => {
5025
- if (input.type === import_transactions20.InputType.Coin) {
5026
- this.cache?.set(input.id);
5027
- }
5028
- });
5591
+ const inputsToCache = inputs.reduce(
5592
+ (acc, input) => {
5593
+ if (input.type === import_transactions20.InputType.Coin) {
5594
+ acc.utxos.push(input.id);
5595
+ } else if (input.type === import_transactions20.InputType.Message) {
5596
+ acc.messages.push(input.nonce);
5597
+ }
5598
+ return acc;
5599
+ },
5600
+ { utxos: [], messages: [] }
5601
+ );
5602
+ this.cache.set(transactionId, inputsToCache);
5029
5603
  };
5030
5604
  /** @hidden */
5031
5605
  __publicField(Provider, "chainInfoCache", {});
@@ -5033,10 +5607,10 @@ __publicField(Provider, "chainInfoCache", {});
5033
5607
  __publicField(Provider, "nodeInfoCache", {});
5034
5608
 
5035
5609
  // src/providers/transaction-summary/get-transaction-summary.ts
5036
- var import_errors15 = require("@fuel-ts/errors");
5037
- var import_math18 = require("@fuel-ts/math");
5610
+ var import_errors17 = require("@fuel-ts/errors");
5611
+ var import_math20 = require("@fuel-ts/math");
5038
5612
  var import_transactions21 = require("@fuel-ts/transactions");
5039
- var import_utils26 = require("@fuel-ts/utils");
5613
+ var import_utils29 = require("@fuel-ts/utils");
5040
5614
 
5041
5615
  // src/providers/chains.ts
5042
5616
  var CHAIN_IDS = {
@@ -5109,19 +5683,75 @@ var rawAssets = [
5109
5683
  ];
5110
5684
  var assets = resolveIconPaths(rawAssets, fuelAssetsBaseUrl);
5111
5685
 
5686
+ // src/test-utils/test-asset-id.ts
5687
+ var import_crypto4 = require("@fuel-ts/crypto");
5688
+ var import_utils31 = require("@fuel-ts/utils");
5689
+ var _TestAssetId = class {
5690
+ constructor(value) {
5691
+ this.value = value;
5692
+ }
5693
+ static random(count = 1) {
5694
+ const assetIds = [];
5695
+ for (let i = 0; i < count; i++) {
5696
+ assetIds.push(new _TestAssetId((0, import_utils31.hexlify)((0, import_crypto4.randomBytes)(32))));
5697
+ }
5698
+ return assetIds;
5699
+ }
5700
+ };
5701
+ var TestAssetId = _TestAssetId;
5702
+ __publicField(TestAssetId, "A", new _TestAssetId(
5703
+ "0x0101010101010101010101010101010101010101010101010101010101010101"
5704
+ ));
5705
+ __publicField(TestAssetId, "B", new _TestAssetId(
5706
+ "0x0202020202020202020202020202020202020202020202020202020202020202"
5707
+ ));
5708
+
5709
+ // src/test-utils/wallet-config.ts
5710
+ var import_crypto9 = require("@fuel-ts/crypto");
5711
+ var import_errors23 = require("@fuel-ts/errors");
5712
+ var import_utils40 = require("@fuel-ts/utils");
5713
+
5714
+ // src/wallet/base-wallet-unlocked.ts
5715
+ var import_hasher3 = require("@fuel-ts/hasher");
5716
+ var import_utils35 = require("@fuel-ts/utils");
5717
+
5718
+ // src/account.ts
5719
+ var import_abi_coder8 = require("@fuel-ts/abi-coder");
5720
+ var import_address5 = require("@fuel-ts/address");
5721
+ var import_crypto5 = require("@fuel-ts/crypto");
5722
+ var import_errors18 = require("@fuel-ts/errors");
5723
+ var import_interfaces = require("@fuel-ts/interfaces");
5724
+ var import_math22 = require("@fuel-ts/math");
5725
+ var import_utils33 = require("@fuel-ts/utils");
5726
+ var import_ramda4 = require("ramda");
5727
+
5728
+ // src/providers/utils/merge-quantities.ts
5729
+ var mergeQuantities = (...coinQuantities) => {
5730
+ const resultMap = {};
5731
+ function addToMap({ amount, assetId }) {
5732
+ if (resultMap[assetId]) {
5733
+ resultMap[assetId] = resultMap[assetId].add(amount);
5734
+ } else {
5735
+ resultMap[assetId] = amount;
5736
+ }
5737
+ }
5738
+ coinQuantities.forEach((arr) => arr.forEach(addToMap));
5739
+ return Object.entries(resultMap).map(([assetId, amount]) => ({ assetId, amount }));
5740
+ };
5741
+
5112
5742
  // src/utils/formatTransferToContractScriptData.ts
5113
- var import_abi_coder6 = require("@fuel-ts/abi-coder");
5114
- var import_math19 = require("@fuel-ts/math");
5115
- var import_utils28 = require("@fuel-ts/utils");
5743
+ var import_abi_coder7 = require("@fuel-ts/abi-coder");
5744
+ var import_math21 = require("@fuel-ts/math");
5745
+ var import_utils32 = require("@fuel-ts/utils");
5116
5746
  var asm = __toESM(require("@fuels/vm-asm"));
5117
5747
  var formatTransferToContractScriptData = (params) => {
5118
5748
  const { assetId, amountToTransfer, hexlifiedContractId } = params;
5119
- const numberCoder = new import_abi_coder6.BigNumberCoder("u64");
5120
- const encoded = numberCoder.encode(new import_math19.BN(amountToTransfer).toNumber());
5749
+ const numberCoder = new import_abi_coder7.BigNumberCoder("u64");
5750
+ const encoded = numberCoder.encode(new import_math21.BN(amountToTransfer).toNumber());
5121
5751
  const scriptData = Uint8Array.from([
5122
- ...(0, import_utils28.arrayify)(hexlifiedContractId),
5752
+ ...(0, import_utils32.arrayify)(hexlifiedContractId),
5123
5753
  ...encoded,
5124
- ...(0, import_utils28.arrayify)(assetId)
5754
+ ...(0, import_utils32.arrayify)(assetId)
5125
5755
  ]);
5126
5756
  return scriptData;
5127
5757
  };
@@ -5146,7 +5776,7 @@ var assembleTransferToContractScript = async (params) => {
5146
5776
  };
5147
5777
 
5148
5778
  // src/account.ts
5149
- var MAX_FUNDING_ATTEMPTS = 2;
5779
+ var MAX_FUNDING_ATTEMPTS = 5;
5150
5780
  var Account = class extends import_interfaces.AbstractAccount {
5151
5781
  /**
5152
5782
  * The address associated with the account.
@@ -5171,7 +5801,7 @@ var Account = class extends import_interfaces.AbstractAccount {
5171
5801
  super();
5172
5802
  this._provider = provider;
5173
5803
  this._connector = connector;
5174
- this.address = import_address4.Address.fromDynamicInput(address);
5804
+ this.address = import_address5.Address.fromDynamicInput(address);
5175
5805
  }
5176
5806
  /**
5177
5807
  * The provider used to interact with the network.
@@ -5182,7 +5812,7 @@ var Account = class extends import_interfaces.AbstractAccount {
5182
5812
  */
5183
5813
  get provider() {
5184
5814
  if (!this._provider) {
5185
- throw new import_errors16.FuelError(import_errors16.ErrorCode.MISSING_PROVIDER, "Provider not set");
5815
+ throw new import_errors18.FuelError(import_errors18.ErrorCode.MISSING_PROVIDER, "Provider not set");
5186
5816
  }
5187
5817
  return this._provider;
5188
5818
  }
@@ -5259,12 +5889,12 @@ var Account = class extends import_interfaces.AbstractAccount {
5259
5889
  * @returns A promise that resolves to the funded transaction request.
5260
5890
  */
5261
5891
  async fund(request, params) {
5262
- const { addedSignatures, estimatedPredicates, requiredQuantities, updateMaxFee } = params;
5892
+ const { addedSignatures, estimatedPredicates, requiredQuantities, updateMaxFee, gasPrice } = params;
5263
5893
  const fee = request.maxFee;
5264
5894
  const baseAssetId = this.provider.getBaseAssetId();
5265
- const requiredInBaseAsset = requiredQuantities.find((quantity) => quantity.assetId === baseAssetId)?.amount || (0, import_math20.bn)(0);
5895
+ const requiredInBaseAsset = requiredQuantities.find((quantity) => quantity.assetId === baseAssetId)?.amount || (0, import_math22.bn)(0);
5266
5896
  const requiredQuantitiesWithFee = addAmountToCoinQuantities({
5267
- amount: (0, import_math20.bn)(fee),
5897
+ amount: (0, import_math22.bn)(fee),
5268
5898
  assetId: baseAssetId,
5269
5899
  coinQuantities: requiredQuantities
5270
5900
  });
@@ -5272,7 +5902,7 @@ var Account = class extends import_interfaces.AbstractAccount {
5272
5902
  requiredQuantitiesWithFee.forEach(({ amount, assetId }) => {
5273
5903
  quantitiesDict[assetId] = {
5274
5904
  required: amount,
5275
- owned: (0, import_math20.bn)(0)
5905
+ owned: (0, import_math22.bn)(0)
5276
5906
  };
5277
5907
  });
5278
5908
  request.inputs.filter(isRequestInputResource).forEach((input) => {
@@ -5307,10 +5937,12 @@ var Account = class extends import_interfaces.AbstractAccount {
5307
5937
  );
5308
5938
  }
5309
5939
  if (!updateMaxFee) {
5940
+ needsToBeFunded = false;
5310
5941
  break;
5311
5942
  }
5312
5943
  const { maxFee: newFee } = await this.provider.estimateTxGasAndFee({
5313
- transactionRequest: requestToReestimate2
5944
+ transactionRequest: requestToReestimate2,
5945
+ gasPrice
5314
5946
  });
5315
5947
  const totalBaseAssetOnInputs = getAssetAmountInRequestInputs(
5316
5948
  request.inputs,
@@ -5330,6 +5962,12 @@ var Account = class extends import_interfaces.AbstractAccount {
5330
5962
  }
5331
5963
  fundingAttempts += 1;
5332
5964
  }
5965
+ if (needsToBeFunded) {
5966
+ throw new import_errors18.FuelError(
5967
+ import_errors18.ErrorCode.NOT_ENOUGH_FUNDS,
5968
+ `The account ${this.address} does not have enough base asset funds to cover the transaction execution.`
5969
+ );
5970
+ }
5333
5971
  request.updatePredicateGasUsed(estimatedPredicates);
5334
5972
  const requestToReestimate = (0, import_ramda4.clone)(request);
5335
5973
  if (addedSignatures) {
@@ -5396,7 +6034,7 @@ var Account = class extends import_interfaces.AbstractAccount {
5396
6034
  const { destination, amount, assetId } = transferParams;
5397
6035
  this.validateTransferAmount(amount);
5398
6036
  request.addCoinOutput(
5399
- import_address4.Address.fromAddressOrString(destination),
6037
+ import_address5.Address.fromAddressOrString(destination),
5400
6038
  amount,
5401
6039
  assetId ?? this.provider.getBaseAssetId()
5402
6040
  );
@@ -5430,17 +6068,17 @@ var Account = class extends import_interfaces.AbstractAccount {
5430
6068
  * @returns A promise that resolves to the transaction response.
5431
6069
  */
5432
6070
  async transferToContract(contractId, amount, assetId, txParams = {}) {
5433
- if ((0, import_math20.bn)(amount).lte(0)) {
5434
- throw new import_errors16.FuelError(
5435
- import_errors16.ErrorCode.INVALID_TRANSFER_AMOUNT,
6071
+ if ((0, import_math22.bn)(amount).lte(0)) {
6072
+ throw new import_errors18.FuelError(
6073
+ import_errors18.ErrorCode.INVALID_TRANSFER_AMOUNT,
5436
6074
  "Transfer amount must be a positive number."
5437
6075
  );
5438
6076
  }
5439
- const contractAddress = import_address4.Address.fromAddressOrString(contractId);
6077
+ const contractAddress = import_address5.Address.fromAddressOrString(contractId);
5440
6078
  const assetIdToTransfer = assetId ?? this.provider.getBaseAssetId();
5441
6079
  const { script, scriptData } = await assembleTransferToContractScript({
5442
6080
  hexlifiedContractId: contractAddress.toB256(),
5443
- amountToTransfer: (0, import_math20.bn)(amount),
6081
+ amountToTransfer: (0, import_math22.bn)(amount),
5444
6082
  assetId: assetIdToTransfer
5445
6083
  });
5446
6084
  let request = new ScriptTransactionRequest({
@@ -5449,9 +6087,8 @@ var Account = class extends import_interfaces.AbstractAccount {
5449
6087
  scriptData
5450
6088
  });
5451
6089
  request.addContractInputAndOutput(contractAddress);
5452
- const txCost = await this.provider.getTransactionCost(request, {
5453
- resourcesOwner: this,
5454
- quantitiesToContract: [{ amount: (0, import_math20.bn)(amount), assetId: String(assetIdToTransfer) }]
6090
+ const txCost = await this.getTransactionCost(request, {
6091
+ quantities: [{ amount: (0, import_math22.bn)(amount), assetId: String(assetIdToTransfer) }]
5455
6092
  });
5456
6093
  request = this.validateGasLimitAndMaxFee({
5457
6094
  transactionRequest: request,
@@ -5471,23 +6108,23 @@ var Account = class extends import_interfaces.AbstractAccount {
5471
6108
  * @returns A promise that resolves to the transaction response.
5472
6109
  */
5473
6110
  async withdrawToBaseLayer(recipient, amount, txParams = {}) {
5474
- const recipientAddress = import_address4.Address.fromAddressOrString(recipient);
5475
- const recipientDataArray = (0, import_utils29.arrayify)(
6111
+ const recipientAddress = import_address5.Address.fromAddressOrString(recipient);
6112
+ const recipientDataArray = (0, import_utils33.arrayify)(
5476
6113
  "0x".concat(recipientAddress.toHexString().substring(2).padStart(64, "0"))
5477
6114
  );
5478
- const amountDataArray = (0, import_utils29.arrayify)(
5479
- "0x".concat((0, import_math20.bn)(amount).toHex().substring(2).padStart(16, "0"))
6115
+ const amountDataArray = (0, import_utils33.arrayify)(
6116
+ "0x".concat((0, import_math22.bn)(amount).toHex().substring(2).padStart(16, "0"))
5480
6117
  );
5481
6118
  const script = new Uint8Array([
5482
- ...(0, import_utils29.arrayify)(withdrawScript.bytes),
6119
+ ...(0, import_utils33.arrayify)(withdrawScript.bytes),
5483
6120
  ...recipientDataArray,
5484
6121
  ...amountDataArray
5485
6122
  ]);
5486
6123
  const params = { script, ...txParams };
5487
6124
  const baseAssetId = this.provider.getBaseAssetId();
5488
6125
  let request = new ScriptTransactionRequest(params);
5489
- const quantitiesToContract = [{ amount: (0, import_math20.bn)(amount), assetId: baseAssetId }];
5490
- const txCost = await this.provider.getTransactionCost(request, { quantitiesToContract });
6126
+ const quantities = [{ amount: (0, import_math22.bn)(amount), assetId: baseAssetId }];
6127
+ const txCost = await this.getTransactionCost(request, { quantities });
5491
6128
  request = this.validateGasLimitAndMaxFee({
5492
6129
  transactionRequest: request,
5493
6130
  gasUsed: txCost.gasUsed,
@@ -5497,6 +6134,58 @@ var Account = class extends import_interfaces.AbstractAccount {
5497
6134
  await this.fund(request, txCost);
5498
6135
  return this.sendTransaction(request);
5499
6136
  }
6137
+ /**
6138
+ * Returns a transaction cost to enable user
6139
+ * to set gasLimit and also reserve balance amounts
6140
+ * on the transaction.
6141
+ *
6142
+ * @param transactionRequestLike - The transaction request object.
6143
+ * @param transactionCostParams - The transaction cost parameters (optional).
6144
+ *
6145
+ * @returns A promise that resolves to the transaction cost object.
6146
+ */
6147
+ async getTransactionCost(transactionRequestLike, { signatureCallback, quantities = [] } = {}) {
6148
+ const txRequestClone = (0, import_ramda4.clone)(transactionRequestify(transactionRequestLike));
6149
+ const baseAssetId = this.provider.getBaseAssetId();
6150
+ const coinOutputsQuantities = txRequestClone.getCoinOutputsQuantities();
6151
+ const requiredQuantities = mergeQuantities(coinOutputsQuantities, quantities);
6152
+ const transactionFeeForDryRun = [{ assetId: baseAssetId, amount: (0, import_math22.bn)("100000000000000000") }];
6153
+ const findAssetInput = (assetId) => txRequestClone.inputs.find((input) => {
6154
+ if ("assetId" in input) {
6155
+ return input.assetId === assetId;
6156
+ }
6157
+ if ("recipient" in input) {
6158
+ return baseAssetId === assetId;
6159
+ }
6160
+ return false;
6161
+ });
6162
+ const updateAssetInput = (assetId, quantity) => {
6163
+ const assetInput = findAssetInput(assetId);
6164
+ const usedQuantity = quantity;
6165
+ if (assetInput && "amount" in assetInput) {
6166
+ assetInput.amount = usedQuantity;
6167
+ } else {
6168
+ txRequestClone.addResources(
6169
+ this.generateFakeResources([
6170
+ {
6171
+ amount: quantity,
6172
+ assetId
6173
+ }
6174
+ ])
6175
+ );
6176
+ }
6177
+ };
6178
+ mergeQuantities(requiredQuantities, transactionFeeForDryRun).forEach(
6179
+ ({ amount, assetId }) => updateAssetInput(assetId, amount)
6180
+ );
6181
+ const txCost = await this.provider.getTransactionCost(txRequestClone, {
6182
+ signatureCallback
6183
+ });
6184
+ return {
6185
+ ...txCost,
6186
+ requiredQuantities
6187
+ };
6188
+ }
5500
6189
  /**
5501
6190
  * Sign a message from the account via the connector.
5502
6191
  *
@@ -5507,7 +6196,7 @@ var Account = class extends import_interfaces.AbstractAccount {
5507
6196
  */
5508
6197
  async signMessage(message) {
5509
6198
  if (!this._connector) {
5510
- throw new import_errors16.FuelError(import_errors16.ErrorCode.MISSING_CONNECTOR, "A connector is required to sign messages.");
6199
+ throw new import_errors18.FuelError(import_errors18.ErrorCode.MISSING_CONNECTOR, "A connector is required to sign messages.");
5511
6200
  }
5512
6201
  return this._connector.signMessage(this.address.toString(), message);
5513
6202
  }
@@ -5519,8 +6208,8 @@ var Account = class extends import_interfaces.AbstractAccount {
5519
6208
  */
5520
6209
  async signTransaction(transactionRequestLike) {
5521
6210
  if (!this._connector) {
5522
- throw new import_errors16.FuelError(
5523
- import_errors16.ErrorCode.MISSING_CONNECTOR,
6211
+ throw new import_errors18.FuelError(
6212
+ import_errors18.ErrorCode.MISSING_CONNECTOR,
5524
6213
  "A connector is required to sign transactions."
5525
6214
  );
5526
6215
  }
@@ -5533,7 +6222,7 @@ var Account = class extends import_interfaces.AbstractAccount {
5533
6222
  * @param sendTransactionParams - The provider send transaction parameters (optional).
5534
6223
  * @returns A promise that resolves to the transaction response.
5535
6224
  */
5536
- async sendTransaction(transactionRequestLike, { estimateTxDependencies = true, awaitExecution } = {}) {
6225
+ async sendTransaction(transactionRequestLike, { estimateTxDependencies = true } = {}) {
5537
6226
  if (this._connector) {
5538
6227
  return this.provider.getTransactionResponse(
5539
6228
  await this._connector.sendTransaction(this.address.toString(), transactionRequestLike)
@@ -5544,7 +6233,6 @@ var Account = class extends import_interfaces.AbstractAccount {
5544
6233
  await this.provider.estimateTxDependencies(transactionRequest);
5545
6234
  }
5546
6235
  return this.provider.sendTransaction(transactionRequest, {
5547
- awaitExecution,
5548
6236
  estimateTxDependencies: false
5549
6237
  });
5550
6238
  }
@@ -5570,18 +6258,18 @@ var Account = class extends import_interfaces.AbstractAccount {
5570
6258
  */
5571
6259
  generateFakeResources(coins) {
5572
6260
  return coins.map((coin) => ({
5573
- id: (0, import_utils29.hexlify)((0, import_crypto2.randomBytes)(import_abi_coder7.UTXO_ID_LEN)),
6261
+ id: (0, import_utils33.hexlify)((0, import_crypto5.randomBytes)(import_abi_coder8.UTXO_ID_LEN)),
5574
6262
  owner: this.address,
5575
- blockCreated: (0, import_math20.bn)(1),
5576
- txCreatedIdx: (0, import_math20.bn)(1),
6263
+ blockCreated: (0, import_math22.bn)(1),
6264
+ txCreatedIdx: (0, import_math22.bn)(1),
5577
6265
  ...coin
5578
6266
  }));
5579
6267
  }
5580
6268
  /** @hidden * */
5581
6269
  validateTransferAmount(amount) {
5582
- if ((0, import_math20.bn)(amount).lte(0)) {
5583
- throw new import_errors16.FuelError(
5584
- import_errors16.ErrorCode.INVALID_TRANSFER_AMOUNT,
6270
+ if ((0, import_math22.bn)(amount).lte(0)) {
6271
+ throw new import_errors18.FuelError(
6272
+ import_errors18.ErrorCode.INVALID_TRANSFER_AMOUNT,
5585
6273
  "Transfer amount must be a positive number."
5586
6274
  );
5587
6275
  }
@@ -5589,9 +6277,7 @@ var Account = class extends import_interfaces.AbstractAccount {
5589
6277
  /** @hidden * */
5590
6278
  async estimateAndFundTransaction(transactionRequest, txParams) {
5591
6279
  let request = transactionRequest;
5592
- const txCost = await this.provider.getTransactionCost(request, {
5593
- resourcesOwner: this
5594
- });
6280
+ const txCost = await this.getTransactionCost(request);
5595
6281
  request = this.validateGasLimitAndMaxFee({
5596
6282
  transactionRequest: request,
5597
6283
  gasUsed: txCost.gasUsed,
@@ -5609,19 +6295,19 @@ var Account = class extends import_interfaces.AbstractAccount {
5609
6295
  txParams: { gasLimit: setGasLimit, maxFee: setMaxFee }
5610
6296
  }) {
5611
6297
  const request = transactionRequestify(transactionRequest);
5612
- if (!(0, import_utils29.isDefined)(setGasLimit)) {
6298
+ if (!(0, import_utils33.isDefined)(setGasLimit)) {
5613
6299
  request.gasLimit = gasUsed;
5614
6300
  } else if (gasUsed.gt(setGasLimit)) {
5615
- throw new import_errors16.FuelError(
5616
- import_errors16.ErrorCode.GAS_LIMIT_TOO_LOW,
6301
+ throw new import_errors18.FuelError(
6302
+ import_errors18.ErrorCode.GAS_LIMIT_TOO_LOW,
5617
6303
  `Gas limit '${setGasLimit}' is lower than the required: '${gasUsed}'.`
5618
6304
  );
5619
6305
  }
5620
- if (!(0, import_utils29.isDefined)(setMaxFee)) {
6306
+ if (!(0, import_utils33.isDefined)(setMaxFee)) {
5621
6307
  request.maxFee = maxFee;
5622
6308
  } else if (maxFee.gt(setMaxFee)) {
5623
- throw new import_errors16.FuelError(
5624
- import_errors16.ErrorCode.MAX_FEE_TOO_LOW,
6309
+ throw new import_errors18.FuelError(
6310
+ import_errors18.ErrorCode.MAX_FEE_TOO_LOW,
5625
6311
  `Max fee '${setMaxFee}' is lower than the required: '${maxFee}'.`
5626
6312
  );
5627
6313
  }
@@ -5629,121 +6315,11 @@ var Account = class extends import_interfaces.AbstractAccount {
5629
6315
  }
5630
6316
  };
5631
6317
 
5632
- // src/signer/signer.ts
5633
- var import_address5 = require("@fuel-ts/address");
5634
- var import_crypto3 = require("@fuel-ts/crypto");
5635
- var import_hasher2 = require("@fuel-ts/hasher");
5636
- var import_math21 = require("@fuel-ts/math");
5637
- var import_utils30 = require("@fuel-ts/utils");
5638
- var import_secp256k1 = require("@noble/curves/secp256k1");
5639
- var Signer = class {
5640
- address;
5641
- publicKey;
5642
- compressedPublicKey;
5643
- privateKey;
5644
- /**
5645
- * Create a Signer instance from a given private key
5646
- *
5647
- * @param privateKey - The private key to use for signing
5648
- * @returns A new Signer instance
5649
- */
5650
- constructor(privateKey) {
5651
- if (typeof privateKey === "string") {
5652
- if (privateKey.match(/^[0-9a-f]*$/i) && privateKey.length === 64) {
5653
- privateKey = `0x${privateKey}`;
5654
- }
5655
- }
5656
- const privateKeyBytes = (0, import_math21.toBytes)(privateKey, 32);
5657
- this.privateKey = (0, import_utils30.hexlify)(privateKeyBytes);
5658
- this.publicKey = (0, import_utils30.hexlify)(import_secp256k1.secp256k1.getPublicKey(privateKeyBytes, false).slice(1));
5659
- this.compressedPublicKey = (0, import_utils30.hexlify)(import_secp256k1.secp256k1.getPublicKey(privateKeyBytes, true));
5660
- this.address = import_address5.Address.fromPublicKey(this.publicKey);
5661
- }
5662
- /**
5663
- * Sign data using the Signer instance
5664
- *
5665
- * Signature is a 64 byte array of the concatenated r and s values with the compressed recoveryParam byte.
5666
- * @ignore
5667
- * [Read more](FuelLabs/fuel-specs/specs/protocol/cryptographic_primitives.md#public-key-cryptography)
5668
- *
5669
- * @param data - The data to be sign
5670
- * @returns hashed signature
5671
- */
5672
- sign(data) {
5673
- const signature = import_secp256k1.secp256k1.sign((0, import_utils30.arrayify)(data), (0, import_utils30.arrayify)(this.privateKey));
5674
- const r = (0, import_math21.toBytes)(`0x${signature.r.toString(16)}`, 32);
5675
- const s = (0, import_math21.toBytes)(`0x${signature.s.toString(16)}`, 32);
5676
- s[0] |= (signature.recovery || 0) << 7;
5677
- return (0, import_utils30.hexlify)((0, import_utils30.concat)([r, s]));
5678
- }
5679
- /**
5680
- * Add point on the current elliptic curve
5681
- *
5682
- * @param point - Point to add on the curve
5683
- * @returns compressed point on the curve
5684
- */
5685
- addPoint(point) {
5686
- const p0 = import_secp256k1.secp256k1.ProjectivePoint.fromHex((0, import_utils30.arrayify)(this.compressedPublicKey));
5687
- const p1 = import_secp256k1.secp256k1.ProjectivePoint.fromHex((0, import_utils30.arrayify)(point));
5688
- const result = p0.add(p1);
5689
- return `0x${result.toHex(true)}`;
5690
- }
5691
- /**
5692
- * Recover the public key from a signature performed with [`sign`](#sign).
5693
- *
5694
- * @param data - Data
5695
- * @param signature - hashed signature
5696
- * @returns public key from signature from the
5697
- */
5698
- static recoverPublicKey(data, signature) {
5699
- const signedMessageBytes = (0, import_utils30.arrayify)(signature);
5700
- const r = signedMessageBytes.slice(0, 32);
5701
- const s = signedMessageBytes.slice(32, 64);
5702
- const recoveryParam = (s[0] & 128) >> 7;
5703
- s[0] &= 127;
5704
- const sig = new import_secp256k1.secp256k1.Signature(BigInt((0, import_utils30.hexlify)(r)), BigInt((0, import_utils30.hexlify)(s))).addRecoveryBit(
5705
- recoveryParam
5706
- );
5707
- const publicKey = sig.recoverPublicKey((0, import_utils30.arrayify)(data)).toRawBytes(false).slice(1);
5708
- return (0, import_utils30.hexlify)(publicKey);
5709
- }
5710
- /**
5711
- * Recover the address from a signature performed with [`sign`](#sign).
5712
- *
5713
- * @param data - Data
5714
- * @param signature - Signature
5715
- * @returns Address from signature
5716
- */
5717
- static recoverAddress(data, signature) {
5718
- return import_address5.Address.fromPublicKey(Signer.recoverPublicKey(data, signature));
5719
- }
5720
- /**
5721
- * Generate a random privateKey
5722
- *
5723
- * @param entropy - Adds extra entropy to generate the privateKey
5724
- * @returns random 32-byte hashed
5725
- */
5726
- static generatePrivateKey(entropy) {
5727
- return entropy ? (0, import_hasher2.hash)((0, import_utils30.concat)([(0, import_crypto3.randomBytes)(32), (0, import_utils30.arrayify)(entropy)])) : (0, import_crypto3.randomBytes)(32);
5728
- }
5729
- /**
5730
- * Extended publicKey from a compact publicKey
5731
- *
5732
- * @param publicKey - Compact publicKey
5733
- * @returns extended publicKey
5734
- */
5735
- static extendPublicKey(publicKey) {
5736
- const point = import_secp256k1.secp256k1.ProjectivePoint.fromHex((0, import_utils30.arrayify)(publicKey));
5737
- return (0, import_utils30.hexlify)(point.toRawBytes(false).slice(1));
5738
- }
5739
- };
5740
-
5741
6318
  // src/wallet/keystore-wallet.ts
5742
6319
  var import_address6 = require("@fuel-ts/address");
5743
- var import_crypto4 = require("@fuel-ts/crypto");
5744
- var import_errors17 = require("@fuel-ts/errors");
5745
- var import_utils31 = require("@fuel-ts/utils");
5746
- var import_uuid = require("uuid");
6320
+ var import_crypto6 = require("@fuel-ts/crypto");
6321
+ var import_errors19 = require("@fuel-ts/errors");
6322
+ var import_utils34 = require("@fuel-ts/utils");
5747
6323
  var DEFAULT_KDF_PARAMS_LOG_N = 13;
5748
6324
  var DEFAULT_KDF_PARAMS_R = 8;
5749
6325
  var DEFAULT_KDF_PARAMS_P = 1;
@@ -5756,38 +6332,38 @@ var removeHexPrefix = (hexString) => {
5756
6332
  return hexString;
5757
6333
  };
5758
6334
  async function encryptKeystoreWallet(privateKey, address, password) {
5759
- const privateKeyBuffer = (0, import_crypto4.bufferFromString)(removeHexPrefix(privateKey), "hex");
6335
+ const privateKeyBuffer = (0, import_crypto6.bufferFromString)(removeHexPrefix(privateKey), "hex");
5760
6336
  const ownerAddress = import_address6.Address.fromAddressOrString(address);
5761
- const salt = (0, import_crypto4.randomBytes)(DEFAULT_KEY_SIZE);
5762
- const key = (0, import_crypto4.scrypt)({
5763
- password: (0, import_crypto4.bufferFromString)(password),
6337
+ const salt = (0, import_crypto6.randomBytes)(DEFAULT_KEY_SIZE);
6338
+ const key = (0, import_crypto6.scrypt)({
6339
+ password: (0, import_crypto6.bufferFromString)(password),
5764
6340
  salt,
5765
6341
  dklen: DEFAULT_KEY_SIZE,
5766
6342
  n: 2 ** DEFAULT_KDF_PARAMS_LOG_N,
5767
6343
  r: DEFAULT_KDF_PARAMS_R,
5768
6344
  p: DEFAULT_KDF_PARAMS_P
5769
6345
  });
5770
- const iv = (0, import_crypto4.randomBytes)(DEFAULT_IV_SIZE);
5771
- const ciphertext = await (0, import_crypto4.encryptJsonWalletData)(privateKeyBuffer, key, iv);
6346
+ const iv = (0, import_crypto6.randomBytes)(DEFAULT_IV_SIZE);
6347
+ const ciphertext = await (0, import_crypto6.encryptJsonWalletData)(privateKeyBuffer, key, iv);
5772
6348
  const data = Uint8Array.from([...key.subarray(16, 32), ...ciphertext]);
5773
- const macHashUint8Array = (0, import_crypto4.keccak256)(data);
5774
- const mac = (0, import_crypto4.stringFromBuffer)(macHashUint8Array, "hex");
6349
+ const macHashUint8Array = (0, import_crypto6.keccak256)(data);
6350
+ const mac = (0, import_crypto6.stringFromBuffer)(macHashUint8Array, "hex");
5775
6351
  const keystore = {
5776
- id: (0, import_uuid.v4)(),
6352
+ id: (0, import_crypto6.randomUUID)(),
5777
6353
  version: 3,
5778
6354
  address: removeHexPrefix(ownerAddress.toHexString()),
5779
6355
  crypto: {
5780
6356
  cipher: "aes-128-ctr",
5781
6357
  mac,
5782
- cipherparams: { iv: (0, import_crypto4.stringFromBuffer)(iv, "hex") },
5783
- ciphertext: (0, import_crypto4.stringFromBuffer)(ciphertext, "hex"),
6358
+ cipherparams: { iv: (0, import_crypto6.stringFromBuffer)(iv, "hex") },
6359
+ ciphertext: (0, import_crypto6.stringFromBuffer)(ciphertext, "hex"),
5784
6360
  kdf: "scrypt",
5785
6361
  kdfparams: {
5786
6362
  dklen: DEFAULT_KEY_SIZE,
5787
6363
  n: 2 ** DEFAULT_KDF_PARAMS_LOG_N,
5788
6364
  p: DEFAULT_KDF_PARAMS_P,
5789
6365
  r: DEFAULT_KDF_PARAMS_R,
5790
- salt: (0, import_crypto4.stringFromBuffer)(salt, "hex")
6366
+ salt: (0, import_crypto6.stringFromBuffer)(salt, "hex")
5791
6367
  }
5792
6368
  }
5793
6369
  };
@@ -5803,11 +6379,11 @@ async function decryptKeystoreWallet(jsonWallet, password) {
5803
6379
  kdfparams: { dklen, n, r, p, salt }
5804
6380
  }
5805
6381
  } = keystoreWallet;
5806
- const ciphertextBuffer = (0, import_crypto4.bufferFromString)(ciphertext, "hex");
5807
- const ivBuffer = (0, import_crypto4.bufferFromString)(iv, "hex");
5808
- const saltBuffer = (0, import_crypto4.bufferFromString)(salt, "hex");
5809
- const passwordBuffer = (0, import_crypto4.bufferFromString)(password);
5810
- const key = (0, import_crypto4.scrypt)({
6382
+ const ciphertextBuffer = (0, import_crypto6.bufferFromString)(ciphertext, "hex");
6383
+ const ivBuffer = (0, import_crypto6.bufferFromString)(iv, "hex");
6384
+ const saltBuffer = (0, import_crypto6.bufferFromString)(salt, "hex");
6385
+ const passwordBuffer = (0, import_crypto6.bufferFromString)(password);
6386
+ const key = (0, import_crypto6.scrypt)({
5811
6387
  password: passwordBuffer,
5812
6388
  salt: saltBuffer,
5813
6389
  n,
@@ -5816,16 +6392,16 @@ async function decryptKeystoreWallet(jsonWallet, password) {
5816
6392
  dklen
5817
6393
  });
5818
6394
  const data = Uint8Array.from([...key.subarray(16, 32), ...ciphertextBuffer]);
5819
- const macHashUint8Array = (0, import_crypto4.keccak256)(data);
5820
- const macHash = (0, import_crypto4.stringFromBuffer)(macHashUint8Array, "hex");
6395
+ const macHashUint8Array = (0, import_crypto6.keccak256)(data);
6396
+ const macHash = (0, import_crypto6.stringFromBuffer)(macHashUint8Array, "hex");
5821
6397
  if (mac !== macHash) {
5822
- throw new import_errors17.FuelError(
5823
- import_errors17.ErrorCode.INVALID_PASSWORD,
6398
+ throw new import_errors19.FuelError(
6399
+ import_errors19.ErrorCode.INVALID_PASSWORD,
5824
6400
  "Failed to decrypt the keystore wallet, the provided password is incorrect."
5825
6401
  );
5826
6402
  }
5827
- const buffer = await (0, import_crypto4.decryptJsonWalletData)(ciphertextBuffer, key, ivBuffer);
5828
- const privateKey = (0, import_utils31.hexlify)(buffer);
6403
+ const buffer = await (0, import_crypto6.decryptJsonWalletData)(ciphertextBuffer, key, ivBuffer);
6404
+ const privateKey = (0, import_utils34.hexlify)(buffer);
5829
6405
  return privateKey;
5830
6406
  }
5831
6407
 
@@ -5870,7 +6446,7 @@ var BaseWalletUnlocked = class extends Account {
5870
6446
  */
5871
6447
  async signMessage(message) {
5872
6448
  const signedMessage = await this.signer().sign((0, import_hasher3.hashMessage)(message));
5873
- return (0, import_utils32.hexlify)(signedMessage);
6449
+ return (0, import_utils35.hexlify)(signedMessage);
5874
6450
  }
5875
6451
  /**
5876
6452
  * Signs a transaction with the wallet's private key.
@@ -5883,7 +6459,7 @@ var BaseWalletUnlocked = class extends Account {
5883
6459
  const chainId = this.provider.getChainId();
5884
6460
  const hashedTransaction = transactionRequest.getTransactionId(chainId);
5885
6461
  const signature = await this.signer().sign(hashedTransaction);
5886
- return (0, import_utils32.hexlify)(signature);
6462
+ return (0, import_utils35.hexlify)(signature);
5887
6463
  }
5888
6464
  /**
5889
6465
  * Populates a transaction with the witnesses signature.
@@ -5902,17 +6478,16 @@ var BaseWalletUnlocked = class extends Account {
5902
6478
  *
5903
6479
  * @param transactionRequestLike - The transaction request to send.
5904
6480
  * @param estimateTxDependencies - Whether to estimate the transaction dependencies.
5905
- * @param awaitExecution - Whether to wait for the transaction to be executed.
5906
6481
  * @returns A promise that resolves to the TransactionResponse object.
5907
6482
  */
5908
- async sendTransaction(transactionRequestLike, { estimateTxDependencies = false, awaitExecution } = {}) {
6483
+ async sendTransaction(transactionRequestLike, { estimateTxDependencies = false } = {}) {
5909
6484
  const transactionRequest = transactionRequestify(transactionRequestLike);
5910
6485
  if (estimateTxDependencies) {
5911
6486
  await this.provider.estimateTxDependencies(transactionRequest);
5912
6487
  }
5913
6488
  return this.provider.sendTransaction(
5914
6489
  await this.populateTransactionWitnessesSignature(transactionRequest),
5915
- { awaitExecution, estimateTxDependencies: false }
6490
+ { estimateTxDependencies: false }
5916
6491
  );
5917
6492
  }
5918
6493
  /**
@@ -5950,17 +6525,17 @@ var BaseWalletUnlocked = class extends Account {
5950
6525
  __publicField(BaseWalletUnlocked, "defaultPath", "m/44'/1179993420'/0'/0/0");
5951
6526
 
5952
6527
  // src/hdwallet/hdwallet.ts
5953
- var import_crypto6 = require("@fuel-ts/crypto");
5954
- var import_errors20 = require("@fuel-ts/errors");
6528
+ var import_crypto8 = require("@fuel-ts/crypto");
6529
+ var import_errors22 = require("@fuel-ts/errors");
5955
6530
  var import_hasher6 = require("@fuel-ts/hasher");
5956
- var import_math22 = require("@fuel-ts/math");
5957
- var import_utils36 = require("@fuel-ts/utils");
6531
+ var import_math23 = require("@fuel-ts/math");
6532
+ var import_utils39 = require("@fuel-ts/utils");
5958
6533
 
5959
6534
  // src/mnemonic/mnemonic.ts
5960
- var import_crypto5 = require("@fuel-ts/crypto");
5961
- var import_errors19 = require("@fuel-ts/errors");
6535
+ var import_crypto7 = require("@fuel-ts/crypto");
6536
+ var import_errors21 = require("@fuel-ts/errors");
5962
6537
  var import_hasher5 = require("@fuel-ts/hasher");
5963
- var import_utils34 = require("@fuel-ts/utils");
6538
+ var import_utils37 = require("@fuel-ts/utils");
5964
6539
 
5965
6540
  // src/wordlists/words/english.ts
5966
6541
  var english = [
@@ -8015,9 +8590,9 @@ var english = [
8015
8590
  ];
8016
8591
 
8017
8592
  // src/mnemonic/utils.ts
8018
- var import_errors18 = require("@fuel-ts/errors");
8593
+ var import_errors20 = require("@fuel-ts/errors");
8019
8594
  var import_hasher4 = require("@fuel-ts/hasher");
8020
- var import_utils33 = require("@fuel-ts/utils");
8595
+ var import_utils36 = require("@fuel-ts/utils");
8021
8596
  function getLowerMask(bits) {
8022
8597
  return (1 << bits) - 1;
8023
8598
  }
@@ -8052,20 +8627,20 @@ function entropyToMnemonicIndices(entropy) {
8052
8627
  }
8053
8628
  }
8054
8629
  const checksumBits = entropy.length / 4;
8055
- const checksum = (0, import_utils33.arrayify)((0, import_hasher4.sha256)(entropy))[0] & getUpperMask(checksumBits);
8630
+ const checksum = (0, import_utils36.arrayify)((0, import_hasher4.sha256)(entropy))[0] & getUpperMask(checksumBits);
8056
8631
  indices[indices.length - 1] <<= checksumBits;
8057
8632
  indices[indices.length - 1] |= checksum >> 8 - checksumBits;
8058
8633
  return indices;
8059
8634
  }
8060
8635
  function mnemonicWordsToEntropy(words, wordlist) {
8061
8636
  const size = Math.ceil(11 * words.length / 8);
8062
- const entropy = (0, import_utils33.arrayify)(new Uint8Array(size));
8637
+ const entropy = (0, import_utils36.arrayify)(new Uint8Array(size));
8063
8638
  let offset = 0;
8064
8639
  for (let i = 0; i < words.length; i += 1) {
8065
8640
  const index = wordlist.indexOf(words[i].normalize("NFKD"));
8066
8641
  if (index === -1) {
8067
- throw new import_errors18.FuelError(
8068
- import_errors18.ErrorCode.INVALID_MNEMONIC,
8642
+ throw new import_errors20.FuelError(
8643
+ import_errors20.ErrorCode.INVALID_MNEMONIC,
8069
8644
  `Invalid mnemonic: the word '${words[i]}' is not found in the provided wordlist.`
8070
8645
  );
8071
8646
  }
@@ -8079,10 +8654,10 @@ function mnemonicWordsToEntropy(words, wordlist) {
8079
8654
  const entropyBits = 32 * words.length / 3;
8080
8655
  const checksumBits = words.length / 3;
8081
8656
  const checksumMask = getUpperMask(checksumBits);
8082
- const checksum = (0, import_utils33.arrayify)((0, import_hasher4.sha256)(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
8657
+ const checksum = (0, import_utils36.arrayify)((0, import_hasher4.sha256)(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
8083
8658
  if (checksum !== (entropy[entropy.length - 1] & checksumMask)) {
8084
- throw new import_errors18.FuelError(
8085
- import_errors18.ErrorCode.INVALID_CHECKSUM,
8659
+ throw new import_errors20.FuelError(
8660
+ import_errors20.ErrorCode.INVALID_CHECKSUM,
8086
8661
  "Checksum validation failed for the provided mnemonic."
8087
8662
  );
8088
8663
  }
@@ -8090,22 +8665,22 @@ function mnemonicWordsToEntropy(words, wordlist) {
8090
8665
  }
8091
8666
 
8092
8667
  // src/mnemonic/mnemonic.ts
8093
- var MasterSecret = (0, import_utils34.toUtf8Bytes)("Bitcoin seed");
8668
+ var MasterSecret = (0, import_utils37.toUtf8Bytes)("Bitcoin seed");
8094
8669
  var MainnetPRV = "0x0488ade4";
8095
8670
  var TestnetPRV = "0x04358394";
8096
8671
  var MNEMONIC_SIZES = [12, 15, 18, 21, 24];
8097
8672
  function assertWordList(wordlist) {
8098
8673
  if (wordlist.length !== 2048) {
8099
- throw new import_errors19.FuelError(
8100
- import_errors19.ErrorCode.INVALID_WORD_LIST,
8674
+ throw new import_errors21.FuelError(
8675
+ import_errors21.ErrorCode.INVALID_WORD_LIST,
8101
8676
  `Expected word list length of 2048, but got ${wordlist.length}.`
8102
8677
  );
8103
8678
  }
8104
8679
  }
8105
8680
  function assertEntropy(entropy) {
8106
8681
  if (entropy.length % 4 !== 0 || entropy.length < 16 || entropy.length > 32) {
8107
- throw new import_errors19.FuelError(
8108
- import_errors19.ErrorCode.INVALID_ENTROPY,
8682
+ throw new import_errors21.FuelError(
8683
+ import_errors21.ErrorCode.INVALID_ENTROPY,
8109
8684
  `Entropy should be between 16 and 32 bytes and a multiple of 4, but got ${entropy.length} bytes.`
8110
8685
  );
8111
8686
  }
@@ -8115,7 +8690,7 @@ function assertMnemonic(words) {
8115
8690
  const errorMsg = `Invalid mnemonic size. Expected one of [${MNEMONIC_SIZES.join(
8116
8691
  ", "
8117
8692
  )}] words, but got ${words.length}.`;
8118
- throw new import_errors19.FuelError(import_errors19.ErrorCode.INVALID_MNEMONIC, errorMsg);
8693
+ throw new import_errors21.FuelError(import_errors21.ErrorCode.INVALID_MNEMONIC, errorMsg);
8119
8694
  }
8120
8695
  }
8121
8696
  var Mnemonic = class {
@@ -8154,7 +8729,7 @@ var Mnemonic = class {
8154
8729
  static mnemonicToEntropy(phrase, wordlist = english) {
8155
8730
  const words = getWords(phrase);
8156
8731
  assertMnemonic(words);
8157
- return (0, import_utils34.hexlify)(mnemonicWordsToEntropy(words, wordlist));
8732
+ return (0, import_utils37.hexlify)(mnemonicWordsToEntropy(words, wordlist));
8158
8733
  }
8159
8734
  /**
8160
8735
  * @param entropy - Entropy source to the mnemonic phrase.
@@ -8162,7 +8737,7 @@ var Mnemonic = class {
8162
8737
  * @returns 64-byte array contains privateKey and chainCode as described on BIP39
8163
8738
  */
8164
8739
  static entropyToMnemonic(entropy, wordlist = english) {
8165
- const entropyBytes = (0, import_utils34.arrayify)(entropy);
8740
+ const entropyBytes = (0, import_utils37.arrayify)(entropy);
8166
8741
  assertWordList(wordlist);
8167
8742
  assertEntropy(entropyBytes);
8168
8743
  return entropyToMnemonicIndices(entropyBytes).map((i) => wordlist[i]).join(" ");
@@ -8174,9 +8749,9 @@ var Mnemonic = class {
8174
8749
  */
8175
8750
  static mnemonicToSeed(phrase, passphrase = "") {
8176
8751
  assertMnemonic(getWords(phrase));
8177
- const phraseBytes = (0, import_utils34.toUtf8Bytes)(getPhrase(phrase));
8178
- const salt = (0, import_utils34.toUtf8Bytes)(`mnemonic${passphrase}`);
8179
- return (0, import_crypto5.pbkdf2)(phraseBytes, salt, 2048, 64, "sha512");
8752
+ const phraseBytes = (0, import_utils37.toUtf8Bytes)(getPhrase(phrase));
8753
+ const salt = (0, import_utils37.toUtf8Bytes)(`mnemonic${passphrase}`);
8754
+ return (0, import_crypto7.pbkdf2)(phraseBytes, salt, 2048, 64, "sha512");
8180
8755
  }
8181
8756
  /**
8182
8757
  * @param phrase - Mnemonic phrase composed by words from the provided wordlist
@@ -8231,14 +8806,14 @@ var Mnemonic = class {
8231
8806
  * @returns 64-byte array contains privateKey and chainCode as described on BIP39
8232
8807
  */
8233
8808
  static masterKeysFromSeed(seed) {
8234
- const seedArray = (0, import_utils34.arrayify)(seed);
8809
+ const seedArray = (0, import_utils37.arrayify)(seed);
8235
8810
  if (seedArray.length < 16 || seedArray.length > 64) {
8236
- throw new import_errors19.FuelError(
8237
- import_errors19.ErrorCode.INVALID_SEED,
8811
+ throw new import_errors21.FuelError(
8812
+ import_errors21.ErrorCode.INVALID_SEED,
8238
8813
  `Seed length should be between 16 and 64 bytes, but received ${seedArray.length} bytes.`
8239
8814
  );
8240
8815
  }
8241
- return (0, import_utils34.arrayify)((0, import_crypto5.computeHmac)("sha512", MasterSecret, seedArray));
8816
+ return (0, import_utils37.arrayify)((0, import_crypto7.computeHmac)("sha512", MasterSecret, seedArray));
8242
8817
  }
8243
8818
  /**
8244
8819
  * Get the extendKey as defined on BIP-32 from the provided seed
@@ -8249,22 +8824,22 @@ var Mnemonic = class {
8249
8824
  */
8250
8825
  static seedToExtendedKey(seed, testnet = false) {
8251
8826
  const masterKey = Mnemonic.masterKeysFromSeed(seed);
8252
- const prefix = (0, import_utils34.arrayify)(testnet ? TestnetPRV : MainnetPRV);
8827
+ const prefix = (0, import_utils37.arrayify)(testnet ? TestnetPRV : MainnetPRV);
8253
8828
  const depth = "0x00";
8254
8829
  const fingerprint = "0x00000000";
8255
8830
  const index = "0x00000000";
8256
8831
  const chainCode = masterKey.slice(32);
8257
8832
  const privateKey = masterKey.slice(0, 32);
8258
- const extendedKey = (0, import_utils34.concat)([
8833
+ const extendedKey = (0, import_utils37.concat)([
8259
8834
  prefix,
8260
8835
  depth,
8261
8836
  fingerprint,
8262
8837
  index,
8263
8838
  chainCode,
8264
- (0, import_utils34.concat)(["0x00", privateKey])
8839
+ (0, import_utils37.concat)(["0x00", privateKey])
8265
8840
  ]);
8266
- const checksum = (0, import_utils34.dataSlice)((0, import_hasher5.sha256)((0, import_hasher5.sha256)(extendedKey)), 0, 4);
8267
- return (0, import_utils34.encodeBase58)((0, import_utils34.concat)([extendedKey, checksum]));
8841
+ const checksum = (0, import_utils37.dataSlice)((0, import_hasher5.sha256)((0, import_hasher5.sha256)(extendedKey)), 0, 4);
8842
+ return (0, import_utils37.encodeBase58)((0, import_utils37.concat)([extendedKey, checksum]));
8268
8843
  }
8269
8844
  /**
8270
8845
  * Create a new mnemonic using a randomly generated number as entropy.
@@ -8279,7 +8854,7 @@ var Mnemonic = class {
8279
8854
  * @returns A randomly generated mnemonic
8280
8855
  */
8281
8856
  static generate(size = 32, extraEntropy = "") {
8282
- const entropy = extraEntropy ? (0, import_hasher5.sha256)((0, import_utils34.concat)([(0, import_crypto5.randomBytes)(size), (0, import_utils34.arrayify)(extraEntropy)])) : (0, import_crypto5.randomBytes)(size);
8857
+ const entropy = extraEntropy ? (0, import_hasher5.sha256)((0, import_utils37.concat)([(0, import_crypto7.randomBytes)(size), (0, import_utils37.arrayify)(extraEntropy)])) : (0, import_crypto7.randomBytes)(size);
8283
8858
  return Mnemonic.entropyToMnemonic(entropy);
8284
8859
  }
8285
8860
  };
@@ -8287,12 +8862,12 @@ var mnemonic_default = Mnemonic;
8287
8862
 
8288
8863
  // src/hdwallet/hdwallet.ts
8289
8864
  var HARDENED_INDEX = 2147483648;
8290
- var MainnetPRV2 = (0, import_utils36.hexlify)("0x0488ade4");
8291
- var MainnetPUB = (0, import_utils36.hexlify)("0x0488b21e");
8292
- var TestnetPRV2 = (0, import_utils36.hexlify)("0x04358394");
8293
- var TestnetPUB = (0, import_utils36.hexlify)("0x043587cf");
8865
+ var MainnetPRV2 = (0, import_utils39.hexlify)("0x0488ade4");
8866
+ var MainnetPUB = (0, import_utils39.hexlify)("0x0488b21e");
8867
+ var TestnetPRV2 = (0, import_utils39.hexlify)("0x04358394");
8868
+ var TestnetPUB = (0, import_utils39.hexlify)("0x043587cf");
8294
8869
  function base58check(data) {
8295
- return (0, import_utils36.encodeBase58)((0, import_utils36.concat)([data, (0, import_utils36.dataSlice)((0, import_hasher6.sha256)((0, import_hasher6.sha256)(data)), 0, 4)]));
8870
+ return (0, import_utils39.encodeBase58)((0, import_utils39.concat)([data, (0, import_utils39.dataSlice)((0, import_hasher6.sha256)((0, import_hasher6.sha256)(data)), 0, 4)]));
8296
8871
  }
8297
8872
  function getExtendedKeyPrefix(isPublic = false, testnet = false) {
8298
8873
  if (isPublic) {
@@ -8301,17 +8876,17 @@ function getExtendedKeyPrefix(isPublic = false, testnet = false) {
8301
8876
  return testnet ? TestnetPRV2 : MainnetPRV2;
8302
8877
  }
8303
8878
  function isPublicExtendedKey(extendedKey) {
8304
- return [MainnetPUB, TestnetPUB].includes((0, import_utils36.hexlify)(extendedKey.slice(0, 4)));
8879
+ return [MainnetPUB, TestnetPUB].includes((0, import_utils39.hexlify)(extendedKey.slice(0, 4)));
8305
8880
  }
8306
8881
  function isValidExtendedKey(extendedKey) {
8307
8882
  return [MainnetPRV2, TestnetPRV2, MainnetPUB, TestnetPUB].includes(
8308
- (0, import_utils36.hexlify)(extendedKey.slice(0, 4))
8883
+ (0, import_utils39.hexlify)(extendedKey.slice(0, 4))
8309
8884
  );
8310
8885
  }
8311
8886
  function parsePath(path2, depth = 0) {
8312
8887
  const components = path2.split("/");
8313
8888
  if (components.length === 0 || components[0] === "m" && depth !== 0) {
8314
- throw new import_errors20.FuelError(import_errors20.ErrorCode.HD_WALLET_ERROR, `invalid path - ${path2}`);
8889
+ throw new import_errors22.FuelError(import_errors22.ErrorCode.HD_WALLET_ERROR, `invalid path - ${path2}`);
8315
8890
  }
8316
8891
  if (components[0] === "m") {
8317
8892
  components.shift();
@@ -8323,8 +8898,8 @@ function parsePath(path2, depth = 0) {
8323
8898
  var HDWallet = class {
8324
8899
  depth = 0;
8325
8900
  index = 0;
8326
- fingerprint = (0, import_utils36.hexlify)("0x00000000");
8327
- parentFingerprint = (0, import_utils36.hexlify)("0x00000000");
8901
+ fingerprint = (0, import_utils39.hexlify)("0x00000000");
8902
+ parentFingerprint = (0, import_utils39.hexlify)("0x00000000");
8328
8903
  privateKey;
8329
8904
  publicKey;
8330
8905
  chainCode;
@@ -8336,19 +8911,19 @@ var HDWallet = class {
8336
8911
  constructor(config) {
8337
8912
  if (config.privateKey) {
8338
8913
  const signer = new Signer(config.privateKey);
8339
- this.publicKey = (0, import_utils36.hexlify)(signer.compressedPublicKey);
8340
- this.privateKey = (0, import_utils36.hexlify)(config.privateKey);
8914
+ this.publicKey = (0, import_utils39.hexlify)(signer.compressedPublicKey);
8915
+ this.privateKey = (0, import_utils39.hexlify)(config.privateKey);
8341
8916
  } else {
8342
8917
  if (!config.publicKey) {
8343
- throw new import_errors20.FuelError(
8344
- import_errors20.ErrorCode.HD_WALLET_ERROR,
8918
+ throw new import_errors22.FuelError(
8919
+ import_errors22.ErrorCode.HD_WALLET_ERROR,
8345
8920
  "Both public and private Key cannot be missing. At least one should be provided."
8346
8921
  );
8347
8922
  }
8348
- this.publicKey = (0, import_utils36.hexlify)(config.publicKey);
8923
+ this.publicKey = (0, import_utils39.hexlify)(config.publicKey);
8349
8924
  }
8350
8925
  this.parentFingerprint = config.parentFingerprint || this.parentFingerprint;
8351
- this.fingerprint = (0, import_utils36.dataSlice)((0, import_crypto6.ripemd160)((0, import_hasher6.sha256)(this.publicKey)), 0, 4);
8926
+ this.fingerprint = (0, import_utils39.dataSlice)((0, import_crypto8.ripemd160)((0, import_hasher6.sha256)(this.publicKey)), 0, 4);
8352
8927
  this.depth = config.depth || this.depth;
8353
8928
  this.index = config.index || this.index;
8354
8929
  this.chainCode = config.chainCode;
@@ -8364,28 +8939,28 @@ var HDWallet = class {
8364
8939
  * @returns A new instance of HDWallet on the derived index
8365
8940
  */
8366
8941
  deriveIndex(index) {
8367
- const privateKey = this.privateKey && (0, import_utils36.arrayify)(this.privateKey);
8368
- const publicKey = (0, import_utils36.arrayify)(this.publicKey);
8369
- const chainCode = (0, import_utils36.arrayify)(this.chainCode);
8942
+ const privateKey = this.privateKey && (0, import_utils39.arrayify)(this.privateKey);
8943
+ const publicKey = (0, import_utils39.arrayify)(this.publicKey);
8944
+ const chainCode = (0, import_utils39.arrayify)(this.chainCode);
8370
8945
  const data = new Uint8Array(37);
8371
8946
  if (index & HARDENED_INDEX) {
8372
8947
  if (!privateKey) {
8373
- throw new import_errors20.FuelError(
8374
- import_errors20.ErrorCode.HD_WALLET_ERROR,
8948
+ throw new import_errors22.FuelError(
8949
+ import_errors22.ErrorCode.HD_WALLET_ERROR,
8375
8950
  "Cannot derive a hardened index without a private Key."
8376
8951
  );
8377
8952
  }
8378
8953
  data.set(privateKey, 1);
8379
8954
  } else {
8380
- data.set((0, import_utils36.arrayify)(this.publicKey));
8955
+ data.set((0, import_utils39.arrayify)(this.publicKey));
8381
8956
  }
8382
- data.set((0, import_math22.toBytes)(index, 4), 33);
8383
- const bytes = (0, import_utils36.arrayify)((0, import_crypto6.computeHmac)("sha512", chainCode, data));
8957
+ data.set((0, import_math23.toBytes)(index, 4), 33);
8958
+ const bytes = (0, import_utils39.arrayify)((0, import_crypto8.computeHmac)("sha512", chainCode, data));
8384
8959
  const IL = bytes.slice(0, 32);
8385
8960
  const IR = bytes.slice(32);
8386
8961
  if (privateKey) {
8387
8962
  const N = "0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141";
8388
- const ki = (0, import_math22.bn)(IL).add(privateKey).mod(N).toBytes(32);
8963
+ const ki = (0, import_math23.bn)(IL).add(privateKey).mod(N).toBytes(32);
8389
8964
  return new HDWallet({
8390
8965
  privateKey: ki,
8391
8966
  chainCode: IR,
@@ -8394,7 +8969,7 @@ var HDWallet = class {
8394
8969
  parentFingerprint: this.fingerprint
8395
8970
  });
8396
8971
  }
8397
- const signer = new Signer((0, import_utils36.hexlify)(IL));
8972
+ const signer = new Signer((0, import_utils39.hexlify)(IL));
8398
8973
  const Ki = signer.addPoint(publicKey);
8399
8974
  return new HDWallet({
8400
8975
  publicKey: Ki,
@@ -8423,18 +8998,18 @@ var HDWallet = class {
8423
8998
  */
8424
8999
  toExtendedKey(isPublic = false, testnet = false) {
8425
9000
  if (this.depth >= 256) {
8426
- throw new import_errors20.FuelError(
8427
- import_errors20.ErrorCode.HD_WALLET_ERROR,
9001
+ throw new import_errors22.FuelError(
9002
+ import_errors22.ErrorCode.HD_WALLET_ERROR,
8428
9003
  `Exceeded max depth of 255. Current depth: ${this.depth}.`
8429
9004
  );
8430
9005
  }
8431
9006
  const prefix = getExtendedKeyPrefix(this.privateKey == null || isPublic, testnet);
8432
- const depth = (0, import_utils36.hexlify)(Uint8Array.from([this.depth]));
9007
+ const depth = (0, import_utils39.hexlify)(Uint8Array.from([this.depth]));
8433
9008
  const parentFingerprint = this.parentFingerprint;
8434
- const index = (0, import_math22.toHex)(this.index, 4);
9009
+ const index = (0, import_math23.toHex)(this.index, 4);
8435
9010
  const chainCode = this.chainCode;
8436
- const key = this.privateKey != null && !isPublic ? (0, import_utils36.concat)(["0x00", this.privateKey]) : this.publicKey;
8437
- const extendedKey = (0, import_utils36.arrayify)((0, import_utils36.concat)([prefix, depth, parentFingerprint, index, chainCode, key]));
9011
+ const key = this.privateKey != null && !isPublic ? (0, import_utils39.concat)(["0x00", this.privateKey]) : this.publicKey;
9012
+ const extendedKey = (0, import_utils39.arrayify)((0, import_utils39.concat)([prefix, depth, parentFingerprint, index, chainCode, key]));
8438
9013
  return base58check(extendedKey);
8439
9014
  }
8440
9015
  /**
@@ -8446,34 +9021,34 @@ var HDWallet = class {
8446
9021
  static fromSeed(seed) {
8447
9022
  const masterKey = mnemonic_default.masterKeysFromSeed(seed);
8448
9023
  return new HDWallet({
8449
- chainCode: (0, import_utils36.arrayify)(masterKey.slice(32)),
8450
- privateKey: (0, import_utils36.arrayify)(masterKey.slice(0, 32))
9024
+ chainCode: (0, import_utils39.arrayify)(masterKey.slice(32)),
9025
+ privateKey: (0, import_utils39.arrayify)(masterKey.slice(0, 32))
8451
9026
  });
8452
9027
  }
8453
9028
  static fromExtendedKey(extendedKey) {
8454
- const decoded = (0, import_utils36.hexlify)((0, import_math22.toBytes)((0, import_utils36.decodeBase58)(extendedKey)));
8455
- const bytes = (0, import_utils36.arrayify)(decoded);
9029
+ const decoded = (0, import_utils39.hexlify)((0, import_math23.toBytes)((0, import_utils39.decodeBase58)(extendedKey)));
9030
+ const bytes = (0, import_utils39.arrayify)(decoded);
8456
9031
  const validChecksum = base58check(bytes.slice(0, 78)) === extendedKey;
8457
9032
  if (bytes.length !== 82 || !isValidExtendedKey(bytes)) {
8458
- throw new import_errors20.FuelError(import_errors20.ErrorCode.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
9033
+ throw new import_errors22.FuelError(import_errors22.ErrorCode.HD_WALLET_ERROR, "Provided key is not a valid extended key.");
8459
9034
  }
8460
9035
  if (!validChecksum) {
8461
- throw new import_errors20.FuelError(import_errors20.ErrorCode.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
9036
+ throw new import_errors22.FuelError(import_errors22.ErrorCode.HD_WALLET_ERROR, "Provided key has an invalid checksum.");
8462
9037
  }
8463
9038
  const depth = bytes[4];
8464
- const parentFingerprint = (0, import_utils36.hexlify)(bytes.slice(5, 9));
8465
- const index = parseInt((0, import_utils36.hexlify)(bytes.slice(9, 13)).substring(2), 16);
8466
- const chainCode = (0, import_utils36.hexlify)(bytes.slice(13, 45));
9039
+ const parentFingerprint = (0, import_utils39.hexlify)(bytes.slice(5, 9));
9040
+ const index = parseInt((0, import_utils39.hexlify)(bytes.slice(9, 13)).substring(2), 16);
9041
+ const chainCode = (0, import_utils39.hexlify)(bytes.slice(13, 45));
8467
9042
  const key = bytes.slice(45, 78);
8468
9043
  if (depth === 0 && parentFingerprint !== "0x00000000" || depth === 0 && index !== 0) {
8469
- throw new import_errors20.FuelError(
8470
- import_errors20.ErrorCode.HD_WALLET_ERROR,
9044
+ throw new import_errors22.FuelError(
9045
+ import_errors22.ErrorCode.HD_WALLET_ERROR,
8471
9046
  "Inconsistency detected: Depth is zero but fingerprint/index is non-zero."
8472
9047
  );
8473
9048
  }
8474
9049
  if (isPublicExtendedKey(bytes)) {
8475
9050
  if (key[0] !== 3) {
8476
- throw new import_errors20.FuelError(import_errors20.ErrorCode.HD_WALLET_ERROR, "Invalid public extended key.");
9051
+ throw new import_errors22.FuelError(import_errors22.ErrorCode.HD_WALLET_ERROR, "Invalid public extended key.");
8477
9052
  }
8478
9053
  return new HDWallet({
8479
9054
  publicKey: key,
@@ -8484,7 +9059,7 @@ var HDWallet = class {
8484
9059
  });
8485
9060
  }
8486
9061
  if (key[0] !== 0) {
8487
- throw new import_errors20.FuelError(import_errors20.ErrorCode.HD_WALLET_ERROR, "Invalid private extended key.");
9062
+ throw new import_errors22.FuelError(import_errors22.ErrorCode.HD_WALLET_ERROR, "Invalid private extended key.");
8488
9063
  }
8489
9064
  return new HDWallet({
8490
9065
  privateKey: key.slice(1),
@@ -8649,292 +9224,7 @@ __publicField(Wallet, "fromExtendedKey", WalletUnlocked.fromExtendedKey);
8649
9224
  */
8650
9225
  __publicField(Wallet, "fromEncryptedJson", WalletUnlocked.fromEncryptedJson);
8651
9226
 
8652
- // src/test-utils/seedTestWallet.ts
8653
- var import_crypto7 = require("@fuel-ts/crypto");
8654
- var seedTestWallet = async (wallet, quantities, utxosAmount = 1) => {
8655
- const accountsToBeFunded = Array.isArray(wallet) ? wallet : [wallet];
8656
- const [{ provider }] = accountsToBeFunded;
8657
- const genesisWallet = new WalletUnlocked(process.env.GENESIS_SECRET || (0, import_crypto7.randomBytes)(32), provider);
8658
- const request = new ScriptTransactionRequest();
8659
- quantities.map(coinQuantityfy).forEach(
8660
- ({ amount, assetId }) => accountsToBeFunded.forEach(({ address }) => {
8661
- for (let i = 0; i < utxosAmount; i++) {
8662
- request.addCoinOutput(address, amount.div(utxosAmount), assetId);
8663
- }
8664
- })
8665
- );
8666
- const txCost = await genesisWallet.provider.getTransactionCost(request);
8667
- request.gasLimit = txCost.gasUsed;
8668
- request.maxFee = txCost.maxFee;
8669
- await genesisWallet.fund(request, txCost);
8670
- await genesisWallet.sendTransaction(request, { awaitExecution: true });
8671
- };
8672
-
8673
- // src/test-utils/generateTestWallet.ts
8674
- var generateTestWallet = async (provider, quantities) => {
8675
- const wallet = Wallet.generate({ provider });
8676
- if (quantities) {
8677
- await seedTestWallet(wallet, quantities);
8678
- }
8679
- return wallet;
8680
- };
8681
-
8682
- // src/test-utils/launchNode.ts
8683
- var import_abi_coder8 = require("@fuel-ts/abi-coder");
8684
- var import_crypto8 = require("@fuel-ts/crypto");
8685
- var import_errors21 = require("@fuel-ts/errors");
8686
- var import_utils37 = require("@fuel-ts/utils");
8687
- var import_crypto9 = require("crypto");
8688
- var import_fs = require("fs");
8689
- var import_os = __toESM(require("os"));
8690
- var import_path = __toESM(require("path"));
8691
- var import_portfinder = require("portfinder");
8692
- var getFlagValueFromArgs = (args, flag) => {
8693
- const flagIndex = args.indexOf(flag);
8694
- if (flagIndex === -1) {
8695
- return void 0;
8696
- }
8697
- return args[flagIndex + 1];
8698
- };
8699
- var extractRemainingArgs = (args, flagsToRemove) => {
8700
- const newArgs = [...args];
8701
- flagsToRemove.forEach((flag) => {
8702
- const flagIndex = newArgs.indexOf(flag);
8703
- if (flagIndex !== -1) {
8704
- newArgs.splice(flagIndex, 2);
8705
- }
8706
- });
8707
- return newArgs;
8708
- };
8709
- function getFinalStateConfigJSON({ stateConfig, chainConfig }) {
8710
- const defaultCoins = import_utils37.defaultSnapshotConfigs.stateConfig.coins.map((coin) => ({
8711
- ...coin,
8712
- amount: "18446744073709551615"
8713
- }));
8714
- const defaultMessages = import_utils37.defaultSnapshotConfigs.stateConfig.messages.map((message) => ({
8715
- ...message,
8716
- amount: "18446744073709551615"
8717
- }));
8718
- 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);
8719
- 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);
8720
- if (!process.env.GENESIS_SECRET) {
8721
- const pk = Signer.generatePrivateKey();
8722
- const signer = new Signer(pk);
8723
- process.env.GENESIS_SECRET = (0, import_utils37.hexlify)(pk);
8724
- coins.push({
8725
- tx_id: (0, import_utils37.hexlify)((0, import_crypto8.randomBytes)(import_abi_coder8.BYTES_32)),
8726
- owner: signer.address.toHexString(),
8727
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
8728
- amount: "18446744073709551615",
8729
- asset_id: chainConfig.consensus_parameters.V1.base_asset_id,
8730
- output_index: 0,
8731
- tx_pointer_block_height: 0,
8732
- tx_pointer_tx_idx: 0
8733
- });
8734
- }
8735
- const json = JSON.stringify({
8736
- ...stateConfig,
8737
- coins,
8738
- messages
8739
- });
8740
- const regexMakeNumber = /("amount":)"(\d+)"/gm;
8741
- return json.replace(regexMakeNumber, "$1$2");
8742
- }
8743
- var launchNode = async ({
8744
- ip,
8745
- port,
8746
- args = [],
8747
- fuelCorePath = process.env.FUEL_CORE_PATH || void 0,
8748
- loggingEnabled = true,
8749
- basePath,
8750
- snapshotConfig = import_utils37.defaultSnapshotConfigs
8751
- } = {}) => (
8752
- // eslint-disable-next-line no-async-promise-executor
8753
- new Promise(async (resolve, reject) => {
8754
- const remainingArgs = extractRemainingArgs(args, [
8755
- "--snapshot",
8756
- "--consensus-key",
8757
- "--db-type",
8758
- "--poa-instant"
8759
- ]);
8760
- const snapshotDir = getFlagValueFromArgs(args, "--snapshot");
8761
- const consensusKey = getFlagValueFromArgs(args, "--consensus-key") || import_utils37.defaultConsensusKey;
8762
- const dbTypeFlagValue = getFlagValueFromArgs(args, "--db-type");
8763
- const useInMemoryDb = dbTypeFlagValue === "in-memory" || dbTypeFlagValue === void 0;
8764
- const poaInstantFlagValue = getFlagValueFromArgs(args, "--poa-instant");
8765
- const poaInstant = poaInstantFlagValue === "true" || poaInstantFlagValue === void 0;
8766
- const nativeExecutorVersion = getFlagValueFromArgs(args, "--native-executor-version") || "0";
8767
- const graphQLStartSubstring = "Binding GraphQL provider to";
8768
- const command = fuelCorePath || "fuel-core";
8769
- const ipToUse = ip || "0.0.0.0";
8770
- const portToUse = port || (await (0, import_portfinder.getPortPromise)({
8771
- port: 4e3,
8772
- // tries 4000 first, then 4001, then 4002, etc.
8773
- stopPort: 5e3
8774
- // don't try ports above 5000
8775
- })).toString();
8776
- let snapshotDirToUse;
8777
- const prefix = basePath || import_os.default.tmpdir();
8778
- const suffix = basePath ? "" : (0, import_crypto9.randomUUID)();
8779
- const tempDir = import_path.default.join(prefix, ".fuels", suffix, "snapshotDir");
8780
- if (snapshotDir) {
8781
- snapshotDirToUse = snapshotDir;
8782
- } else {
8783
- if (!(0, import_fs.existsSync)(tempDir)) {
8784
- (0, import_fs.mkdirSync)(tempDir, { recursive: true });
8785
- }
8786
- const { metadata } = snapshotConfig;
8787
- const metadataPath = import_path.default.join(tempDir, "metadata.json");
8788
- const chainConfigPath = import_path.default.join(tempDir, metadata.chain_config);
8789
- const stateConfigPath = import_path.default.join(tempDir, metadata.table_encoding.Json.filepath);
8790
- const stateTransitionPath = import_path.default.join(tempDir, "state_transition_bytecode.wasm");
8791
- (0, import_fs.writeFileSync)(chainConfigPath, JSON.stringify(snapshotConfig.chainConfig), "utf8");
8792
- (0, import_fs.writeFileSync)(stateConfigPath, getFinalStateConfigJSON(snapshotConfig), "utf8");
8793
- (0, import_fs.writeFileSync)(metadataPath, JSON.stringify(metadata), "utf8");
8794
- (0, import_fs.writeFileSync)(stateTransitionPath, JSON.stringify(""));
8795
- snapshotDirToUse = tempDir;
8796
- }
8797
- const { spawn } = await import("child_process");
8798
- const child = spawn(
8799
- command,
8800
- [
8801
- "run",
8802
- ["--ip", ipToUse],
8803
- ["--port", portToUse],
8804
- useInMemoryDb ? ["--db-type", "in-memory"] : ["--db-path", tempDir],
8805
- ["--min-gas-price", "1"],
8806
- poaInstant ? ["--poa-instant", "true"] : [],
8807
- ["--native-executor-version", nativeExecutorVersion],
8808
- ["--consensus-key", consensusKey],
8809
- ["--snapshot", snapshotDirToUse],
8810
- "--vm-backtrace",
8811
- "--utxo-validation",
8812
- "--debug",
8813
- ...remainingArgs
8814
- ].flat(),
8815
- { stdio: "pipe", detached: true }
8816
- );
8817
- if (loggingEnabled) {
8818
- child.stderr.on("data", (chunk) => {
8819
- console.log(chunk.toString());
8820
- });
8821
- }
8822
- const removeSideffects = () => {
8823
- child.stderr.removeAllListeners();
8824
- if ((0, import_fs.existsSync)(tempDir)) {
8825
- (0, import_fs.rmSync)(tempDir, { recursive: true });
8826
- }
8827
- };
8828
- child.on("error", removeSideffects);
8829
- child.on("exit", removeSideffects);
8830
- const childState = {
8831
- isDead: false
8832
- };
8833
- const cleanup = () => {
8834
- if (childState.isDead) {
8835
- return;
8836
- }
8837
- childState.isDead = true;
8838
- removeSideffects();
8839
- if (child.pid !== void 0) {
8840
- try {
8841
- process.kill(-child.pid);
8842
- } catch (e) {
8843
- const error = e;
8844
- if (error.code === "ESRCH") {
8845
- console.log(
8846
- `fuel-core node under pid ${child.pid} does not exist. The node might have been killed before cleanup was called. Exiting cleanly.`
8847
- );
8848
- } else {
8849
- throw e;
8850
- }
8851
- }
8852
- } else {
8853
- console.error("No PID available for the child process, unable to kill launched node");
8854
- }
8855
- };
8856
- child.stderr.on("data", (chunk) => {
8857
- const text = typeof chunk === "string" ? chunk : chunk.toString();
8858
- if (text.indexOf(graphQLStartSubstring) !== -1) {
8859
- const rows = text.split("\n");
8860
- const rowWithUrl = rows.find((row) => row.indexOf(graphQLStartSubstring) !== -1);
8861
- const [realIp, realPort] = rowWithUrl.split(" ").at(-1).trim().split(":");
8862
- resolve({
8863
- cleanup,
8864
- ip: realIp,
8865
- port: realPort,
8866
- url: `http://${realIp}:${realPort}/v1/graphql`,
8867
- snapshotDir: snapshotDirToUse,
8868
- pid: child.pid
8869
- });
8870
- }
8871
- if (/error/i.test(text)) {
8872
- console.log(text);
8873
- reject(new import_errors21.FuelError(import_errors21.FuelError.CODES.NODE_LAUNCH_FAILED, text));
8874
- }
8875
- });
8876
- process.on("exit", cleanup);
8877
- process.on("SIGINT", cleanup);
8878
- process.on("SIGUSR1", cleanup);
8879
- process.on("SIGUSR2", cleanup);
8880
- process.on("beforeExit", cleanup);
8881
- process.on("uncaughtException", cleanup);
8882
- child.on("error", reject);
8883
- })
8884
- );
8885
- var generateWallets = async (count, provider) => {
8886
- const baseAssetId = provider.getBaseAssetId();
8887
- const wallets = [];
8888
- for (let i = 0; i < count; i += 1) {
8889
- const wallet = await generateTestWallet(provider, [[1e5, baseAssetId]]);
8890
- wallets.push(wallet);
8891
- }
8892
- return wallets;
8893
- };
8894
- var launchNodeAndGetWallets = async ({
8895
- launchNodeOptions,
8896
- walletCount = 10
8897
- } = {}) => {
8898
- const { cleanup: closeNode, ip, port } = await launchNode(launchNodeOptions || {});
8899
- const provider = await Provider.create(`http://${ip}:${port}/v1/graphql`);
8900
- const wallets = await generateWallets(walletCount, provider);
8901
- const cleanup = () => {
8902
- closeNode();
8903
- };
8904
- return { wallets, stop: cleanup, provider };
8905
- };
8906
-
8907
- // src/test-utils/setup-test-provider-and-wallets.ts
8908
- var import_utils40 = require("@fuel-ts/utils");
8909
- var import_ramda5 = require("ramda");
8910
-
8911
- // src/test-utils/asset-id.ts
8912
- var import_crypto10 = require("@fuel-ts/crypto");
8913
- var import_utils38 = require("@fuel-ts/utils");
8914
- var _AssetId = class {
8915
- constructor(value) {
8916
- this.value = value;
8917
- }
8918
- static random(count = 1) {
8919
- const assetIds = [];
8920
- for (let i = 0; i < count; i++) {
8921
- assetIds.push(new _AssetId((0, import_utils38.hexlify)((0, import_crypto10.randomBytes)(32))));
8922
- }
8923
- return assetIds;
8924
- }
8925
- };
8926
- var AssetId = _AssetId;
8927
- __publicField(AssetId, "A", new _AssetId(
8928
- "0x0101010101010101010101010101010101010101010101010101010101010101"
8929
- ));
8930
- __publicField(AssetId, "B", new _AssetId(
8931
- "0x0202020202020202020202020202020202020202020202020202020202020202"
8932
- ));
8933
-
8934
9227
  // src/test-utils/wallet-config.ts
8935
- var import_crypto11 = require("@fuel-ts/crypto");
8936
- var import_errors22 = require("@fuel-ts/errors");
8937
- var import_utils39 = require("@fuel-ts/utils");
8938
9228
  var WalletsConfig = class {
8939
9229
  initialState;
8940
9230
  options;
@@ -8942,7 +9232,7 @@ var WalletsConfig = class {
8942
9232
  generateWallets = () => {
8943
9233
  const generatedWallets = [];
8944
9234
  for (let index = 1; index <= this.options.count; index++) {
8945
- generatedWallets.push(new WalletUnlocked((0, import_crypto11.randomBytes)(32)));
9235
+ generatedWallets.push(new WalletUnlocked((0, import_crypto9.randomBytes)(32)));
8946
9236
  }
8947
9237
  return generatedWallets;
8948
9238
  };
@@ -8966,7 +9256,7 @@ var WalletsConfig = class {
8966
9256
  return {
8967
9257
  ...snapshotConfig,
8968
9258
  stateConfig: {
8969
- ...snapshotConfig?.stateConfig ?? import_utils39.defaultSnapshotConfigs.stateConfig,
9259
+ ...snapshotConfig?.stateConfig ?? import_utils40.defaultSnapshotConfigs.stateConfig,
8970
9260
  coins: this.initialState.coins.concat(snapshotConfig?.stateConfig?.coins || []),
8971
9261
  messages: this.initialState.messages.concat(snapshotConfig?.stateConfig?.messages ?? [])
8972
9262
  }
@@ -8987,7 +9277,7 @@ var WalletsConfig = class {
8987
9277
  if (Array.isArray(assets2)) {
8988
9278
  assetIds = assetIds.concat(assets2.map((a) => a.value));
8989
9279
  } else {
8990
- assetIds = assetIds.concat(AssetId.random(assets2 - 1).map((a) => a.value));
9280
+ assetIds = assetIds.concat(TestAssetId.random(assets2 - 1).map((a) => a.value));
8991
9281
  }
8992
9282
  wallets.map((wallet) => wallet.address.toHexString()).forEach((walletAddress) => {
8993
9283
  assetIds.forEach((assetId) => {
@@ -8999,7 +9289,7 @@ var WalletsConfig = class {
8999
9289
  tx_pointer_block_height: 0,
9000
9290
  tx_pointer_tx_idx: 0,
9001
9291
  output_index: 0,
9002
- tx_id: (0, import_utils39.hexlify)((0, import_crypto11.randomBytes)(32))
9292
+ tx_id: (0, import_utils40.hexlify)((0, import_crypto9.randomBytes)(32))
9003
9293
  });
9004
9294
  }
9005
9295
  });
@@ -9013,27 +9303,27 @@ var WalletsConfig = class {
9013
9303
  amountPerCoin
9014
9304
  }) {
9015
9305
  if (Array.isArray(wallets) && wallets.length === 0 || typeof wallets === "number" && wallets <= 0) {
9016
- throw new import_errors22.FuelError(
9017
- import_errors22.FuelError.CODES.INVALID_INPUT_PARAMETERS,
9306
+ throw new import_errors23.FuelError(
9307
+ import_errors23.FuelError.CODES.INVALID_INPUT_PARAMETERS,
9018
9308
  "Number of wallets must be greater than zero."
9019
9309
  );
9020
9310
  }
9021
9311
  if (Array.isArray(assets2) && assets2.length === 0 || typeof assets2 === "number" && assets2 <= 0) {
9022
- throw new import_errors22.FuelError(
9023
- import_errors22.FuelError.CODES.INVALID_INPUT_PARAMETERS,
9312
+ throw new import_errors23.FuelError(
9313
+ import_errors23.FuelError.CODES.INVALID_INPUT_PARAMETERS,
9024
9314
  "Number of assets per wallet must be greater than zero."
9025
9315
  );
9026
9316
  }
9027
9317
  if (coinsPerAsset <= 0) {
9028
- throw new import_errors22.FuelError(
9029
- import_errors22.FuelError.CODES.INVALID_INPUT_PARAMETERS,
9318
+ throw new import_errors23.FuelError(
9319
+ import_errors23.FuelError.CODES.INVALID_INPUT_PARAMETERS,
9030
9320
  "Number of coins per asset must be greater than zero."
9031
9321
  );
9032
9322
  }
9033
- if (amountPerCoin <= 0) {
9034
- throw new import_errors22.FuelError(
9035
- import_errors22.FuelError.CODES.INVALID_INPUT_PARAMETERS,
9036
- "Amount per coin must be greater than zero."
9323
+ if (amountPerCoin < 0) {
9324
+ throw new import_errors23.FuelError(
9325
+ import_errors23.FuelError.CODES.INVALID_INPUT_PARAMETERS,
9326
+ "Amount per coin must be greater than or equal to zero."
9037
9327
  );
9038
9328
  }
9039
9329
  }
@@ -9042,7 +9332,7 @@ var WalletsConfig = class {
9042
9332
  // src/test-utils/setup-test-provider-and-wallets.ts
9043
9333
  var defaultWalletConfigOptions = {
9044
9334
  count: 2,
9045
- assets: [AssetId.A, AssetId.B],
9335
+ assets: [TestAssetId.A, TestAssetId.B],
9046
9336
  coinsPerAsset: 1,
9047
9337
  amountPerCoin: 1e10,
9048
9338
  messages: []
@@ -9055,7 +9345,7 @@ async function setupTestProviderAndWallets({
9055
9345
  } = {}) {
9056
9346
  Symbol.dispose ??= Symbol("Symbol.dispose");
9057
9347
  const walletsConfig = new WalletsConfig(
9058
- nodeOptions.snapshotConfig?.chainConfig?.consensus_parameters?.V1?.base_asset_id ?? import_utils40.defaultSnapshotConfigs.chainConfig.consensus_parameters.V1.base_asset_id,
9348
+ nodeOptions.snapshotConfig?.chainConfig?.consensus_parameters?.V1?.base_asset_id ?? import_utils41.defaultSnapshotConfigs.chainConfig.consensus_parameters.V1.base_asset_id,
9059
9349
  {
9060
9350
  ...defaultWalletConfigOptions,
9061
9351
  ...walletsConfigOptions
@@ -9065,10 +9355,10 @@ async function setupTestProviderAndWallets({
9065
9355
  loggingEnabled: false,
9066
9356
  ...nodeOptions,
9067
9357
  snapshotConfig: (0, import_ramda5.mergeDeepRight)(
9068
- import_utils40.defaultSnapshotConfigs,
9358
+ import_utils41.defaultSnapshotConfigs,
9069
9359
  walletsConfig.apply(nodeOptions?.snapshotConfig)
9070
9360
  ),
9071
- port: "0"
9361
+ port: nodeOptions.port || "0"
9072
9362
  };
9073
9363
  let cleanup;
9074
9364
  let url;
@@ -9104,9 +9394,9 @@ async function setupTestProviderAndWallets({
9104
9394
 
9105
9395
  // src/test-utils/test-message.ts
9106
9396
  var import_address7 = require("@fuel-ts/address");
9107
- var import_crypto12 = require("@fuel-ts/crypto");
9108
- var import_math23 = require("@fuel-ts/math");
9109
- var import_utils41 = require("@fuel-ts/utils");
9397
+ var import_crypto10 = require("@fuel-ts/crypto");
9398
+ var import_math24 = require("@fuel-ts/math");
9399
+ var import_utils42 = require("@fuel-ts/utils");
9110
9400
  var TestMessage = class {
9111
9401
  sender;
9112
9402
  recipient;
@@ -9123,9 +9413,10 @@ var TestMessage = class {
9123
9413
  constructor({
9124
9414
  sender = import_address7.Address.fromRandom(),
9125
9415
  recipient = import_address7.Address.fromRandom(),
9126
- nonce = (0, import_utils41.hexlify)((0, import_crypto12.randomBytes)(32)),
9416
+ nonce = (0, import_utils42.hexlify)((0, import_crypto10.randomBytes)(32)),
9127
9417
  amount = 1e6,
9128
- data = "02",
9418
+ data = "",
9419
+ // Will default to empty data in order to be a spendable message
9129
9420
  da_height = 0
9130
9421
  } = {}) {
9131
9422
  this.sender = sender;
@@ -9136,25 +9427,23 @@ var TestMessage = class {
9136
9427
  this.da_height = da_height;
9137
9428
  }
9138
9429
  toChainMessage(recipient) {
9430
+ const data = /^0x/.test(this.data) ? this.data.replace(/^0x/, "") : this.data;
9139
9431
  return {
9140
9432
  sender: this.sender.toB256(),
9141
9433
  recipient: recipient?.toB256() ?? this.recipient.toB256(),
9142
9434
  nonce: this.nonce,
9143
- amount: (0, import_math23.bn)(this.amount).toNumber(),
9144
- data: this.data,
9435
+ amount: (0, import_math24.bn)(this.amount).toNumber(),
9436
+ data,
9145
9437
  da_height: this.da_height
9146
9438
  };
9147
9439
  }
9148
9440
  };
9149
9441
  // Annotate the CommonJS export names for ESM import in node:
9150
9442
  0 && (module.exports = {
9151
- AssetId,
9443
+ TestAssetId,
9152
9444
  TestMessage,
9153
9445
  WalletsConfig,
9154
- generateTestWallet,
9155
9446
  launchNode,
9156
- launchNodeAndGetWallets,
9157
- seedTestWallet,
9158
9447
  setupTestProviderAndWallets
9159
9448
  });
9160
9449
  //# sourceMappingURL=test-utils.js.map