Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Markdown
https://github.com/fuellabs/markdown
Admin
Consolidated docs in markdown form for Fuel Labs projects.
Tokens:
526,002
Snippets:
4,297
Trust Score:
9.7
License:
Apache-2.0
Update:
2 months ago
Context
Chat
Benchmark
66
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Setup Program Test with Deploy and Contract Call Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-rs/docs/src/testing/the-setup-program-test-macro.md Reduces setup code by using the macro to deploy a contract and then call its methods. The contract is deployed with salt, allowing multiple deployments. The example shows how to call a contract method and assert the response. ```rust setup_program_test!( Wallets("wallet"), Abigen(Contract( name = "TestContract", project = "e2e/sway/contracts/contract_test" )), Deploy( name = "contract_instance", contract = "TestContract", wallet = "wallet" ), ); let response = contract_instance .methods() .initialize_counter(42) .call() .await?; assert_eq!(42, response.value); ``` -------------------------------- ### Full example with transaction preparation Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/scripts/configurable-constants.md.md Complete TypeScript example that sets configurable constants, calls the script, and also demonstrates preparing a transaction with callParams, getting the transaction ID, and retrieving actual gas used. ```typescript import { Script, BN, Wallet, Provider } from 'fuels'; import { WALLET_PVT_KEY, LOCAL_NETWORK_URL } from '../../../env'; import { ScriptSum } from '../../../typegend/scripts/ScriptSum'; // #region script-with-configurable-contants-2 const provider = new Provider(LOCAL_NETWORK_URL); const wallet = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider); const script = new Script(ScriptSum.bytecode, ScriptSum.abi, wallet); const configurableConstants = { AMOUNT: 81, }; script.setConfigurableConstants(configurableConstants); const inputtedValue = 10; const { waitForResult } = await script.functions.main(inputtedValue).call(); const { value } = await waitForResult(); const expectedTotal = inputtedValue + configurableConstants.AMOUNT; // #endregion script-with-configurable-contants-2 const argument = 10; const expected = 20; // #region preparing-scripts const myMainScript = new Script(ScriptSum.bytecode, ScriptSum.abi, wallet); const tx = myMainScript.functions.main(argument); // Set the call parameters tx.callParams({ gasLimit: 7500 }); // Get the entire transaction request prior to const txRequest = await tx.getTransactionRequest(); // Get the transaction ID const chainId = await provider.getChainId(); const txId = txRequest.getTransactionId(chainId); // Retrieve the value of the call and the actual gas used const { waitForResult: waitForActualGasUsed } = await tx.call(); const { value: valueOfActualGasUsed, gasUsed: gasUsedOfActualGasUsed } = await waitForActualGasUsed(); // #endregion preparing-scripts ``` -------------------------------- ### Manual Wallet Creation with Setup Macro Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-rs/docs/src/testing/the-setup-program-test-macro.md Shows how to manually create wallets and use them inside the macro for custom setups. Useful for creating custom wallets or providers while still reducing boilerplate. The example uses a custom provider configuration and deploys a contract with a fixed salt. ```rust let config = WalletsConfig::new(Some(2), Some(1), Some(DEFAULT_COIN_AMOUNT)); let mut wallets = launch_custom_provider_and_get_wallets(config, None, None).await?; let wallet = wallets.pop().unwrap(); let wallet_2 = wallets.pop().unwrap(); setup_program_test!( Abigen(Contract( name = "TestContract", project = "e2e/sway/contracts/contract_test" )), Deploy( name = "contract_instance", contract = "TestContract", wallet = "wallet", random_salt = false, ), ); ``` -------------------------------- ### Install Cosmovisor with go install Source: https://github.com/fuellabs/markdown/blob/main/docs/node-operator/docs/src/fuel-sequencer/testnet-validator.md Installs the Cosmovisor binary using the Go toolchain. Run this command before setting environment variables. ```sh go install cosmossdk.io/tools/cosmovisor/cmd/cosmovisor@latest ``` -------------------------------- ### Install Cosmovisor Source: https://github.com/fuellabs/markdown/blob/main/docs/node-operator/docs/src/fuel-sequencer/mainnet-validator.md Installs the Cosmovisor binary using Go and sets up the required environment variables for the Fuel Sequencer daemon. ```APIDOC ## Install Cosmovisor ### Description Installs the Cosmovisor binary using Go and sets up the required environment variables for the Fuel Sequencer daemon. ### Method N/A (Command-line installation) ### Command ```sh go install cosmossdk.io/tools/cosmovisor/cmd/cosmovisor@latest ``` ### Environment Variables - **DAEMON_NAME** (string) - Required - The name of the daemon binary (fuelsequencerd). - **DAEMON_HOME** (string) - Required - The home directory for the daemon ($HOME/.fuelsequencer). - **DAEMON_ALLOW_DOWNLOAD_BINARIES** (boolean) - Required - Whether to allow downloading binaries (true). - **DAEMON_LOG_BUFFER_SIZE** (integer) - Required - Log buffer size (512). - **DAEMON_RESTART_AFTER_UPGRADE** (boolean) - Required - Whether to restart after upgrade (true). - **UNSAFE_SKIP_BACKUP** (boolean) - Required - Skip backup (true). - **DAEMON_SHUTDOWN_GRACE** (duration) - Required - Grace period for shutdown (15s). ### Example (zsh) ```zsh echo "# Setup Cosmovisor" >> ~/.zshrc echo "export DAEMON_NAME=fuelsequencerd" >> ~/.zshrc echo "export DAEMON_HOME=$HOME/.fuelsequencer" >> ~/.zshrc echo "export DAEMON_ALLOW_DOWNLOAD_BINARIES=true" >> ~/.zshrc echo "export DAEMON_LOG_BUFFER_SIZE=512" >> ~/.zshrc echo "export DAEMON_RESTART_AFTER_UPGRADE=true" >> ~/.zshrc echo "export UNSAFE_SKIP_BACKUP=true" >> ~/.zshrc echo "export DAEMON_SHUTDOWN_GRACE=15s" >> ~/.zshrc source ~/.zshrc ``` ### Example (bash) ```zsh echo "# Setup Cosmovisor" >> ~/.bashrc echo "export DAEMON_NAME=fuelsequencerd" >> ~/.bashrc echo "export DAEMON_HOME=$HOME/.fuelsequencer" >> ~/.bashrc echo "export DAEMON_ALLOW_DOWNLOAD_BINARIES=true" >> ~/.bashrc echo "export DAEMON_LOG_BUFFER_SIZE=512" >> ~/.bashrc echo "export DAEMON_RESTART_AFTER_UPGRADE=true" >> ~/.bashrc echo "export UNSAFE_SKIP_BACKUP=true" >> ~/.bashrc echo "export DAEMON_SHUTDOWN_GRACE=15s" >> ~/.bashrc source ~/.bashrc ``` ### Verify Installation ```sh cosmovisor version ``` ### Initialize Directories ```sh cosmovisor init <path/to/fuelsequencerd> ``` ### Notes - After initialization, `cosmovisor run` is equivalent to running `fuelsequencerd`. - Do not run the node yet. ``` -------------------------------- ### Full Transaction Parameters Example Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/transactions/adding-parameters.md.md This snippet shows the complete setup for configuring transaction parameters in a Fuel dApp. It includes importing necessary modules, deploying a contract, defining a TxParams object with all parameters, creating a transaction request, and executing a contract call. The example uses a local network and a wallet from a private key. ```typescript import type { TxParams } from 'fuels'; import { bn, Provider, ScriptTransactionRequest, Wallet } from 'fuels'; import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../env'; import { CounterFactory } from '../../../typegend'; import { ScriptSum } from '../../../typegend/scripts'; const provider = new Provider(LOCAL_NETWORK_URL); const wallet = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider); const deploy = await CounterFactory.deploy(wallet); const { contract } = await deploy.waitForResult(); // #region transaction-parameters-7 const txParams: TxParams = { // #region transaction-parameters-1 gasLimit: bn(70935), // #endregion transaction-parameters-1 // #region transaction-parameters-2 maxFee: bn(69242), // #endregion transaction-parameters-2 // #region transaction-parameters-3 tip: bn(100), // #endregion transaction-parameters-3 // #region transaction-parameters-4 maturity: 1, // #endregion transaction-parameters-4 // #region transaction-parameters-5 witnessLimit: bn(5000), // #endregion transaction-parameters-5 // #region transaction-parameters-6 expiration: 200, // #endregion transaction-parameters-6 }; // #endregion transaction-parameters-7 // #region transaction-parameters-8 const transactionRequest = new ScriptTransactionRequest({ script: ScriptSum.bytecode, gasLimit: 100, }); // #endregion transaction-parameters-8 // #region transaction-parameters-9 const { waitForResult } = await contract.functions .increment_count(15) // .txParams(txParams) .call(); const { value, transactionResult: { isStatusSuccess }, } = await waitForResult(); console.log('Transaction request', transactionRequest); console.log('Transaction status', isStatusSuccess); console.log('Transaction value', value); // #endregion transaction-parameters-9 ``` -------------------------------- ### Start node with setup_test_provider Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-rs/docs/src/cookbook/custom-chain.md Calls setup_test_provider with the coins, an empty vec, a default NodeConfig, and the custom chain_config to start a node and return a provider. ```rust let node_config = NodeConfig::default(); let _provider = setup_test_provider(coins, vec![], Some(node_config), Some(chain_config)).await?; ``` -------------------------------- ### Install Fuel toolchain with fuelup-init Source: https://github.com/fuellabs/markdown/blob/main/docs/node-operator/docs/src/fuel-ignition/testnet-node.md Run this command in a terminal to install the Fuel toolchain, including forc, forc-client, forc-fmt, forc-lsp, forc-wallet, and fuel-core into ~/.fuelup/bin. ```sh curl https://install.fuel.network | sh ``` -------------------------------- ### Install urql and graphql Source: https://github.com/fuellabs/markdown/blob/main/docs/fuel-graphql-docs/docs/querying-from-a-dapp.md Command to install the urql and graphql packages via npm. ```bash npm install urql graphql ``` -------------------------------- ### Function Examples Section Example Source: https://github.com/fuellabs/markdown/blob/main/docs/sway-standards/docs/src/src-2-inline-documentation.md Shows the format for providing an example of function usage, with a nested code block inside the documentation comment. ```sway /// # Examples /// /// ```sway /// fn foo(argument_1: b256, argument_2: b256) { /// let result = my_function(argument_1, argument_2); /// } ``` -------------------------------- ### Install Apollo Client and graphql Source: https://github.com/fuellabs/markdown/blob/main/docs/fuel-graphql-docs/docs/querying-from-a-dapp.md Command to install the Apollo Client and graphql packages via npm. ```bash npm install @apollo/client graphql ``` -------------------------------- ### Example output of fuelsequencerd keys list Source: https://github.com/fuellabs/markdown/blob/main/docs/node-operator/docs/src/fuel-sequencer/mainnet-validator.md Example output showing the address, name, public key, and type of a local account. ```sh address: fuelsequencer1zzu4804kp6m6whzza6r75g7mnme2ahqkjuw4kf name: my-mainnet-validator pubkey: '{"@type":"/cosmos.crypto.secp256k1.PubKey","key":"Al6W+Ttrscm/8njeMOt79T0BOdphfWGXrDLij+O3g19N"}' type: local ``` -------------------------------- ### Run guide tests locally with pnpm test:guides Source: https://github.com/fuellabs/markdown/blob/main/docs/contributing/guides.md Use this command to run the guide tests locally. It is recommended to create a test for new guides using the TestAction component. ```sh pnpm test:guides ``` -------------------------------- ### Configurable Example Source: https://github.com/fuellabs/markdown/blob/main/docs/sway-standards/docs/src/src-2-inline-documentation.md An example of a documented configurable variable representing a threshold required for activation. ```APIDOC ## Configurable: THRESHOLD ### Description The threshold required for activation. ### Value - `THRESHOLD` (u64) - Default value: `5`. ``` -------------------------------- ### Library `Forc.toml` example Source: https://github.com/fuellabs/markdown/blob/main/docs/sway/docs/book/src/sway-program-types/libraries.md An example of a library's `Forc.toml` file, which includes project metadata such as authors, entry file, license, name, and dependencies. ```toml [project] authors = ["Fuel Labs <contact@fuel.sh>"] entry = "lib.sw" license = "Apache-2.0" name = "my_library" [dependencies] ``` -------------------------------- ### CDN Usage Example Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/getting-started/cdn-usage.md.md This example shows how to import the Fuel SDK from a CDN and use it to create a Provider instance, connect to a Fuel network, and retrieve the chain name. ```APIDOC ## CDN Usage Example ### Description This example demonstrates how to use the Fuel SDK in a browser by importing it from a CDN. It creates a Provider instance, connects to a Fuel network, and fetches the chain name. ### Method - **Provider** - Constructor for creating a new Provider instance. - **getChain** - Asynchronous method to retrieve chain information. ### Endpoint - **Provider** - `new Provider(url)` - **getChain** - `provider.getChain()` ### Parameters #### Provider Constructor - **url** (string) - Required - The GraphQL endpoint URL of the Fuel network. ### Request Example ```javascript const provider = new Provider("https://mainnet.fuel.network/v1/graphql"); ``` ### Response #### getChain Response - **name** (string) - The name of the chain. #### Response Example ```javascript const { name } = await provider.getChain(); console.log(name); ``` ``` -------------------------------- ### connectors Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/wallets/connectors.md.md Gets the current list of installed and connected connectors. ```APIDOC ## connectors ### Description Gets the current list of installed and connected connectors. ### Method connectors ### Signature ```typescript connectors: () => Promise<Array<FuelConnector>>; ``` ### Parameters None ### Returns - **Promise<Array<FuelConnector>>** - A promise that resolves to an array of FuelConnector objects. ``` -------------------------------- ### Function Reverts Example Source: https://github.com/fuellabs/markdown/blob/main/docs/sway-standards/docs/src/src-2-inline-documentation.md Shows the format for listing revert conditions, with each case starting with an asterisk. ```sway /// # Reverts /// /// * When `argument_1` or `argument_2` are a zero [b256]. ``` -------------------------------- ### Set up provider and wallets Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-rs/docs/src/predicates/send-spend-predicate.md Sets up test coins and a provider, then creates wallets for the three signers and the receiver. Uses `setup_single_asset_coins` and `setup_test_provider`. ```rust let asset_id = AssetId::zeroed(); let num_coins = 32; let amount = 64; let initial_balance = amount * num_coins; let all_coins = [ &wallet_signer, &wallet2_signer, &wallet3_signer, &receiver_signer, ] .iter() .flat_map(|signer| setup_single_asset_coins(signer.address(), asset_id, num_coins, amount)) .collect::<Vec<_>>(); let provider = setup_test_provider(all_coins, vec![], None, None).await?; let wallet = Wallet::new(wallet_signer, provider.clone()); let wallet2 = Wallet::new(wallet2_signer, provider.clone()); let wallet3 = Wallet::new(wallet3_signer, provider.clone()); let receiver = Wallet::new(receiver_signer, provider.clone()); ``` -------------------------------- ### Sway contract integration example Source: https://github.com/fuellabs/markdown/blob/main/docs/sway-libs/docs/book/src/ownership/index.md Complete example of using the ownership library in a Sway contract. It demonstrates initializing ownership, restricting functions to the owner, transferring and renouncing ownership, and retrieving the current owner. The example defines a contract with configurable initial owner and implements the SRC5 standard and a custom ABI. ```sway contract; use ownership::{_owner, initialize_ownership, only_owner, renounce_ownership, transfer_ownership}; use src5::{SRC5, State}; configurable { INITAL_OWNER: Identity = Identity::Address(Address::zero()), } impl SRC5 for Contract { #[storage(read)] fn owner() -> State { _owner() } } abi MyContract { #[storage(read, write)] fn initialize(); #[storage(read)] fn restricted_action(); #[storage(read, write)] fn change_owner(new_owner: Identity); #[storage(read, write)] fn revoke_ownership(); #[storage(read)] fn get_current_owner() -> State; } impl MyContract for Contract { #[storage(read, write)] fn initialize() { initialize_ownership(INITAL_OWNER); } // A function restricted to the owner #[storage(read)] fn restricted_action() { only_owner(); // Protected action } // Transfer ownership #[storage(read, write)] fn change_owner(new_owner: Identity) { transfer_ownership(new_owner); } // Renounce ownership #[storage(read, write)] fn revoke_ownership() { renounce_ownership(); } // Get current owner state #[storage(read)] fn get_current_owner() -> State { _owner() } } ``` -------------------------------- ### Create a new Sway project with forc new Source: https://github.com/fuellabs/markdown/blob/main/docs/sway/docs/book/src/debugging/debugging_with_cli.md Creates a new script project named `dbg_example` and changes into its directory. Run this before adding source code. ```bash forc new --script dbg_example && cd dbg_example ``` -------------------------------- ### Read contract data with `get` Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/contracts/methods.md.md Use the `get` method to read data from the blockchain without spending resources. It can be used with an unfunded wallet or even without a wallet at all. The example deploys a counter contract and reads the `get_count` function, returning the value 0. ```typescript import { Provider, Wallet } from 'fuels'; import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../../env'; import { CounterFactory } from '../../../../typegend'; const provider = new Provider(LOCAL_NETWORK_URL); const deployer = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider); const deployContract = await CounterFactory.deploy(deployer); const { contract } = await deployContract.waitForResult(); // Read from the blockchain const { value } = await contract.functions.get_count().get(); // 0 ``` -------------------------------- ### Initialize Cosmovisor Source: https://github.com/fuellabs/markdown/blob/main/docs/node-operator/docs/src/fuel-sequencer/mainnet-node.md Sets up Cosmovisor directories. Replace <path/to/fuelsequencerd> with the actual binary path, which can be found using 'whereis fuelsequencerd'. ```sh cosmovisor init <path/to/fuelsequencerd> ``` -------------------------------- ### Inter-Contract Call using SDK (TypeScript) Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/contracts/inter-contract-calls.md.md This TypeScript example deploys both contracts and performs a call from TokenDepositor to SimpleToken. It highlights the addContracts method, which is required for the inter-contract call to work. The example shows how to get the initial balance, make the deposit, and then check the final balance. ```typescript import { Provider, Wallet } from 'fuels'; import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../env'; import { SimpleTokenFactory, TokenDepositorFactory } from '../../../typegend'; const provider = new Provider(LOCAL_NETWORK_URL); const wallet = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider); const { waitForResult: waitForSimpleToken } = await SimpleTokenFactory.deploy(wallet); const { contract: simpleToken } = await waitForSimpleToken(); const { waitForResult: waitForTokenDepositor } = await TokenDepositorFactory.deploy(wallet); const { contract: tokenDepositor } = await waitForTokenDepositor(); const amountToDeposit = 70; const call1 = await simpleToken.functions .get_balance(wallet.address.toB256()) .call(); const { value: initialBalance } = await call1.waitForResult(); const call2 = await tokenDepositor.functions .deposit_to_simple_token(simpleToken.id.toB256(), amountToDeposit) .addContracts([simpleToken]) .call(); await call2.waitForResult(); const call3 = await simpleToken.functions .get_balance(wallet.address.toB256()) .call(); const { value: finalBalance } = await call3.waitForResult(); ``` -------------------------------- ### Withdraw Function Implementation Source: https://github.com/fuellabs/markdown/blob/main/docs/sway-standards/docs/src/src-6-vault.md Handles withdrawal of assets from the vault, logging the withdrawal event. Uses msg_sender().unwrap() to get the caller and returns the assets after withdrawal. ```Sway Withdraw::new( msg_sender() .unwrap(), receiver, underlying_asset, vault_sub_id, assets, shares, ) .log(); assets } ``` -------------------------------- ### Restrict function to owner with only_owner Source: https://github.com/fuellabs/markdown/blob/main/docs/sway-libs/docs/book/src/ownership/index.md Call only_owner() at the start of a function to ensure only the contract owner can execute it. The example shows a function that only the owner can reach. ```sway #[storage(read)] fn only_owner_may_call() { only_owner(); // Only the contract's owner may reach this line. } ``` -------------------------------- ### Get current ownership state with _owner Source: https://github.com/fuellabs/markdown/blob/main/docs/sway-libs/docs/book/src/ownership/index.md Call _owner() to retrieve the current ownership state. The example stores the result in a variable of type State. ```sway #[storage(read)] fn get_owner_state() { let owner: State = _owner(); } ``` -------------------------------- ### Set metadata.install object Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/wallets/connectors.md.md Provides installation information with required action, link, and description properties. ```typescript install: { action: 'Install', description: 'Install the My Wallet Connector', link: 'https://example.com/install', }, ``` -------------------------------- ### Success message after scaffolding Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/creating-a-fuel-dapp/index.md.md Output after the project is scaffolded and dependencies installed. Provides next steps: cd into the project, start the dev server, and run the frontend. ```md ⚡️ Success! Created a fullstack Fuel dapp at my-fuel-project To get started: - cd into the project directory: cd my-fuel-project - Start a local Fuel dev server: pnpm fuels:dev - Run the frontend: pnpm dev -> TS SDK docs: https://docs.fuel.network/docs/fuels-ts/ -> Sway docs: https://docs.fuel.network/docs/sway/ -> If you have any questions, check the Fuel forum: https://forum.fuel.network/ ``` -------------------------------- ### Example Forc.toml with [project] and [project.metadata] Source: https://github.com/fuellabs/markdown/blob/main/docs/sway/docs/book/src/forc/manifest_reference.md Shows a complete Forc.toml example with the [project] section and a [project.metadata] section for indexing. The [project] fields are optional except for name and license, with defaults for entry and implicit-std. ```toml [project] authors = ["user"] entry = "main.sw" description = "Wallet contract" version = "1.0.0" homepage = "https://example.com/" repository = "https://example.com/" documentation = "https://example.com/" organization = "Fuel_Labs" license = "Apache-2.0" name = "wallet_contract" categories = ["example"] keywords = ["example"] [project.metadata] indexing = { namespace = "counter-contract", schema_path = "out/release/counter-contract-abi.json" } ``` -------------------------------- ### Get output values with type annotation on method Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-rs/docs/src/calling-contracts/multicalls.md Alternatively, move the type annotation to the invoked method to interact with the CallResponse directly. This example uses call::<(u64, [u64; 2])>() to specify the output type. ```rust let response = multi_call_handler.call::<(u64, [u64; 2])>().await?; ``` -------------------------------- ### Setup test wallet with multiple custom assets Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-rs/docs/src/wallets/test-wallets.md Creates a test wallet with custom assets by defining `AssetConfig` for each asset, including the base asset. Uses `setup_custom_assets_coins` to generate coins and then sets up a provider and wallet. ```rust use fuels::prelude::*; use rand::Fill; let mut rng = rand::thread_rng(); let signer = PrivateKeySigner::random(&mut rng); let asset_base = AssetConfig { id: AssetId::zeroed(), num_coins: 2, coin_amount: 4, }; let mut asset_id_1 = AssetId::zeroed(); asset_id_1.try_fill(&mut rng)?; let asset_1 = AssetConfig { id: asset_id_1, num_coins: 6, coin_amount: 8, }; let mut asset_id_2 = AssetId::zeroed(); asset_id_2.try_fill(&mut rng)?; let asset_2 = AssetConfig { id: asset_id_2, num_coins: 10, coin_amount: 12, }; let assets = vec![asset_base, asset_1, asset_2]; let coins = setup_custom_assets_coins(signer.address(), &assets); let provider = setup_test_provider(coins, vec![], None, None).await?; let wallet = Wallet::new(signer, provider.clone()); let num_wallets = 1; let wallet_config = WalletsConfig::new_multiple_assets(num_wallets, assets); let wallets = launch_custom_provider_and_get_wallets(wallet_config, None, None).await?; ``` -------------------------------- ### Get output values with explicit type annotation Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-rs/docs/src/calling-contracts/multicalls.md When calling or simulating a multi-call, provide explicit type annotations to capture the output values. This example shows saving the result of call() to a variable with a tuple type. ```rust let (counter, array): (u64, [u64; 2]) = multi_call_handler.call().await?.value; ``` -------------------------------- ### Inter-contract: Sway Contract Example Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/contracts/logs.md.md Sway contract that makes an inter-contract call to the `LogSimple` contract. It defines ABIs for `LogSimple` and `LogInterCalls`, and the `log_inter_call` function logs a start message, calls the simple contract, and logs a completion message. ```sway contract; // Interface from the `LogSimple` contract abi LogSimple { fn log_simple(val: str[9]); } // Interface for the contract abi LogInterCalls { fn log_inter_call(contract_id: b256, simple_log_message: str[9]); } impl LogInterCalls for Contract { fn log_inter_call(contract_id: b256, simple_log_message: str[9]) { log("Starting inter-call"); let logger = abi(LogSimple, contract_id); logger.log_simple(simple_log_message); log("Inter-call completed"); } } ``` -------------------------------- ### File structure example Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/fuels-cli/index.md.md Shows the expected file structure for a Fuel dApp project, including the sway-programs workspace and generated API directory. ```sh my-fuel-dapp # NextJS app or similar ├── sway-programs # Forc's workspace │ ├── src │ ├── ... │ └── Forc.toml ├── public │ └── ... ├── src │ ├── app │ ├── ... ├ └── sway-programs-api # Type-safe generated API └── package.json ``` -------------------------------- ### Example using Option for division Source: https://github.com/fuellabs/markdown/blob/main/docs/sway/docs/book/src/basics/commonly_used_library_types.md Shows a script that returns Option<u64> from a divide function, using None for division by zero, and pattern matching in main to log the result or an error message. ```sway script; fn divide(numerator: u64, denominator: u64) -> Option<u64> { if denominator == 0 { None } else { Some(numerator / denominator) } } fn main() { let result = divide(6, 2); // Pattern match to retrieve the value match result { // The division was valid Some(x) => std::logging::log(x), // The division was invalid None => std::logging::log("Cannot divide by 0"), } } ``` -------------------------------- ### transfer: Send funds directly from a predicate Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/predicates/methods.md.md Sends funds directly from a predicate to another address. The example shows the required setup: funding the predicate first, then calling `transfer` with the receiver, amount, asset ID, and gas limit. ```typescript import { Provider, Wallet } from 'fuels'; import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../../env'; import { ReturnTruePredicate } from '../../../../typegend'; const provider = new Provider(LOCAL_NETWORK_URL); const baseAssetId = await provider.getBaseAssetId(); const funder = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider); const predicate = new ReturnTruePredicate({ provider, }); const fundPredicate = await funder.transfer( predicate.address, 100_000_000, baseAssetId ); await fundPredicate.waitForResult(); const receiver = Wallet.generate({ provider }); const amountToReceiver = 1000; const transferPredicateCoins = await predicate.transfer( receiver.address, amountToReceiver, baseAssetId, { gasLimit: 1000, } ); await transferPredicateCoins.waitForResult(); ``` -------------------------------- ### Setup test wallet with multiple custom assets using WalletsConfig Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-rs/docs/src/wallets/test-wallets.md Alternative approach to create a test wallet with custom assets using `WalletsConfig::new_multiple_assets` and `launch_custom_provider_and_get_wallets`. Note: you must manually add the base asset and corresponding coins and coin amount. ```rust let num_wallets = 1; let wallet_config = WalletsConfig::new_multiple_assets(num_wallets, assets); let wallets = launch_custom_provider_and_get_wallets(wallet_config, None, None).await?; ``` -------------------------------- ### Run local node with forc node Source: https://github.com/fuellabs/markdown/blob/main/docs/node-operator/docs/src/fuel-ignition/local-node.md Starts a local Fuel node with default configuration (state persistence) using the `forc node local` command. Requires the latest `fuelup` installed. The default configuration is highlighted in green in the output. ```sh forc node local ``` -------------------------------- ### Sway vector examples: storage and heap vectors Source: https://github.com/fuellabs/markdown/blob/main/docs/sway-by-example-lib/docs/src/vector.md This Sway contract demonstrates storage vectors (StorageVec) and heap vectors (Vec). It includes operations like push, pop, get, set, remove, swap_remove, len, and clear, with comments showing expected behavior. ```sway contract; use std::{storage::storage_vec::*}; // storage vector, heap abi MyContract { #[storage(read, write)] fn storage_vec_examples(); fn heap_vec_examples(); } storage { nums: StorageVec<u64> = StorageVec {}, } impl MyContract for Contract { #[storage(read, write)] fn storage_vec_examples() { // push // pop // get // set // remove - moves all elements down by one // swap remove - remove element, move last element // len // clear - sets length to zero // loop // push storage.nums.push(100); storage.nums.push(200); storage.nums.push(300); storage.nums.push(400); storage.nums.push(500); storage.nums.push(600); // pop - remove last - returns Option<num> let last = storage.nums.pop(); // get let first = storage.nums.get(0).unwrap(); let none = storage.nums.get(1000); // set storage.nums.set(0, 123); // remove - Returns value removed // Before remove [100, 200, 300, 400] // After remove [100, 300, 400] let removed_val = storage.nums.remove(1); // swap remove // Before swap_remove [100, 300, 400, 500] // After swap_remove [100, 500, 400] storage.nums.swap_remove(1); let len = storage.nums.len(); // clear - sets length to zero storage.nums.clear(); // Loop example let mut i = 0; while i < len { let val = storage.nums.get(i).unwrap(); i += 1; } } fn heap_vec_examples() { // new // push // pop // remove // get // set // len let mut v: Vec<u64> = Vec::new(); v.push(100); v.push(200); v.push(300); v.push(400); v.push(500); // Returns Option<u64> v.pop(); // Before remove [100, 200, 300, 400] // After remove [100, 300, 400] // Returns removed element v.remove(1); let val = v.get(1).unwrap(); v.set(1, val + 1); let len = v.len(); } } ``` -------------------------------- ### Initialize with contracts Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/fuels-cli/commands.md.md Creates a sample `fuel.config.ts` file, specifying contracts and output paths. ```console-vue npx fuels@{{fuels}} init --contracts ./my-contracts/* --output ./src/sway-contracts-api ``` -------------------------------- ### Setup test wallet with multiple random assets Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-rs/docs/src/wallets/test-wallets.md Creates a test wallet with multiple random assets, including the base asset for gas. Uses `setup_multiple_assets_coins` to generate coins and asset IDs, then sets up a provider and wallet. ```rust // ANCHOR: multiple_assets_coins use fuels::prelude::*; let signer = PrivateKeySigner::random(&mut thread_rng()); let num_assets = 5; let coins_per_asset = 10; let amount_per_coin = 15; let (coins, asset_ids) = setup_multiple_assets_coins( signer.address(), num_assets, coins_per_asset, amount_per_coin, ); // ANCHOR_END: multiple_assets_coins let provider = setup_test_provider(coins.clone(), vec![], None, None).await?; let wallet = Wallet::new(signer, provider); ``` -------------------------------- ### TypeScript: mint coins and get minted asset ID with getMintedAssetId Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/contracts/minted-token-asset-id.md.md TypeScript example that deploys a token contract, mints coins with a sub ID, and uses the getMintedAssetId helper to obtain the minted asset ID. Requires a local network and a wallet private key from the environment. ```typescript import { bn, getMintedAssetId, Provider, Wallet } from 'fuels'; import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../../env'; import { TokenFactory } from '../../../../typegend'; const provider = new Provider(LOCAL_NETWORK_URL); const deployer = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider); const deployContract = await TokenFactory.deploy(deployer); const { contract } = await deployContract.waitForResult(); // Any valid B256 string can be used as a sub ID const subID = '0xc7fd1d987ada439fc085cfa3c49416cf2b504ac50151e3c2335d60595cb90745'; const mintAmount = bn(1000); const { waitForResult } = await contract.functions .mint_coins(subID, mintAmount) .call(); await waitForResult(); // Get the minted const mintedAssetId = getMintedAssetId(contract.id.toB256(), subID); ``` -------------------------------- ### Check if a function is read-only with `isReadOnly` Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/contracts/methods.md.md Use the `isReadOnly` utility method to determine whether a contract function is read-only. If read-only, use `get` to retrieve onchain data without spending gas; otherwise, use `call` to submit a transaction that incurs a gas fee. The example checks `get_count` and branches accordingly. ```typescript import { Provider, Wallet } from 'fuels'; import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../../env'; import { CounterFactory } from '../../../../typegend'; const provider = new Provider(LOCAL_NETWORK_URL); const deployer = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider); const deployContract = await CounterFactory.deploy(deployer); const { contract } = await deployContract.waitForResult(); const isReadOnly = contract.functions.get_count.isReadOnly(); if (isReadOnly) { await contract.functions.get_count().get(); } else { const { waitForResult } = await contract.functions.get_count().call(); await waitForResult(); } ``` -------------------------------- ### Deploy Command Example Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-rs/docs/src/testing/the-setup-program-test-macro.md Deploys a contract using a specified wallet and creates a contract instance accessible by name. Requires an Abigen command with the same contract name. The same contract can be deployed multiple times due to salt usage. ```rust Deploy(name="instance_name", contract="MyContract", wallet="a_wallet") ``` -------------------------------- ### Get predicate resources to spend and add to transaction request Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/predicates/methods.md.md Use getResourcesToSpend to retrieve the predicate's available coins for a transaction. This is called under the hood by transfer and createTransfer, but you may need it directly when using a predicate in an existing transaction request. The example funds the predicate, creates a ScriptTransactionRequest, fetches the predicate's resources, and adds them to the request. ```typescript import { bn, Provider, ScriptTransactionRequest, Wallet } from 'fuels'; import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../../env'; import { ReturnTruePredicate } from '../../../../typegend'; const provider = new Provider(LOCAL_NETWORK_URL); const baseAssetId = await provider.getBaseAssetId(); const funder = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider); const predicate = new ReturnTruePredicate({ provider, }); // Fund the predicate const fundPredicate = await funder.transfer( predicate.address, 100_000_000, baseAssetId ); await fundPredicate.waitForResult(); // Instantiate the transaction request. const transactionRequest = new ScriptTransactionRequest({ gasLimit: 2000, maxFee: bn(0), }); // Get the resources available to send from the predicate. const predicateCoins = await predicate.getResourcesToSpend([ { amount: 2000, assetId: baseAssetId }, ]); // Add the predicate input and resources. transactionRequest.addResources(predicateCoins); ``` -------------------------------- ### Project name prompt output Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/creating-a-fuel-dapp/index.md.md Example output shown when the CLI asks for the project name. Enter your desired name at the prompt. ```md ◇ What is the name of your project? │ my-fuel-project └ ``` -------------------------------- ### Launch multiple test wallets with default config Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-rs/docs/src/wallets/test-wallets.md Uses launch_custom_provider_and_get_wallets with WalletsConfig::default() to launch a local node and provide 10 test wallets, each with 1 coin of 1_000_000_000 amount. ```rust use fuels::prelude::*; // This helper launches a local node and provides 10 test wallets linked to it. // The initial balance defaults to 1 coin per wallet with an amount of 1_000_000_000. let wallets = launch_custom_provider_and_get_wallets(WalletsConfig::default(), None, None).await?; ``` -------------------------------- ### Storage Map Basic and Nested Examples in Sway Source: https://github.com/fuellabs/markdown/blob/main/docs/sway-by-example-lib/docs/src/storage-map.md Complete Sway contract demonstrating storage map usage. Includes basic operations (insert, read, update, remove) on a StorageMap<Identity, u64> and nested operations using a tuple key (Identity, Identity) for allowance. Requires a contract with storage annotations and uses msg_sender() to get the caller. ```sway contract; use std::{ hash::Hash, auth::msg_sender }; // StorageMap // - basic (insert, read, update, remove) // - nested abi MyContract { #[storage(read, write)] fn basic_examples(); #[storage(read, write)] fn nested_examples(); } storage { balance_of: StorageMap<Identity, u64> = StorageMap {}, allowance: StorageMap<(Identity, Identity), u64> = StorageMap {}, } const ADDR: b256 = 0x1000000000000000000000000000000000000000000000000000000000000000; impl MyContract for Contract { #[storage(read, write)] fn basic_examples() { let sender = msg_sender().unwrap(); // Insert storage.balance_of.insert(sender, 123); // Read let bal = storage.balance_of.get(sender).try_read().unwrap_or(0); // Update storage.balance_of.insert(sender, bal + 1); // Remove storage.balance_of.remove(sender); } #[storage(read, write)] fn nested_examples() { let sender = msg_sender().unwrap(); let spender = Identity::Address(Address::from(ADDR)); // Read let val = storage.allowance.get((sender, spender)).try_read().unwrap_or(0); // Insert / update storage.allowance.insert((sender, spender), val + 1); // Remove storage.allowance.remove((sender, spender)); } } ``` -------------------------------- ### fuels init options Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/fuels-cli/commands.md.md Lists all options for the `fuels init` command, such as --path, --workspace, --contracts, --scripts, --predicates, --output, --forc-path, --fuel-core-path, --auto-start-fuel-core, --fuel-core-port, and --help. ```console Options: --path <path> Path to project root (default: current directory) -w, --workspace <path> Relative dir path to Forc workspace -c, --contracts [paths...] Relative paths to Contracts -s, --scripts [paths...] Relative paths to Scripts -p, --predicates [paths...] Relative paths to Predicates -o, --output <path> Relative dir path for Typescript generation output --forc-path <path> Path to the `forc` binary --fuel-core-path <path> Path to the `fuel-core` binary --auto-start-fuel-core Auto-starts a `fuel-core` node during `dev` command --fuel-core-port <port> Port to use when starting a local `fuel-core` node for dev mode -h, --help Display help ``` -------------------------------- ### Initialize a Sway project in an existing folder Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-rs/docs/src/getting-started.md Use this command to initialize a Sway project within the current directory. ```shell forc init ``` -------------------------------- ### Example state_config.json coins array Source: https://github.com/fuellabs/markdown/blob/main/docs/node-operator/docs/src/fuel-ignition/local-node.md Example configuration for initial assets in a local chain. The owner must be a B256 address (0x...). The amount is a numerical value; here it represents 1 ETH. ```json "coins": [ { "tx_id": "0x0000000000000000000000000000000000000000000000000000000000000001", "output_index": 0, "tx_pointer_block_height": 0, "tx_pointer_tx_idx": 0, "owner": "0x488284d46414347c78221d3bad71dfebcff61ab2ae26d71129701d50796f714d", "amount": 1000000000, "asset_id": "0xf8f8b6283d7fa5b672b530cbb84fcccb4ff8dc40f8176ef4544ddb1f1952ad07" } ] ``` -------------------------------- ### Verify Cosmovisor installation Source: https://github.com/fuellabs/markdown/blob/main/docs/node-operator/docs/src/fuel-sequencer/mainnet-node.md Checks that Cosmovisor is installed and accessible via the PATH. ```sh cosmovisor version ``` -------------------------------- ### Function Example: only_owner Source: https://github.com/fuellabs/markdown/blob/main/docs/sway-standards/docs/src/src-2-inline-documentation.md An example of a documented function that checks if the sender is the owner and verifies a number equals 5. The documentation includes arguments, returns, reverts, storage accesses, and usage examples. ```APIDOC ## Function: only_owner ### Description Ensures that the sender is the owner and checks if the provided number is 5. ### Signature ```sway #[storage(read)] pub fn only_owner(self, number: u64) -> bool ``` ### Parameters - `self` - The contract instance. - `number` (u64) - A value that is checked to be 5. ### Returns - (bool) - Determines whether `number` is or is not 5. ### Reverts - When the sender is not the owner. ### Number of Storage Accesses - Reads: `1` ### Examples ```sway use ownable::Ownership; storage { owner: Ownership = Ownership::initialized(Identity::Address(Address::zero())), } fn foo() { storage.owner.only_owner(); // Do stuff here } ``` ``` -------------------------------- ### Set up multiple test wallets with launchTestNode Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/testing/setting-up-test-wallets.md.md Uses the `launchTestNode` utility with `walletsConfig` to create multiple wallets with specified assets, coins per asset, and amount per coin. ```typescript using launched = await launchTestNode({ walletsConfig: { count: 3, assets: [TestAssetId.A, TestAssetId.B], coinsPerAsset: 5, amountPerCoin: 100_000, }, }); const { wallets: [wallet1, wallet2, wallet3], } = launched; ``` -------------------------------- ### SuperABI Example Source: https://github.com/fuellabs/markdown/blob/main/docs/sway/docs/book/src/advanced/traits.md Shows how an ABI can have a superABI. The implementation of `MyAbi` for `Contract` must also implement `MySuperAbi`. Methods from the superABI become part of the contract interface and are externally available. ```sway contract; abi MySuperAbi { fn foo(); } abi MyAbi : MySuperAbi { fn bar(); } impl MySuperAbi for Contract { fn foo() {} } // The implementation of MyAbi for Contract must also implement MySuperAbi impl MyAbi for Contract { fn bar() {} } ``` -------------------------------- ### Usage syntax for pnpm, npm, and bun Source: https://github.com/fuellabs/markdown/blob/main/docs/fuels-ts/fuels-ts/apps/docs/src/guide/creating-a-fuel-dapp/options.md.md Shows the basic command syntax for creating a project with `npm create fuels` using pnpm, npm, and bun. The `[project-name]` and `[options]` placeholders are used. The version placeholder `{{fuels}}` is replaced with the actual version. ```sh pnpm create fuels@{{fuels}} [project-name] [options] ``` ```sh npm create fuels@{{fuels}} -- [project-name] [options] ``` ```sh bun create fuels@{{fuels}} [project-name] [options] ```