From facff0863085f4676873869780c1b1346ba440f6 Mon Sep 17 00:00:00 2001 From: Saurabh Chauhan <36479565+starc007@users.noreply.github.com> Date: Wed, 27 Nov 2024 00:36:50 +0530 Subject: [PATCH 01/13] feat: integrate vitest matchers globally --- packages/fuel-gauge/src/abi/abi-coder.test.ts | 12 ---- packages/fuel-gauge/src/abi/vitest.matcher.ts | 55 ++++++++++++++----- packages/fuel-gauge/src/test/setup.ts | 4 ++ vitest.shared.config.mts | 1 + 4 files changed, 47 insertions(+), 25 deletions(-) create mode 100644 packages/fuel-gauge/src/test/setup.ts diff --git a/packages/fuel-gauge/src/abi/abi-coder.test.ts b/packages/fuel-gauge/src/abi/abi-coder.test.ts index cf3b9459fbd..5f7fe677b1a 100644 --- a/packages/fuel-gauge/src/abi/abi-coder.test.ts +++ b/packages/fuel-gauge/src/abi/abi-coder.test.ts @@ -47,9 +47,6 @@ import { U8_MAX, U8_MIN, } from './constants'; -import { toEqualBn } from './vitest.matcher'; - -expect.extend({ toEqualBn }); /** * @group browser @@ -761,7 +758,6 @@ describe('AbiCoder', () => { const EXPECTED_STRUCT = { a: { - // @ts-expect-error: Custom matcher 'toEqualBn' a: expect.toEqualBn(20), }, b: 'B', @@ -885,7 +881,6 @@ describe('AbiCoder', () => { describe('types_struct_with_tuple', () => { it('should encode/decode just fine', async () => { const input: StructSingleGenericInput<[boolean, BigNumberish]> = { a: [true, 10] }; - // @ts-expect-error: Custom matcher 'toEqualBn' const expected = { a: [false, expect.toEqualBn(20)] }; const { waitForResult } = await contract.functions.types_struct_with_tuple(input).call(); @@ -942,7 +937,6 @@ describe('AbiCoder', () => { describe('types_struct_external', () => { it('should encode/decode just fine', async () => { const input = { value: 10 }; - // @ts-expect-error: Custom matcher 'toEqualBn' const expected = { value: expect.toEqualBn(20) }; const { waitForResult } = await contract.functions.types_struct_external(input).call(); @@ -1136,7 +1130,6 @@ describe('AbiCoder', () => { it('should encode/decode just fine', async () => { const INPUT_STRUCT = { a: { a: 10 }, b: 'A' }; const input: StructWithNestedArrayInput = { a: [INPUT_STRUCT, INPUT_STRUCT] }; - // @ts-expect-error: Custom matcher 'toEqualBn' const EXPECTED_STRUCT = { a: { a: expect.toEqualBn(20) }, b: 'B' }; const EXPECTED = { a: [EXPECTED_STRUCT, EXPECTED_STRUCT] }; @@ -1170,7 +1163,6 @@ describe('AbiCoder', () => { describe('types_struct_with_nested_tuple', () => { it('should encode/decode just fine', async () => { const input: StructWithNestedTupleInput = { a: [10, { a: { a: 20 } }, 'ABC'] }; - // @ts-expect-error: Custom matcher 'toEqualBn' const expected = { a: [30, { a: { a: expect.toEqualBn(40) } }, 'CBA'] }; const { waitForResult } = await contract.functions @@ -1375,7 +1367,6 @@ describe('AbiCoder', () => { StructSingleGenericInput>, string, ]; - // @ts-expect-error: Custom matcher 'toEqualBn' const expected = [3, { a: { a: expect.toEqualBn(30) } }, 'CBA']; const { waitForResult } = await contract.functions.types_tuple_complex(input).call(); @@ -1505,7 +1496,6 @@ describe('AbiCoder', () => { describe('types_enum_with_builtin_type', () => { it('should encode/decode just fine', async () => { const input: EnumWithBuiltinTypeInput = { a: true }; - // @ts-expect-error: Custom matcher 'toEqualBn' const expected: EnumWithBuiltinTypeOutput = { b: expect.toEqualBn(20) }; const { waitForResult } = await contract.functions.types_enum_with_builtin_type(input).call(); @@ -2053,7 +2043,6 @@ describe('AbiCoder', () => { Ok: 10, }; const expected: Result = { - // @ts-expect-error: Custom matcher 'toEqualBn' Ok: expect.toEqualBn(2), }; @@ -2292,7 +2281,6 @@ describe('AbiCoder', () => { it('should encode/decode just fine', async () => { const inputX = 1; const inputY = 2; - // @ts-expect-error: Custom matcher 'toEqualBn' const expected = expect.toEqualBn(3); const { waitForResult } = await contract.functions.multi_arg_u64_u64(inputX, inputY).call(); diff --git a/packages/fuel-gauge/src/abi/vitest.matcher.ts b/packages/fuel-gauge/src/abi/vitest.matcher.ts index 32a1cd3b4a8..bc35ff8ea17 100644 --- a/packages/fuel-gauge/src/abi/vitest.matcher.ts +++ b/packages/fuel-gauge/src/abi/vitest.matcher.ts @@ -1,20 +1,49 @@ import { bn } from 'fuels'; import type { BNInput } from 'fuels'; -export const toEqualBn = (_received: BNInput, _argument: BNInput) => { - const received = bn(_received); - const argument = bn(_argument); +type MatcherResult = { + message: () => string; + pass: boolean; +}; - const pass = received.eq(argument); +type BNAsymmetricMatcher = { + asymmetricMatch(actual: BNInput): boolean; + toString(): string; +}; - if (pass) { - return { - message: () => `Expected ${received.toString()} not to equal ${argument.toString()}`, - pass: true, - }; +declare module 'vitest' { + interface Expect { + toEqualBn(expected: BNInput): void; + } + interface ExpectStatic { + toEqualBn(expected: BNInput): BNAsymmetricMatcher; + } + interface AsymmetricMatchersContaining { + toEqualBn(expected: BNInput): BNAsymmetricMatcher; } - return { - message: () => `expected ${received.toString()} to equal ${argument.toString()}`, - pass: false, - }; +} + +const createMatcher = (expected: BNInput): BNAsymmetricMatcher => ({ + asymmetricMatch: (actual: BNInput) => bn(actual).eq(bn(expected)), + toString: () => `BNMatcher(${expected})`, +}); + +export const setupTestMatchers = () => { + expect.extend({ + toEqualBn(received: BNInput, expected: BNInput): MatcherResult { + const actualBn = bn(received); + const expectedBn = bn(expected); + const pass = actualBn.eq(expectedBn); + + return { + pass, + message: () => + pass + ? `Expected ${actualBn.toString()} not to equal ${expectedBn.toString()}` + : `Expected ${actualBn.toString()} to equal ${expectedBn.toString()}`, + }; + }, + }); + + expect.toEqualBn = createMatcher; }; diff --git a/packages/fuel-gauge/src/test/setup.ts b/packages/fuel-gauge/src/test/setup.ts new file mode 100644 index 00000000000..8c97ef349eb --- /dev/null +++ b/packages/fuel-gauge/src/test/setup.ts @@ -0,0 +1,4 @@ +import { setupTestMatchers } from '../abi/vitest.matcher'; + +// Call the setup function immediately +setupTestMatchers(); diff --git a/vitest.shared.config.mts b/vitest.shared.config.mts index dbde7fc4409..1270cf02afb 100644 --- a/vitest.shared.config.mts +++ b/vitest.shared.config.mts @@ -17,6 +17,7 @@ export default defineConfig({ esbuild: { target: "es2022" }, test: { globalSetup: ["vitest.global-setup.ts"], + setupFiles: ["./packages/fuel-gauge/src/test/setup.ts"], coverage: { enabled: true, provider: "istanbul", From b70acc1e24947f94c0c565c25b9a270b29b886da Mon Sep 17 00:00:00 2001 From: Saurabh Chauhan <36479565+starc007@users.noreply.github.com> Date: Sat, 30 Nov 2024 02:16:42 +0530 Subject: [PATCH 02/13] fix: added global type file & changed setup file directory --- .changeset/clean-plums-wait.md | 5 ++ packages/fuel-gauge/global.d.ts | 15 ++++++ packages/fuel-gauge/src/abi/vitest.matcher.ts | 47 +++++++------------ packages/fuel-gauge/src/test/setup.ts | 4 -- packages/fuel-gauge/tsconfig.json | 5 +- packages/fuel-gauge/vitest.setup.ts | 3 ++ vitest.shared.config.mts | 2 +- 7 files changed, 45 insertions(+), 36 deletions(-) create mode 100644 .changeset/clean-plums-wait.md create mode 100644 packages/fuel-gauge/global.d.ts delete mode 100644 packages/fuel-gauge/src/test/setup.ts create mode 100644 packages/fuel-gauge/vitest.setup.ts diff --git a/.changeset/clean-plums-wait.md b/.changeset/clean-plums-wait.md new file mode 100644 index 00000000000..97cca38a5bc --- /dev/null +++ b/.changeset/clean-plums-wait.md @@ -0,0 +1,5 @@ +--- +"fuels": minor +--- + +chore: integrate vitest matchers globally diff --git a/packages/fuel-gauge/global.d.ts b/packages/fuel-gauge/global.d.ts new file mode 100644 index 00000000000..9e70609e8d3 --- /dev/null +++ b/packages/fuel-gauge/global.d.ts @@ -0,0 +1,15 @@ +import type { BNInput } from 'fuels'; + +declare global { + namespace Vitest { + interface Assertion { + toEqualBn(expected: BNInput): void; + } + interface ExpectStatic { + toEqualBn(expected: BNInput): { + asymmetricMatch(actual: BNInput): boolean; + toString(): string; + }; + } + } +} diff --git a/packages/fuel-gauge/src/abi/vitest.matcher.ts b/packages/fuel-gauge/src/abi/vitest.matcher.ts index bc35ff8ea17..811d3f181c0 100644 --- a/packages/fuel-gauge/src/abi/vitest.matcher.ts +++ b/packages/fuel-gauge/src/abi/vitest.matcher.ts @@ -1,49 +1,38 @@ import { bn } from 'fuels'; -import type { BNInput } from 'fuels'; +import type { BNInput, BN } from 'fuels'; -type MatcherResult = { - message: () => string; - pass: boolean; -}; - -type BNAsymmetricMatcher = { - asymmetricMatch(actual: BNInput): boolean; - toString(): string; -}; +interface Matchers { + toEqualBn: (expected: BNInput) => R; +} declare module 'vitest' { - interface Expect { - toEqualBn(expected: BNInput): void; - } + interface Assertion extends Matchers {} + interface AsymmetricMatchersContaining extends Matchers {} interface ExpectStatic { - toEqualBn(expected: BNInput): BNAsymmetricMatcher; - } - interface AsymmetricMatchersContaining { - toEqualBn(expected: BNInput): BNAsymmetricMatcher; + toEqualBn(expected: BNInput): BN; } } -const createMatcher = (expected: BNInput): BNAsymmetricMatcher => ({ - asymmetricMatch: (actual: BNInput) => bn(actual).eq(bn(expected)), - toString: () => `BNMatcher(${expected})`, -}); - export const setupTestMatchers = () => { expect.extend({ - toEqualBn(received: BNInput, expected: BNInput): MatcherResult { + toEqualBn(received: BNInput, expected: BNInput) { const actualBn = bn(received); const expectedBn = bn(expected); const pass = actualBn.eq(expectedBn); + if (pass) { + return { + pass, + message: () => `Expected ${actualBn} not to equal ${expectedBn}`, + actual: actualBn, + }; + } + return { pass, - message: () => - pass - ? `Expected ${actualBn.toString()} not to equal ${expectedBn.toString()}` - : `Expected ${actualBn.toString()} to equal ${expectedBn.toString()}`, + message: () => `Expected ${actualBn} to equal ${expectedBn}`, + actual: expectedBn, }; }, }); - - expect.toEqualBn = createMatcher; }; diff --git a/packages/fuel-gauge/src/test/setup.ts b/packages/fuel-gauge/src/test/setup.ts deleted file mode 100644 index 8c97ef349eb..00000000000 --- a/packages/fuel-gauge/src/test/setup.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { setupTestMatchers } from '../abi/vitest.matcher'; - -// Call the setup function immediately -setupTestMatchers(); diff --git a/packages/fuel-gauge/tsconfig.json b/packages/fuel-gauge/tsconfig.json index b22c89a4b35..1caadd4e332 100644 --- a/packages/fuel-gauge/tsconfig.json +++ b/packages/fuel-gauge/tsconfig.json @@ -1,7 +1,8 @@ { "extends": "../../tsconfig.base.json", "compilerOptions": { - "outDir": "./dist" + "outDir": "./dist", + "types": ["vitest/globals"] }, - "include": ["src", "test"] + "include": ["src", "global.d.ts"] } diff --git a/packages/fuel-gauge/vitest.setup.ts b/packages/fuel-gauge/vitest.setup.ts new file mode 100644 index 00000000000..4179c5c2e08 --- /dev/null +++ b/packages/fuel-gauge/vitest.setup.ts @@ -0,0 +1,3 @@ +import { setupTestMatchers } from './src/abi/vitest.matcher'; + +setupTestMatchers(); diff --git a/vitest.shared.config.mts b/vitest.shared.config.mts index 1270cf02afb..f4329d6039f 100644 --- a/vitest.shared.config.mts +++ b/vitest.shared.config.mts @@ -17,7 +17,7 @@ export default defineConfig({ esbuild: { target: "es2022" }, test: { globalSetup: ["vitest.global-setup.ts"], - setupFiles: ["./packages/fuel-gauge/src/test/setup.ts"], + setupFiles: ["./packages/fuel-gauge/vitest.setup.ts"], coverage: { enabled: true, provider: "istanbul", From 6fa356a92db94c53fd1b585d28a05b37877b052d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9rgio=20Torres?= <30977845+Torres-ssf@users.noreply.github.com> Date: Tue, 3 Dec 2024 22:44:58 -0300 Subject: [PATCH 03/13] docs: improve `cookbook/transaction-request` (#3440) --- .changeset/spicy-mails-sort.md | 4 ++ apps/docs/scripts/launcher-snippet.ts | 4 +- apps/docs/scripts/wrap-snippets.ts | 2 +- .../transaction-request/add-output-coin.ts | 26 ++++++++ .../transaction-request/add-predicate.ts | 4 +- .../transaction-request/add-witness.ts | 32 +++++----- .../transaction-request/estimate-and-fund.ts | 22 +++++++ .../transaction-request/fetch-coins.ts | 22 +++++++ .../transaction-request/fetch-resources.ts | 37 ++++++++++++ .../transaction-request/fund-request.ts | 59 ------------------- .../transaction-request/input-contract.ts | 20 +++++++ .../guide/transactions/transaction-request.md | 42 ++++++++++--- apps/docs/sway/Forc.toml | 1 + apps/docs/sway/script-call-contract/Forc.toml | 7 +++ .../sway/script-call-contract/src/counter.sw | 12 ++++ .../sway/script-call-contract/src/main.sw | 11 ++++ 16 files changed, 214 insertions(+), 91 deletions(-) create mode 100644 .changeset/spicy-mails-sort.md create mode 100644 apps/docs/src/guide/transactions/snippets/transaction-request/add-output-coin.ts create mode 100644 apps/docs/src/guide/transactions/snippets/transaction-request/estimate-and-fund.ts create mode 100644 apps/docs/src/guide/transactions/snippets/transaction-request/fetch-coins.ts create mode 100644 apps/docs/src/guide/transactions/snippets/transaction-request/fetch-resources.ts delete mode 100644 apps/docs/src/guide/transactions/snippets/transaction-request/fund-request.ts create mode 100644 apps/docs/src/guide/transactions/snippets/transaction-request/input-contract.ts create mode 100644 apps/docs/sway/script-call-contract/Forc.toml create mode 100644 apps/docs/sway/script-call-contract/src/counter.sw create mode 100644 apps/docs/sway/script-call-contract/src/main.sw diff --git a/.changeset/spicy-mails-sort.md b/.changeset/spicy-mails-sort.md new file mode 100644 index 00000000000..14b887f7d93 --- /dev/null +++ b/.changeset/spicy-mails-sort.md @@ -0,0 +1,4 @@ +--- +--- + +docs: improve `cookbook/transaction-request` diff --git a/apps/docs/scripts/launcher-snippet.ts b/apps/docs/scripts/launcher-snippet.ts index 2d4dd03089b..72e573112ea 100644 --- a/apps/docs/scripts/launcher-snippet.ts +++ b/apps/docs/scripts/launcher-snippet.ts @@ -1,6 +1,6 @@ -import { launchTestNode } from 'fuels/test-utils'; +import { launchTestNode, TestMessage } from 'fuels/test-utils'; -using node = await launchTestNode({ walletsConfig: { count: 5 } }); +using node = await launchTestNode({ walletsConfig: { count: 5, messages: [new TestMessage()] } }); const LOCAL_NETWORK_URL = node.provider.url; diff --git a/apps/docs/scripts/wrap-snippets.ts b/apps/docs/scripts/wrap-snippets.ts index 11ff2fc0a37..98de3b93e65 100644 --- a/apps/docs/scripts/wrap-snippets.ts +++ b/apps/docs/scripts/wrap-snippets.ts @@ -67,7 +67,7 @@ export const wrapSnippet = (filepath: string) => { Adds `launchTestNode` import, always right below the last `fuels` import and before the next relative one. */ - const launchImport = `import { launchTestNode } from 'fuels/test-utils';`; + const launchImport = `import { launchTestNode, TestMessage } from 'fuels/test-utils';`; const searchStr = `from 'fuels';`; const lastIndexStart = imports.lastIndexOf(searchStr); diff --git a/apps/docs/src/guide/transactions/snippets/transaction-request/add-output-coin.ts b/apps/docs/src/guide/transactions/snippets/transaction-request/add-output-coin.ts new file mode 100644 index 00000000000..568c2b300b8 --- /dev/null +++ b/apps/docs/src/guide/transactions/snippets/transaction-request/add-output-coin.ts @@ -0,0 +1,26 @@ +import { Provider, ScriptTransactionRequest, Wallet } from 'fuels'; +import { TestAssetId } from 'fuels/test-utils'; + +import { + LOCAL_NETWORK_URL, + WALLET_PVT_KEY, + WALLET_PVT_KEY_2, +} from '../../../../env'; +import { ScriptSum } from '../../../../typegend'; + +// #region transaction-request-3 +const provider = await Provider.create(LOCAL_NETWORK_URL); + +const recipient1 = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider); +const recipient2 = Wallet.fromPrivateKey(WALLET_PVT_KEY_2, provider); + +const baseAssetId = provider.getBaseAssetId(); +const assetA = TestAssetId.A.value; + +const transactionRequest = new ScriptTransactionRequest({ + script: ScriptSum.bytecode, +}); + +transactionRequest.addCoinOutput(recipient1.address, 1000, baseAssetId); +transactionRequest.addCoinOutput(recipient2.address, 500, assetA); +// #endregion transaction-request-3 diff --git a/apps/docs/src/guide/transactions/snippets/transaction-request/add-predicate.ts b/apps/docs/src/guide/transactions/snippets/transaction-request/add-predicate.ts index 1b867ddbcba..557fe8df8b8 100644 --- a/apps/docs/src/guide/transactions/snippets/transaction-request/add-predicate.ts +++ b/apps/docs/src/guide/transactions/snippets/transaction-request/add-predicate.ts @@ -13,7 +13,7 @@ import { ScriptSum, SimplePredicate } from '../../../../typegend'; const provider = await Provider.create(LOCAL_NETWORK_URL); const wallet = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider); -// #region transaction-request-5 +// #region transaction-request-9 // Instantiate the transaction request const transactionRequest = new ScriptTransactionRequest({ script: ScriptSum.bytecode, @@ -42,4 +42,4 @@ const predicateCoins = await predicate.getResourcesToSpend([ // Add the predicate input and resources transactionRequest.addResources(predicateCoins); -// #endregion transaction-request-5 +// #endregion transaction-request-9 diff --git a/apps/docs/src/guide/transactions/snippets/transaction-request/add-witness.ts b/apps/docs/src/guide/transactions/snippets/transaction-request/add-witness.ts index ac601192485..3903cd1eec2 100644 --- a/apps/docs/src/guide/transactions/snippets/transaction-request/add-witness.ts +++ b/apps/docs/src/guide/transactions/snippets/transaction-request/add-witness.ts @@ -1,38 +1,34 @@ -import type { Account } from 'fuels'; -import { - Provider, - ScriptTransactionRequest, - WalletUnlocked, - ZeroBytes32, -} from 'fuels'; - -import { LOCAL_NETWORK_URL } from '../../../../env'; +import { Provider, ScriptTransactionRequest, Wallet } from 'fuels'; + +import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../../env'; import { ScriptSum } from '../../../../typegend'; +// #region transaction-request-10 const provider = await Provider.create(LOCAL_NETWORK_URL); -const witness = ZeroBytes32; +const accountA = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider); +const accountB = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider); const transactionRequest = new ScriptTransactionRequest({ script: ScriptSum.bytecode, }); -// #region transaction-request-6 // Add a witness directly -transactionRequest.addWitness(witness); +// Add a witness signature directly +const signature = await accountA.signTransaction(transactionRequest); +transactionRequest.addWitness(signature); -// Add a witness using an account -const account: Account = WalletUnlocked.generate({ provider }); -await transactionRequest.addAccountWitnesses(account); -// #endregion transaction-request-6 +// Or add multiple via `addAccountWitnesses` +await transactionRequest.addAccountWitnesses([accountB]); +// #endregion transaction-request-10 -// #region transaction-request-7 +// #region transaction-request-11 // Get the chain ID const chainId = provider.getChainId(); // Get the transaction ID using the Chain ID const transactionId = transactionRequest.getTransactionId(chainId); // TX ID: 0x420f6... -// #endregion transaction-request-7 +// #endregion transaction-request-11 console.log('transactionId', transactionId); console.log('witnesses', transactionRequest.witnesses.length === 2); diff --git a/apps/docs/src/guide/transactions/snippets/transaction-request/estimate-and-fund.ts b/apps/docs/src/guide/transactions/snippets/transaction-request/estimate-and-fund.ts new file mode 100644 index 00000000000..4b593a11678 --- /dev/null +++ b/apps/docs/src/guide/transactions/snippets/transaction-request/estimate-and-fund.ts @@ -0,0 +1,22 @@ +import { Provider, ScriptTransactionRequest, Wallet } from 'fuels'; + +import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../../env'; +import { ScriptSum } from '../../../../typegend'; + +const provider = await Provider.create(LOCAL_NETWORK_URL); +const wallet = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider); + +// #region transaction-request-4 +const transactionRequest = new ScriptTransactionRequest({ + script: ScriptSum.bytecode, +}); + +const cost = await wallet.getTransactionCost(transactionRequest); + +transactionRequest.gasLimit = cost.gasUsed; +transactionRequest.maxFee = cost.maxFee; + +await wallet.fund(transactionRequest, cost); + +await wallet.sendTransaction(transactionRequest); +// #endregion transaction-request-4 diff --git a/apps/docs/src/guide/transactions/snippets/transaction-request/fetch-coins.ts b/apps/docs/src/guide/transactions/snippets/transaction-request/fetch-coins.ts new file mode 100644 index 00000000000..aedcb18b45f --- /dev/null +++ b/apps/docs/src/guide/transactions/snippets/transaction-request/fetch-coins.ts @@ -0,0 +1,22 @@ +import { Provider, ScriptTransactionRequest, Wallet } from 'fuels'; + +import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../../env'; +import { ScriptSum } from '../../../../typegend'; + +const provider = await Provider.create(LOCAL_NETWORK_URL); +const wallet = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider); +const baseAssetId = provider.getBaseAssetId(); + +const transactionRequest = new ScriptTransactionRequest({ + script: ScriptSum.bytecode, +}); + +// #region transaction-request-6 +// Fetching coins +const { coins } = await wallet.getCoins(baseAssetId); +const { messages } = await wallet.getMessages(); + +// Adding a specific coin or message +transactionRequest.addCoinInput(coins[0]); +transactionRequest.addMessageInput(messages[0]); +// #endregion transaction-request-6 diff --git a/apps/docs/src/guide/transactions/snippets/transaction-request/fetch-resources.ts b/apps/docs/src/guide/transactions/snippets/transaction-request/fetch-resources.ts new file mode 100644 index 00000000000..dc7bec20eec --- /dev/null +++ b/apps/docs/src/guide/transactions/snippets/transaction-request/fetch-resources.ts @@ -0,0 +1,37 @@ +import type { CoinQuantity } from 'fuels'; +import { bn, Provider, ScriptTransactionRequest, Wallet } from 'fuels'; +import { TestAssetId } from 'fuels/test-utils'; + +import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../../env'; +import { ScriptSum } from '../../../../typegend'; + +const provider = await Provider.create(LOCAL_NETWORK_URL); +const wallet = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider); + +// #region transaction-request-5 +// Instantiate the transaction request +const transactionRequest = new ScriptTransactionRequest({ + script: ScriptSum.bytecode, +}); + +const baseAssetId = provider.getBaseAssetId(); +const assetA = TestAssetId.A.value; + +// Define the quantities to fetch +const quantities: CoinQuantity[] = [ + { + amount: bn(10000), + assetId: baseAssetId, + }, + { + amount: bn(100), + assetId: assetA, + }, +]; + +// Fetching resources +const resources = await wallet.getResourcesToSpend(quantities); + +// Adding resources (coins or messages) +transactionRequest.addResources(resources); +// #endregion transaction-request-5 diff --git a/apps/docs/src/guide/transactions/snippets/transaction-request/fund-request.ts b/apps/docs/src/guide/transactions/snippets/transaction-request/fund-request.ts deleted file mode 100644 index ab8f0294a51..00000000000 --- a/apps/docs/src/guide/transactions/snippets/transaction-request/fund-request.ts +++ /dev/null @@ -1,59 +0,0 @@ -import type { Coin, MessageCoin, Resource } from 'fuels'; -import { Address, bn, Provider, ScriptTransactionRequest, Wallet } from 'fuels'; - -import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../../env'; -import { CounterFactory, ScriptSum } from '../../../../typegend'; - -const provider = await Provider.create(LOCAL_NETWORK_URL); -const wallet = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider); -const address = Address.fromRandom(); - -const message: MessageCoin = { - assetId: provider.getBaseAssetId(), - sender: address, - recipient: address, - nonce: '0x', - amount: bn(0), - daHeight: bn(0), -}; -const coin: Coin = { - id: '0x', - assetId: provider.getBaseAssetId(), - amount: bn(0), - owner: address, - blockCreated: bn(0), - txCreatedIdx: bn(0), -}; -const recipientAddress = address; -const resource = coin; -const resources: Resource[] = [resource]; - -// #region transaction-request-3 -// Instantiate the transaction request -const transactionRequest = new ScriptTransactionRequest({ - script: ScriptSum.bytecode, -}); - -// Adding resources (coins or messages) -transactionRequest.addResources(resources); -transactionRequest.addResource(resource); - -// Adding coin inputs and outputs (including transfer to recipient) -transactionRequest.addCoinInput(coin); -transactionRequest.addCoinOutput( - recipientAddress, - 1000, - provider.getBaseAssetId() -); - -// Adding message inputs -transactionRequest.addMessageInput(message); -// #endregion transaction-request-3 - -// #region transaction-request-4 -const deploy = await CounterFactory.deploy(wallet); -const { contract } = await deploy.waitForResult(); - -// Add the contract input and output using the contract ID -transactionRequest.addContractInputAndOutput(contract.id); -// #endregion transaction-request-4 diff --git a/apps/docs/src/guide/transactions/snippets/transaction-request/input-contract.ts b/apps/docs/src/guide/transactions/snippets/transaction-request/input-contract.ts new file mode 100644 index 00000000000..ccb38131e4c --- /dev/null +++ b/apps/docs/src/guide/transactions/snippets/transaction-request/input-contract.ts @@ -0,0 +1,20 @@ +import { Provider, ScriptTransactionRequest, Wallet } from 'fuels'; + +import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../../env'; +import { CounterFactory, ScriptSum } from '../../../../typegend'; + +const provider = await Provider.create(LOCAL_NETWORK_URL); +const wallet = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider); + +// #region transaction-request-8 +const deploy = await CounterFactory.deploy(wallet); +const { contract } = await deploy.waitForResult(); + +const transactionRequest = new ScriptTransactionRequest({ + script: ScriptSum.bytecode, + scriptData: contract.id.toB256(), +}); + +// Add the contract input and output using the contract ID +transactionRequest.addContractInputAndOutput(contract.id); +// #endregion transaction-request-8 diff --git a/apps/docs/src/guide/transactions/transaction-request.md b/apps/docs/src/guide/transactions/transaction-request.md index ede75601993..95ceb4847bb 100644 --- a/apps/docs/src/guide/transactions/transaction-request.md +++ b/apps/docs/src/guide/transactions/transaction-request.md @@ -30,23 +30,47 @@ A `CreateTransactionRequest` is used for create transactions, which are transact Once you have instantiated a transaction request, you can modify it by setting the transaction parameters and policies. This can either be done manually by directly altering the transaction request object, or through helper methods that are available on the above classes. -### Adding Resources to a Transaction Request +### Adding `OutputCoin` -Resources populate the inputs and outputs of a transaction request. This can take the form of coins, messages or contracts. The SDK provides a range of methods for dealing with resources. Below will detail how coins and messages can be added to a transaction request. +Including `OutputCoin`s in the transaction request specifies the UTXOs that will be created once the transaction is processed. These UTXOs represent the amounts being transferred to specified account addresses during the transaction: -<<< @./snippets/transaction-request/fund-request.ts#transaction-request-3{ts:line-numbers} +<<< @./snippets/transaction-request/add-output-coin.ts#transaction-request-3{ts:line-numbers} -### Adding a Contract to a Transaction Request +### Estimating and Funding the Transaction Request -Scripts can perform multiple actions on chain, therefore you may want to chain contract calls. For this you will need to add a contract to the transaction request. This can be done like so: +Before submitting a transaction, it is essential to ensure it is properly funded to meet its requirements and cover the associated fee: -<<< @./snippets/transaction-request/fund-request.ts#transaction-request-4{ts:line-numbers} +<<< @./snippets/transaction-request/estimate-and-fund.ts#transaction-request-4{ts:line-numbers} + +This is the recommended approach for manually estimating and funding a transaction before submission. It ensures that the `gasLimit` and `maxFee` are accurately calculated and that the required amounts for `OutputCoin`s are fulfilled. The `fund` method automatically fetches any missing resource amounts from the calling account and adds them to the transaction request. + +### Manually Fetching Resources + +In certain scenarios, you may need to manually fetch resources. This can be achieved using the `getResourcesToSpend` method, which accepts an array of `CoinQuantities` and returns the necessary resources to meet the specified amounts: + +<<< @./snippets/transaction-request/fetch-resources.ts#transaction-request-5{ts:line-numbers} + +#### Manually Fetching Coins or Messages + +If needed, you can manually include specific coins or messages in the transaction. However, this approach is generally discouraged and should only be used in scenarios where explicitly adding particular coins or messages to the transaction request is required: + +<<< @./snippets/transaction-request/fetch-coins.ts#transaction-request-6{ts:line-numbers} + +### Adding a Contract Input and Output to a Transaction Request + +Imagine that you have a Sway script that manually calls a contract: + +<<< @../../../../sway/script-call-contract/src/main.sw#transaction-request-7{rs:line-numbers} + +In those cases, you will need to add both an `InputContract` and `OutputContract` to the transaction request: + +<<< @./snippets/transaction-request/input-contract.ts#transaction-request-8{ts:line-numbers} ### Adding a Predicate to a Transaction Request Predicates are used to define the conditions under which a transaction can be executed. Therefore you may want to add a predicate to a transaction request to unlock funds that are utilized by a script. This can be added like so: -<<< @./snippets/transaction-request/add-predicate.ts#transaction-request-5{ts:line-numbers} +<<< @./snippets/transaction-request/add-predicate.ts#transaction-request-9{ts:line-numbers} > **Note**: For more information on predicates, including information on configuring them, funding them and using them to unlock funds, please refer to the [predicate guide](../predicates/index.md). @@ -54,7 +78,7 @@ Predicates are used to define the conditions under which a transaction can be ex The SDK provides a way of either modifying the witnesses for a transaction request directly, or by passing accounts. This will then sign the transaction request with the account's private key. Below will detail how to add a witness to a transaction request: -<<< @./snippets/transaction-request/add-witness.ts#transaction-request-6{ts:line-numbers} +<<< @./snippets/transaction-request/add-witness.ts#transaction-request-10{ts:line-numbers} A more complex example of adding multiple witnesses to a transaction request can be seen in the multiple signers guide [here](../cookbook/transactions-with-multiple-signers.md), which validates the signatures inside the script itself. @@ -64,6 +88,6 @@ A more complex example of adding multiple witnesses to a transaction request can The transaction ID is a SHA-256 hash of the entire transaction request. This can be useful for tracking the transaction on chain. To get the transaction ID, you can use the following method: -<<< @./snippets/transaction-request/add-witness.ts#transaction-request-7{ts:line-numbers} +<<< @./snippets/transaction-request/add-witness.ts#transaction-request-11{ts:line-numbers} > **Note**: Any changes made to a transaction request will alter the transaction ID. Therefore, you should only get the transaction ID after all modifications have been made. diff --git a/apps/docs/sway/Forc.toml b/apps/docs/sway/Forc.toml index b737384200f..f5103be9737 100644 --- a/apps/docs/sway/Forc.toml +++ b/apps/docs/sway/Forc.toml @@ -32,6 +32,7 @@ members = [ "simple-predicate", "simple-token", "simple-token-abi", + "script-call-contract", "storage-test-contract", "sum-option-u8", "token", diff --git a/apps/docs/sway/script-call-contract/Forc.toml b/apps/docs/sway/script-call-contract/Forc.toml new file mode 100644 index 00000000000..4fa1432ff68 --- /dev/null +++ b/apps/docs/sway/script-call-contract/Forc.toml @@ -0,0 +1,7 @@ +[project] +authors = ["Fuel Labs "] +entry = "main.sw" +license = "Apache-2.0" +name = "script-call-contract" + +[dependencies] diff --git a/apps/docs/sway/script-call-contract/src/counter.sw b/apps/docs/sway/script-call-contract/src/counter.sw new file mode 100644 index 00000000000..32217e37d56 --- /dev/null +++ b/apps/docs/sway/script-call-contract/src/counter.sw @@ -0,0 +1,12 @@ +library; + +abi CounterAbi { + #[storage(read)] + fn get_count() -> u64; + + #[storage(write, read)] + fn increment_count(amount: u64) -> u64; + + #[storage(write, read)] + fn decrement_count(amount: u64) -> u64; +} diff --git a/apps/docs/sway/script-call-contract/src/main.sw b/apps/docs/sway/script-call-contract/src/main.sw new file mode 100644 index 00000000000..0e29bf7c735 --- /dev/null +++ b/apps/docs/sway/script-call-contract/src/main.sw @@ -0,0 +1,11 @@ +script; + +mod counter; + +// #region transaction-request-7 +use counter::CounterAbi; +fn main(contract_id: ContractId) -> u64 { + let counter_contract = abi(CounterAbi, contract_id.into()); + counter_contract.get_count() +} +// #endregion transaction-request-7 From c4e65e3436791b379240b9b081d993cf18af4b14 Mon Sep 17 00:00:00 2001 From: Daniel Bate Date: Fri, 6 Dec 2024 14:44:15 +0000 Subject: [PATCH 04/13] chore: silence recipes format logs (#3451) * chore: silence recipe logs * chore: update changeset --- .changeset/afraid-ligers-work.md | 4 ++++ packages/recipes/package.json | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 .changeset/afraid-ligers-work.md diff --git a/.changeset/afraid-ligers-work.md b/.changeset/afraid-ligers-work.md new file mode 100644 index 00000000000..4e57acc6d8f --- /dev/null +++ b/.changeset/afraid-ligers-work.md @@ -0,0 +1,4 @@ +--- +--- + +chore: silence recipes format logs diff --git a/packages/recipes/package.json b/packages/recipes/package.json index ad436f02427..71718d8ace9 100644 --- a/packages/recipes/package.json +++ b/packages/recipes/package.json @@ -23,7 +23,7 @@ "build": "run-s build:package build:recipes build:format", "build:package": "tsup", "build:recipes": "tsx ./scripts/build-recipes.ts", - "build:format": "prettier --config ../../.prettierrc --write .", + "build:format": "prettier --config ../../.prettierrc --log-level error --write .", "postbuild": "tsx ../../scripts/postbuild.ts" }, "license": "Apache-2.0", From 4ff8c3b050b173a64d1a87709101c0737b951c64 Mon Sep 17 00:00:00 2001 From: Peter Smith Date: Sat, 7 Dec 2024 13:37:33 +0000 Subject: [PATCH 05/13] docs: fix api links (#3452) * docs: fixing API links * chore: fixing relative links --- .../src/guide/contracts/contract-balance.md | 2 +- .../src/guide/contracts/cost-estimation.md | 2 +- .../guide/contracts/dependency-estimation.md | 2 +- .../guide/contracts/deploying-contracts.md | 2 +- .../guide/contracts/minted-token-asset-id.md | 2 +- apps/docs/src/guide/predicates/methods.md | 2 +- .../src/guide/provider/provider-options.md | 2 +- .../guide/testing/launching-a-test-node.md | 2 +- apps/docs/src/guide/utilities/using-assets.md | 4 +-- .../src/guide/wallets/checking-balances.md | 4 +-- apps/docs/src/guide/wallets/connectors.md | 26 +++++++++---------- 11 files changed, 25 insertions(+), 25 deletions(-) diff --git a/apps/docs/src/guide/contracts/contract-balance.md b/apps/docs/src/guide/contracts/contract-balance.md index 2aa3867ea16..aa60d1a211c 100644 --- a/apps/docs/src/guide/contracts/contract-balance.md +++ b/apps/docs/src/guide/contracts/contract-balance.md @@ -4,7 +4,7 @@ When working with contracts, it's crucial to be aware of the available contract ## The `getBalance` Method -The [`Contract.getBalance`](https://fuels-ts-docs-api.vercel.app/classes/_fuel_ts_program.Contract.html#getbalance) method retrieves the available balance of a specific asset on your contract. This method is particularly useful for determining the remaining balance after sending assets to a contract and executing contract calls. +The [`Contract.getBalance`](https://fuels-ts-docs-api.vercel.app/classes/_fuel_ts_program.Contract.html#getBalance) method retrieves the available balance of a specific asset on your contract. This method is particularly useful for determining the remaining balance after sending assets to a contract and executing contract calls. It is important to note that this method returns the total available contract balance, regardless of how often assets have been sent to it or spent. diff --git a/apps/docs/src/guide/contracts/cost-estimation.md b/apps/docs/src/guide/contracts/cost-estimation.md index 0039de9d2cf..020cea63a49 100644 --- a/apps/docs/src/guide/contracts/cost-estimation.md +++ b/apps/docs/src/guide/contracts/cost-estimation.md @@ -1,6 +1,6 @@ # Estimating Contract Call Cost -The [`FunctionInvocationScope.getTransactionCost`](https://fuels-ts-docs-api.vercel.app/classes/_fuel_ts_program.FunctionInvocationScope.html#gettransactioncost) method allows you to estimate the cost of a specific contract call. The return type, `TransactionCost`, is an object containing relevant information for the estimation: +The [`FunctionInvocationScope.getTransactionCost`](https://fuels-ts-docs-api.vercel.app/classes/_fuel_ts_program.FunctionInvocationScope.html#getTransactionCost) method allows you to estimate the cost of a specific contract call. The return type, `TransactionCost`, is an object containing relevant information for the estimation: <<< @/../../../packages/account/src/providers/provider.ts#cost-estimation-1{ts:line-numbers} diff --git a/apps/docs/src/guide/contracts/dependency-estimation.md b/apps/docs/src/guide/contracts/dependency-estimation.md index 718b1da118e..1511624f3e4 100644 --- a/apps/docs/src/guide/contracts/dependency-estimation.md +++ b/apps/docs/src/guide/contracts/dependency-estimation.md @@ -4,6 +4,6 @@ In [variable outputs](./variable-outputs.md), we mention that a contract call mi However, by default the SDK always automatically estimates these dependencies and double-checks if everything is in order whenever you invoke a contract function or attempt to send a transaction. -The SDK uses the [Provider.estimateTxDependencies](https://fuels-ts-docs-api.vercel.app/classes/_fuel_ts_account.Provider.html#estimatetxdependencies) method to set any missing dependencies identified during the estimation process. This requires simulating the transaction a few times in the background. +The SDK uses the [Provider.estimateTxDependencies](https://fuels-ts-docs-api.vercel.app/classes/_fuel_ts_account.Provider.html#estimateTxDependencies) method to set any missing dependencies identified during the estimation process. This requires simulating the transaction a few times in the background. While relying on the SDK's automatic estimation is a decent default behavior, we recommend manually specifying the dependencies if they are known in advance to avoid the performance impact of the estimation process. diff --git a/apps/docs/src/guide/contracts/deploying-contracts.md b/apps/docs/src/guide/contracts/deploying-contracts.md index 0a71cd61400..34571fb4039 100644 --- a/apps/docs/src/guide/contracts/deploying-contracts.md +++ b/apps/docs/src/guide/contracts/deploying-contracts.md @@ -53,7 +53,7 @@ Now that the contract is deployed, you can interact with it by submitting a cont ## Deploying a Large Contract as Blobs -In the above guide we use the recommended `deploy` method. If you are working with a contract that is too large to be deployed in a single transaction, then the SDK will chunk the contract for you and submit it as blobs, to then be accessed later by a create transaction. This process is handled by the [`ContractFactory.deployAsBlobTx`](https://fuels-ts-docs-api.vercel.app/classes/_fuel_ts_contract.index.ContractFactory.html#deployasblobtx) method. +In the above guide we use the recommended `deploy` method. If you are working with a contract that is too large to be deployed in a single transaction, then the SDK will chunk the contract for you and submit it as blobs, to then be accessed later by a create transaction. This process is handled by the [`ContractFactory.deployAsBlobTx`](https://fuels-ts-docs-api.vercel.app/classes/_fuel_ts_contract.index.ContractFactory.html#deployAsBlobTx) method. <<< @./snippets/deploying-contracts/deployment.ts#blobs{ts:line-numbers} diff --git a/apps/docs/src/guide/contracts/minted-token-asset-id.md b/apps/docs/src/guide/contracts/minted-token-asset-id.md index a7cfce24f29..29d09589779 100644 --- a/apps/docs/src/guide/contracts/minted-token-asset-id.md +++ b/apps/docs/src/guide/contracts/minted-token-asset-id.md @@ -23,6 +23,6 @@ Since the asset ID depends on the contract ID, which is always dynamic (unlike t ## Create Asset Id -The SDK provides a helper named `createAssetId` which takes the contract ID and sub ID as parameters. This helper internally calls `getMintedAssetId` and returns the Sway native parameter [AssetId](https://docs.fuel.network/docs/fuels-ts/interfaces/#assetid), ready to be used in a Sway program invocation: +The SDK provides a helper named `createAssetId` which takes the contract ID and sub ID as parameters. This helper internally calls `getMintedAssetId` and returns the Sway native parameter [AssetId](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_interfaces.AssetId.html), ready to be used in a Sway program invocation: <<< @./snippets/utilities/create-asset-id.ts#create-asset-id-1{ts:line-numbers} diff --git a/apps/docs/src/guide/predicates/methods.md b/apps/docs/src/guide/predicates/methods.md index b01557af6d6..a1d768c2a58 100644 --- a/apps/docs/src/guide/predicates/methods.md +++ b/apps/docs/src/guide/predicates/methods.md @@ -1,6 +1,6 @@ # Interacting With Predicates -The `Predicate` class extends the [`Account`](https://docs.fuel.network/docs/fuels-ts/account/) class, inheriting all its methods. Therefore, there are multiple ways to interact with predicates, but broadly speaking, we can think about three: +The `Predicate` class extends the [`Account`](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html) class, inheriting all its methods. Therefore, there are multiple ways to interact with predicates, but broadly speaking, we can think about three: - `Checking Balances` - `Transactions` diff --git a/apps/docs/src/guide/provider/provider-options.md b/apps/docs/src/guide/provider/provider-options.md index 1eb6bab5f55..6a9ce98c1db 100644 --- a/apps/docs/src/guide/provider/provider-options.md +++ b/apps/docs/src/guide/provider/provider-options.md @@ -1,6 +1,6 @@ # Provider Options -You can provide various [options](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html#provideroptions) on `Provider` instantiation to modify its behavior. +You can provide various [options](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.ProviderOptions.html) on `Provider` instantiation to modify its behavior. ### `retryOptions` diff --git a/apps/docs/src/guide/testing/launching-a-test-node.md b/apps/docs/src/guide/testing/launching-a-test-node.md index 118bd70bbd7..304dfc6c445 100644 --- a/apps/docs/src/guide/testing/launching-a-test-node.md +++ b/apps/docs/src/guide/testing/launching-a-test-node.md @@ -4,7 +4,7 @@ To simplify testing in isolation, we provide a utility called `launchTestNode`. It allows you to spin up a short-lived `fuel-core` node, set up a custom provider, wallets, deploy contracts, and much more in one go. -For usage information for `launchTestNode` including it's inputs, outputs and options, please check the [API reference](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_contract.test_utils.html#launchtestnode). +For usage information for `launchTestNode` including it's inputs, outputs and options, please check the [API reference](https://fuels-ts-docs-api.vercel.app/functions/_fuel_ts_contract.test_utils.launchTestNode.html). ## Explicit Resource Management diff --git a/apps/docs/src/guide/utilities/using-assets.md b/apps/docs/src/guide/utilities/using-assets.md index afe5ce152e6..88728f3b51b 100644 --- a/apps/docs/src/guide/utilities/using-assets.md +++ b/apps/docs/src/guide/utilities/using-assets.md @@ -1,6 +1,6 @@ # Assets -We export an array of [`Asset`](https://docs.fuel.network/docs/fuels-ts/account/#asset) objects, that can be useful when creating your dApp. The `Asset` object has useful metadata about the different assets that are available on blockchain networks (Fuel and Ethereum). +We export an array of [`Asset`](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.Asset.html) objects, that can be useful when creating your dApp. The `Asset` object has useful metadata about the different assets that are available on blockchain networks (Fuel and Ethereum). Included assets such as: @@ -9,6 +9,6 @@ Included assets such as: - USD Coin (USDC) - Wrapped ETH (WETH) -The helper functions `getAssetFuel` and `getAssetEth` can be used to get an asset's details relative to each network. These return a combination of the asset, and network information (the return types are [`AssetFuel`](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html#assetfuel) and [`AssetEth`](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html#asseteth) respectively). +The helper functions `getAssetFuel` and `getAssetEth` can be used to get an asset's details relative to each network. These return a combination of the asset, and network information (the return types are [`AssetFuel`](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.AssetFuel.html) and [`AssetEth`](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.AssetEth.html) respectively). <<< @./snippets/using-assets.ts#using-assets-1{ts:line-numbers} diff --git a/apps/docs/src/guide/wallets/checking-balances.md b/apps/docs/src/guide/wallets/checking-balances.md index 08d19d9f018..6c9450dbdf7 100644 --- a/apps/docs/src/guide/wallets/checking-balances.md +++ b/apps/docs/src/guide/wallets/checking-balances.md @@ -1,9 +1,9 @@ # Checking balances -To check the balance of a specific asset, you can use [`getBalance`](https://fuels-ts-docs-api.vercel.app/classes/_fuel_ts_account.Account.html#getbalance) method. This function aggregates the amounts of all unspent coins of the given asset in your wallet. +To check the balance of a specific asset, you can use [`getBalance`](https://fuels-ts-docs-api.vercel.app/classes/_fuel_ts_account.Account.html#getBalance) method. This function aggregates the amounts of all unspent coins of the given asset in your wallet. <<< @./snippets/checking-balances.ts#checking-balances-1{ts:line-numbers} -To retrieve the balances of all assets in your wallet, use the [`getBalances`](https://fuels-ts-docs-api.vercel.app/classes/_fuel_ts_account.Account.html#getbalances) method, it returns an array of [`CoinQuantity`](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html#coinquantity). This is useful for getting a comprehensive view of your holdings. +To retrieve the balances of all assets in your wallet, use the [`getBalances`](https://fuels-ts-docs-api.vercel.app/classes/_fuel_ts_account.Account.html#getBalances) method, it returns an array of [`CoinQuantity`](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.CoinQuantity.html). This is useful for getting a comprehensive view of your holdings. <<< @./snippets/checking-balances-two.ts#checking-balances-2{ts:line-numbers} diff --git a/apps/docs/src/guide/wallets/connectors.md b/apps/docs/src/guide/wallets/connectors.md index 29f921c470c..5b771d08e9a 100644 --- a/apps/docs/src/guide/wallets/connectors.md +++ b/apps/docs/src/guide/wallets/connectors.md @@ -91,25 +91,25 @@ The `connection` event is emitted every time the connection status changes. The #### `networks` -The `networks` event is emitted every time the network changes. The event data will be a [`Network`](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html#network) object containing the current network information. +The `networks` event is emitted every time the network changes. The event data will be a [`Network`](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.Network.html) object containing the current network information. <<< @./snippets/connectors.ts#fuel-connector-events-networks{ts:line-numbers} #### `currentNetwork` -The `currentNetwork` event is emitted every time the current network changes. The event data will be a [`Network`](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html#network) object containing the current network information. +The `currentNetwork` event is emitted every time the current network changes. The event data will be a [`Network`](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.Network.html) object containing the current network information. <<< @./snippets/connectors.ts#fuel-connector-events-currentNetwork{ts:line-numbers} #### `assets` -The `assets` event is emitted every time the assets change. The event data will be an array of [`Asset`](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html#asset) objects available on the network. +The `assets` event is emitted every time the assets change. The event data will be an array of [`Asset`](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.Asset.html) objects available on the network. <<< @./snippets/connectors.ts#fuel-connector-events-assets{ts:line-numbers} #### `abis` -The `abis` event is emitted every time an ABI is added to a connector. The event data will be an array of [`FuelABI`](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html#fuelabi) object. +The `abis` event is emitted every time an ABI is added to a connector. The event data will be an array of [`FuelABI`](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.FuelABI.html) object. <<< @./snippets/connectors.ts#fuel-connector-events-assets{ts:line-numbers} @@ -197,7 +197,7 @@ The `signTransaction` method initiates the send transaction flow for the current It requires two arguments: - `address` (`string`) -- `transaction` ([`TransactionRequestLike`](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html#transactionrequestlike)) +- `transaction` ([`TransactionRequestLike`](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.TransactionRequestLike.html)) It will return the transaction signature (as a `string`) if it is successfully signed. @@ -207,7 +207,7 @@ It will return the transaction signature (as a `string`) if it is successfully s The `assets` method returns a list of all the assets available for the current connection. -It will return a promise that will resolve to an array of assets (see [`Asset`](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html#asset)) that are available on the network. +It will return a promise that will resolve to an array of assets (see [`Asset`](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.Asset.html)) that are available on the network. <<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-assets{ts:line-numbers} @@ -217,7 +217,7 @@ The `addAsset` method adds asset metadata to the connector. It requires a single argument: -- `asset` ([`Asset`](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html#asset)) +- `asset` ([`Asset`](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.Asset.html)) It returns a promise that resolves to `true` if the asset is successfully added; otherwise, it resolves to `false`. @@ -229,7 +229,7 @@ The `addAssets` method adds multiple asset metadata to the connector. It requires a single argument: -- `assets` (an Array of [`Asset`](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html#asset)). +- `assets` (an Array of [`Asset`](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.Asset.html)). Returns a promise that resolves to `true` if the assets are successfully added; otherwise, resolves to `false`. @@ -253,7 +253,7 @@ It should throw an error if the network is not available or the network already The `networks` method returns a list of all the networks available for the current connection. -Returns a promise that resolves to an array of available networks (see [`Network`](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html#network)). +Returns a promise that resolves to an array of available networks (see [`Network`](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.Network.html)). <<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-networks{ts:line-numbers} @@ -261,7 +261,7 @@ Returns a promise that resolves to an array of available networks (see [`Network The `currentNetwork` method will return the current network that is connected. -It will return a promise that will resolve to the current network (see [`Network`](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html#network)). +It will return a promise that will resolve to the current network (see [`Network`](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.Network.html)). <<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-currentNetwork{ts:line-numbers} @@ -271,7 +271,7 @@ The `selectNetwork` method requests the user to select a network for the current It requires a single argument: -- `network` ([`Network`](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html#network)) +- `network` ([`Network`](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.Network.html)) You call this method with either the `providerUrl` or `chainId` to select the network. @@ -288,7 +288,7 @@ The `addABI` method adds ABI information about a contract to the connector. This It requires two arguments: - `contractId` (`string`) -- `abi` ([`FuelABI`](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html#fuelabi)). +- `abi` ([`FuelABI`](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.FuelABI.html)). It will return a promise that will resolve to `true` if the ABI is successfully added; otherwise `false`. @@ -302,7 +302,7 @@ It requires a single argument: - `contractId` (`string`) -Returns a promise that resolves to the ABI information (as a [`FuelABI`](https://fuels-ts-docs-api.vercel.app/modules/_fuel_ts_account.html#fuelabi)) or `null` if the data is unavailable. +Returns a promise that resolves to the ABI information (as a [`FuelABI`](https://fuels-ts-docs-api.vercel.app/types/_fuel_ts_account.FuelABI.html)) or `null` if the data is unavailable. <<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-getABI{ts:line-numbers} From a97c772fe80dd7681b2a53ba166a02c2dfaea1ba Mon Sep 17 00:00:00 2001 From: Peter Smith Date: Mon, 9 Dec 2024 12:15:36 +0000 Subject: [PATCH 06/13] fix: `transferToContract` method now allows big numbers (#3458) * fix: incorrectly converting BN to number for `formatTransferToContractScriptData` * chore: changeset * chore: tests * chore: added test for batch transfer --- .changeset/lazy-experts-rescue.md | 5 ++ ...formatTransferToContractScriptData.test.ts | 23 ++++++ .../formatTransferToContractScriptData.ts | 4 +- packages/fuel-gauge/src/contract.test.ts | 77 +++++++++++++++++++ 4 files changed, 107 insertions(+), 2 deletions(-) create mode 100644 .changeset/lazy-experts-rescue.md diff --git a/.changeset/lazy-experts-rescue.md b/.changeset/lazy-experts-rescue.md new file mode 100644 index 00000000000..6eaa6230145 --- /dev/null +++ b/.changeset/lazy-experts-rescue.md @@ -0,0 +1,5 @@ +--- +"@fuel-ts/account": patch +--- + +fix: `transferToContract` method now allows big numbers diff --git a/packages/account/src/utils/formatTransferToContractScriptData.test.ts b/packages/account/src/utils/formatTransferToContractScriptData.test.ts index 956677fe332..1cee087afa1 100644 --- a/packages/account/src/utils/formatTransferToContractScriptData.test.ts +++ b/packages/account/src/utils/formatTransferToContractScriptData.test.ts @@ -72,4 +72,27 @@ describe('util', () => { expect(arrayify).toHaveBeenCalledTimes(2); expect(encode).toHaveBeenCalledTimes(1); }); + + it('should ensure "formatScriptDataForTransferringToContract" returns script data just fine', () => { + const contractId = '0xf3eb53ed00347d305fc6f6e3a57e91ea6c3182a9efc253488db29494f63c9610'; + const amount: BigNumberish = bn(2).pow(64).sub(1); // Max u64 + const assetId: BytesLike = '0x0f622143ec845f9095bdf02d80273ac48556efcf9f95c1fdadb9351fd8ffcd24'; + + const scriptData = formatTransferToContractScriptData([ + { + contractId, + amount, + assetId, + }, + ]); + + expect(scriptData).toStrictEqual( + new Uint8Array([ + 243, 235, 83, 237, 0, 52, 125, 48, 95, 198, 246, 227, 165, 126, 145, 234, 108, 49, 130, 169, + 239, 194, 83, 72, 141, 178, 148, 148, 246, 60, 150, 16, 255, 255, 255, 255, 255, 255, 255, + 255, 15, 98, 33, 67, 236, 132, 95, 144, 149, 189, 240, 45, 128, 39, 58, 196, 133, 86, 239, + 207, 159, 149, 193, 253, 173, 185, 53, 31, 216, 255, 205, 36, + ]) + ); + }); }); diff --git a/packages/account/src/utils/formatTransferToContractScriptData.ts b/packages/account/src/utils/formatTransferToContractScriptData.ts index d290ccbd949..1c441314e4c 100644 --- a/packages/account/src/utils/formatTransferToContractScriptData.ts +++ b/packages/account/src/utils/formatTransferToContractScriptData.ts @@ -1,7 +1,7 @@ import { ASSET_ID_LEN, BigNumberCoder, CONTRACT_ID_LEN, WORD_SIZE } from '@fuel-ts/abi-coder'; import { Address } from '@fuel-ts/address'; import type { BytesLike } from '@fuel-ts/interfaces'; -import { BN } from '@fuel-ts/math'; +import type { BN } from '@fuel-ts/math'; import { arrayify, concat } from '@fuel-ts/utils'; import * as asm from '@fuels/vm-asm'; @@ -17,7 +17,7 @@ export const formatTransferToContractScriptData = ( const numberCoder = new BigNumberCoder('u64'); return transferParams.reduce((acc, transferParam) => { const { assetId, amount, contractId } = transferParam; - const encoded = numberCoder.encode(new BN(amount).toNumber()); + const encoded = numberCoder.encode(amount); const scriptData = concat([ Address.fromAddressOrString(contractId).toBytes(), encoded, diff --git a/packages/fuel-gauge/src/contract.test.ts b/packages/fuel-gauge/src/contract.test.ts index baeccb057a8..04fe5dffc7d 100644 --- a/packages/fuel-gauge/src/contract.test.ts +++ b/packages/fuel-gauge/src/contract.test.ts @@ -691,6 +691,83 @@ describe('Contract', () => { expect(finalBalance).toBe(initialBalance + amountToContract.toNumber()); }); + it('should transferToContract with a large amount of assets', async () => { + using launched = await launchTestNode({ + contractsConfigs, + walletsConfig: { + amountPerCoin: 2 ** 62, + }, + }); + const { + provider, + wallets: [wallet], + contracts: [contract], + } = launched; + + const initialBalance = new BN(await contract.getBalance(provider.getBaseAssetId())).toNumber(); + const amountToContract = bn(2).pow(62); // Very big number + + const tx = await wallet.transferToContract( + contract.id, + amountToContract, + provider.getBaseAssetId() + ); + + await tx.waitForResult(); + + const finalBalance = new BN(await contract.getBalance(provider.getBaseAssetId())).toString(); + expect(finalBalance).toBe(amountToContract.add(initialBalance).toString()); + }); + + it('should batch transfer with a large amount of assets', async () => { + using launched = await launchTestNode({ + contractsConfigs, + walletsConfig: { + amountPerCoin: 2 ** 62, + }, + }); + const { + provider, + wallets: [wallet], + contracts: [contract], + } = launched; + + const baseAssetId = provider.getBaseAssetId(); + const contractTransferParams: ContractTransferParams[] = [ + { + contractId: contract.id, + amount: bn(2).pow(50), + assetId: baseAssetId, + }, + { + contractId: contract.id, + amount: bn(2).pow(10), + assetId: baseAssetId, + }, + ]; + + const tx = await wallet.batchTransferToContracts(contractTransferParams); + + const { receipts } = await tx.waitForResult(); + + const transferReceipts = receipts.filter( + ({ type }) => type === ReceiptType.Transfer + ) as ReceiptTransfer[]; + + expect(transferReceipts.length).toBe(contractTransferParams.length); + + contractTransferParams.forEach(({ amount, contractId, assetId = baseAssetId }) => { + const foundReceipt = transferReceipts.find( + (r) => + r.amount.eq(amount) && + r.to.toLowerCase() === contractId.toString().toLowerCase() && + r.assetId === assetId + ); + + expect(foundReceipt).toBeDefined(); + }); + }); + it('should transfer assets to deployed contracts just fine', async () => { using launched = await launchTestNode({ contractsConfigs: [ From b274d6d1a7c5784d5bb4d2997119312b3ca14dbc Mon Sep 17 00:00:00 2001 From: Saurabh Chauhan <36479565+starc007@users.noreply.github.com> Date: Mon, 9 Dec 2024 23:28:53 +0530 Subject: [PATCH 07/13] fix: moved vitest matcher setup from fuel-gauge to utils --- packages/fuel-gauge/global.d.ts | 15 --------------- packages/fuel-gauge/tsconfig.json | 4 ++-- packages/fuel-gauge/vitest.setup.ts | 3 --- packages/utils/global.d.ts | 13 +++++++++++++ packages/utils/src/test-utils.ts | 1 + .../src/test-utils}/vitest.matcher.ts | 16 ++-------------- packages/utils/tsconfig.json | 2 +- packages/utils/vitest.setup.ts | 3 +++ vitest.shared.config.mts | 2 +- 9 files changed, 23 insertions(+), 36 deletions(-) delete mode 100644 packages/fuel-gauge/global.d.ts delete mode 100644 packages/fuel-gauge/vitest.setup.ts create mode 100644 packages/utils/global.d.ts rename packages/{fuel-gauge/src/abi => utils/src/test-utils}/vitest.matcher.ts (62%) create mode 100644 packages/utils/vitest.setup.ts diff --git a/packages/fuel-gauge/global.d.ts b/packages/fuel-gauge/global.d.ts deleted file mode 100644 index 9e70609e8d3..00000000000 --- a/packages/fuel-gauge/global.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { BNInput } from 'fuels'; - -declare global { - namespace Vitest { - interface Assertion { - toEqualBn(expected: BNInput): void; - } - interface ExpectStatic { - toEqualBn(expected: BNInput): { - asymmetricMatch(actual: BNInput): boolean; - toString(): string; - }; - } - } -} diff --git a/packages/fuel-gauge/tsconfig.json b/packages/fuel-gauge/tsconfig.json index 1caadd4e332..968f826bbc9 100644 --- a/packages/fuel-gauge/tsconfig.json +++ b/packages/fuel-gauge/tsconfig.json @@ -2,7 +2,7 @@ "extends": "../../tsconfig.base.json", "compilerOptions": { "outDir": "./dist", - "types": ["vitest/globals"] + "types": ["vitest/globals", "@fuel-ts/utils/global"] }, - "include": ["src", "global.d.ts"] + "include": ["src", "test"] } diff --git a/packages/fuel-gauge/vitest.setup.ts b/packages/fuel-gauge/vitest.setup.ts deleted file mode 100644 index 4179c5c2e08..00000000000 --- a/packages/fuel-gauge/vitest.setup.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { setupTestMatchers } from './src/abi/vitest.matcher'; - -setupTestMatchers(); diff --git a/packages/utils/global.d.ts b/packages/utils/global.d.ts new file mode 100644 index 00000000000..aae887687f7 --- /dev/null +++ b/packages/utils/global.d.ts @@ -0,0 +1,13 @@ +import type { BN, BNInput } from '@fuel-ts/math'; + +interface Matchers { + toEqualBn: (expected: BNInput) => R; +} + +declare module 'vitest' { + interface Assertion extends Matchers {} + interface AsymmetricMatchersContaining extends Matchers {} + interface ExpectStatic { + toEqualBn(expected: BNInput): BN; + } +} diff --git a/packages/utils/src/test-utils.ts b/packages/utils/src/test-utils.ts index bfad80a17ed..fe5665ab47d 100644 --- a/packages/utils/src/test-utils.ts +++ b/packages/utils/src/test-utils.ts @@ -2,3 +2,4 @@ export * from './test-utils/getForcProject'; export * from './test-utils/expectToBeInRange'; export * from './test-utils/constants'; export * from './test-utils/wait-until-unreachable'; +export * from './test-utils/vitest.matcher'; diff --git a/packages/fuel-gauge/src/abi/vitest.matcher.ts b/packages/utils/src/test-utils/vitest.matcher.ts similarity index 62% rename from packages/fuel-gauge/src/abi/vitest.matcher.ts rename to packages/utils/src/test-utils/vitest.matcher.ts index 811d3f181c0..8daeb3fc957 100644 --- a/packages/fuel-gauge/src/abi/vitest.matcher.ts +++ b/packages/utils/src/test-utils/vitest.matcher.ts @@ -1,17 +1,5 @@ -import { bn } from 'fuels'; -import type { BNInput, BN } from 'fuels'; - -interface Matchers { - toEqualBn: (expected: BNInput) => R; -} - -declare module 'vitest' { - interface Assertion extends Matchers {} - interface AsymmetricMatchersContaining extends Matchers {} - interface ExpectStatic { - toEqualBn(expected: BNInput): BN; - } -} +import { bn } from '@fuel-ts/math'; +import type { BNInput } from '@fuel-ts/math'; export const setupTestMatchers = () => { expect.extend({ diff --git a/packages/utils/tsconfig.json b/packages/utils/tsconfig.json index b22c89a4b35..ac17ae8db77 100644 --- a/packages/utils/tsconfig.json +++ b/packages/utils/tsconfig.json @@ -3,5 +3,5 @@ "compilerOptions": { "outDir": "./dist" }, - "include": ["src", "test"] + "include": ["src", "test", "global.d.ts"] } diff --git a/packages/utils/vitest.setup.ts b/packages/utils/vitest.setup.ts new file mode 100644 index 00000000000..afd50a172a9 --- /dev/null +++ b/packages/utils/vitest.setup.ts @@ -0,0 +1,3 @@ +import { setupTestMatchers } from './src/test-utils'; + +setupTestMatchers(); diff --git a/vitest.shared.config.mts b/vitest.shared.config.mts index f4329d6039f..d671785401c 100644 --- a/vitest.shared.config.mts +++ b/vitest.shared.config.mts @@ -17,7 +17,7 @@ export default defineConfig({ esbuild: { target: "es2022" }, test: { globalSetup: ["vitest.global-setup.ts"], - setupFiles: ["./packages/fuel-gauge/vitest.setup.ts"], + setupFiles: ["./packages/utils/vitest.setup.ts"], coverage: { enabled: true, provider: "istanbul", From 2edccc6bc9b98957d41dc27ed2fd8ad3ab07d262 Mon Sep 17 00:00:00 2001 From: Saurabh Chauhan <36479565+starc007@users.noreply.github.com> Date: Mon, 9 Dec 2024 23:43:00 +0530 Subject: [PATCH 08/13] fix(utils): update vitest matcher import path --- packages/utils/src/test-utils.ts | 1 - packages/utils/vitest.setup.ts | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/utils/src/test-utils.ts b/packages/utils/src/test-utils.ts index fe5665ab47d..bfad80a17ed 100644 --- a/packages/utils/src/test-utils.ts +++ b/packages/utils/src/test-utils.ts @@ -2,4 +2,3 @@ export * from './test-utils/getForcProject'; export * from './test-utils/expectToBeInRange'; export * from './test-utils/constants'; export * from './test-utils/wait-until-unreachable'; -export * from './test-utils/vitest.matcher'; diff --git a/packages/utils/vitest.setup.ts b/packages/utils/vitest.setup.ts index afd50a172a9..cc5509d5748 100644 --- a/packages/utils/vitest.setup.ts +++ b/packages/utils/vitest.setup.ts @@ -1,3 +1,3 @@ -import { setupTestMatchers } from './src/test-utils'; +import { setupTestMatchers } from './src/test-utils/vitest.matcher'; setupTestMatchers(); From 6abcebd17e089d9df42d0bf2e654bd7504158132 Mon Sep 17 00:00:00 2001 From: Saurabh Chauhan <36479565+starc007@users.noreply.github.com> Date: Tue, 10 Dec 2024 00:14:16 +0530 Subject: [PATCH 09/13] chore: add changeset for vitest matcher changes --- .changeset/tame-goats-ring.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/tame-goats-ring.md diff --git a/.changeset/tame-goats-ring.md b/.changeset/tame-goats-ring.md new file mode 100644 index 00000000000..01c1a7671ec --- /dev/null +++ b/.changeset/tame-goats-ring.md @@ -0,0 +1,5 @@ +--- +"@fuel-ts/utils": minor +--- + +Move vitest matcher to @fuel-ts/utils making it globally accessible across packages. The matcher can now be used throughout the SDK without individual imports and extensions. From f5b35b18eab67bbb75a7be5b839e3a2d0bb22823 Mon Sep 17 00:00:00 2001 From: Saurabh Chauhan <36479565+starc007@users.noreply.github.com> Date: Tue, 10 Dec 2024 00:38:06 +0530 Subject: [PATCH 10/13] fix: removed previous changeset --- .changeset/clean-plums-wait.md | 5 ----- .changeset/tame-goats-ring.md | 2 +- 2 files changed, 1 insertion(+), 6 deletions(-) delete mode 100644 .changeset/clean-plums-wait.md diff --git a/.changeset/clean-plums-wait.md b/.changeset/clean-plums-wait.md deleted file mode 100644 index 97cca38a5bc..00000000000 --- a/.changeset/clean-plums-wait.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"fuels": minor ---- - -chore: integrate vitest matchers globally diff --git a/.changeset/tame-goats-ring.md b/.changeset/tame-goats-ring.md index 01c1a7671ec..5659190f6a5 100644 --- a/.changeset/tame-goats-ring.md +++ b/.changeset/tame-goats-ring.md @@ -2,4 +2,4 @@ "@fuel-ts/utils": minor --- -Move vitest matcher to @fuel-ts/utils making it globally accessible across packages. The matcher can now be used throughout the SDK without individual imports and extensions. +chore: integrate vitest matchers globally From 98d368205ab717d5ec781c68418371bba2d23514 Mon Sep 17 00:00:00 2001 From: Saurabh Chauhan <36479565+starc007@users.noreply.github.com> Date: Tue, 10 Dec 2024 16:42:39 +0530 Subject: [PATCH 11/13] chore: removed types --- packages/fuel-gauge/tsconfig.json | 3 +-- packages/utils/global.d.ts | 13 ------------- packages/utils/src/test-utils.ts | 1 + .../{vitest.matcher.ts => vitest.matchers.ts} | 13 ++++++++++++- packages/utils/tsconfig.json | 2 +- packages/utils/vitest.setup.ts | 3 --- vitest.setup-files.ts | 3 +++ vitest.shared.config.mts | 2 +- 8 files changed, 19 insertions(+), 21 deletions(-) delete mode 100644 packages/utils/global.d.ts rename packages/utils/src/test-utils/{vitest.matcher.ts => vitest.matchers.ts} (65%) delete mode 100644 packages/utils/vitest.setup.ts create mode 100644 vitest.setup-files.ts diff --git a/packages/fuel-gauge/tsconfig.json b/packages/fuel-gauge/tsconfig.json index 968f826bbc9..b22c89a4b35 100644 --- a/packages/fuel-gauge/tsconfig.json +++ b/packages/fuel-gauge/tsconfig.json @@ -1,8 +1,7 @@ { "extends": "../../tsconfig.base.json", "compilerOptions": { - "outDir": "./dist", - "types": ["vitest/globals", "@fuel-ts/utils/global"] + "outDir": "./dist" }, "include": ["src", "test"] } diff --git a/packages/utils/global.d.ts b/packages/utils/global.d.ts deleted file mode 100644 index aae887687f7..00000000000 --- a/packages/utils/global.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { BN, BNInput } from '@fuel-ts/math'; - -interface Matchers { - toEqualBn: (expected: BNInput) => R; -} - -declare module 'vitest' { - interface Assertion extends Matchers {} - interface AsymmetricMatchersContaining extends Matchers {} - interface ExpectStatic { - toEqualBn(expected: BNInput): BN; - } -} diff --git a/packages/utils/src/test-utils.ts b/packages/utils/src/test-utils.ts index bfad80a17ed..266fa8b5b55 100644 --- a/packages/utils/src/test-utils.ts +++ b/packages/utils/src/test-utils.ts @@ -2,3 +2,4 @@ export * from './test-utils/getForcProject'; export * from './test-utils/expectToBeInRange'; export * from './test-utils/constants'; export * from './test-utils/wait-until-unreachable'; +export * from './test-utils/vitest.matchers'; diff --git a/packages/utils/src/test-utils/vitest.matcher.ts b/packages/utils/src/test-utils/vitest.matchers.ts similarity index 65% rename from packages/utils/src/test-utils/vitest.matcher.ts rename to packages/utils/src/test-utils/vitest.matchers.ts index 8daeb3fc957..0240caa917e 100644 --- a/packages/utils/src/test-utils/vitest.matcher.ts +++ b/packages/utils/src/test-utils/vitest.matchers.ts @@ -1,5 +1,16 @@ import { bn } from '@fuel-ts/math'; -import type { BNInput } from '@fuel-ts/math'; +import type { BN, BNInput } from '@fuel-ts/math'; + +interface Matchers { + toEqualBn: (expected: BNInput) => R; +} +declare module 'vitest' { + interface Assertion extends Matchers {} + interface AsymmetricMatchersContaining extends Matchers {} + interface ExpectStatic { + toEqualBn(expected: BNInput): BN; + } +} export const setupTestMatchers = () => { expect.extend({ diff --git a/packages/utils/tsconfig.json b/packages/utils/tsconfig.json index ac17ae8db77..b22c89a4b35 100644 --- a/packages/utils/tsconfig.json +++ b/packages/utils/tsconfig.json @@ -3,5 +3,5 @@ "compilerOptions": { "outDir": "./dist" }, - "include": ["src", "test", "global.d.ts"] + "include": ["src", "test"] } diff --git a/packages/utils/vitest.setup.ts b/packages/utils/vitest.setup.ts deleted file mode 100644 index cc5509d5748..00000000000 --- a/packages/utils/vitest.setup.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { setupTestMatchers } from './src/test-utils/vitest.matcher'; - -setupTestMatchers(); diff --git a/vitest.setup-files.ts b/vitest.setup-files.ts new file mode 100644 index 00000000000..8cd866cc303 --- /dev/null +++ b/vitest.setup-files.ts @@ -0,0 +1,3 @@ +import { setupTestMatchers } from '@fuel-ts/utils/test-utils'; + +setupTestMatchers(); diff --git a/vitest.shared.config.mts b/vitest.shared.config.mts index d671785401c..799cd7bc2e5 100644 --- a/vitest.shared.config.mts +++ b/vitest.shared.config.mts @@ -17,7 +17,7 @@ export default defineConfig({ esbuild: { target: "es2022" }, test: { globalSetup: ["vitest.global-setup.ts"], - setupFiles: ["./packages/utils/vitest.setup.ts"], + setupFiles: ["./vitest.setup-files.ts"], coverage: { enabled: true, provider: "istanbul", From 732864413819e352fcd299083751b8677e3b1641 Mon Sep 17 00:00:00 2001 From: Saurabh Chauhan <36479565+starc007@users.noreply.github.com> Date: Tue, 10 Dec 2024 16:43:50 +0530 Subject: [PATCH 12/13] chore: added changeset --- .changeset/{tame-goats-ring.md => rare-hornets-rush.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .changeset/{tame-goats-ring.md => rare-hornets-rush.md} (100%) diff --git a/.changeset/tame-goats-ring.md b/.changeset/rare-hornets-rush.md similarity index 100% rename from .changeset/tame-goats-ring.md rename to .changeset/rare-hornets-rush.md From 9168f31a2c187f6e9895d17a78b7c5100b0587d2 Mon Sep 17 00:00:00 2001 From: Peter Smith Date: Tue, 10 Dec 2024 11:42:14 +0000 Subject: [PATCH 13/13] Update .changeset/rare-hornets-rush.md --- .changeset/rare-hornets-rush.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/rare-hornets-rush.md b/.changeset/rare-hornets-rush.md index 5659190f6a5..6addec2382c 100644 --- a/.changeset/rare-hornets-rush.md +++ b/.changeset/rare-hornets-rush.md @@ -1,5 +1,5 @@ --- -"@fuel-ts/utils": minor +"@fuel-ts/utils": patch --- chore: integrate vitest matchers globally