From bc003b815f45da7ef28365445874b7b00b41b0e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9rgio=20Torres?= <30977845+Torres-ssf@users.noreply.github.com> Date: Fri, 22 Dec 2023 17:20:51 -0300 Subject: [PATCH 01/10] rename and export getAssetId helper --- packages/transactions/src/coders/receipt.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/transactions/src/coders/receipt.ts b/packages/transactions/src/coders/receipt.ts index ba80cc8925b..a00a38637eb 100644 --- a/packages/transactions/src/coders/receipt.ts +++ b/packages/transactions/src/coders/receipt.ts @@ -767,7 +767,7 @@ export type ReceiptMint = { is: BN; }; -const getAssetIdForMintAndBurnReceipts = (contractId: string, subId: string): string => { +export const getAssetId = (contractId: string, subId: string): string => { const contractIdBytes = getBytesCopy(contractId); const subIdBytes = getBytesCopy(subId); @@ -780,7 +780,7 @@ export class ReceiptMintCoder extends Coder { } static getAssetId(contractId: string, subId: string): string { - return getAssetIdForMintAndBurnReceipts(contractId, subId); + return getAssetId(contractId, subId); } encode(value: ReceiptMint): Uint8Array { @@ -848,7 +848,7 @@ export class ReceiptBurnCoder extends Coder { } static getAssetId(contractId: string, subId: string): string { - return getAssetIdForMintAndBurnReceipts(contractId, subId); + return getAssetId(contractId, subId); } encode(value: ReceiptBurn): Uint8Array { From 35ab93a2af18527efa9b6150bf1a1633bec665f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9rgio=20Torres?= <30977845+Torres-ssf@users.noreply.github.com> Date: Fri, 22 Dec 2023 17:21:22 -0300 Subject: [PATCH 02/10] remove test case from doc-examples test suite --- packages/fuel-gauge/src/doc-examples.test.ts | 94 -------------------- 1 file changed, 94 deletions(-) diff --git a/packages/fuel-gauge/src/doc-examples.test.ts b/packages/fuel-gauge/src/doc-examples.test.ts index e8d67fe47dc..a5176c2aa24 100644 --- a/packages/fuel-gauge/src/doc-examples.test.ts +++ b/packages/fuel-gauge/src/doc-examples.test.ts @@ -23,7 +23,6 @@ import { Wallet, WalletUnlocked, Signer, - ContractFactory, ZeroBytes32, BaseAssetId, FUEL_NETWORK_URL, @@ -35,9 +34,6 @@ const { abiContents: callTestAbi } = getFuelGaugeForcProject( FuelGaugeProjectsEnum.CALL_TEST_CONTRACT ); -const { binHexlified: liquidityPoolContractBytecode, abiContents: liquidityPoolABI } = - getFuelGaugeForcProject(FuelGaugeProjectsEnum.LIQUIDITY_POOL); - const { binHexlified: predicateTriple } = getFuelGaugeForcProject( FuelGaugeProjectsEnum.PREDICATE_TRIPLE_SIG ); @@ -46,9 +42,6 @@ const { binHexlified: testPredicateTrue } = getFuelGaugeForcProject( FuelGaugeProjectsEnum.PREDICATE_TRUE ); -const { binHexlified: tokenContractBytecode, abiContents: tokenContractABI } = - getFuelGaugeForcProject(FuelGaugeProjectsEnum.TOKEN_CONTRACT); - const PUBLIC_KEY = '0x2f34bc0df4db0ec391792cedb05768832b49b1aa3a2dd8c30054d1af00f67d00b74b7acbbf3087c8e0b1a4c343db50aa471d21f278ff5ce09f07795d541fb47e'; @@ -472,91 +465,4 @@ describe('Doc Examples', () => { // assert that predicate funds now belong to the receiver expect(bn(receiverBalance).gte(bn(amountToReceiver))).toBeTruthy(); }); - - test.skip('deposit and withdraw cookbook guide', async () => { - // #region deposit-and-withdraw-cookbook-wallet-setup - const provider = await Provider.create(FUEL_NETWORK_URL); - const PRIVATE_KEY = '0x862512a2363db2b3a375c0d4bbbd27172180d89f23f2e259bac850ab02619301'; - const wallet = Wallet.fromPrivateKey(PRIVATE_KEY, provider); - await seedTestWallet(wallet, [{ assetId: BaseAssetId, amount: bn(100_000) }]); - // #endregion deposit-and-withdraw-cookbook-wallet-setup - - // #region deposit-and-withdraw-cookbook-contract-deployments - const tokenContractFactory = new ContractFactory( - tokenContractBytecode, - tokenContractABI, - wallet - ); - const tokenContract = await tokenContractFactory.deployContract({ gasPrice }); - const tokenContractID = tokenContract.id; - - const liquidityPoolContractFactory = new ContractFactory( - liquidityPoolContractBytecode, - liquidityPoolABI, - wallet - ); - const liquidityPoolContract = await liquidityPoolContractFactory.deployContract({ gasPrice }); - const liquidityPoolContractID = liquidityPoolContract.id; - await liquidityPoolContract.functions.set_base_token(tokenContractID).call(); - // #endregion deposit-and-withdraw-cookbook-contract-deployments - - // mint some base tokens to the current wallet - // #region deposit-and-withdraw-cookbook-mint-and-transfer - await tokenContract.functions.mint_coins(500, 1).call(); - await tokenContract.functions - .transfer_coins_to_output( - 200, - { - value: tokenContract.id, - }, - { - value: wallet.address.toB256(), - } - ) - .txParams({ - variableOutputs: 1, - gasPrice, - }) - .call(); - // #endregion deposit-and-withdraw-cookbook-mint-and-transfer - - // deposit base tokens into the liquidity pool - // #region deposit-and-withdraw-cookbook-deposit - await liquidityPoolContract.functions - .deposit({ - value: wallet.address.toB256(), - }) - .callParams({ - forward: { - amount: bn(100), - assetId: tokenContractID.toB256(), - }, - }) - .call(); - // #endregion deposit-and-withdraw-cookbook-deposit - - // verify balances - expect(await wallet.getBalance(tokenContractID.toB256())).toEqual(bn(100)); - expect(await wallet.getBalance(liquidityPoolContractID.toB256())).toEqual(bn(200)); - - // withdraw base tokens from the liquidity pool - // #region deposit-and-withdraw-cookbook-withdraw - const lpTokenBalance = await wallet.getBalance(liquidityPoolContractID.toB256()); - await liquidityPoolContract.functions - .withdraw({ - value: wallet.address.toB256(), - }) - .callParams({ - forward: { - amount: lpTokenBalance, - assetId: liquidityPoolContractID.toB256(), - }, - }) - .call(); - // #endregion deposit-and-withdraw-cookbook-withdraw - - // verify balances again - expect(await wallet.getBalance(tokenContractID.toB256())).toEqual(bn(200)); - expect(await wallet.getBalance(liquidityPoolContractID.toB256())).toEqual(bn(0)); - }); }); From ce9c49b9b0f0df718bcc9682ffda49467597dfb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9rgio=20Torres?= <30977845+Torres-ssf@users.noreply.github.com> Date: Fri, 22 Dec 2023 17:22:07 -0300 Subject: [PATCH 03/10] using another contract on predicate test --- .../predicate/predicate-with-contract.test.ts | 41 +++++-------------- 1 file changed, 11 insertions(+), 30 deletions(-) diff --git a/packages/fuel-gauge/src/predicate/predicate-with-contract.test.ts b/packages/fuel-gauge/src/predicate/predicate-with-contract.test.ts index 52004584230..ff92f02d3fa 100644 --- a/packages/fuel-gauge/src/predicate/predicate-with-contract.test.ts +++ b/packages/fuel-gauge/src/predicate/predicate-with-contract.test.ts @@ -23,8 +23,9 @@ describe('Predicate', () => { const { binHexlified: contractBytes, abiContents: contractAbi } = getFuelGaugeForcProject( FuelGaugeProjectsEnum.CALL_TEST_CONTRACT ); - const { binHexlified: liquidityPoolBytes, abiContents: liquidityPoolAbi } = - getFuelGaugeForcProject(FuelGaugeProjectsEnum.LIQUIDITY_POOL); + const { binHexlified: tokenPoolBytes, abiContents: tokenPoolAbi } = getFuelGaugeForcProject( + FuelGaugeProjectsEnum.TOKEN_CONTRACT + ); const { abiContents: predicateAbiMainArgsStruct } = getFuelGaugeForcProject( FuelGaugeProjectsEnum.PREDICATE_MAIN_ARGS_STRUCT @@ -86,8 +87,8 @@ describe('Predicate', () => { it('calls a predicate and uses proceeds for a contract call', async () => { const contract = await new ContractFactory( - liquidityPoolBytes, - liquidityPoolAbi, + tokenPoolBytes, + tokenPoolAbi, wallet ).deployContract({ gasPrice }); @@ -97,15 +98,10 @@ describe('Predicate', () => { contract.account = receiver; await expect( contract.functions - .deposit({ - value: receiver.address.toB256(), - }) - .callParams({ - forward: [100, BaseAssetId], - }) + .mint_coins(200) .txParams({ gasPrice, - gasLimit: 10_000, + gasLimit: 1_000, }) .call() ).rejects.toThrow(/not enough coins to fit the target/); @@ -139,23 +135,12 @@ describe('Predicate', () => { // calling the contract with the receiver account (with resources) const contractAmount = 10; const { - transactionResult: { fee: receiverTxFee1 }, - } = await contract.functions - .set_base_token(BaseAssetId) - .txParams({ gasPrice, gasLimit: 10_000 }) - .call(); - const { - transactionResult: { fee: receiverTxFee2 }, + transactionResult: { fee: receiverTxFee }, } = await contract.functions - .deposit({ - value: receiver.address.toB256(), - }) - .callParams({ - forward: [contractAmount, BaseAssetId], - }) + .mint_coins(200) .txParams({ gasPrice, - gasLimit: 10_000, + gasLimit: 1_000, }) .call(); @@ -163,11 +148,7 @@ describe('Predicate', () => { const remainingPredicateBalance = toNumber(await predicate.getBalance()); const expectedFinalReceiverBalance = - initialReceiverBalance + - amountToReceiver - - contractAmount - - receiverTxFee1.toNumber() - - receiverTxFee2.toNumber(); + initialReceiverBalance + amountToReceiver - contractAmount - receiverTxFee.toNumber(); expectToBeInRange({ value: finalReceiverBalance, From c6f442398143fc513228f5a76a002972fd3bfa69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9rgio=20Torres?= <30977845+Torres-ssf@users.noreply.github.com> Date: Fri, 22 Dec 2023 17:22:40 -0300 Subject: [PATCH 04/10] remove liquidity-pool contract from fuel-gauge --- .../test/fixtures/forc-projects/Forc.toml | 1 - .../forc-projects/liquidity-pool/Forc.toml | 6 -- .../forc-projects/liquidity-pool/src/main.sw | 71 ------------------- packages/fuel-gauge/test/fixtures/index.ts | 1 - 4 files changed, 79 deletions(-) delete mode 100644 packages/fuel-gauge/test/fixtures/forc-projects/liquidity-pool/Forc.toml delete mode 100644 packages/fuel-gauge/test/fixtures/forc-projects/liquidity-pool/src/main.sw diff --git a/packages/fuel-gauge/test/fixtures/forc-projects/Forc.toml b/packages/fuel-gauge/test/fixtures/forc-projects/Forc.toml index 6e8bb25e02d..02c4857fb84 100644 --- a/packages/fuel-gauge/test/fixtures/forc-projects/Forc.toml +++ b/packages/fuel-gauge/test/fixtures/forc-projects/Forc.toml @@ -11,7 +11,6 @@ members = [ "configurable-contract", "coverage-contract", "generic-types-contract", - "liquidity-pool", "multi-token-contract", "payable-annotation", "predicate-address", diff --git a/packages/fuel-gauge/test/fixtures/forc-projects/liquidity-pool/Forc.toml b/packages/fuel-gauge/test/fixtures/forc-projects/liquidity-pool/Forc.toml deleted file mode 100644 index fe0f80317d9..00000000000 --- a/packages/fuel-gauge/test/fixtures/forc-projects/liquidity-pool/Forc.toml +++ /dev/null @@ -1,6 +0,0 @@ -[project] -authors = ["Fuel Labs "] -license = "Apache-2.0" -name = "liquidity-pool" - -[dependencies] diff --git a/packages/fuel-gauge/test/fixtures/forc-projects/liquidity-pool/src/main.sw b/packages/fuel-gauge/test/fixtures/forc-projects/liquidity-pool/src/main.sw deleted file mode 100644 index 87094659732..00000000000 --- a/packages/fuel-gauge/test/fixtures/forc-projects/liquidity-pool/src/main.sw +++ /dev/null @@ -1,71 +0,0 @@ -// #region liquidity-pool-contract -contract; - -use std::constants::ZERO_B256; - -use std::{ - call_frames::{ - contract_id, - msg_asset_id, - }, - context::msg_amount, - token::{ - mint_to_address, - transfer_to_address, - }, -}; - -abi LiquidityPool { - #[storage(write)] - fn set_base_token(base_token_id: b256) -> (); - - #[storage(read), payable] - fn deposit(recipient: Address); - - #[storage(read), payable] - fn withdraw(recipient: Address); -} - -storage { - base_token: AssetId = AssetId { - value: 0x0000000000000000000000000000000000000000000000000000000000000000, - }, -} - -impl LiquidityPool for Contract { - #[storage(write)] - fn set_base_token(base_token_id: b256) { - storage - .base_token - .write(AssetId { - value: base_token_id, - }); - } - - #[storage(read), payable] - fn deposit(recipient: Address) { - log(msg_asset_id()); - log(msg_amount()); - log(msg_amount()); - assert(storage.base_token.read() == msg_asset_id()); - assert(0 < msg_amount()); - - // Mint two times the amount. - let amount_to_mint = msg_amount() * 2; - - // Mint some LP token based upon the amount of the base token. - mint_to_address(recipient, ZERO_B256, amount_to_mint); - } - - #[storage(read), payable] - fn withdraw(recipient: Address) { - assert(0 < msg_amount()); - - // Amount to withdraw. - let amount_to_transfer = msg_amount() / 2; - - // Transfer base token to recipient. - transfer_to_address(recipient, storage.base_token.read(), amount_to_transfer); - } -} -// #endregion liquidity-pool-contract diff --git a/packages/fuel-gauge/test/fixtures/index.ts b/packages/fuel-gauge/test/fixtures/index.ts index d52e688247b..c150b70816f 100644 --- a/packages/fuel-gauge/test/fixtures/index.ts +++ b/packages/fuel-gauge/test/fixtures/index.ts @@ -16,7 +16,6 @@ export enum FuelGaugeProjectsEnum { COLLISION_IN_FN_NAMES = 'collision_in_fn_names', COVERAGE_CONTRACT = 'coverage-contract', GENERIC_TYPES_CONTRACT = 'generic-types-contract', - LIQUIDITY_POOL = 'liquidity-pool', MULTI_TOKEN_CONTRACT = 'multi-token-contract', PAYABLE_ANNOTATION = 'payable-annotation', PREDICATE_ADDRESS = 'predicate-address', From e42115f7067cf5c76495676300e13337a1dc1dbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9rgio=20Torres?= <30977845+Torres-ssf@users.noreply.github.com> Date: Fri, 22 Dec 2023 17:23:22 -0300 Subject: [PATCH 05/10] implement updated liquidity-pool contract on docs-snippets --- .../test/fixtures/forc-projects/Forc.toml | 1 + .../test/fixtures/forc-projects/index.ts | 1 + .../forc-projects/liquidity-pool/Forc.toml | 7 +++ .../forc-projects/liquidity-pool/src/main.sw | 51 +++++++++++++++++++ 4 files changed, 60 insertions(+) create mode 100644 apps/docs-snippets/test/fixtures/forc-projects/liquidity-pool/Forc.toml create mode 100644 apps/docs-snippets/test/fixtures/forc-projects/liquidity-pool/src/main.sw diff --git a/apps/docs-snippets/test/fixtures/forc-projects/Forc.toml b/apps/docs-snippets/test/fixtures/forc-projects/Forc.toml index ba78a81940a..866df5611da 100644 --- a/apps/docs-snippets/test/fixtures/forc-projects/Forc.toml +++ b/apps/docs-snippets/test/fixtures/forc-projects/Forc.toml @@ -2,6 +2,7 @@ members = [ "counter", "echo-enum", + "liquidity-pool", "log-values", "sum-script", "echo-values", diff --git a/apps/docs-snippets/test/fixtures/forc-projects/index.ts b/apps/docs-snippets/test/fixtures/forc-projects/index.ts index 91b257ed3ea..a09b1bcbfbb 100644 --- a/apps/docs-snippets/test/fixtures/forc-projects/index.ts +++ b/apps/docs-snippets/test/fixtures/forc-projects/index.ts @@ -13,6 +13,7 @@ export enum DocSnippetProjectsEnum { ECHO_U64_ARRAY = 'echo-u64-array', RETURN_CONTEXT = 'return-context', TOKEN_DEPOSITOR = 'token-depositor', + LIQUIDITY_POOL = 'liquidity-pool', SIMPLE_PREDICATE = 'simple-predicate', ECHO_CONFIGURABLES = 'echo-configurables', TRANSFER_TO_ADDRESS = 'transfer-to-address', diff --git a/apps/docs-snippets/test/fixtures/forc-projects/liquidity-pool/Forc.toml b/apps/docs-snippets/test/fixtures/forc-projects/liquidity-pool/Forc.toml new file mode 100644 index 00000000000..878acd9c679 --- /dev/null +++ b/apps/docs-snippets/test/fixtures/forc-projects/liquidity-pool/Forc.toml @@ -0,0 +1,7 @@ +[project] +authors = ["Sérgio Torres da Silveira Filho"] +entry = "main.sw" +license = "Apache-2.0" +name = "liquidity-pool" + +[dependencies] diff --git a/apps/docs-snippets/test/fixtures/forc-projects/liquidity-pool/src/main.sw b/apps/docs-snippets/test/fixtures/forc-projects/liquidity-pool/src/main.sw new file mode 100644 index 00000000000..3f4a16b7614 --- /dev/null +++ b/apps/docs-snippets/test/fixtures/forc-projects/liquidity-pool/src/main.sw @@ -0,0 +1,51 @@ +// #region deposit-and-withdraw-cookbook-1 +contract; + +use std::{ + call_frames::{ + msg_asset_id, + }, + context::msg_amount, + token::{ + mint_to_address, + transfer_to_address, + }, +}; +use std::constants::ZERO_B256; + +abi LiquidityPool { + #[payable] + fn deposit(recipient: Address); + #[payable] + fn withdraw(recipient: Address); +} + +const BASE_TOKEN: AssetId = AssetId::from( + 0x0000000000000000000000000000000000000000000000000000000000000000, +); + +impl LiquidityPool for Contract { + #[payable] + fn deposit(recipient: Address) { + assert(BASE_TOKEN == msg_asset_id()); + assert(0 < msg_amount()); + + // Mint two times the amount. + let amount_to_mint = msg_amount() * 2; + + // Mint some LP token based upon the amount of the base token. + mint_to_address(recipient, ZERO_B256, amount_to_mint); + } + + #[payable] + fn withdraw(recipient: Address) { + assert(0 < msg_amount()); + + // Amount to withdraw. + let amount_to_transfer = msg_amount() / 2; + + // Transfer base token to recipient. + transfer_to_address(recipient, BASE_TOKEN, amount_to_transfer); + } +} +// #endregion deposit-and-withdraw-cookbook-1 From bf4b5006ad5e385f4e6b978986c608767da147a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9rgio=20Torres?= <30977845+Torres-ssf@users.noreply.github.com> Date: Fri, 22 Dec 2023 17:23:44 -0300 Subject: [PATCH 06/10] update doc page deposit and withdraw --- .../cookbook/deposit-and-withdraw.test.ts | 64 +++++++++++++++++++ .../guide/cookbook/deposit-and-withdraw.md | 34 ++-------- 2 files changed, 70 insertions(+), 28 deletions(-) create mode 100644 apps/docs-snippets/src/guide/cookbook/deposit-and-withdraw.test.ts diff --git a/apps/docs-snippets/src/guide/cookbook/deposit-and-withdraw.test.ts b/apps/docs-snippets/src/guide/cookbook/deposit-and-withdraw.test.ts new file mode 100644 index 00000000000..dfc1b2c120b --- /dev/null +++ b/apps/docs-snippets/src/guide/cookbook/deposit-and-withdraw.test.ts @@ -0,0 +1,64 @@ +import type { Contract, WalletUnlocked, Provider } from 'fuels'; +import { ContractFactory, BaseAssetId, Wallet, ZeroBytes32, getAssetId } from 'fuels'; + +import { + DocSnippetProjectsEnum, + getDocsSnippetsForcProject, +} from '../../../test/fixtures/forc-projects'; +import { getTestWallet } from '../../utils'; + +/** + * @group node + */ +describe(__filename, () => { + let sender: WalletUnlocked; + let liquidityPoolContract: Contract; + let provider: Provider; + + beforeAll(async () => { + sender = await getTestWallet(); + + const { abiContents, binHexlified } = getDocsSnippetsForcProject( + DocSnippetProjectsEnum.LIQUIDITY_POOL + ); + provider = sender.provider; + const factory = new ContractFactory(binHexlified, abiContents, sender); + const { minGasPrice } = sender.provider.getGasConfig(); + liquidityPoolContract = await factory.deployContract({ gasPrice: minGasPrice }); + }); + + it('deposit and withdraw cookbook guide', async () => { + // #region deposit-and-withdraw-cookbook-2 + const depositAmount = 100_000; + const liquidityOwner = Wallet.generate({ provider }); + + // the subId used to mint the new asset is a zero b256 on the contract + const subId = ZeroBytes32; + const contractId = liquidityPoolContract.id.toB256(); + + const assetId = getAssetId(contractId, subId); + + await liquidityPoolContract.functions + .deposit({ value: liquidityOwner.address.toB256() }) + .callParams({ forward: [depositAmount, BaseAssetId] }) + .txParams({ gasLimit: 1_000, variableOutputs: 1, gasPrice: 1 }) + .call(); + + const liquidityAmount = await liquidityOwner.getBalance(assetId); + + expect(liquidityAmount.toNumber()).toBe(depositAmount * 2); + // #endregion deposit-and-withdraw-cookbook-2 + + // #region deposit-and-withdraw-cookbook-3 + await liquidityPoolContract.functions + .withdraw({ value: liquidityOwner.address.toB256() }) + .callParams({ forward: [depositAmount, BaseAssetId] }) + .txParams({ gasLimit: 1_000, variableOutputs: 1, gasPrice: 1 }) + .call(); + + const baseAssetAfterWithdraw = await liquidityOwner.getBalance(BaseAssetId); + + expect(baseAssetAfterWithdraw.toNumber()).toBe(depositAmount / 2); + // #endregion deposit-and-withdraw-cookbook-3 + }); +}); diff --git a/apps/docs/src/guide/cookbook/deposit-and-withdraw.md b/apps/docs/src/guide/cookbook/deposit-and-withdraw.md index fa70f045325..511d1a746bf 100644 --- a/apps/docs/src/guide/cookbook/deposit-and-withdraw.md +++ b/apps/docs/src/guide/cookbook/deposit-and-withdraw.md @@ -1,37 +1,15 @@ # Deposit And Withdraw -Consider the following contracts: +Consider the following contract: -<<< @/../../../packages/fuel-gauge/test/fixtures/forc-projects/token_contract/src/main.sw#token-contract{rust:line-numbers} +<<< @/../../docs-snippets/test/fixtures/forc-projects/liquidity-pool/src/main.sw#deposit-and-withdraw-cookbook-1{rust:line-numbers} -<<< @/../../../packages/fuel-gauge/test/fixtures/forc-projects/liquidity-pool/src/main.sw#liquidity-pool-contract{rust:line-numbers} +As the name implies, this contract represents a simplified version of a liquidity pool. The `deposit()` method allows you to supply an arbitrary amount of `BASE_TOKEN`. In response, it mints twice the amount of the liquidity asset to the caller's address. Similarly, the `withdraw()` method transfers half the amount of the `BASE_TOKEN` back to the caller's address. -The first contract is a contract that represents a simple token. +Now, let's deposit some tokens into the liquidity pool contract. Since this requires forwarding assets to the contract, we need to pass the appropriate values to `callParams` when creating out contract call. -The second contract, as its name suggests, represents a simplified example of a liquidity pool contract. The method deposit() expects you to supply an arbitrary amount of the `base_token`. As a result, it mints double the amount of the liquidity asset to the calling address. Analogously, if you call `withdraw()` supplying it with the liquidity asset, it will transfer half that amount of the `base_token` back to the calling address except for deducting it from the contract balance instead of minting it. - -The first step towards interacting with any contract in the TypeScript SDK is using the `typegen` CLI utility to generate type-safe bindings for the contract methods: - -```sh -$ npx fuels typegen -i ./contract/out/debug/*-abi.json -o ./contract-types -``` - -Next, let's setup a [`Wallet`](../wallets/index.md) and seed it with some coins. We will need these coins to deploy the contracts and to interact with them. - -<<< @/../../../packages/fuel-gauge/src/doc-examples.test.ts#deposit-and-withdraw-cookbook-wallet-setup{ts:line-numbers} - -Let's now deploy both the contracts and set them up. - -<<< @/../../../packages/fuel-gauge/src/doc-examples.test.ts#deposit-and-withdraw-cookbook-contract-deployments{ts:line-numbers} - -Next, let's mint some tokens and transfer them to our wallet. - -<<< @/../../../packages/fuel-gauge/src/doc-examples.test.ts#deposit-and-withdraw-cookbook-mint-and-transfer{ts:line-numbers} - -Now, let's deposit some tokens into the liquidity pool contract. Since we have to transfer assets to the contract, we create the appropriate [`callParams`](../contracts/call-parameters.md) and chain them to the method call. - -<<< @/../../../packages/fuel-gauge/src/doc-examples.test.ts#deposit-and-withdraw-cookbook-deposit{ts:line-numbers} +<<< @/../../docs-snippets/src/guide/cookbook/deposit-and-withdraw.test.ts#deposit-and-withdraw-cookbook-2{ts:line-numbers} As a final demonstration, let's use all our liquidity asset balance to withdraw from the pool and confirm we retrieved the initial amount. For this, we get our liquidity asset balance and supply it to the `withdraw()` function via `callParams`. -<<< @/../../../packages/fuel-gauge/src/doc-examples.test.ts#deposit-and-withdraw-cookbook-withdraw{ts:line-numbers} +<<< @/../../docs-snippets/src/guide/cookbook/deposit-and-withdraw.test.ts#deposit-and-withdraw-cookbook-3{ts:line-numbers} From f7ebc99567e0f70bff918ea68fbd7b395b7af146 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9rgio=20Torres?= <30977845+Torres-ssf@users.noreply.github.com> Date: Fri, 22 Dec 2023 17:25:26 -0300 Subject: [PATCH 07/10] add changeset --- .changeset/kind-hotels-divide.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/kind-hotels-divide.md diff --git a/.changeset/kind-hotels-divide.md b/.changeset/kind-hotels-divide.md new file mode 100644 index 00000000000..7683a229116 --- /dev/null +++ b/.changeset/kind-hotels-divide.md @@ -0,0 +1,5 @@ +--- +"@fuel-ts/transactions": minor +--- + +update deposit and withdraw doc page From 19727c0bfeb799b34502739973d1685016a382ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9rgio=20Torres?= <30977845+Torres-ssf@users.noreply.github.com> Date: Fri, 22 Dec 2023 17:34:51 -0300 Subject: [PATCH 08/10] fixing forc project authors --- .../test/fixtures/forc-projects/liquidity-pool/Forc.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/docs-snippets/test/fixtures/forc-projects/liquidity-pool/Forc.toml b/apps/docs-snippets/test/fixtures/forc-projects/liquidity-pool/Forc.toml index 878acd9c679..6fbb1a576a4 100644 --- a/apps/docs-snippets/test/fixtures/forc-projects/liquidity-pool/Forc.toml +++ b/apps/docs-snippets/test/fixtures/forc-projects/liquidity-pool/Forc.toml @@ -1,5 +1,5 @@ [project] -authors = ["Sérgio Torres da Silveira Filho"] +authors = ["Fuel Labs "] entry = "main.sw" license = "Apache-2.0" name = "liquidity-pool" From ca88588a64a00766f18ed3a87cd833d30ee8da8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9rgio=20Torres?= <30977845+Torres-ssf@users.noreply.github.com> Date: Fri, 22 Dec 2023 17:49:03 -0300 Subject: [PATCH 09/10] Update apps/docs/src/guide/cookbook/deposit-and-withdraw.md Co-authored-by: Anderson Arboleya --- apps/docs/src/guide/cookbook/deposit-and-withdraw.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/docs/src/guide/cookbook/deposit-and-withdraw.md b/apps/docs/src/guide/cookbook/deposit-and-withdraw.md index 511d1a746bf..0ae4806e3c9 100644 --- a/apps/docs/src/guide/cookbook/deposit-and-withdraw.md +++ b/apps/docs/src/guide/cookbook/deposit-and-withdraw.md @@ -6,7 +6,7 @@ Consider the following contract: As the name implies, this contract represents a simplified version of a liquidity pool. The `deposit()` method allows you to supply an arbitrary amount of `BASE_TOKEN`. In response, it mints twice the amount of the liquidity asset to the caller's address. Similarly, the `withdraw()` method transfers half the amount of the `BASE_TOKEN` back to the caller's address. -Now, let's deposit some tokens into the liquidity pool contract. Since this requires forwarding assets to the contract, we need to pass the appropriate values to `callParams` when creating out contract call. +Now, let's deposit some tokens into the liquidity pool contract. Since this requires forwarding assets to the contract, we need to pass the appropriate values to `callParams` when creating a contract call. <<< @/../../docs-snippets/src/guide/cookbook/deposit-and-withdraw.test.ts#deposit-and-withdraw-cookbook-2{ts:line-numbers} From c886d824db4d209e979c0dd71627da580bd807d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9rgio=20Torres?= <30977845+Torres-ssf@users.noreply.github.com> Date: Fri, 22 Dec 2023 18:28:06 -0300 Subject: [PATCH 10/10] try to fix flaky test --- packages/providers/test/provider.test.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/providers/test/provider.test.ts b/packages/providers/test/provider.test.ts index 246e45b3799..95cc5339398 100644 --- a/packages/providers/test/provider.test.ts +++ b/packages/providers/test/provider.test.ts @@ -11,6 +11,7 @@ import * as fuelTsVersionsMod from '@fuel-ts/versions'; import { getBytesCopy, hexlify } from 'ethers'; import type { BytesLike } from 'ethers'; +import { fromTai64ToDate } from '../src'; import type { ChainInfo, NodeInfo, TransactionCost, FetchRequestOptions } from '../src/provider'; import Provider from '../src/provider'; import type { @@ -295,20 +296,19 @@ describe('Provider', () => { if (!block) { throw new Error('No latest block'); } - const { height: latestBlockNumberBeforeProduce } = block; + const { time: timeLastBlockProduced } = block; const amountOfBlocksToProduce = 3; - await provider.produceBlocks(amountOfBlocksToProduce); + const producedBlockHeigh = await provider.produceBlocks(amountOfBlocksToProduce); - const blocks = await provider.getBlocks({ - last: 20, - }); + const producedBlock = await provider.getBlock(producedBlockHeigh.toNumber()); - const lastBlockIndex = blocks.findIndex((b) => b.height.eq(latestBlockNumberBeforeProduce)); + expect(producedBlock).toBeDefined(); - const newBlocks = blocks.slice(lastBlockIndex + 1); + const oldest = new Date(fromTai64ToDate(timeLastBlockProduced || '')); + const newest = new Date(fromTai64ToDate(producedBlock?.time || '')); - expect(newBlocks.length).toBeGreaterThanOrEqual(amountOfBlocksToProduce); + expect(newest >= oldest).toBeTruthy(); // #endregion Provider-produce-blocks });