@fuel-ts/account 0.0.0-rc-2333-20240521114009 → 0.0.0-rc-1356-20240521154745

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.

@@ -1647,15 +1647,6 @@ function normalizeJSON(root) {
1647
1647
  return normalize(clone(root));
1648
1648
  }
1649
1649
 
1650
- // src/providers/utils/sleep.ts
1651
- function sleep(time) {
1652
- return new Promise((resolve) => {
1653
- setTimeout(() => {
1654
- resolve(true);
1655
- }, time);
1656
- });
1657
- }
1658
-
1659
1650
  // src/providers/utils/extract-tx-error.ts
1660
1651
  import { ErrorCode as ErrorCode7, FuelError as FuelError7 } from "@fuel-ts/errors";
1661
1652
  import { bn as bn6 } from "@fuel-ts/math";
@@ -3604,6 +3595,7 @@ var TransactionResponse = class {
3604
3595
  };
3605
3596
 
3606
3597
  // src/providers/utils/auto-retry-fetch.ts
3598
+ import { sleep } from "@fuel-ts/utils";
3607
3599
  function getWaitDelay(options, retryAttemptNum) {
3608
3600
  const duration = options.baseDelay ?? 150;
3609
3601
  switch (options.backoff) {
@@ -8482,7 +8474,7 @@ var generateTestWallet = async (provider, quantities) => {
8482
8474
  // src/test-utils/launchNode.ts
8483
8475
  import { UTXO_ID_LEN as UTXO_ID_LEN3 } from "@fuel-ts/abi-coder";
8484
8476
  import { randomBytes as randomBytes6 } from "@fuel-ts/crypto";
8485
- import { defaultSnapshotConfigs, defaultConsensusKey, hexlify as hexlify18 } from "@fuel-ts/utils";
8477
+ import { defaultConsensusKey, hexlify as hexlify18, defaultSnapshotConfigs } from "@fuel-ts/utils";
8486
8478
  import { spawn } from "child_process";
8487
8479
  import { randomUUID } from "crypto";
8488
8480
  import { existsSync, mkdirSync, rmSync, writeFileSync } from "fs";
@@ -8521,6 +8513,40 @@ var killNode = (params) => {
8521
8513
  }
8522
8514
  }
8523
8515
  };
8516
+ function getFinalStateConfigJSON({ stateConfig, chainConfig }) {
8517
+ const defaultCoins = defaultSnapshotConfigs.stateConfig.coins.map((coin) => ({
8518
+ ...coin,
8519
+ amount: "18446744073709551615"
8520
+ }));
8521
+ const defaultMessages = defaultSnapshotConfigs.stateConfig.messages.map((message) => ({
8522
+ ...message,
8523
+ amount: "18446744073709551615"
8524
+ }));
8525
+ 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);
8526
+ 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);
8527
+ if (!process.env.GENESIS_SECRET) {
8528
+ const pk = Signer.generatePrivateKey();
8529
+ const signer = new Signer(pk);
8530
+ process.env.GENESIS_SECRET = hexlify18(pk);
8531
+ coins.push({
8532
+ tx_id: hexlify18(randomBytes6(UTXO_ID_LEN3)),
8533
+ owner: signer.address.toHexString(),
8534
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
8535
+ amount: "18446744073709551615",
8536
+ asset_id: chainConfig.consensus_parameters.V1.base_asset_id,
8537
+ output_index: 0,
8538
+ tx_pointer_block_height: 0,
8539
+ tx_pointer_tx_idx: 0
8540
+ });
8541
+ }
8542
+ const json = JSON.stringify({
8543
+ ...stateConfig,
8544
+ coins,
8545
+ messages
8546
+ });
8547
+ const regexMakeNumber = /("amount":)"(\d+)"/gm;
8548
+ return json.replace(regexMakeNumber, "$1$2");
8549
+ }
8524
8550
  var launchNode = async ({
8525
8551
  ip,
8526
8552
  port,
@@ -8528,7 +8554,8 @@ var launchNode = async ({
8528
8554
  fuelCorePath = process.env.FUEL_CORE_PATH ?? void 0,
8529
8555
  loggingEnabled = true,
8530
8556
  debugEnabled = false,
8531
- basePath
8557
+ basePath,
8558
+ snapshotConfig = defaultSnapshotConfigs
8532
8559
  }) => (
8533
8560
  // eslint-disable-next-line no-async-promise-executor
8534
8561
  new Promise(async (resolve, reject) => {
@@ -8556,56 +8583,23 @@ var launchNode = async ({
8556
8583
  let snapshotDirToUse;
8557
8584
  const prefix = basePath || os.tmpdir();
8558
8585
  const suffix = basePath ? "" : randomUUID();
8559
- const tempDirPath = path.join(prefix, ".fuels", suffix, "snapshotDir");
8586
+ const tempDir = path.join(prefix, ".fuels", suffix, "snapshotDir");
8560
8587
  if (snapshotDir) {
8561
8588
  snapshotDirToUse = snapshotDir;
8562
8589
  } else {
8563
- if (!existsSync(tempDirPath)) {
8564
- mkdirSync(tempDirPath, { recursive: true });
8590
+ if (!existsSync(tempDir)) {
8591
+ mkdirSync(tempDir, { recursive: true });
8565
8592
  }
8566
- let { stateConfigJson } = defaultSnapshotConfigs;
8567
- const { chainConfigJson, metadataJson } = defaultSnapshotConfigs;
8568
- stateConfigJson = {
8569
- ...stateConfigJson,
8570
- coins: [
8571
- ...stateConfigJson.coins.map((coin) => ({
8572
- ...coin,
8573
- amount: "18446744073709551615"
8574
- }))
8575
- ],
8576
- messages: stateConfigJson.messages.map((message) => ({
8577
- ...message,
8578
- amount: "18446744073709551615"
8579
- }))
8580
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
8581
- };
8582
- if (!process.env.GENESIS_SECRET) {
8583
- const pk = Signer.generatePrivateKey();
8584
- const signer = new Signer(pk);
8585
- process.env.GENESIS_SECRET = hexlify18(pk);
8586
- stateConfigJson.coins.push({
8587
- tx_id: hexlify18(randomBytes6(UTXO_ID_LEN3)),
8588
- owner: signer.address.toHexString(),
8589
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
8590
- amount: "18446744073709551615",
8591
- asset_id: chainConfigJson.consensus_parameters.V1.base_asset_id,
8592
- output_index: 0,
8593
- tx_pointer_block_height: 0,
8594
- tx_pointer_tx_idx: 0
8595
- });
8596
- }
8597
- let fixedStateConfigJSON = JSON.stringify(stateConfigJson);
8598
- const regexMakeNumber = /("amount":)"(\d+)"/gm;
8599
- fixedStateConfigJSON = fixedStateConfigJSON.replace(regexMakeNumber, "$1$2");
8600
- const chainConfigWritePath = path.join(tempDirPath, "chainConfig.json");
8601
- const stateConfigWritePath = path.join(tempDirPath, "stateConfig.json");
8602
- const metadataWritePath = path.join(tempDirPath, "metadata.json");
8603
- const stateTransitionWritePath = path.join(tempDirPath, "state_transition_bytecode.wasm");
8604
- writeFileSync(chainConfigWritePath, JSON.stringify(chainConfigJson), "utf8");
8605
- writeFileSync(stateConfigWritePath, fixedStateConfigJSON, "utf8");
8606
- writeFileSync(metadataWritePath, JSON.stringify(metadataJson), "utf8");
8607
- writeFileSync(stateTransitionWritePath, JSON.stringify(""));
8608
- snapshotDirToUse = tempDirPath;
8593
+ const { metadata } = snapshotConfig;
8594
+ const metadataPath = path.join(tempDir, "metadata.json");
8595
+ const chainConfigPath = path.join(tempDir, metadata.chain_config);
8596
+ const stateConfigPath = path.join(tempDir, metadata.table_encoding.Json.filepath);
8597
+ const stateTransitionPath = path.join(tempDir, "state_transition_bytecode.wasm");
8598
+ writeFileSync(chainConfigPath, JSON.stringify(snapshotConfig.chainConfig), "utf8");
8599
+ writeFileSync(stateConfigPath, getFinalStateConfigJSON(snapshotConfig), "utf8");
8600
+ writeFileSync(metadataPath, JSON.stringify(metadata), "utf8");
8601
+ writeFileSync(stateTransitionPath, JSON.stringify(""));
8602
+ snapshotDirToUse = tempDir;
8609
8603
  }
8610
8604
  const child = spawn(
8611
8605
  command,
@@ -8613,7 +8607,7 @@ var launchNode = async ({
8613
8607
  "run",
8614
8608
  ["--ip", ipToUse],
8615
8609
  ["--port", portToUse],
8616
- useInMemoryDb ? ["--db-type", "in-memory"] : ["--db-path", tempDirPath],
8610
+ useInMemoryDb ? ["--db-type", "in-memory"] : ["--db-path", tempDir],
8617
8611
  ["--min-gas-price", "1"],
8618
8612
  poaInstant ? ["--poa-instant", "true"] : [],
8619
8613
  ["--consensus-key", consensusKey],
@@ -8635,23 +8629,28 @@ var launchNode = async ({
8635
8629
  }
8636
8630
  const cleanupConfig = {
8637
8631
  child,
8638
- configPath: tempDirPath,
8632
+ configPath: tempDir,
8639
8633
  killFn: treeKill,
8640
8634
  state: {
8641
8635
  isDead: false
8642
8636
  }
8643
8637
  };
8644
8638
  child.stderr.on("data", (chunk) => {
8645
- if (chunk.indexOf(graphQLStartSubstring) !== -1) {
8639
+ const text = typeof chunk === "string" ? chunk : chunk.toString();
8640
+ if (text.indexOf(graphQLStartSubstring) !== -1) {
8641
+ const rows = text.split("\n");
8642
+ const rowWithUrl = rows.find((row) => row.indexOf(graphQLStartSubstring) !== -1);
8643
+ const [realIp, realPort] = rowWithUrl.split(" ").at(-1).trim().split(":");
8646
8644
  resolve({
8647
8645
  cleanup: () => killNode(cleanupConfig),
8648
- ip: ipToUse,
8649
- port: portToUse,
8646
+ ip: realIp,
8647
+ port: realPort,
8648
+ url: `http://${realIp}:${realPort}/v1/graphql`,
8650
8649
  snapshotDir: snapshotDirToUse
8651
8650
  });
8652
8651
  }
8653
- if (/error/i.test(chunk)) {
8654
- reject(chunk.toString());
8652
+ if (/error/i.test(text)) {
8653
+ reject(text.toString());
8655
8654
  }
8656
8655
  });
8657
8656
  process.on("exit", () => killNode(cleanupConfig));
@@ -8684,11 +8683,245 @@ var launchNodeAndGetWallets = async ({
8684
8683
  };
8685
8684
  return { wallets, stop: cleanup, provider };
8686
8685
  };
8686
+
8687
+ // src/test-utils/setup-test-provider-and-wallets.ts
8688
+ import { defaultSnapshotConfigs as defaultSnapshotConfigs3 } from "@fuel-ts/utils";
8689
+ import { mergeDeepRight } from "ramda";
8690
+
8691
+ // src/test-utils/asset-id.ts
8692
+ import { randomBytes as randomBytes7 } from "@fuel-ts/crypto";
8693
+ import { hexlify as hexlify19 } from "@fuel-ts/utils";
8694
+ var _AssetId = class {
8695
+ constructor(value) {
8696
+ this.value = value;
8697
+ }
8698
+ static random(count = 1) {
8699
+ const assetIds = [];
8700
+ for (let i = 0; i < count; i++) {
8701
+ assetIds.push(new _AssetId(hexlify19(randomBytes7(32))));
8702
+ }
8703
+ return assetIds;
8704
+ }
8705
+ };
8706
+ var AssetId = _AssetId;
8707
+ __publicField(AssetId, "A", new _AssetId(
8708
+ "0x0101010101010101010101010101010101010101010101010101010101010101"
8709
+ ));
8710
+ __publicField(AssetId, "B", new _AssetId(
8711
+ "0x0202020202020202020202020202020202020202020202020202020202020202"
8712
+ ));
8713
+
8714
+ // src/test-utils/wallet-config.ts
8715
+ import { randomBytes as randomBytes8 } from "@fuel-ts/crypto";
8716
+ import { FuelError as FuelError20 } from "@fuel-ts/errors";
8717
+ import { defaultSnapshotConfigs as defaultSnapshotConfigs2, hexlify as hexlify20 } from "@fuel-ts/utils";
8718
+ var WalletConfig = class {
8719
+ initialState;
8720
+ options;
8721
+ wallets;
8722
+ generateWallets = () => {
8723
+ const generatedWallets = [];
8724
+ for (let index = 1; index <= this.options.count; index++) {
8725
+ generatedWallets.push(new WalletUnlocked(randomBytes8(32)));
8726
+ }
8727
+ return generatedWallets;
8728
+ };
8729
+ constructor(baseAssetId, config) {
8730
+ WalletConfig.validate(config);
8731
+ this.options = config;
8732
+ const { assets: assets2, coinsPerAsset, amountPerCoin, messages } = this.options;
8733
+ this.wallets = this.generateWallets();
8734
+ this.initialState = {
8735
+ messages: WalletConfig.createMessages(this.wallets, messages),
8736
+ coins: WalletConfig.createCoins(
8737
+ this.wallets,
8738
+ baseAssetId,
8739
+ assets2,
8740
+ coinsPerAsset,
8741
+ amountPerCoin
8742
+ )
8743
+ };
8744
+ }
8745
+ apply(snapshotConfig) {
8746
+ return {
8747
+ ...snapshotConfig,
8748
+ stateConfig: {
8749
+ ...snapshotConfig?.stateConfig ?? defaultSnapshotConfigs2.stateConfig,
8750
+ coins: this.initialState.coins.concat(snapshotConfig?.stateConfig?.coins || []),
8751
+ messages: this.initialState.messages.concat(snapshotConfig?.stateConfig?.messages ?? [])
8752
+ }
8753
+ };
8754
+ }
8755
+ /**
8756
+ * Create messages for the wallets in the format that the chain expects.
8757
+ */
8758
+ static createMessages(wallets, messages) {
8759
+ return messages.map((msg) => wallets.map((wallet) => msg.toChainMessage(wallet.address))).flatMap((x) => x);
8760
+ }
8761
+ /**
8762
+ * Create coins for the wallets in the format that the chain expects.
8763
+ */
8764
+ static createCoins(wallets, baseAssetId, assets2, coinsPerAsset, amountPerCoin) {
8765
+ const coins = [];
8766
+ let assetIds = [baseAssetId];
8767
+ if (Array.isArray(assets2)) {
8768
+ assetIds = assetIds.concat(assets2.map((a) => a.value));
8769
+ } else {
8770
+ assetIds = assetIds.concat(AssetId.random(assets2).map((a) => a.value));
8771
+ }
8772
+ console.log("assetIds", assets2, assetIds);
8773
+ wallets.map((wallet) => wallet.address.toHexString()).forEach((walletAddress) => {
8774
+ assetIds.forEach((assetId) => {
8775
+ for (let index = 0; index < coinsPerAsset; index++) {
8776
+ coins.push({
8777
+ amount: amountPerCoin,
8778
+ asset_id: assetId,
8779
+ owner: walletAddress,
8780
+ tx_pointer_block_height: 0,
8781
+ tx_pointer_tx_idx: 0,
8782
+ output_index: 0,
8783
+ tx_id: hexlify20(randomBytes8(32))
8784
+ });
8785
+ }
8786
+ });
8787
+ });
8788
+ return coins;
8789
+ }
8790
+ static validate({
8791
+ count: wallets,
8792
+ assets: assets2,
8793
+ coinsPerAsset,
8794
+ amountPerCoin
8795
+ }) {
8796
+ if (Array.isArray(wallets) && wallets.length === 0 || typeof wallets === "number" && wallets <= 0) {
8797
+ throw new FuelError20(
8798
+ FuelError20.CODES.INVALID_INPUT_PARAMETERS,
8799
+ "Number of wallets must be greater than zero."
8800
+ );
8801
+ }
8802
+ if (Array.isArray(assets2) && assets2.length === 0 || typeof assets2 === "number" && assets2 <= 0) {
8803
+ throw new FuelError20(
8804
+ FuelError20.CODES.INVALID_INPUT_PARAMETERS,
8805
+ "Number of assets per wallet must be greater than zero."
8806
+ );
8807
+ }
8808
+ if (coinsPerAsset <= 0) {
8809
+ throw new FuelError20(
8810
+ FuelError20.CODES.INVALID_INPUT_PARAMETERS,
8811
+ "Number of coins per asset must be greater than zero."
8812
+ );
8813
+ }
8814
+ if (amountPerCoin <= 0) {
8815
+ throw new FuelError20(
8816
+ FuelError20.CODES.INVALID_INPUT_PARAMETERS,
8817
+ "Amount per coin must be greater than zero."
8818
+ );
8819
+ }
8820
+ }
8821
+ };
8822
+
8823
+ // src/test-utils/setup-test-provider-and-wallets.ts
8824
+ var defaultWalletConfigOptions = {
8825
+ count: 2,
8826
+ assets: [AssetId.A, AssetId.B],
8827
+ coinsPerAsset: 1,
8828
+ amountPerCoin: 1e10,
8829
+ messages: []
8830
+ };
8831
+ async function setupTestProviderAndWallets({
8832
+ walletConfig: walletConfigOptions = {},
8833
+ providerOptions,
8834
+ nodeOptions = {}
8835
+ } = {}) {
8836
+ Symbol.dispose ??= Symbol("Symbol.dispose");
8837
+ const walletConfig = new WalletConfig(
8838
+ nodeOptions.snapshotConfig?.chainConfig?.consensus_parameters?.V1?.base_asset_id ?? defaultSnapshotConfigs3.chainConfig.consensus_parameters.V1.base_asset_id,
8839
+ {
8840
+ ...defaultWalletConfigOptions,
8841
+ ...walletConfigOptions
8842
+ }
8843
+ );
8844
+ const { cleanup, url } = await launchNode({
8845
+ loggingEnabled: false,
8846
+ ...nodeOptions,
8847
+ snapshotConfig: mergeDeepRight(
8848
+ defaultSnapshotConfigs3,
8849
+ walletConfig.apply(nodeOptions?.snapshotConfig)
8850
+ ),
8851
+ port: "0"
8852
+ });
8853
+ let provider;
8854
+ try {
8855
+ provider = await Provider.create(url, providerOptions);
8856
+ } catch (err) {
8857
+ cleanup();
8858
+ throw err;
8859
+ }
8860
+ const wallets = walletConfig.wallets;
8861
+ wallets.forEach((wallet) => {
8862
+ wallet.connect(provider);
8863
+ });
8864
+ return {
8865
+ provider,
8866
+ wallets,
8867
+ cleanup,
8868
+ [Symbol.dispose]: cleanup
8869
+ };
8870
+ }
8871
+
8872
+ // src/test-utils/test-message.ts
8873
+ import { Address as Address6 } from "@fuel-ts/address";
8874
+ import { randomBytes as randomBytes9 } from "@fuel-ts/crypto";
8875
+ import { bn as bn21 } from "@fuel-ts/math";
8876
+ import { hexlify as hexlify21 } from "@fuel-ts/utils";
8877
+ var TestMessage = class {
8878
+ sender;
8879
+ recipient;
8880
+ nonce;
8881
+ amount;
8882
+ data;
8883
+ da_height;
8884
+ /**
8885
+ * A helper class to create messages for testing purposes.
8886
+ *
8887
+ * Used in tandem with `WalletConfig`.
8888
+ * It can also be used standalone and passed into the initial state of a chain via the `.toChainMessage` method.
8889
+ */
8890
+ constructor({
8891
+ sender = Address6.fromRandom(),
8892
+ recipient = Address6.fromRandom(),
8893
+ nonce = hexlify21(randomBytes9(32)),
8894
+ amount = 1e6,
8895
+ data = "02",
8896
+ da_height = 0
8897
+ } = {}) {
8898
+ this.sender = sender;
8899
+ this.recipient = recipient;
8900
+ this.nonce = nonce;
8901
+ this.amount = amount;
8902
+ this.data = data;
8903
+ this.da_height = da_height;
8904
+ }
8905
+ toChainMessage(recipient) {
8906
+ return {
8907
+ sender: this.sender.toB256(),
8908
+ recipient: recipient?.toB256() ?? this.recipient.toB256(),
8909
+ nonce: this.nonce,
8910
+ amount: bn21(this.amount).toNumber(),
8911
+ data: this.data,
8912
+ da_height: this.da_height
8913
+ };
8914
+ }
8915
+ };
8687
8916
  export {
8917
+ AssetId,
8918
+ TestMessage,
8919
+ WalletConfig,
8688
8920
  generateTestWallet,
8689
8921
  killNode,
8690
8922
  launchNode,
8691
8923
  launchNodeAndGetWallets,
8692
- seedTestWallet
8924
+ seedTestWallet,
8925
+ setupTestProviderAndWallets
8693
8926
  };
8694
8927
  //# sourceMappingURL=test-utils.mjs.map