Set up a Foundry project

In this workshop we will learn how to create an evm project with hardhat

This guide will walk you through setting up an EVM project on the XRPL sidechain using Foundry, a powerful toolkit for Ethereum application development.

Part 1: Installing Foundry

Foundry is a blazing fast, portable and modular toolkit for Ethereum application development written in Rust. It consists of four main tools:

  • Forge: Ethereum testing framework

  • Cast: Swiss army knife for interacting with EVM smart contracts

  • Anvil: Local Ethereum node for development

  • Chisel: Fast, utilitarian, and verbose solidity REPL

Prerequisites

Before installing Foundry, ensure you have:

  • A terminal application (Git BASH or WSL for Windows users)

  • Internet connection for downloading the installer

Installation Methods

Foundryup is the official installer for the Foundry toolchain and the easiest way to get started.

  1. Install Foundryup

    Open your terminal and run:

    curl -L https://foundry.paradigm.xyz | bash
  2. Follow the on-screen instructions to complete the installation

  3. Install Foundry tools

    Run the following command to install the latest stable version:

    foundryup

    For the latest nightly build (with newest features), use:

    foundryup --version nightly

Option 2: Building from Source

If you prefer to build from source or need a custom configuration:

  1. Install Rust

    First, install Rust using rustup:

    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  2. Update Rust (if already installed)

    rustup update stable
  3. Install via Cargo

    cargo install --git https://github.com/foundry-rs/foundry --profile release --locked forge cast chisel anvil

Option 3: Using Docker

For containerized development:

docker pull ghcr.io/foundry-rs/foundry:latest

Verification

After installation, verify that Foundry is properly installed by checking the version:

forge --version

You should see version information for Forge, confirming the installation was successful.

Platform-Specific Notes

  • Windows: Use Git BASH or WSL as your terminal. PowerShell and Command Prompt are not currently supported by foundryup

  • macOS: Standard terminal works perfectly

  • Linux: Any terminal emulator will work

Troubleshooting

If you encounter issues during installation:

  1. Check your internet connection

  2. Ensure you have the latest version of your terminal

  3. For Windows users: Make sure you're using Git BASH or WSL

  4. Refer to the Foundry FAQ for additional help

Security Note

Foundry binaries are verified using GitHub artifact attestations to ensure integrity and authenticity. The installer automatically verifies these attestations during installation.


✅ Checkpoint: You now have Foundry installed and ready to use for XRPL sidechain development!

Part 2: Initializing a Foundry Project

Now that Foundry is installed, let's create a new project and understand the project structure.

Creating a New Project

Initialize a new Foundry project using the forge init command:

forge init my-xrpl-project
cd my-xrpl-project

This creates a new directory with a complete Foundry project structure.

Understanding the Project Structure

After initialization, your project will have the following structure:

my-xrpl-project/
├── foundry.toml          # Foundry configuration file
├── src/                  # Smart contracts directory
│   └── Counter.sol       # Example contract
├── script/               # Deployment and interaction scripts
│   └── Counter.s.sol     # Example deployment script
├── test/                 # Test files
│   └── Counter.t.sol     # Example test file
└── lib/                  # Dependencies (managed by Soldeer)

Key Directories Explained

  • /src: Contains your smart contracts written in Solidity

  • /test: Contains test files for your contracts (typically with .t.sol extension)

  • /script: Contains deployment scripts and other automation scripts

  • /lib: Contains external dependencies managed by Soldeer package manager

Setting Up Soldeer Package Manager

Soldeer is Foundry's native package manager for handling smart contract dependencies. Let's configure it for your project:

  1. Initialize Soldeer

    forge soldeer init
  2. Verify Soldeer Configuration

    Check that foundry.toml now includes Soldeer configuration:

    cat foundry.toml

    You should see something like:

    [profile.default]
    src = "src"
    out = "out"
    libs = ["lib"]
    
    [dependencies]
    # Dependencies will be listed here

Building Your Project

Compile the smart contracts to ensure everything is set up correctly:

forge build

You should see output indicating successful compilation of the example Counter contract.

Running Tests

Run the included tests to verify the setup:

forge test

This will execute all tests in the /test directory and show the results.

Understanding the Foundry Tools

Your project now has access to all Foundry tools:

Tool
Purpose

forge

Build, test, debug, deploy and verify smart contracts

anvil

Run a local Ethereum development node with forking capabilities

cast

Interact with contracts, send transactions, and retrieve chain data

chisel

Fast Solidity REPL for rapid prototyping and debugging

Adding Dependencies with Soldeer

To add external smart contract libraries (like OpenZeppelin), use Soldeer:

