### Install Dependencies and Start Dev Server Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/README-without-sc.md Installs project dependencies and starts the development server. Ensure Node.js 18+ is installed. ```bash npm install npm run dev ``` -------------------------------- ### Install and Start Scaffold-XRP Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/QUICKSTART.md Commands to clone the repository, install dependencies, and launch the development server. ```bash # Clone the repository git clone https://github.com/XRPL-Commons/scaffold-xrp.git cd scaffold-xrp # Install dependencies pnpm install # Start the development server pnpm dev ``` -------------------------------- ### Run Development Server Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/CONTRIBUTING.md Use this command to start the development server. Ensure dependencies are installed first. ```bash pnpm dev ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/README.md Example content for the .env.local file to set the default network. ```bash # Optional: Configure default network NEXT_PUBLIC_DEFAULT_NETWORK=alphanet ``` -------------------------------- ### Implement Post-Install Script Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/docs/module-template/README.md Optional script executed after file copying to perform custom setup tasks using environment variables provided by the scaffold. ```javascript // install.js const fs = require('fs'); const path = require('path'); // Environment variables available: // - SCAFFOLD_XRP_PROJECT_DIR: Root project directory // - SCAFFOLD_XRP_FRAMEWORK: 'nextjs' or 'nuxt' // - SCAFFOLD_XRP_WEB_DIR: Path to apps/web const projectDir = process.env.SCAFFOLD_XRP_PROJECT_DIR; const framework = process.env.SCAFFOLD_XRP_FRAMEWORK; console.log(`Running post-install for ${framework} project...`); // Example: Update tailwind.config.js to include module paths // Example: Add environment variables to .env.example ``` -------------------------------- ### Create XRPL dApp with Different Package Managers Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/packages/create-xrp/README.md Examples of initializing an XRPL dApp project using npm, pnpm, or yarn. ```bash # npm npx create-xrp my-app ``` ```bash # pnpm pnpm create xrp my-app ``` ```bash # yarn yarn create xrp my-app ``` -------------------------------- ### Troubleshoot Build Errors Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/QUICKSTART.md Commands to clean the project environment and perform a fresh dependency installation. ```bash # Clean and reinstall pnpm clean rm -rf node_modules pnpm install ``` -------------------------------- ### Install Rust Toolchain Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/README.md Commands to install Rust and the WASM target required for smart contract development. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh rustup target add wasm32-unknown-unknown ``` -------------------------------- ### Scaffold-XRP Optional Post-Install Script (install.js) Source: https://context7.com/xrpl-commons/scaffold-xrp/llms.txt An optional Node.js script that runs after a module is installed. It can access environment variables for project-specific setup. ```javascript // install.js - Optional post-install script const fs = require('fs'); const path = require('path'); // Available environment variables: // SCAFFOLD_XRP_PROJECT_DIR - Root project directory // SCAFFOLD_XRP_FRAMEWORK - 'nextjs' or 'nuxt' // SCAFFOLD_XRP_WEB_DIR - Path to apps/web const projectDir = process.env.SCAFFOLD_XRP_PROJECT_DIR; const framework = process.env.SCAFFOLD_XRP_FRAMEWORK; console.log(`Running post-install for ${framework} project...`); // Custom setup logic here ``` -------------------------------- ### Start a Local XRPL Node Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/packages/bedrock/README.md Initiates a local node for testing and development of XRPL smart contracts. ```bash bedrock basalt start ``` -------------------------------- ### Bedrock CLI: Build and Deploy XRPL Contracts Source: https://context7.com/xrpl-commons/scaffold-xrp/llms.txt Commands for installing Rust, setting up the WASM target, building smart contracts, vaults, and escrows, and deploying them using the Bedrock CLI. ```bash # Install Rust and WASM target curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh rustup target add wasm32-unknown-unknown # Build smart contracts bedrock build --type contract # Build contract WASM bedrock build --type vault # Build vault WASM bedrock build --type escrow # Build escrow WASM # Start local XRPL node bedrock basalt start # Deploy contracts bedrock deploy --network local bedrock slate deploy --network local # Deploy vault with specific configuration bedrock vault deploy --asset XRP --wallet --network local ``` -------------------------------- ### Install Module via CLI Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/docs/module-template/README.md Command to install a module directly from a public Git repository URL. ```bash npx create-xrp add https://github.com/your-username/your-module ``` -------------------------------- ### Build the Counter Contract Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/QUICKSTART.md Steps to install the Rust toolchain and compile the sample counter contract to WASM. ```bash # Install Rust (if not already installed) curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh rustup target add wasm32-unknown-unknown # Build the counter contract cd packages/bedrock cargo build --target wasm32-unknown-unknown --release ``` -------------------------------- ### Import Module Components and Hooks Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/docs/module-template/README.md Example usage of installed module assets within Next.js and Nuxt applications. ```typescript // Next.js import { ExampleComponent } from '@/modules/example-module/components/ExampleComponent'; import { useExample } from '@/modules/example-module/hooks/useExample'; // Nuxt import ExampleComponent from '~/modules/example-module/components/ExampleComponent.vue'; import { useExample } from '~/modules/example-module/composables/useExample'; ``` -------------------------------- ### Create a New XRPL dApp Project Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/packages/create-xrp/README.md Use this command to initialize a new XRPL dApp project named 'my-app'. It prompts for project details and sets up the Next.js and smart contract scaffold. ```bash npx create-xrp my-app ``` -------------------------------- ### Build Project Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/CONTRIBUTING.md Execute this command to build the project for deployment. This command compiles assets and code. ```bash pnpm build ``` -------------------------------- ### Scaffold a New Project Source: https://context7.com/xrpl-commons/scaffold-xrp/llms.txt Use the create-xrp CLI to initialize a new project with specific framework and package manager configurations. ```bash # Create a new project with interactive prompts npx create-xrp my-app # Create with specific options npx create-xrp my-app --framework nextjs --pm pnpm --primitives contract,vault,escrow # Using different package managers pnpm create xrp my-app yarn create xrp my-app # After creation, start the development server cd my-app pnpm dev ``` -------------------------------- ### Initialize Wallet Manager Source: https://context7.com/xrpl-commons/scaffold-xrp/llms.txt Use the useWalletManager hook to initialize the connection system and support various wallet adapters. ```javascript import { useWalletManager } from "../hooks/useWalletManager"; import { useWallet } from "./providers/WalletProvider"; function App() { // Initialize wallet manager (call once at app root) const { walletManager } = useWalletManager(); // Access wallet state const { isConnected, accountInfo } = useWallet(); // The wallet manager supports these adapters: // - XamanAdapter (requires NEXT_PUBLIC_XAMAN_API_KEY) // - WalletConnectAdapter (requires NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID) // - CrossmarkAdapter (browser extension) // - GemWalletAdapter (browser extension) // - OtsuAdapter (browser extension) return (
{isConnected && (

Address: {accountInfo.address}

Network: {accountInfo.network}

Wallet: {accountInfo.walletName}

)}
); } ``` -------------------------------- ### Implement WalletProvider and useWallet Source: https://context7.com/xrpl-commons/scaffold-xrp/llms.txt Wrap the application with WalletProvider and use the useWallet hook to access global wallet state and helper methods. ```javascript // app/layout.js or pages/_app.js import { WalletProvider } from "./components/providers/WalletProvider"; export default function RootLayout({ children }) { return ( {children} ); } // In any component import { useWallet } from "./components/providers/WalletProvider"; function MyComponent() { const { walletManager, // WalletManager instance from xrpl-connect isConnected, // Boolean connection status accountInfo, // { address, network, walletName } events, // Array of { timestamp, name, data } statusMessage, // { message, type } for notifications addEvent, // (name, data) => void showStatus, // (message, type) => void - auto-dismisses after 5s clearEvents, // () => void } = useWallet(); // Example: Show a status message showStatus("Transaction submitted!", "success"); // Example: Log an event addEvent("Custom Action", { txHash: "ABC123" }); return
Connected: {isConnected ? accountInfo.address : "Not connected"}
; } ``` -------------------------------- ### Deploy Escrow with Scaffold-XRP CLI Source: https://context7.com/xrpl-commons/scaffold-xrp/llms.txt Use the bedrock CLI to deploy an escrow. Ensure you replace placeholders with your specific details. ```bash bedrock escrow deploy --destination --amount --wallet --network local ``` -------------------------------- ### Build the XRPL Smart Contract Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/packages/bedrock/README.md Use this command to compile and build your XRPL smart contract in release mode. ```bash bedrock flint build --release ``` -------------------------------- ### Build and Publish create-xrp Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/packages/create-xrp/README.md Commands to build the create-xrp CLI for publishing and then publish it to npm. Ensure you have the necessary permissions and have updated the version. ```bash # Build pnpm build ``` ```bash # Publish to npm npm publish ``` -------------------------------- ### Build and Link create-xrp Locally Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/packages/create-xrp/README.md Commands to build the create-xrp CLI and link it globally for local testing. This is useful during development to test changes before publishing. ```bash # Build the CLI pnpm build ``` ```bash # Link it globally npm link ``` ```bash # Test it create-xrp test-project ``` -------------------------------- ### Deploy XRPL Smart Contract to Local Network Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/packages/bedrock/README.md Deploys your XRPL smart contract to the local network environment. ```bash bedrock slate deploy --network local ``` -------------------------------- ### Development Commands Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/README.md Commonly used CLI commands for managing the project. ```bash pnpm dev # Start development server pnpm build # Build all packages pnpm lint # Lint all packages pnpm format # Format code with Prettier pnpm clean # Clean build artifacts ``` -------------------------------- ### Manage Project Modules Source: https://context7.com/xrpl-commons/scaffold-xrp/llms.txt Commands for adding, listing, and removing community modules within a Scaffold-XRP project. ```bash # Add a module interactively (shows registry modules) npx create-xrp add # Add a specific module by name npx create-xrp add # Add a module from a custom git URL npx create-xrp add https://github.com/user/custom-module # List installed and available modules npx create-xrp list npx create-xrp ls --remote # Remove an installed module npx create-xrp remove npx create-xrp rm ``` -------------------------------- ### Build Counter Contract Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/README.md Compile the Rust smart contract to WASM. ```bash cd packages/bedrock cargo build --target wasm32-unknown-unknown --release ``` -------------------------------- ### Configure module.json Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/docs/module-template/README.md The required metadata file defining module identity, compatibility, file mappings, and dependencies. ```json { "name": "my-module", "version": "1.0.0", "description": "Description of what your module does", "author": "Your Name", "compatibility": { "scaffold-xrp": ">=0.1.0", "frameworks": ["nextjs", "nuxt"] }, "files": { "components": ["components/"], "hooks": ["hooks/"], "composables": ["composables/"], "lib": ["lib/"], "contracts": ["contracts/"], "pages": ["pages/"], "data": ["data/"] }, "dependencies": { "npm": ["some-npm-package"], "modules": ["other-scaffold-module"] } } ``` -------------------------------- ### Project Directory Structure Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/README.md Overview of the monorepo file organization. ```text scaffold-xrp/ ├── apps/ │ └── web/ # Next.js application │ ├── app/ # Next.js App Router │ ├── components/ # React components │ └── lib/ # Utilities and configurations ├── packages/ │ └── bedrock/ # Smart contracts (Rust) │ ├── src/ │ │ └── lib.rs # Counter contract example │ └── Cargo.toml ├── package.json ├── pnpm-workspace.yaml └── turbo.json ``` -------------------------------- ### Lint and Format Code Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/CONTRIBUTING.md Run these commands to ensure code quality and consistent formatting across the project. Prettier is used for formatting. ```bash pnpm lint ``` ```bash pnpm format ``` -------------------------------- ### Access XRPL Network Configuration Source: https://context7.com/xrpl-commons/scaffold-xrp/llms.txt Import and use the predefined network constants to access WebSocket URLs, faucet endpoints, and explorer links. ```javascript import { NETWORKS, DEFAULT_NETWORK } from "../lib/networks"; // Available networks console.log(NETWORKS.ALPHANET); // { // id: "alphanet", // name: "AlphaNet", // networkId: 21465, // wss: "wss://alphanet.nerdnest.xyz", // faucet: "https://alphanet.faucet.nerdnest.xyz/accounts", // explorer: "https://alphanet.xrpl.org" // } console.log(NETWORKS.TESTNET); // { // id: "testnet", // name: "Testnet", // networkId: 1, // wss: "wss://s.altnet.rippletest.net:51233", // faucet: "https://faucet.altnet.rippletest.net/accounts", // explorer: "https://testnet.xrpl.org" // } console.log(NETWORKS.DEVNET); // { // id: "devnet", // name: "Devnet", // networkId: 2, // wss: "wss://s.devnet.rippletest.net:51233", // faucet: "https://faucet.devnet.rippletest.net/accounts", // explorer: "https://devnet.xrpl.org" // } // Default is AlphaNet const currentNetwork = DEFAULT_NETWORK; ``` -------------------------------- ### Importing Modules in Next.js and Nuxt Source: https://context7.com/xrpl-commons/scaffold-xrp/llms.txt Demonstrates how to import components and hooks from custom modules in both Next.js and Nuxt.js applications. ```typescript // Next.js import { ExampleComponent } from '@/modules/my-module/components/ExampleComponent'; import { useExample } from '@/modules/my-module/hooks/useExample'; // Nuxt import ExampleComponent from '~/modules/my-module/components/ExampleComponent.vue'; import { useExample } from '~/modules/my-module/composables/useExample'; ``` -------------------------------- ### Create, Finish, and Cancel XRPL Escrows Source: https://context7.com/xrpl-commons/scaffold-xrp/llms.txt Use these functions to manage time-locked escrows on the XRPL. Ensure the wallet provider is set up and provides the necessary `walletManager` and `addEvent` functions. ```javascript import { useWallet } from "./providers/WalletProvider"; const RIPPLE_EPOCH_OFFSET = 946684800; // Seconds between Unix epoch and Ripple epoch function EscrowExample() { const { walletManager, showStatus, addEvent } = useWallet(); // Create a new escrow const createEscrow = async (destination, amountDrops, finishAfterSeconds, cancelAfterSeconds) => { const nowRipple = Math.floor(Date.now() / 1000) - RIPPLE_EPOCH_OFFSET; const transaction = { TransactionType: "EscrowCreate", Account: walletManager.account.address, Destination: destination, Amount: String(amountDrops), }; // FinishAfter: earliest time escrow can be finished if (finishAfterSeconds) { transaction.FinishAfter = nowRipple + parseInt(finishAfterSeconds, 10); } // CancelAfter: time after which escrow can be canceled if (cancelAfterSeconds) { transaction.CancelAfter = nowRipple + parseInt(cancelAfterSeconds, 10); } const txResult = await walletManager.signAndSubmit(transaction); addEvent("Escrow Created", txResult); return txResult; }; // Finish an escrow (release funds) const finishEscrow = async (owner, escrowId) => { const transaction = { TransactionType: "EscrowFinish", Account: walletManager.account.address, Owner: owner, // Original creator of the escrow EscrowID: escrowId, // Ledger ID of the escrow }; const txResult = await walletManager.signAndSubmit(transaction); addEvent("Escrow Finished", txResult); return txResult; }; // Cancel an expired escrow const cancelEscrow = async (owner, escrowId) => { const transaction = { TransactionType: "EscrowCancel", Account: walletManager.account.address, Owner: owner, EscrowID: escrowId, }; const txResult = await walletManager.signAndSubmit(transaction); addEvent("Escrow Canceled", txResult); return txResult; }; return (
{/* Create escrow: 1 XRP, finishable after 60s, cancelable after 1 hour */}
); } ``` -------------------------------- ### Scaffold-XRP Module Configuration (module.json) Source: https://context7.com/xrpl-commons/scaffold-xrp/llms.txt Defines the structure and dependencies for a custom module within a Scaffold-XRP project. This file is required for module creation. ```json // module.json - Required module configuration { "name": "my-module", "version": "1.0.0", "description": "Description of what your module does", "author": "Your Name", "compatibility": { "scaffold-xrp": ">=0.1.0", "frameworks": ["nextjs", "nuxt"] }, "files": { "components": ["components/"], "hooks": ["hooks/"], "composables": ["composables/"], "lib": ["lib/"], "contracts": ["contracts/"], "pages": ["pages/"], "data": ["data/"] }, "dependencies": { "npm": ["some-npm-package"], "modules": ["other-scaffold-module"] } } ``` -------------------------------- ### Define Module Structure Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/docs/module-template/README.md The standard directory layout for a scaffold-xrp module, including support for React, Vue, and Rust/WASM contracts. ```text my-module/ ├── module.json # Required: Module metadata and configuration ├── README.md # Documentation for your module ├── components/ │ ├── react/ # React components (for Next.js) │ │ └── ExampleComponent.tsx │ └── vue/ # Vue components (for Nuxt) │ └── ExampleComponent.vue ├── hooks/ # React hooks (copied for Next.js projects) │ └── useExample.ts ├── composables/ # Vue composables (copied for Nuxt projects) │ └── useExample.ts ├── lib/ # Shared utilities (copied to both frameworks) │ └── utils.ts ├── pages/ # Page components │ ├── react/ # Next.js pages │ │ └── example.tsx │ └── vue/ # Nuxt pages │ └── example.vue ├── contracts/ # Rust/WASM smart contracts │ └── src/ │ └── lib.rs ├── data/ # Static data files │ └── config.json └── install.js # Optional: Post-install script ``` -------------------------------- ### Create MPToken with Scaffold-XRP Source: https://context7.com/xrpl-commons/scaffold-xrp/llms.txt Use this JavaScript function to create a Multi-Purpose Token with customizable properties like asset scale, maximum supply, and transfer permissions. It requires the use of the WalletProvider. ```javascript import { useWallet } from "./providers/WalletProvider"; import { stringToHex } from "../lib/utils"; const FLAG_TRANSFERABLE = 0x20; function MPTokenExample() { const { walletManager, showStatus, addEvent } = useWallet(); const createMPToken = async (tokenName, assetScale = 2, maxAmount = null, transferable = true) => { const metadata = JSON.stringify({ name: tokenName, description: "MPToken created via Scaffold-XRP", }); const transaction = { TransactionType: "MPTokenIssuanceCreate", Account: walletManager.account.address, AssetScale: assetScale, Flags: transferable ? FLAG_TRANSFERABLE : 0, MPTokenMetadata: stringToHex(metadata), }; if (maxAmount) { transaction.MaximumAmount = maxAmount; } const txResult = await walletManager.signAndSubmit(transaction); const issuanceId = txResult?.result?.mpt_issuance_id || txResult?.mpt_issuance_id || "Check transaction for ID"; showStatus("MPToken created successfully!", "success"); addEvent("MPToken Created", txResult); return { hash: txResult.hash, issuanceId }; }; return ( ); } ``` -------------------------------- ### WASM Output Path Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/README.md Location of the compiled WASM file after building. ```text target/wasm32-unknown-unknown/release/counter.wasm ``` -------------------------------- ### Scaffold-XRP Utility Functions: String to Hex and Class Merging Source: https://context7.com/xrpl-commons/scaffold-xrp/llms.txt Utilizes helper functions for converting strings to hexadecimal format for XRPL transactions and merging CSS class names using Tailwind CSS conventions. ```javascript import { cn, stringToHex } from "../lib/utils"; // Convert string to hex (uppercase) for XRPL transactions const functionName = "increment"; const hexName = stringToHex(functionName); console.log(hexName); // "696E6372656D656E74" // Merge Tailwind CSS classes (uses clsx + tailwind-merge) const buttonClasses = cn( "px-4 py-2 rounded", isActive && "bg-blue-500", isDisabled && "opacity-50 cursor-not-allowed" ); ``` -------------------------------- ### Locate Compiled WASM File Source: https://github.com/xrpl-commons/scaffold-xrp/blob/main/QUICKSTART.md The file path for the generated WASM binary after a successful build. ```text packages/bedrock/target/wasm32-unknown-unknown/release/counter.wasm ``` -------------------------------- ### Sign and Submit Transactions Source: https://context7.com/xrpl-commons/scaffold-xrp/llms.txt Use the walletManager.signAndSubmit method to sign and broadcast transactions to the XRPL network. ```javascript import { useWallet } from "./providers/WalletProvider"; function TransactionExample() { const { walletManager, isConnected, showStatus, addEvent } = useWallet(); const sendPayment = async () => { if (!walletManager || !walletManager.account) { showStatus("Please connect a wallet first", "error"); return; } try { const transaction = { TransactionType: "Payment", Account: walletManager.account.address, Destination: "rN7n7otQDd6FczFgLdlqtyMVrn3HMfXoQT", Amount: "1000000", // 1 XRP in drops (1 XRP = 1,000,000 drops) }; const txResult = await walletManager.signAndSubmit(transaction); console.log("Transaction hash:", txResult.hash); console.log("Transaction ID:", txResult.id); showStatus("Transaction submitted successfully!", "success"); addEvent("Payment Sent", txResult); } catch (error) { showStatus(`Transaction failed: ${error.message}`, "error"); addEvent("Payment Failed", error); } }; return ( ); } ``` -------------------------------- ### Rust Counter Smart Contract for XRPL Source: https://context7.com/xrpl-commons/scaffold-xrp/llms.txt This Rust smart contract demonstrates persistent storage and function exports for a counter on XRPL. It uses the `xrpl-wasm-std` library and compiles to WASM. ```rust #![cfg_attr(target_arch = "wasm32", no_std)] use xrpl_wasm_std::core::current_tx::contract_call::get_current_contract_call; use xrpl_wasm_std::core::current_tx::traits::ContractCallFields; use xrpl_wasm_std::core::data::codec::{get_data, set_data}; use xrpl_wasm_std::host::trace::trace; const COUNTER_KEY: &str = "counter"; const SUCCESS: i32 = 0; const ERROR: i32 = -1; fn read_counter() -> u32 { let contract_call = get_current_contract_call(); let contract_account = contract_call.get_contract_account().unwrap(); match get_data::(&contract_account, COUNTER_KEY) { Some(value) => value, None => 0, } } fn write_counter(value: u32) -> i32 { let contract_call = get_current_contract_call(); let contract_account = contract_call.get_contract_account().unwrap(); match set_data::(&contract_account, COUNTER_KEY, value) { Ok(_) => SUCCESS, Err(e) => e, } } /// @xrpl-function get_count #[unsafe(no_mangle)] pub extern "C" fn get_count() -> i32 { let value = read_counter(); let _ = trace("Getting counter value"); value as i32 } /// @xrpl-function increment #[unsafe(no_mangle)] pub extern "C" fn increment() -> i32 { let current = read_counter(); let new_value = current + 1; if write_counter(new_value) != SUCCESS { let _ = trace("Failed to increment counter"); return ERROR; } let _ = trace("Counter incremented"); new_value as i32 } /// @xrpl-function decrement #[unsafe(no_mangle)] pub extern "C" fn decrement() -> i32 { let current = read_counter(); if current == 0 { let _ = trace("Counter already at 0"); return 0; } let new_value = current - 1; if write_counter(new_value) != SUCCESS { return ERROR; } new_value as i32 } /// @xrpl-function reset #[unsafe(no_mangle)] pub extern "C" fn reset() -> i32 { if write_counter(0) != SUCCESS { return ERROR; } let _ = trace("Counter reset to 0"); 0 } /// @xrpl-function add #[unsafe(no_mangle)] pub extern "C" fn add(amount: u32) -> i32 { let current = read_counter(); let new_value = current + amount; if write_counter(new_value) != SUCCESS { return ERROR; } new_value as i32 } ``` -------------------------------- ### Deposit and Withdraw from XRPL Vaults Source: https://context7.com/xrpl-commons/scaffold-xrp/llms.txt Manage funds in smart vaults using these functions. Requires a configured wallet provider and `walletManager` with `showStatus` and `addEvent`. ```javascript import { useWallet } from "./providers/WalletProvider"; function VaultExample() { const { walletManager, showStatus, addEvent } = useWallet(); // Deposit to a vault const depositToVault = async (vaultId, amountDrops) => { const transaction = { TransactionType: "VaultDeposit", Account: walletManager.account.address, VaultID: vaultId, Amount: String(amountDrops), ComputationAllowance: 1000000, Fee: "1000000", }; const txResult = await walletManager.signAndSubmit(transaction); showStatus("Vault deposit successful!", "success"); addEvent("Vault Deposit", txResult); return txResult; }; // Withdraw from a vault const withdrawFromVault = async (vaultId, amountDrops) => { const transaction = { TransactionType: "VaultWithdraw", Account: walletManager.account.address, VaultID: vaultId, Amount: String(amountDrops), ComputationAllowance: 1000000, Fee: "1000000", }; const txResult = await walletManager.signAndSubmit(transaction); showStatus("Vault withdrawal successful!", "success"); addEvent("Vault Withdraw", txResult); return txResult; }; return (
); } ``` -------------------------------- ### Interact with Smart Contracts Source: https://context7.com/xrpl-commons/scaffold-xrp/llms.txt Execute smart contract functions using the ContractCall transaction type, ensuring function names and arguments are converted to hex. ```javascript import { useWallet } from "./providers/WalletProvider"; import { stringToHex } from "../lib/utils"; function ContractCallExample() { const { walletManager, showStatus, addEvent } = useWallet(); const callContract = async (contractAddress, functionName, args = "") => { if (!walletManager || !walletManager.account) { showStatus("Please connect a wallet first", "error"); return; } try { const transaction = { TransactionType: "ContractCall", Account: walletManager.account.address, ContractAccount: contractAddress, // rAddress of deployed contract Fee: "1000000", // 1 XRP fee in drops FunctionName: stringToHex(functionName), // e.g., "increment" -> hex ComputationAllowance: "1000000", }; // Add optional arguments if (args) { transaction.FunctionArguments = stringToHex(args); } const txResult = await walletManager.signAndSubmit(transaction); showStatus("Contract called successfully!", "success"); addEvent("Contract Called", txResult); return { success: true, hash: txResult.hash, id: txResult.id }; } catch (error) { showStatus(`Contract call failed: ${error.message}`, "error"); return { success: false, error: error.message }; } }; // Example: Call counter contract functions return (
); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.