### Start Development Server Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/typescript-sdk.mdx Starts the development server for the frontend application using npm. ```sh npm start ``` -------------------------------- ### Install Fuel Toolchain with fuelup Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/installation/index.mdx Use this command to install the Fuel toolchain, including `forc`, `forc-client`, `forc-fmt`, `forc-lsp`, `forc-wallet`, and `fuel-core`. The binaries will be installed in `~/.fuelup/bin`. ```sh curl https://install.fuel.network | sh ``` -------------------------------- ### Start Frontend Development Server Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/frontend-quickstart/index.mdx After starting the local development node, run this command in a new terminal to start the frontend development server. This command can be run with either pnpm or npm. ```sh pnpm dev ``` ```sh npm run dev ``` -------------------------------- ### Run Guide Tests Locally Source: https://github.com/fuellabs/docs-hub/blob/master/docs/contributing/guides.mdx Execute guide tests locally using the provided pnpm command. This ensures guides function as expected before merging. ```sh pnpm test:guides ``` -------------------------------- ### Install Frontend Dependencies Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/counter-dapp/building-a-frontend.mdx Navigate into the newly created frontend directory and install its dependencies. This includes the `fuels` SDK, React-specific Fuel packages, and React Query for state management. ```bash cd frontend && npm install ``` -------------------------------- ### Example Deployment Output Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/counter-dapp/building-a-smart-contract.mdx This is an example of the output you will receive after successfully deploying your contract. Save the Contract ID for frontend integration. ```sh Contract counter-contract Deployed! Network: https://testnet.fuel.network Contract ID: 0x8342d413de2a678245d9ee39f020795800c7e6a4ac5ff7daae275f533dc05e08 Deployed in block 0x4ea52b6652836c499e44b7e42f7c22d1ed1f03cf90a1d94cd0113b9023dfa636 ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/fuellabs/docs-hub/blob/master/README.md Installs all necessary project dependencies using PNPM. Make sure PNPM is installed globally. ```sh pnpm install ``` -------------------------------- ### Install Rust Toolchain using rustup Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/installation/index.mdx Install the Rust programming language toolchain using the official `rustup` installer script. This is required for developing with the Rust SDK. ```sh curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` -------------------------------- ### Run Local Development Server Source: https://github.com/fuellabs/docs-hub/blob/master/README.md Starts the local development frontend. Access the application at http://localhost:3000 in your browser after execution. ```sh pnpm dev ``` -------------------------------- ### Navigate to Predicate Folder Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/prerequisites.mdx Move into the newly created predicate directory to start working on the code. ```sh cd predicate ``` -------------------------------- ### Install cargo-generate Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/debugging-with-scripts-rust.mdx Install the `cargo-generate` tool, which is used to create new projects from existing templates. ```bash cargo install cargo-generate --locked ``` -------------------------------- ### Install Nightly Toolchain Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/installation/index.mdx Install the 'nightly' Fuel toolchain to access unreleased features. This command downloads and installs the latest nightly build. ```sh fuelup toolchain install nightly ``` ```sh The Fuel toolchain is installed and up to date ``` -------------------------------- ### Install Fuels SDK and Wallet Packages Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/counter-dapp/building-a-frontend.mdx Install the core `fuels` package along with `@fuels/react`, `@fuels/connectors`, and `@tanstack/react-query` in your frontend project. These are essential for interacting with the Fuel network and wallets. ```bash npm install fuels @fuels/react @fuels/connectors @tanstack/react-query ``` -------------------------------- ### Token Setup Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/rust-sdk.mdx Initializes the default token and distributes some tokens to each wallet. This step ensures wallets have assets to interact with. ```rust let mut multi_call = MultiCallEncoder::new(network.get_provider_mut()); let default_token = multi_call.get_asset_id("default"); let wallet1_balance = multi_call.get_asset_balance(wallet1.address(), default_token); let wallet2_balance = multi_call.get_asset_balance(wallet2.address(), default_token); let wallet3_balance = multi_call.get_asset_balance(wallet3.address(), default_token); let _ = multi_call.call().await; let wallet1_balance = wallet1_balance.value().await; let wallet2_balance = wallet2_balance.value().await; let wallet3_balance = wallet3_balance.value().await; let amount = wallet1_balance / 2; let _ = Wallet::fund(&[wallet1.clone(), wallet2.clone(), wallet3.clone()], amount).await; ``` -------------------------------- ### Check fuelup Installation Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/installation/index.mdx Verify your `fuelup` installation by checking its version. This command outputs the currently installed `fuelup` version. ```sh fuelup --version ``` -------------------------------- ### Wallet Configuration Setup Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/rust-sdk.mdx Configures the wallets that will act as owners for the multisig predicate. This setup is part of the overall test environment preparation. ```rust let (network, wallet1, wallet2, wallet3) = setup_wallets_and_network(); ``` -------------------------------- ### Predicate main.sw file Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/checkpoint.mdx This is the content of the main.sw file for the multisig predicate example. Ensure your predicate matches this structure. ```sway predicate main() -> bool { true } ``` -------------------------------- ### Setup Wallets and Network Function Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/rust-sdk.mdx Provides a utility function to set up mock wallets and a network for testing purposes. This function is crucial for simulating the testing environment. ```rust fn setup_wallets_and_network() -> (Network, Wallet, Wallet, Wallet) { let mut network = MockNetwork::launch(); let mut wallets = Vec::new(); for _ in 0..3 { wallets.push(Wallet::new(network.get_private_key(0), network.get_provider_mut())); } (network, wallets[0].clone(), wallets[1].clone(), wallets[2].clone()) } ``` -------------------------------- ### Start Local Development Node Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/frontend-quickstart/index.mdx Run this command in your project directory to start a local development node for your Fuel project. This command can be run with either pnpm or npm. ```sh pnpm fuels:dev ``` ```sh npm run fuels:dev ``` -------------------------------- ### Use MDX Context Variables in Guides Source: https://github.com/fuellabs/docs-hub/blob/master/docs/contributing/style-guide.mdx Demonstrates how to use context variables passed into the MDX environment within a guide. Ensure the variable exists in the MDX context. ```mdx The faucet URL is {props.faucetUrl} ``` -------------------------------- ### Install Fuel Toolchain with `fuelup` Source: https://context7.com/fuellabs/docs-hub/llms.txt Installs the Fuel toolchain, including `forc`, `fuel-core`, and other essential components. Use `fuelup self update` and `fuelup update` to keep the toolchain up-to-date. ```sh # Install the Fuel toolchain curl https://install.fuel.network | sh # Verify installation fuelup --version # fuelup 0.21.0 # Keep toolchain up to date fuelup self update fuelup update fuelup default latest # Inspect active toolchain and component versions fuelup show # active toolchain # ----------------- # latest-x86_64-unknown-linux-gnu (default) # forc : 0.45.0 # fuel-core : 0.20.4 # Optionally install the nightly toolchain for unreleased features fuelup toolchain install nightly fuelup default nightly ``` -------------------------------- ### Network Setup for Transaction Broadcasting Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/rust-sdk.mdx Prepares the network to broadcast transactions, which is necessary for successfully unlocking tokens from the predicate. ```rust let provider = network.get_provider_mut(); ``` -------------------------------- ### Sway Smart Contract Example Source: https://context7.com/fuellabs/docs-hub/llms.txt A basic Sway contract demonstrating storage declaration, ABI interface, and function implementation for incrementing and reading a counter. ```sway // counter-contract/src/main.sw contract; storage { counter: u64 = 0, } abi Counter { #[storage(read, write)] fn increment(); #[storage(read)] fn count() -> u64; } impl Counter for Contract { #[storage(read)] fn count() -> u64 { storage.counter.read() } #[storage(read, write)] fn increment() { let incremented = storage.counter.read() + 1; storage.counter.write(incremented); } } ``` -------------------------------- ### Verify Latest Toolchain Installation Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/installation/index.mdx Run this command to check if the 'latest' Fuel toolchain is installed and active. It should show 'latest' as the default. ```sh fuelup show ``` ```sh installed toolchains -------------------- latest-x86_64-unknown-linux-gnu (default) active toolchain ----------------- latest-x86_64-unknown-linux-gnu (default) ... ``` -------------------------------- ### Sway Contract Marketplace Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/checkpoint.mdx This is the complete Sway contract for the marketplace example. Ensure your main.sw file matches this structure. ```sway contract marketplace; use std::storage::StorageMap; storage { items: StorageMap, } struct Item { id: u64, name: str[32], price: u64, } impl marketplace { // Initializes the storage with an empty StorageMap. abi init() { storage.items.init(); } // Adds a new item to the marketplace. abi add(id: u64, name: str[32], price: u64) { let item = Item { id, name, price, }; storage.items.insert(id, item); } // Retrieves an item from the marketplace by its ID. abi get(id: u64) -> Item { storage.items.get(id).unwrap_or(Item { id: 0, name: "", price: 0, }) } // Updates the price of an existing item. abi update_price(id: u64, new_price: u64) { let item = storage.items.get(id).unwrap(); let updated_item = Item { id: item.id, name: item.name, price: new_price, }; storage.items.insert(id, updated_item); } // Removes an item from the marketplace. abi remove(id: u64) { storage.items.remove(id); } } ``` -------------------------------- ### Check Node.js Version Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/prerequisites.mdx Verify your installed Node.js version to ensure compatibility. This is a standard command-line check. ```sh node -v ``` -------------------------------- ### Setup FuelProvider in main.tsx Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/counter-dapp/building-a-frontend.mdx Wrap your application with FuelProvider and QueryClientProvider to enable interaction with the Fuel network and manage state. Ensure these are imported at the top of your main entry file. ```tsx import { FuelProvider } from '@fuels/react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; import './index.css'; ``` ```tsx const queryClient = new QueryClient(); ReactDOM.createRoot(document.getElementById('root')!).render( , ); ``` -------------------------------- ### Start Local Fuel Development Node Source: https://context7.com/fuellabs/docs-hub/llms.txt Use the `fuels dev` command to start a local Fuel node, deploy contracts, and automatically redeploy and regenerate types on file changes. This command is run from your frontend directory. ```sh # In your frontend directory, start the local development node npx fuels dev # Expected output: # Starting a local Fuel node... # Deploying contracts... # 🎉 Contracts deployed! # Watching for changes... # When you change a .sw file: ``` -------------------------------- ### Successful Build Output Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/typescript-sdk.mdx This is an example of the expected output after a successful contract build and type generation process. It confirms that the build and type generation steps completed without errors. ```bash Building.. Building Sway programs using built-in 'forc' binary Generating types.. 🎉 Build completed successfully! ``` -------------------------------- ### Clone Fuel Docs Hub Repository Source: https://github.com/fuellabs/docs-hub/blob/master/README.md Use this command to clone the repository and its submodules. Ensure you have Git installed. ```sh git clone --recursive https://github.com/FuelLabs/docs-hub cd docs-hub ``` -------------------------------- ### Initialize FuelProvider and QueryClientProvider Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/typescript-sdk.mdx Wrap your application's root component with FuelProvider and QueryClientProvider to enable Fuel's React hooks for wallet functionalities. This setup is necessary for connecting to the Fuel network and managing wallet interactions. ```tsx import { FuelProvider, QueryClientProvider, } from '@fuels/react'; function App() { return ( {/* Your app components */} ); } ``` -------------------------------- ### Implement Counter Contract Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/counter-dapp/building-a-smart-contract.mdx This is the complete implementation of the counter contract. It includes functions for incrementing and getting the counter value. Ensure this code is placed in `src/main.sw`. ```sway contract; abi Counter { #[storage(read, write)] fn increment() -> bool; #[storage(read)] fn get() -> u64; } storage { counter: u64 = 0; } impl Counter for Contract { #[storage(read, write)] fn increment() -> bool { storage.counter.write(storage.counter.read() + 1); true } #[storage(read)] fn get() -> u64 { storage.counter.read() } } ``` -------------------------------- ### Define Contract Storage Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/counter-dapp/building-a-smart-contract.mdx Declare and initialize storage variables for the contract. This example defines a `counter` of type `u64` initialized to 0. ```sway storage { counter: u64 = 0; } ``` -------------------------------- ### Check Current Toolchain and Versions Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/installation/index.mdx Use `fuelup show` to display the currently active toolchain and the versions of installed Fuel tools like `forc` and `fuel-core`. This is useful for debugging and ensuring compatibility. ```sh fuelup show ``` ```sh active toolchain ----------------- beta-4-x86_64-unknown-linux-gnu (default) forc : 0.45.0 - forc-client - forc-deploy : 0.45.0 - forc-run : 0.45.0 - forc-doc : 0.45.0 - forc-explore : 0.28.1 - forc-fmt : 0.45.0 - forc-index : 0.20.7 - forc-lsp : 0.45.0 - forc-tx : 0.45.0 - forc-wallet : 0.3.0 fuel-core : 0.20.4 fuel-core-keygen : Error getting version string fuels versions --------------- forc : 0.45 forc-wallet : 0.45 ``` -------------------------------- ### Predicate Code Example (Fails with Logging) Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/debugging-with-scripts.mdx This Sway code represents a predicate. Attempting to build it with logging statements will result in an error because predicates must be pure. ```sway library; fn main() { // This is a predicate // You can use logging here use std::logging::log; log(LogData::Message("Hello, world!")); } ``` -------------------------------- ### Configure VS Code Extensions for Sway LSP Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/installation/codespace.mdx Specify VS Code extensions to be installed in the codespace, such as the Sway LSP plugin. ```json "customizations": { "vscode": { "extensions": [ "fuellabs.sway-vscode-plugin" ] } } ``` -------------------------------- ### Example Predicate Root Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/predicate-root.mdx This is the expected predicate root for the default templated predicate code. Any modification to the predicate code will result in a different predicate root. ```sh 0x68fec7a57e48f4ec6467d7e09c27272bd8ca72b312ea553a470b98731475ccf3 ``` -------------------------------- ### Navigate to Parent Directory Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/counter-dapp/building-a-frontend.mdx Before initializing the frontend project, navigate one directory up from your contract's folder. ```bash cd .. ``` -------------------------------- ### Initialize Contract Instance and Wallets Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/rust-sdk.mdx This helper function sets up a fresh contract instance and wallets for each test case, exporting deployed contracts, contract IDs, and generated wallets. ```rust async fn get_contract_instance() -> Contract { let mut wallets = ::fuels::test_helpers::setup_client().await.unwrap().get_wallets(1, None).await.unwrap(); let wallet = wallets.pop().unwrap(); let id = Contract::load_from( "asset-transfer", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", ) .await .unwrap(); let instance = Contract::new(id, wallet.clone()); instance } ``` -------------------------------- ### Navigate to Project Folder Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/prerequisites.mdx Change your current directory to the newly created project folder. ```sh cd multisig-predicate ``` -------------------------------- ### Set Up Local Wallet with `forc-wallet` Source: https://context7.com/fuellabs/docs-hub/llms.txt Initializes a new encrypted wallet vault using `forc wallet new`. Remember to store the generated mnemonic phrase securely. ```sh # Create a new encrypted wallet vault (saves mnemonic — store it safely) forc wallet new ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/prerequisites.mdx Change the current directory to the newly created Sway project folder. ```sh cd sway-store ``` -------------------------------- ### Initialize a New Fuel Wallet Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/installation/index.mdx Create a new wallet using `forc-wallet`. Remember to securely save the outputted mnemonic phrase and password. This command initializes the wallet. ```console forc wallet new ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/debugging-with-scripts.mdx Change the current directory to the parent directory of the MultiSig project to create a new, separate project. ```bash cd ../.. ``` -------------------------------- ### Update Fuelup Toolchain Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/counter-dapp/building-a-smart-contract.mdx Ensure you have the latest Fuelup toolchain installed by running these commands. ```sh fuelup self update fuelup update fuelup default latest ``` -------------------------------- ### Build the Counter Contract Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/counter-dapp/building-a-smart-contract.mdx Navigate to your contract folder and run `forc build` to compile your smart contract. This command generates the necessary build artifacts in the `out/debug` directory. ```sh cd counter-contract ``` ```sh forc build ``` -------------------------------- ### Retrieve Transaction Amount Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/contract-functions.mdx Gets the quantity of coins transferred by the buyer in the current transaction using msg_amount. ```sway let amount = msg_amount(); ``` -------------------------------- ### Initialize React Project with Vite Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/counter-dapp/building-a-frontend.mdx Initialize a new React project with TypeScript using Vite. This command scaffolds the basic project structure. ```bash npm create vite@latest frontend -- --template react-ts ``` -------------------------------- ### Create AllItems.tsx File Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/typescript-sdk.mdx Use this command to create the AllItems.tsx file in the specified directory. ```bash touch AllItems.tsx ``` -------------------------------- ### Create Project Folder Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/prerequisites.mdx Use this command to create a new directory for your predicate project. ```sh mkdir multisig-predicate ``` -------------------------------- ### Create a New Sway Contract with `forc new` Source: https://context7.com/fuellabs/docs-hub/llms.txt Scaffolds a new Sway project with a `Forc.toml` manifest and a `src/main.sw` entry point. `forc` is the build system and package manager for Sway. ```sh # Create a new project directory and scaffold a contract mkdir fuel-project && cd fuel-project forc new counter-contract # Output: # To compile, use `forc build`, and to run tests use `forc test` # Read the Docs: # - Sway Book: https://docs.fuel.network/docs/sway # - Forc Book: https://docs.fuel.network/docs/forc # Resulting layout: # counter-contract/ # ⌕⌕ Forc.toml # ⌕⌕ src/ # ⌕⌕ main.sw ``` -------------------------------- ### Create New Predicate Script Project Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/debugging-with-scripts.mdx Initialize a new Fuel project specifically for predicate-script logging experiments. ```bash forc new --predicate predicate-script-logging ``` -------------------------------- ### Contract Skeleton in Sway Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/contract-functions.mdx Defines the basic structure and ABI for a Sway contract, serving as a starting point for implementing contract functions. ```sway use std::storage::StorageMap; abi SwayStore { fn list_item(price: u64, metadata: str[256]); fn get_item(id: u64) -> Item; fn buy_item(id: u64); } struct Item { id: u64, price: u64, metadata: str[256], total_bought: u64, owner: Identity, } storage { item_counter: u64, item_map: StorageMap, } ``` -------------------------------- ### Get Item Details in Sway Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/contract-functions.mdx Defines a read-only function to retrieve the details of an item using its ID. This function returns an `Item` struct. ```sway fn get_item(item_id: u64) -> Item { // Returns the Item struct for the given item_id storage.items.get(item_id) } ``` -------------------------------- ### Retrieving Message Sender in Sway Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/contract-functions.mdx Shows how to get the identity of the account calling the current function using `msg_sender()` and handling potential errors. ```sway let sender = msg_sender().unwrap(); ``` -------------------------------- ### Build a Counter Contract Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/contract-quickstart/index.mdx Compile your Sway contract. This command should be run from the contract's root directory. ```sway contract; abi ForcTestContract { #[storage(read, write)] fn increment(); #[storage(read)] fn get() -> u64; } storage { count: u64 = 0; } impl ForcTestContract for Contract { #[storage(read, write)] fn increment() { storage.count.increment(); } #[storage(read)] fn get() -> u64 { storage.count } } ``` -------------------------------- ### Update fuelup Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/installation/index.mdx Update `fuelup` to the latest version to access new features and performance improvements. This command fetches and installs the latest `fuelup` binary. ```sh fuelup self update ``` -------------------------------- ### Create and List Fuel Wallet Accounts Source: https://context7.com/fuellabs/docs-hub/llms.txt Use `forc wallet account new` to create a new account derived from your wallet and `forc wallet accounts` to list all available accounts. ```bash forc wallet account new # Address: fuel1efz7lf36w9da9jekqzyuzqsfrqrlzwtt3j3clvemm6eru8fe9nvqj5kar8 # List all accounts forc wallet accounts ``` -------------------------------- ### TestAction Component Props Source: https://github.com/fuellabs/docs-hub/blob/master/docs/contributing/guides.mdx Defines the properties for the TestAction component used in markdown guides. The 'id' must be unique, and 'action' specifies the test to run. ```tsx interface TestActionProps { id: string action: string } ``` -------------------------------- ### Create New Sway Project Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/prerequisites.mdx Initialize a new Sway project using the 'fuels' package manager. This command scaffolds a new project with a default structure. ```sh pnpm create fuels sway-store ``` -------------------------------- ### Create ListItem.tsx File Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/typescript-sdk.mdx Use this command to create the ListItem.tsx file in your project. ```bash touch ListItem.tsx ``` -------------------------------- ### Get Total Item Count in Sway Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/contract-functions.mdx A simple getter function that returns the current value of the `item_counter` variable stored in the contract's storage. ```sway fn get_count() -> u64 { // Returns the item_counter variable storage.item_counter } ``` -------------------------------- ### Build a Counter Contract Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/contract-quickstart/index.mdx Compile your Sway contract. This command should be run from the contract's root directory. ```sh forc build ``` -------------------------------- ### Create New Sway Predicate Project Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/prerequisites.mdx Initialize a new Sway project specifically for a predicate. The `--predicate` flag is crucial for this. ```sh forc new --predicate predicate ``` -------------------------------- ### Get Accumulated Fee Utility Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/rust-sdk.mdx A placeholder function to represent the calculation of accumulated transaction fees. In a real scenario, this would involve more complex fee estimation. ```rust fn get_accumulated_fee() -> u64 { 100000 } ``` -------------------------------- ### Navigate to Contract Directory Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/prerequisites.mdx Move into the specific directory for the contract program within the Sway project. ```sh cd sway-programs/contract ``` -------------------------------- ### Inserting Item into StorageMap in Sway Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/contract-functions.mdx Demonstrates how to add a new item to a `StorageMap` in Sway using the `insert` method. ```sway storage.item_map.insert(item_id, new_item); ``` -------------------------------- ### Fetch Items using useEffect in AllItems Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/typescript-sdk.mdx This useEffect hook fetches item data. It uses the `get` method for a dry-run, simulating a transaction without requiring user signature. ```tsx useEffect(() => { const fetchItems = async () => { setIsLoading(true); try { const count = await contract.functions.get_item_count().get(); setItemCount(count.value ?? 0); const fetchedItems: any[] = []; if (count.value && count.value > 0) { for (let i = 0; i < count.value; i++) { const item = await contract.functions.get_item(i).get(); fetchedItems.push(item.value); } setItems(fetchedItems); } } catch (error) { console.error('Error fetching items:', error); } finally { setIsLoading(false); } }; fetchItems(); }, [contract]); ``` -------------------------------- ### Create ItemCard.tsx File Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/typescript-sdk.mdx Use this command to create the ItemCard.tsx file in the components directory. ```bash touch ItemCard.tsx ``` -------------------------------- ### Rust Test Harness with Logging Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/debugging-with-scripts-rust.mdx This Rust code snippet represents the test harness for a Sway predicate. It includes setup for logging and demonstrates how to decode logs to extract specific data, such as a secret number. ```rust use fuels::prelude::*; fn harness(wallets: Vec>) -> Result<()> { let services = State::new(wallets); let provider = services.provider.clone(); // Build and deploy the contract let mut wallet = services.new_wallet_unlocked().await; let identity = Identity::Address(wallet.address()); let contract_instance = Contract::new( Contract::load_from( "../sway-store/out/debug/sway-store-contract.bin", LoadConfiguration { bytecode_offset: 0, gas_price: 0, gas_limit: 0, contract_id: None, }, )? .abi_with_types(sway_store_contract_mod::SwayStoreContractAbi::id()), LoadConfiguration { bytecode_offset: 0, gas_price: 0, gas_limit: 0, contract_id: None, }, provider.clone(), ) .await?; let contract = contract_instance.contract_id(); // Call the predicate let script_instance = Script::new( Script::load_from( "../sway-store/out/debug/sway-store.debug.bin", LoadConfiguration { bytecode_offset: 0, gas_price: 0, gas_limit: 0, contract_id: None, }, )? .abi_with_types(sway_store_mod::SwayStoreAbi::id()), LoadConfiguration { bytecode_offset: 0, gas_price: 0, gas_limit: 0, contract_id: None, }, provider.clone(), ) .await?; let script_call_result = script_instance .with_variable_outputs(1) .call( "run", Args { contract: contract, input: identity.clone(), }, ) .await?; // Decode logs let logs = script_call_result.decode_logs(); // Assert that the secret number was logged assert_eq!(logs.len(), 1); assert_eq!(logs[0].amount, 10); Ok(()) } ``` -------------------------------- ### View Project Structure Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/prerequisites.mdx Display the directory tree of the generated predicate project to understand its structure. ```sh tree predicate ``` -------------------------------- ### Define and Configure Multisig Predicate Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/configurables.mdx This Sway code defines the signers and the required number of signatures for a multisig predicate. These values can be modified at compile time using configurables, allowing for flexible setup of multisignature wallets. ```sway configurable { // The signers responsible for protecting the funds in the predicate. signers: [Address; 2], // The number of signatures required to authorize a transaction. num_required: u8, } fn main() { // Predicate logic here } ``` -------------------------------- ### Add Increment Test Function Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/counter-dapp/building-a-smart-contract.mdx Add the `test_increment` function to your `tests/harness.rs` file to verify that the counter contract's increment functionality works as expected. This test interacts with the contract's `increment` and `get` methods. ```rust mod tests { use super::*; #[test] fn can_get_contract_id() { let result = Counter::new(ContractId::new(0u32.into())).unwrap(); assert!(result.id().is_some()); } #[test] fn test_increment() { let contract_instance = Counter::new(ContractId::new(0u32.into())).unwrap(); let initial_value = contract_instance.get().unwrap(); assert_eq!(initial_value, 0); contract_instance.increment().unwrap(); let incremented_value = contract_instance.get().unwrap(); assert_eq!(incremented_value, 1); } } ``` -------------------------------- ### Creating a New Item Struct in Sway Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/contract-functions.mdx Illustrates how to instantiate a new `Item` struct in Sway, using values from storage and function parameters. ```sway let new_item = Item { id: item_id, price, metadata, total_bought: 0, owner: sender, }; ``` -------------------------------- ### View Forc Project Structure Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/counter-dapp/building-a-smart-contract.mdx Inspect the default file structure generated by `forc new` for a contract project. ```sh tree counter-contract ``` -------------------------------- ### Define Contract ABI in Sway Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/contract-abi.mdx Write this ABI into your `main.sw` file to define the contract's interface. This includes function signatures, storage access, and payable status. ```sway abi MyContract { #[storage(read, write)] fn set_balance(new_balance: u64); #[storage(read)] fn get_balance() -> u64; #[payable] fn buy_item(item_id: u64, quantity: u64) -> bool; } ``` -------------------------------- ### Build and Deploy Sway Contract with `forc` Source: https://context7.com/fuellabs/docs-hub/llms.txt Compiles a Sway contract using `forc build` and deploys it to the Fuel Testnet using `forc deploy --testnet`. Deployment requires a funded `forc-wallet` account. ```sh # Build the contract cd counter-contract forc build # Compiled library "core". # Compiled library "std". # Compiled contract "counter-contract". # Bytecode size: 84 bytes. # out/debug/ now contains: # counter-contract-abi.json # counter-contract-storage_slots.json # counter-contract.bin # Deploy to the Fuel Testnet (requires funded forc-wallet account) forc deploy --testnet # Contract counter-contract Deployed! # Network: https://testnet.fuel.network # Contract ID: 0x8342d413de2a678245d9ee39f020795800c7e6a4ac5ff7daae275f533dc05e08 # Deployed in block 0x4ea52b6652836c499e44b7e42f7c22d1ed1f03cf90a1d94cd0113b9023dfa636 ``` -------------------------------- ### Complete Harness File Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/rust-sdk.mdx This represents the complete content of the `harness.rs` file after all configurations and tests have been added. ```rust // all ``` -------------------------------- ### Development Server Output Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/typescript-sdk.mdx Indicates a successful compilation and provides URLs for accessing the application locally and on the network. ```sh Compiled successfully! You can now view frontend in the browser. Local: http://localhost:3000 On Your Network: http://192.168.4.48:3000 Note that the development build is not optimized. To create a production build, use npm run build. ``` -------------------------------- ### Deploy a Contract to Testnet Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/contract-quickstart/index.mdx Deploy your compiled contract to the Fuel testnet. Ensure your wallet is set up and has test funds. ```sh forc deploy --testnet ``` -------------------------------- ### Full Sway Contract Implementation Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/contract-functions.mdx The complete implementation of the `SwayStore` contract, incorporating all previously defined functions for managing items, ownership, and withdrawals. ```sway // Contract state contract; use std::storage::StorageMap; use std::asset::Transfer; use std::identity::Identity; use std::auth::msg_sender; struct Item { id: u64, name: str[32], price: u64, } storage { items: StorageMap, item_counter: u64, owner: Option, } impl Contract { // Get an item fn get_item(item_id: u64) -> Item { // Returns the Item struct for the given item_id storage.items.get(item_id) } // Initialize the owner fn initialize_owner(owner: Identity) { // Ensure that the owner is not already set // This function can only be called once assert(storage.owner.is_none(), "Owner already initialized."); // Set the owner storage.owner = Some(owner); } // Withdraw funds fn withdraw_funds(amount: u64) { // Ensure owner is initialized let owner = storage.owner.get().unwrap(); // Ensure the caller is the owner assert(owner == Identity::Address(msg_sender().unwrap()), "Not the owner."); // Ensure there are enough funds to withdraw assert(amount <= this_balance(), "Insufficient funds."); // Transfer funds to the owner let result = Transfer::transfer(AssetId::Base, owner, amount, ""); assert(result.is_ok(), "Transfer failed."); } // Get the total items fn get_count() -> u64 { // Returns the item_counter variable storage.item_counter } } ``` -------------------------------- ### Inspect Build Artifacts Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/counter-dapp/building-a-smart-contract.mdx After building, you can inspect the contract's build artifacts, including the ABI JSON and bytecode, by running `tree .` in your contract folder. ```sh tree . ``` -------------------------------- ### Buy Item Function Signature Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/contract-functions.mdx Defines the entry point for the buy_item function, accepting the item ID and the buyer's identity. ```sway pub fn buy_item(item_id: u64, buyer: Identity) { // ... implementation ... ``` -------------------------------- ### Build Sway Contract Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/checkpoint.mdx Compile your Sway contract using the `forc build` command. This generates necessary artifacts like `abi.json` and `contract.bin`. ```sh forc build ``` -------------------------------- ### Build and Sign Transaction Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-predicates/rust-sdk.mdx Construct a transaction to extract funds from the predicate, specifying outputs and native assets. Sign the transaction with the correct wallet addresses to satisfy the predicate's conditions. ```rust let amount_to_withdraw = BASE_ASSET_AMOUNT / 2; let mut msg_to_sign = vec![]; let mut outputs = vec![]; outputs.push(Output::change(wallet.address(), amount_to_withdraw, BASE_ASSET_ID)); let response = wallet.transfer( predicate_root.clone(), amount_to_withdraw, BASE_ASSET_ID, TxPolicies::default() ); let utxos = provider.get_predicate_utxos( &predicate_root, BASE_ASSET_ID ).await?; let utxo = &utxos[0]; let message = Message::new() .add_output(Output::change(wallet.address(), amount_to_withdraw, BASE_ASSET_ID)) .add_input(Input::predicate(utxo.clone())); let msg_bytes = message.clone().to_bytes(); for i in 0..REQUIRED_SIGNATURES { let signature = wallet.sign_message(&msg_bytes)?; msg_to_sign.push(signature); let mut transaction = message.clone().build(); transaction.inputs[0].witnesses = vec![msg_to_sign[i].clone()]; let result = provider.transfer_with_predicate( wallet.address(), transaction, TxPolicies::default() ); println!("Transaction result: {:?}", result); } ``` -------------------------------- ### Import a Single Library in Sway Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/contract-imports.mdx Use the 'use' keyword followed by the namespace qualifier '::' to import a single library or type. This is useful for bringing specific functionalities into your contract's scope. ```sway use std::storage::Storage; ``` -------------------------------- ### Build Contract and Generate Types Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/counter-dapp/building-a-frontend.mdx After initializing the configuration, run the `fuels build` command. This command builds your Sway contract and generates TypeScript definitions based on its ABI, making it easier to interact with from your frontend. ```bash npx fuels build ``` -------------------------------- ### Generate Fuels Configuration and Contract Types Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/counter-dapp/building-a-frontend.mdx Initialize the `fuels.config.ts` file and generate contract types. Specify the path to your contract's directory and the desired output directory for the generated types. ```bash npx fuels init --contracts ../counter-contract/ --output ./src/sway-api ``` -------------------------------- ### Complete harness.rs Test File Source: https://github.com/fuellabs/docs-hub/blob/master/docs/guides/docs/intro-to-sway/rust-sdk.mdx The complete content of the `harness.rs` test file, including all previously shown tests for listing, buying, and withdrawing fees. ```rust use fuels::prelude::*; // Import contract macros use sway_store::contract::YourContract as Contract; // Import contract types use sway_store::contract::{ types::storage::ListItemsToSellToContract, types::storage::BuyItemToContract, }; // Helper function to get wallets async fn get_wallets() -> (WalletUnlocked, WalletUnlocked) { let mut wallets = launch_custom_provider_and_get_wallets( WalletsConfig::new( Some(2), Some(1), Some(1_000_000_000), ), None, None, ) .await; (wallets.pop().unwrap(), wallets.pop().unwrap()) } // Test function to list and buy an item pub fn rs_test_list_and_buy_item() { // Setup wallets let (mut wallet1, wallet2) = get_wallets().await; // Deploy contract let contract_instance = Contract::new( PathBuf::from("../sway-programs/contract"), Configurable::default(), &mut wallet1, ) .await?; // List item let list_item_params = ListItemsToSellToContract { value: 10 }; let _ = contract_instance .methods() .list_item(list_item_params) .append_variable_outputs(true) .call() .await?; // Buy item let buy_item_params = BuyItemToContract { index: 0 }; let _ = contract_instance .methods() .buy_item(buy_item_params) .with_variable_outputs(true) .call(&mut wallet2) .await?; } // Test function to withdraw owner fees pub fn rs_test_withdraw_funds() { // Setup wallets let (mut wallet1, _wallet2) = get_wallets().await; // Deploy contract let contract_instance = Contract::new( PathBuf::from("../sway-programs/contract"), Configurable::default(), &mut wallet1, ) .await?; // Withdraw funds let _ = contract_instance .methods() .withdraw_owner_fees() .append_variable_outputs(true) .call() .await?; } ```