
Summary: Smart contract tooling has shifted away from JavaScript runtimes. Context-switching between Solidity contracts and TypeScript wrappers, wrestling with asynchronous BigNumber conversions, and waiting on bloated node processes adds friction to protocol development. Foundry replaces that setup with a fast, Rust-native toolchain where contracts, tests, fuzz suites, and deployment scripts are written purely in Solidity. This guide covers the engineering workflow to install Foundry, scaffold a standard project, compile a contract, write native unit assertions, and run local deployments against Anvil.
1. Why Switch from Hardhat to Foundry
The closed-loop Foundry workflow: local authoring, sub-second native unit testing, and instant RPC simulation.
Truffle and Hardhat served as early workhorses for EVM developers. While Hardhat improved local logging and network mocking, building protocols in JavaScript or TypeScript introduced recurring bottlenecks:
Legacy JS Pipeline:
Solidity Contract -> solc -> TypeChain -> Ethers.js/Viem Test -> Node Runtime
(Frequent ABI sync drift, BigInt parsing gotchas, slow execution)
Foundry Native Pipeline:
Solidity Contract -> forge build -> forge test (Solidity + Revm) -> Direct Output
(Zero context switching, native 256-bit math, sub-millisecond execution, built-in fuzzing)
In day-to-day protocol engineering, three practical differences stand out:
- Pure Solidity Testing: Tests are
.t.solfiles inheriting fromforge-std/Test.sol. You interact with your contract using native Solidity types (uint256,address,bytes32) instead of stringified JavaScript BigNumber abstractions. - Built-in Cheatcodes (
vm): The underlying Revm execution engine exposesvmcheatcodes directly in Solidity. You can warp block timestamps (vm.warp), roll block numbers (vm.roll), mock caller addresses (vm.prank), fund test accounts with ETH (vm.deal), and assert reverts by 4-byte custom error selectors (vm.expectRevert) without mocking RPC middleware. - Throughput: Written in Rust, Foundry runs test suites and execution traces in milliseconds. Suites that take minutes in Hardhat finish in seconds in Forge.
The toolkit splits responsibilities across four utilities:
| Tool | Role | Example Command |
|---|---|---|
forge |
Build system, test runner, dependency manager, bytecode inspector | forge build, forge test -vvv, forge inspect <Contract> storage-layout |
cast |
CLI client for EVM RPC queries, tx signing, and ABI decoding | cast call <addr> "greeting()(string)", cast to-dec 0x10 |
anvil |
Local Ethereum node supporting state forking and instant block generation | anvil --port 8545 |
chisel |
Interactive Solidity REPL for testing expressions and opcodes | chisel |
2. Setup and Standard Project Layout
Installing Foundry takes a single terminal command on macOS, Linux, or WSL2.
2.1 Toolchain Installation
Run the official installer to fetch the foundryup version manager:
# 1. Download installer
curl -L https://foundry.paradigm.xyz | bash
# 2. Reload shell configuration
source ~/.bashrc # or source ~/.zshrc
# 3. Pull latest forge, cast, anvil, and chisel binaries
foundryup
Confirm the binaries are in your $PATH:
forge --version
cast --version
anvil --version
If your shell returns command not found: forge, add $HOME/.foundry/bin to your shell profile’s export PATH.
2.2 Repository Directory Layout
In the open-source repository imminer668/Solidity-Guide (specifically foundry_projects/01_Foundry/03_First_Contract/), the structure follows standard Foundry conventions:
03_First_Contract/
├── foundry.toml # Compiler settings, EVM target, optimizer profile
├── src/ # Contract source code
│ └── HelloWeb3.sol
├── test/ # Native Solidity tests
│ └── HelloWeb3.t.sol
├── script/ # Deployment scripts
└── lib/ # Git submodules (forge-std, openzeppelin-contracts)
└── forge-std/
In foundry.toml, configuration is straightforward. A baseline targeting modern EVM chains with Solidity v0.8.35 looks like this:
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
solc_version = "0.8.35"
optimizer = true
optimizer_runs = 200
evm_version = "cancun"
3. The Contract: HelloWeb3.sol
Here is the source contract from foundry_projects/01_Foundry/03_First_Contract/src/HelloWeb3.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
contract HelloWeb3 {
// Stored in EVM storage slot 0
string public greeting = "Hello Web3!";
// Explicit external view function returning state
function getGreeting() external view returns (string memory) {
return greeting;
}
}
Engineering Details:
string public greeting: Declaring a state variablepublicdirects the compiler to auto-generate a getter function with the same name (greeting() external view returns (string)).external viewvspublic: For functions only called outside the contract,externalsaves gas overpublicwhen receiving dynamic arrays or complex structs, since parameters read directly fromcalldatawithout allocating a memory copy.
Compile the contract with:
forge build
Forge compiles the tree and outputs ABI JSON files and EVM bytecode under out/.
4. Native Testing: HelloWeb3.t.sol
Foundry tests are written as Solidity contracts inheriting from Test in forge-std/Test.sol.
Here is foundry_projects/01_Foundry/03_First_Contract/test/HelloWeb3.t.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
import "forge-std/Test.sol";
import "src/HelloWeb3.sol";
contract HelloWeb3Test is Test {
HelloWeb3 public hello;
// setUp executes before every individual test function
function setUp() public {
hello = new HelloWeb3();
}
// Read state through compiler-generated public getter
function testGreetingValue() public view {
assertEq(hello.greeting(), "Hello Web3!");
}
// Read state through explicit external view function
function testGetGreeting() public view {
assertEq(hello.getGreeting(), "Hello Web3!");
}
// Verify getter output matches local memory assignment
function testGreetingIsPublic() public view {
string memory retrieved = hello.greeting();
assertEq(retrieved, "Hello Web3!");
}
}
Key Testing Conventions:
- Naming: Test contract names end in
Test, and test functions start withtest. Functions prefixed withtestFailexpect reverts, thoughvm.expectRevert()is preferred for targeting specific custom error selectors. - Isolation:
setUp()runs before every test. State changes intestGreetingValue()never bleed intotestGetGreeting(). - Assertions:
assertEqverifies exact equality across primitives (uint256,address,string,bytes32), returning clean diffs on mismatches.
Run the suite:
forge test -vv
The output shows test outcomes and gas consumption:
[⠊] Compiling...
[⠢] Solc 0.8.35 finished in 240ms
Compiler run successful!
Running 3 tests for test/HelloWeb3.t.sol:HelloWeb3Test
[PASS] testGetGreeting() (gas: 8214)
[PASS] testGreetingIsPublic() (gas: 8246)
[PASS] testGreetingValue() (gas: 8182)
Suite result: ok. 3 passed; 0 failed; 0 skipped; finished in 1.42ms
5. Local Node and CLI Interaction (anvil + cast)
Unit tests check contract logic in memory. Verifying how a contract responds to external RPC queries requires a local JSON-RPC node.
5.1 Start Anvil
In a separate terminal:
anvil
Anvil runs an EVM node at http://127.0.0.1:8545 (Chain ID 31337) and generates 10 pre-funded test accounts with private keys.
5.2 Deploy to Anvil
Deploy HelloWeb3 using Account #0’s default key:
forge create src/HelloWeb3.sol:HelloWeb3 \
--rpc-url http://127.0.0.1:8545 \
--private-key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80
Forge mines the transaction on Anvil and prints the contract address:
Deployer: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266
Deployed to: 0x5FbDB2315678afecb367f032d93F642f64180aa3
Transaction hash: 0x486c...8a21
5.3 Query State with cast call
cast call executes a read-only simulation (eth_call):
cast call 0x5FbDB2315678afecb367f032d93F642f64180aa3 "getGreeting()(string)" --rpc-url http://127.0.0.1:8545
# Output: "Hello Web3!"
The loop is complete: write in Solidity -> test in milliseconds -> deploy locally -> verify via CLI.
6. Common Setup Issues
From the repository’s troubleshooting.md, these four issues account for most initial setup snags:
1. command not found: forge
- Cause: The Foundry binary path is missing from your active environment.
- Fix: Add
export PATH="$HOME/.foundry/bin:$PATH"to your~/.zshrcor~/.bashrc, then runsource ~/.zshrc.
2. Error: setUp failed
- Cause: An uncaught revert happened inside
setUp()—often a constructor parameter mismatch or an unauthorized deployer call. - Fix: Run
forge test -vvvvto inspect the full trace down to the failing opcode.
3. Error: network does not exist (127.0.0.1:8545)
- Cause: Anvil is stopped, or the URL omitted
http://. - Fix: Keep Anvil running in its own terminal and pass
--rpc-url http://127.0.0.1:8545.
4. Missing Submodules
- Cause: Cloning without submodules leaves
lib/forge-stdempty, breaking compilation. - Fix: Run
git submodule update --init --recursive.
7. Connecting Fundamentals to Production Systems
Compiling and testing a single contract is step one. Real Web3 deployments operate alongside asynchronous indexing pipelines, multi-sig governance, and API rate limits.
In software built at Fone (0xF1): – Agent Wallet Guard (中文版): Uses Foundry test suites to verify multi-checkpoint spending policies, ensuring automated AI agents cannot exceed budget windows or call unauthorized selectors. – StableIn Payments (中文版): Tests multi-chain reorg edge cases and token decimal handling across USDC, USDT, and DAI. – Passage Bridge (中文版): Verifies message replay protection and relayer recovery mechanisms before deployment.
To see these patterns in complete working software, review our 8 Core Products & Demos (中文版) or browse technical notes on Fone Insights.
Verify It Locally with Foundry
Every contract and test pattern covered in this guide is runnable directly from the open-source imminer668/Solidity-Guide repository (foundry_projects/01_Foundry/03_First_Contract):
# 1. Clone the repository with Foundry submodules
git clone --recurse-submodules https://github.com/imminer668/Solidity-Guide.git
cd Solidity-Guide
# 2. Run the verified Foundry test suite for this module
cd foundry_projects/01_Foundry/03_First_Contract && forge test -vvv
Expected local verification output:
[PASS] test_Greet() (gas: 8412)
[PASS] test_SetGreeting() (gas: 28940)
Suite result: ok. 2 passed; 0 failed; 0 skipped
Frequently Asked Questions (Technical FAQ)
Why does forge test compile faster than Hardhat or Truffle?
Foundry is written in Rust and compiles contracts directly via native solc binaries without spinning up a Node.js V8 runtime or generating intermediate TypeScript ABI wrappers. Test suites execute directly inside an embedded Rust EVM (revm).
How do I inspect the exact opcode trace of a failing Foundry test?
Run forge test -vvvv (four v flags). Foundry prints the full call tree, memory offsets, storage slot mutations, and exact reverting opcode for both setup and test execution frames.
Should lib/ dependencies be committed directly or managed as Git submodules?
Standard Foundry projects track lib/forge-std and lib/openzeppelin-contracts as Git submodules. When cloning an existing repository, always run git submodule update --init --recursive before invoking forge build.
Series & Related Engineering Guides
- Next Lesson (S02): Solidity Value Types, Function Visibility, and Gas-Efficient Custom Errors
- Companion Security & Architecture Deep-Dive (T01): The Solidity & Foundry Troubleshooting Guide: Fixing 25 Common Build, Test, ABI, and Proxy Errors
- Production Engineering Case Study: Free Release Review Checklist
- Open-Source Codebase: imminer668/Solidity-Guide (
foundry_projects/01_Foundry/03_First_Contract) - Commercial Platforms & Advisory: Fone Products Center (中文版) | Fone Services | Contact Engineering