@fuel-ts/account 0.0.0-rc-2143-20240515072133 → 0.0.0-rc-1356-20240515085856

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


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

@@ -1645,15 +1645,6 @@ function normalizeJSON(root) {
1645
1645
  return normalize(clone(root));
1646
1646
  }
1647
1647
 
1648
- // src/providers/utils/sleep.ts
1649
- function sleep(time) {
1650
- return new Promise((resolve) => {
1651
- setTimeout(() => {
1652
- resolve(true);
1653
- }, time);
1654
- });
1655
- }
1656
-
1657
1648
  // src/providers/utils/extract-tx-error.ts
1658
1649
  import { ErrorCode as ErrorCode7, FuelError as FuelError7 } from "@fuel-ts/errors";
1659
1650
  import { bn as bn6 } from "@fuel-ts/math";
@@ -3605,6 +3596,7 @@ var TransactionResponse = class {
3605
3596
  };
3606
3597
 
3607
3598
  // src/providers/utils/auto-retry-fetch.ts
3599
+ import { sleep } from "@fuel-ts/utils";
3608
3600
  function getWaitDelay(options, retryAttemptNum) {
3609
3601
  const duration = options.baseDelay ?? 150;
3610
3602
  switch (options.backoff) {
@@ -8408,7 +8400,7 @@ var generateTestWallet = async (provider, quantities) => {
8408
8400
  // src/test-utils/launchNode.ts
8409
8401
  import { UTXO_ID_LEN as UTXO_ID_LEN3 } from "@fuel-ts/abi-coder";
8410
8402
  import { randomBytes as randomBytes6 } from "@fuel-ts/crypto";
8411
- import { defaultSnapshotConfigs, defaultConsensusKey, hexlify as hexlify18 } from "@fuel-ts/utils";
8403
+ import { defaultConsensusKey, hexlify as hexlify18, defaultSnapshotConfigs } from "@fuel-ts/utils";
8412
8404
  import { findBinPath } from "@fuel-ts/utils/cli-utils";
8413
8405
  import { spawn } from "child_process";
8414
8406
  import { randomUUID } from "crypto";
@@ -8448,15 +8440,49 @@ var killNode = (params) => {
8448
8440
  }
8449
8441
  }
8450
8442
  };
8443
+ function getFinalStateConfigJSON({ stateConfig, chainConfig }) {
8444
+ const defaultCoins = defaultSnapshotConfigs.stateConfig.coins.map((coin) => ({
8445
+ ...coin,
8446
+ amount: "18446744073709551615"
8447
+ }));
8448
+ const defaultMessages = defaultSnapshotConfigs.stateConfig.messages.map((message) => ({
8449
+ ...message,
8450
+ amount: "18446744073709551615"
8451
+ }));
8452
+ 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);
8453
+ 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);
8454
+ if (!process.env.GENESIS_SECRET) {
8455
+ const pk = Signer.generatePrivateKey();
8456
+ const signer = new Signer(pk);
8457
+ process.env.GENESIS_SECRET = hexlify18(pk);
8458
+ coins.push({
8459
+ tx_id: hexlify18(randomBytes6(UTXO_ID_LEN3)),
8460
+ owner: signer.address.toHexString(),
8461
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
8462
+ amount: "18446744073709551615",
8463
+ asset_id: chainConfig.consensus_parameters.V1.base_asset_id,
8464
+ output_index: 0,
8465
+ tx_pointer_block_height: 0,
8466
+ tx_pointer_tx_idx: 0
8467
+ });
8468
+ }
8469
+ const json = JSON.stringify({
8470
+ ...stateConfig,
8471
+ coins,
8472
+ messages
8473
+ });
8474
+ const regexMakeNumber = /("amount":)"(\d+)"/gm;
8475
+ return json.replace(regexMakeNumber, "$1$2");
8476
+ }
8451
8477
  var launchNode = async ({
8452
8478
  ip,
8453
8479
  port,
8454
8480
  args = [],
8455
- fuelCorePath = void 0,
8456
8481
  useSystemFuelCore = false,
8457
8482
  loggingEnabled = true,
8458
8483
  debugEnabled = false,
8459
- basePath
8484
+ basePath,
8485
+ snapshotConfig = defaultSnapshotConfigs
8460
8486
  }) => (
8461
8487
  // eslint-disable-next-line no-async-promise-executor
8462
8488
  new Promise(async (resolve, reject) => {
@@ -8473,7 +8499,7 @@ var launchNode = async ({
8473
8499
  const poaInstantFlagValue = getFlagValueFromArgs(args, "--poa-instant");
8474
8500
  const poaInstant = poaInstantFlagValue === "true" || poaInstantFlagValue === void 0;
8475
8501
  const graphQLStartSubstring = "Binding GraphQL provider to";
8476
- const binPath = fuelCorePath ?? findBinPath("fuels-core", __dirname);
8502
+ const binPath = findBinPath("fuels-core", __dirname);
8477
8503
  const command = useSystemFuelCore ? "fuel-core" : binPath;
8478
8504
  const ipToUse = ip || "0.0.0.0";
8479
8505
  const portToUse = port || (await getPortPromise({
@@ -8485,56 +8511,23 @@ var launchNode = async ({
8485
8511
  let snapshotDirToUse;
8486
8512
  const prefix = basePath || os.tmpdir();
8487
8513
  const suffix = basePath ? "" : randomUUID();
8488
- const tempDirPath = path.join(prefix, ".fuels", suffix, "snapshotDir");
8514
+ const tempDir = path.join(prefix, ".fuels", suffix, "snapshotDir");
8489
8515
  if (snapshotDir) {
8490
8516
  snapshotDirToUse = snapshotDir;
8491
8517
  } else {
8492
- if (!existsSync(tempDirPath)) {
8493
- mkdirSync(tempDirPath, { recursive: true });
8518
+ if (!existsSync(tempDir)) {
8519
+ mkdirSync(tempDir, { recursive: true });
8494
8520
  }
8495
- let { stateConfigJson } = defaultSnapshotConfigs;
8496
- const { chainConfigJson, metadataJson } = defaultSnapshotConfigs;
8497
- stateConfigJson = {
8498
- ...stateConfigJson,
8499
- coins: [
8500
- ...stateConfigJson.coins.map((coin) => ({
8501
- ...coin,
8502
- amount: "18446744073709551615"
8503
- }))
8504
- ],
8505
- messages: stateConfigJson.messages.map((message) => ({
8506
- ...message,
8507
- amount: "18446744073709551615"
8508
- }))
8509
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
8510
- };
8511
- if (!process.env.GENESIS_SECRET) {
8512
- const pk = Signer.generatePrivateKey();
8513
- const signer = new Signer(pk);
8514
- process.env.GENESIS_SECRET = hexlify18(pk);
8515
- stateConfigJson.coins.push({
8516
- tx_id: hexlify18(randomBytes6(UTXO_ID_LEN3)),
8517
- owner: signer.address.toHexString(),
8518
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
8519
- amount: "18446744073709551615",
8520
- asset_id: chainConfigJson.consensus_parameters.V1.base_asset_id,
8521
- output_index: 0,
8522
- tx_pointer_block_height: 0,
8523
- tx_pointer_tx_idx: 0
8524
- });
8525
- }
8526
- let fixedStateConfigJSON = JSON.stringify(stateConfigJson);
8527
- const regexMakeNumber = /("amount":)"(\d+)"/gm;
8528
- fixedStateConfigJSON = fixedStateConfigJSON.replace(regexMakeNumber, "$1$2");
8529
- const chainConfigWritePath = path.join(tempDirPath, "chainConfig.json");
8530
- const stateConfigWritePath = path.join(tempDirPath, "stateConfig.json");
8531
- const metadataWritePath = path.join(tempDirPath, "metadata.json");
8532
- const stateTransitionWritePath = path.join(tempDirPath, "state_transition_bytecode.wasm");
8533
- writeFileSync(chainConfigWritePath, JSON.stringify(chainConfigJson), "utf8");
8534
- writeFileSync(stateConfigWritePath, fixedStateConfigJSON, "utf8");
8535
- writeFileSync(metadataWritePath, JSON.stringify(metadataJson), "utf8");
8536
- writeFileSync(stateTransitionWritePath, JSON.stringify(""));
8537
- snapshotDirToUse = tempDirPath;
8521
+ const { metadata } = snapshotConfig;
8522
+ const metadataPath = path.join(tempDir, "metadata.json");
8523
+ const chainConfigPath = path.join(tempDir, metadata.chain_config);
8524
+ const stateConfigPath = path.join(tempDir, metadata.table_encoding.Json.filepath);
8525
+ const stateTransitionPath = path.join(tempDir, "state_transition_bytecode.wasm");
8526
+ writeFileSync(chainConfigPath, JSON.stringify(snapshotConfig.chainConfig), "utf8");
8527
+ writeFileSync(stateConfigPath, getFinalStateConfigJSON(snapshotConfig), "utf8");
8528
+ writeFileSync(metadataPath, JSON.stringify(metadata), "utf8");
8529
+ writeFileSync(stateTransitionPath, JSON.stringify(""));
8530
+ snapshotDirToUse = tempDir;
8538
8531
  }
8539
8532
  const child = spawn(
8540
8533
  command,
@@ -8542,7 +8535,7 @@ var launchNode = async ({
8542
8535
  "run",
8543
8536
  ["--ip", ipToUse],
8544
8537
  ["--port", portToUse],
8545
- useInMemoryDb ? ["--db-type", "in-memory"] : ["--db-path", tempDirPath],
8538
+ useInMemoryDb ? ["--db-type", "in-memory"] : ["--db-path", tempDir],
8546
8539
  ["--min-gas-price", "1"],
8547
8540
  poaInstant ? ["--poa-instant", "true"] : [],
8548
8541
  ["--consensus-key", consensusKey],
@@ -8564,23 +8557,28 @@ var launchNode = async ({
8564
8557
  }
8565
8558
  const cleanupConfig = {
8566
8559
  child,
8567
- configPath: tempDirPath,
8560
+ configPath: tempDir,
8568
8561
  killFn: treeKill,
8569
8562
  state: {
8570
8563
  isDead: false
8571
8564
  }
8572
8565
  };
8573
8566
  child.stderr.on("data", (chunk) => {
8574
- if (chunk.indexOf(graphQLStartSubstring) !== -1) {
8567
+ const text = typeof chunk === "string" ? chunk : chunk.toString();
8568
+ if (text.indexOf(graphQLStartSubstring) !== -1) {
8569
+ const rows = text.split("\n");
8570
+ const rowWithUrl = rows.find((row) => row.indexOf(graphQLStartSubstring) !== -1);
8571
+ const [realIp, realPort] = rowWithUrl.split(" ").at(-1).trim().split(":");
8575
8572
  resolve({
8576
8573
  cleanup: () => killNode(cleanupConfig),
8577
- ip: ipToUse,
8578
- port: portToUse,
8574
+ ip: realIp,
8575
+ port: realPort,
8576
+ url: `http://${realIp}:${realPort}/v1/graphql`,
8579
8577
  snapshotDir: snapshotDirToUse
8580
8578
  });
8581
8579
  }
8582
- if (/error/i.test(chunk)) {
8583
- reject(chunk.toString());
8580
+ if (/error/i.test(text)) {
8581
+ reject(text.toString());
8584
8582
  }
8585
8583
  });
8586
8584
  process.on("exit", () => killNode(cleanupConfig));
@@ -8613,11 +8611,237 @@ var launchNodeAndGetWallets = async ({
8613
8611
  };
8614
8612
  return { wallets, stop: cleanup, provider };
8615
8613
  };
8614
+
8615
+ // src/test-utils/setup-test-provider-and-wallets.ts
8616
+ import { defaultSnapshotConfigs as defaultSnapshotConfigs3 } from "@fuel-ts/utils";
8617
+ import { mergeDeepRight } from "ramda";
8618
+
8619
+ // src/test-utils/asset-id.ts
8620
+ import { randomBytes as randomBytes7 } from "@fuel-ts/crypto";
8621
+ import { hexlify as hexlify19 } from "@fuel-ts/utils";
8622
+ var _AssetId = class {
8623
+ constructor(value) {
8624
+ this.value = value;
8625
+ }
8626
+ static random() {
8627
+ return new _AssetId(hexlify19(randomBytes7(32)));
8628
+ }
8629
+ };
8630
+ var AssetId = _AssetId;
8631
+ __publicField(AssetId, "A", new _AssetId(
8632
+ "0x0101010101010101010101010101010101010101010101010101010101010101"
8633
+ ));
8634
+ __publicField(AssetId, "B", new _AssetId(
8635
+ "0x0202020202020202020202020202020202020202020202020202020202020202"
8636
+ ));
8637
+
8638
+ // src/test-utils/wallet-config.ts
8639
+ import { randomBytes as randomBytes8 } from "@fuel-ts/crypto";
8640
+ import { FuelError as FuelError20 } from "@fuel-ts/errors";
8641
+ import { defaultSnapshotConfigs as defaultSnapshotConfigs2, hexlify as hexlify20 } from "@fuel-ts/utils";
8642
+ var WalletConfig = class {
8643
+ initialState;
8644
+ options;
8645
+ wallets;
8646
+ generateWallets = () => {
8647
+ const generatedWallets = [];
8648
+ for (let index = 1; index <= this.options.count; index++) {
8649
+ generatedWallets.push(new WalletUnlocked(randomBytes8(32)));
8650
+ }
8651
+ return generatedWallets;
8652
+ };
8653
+ constructor(baseAssetId, config) {
8654
+ const BASE_ASSET_ID = baseAssetId.startsWith("0x") ? baseAssetId : `0x${baseAssetId}`;
8655
+ WalletConfig.validate(config);
8656
+ this.options = config;
8657
+ const { assets: assets2, coinsPerAsset, amountPerCoin, messages } = this.options;
8658
+ this.wallets = this.generateWallets();
8659
+ this.initialState = {
8660
+ messages: WalletConfig.createMessages(this.wallets, messages),
8661
+ coins: WalletConfig.createCoins(
8662
+ this.wallets,
8663
+ BASE_ASSET_ID,
8664
+ assets2,
8665
+ coinsPerAsset,
8666
+ amountPerCoin
8667
+ )
8668
+ };
8669
+ }
8670
+ apply(snapshotConfig) {
8671
+ return {
8672
+ ...snapshotConfig,
8673
+ stateConfig: {
8674
+ ...snapshotConfig?.stateConfig ?? defaultSnapshotConfigs2.stateConfig,
8675
+ coins: this.initialState.coins.concat(snapshotConfig?.stateConfig?.coins || []),
8676
+ messages: this.initialState.messages.concat(snapshotConfig?.stateConfig?.messages ?? [])
8677
+ }
8678
+ };
8679
+ }
8680
+ static createMessages(wallets, messages) {
8681
+ return messages.map((msg) => wallets.map((wallet) => msg.toChainMessage(wallet.address))).flatMap((x) => x);
8682
+ }
8683
+ static createCoins(wallets, baseAssetId, assets2, coinsPerAsset, amountPerCoin) {
8684
+ const coins = [];
8685
+ let assetIds = [baseAssetId];
8686
+ if (Array.isArray(assets2)) {
8687
+ assetIds = assetIds.concat(assets2.map((a) => a.value));
8688
+ } else {
8689
+ for (let index = 0; index < assets2 - 1; index++) {
8690
+ assetIds.push(AssetId.random().value);
8691
+ }
8692
+ }
8693
+ wallets.map((wallet) => wallet.address.toHexString()).forEach((walletAddress) => {
8694
+ assetIds.forEach((assetId) => {
8695
+ for (let index = 0; index < coinsPerAsset; index++) {
8696
+ coins.push({
8697
+ amount: amountPerCoin,
8698
+ asset_id: assetId,
8699
+ owner: walletAddress,
8700
+ tx_pointer_block_height: 0,
8701
+ tx_pointer_tx_idx: 0,
8702
+ output_index: 0,
8703
+ tx_id: hexlify20(randomBytes8(32))
8704
+ });
8705
+ }
8706
+ });
8707
+ });
8708
+ return coins;
8709
+ }
8710
+ static validate({
8711
+ count: wallets,
8712
+ assets: assets2,
8713
+ coinsPerAsset,
8714
+ amountPerCoin
8715
+ }) {
8716
+ if (Array.isArray(wallets) && wallets.length === 0 || typeof wallets === "number" && wallets <= 0) {
8717
+ throw new FuelError20(
8718
+ FuelError20.CODES.INVALID_INPUT_PARAMETERS,
8719
+ "Number of wallets must be greater than zero."
8720
+ );
8721
+ }
8722
+ if (Array.isArray(assets2) && assets2.length === 0 || typeof assets2 === "number" && assets2 <= 0) {
8723
+ throw new FuelError20(
8724
+ FuelError20.CODES.INVALID_INPUT_PARAMETERS,
8725
+ "Number of assets per wallet must be greater than zero."
8726
+ );
8727
+ }
8728
+ if (coinsPerAsset <= 0) {
8729
+ throw new FuelError20(
8730
+ FuelError20.CODES.INVALID_INPUT_PARAMETERS,
8731
+ "Number of coins per asset must be greater than zero."
8732
+ );
8733
+ }
8734
+ if (amountPerCoin <= 0) {
8735
+ throw new FuelError20(
8736
+ FuelError20.CODES.INVALID_INPUT_PARAMETERS,
8737
+ "Amount per coin must be greater than zero."
8738
+ );
8739
+ }
8740
+ }
8741
+ };
8742
+
8743
+ // src/test-utils/setup-test-provider-and-wallets.ts
8744
+ var defaultWalletConfigOptions = {
8745
+ count: 2,
8746
+ assets: [AssetId.A, AssetId.B],
8747
+ coinsPerAsset: 1,
8748
+ amountPerCoin: 1e10,
8749
+ messages: []
8750
+ };
8751
+ async function setupTestProviderAndWallets({
8752
+ walletConfig: walletConfigOptions = {},
8753
+ providerOptions,
8754
+ nodeOptions = {}
8755
+ } = {}) {
8756
+ Symbol.dispose ??= Symbol("Symbol.dispose");
8757
+ const walletConfig = new WalletConfig(
8758
+ nodeOptions.snapshotConfig?.chainConfig?.consensus_parameters?.V1?.base_asset_id ?? defaultSnapshotConfigs3.chainConfig.consensus_parameters.V1.base_asset_id,
8759
+ {
8760
+ ...defaultWalletConfigOptions,
8761
+ ...walletConfigOptions
8762
+ }
8763
+ );
8764
+ const { cleanup, url } = await launchNode({
8765
+ loggingEnabled: false,
8766
+ ...nodeOptions,
8767
+ snapshotConfig: mergeDeepRight(
8768
+ defaultSnapshotConfigs3,
8769
+ walletConfig.apply(nodeOptions?.snapshotConfig)
8770
+ ),
8771
+ port: "0"
8772
+ });
8773
+ let provider;
8774
+ try {
8775
+ provider = await Provider.create(url, providerOptions);
8776
+ } catch (err) {
8777
+ cleanup();
8778
+ throw err;
8779
+ }
8780
+ const wallets = walletConfig.wallets;
8781
+ wallets.forEach((wallet) => {
8782
+ wallet.connect(provider);
8783
+ });
8784
+ return {
8785
+ provider,
8786
+ wallets,
8787
+ cleanup,
8788
+ [Symbol.dispose]: cleanup
8789
+ };
8790
+ }
8791
+
8792
+ // src/test-utils/test-message.ts
8793
+ import { Address as Address6 } from "@fuel-ts/address";
8794
+ import { randomBytes as randomBytes9 } from "@fuel-ts/crypto";
8795
+ import { bn as bn21 } from "@fuel-ts/math";
8796
+ import { hexlify as hexlify21 } from "@fuel-ts/utils";
8797
+ var TestMessage = class {
8798
+ sender;
8799
+ recipient;
8800
+ nonce;
8801
+ amount;
8802
+ data;
8803
+ da_height;
8804
+ /**
8805
+ * A helper class to create messages for testing purposes.
8806
+ *
8807
+ * Used in tandem with `WalletConfig`.
8808
+ * It can also be used standalone and passed into the initial state of a chain via the `.toChainMessage` method.
8809
+ */
8810
+ constructor({
8811
+ sender = Address6.fromRandom(),
8812
+ recipient = Address6.fromRandom(),
8813
+ nonce = hexlify21(randomBytes9(32)),
8814
+ amount = 1e6,
8815
+ data = "02",
8816
+ da_height = 0
8817
+ } = {}) {
8818
+ this.sender = sender;
8819
+ this.recipient = recipient;
8820
+ this.nonce = nonce;
8821
+ this.amount = amount;
8822
+ this.data = data;
8823
+ this.da_height = da_height;
8824
+ }
8825
+ toChainMessage(recipient) {
8826
+ return {
8827
+ sender: this.sender.toB256(),
8828
+ recipient: recipient?.toB256() ?? this.recipient.toB256(),
8829
+ nonce: this.nonce,
8830
+ amount: bn21(this.amount).toNumber(),
8831
+ data: this.data,
8832
+ da_height: this.da_height
8833
+ };
8834
+ }
8835
+ };
8616
8836
  export {
8837
+ AssetId,
8838
+ TestMessage,
8839
+ WalletConfig,
8617
8840
  generateTestWallet,
8618
8841
  killNode,
8619
8842
  launchNode,
8620
8843
  launchNodeAndGetWallets,
8621
- seedTestWallet
8844
+ seedTestWallet,
8845
+ setupTestProviderAndWallets
8622
8846
  };
8623
8847
  //# sourceMappingURL=test-utils.mjs.map