# Example: Add OpenZeppelin contracts
forge soldeer install @openzeppelin/[email protected]

Dependencies will be automatically added to your foundry.toml and downloaded to the /lib directory.

Customizing Your Project

You can customize various aspects of your project by editing foundry.toml:

[profile.default]
src = "src"
out = "out"
libs = ["lib"]
optimizer = true
optimizer_runs = 200
via_ir = true

[rpc_endpoints]
xrpl_devnet = "https://rpc-evm-sidechain.xrpl.org"

Checkpoint: You now have a fully initialized Foundry project with proper structure and dependency management!

Part 3: Setting Up Your Environment

Before deploying contracts to the XRPL sidechain, you need to set up a wallet and obtain test tokens for deployment.

Installing MetaMask

MetaMask is a popular Ethereum wallet that works with XRPL EVM sidechain. Follow these steps to install and set it up:

  1. Install MetaMask

    • Click "Download" and choose your browser

    • Install the browser extension

    • Create a new wallet or import an existing one

  2. Create a New Wallet (if you don't have one)

    • Click "Create a wallet"

    • Set a strong password

    • IMPORTANT: Write down your seed phrase securely and never share it

    • Confirm your seed phrase

Adding XRPL EVM Sidechain to MetaMask

Configure MetaMask to connect to the XRPL EVM sidechain:

  1. Open MetaMask and click the network dropdown (usually shows "Ethereum Mainnet")

  2. Add Custom Network with these details:

    Network Name: XRPL EVM Sidechain
    New RPC URL: https://rpc-evm-sidechain.xrpl.org
    Chain ID: 1440002
    Currency Symbol: XRP
    Block Explorer URL: https://evm-sidechain.xrpl.org
  3. Save the network configuration

  4. Switch to the XRPL EVM Sidechain network

Getting Your Private Key

⚠️ Security Warning: Never share your private key with anyone. Only use it for development and testing purposes.

  1. Open MetaMask

  2. Click the three dots next to your account name

  3. Select "Account Details"

  4. Click "Show private key"

  5. Enter your password

  6. Copy the private key (you'll need this for deployment)

Getting Test Tokens from the Faucet

You need test XRP tokens to deploy contracts on the XRPL sidechain:

  1. Visit the XRPL EVM Faucet: https://faucet.xrplevm.org/

  2. Connect Your Wallet

    • Click "Connect Wallet"

    • Select MetaMask

    • Approve the connection

  3. Request Test Tokens

    • Make sure you're on the XRPL EVM Sidechain network

    • Your wallet address should be displayed

    • Click "Send me XRP" or the equivalent button

    • Wait for the transaction to complete

  4. Verify Token Receipt

    • Check your MetaMask balance

    • You should see test XRP tokens in your wallet

Setting Up Environment Variables

Create a .env file in your project root to store your private key securely:

  1. Create the file:

    touch .env
  2. Add your private key:

    PRIVATE_KEY=your_private_key_here
    RPC_URL=https://rpc.testnet.xrplevm.org
  3. Add .env to .gitignore (if not already present):

    echo ".env" >> .gitignore

Configuring Foundry for XRPL

Update your foundry.toml to include XRPL-specific settings:

[profile.default]
src = "src"
out = "out"
libs = ["lib"]
optimizer = true
optimizer_runs = 200

[rpc_endpoints]
xrpl = "https://rpc.testnet.xrplevm.org"

[etherscan]
xrpl = { key = "your_api_key_if_available", url = "https://evm-sidechain.xrpl.org/api" }

Testing Your Setup

Verify your environment is ready:

  1. Check your balance:

    cast balance --rpc-url https://rpc.testnet.xrplevm.org YOUR_WALLET_ADDRESS
  2. Load environment variables (if using .env):

    source .env
  3. Test connection:

    cast block-number --rpc-url $RPC_URL

Security Best Practices

  • Never commit your private key to version control

  • Use environment variables for sensitive data

  • Use separate wallets for development and production

  • Regularly backup your seed phrase securely

  • Consider using hardware wallets for production deployments


Checkpoint: Your environment is now configured with MetaMask, test tokens, and proper security setup!

Part 4: Deploying Your Smart Contract

Now that your environment is set up, let's deploy the example Counter contract to the XRPL EVM sidechain using the forge create command.

Understanding the Counter Contract

First, let's look at the Counter contract in src/Counter.sol:

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

contract Counter {
    uint256 public number;

    function setNumber(uint256 newNumber) public {
        number = newNumber;
    }

    function increment() public {
        number++;
    }
}

This simple contract stores a number and provides functions to set and increment it.

Deploying with forge create

The forge create command allows you to deploy a single contract directly without deployment scripts.

Basic Deployment Command

forge create src/Counter.sol:Counter \
  --rpc-url https://rpc.testnet.xrplevm.org \
  --private-key $PRIVATE_KEY \
  --broadcast

Using Environment Variables

For better security, load your environment variables first:

source .env
forge create src/Counter.sol:Counter \
  --rpc-url $RPC_URL \
  --private-key $PRIVATE_KEY \
  --broadcast

Using Foundry Configuration

If you configured the RPC endpoint in foundry.toml, you can use:

forge create src/Counter.sol:Counter \
  --rpc-url xrpl \
  --private-key $PRIVATE_KEY \
  --broadcast

Understanding Deployment Output

After successful deployment, you'll see output like:

[⠢] Compiling...
[⠆] Compiling 1 files with 0.8.19
[⠰] Solc 0.8.19 finished in 1.23s
Compiler run successful!

Deployer: 0xa735b3c25f...
Deployed to: 0x4054415432...
Transaction hash: 0x6b4e0ff93a...

Key Information:

  • Deployer: Your wallet address

  • Deployed to: Your contract's address on the blockchain

  • Transaction hash: Reference for the deployment transaction

Deploying Contracts with Constructor Arguments

If your contract has constructor parameters, use the --constructor-args flag:

// Example contract with constructor
contract MyToken {
    constructor(string memory name, string memory symbol, uint256 supply) {
        // constructor logic
    }
}

Deploy with arguments:

forge create src/MyToken.sol:MyToken \
  --rpc-url $RPC_URL \
  --private-key $PRIVATE_KEY \
  --broadcast \
  --constructor-args "MyToken" "MTK" 1000000

Dry Run Deployment

Test your deployment without broadcasting to the network:

forge create src/Counter.sol:Counter \
  --rpc-url $RPC_URL \
  --private-key $PRIVATE_KEY
  # Note: No --broadcast flag

This simulates the deployment and shows gas estimates without spending real tokens.

Verifying Your Deployment

  1. Check deployment on block explorer:

  2. Interact with your contract using Cast:

    # Set your contract address
    CONTRACT_ADDRESS="your_deployed_contract_address"
    
    # Get the current counter value (should be 0)
    cast call $CONTRACT_ADDRESS "number()" --rpc-url $RPC_URL
    
    # Increment the counter
    cast send $CONTRACT_ADDRESS "increment()" \
      --rpc-url $RPC_URL \
      --private-key $PRIVATE_KEY
    
    # Check the new value (should be 1)
    cast call $CONTRACT_ADDRESS "number()" --rpc-url $RPC_URL
    
    # Set a specific number
    cast send $CONTRACT_ADDRESS "setNumber(uint256)" 42 \
      --rpc-url $RPC_URL \
      --private-key $PRIVATE_KEY

Contract Verification (Optional)

If the XRPL EVM sidechain supports contract verification, you can verify your contract:

forge verify-contract \
  --chain-id 1440002 \
  --watch \
  --verifier blockscout \
  --verifier-url https://evm-sidechain.xrpl.org/api \
  $CONTRACT_ADDRESS \
  src/Counter.sol:Counter

Deployment Best Practices

  1. Always test locally first:

    # Start local Anvil node
    anvil
    
    # Deploy to local node (in another terminal)
    forge create src/Counter.sol:Counter \
      --rpc-url http://127.0.0.1:8545 \
      --private-key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 \
      --broadcast
  2. Check gas costs before deployment:

    # Dry run to see gas estimates
    forge create src/Counter.sol:Counter --rpc-url $RPC_URL
  3. Keep track of deployed contracts:

    • Save contract addresses in a deployment log

    • Document which version was deployed when

    • Keep constructor arguments for reference

Troubleshooting Common Issues

  1. Insufficient Funds:

    • Check your balance: cast balance YOUR_ADDRESS --rpc-url $RPC_URL

    • Get more test tokens from the faucet if needed

  2. Private Key Format:

    • Ensure your private key starts with 0x

    • Check for any extra spaces or characters

  3. Network Issues:

    • Verify the RPC URL is correct

    • Check if the XRPL EVM sidechain is operational

  4. Compilation Errors:

    • Run forge build first to check for compilation issues

    • Ensure all dependencies are properly installed

Using Legacy Transactions

If you encounter EIP-1559 issues, use the --legacy flag:

forge create src/Counter.sol:Counter \
  --rpc-url $RPC_URL \
  --private-key $PRIVATE_KEY \
  --broadcast \
  --legacy

🎉 Congratulations! You have successfully deployed your first smart contract to the XRPL EVM sidechain using Foundry! Your contract is now live and ready for interaction.

Last updated