Foundry Development Framework
Overview
Foundry is a blazing-fast, portable, and modular toolkit for Ethereum development written in Rust. It provides Forge (testing), Cast (CLI), Anvil (local node), and Chisel (Solidity REPL).
ā¹ļø
Foundry tests are written in Solidity, enabling direct contract interaction without JavaScript overhead. This results in faster test execution and better gas reporting.
Architecture
Installation
# Install Foundry
curl -L https://foundry.paradigm.xyz | bash
foundryup
# Or with npm
npm install -g foundryup
# Verify installation
forge --version
cast --version
anvil --version
Project Setup
Initialize Project
# Create new project
forge init my-project
cd my-project
# Or initialize in existing directory
forge init --no-git
# Install dependencies
forge install OpenZeppelin/openzeppelin-contracts
forge install foundry-rs/forge-std
Project Structure
my-project/
āāā src/ # Source contracts
ā āāā Token.sol
ā āāā interfaces/
āāā test/ # Test files
ā āāā Token.t.sol
ā āāā invariant/
āāā script/ # Deployment scripts
ā āāā Deploy.s.sol
āāā lib/ # Dependencies (git submodules)
ā āāā forge-std/
ā āāā openzeppelin-contracts/
āāā foundry.toml # Configuration
āāā remappings.txt # Import remappings
foundry.toml
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
solc_version = "0.8.19"
optimizer = true
optimizer_runs = 200
via_ir = true
evm_version = "paris"
ffi = false
fs_permissions = [{ access = "read", path = "./"}]
fuzz = { runs = 256 }
[profile.ci]
fuzz = { runs = 1024 }
invariant = { runs = 256 }
[rpc_endpoints]
mainnet = "${MAINNET_RPC_URL}"
goerli = "${GOERLI_RPC_URL}"
[etherscan]
mainnet = { key = "${ETHERSCAN_API_KEY}" }
Forge: Testing
Basic Test Structure
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "../src/Token.sol";
contract TokenTest is Test {
Token public token;
address public owner = address(0x1);
address public alice = address(0x2);
address public bob = address(0x3);
// Runs before each test
function setUp() public {
vm.prank(owner);
token = new Token("TestToken", "TT", 18);
vm.prank(owner);
token.mint(owner, 1000 ether);
}
// Test functions must start with "test"
function testDeployment() public {
assertEq(token.name(), "TestToken");
assertEq(token.symbol(), "TT");
assertEq(token.decimals(), 18);
}
function testTransfer() public {
vm.prank(owner);
token.transfer(alice, 100 ether);
assertEq(token.balanceOf(alice), 100 ether);
assertEq(token.balanceOf(owner), 900 ether);
}
function testTransferInsufficientBalance() public {
vm.prank(alice);
vm.expectRevert("ERC20: insufficient balance");
token.transfer(bob, 100 ether);
}
// Test event emission
function testTransferEmitsEvent() public {
vm.prank(owner);
vm.expectEmit(true, true, false, true);
emit Transfer(owner, alice, 100 ether);
token.transfer(alice, 100 ether);
}
}
Cheatcodes Reference
| Cheatcode | Purpose | Example |
|---|---|---|
vm.prank(addr) | Impersonate address | vm.prank(owner) |
vm.startPrank(addr) | Persistent impersonation | vm.startPrank(owner) |
vm.deal(addr, amount) | Set ETH balance | vm.deal(addr, 100 ether) |
vm.warp(timestamp) | Set block timestamp | vm.warp(block.timestamp + 1 days) |
vm.roll(blockNum) | Set block number | vm.roll(block.number + 100) |
vm.expectRevert() | Expect revert | vm.expectRevert("Error msg") |
vm.expectEmit() | Expect event | vm.expectEmit(true, true, false, true) |
vm.load(addr, slot) | Read storage | vm.load(address, bytes32(0)) |
vm.store(addr, slot, val) | Write storage | vm.store(address, slot, val) |
vm.assume(cond) | Fuzz assumption | vm.assume(amount > 0) |
vm.bound(val, min, max) | Bound value | vm.bound(val, 0, 1000) |
Fork Testing
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
contract ForkTest is Test {
// Fork mainnet at specific block
function setUp() public {
vm.createSelectFork("mainnet", 18000000);
}
function testUniswapInteraction() public {
// Interact with mainnet Uniswap
IUniswapV2Router router = IUniswapV2Router(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"
);
// Test your contract against real protocol state
}
}
Fork Commands
# Fork mainnet
forge test --fork-url $MAINNET_RPC_URL
# Fork at specific block
forge test --fork-url $MAINNET_RPC_URL --fork-block-number 18000000
# Fork with cache
forge test --fork-url $MAINNET_RPC_URL --fork-cache-path .fork-cache
Fuzz Testing
Property-Based Testing
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "../src/Token.sol";
contract FuzzTest is Test {
Token public token;
function setUp() public {
token = new Token("TestToken", "TT", 18);
}
// Fuzz test - Foundry generates random inputs
function testFuzzTransfer(uint256 amount) public {
// Bound input to valid range
vm.assume(amount > 0 && amount <= 1000 ether);
// Setup
address user = address(0x1);
vm.deal(user, amount);
vm.prank(user);
token.mint(user, amount);
// Execute
address recipient = address(0x2);
vm.prank(user);
token.transfer(recipient, amount);
// Verify
assertEq(token.balanceOf(recipient), amount);
assertEq(token.balanceOf(user), 0);
}
// Multiple fuzz inputs
function testFuzzTransferMultiple(
uint256 amount1,
uint256 amount2
) public {
vm.assume(amount1 > 0 && amount1 <= 500 ether);
vm.assume(amount2 > 0 && amount2 <= 500 ether);
vm.assume(amount1 + amount2 <= 1000 ether);
address alice = address(0x1);
address bob = address(0x2);
address charlie = address(0x3);
vm.deal(alice, amount1 + amount2);
vm.startPrank(alice);
token.mint(alice, amount1 + amount2);
token.transfer(bob, amount1);
token.transfer(charlie, amount2);
vm.stopPrank();
assertEq(token.balanceOf(bob), amount1);
assertEq(token.balanceOf(charlie), amount2);
}
}
Fuzz Configuration
# foundry.toml
[profile.default]
fuzz = { runs = 256 }
[profile.ci]
fuzz = { runs = 1024 }
Fuzz Testing Commands
# Run fuzz tests
forge test --match-test testFuzz
# Increase fuzz runs
forge test --fuzz-runs 1024
# Run with verbosity
forge test -vvvv
Invariant Testing
Stateful Fuzzing
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "../src/Vault.sol";
contract InvariantTest is Test {
Vault public vault;
address[] public actors;
function setUp() public {
vault = new Vault();
// Create test actors
actors.push(address(0x1));
actors.push(address(0x2));
actors.push(address(0x3));
// Fund actors
for (uint256 i = 0; i < actors.length; i++) {
vm.deal(actors[i], 100 ether);
}
}
// Invariant: total deposits = total ETH in contract
function invariant_totalDepositsEqualsBalance() public view {
uint256 totalDeposits = vault.totalDeposits();
uint256 contractBalance = address(vault).balance;
assertEq(totalDeposits, contractBalance);
}
// Invariant: no actor can withdraw more than deposited
function invariant_withdrawalLessThanDeposit() public {
for (uint256 i = 0; i < actors.length; i++) {
uint256 deposited = vault.deposits(actors[i]);
uint256 balance = address(actors[i]).balance;
// Actor should have at least what they deposited
assertTrue(balance >= deposited || deposited == 0);
}
}
// Target specific functions for invariant testing
function targetFunctionDeposit(address actor) public {
vm.assume(actor != address(0));
vm.assume(actor != address(vault));
vm.prank(actor);
vault.deposit{value: 1 ether}();
}
function targetFunctionWithdraw(address actor, uint256 amount) public {
vm.assume(actor != address(0));
vm.assume(amount > 0 && amount <= 1 ether);
vm.prank(actor);
vault.withdraw(amount);
}
}
Invariant Configuration
# foundry.toml
[profile.default]
invariant = {
runs = 256,
depth = 32,
fail_on_revert = false,
call_override = false
}
Gas Optimization
Gas Reporting
# Run with gas reporting
forge test --gas-report
# Gas report for specific contract
forge test --match-contract TokenTest --gas-report
# Gas snapshot
forge snapshot
# Compare snapshots
forge snapshot --check
Gas Optimization Examples
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract GasOptimized {
// Bad: Storage in loop
function inefficientLoop(uint256[] storage data) public returns (uint256) {
uint256 total = 0;
for (uint256 i = 0; i < data.length; i++) {
total += data[i]; // SLOAD each iteration
}
return total;
}
// Good: Cache and use memory
function efficientLoop(uint256[] storage data) public returns (uint256) {
uint256 total = 0;
uint256 length = data.length; // Cache length
for (uint256 i = 0; i < length;) {
total += data[i];
unchecked { ++i; } // Save gas on increment
}
return total;
}
// Good: Use calldata for external functions
function processCalldata(uint256[] calldata data) external pure returns (uint256) {
uint256 total = 0;
for (uint256 i = 0; i < data.length;) {
total += data[i];
unchecked { ++i; }
}
return total;
}
// Good: Pack storage
struct Packed {
uint128 a;
uint128 b;
}
mapping(address => Packed) public packed;
function setPacked(uint128 a, uint128 b) public {
packed[msg.sender] = Packed(a, b); // Single SSTORE
}
}
Gas Comparison Table
| Operation | Unoptimized | Optimized | Savings |
|---|---|---|---|
| Storage read | 2100 | 2100 | 0 |
| Storage write | 5000-20000 | 5000-20000 | 0 |
| Memory read | 3 | 3 | 0 |
| Loop increment | 5 | 3 | 40% |
| Array length | 100 | 5 | 95% |
| Packed struct | 2 slots | 1 slot | 50% |
Cast: CLI Tool
Common Commands
# Get balance
cast balance 0x...
cast balance 0x... --ether
# Send transaction
cast send 0x... --value 1ether --private-key $PRIVATE_KEY
# Call contract function
cast call 0x... "totalSupply()(uint256)"
# Encode function call
cast calldata "transfer(address,uint256)" 0x... 1000
# Decode transaction
cast tx 0x... --rpc-url $RPC_URL
# Get block number
cast block-number
# Get gas price
cast gas-price
# Estimate gas
cast estimate 0x... "transfer(address,uint256)" 0x... 1000
# Convert units
cast to-wei 1 ether
cast from-wei 1000000000000000000
Advanced Cast Usage
# Impersonate account
cast impersonate 0x... --rpc-url $RPC_URL
# Set storage slot
cast storage 0x... 0 --rpc-url $RPC_URL
# Compute CREATE2 address
cast compute-address $SALT --init-code-hash $HASH --rpc-url $RPC_URL
# ABI encode
cast abi-encode "transfer(address,uint256)" 0x... 1000
# Signature tools
cast wallet new
cast wallet sign "message" --private-key $KEY
cast wallet verify "message" "signature" 0x...
Anvil: Local Node
Start Anvil
# Start with defaults
anvil
# Start with options
anvil --port 8545 --accounts 10 --balance 10000
# Start with fork
anvil --fork-url $MAINNET_RPC_URL --fork-block-number 18000000
# Start with deterministic keys
anvil --deterministic
Anvil Options
| Option | Default | Description |
|---|---|---|
| --port | 8545 | RPC port |
| --accounts | 10 | Number of accounts |
| --balance | 10000 | Initial ETH balance |
| --block-time | auto | Block time in seconds |
| --fork-url | none | Fork URL |
| --deterministic | false | Deterministic addresses |
Anvil for Testing
# Start Anvil in background
anvil &
# Run tests against Anvil
forge test --rpc-url http://localhost:8545
# Deploy to Anvil
forge script script/Deploy.s.sol --rpc-url http://localhost:8545 --broadcast
Deployment Scripts
Forge Script
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Script.sol";
import "../src/Token.sol";
contract DeployToken is Script {
function run() public returns (Token) {
uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY");
vm.startBroadcast(deployerPrivateKey);
Token token = new Token("MyToken", "MTK", 18);
vm.stopBroadcast();
return token;
}
}
Deploy Commands
# Dry run (no broadcast)
forge script script/Deploy.s.sol
# Deploy to local Anvil
forge script script/Deploy.s.sol --rpc-url http://localhost:8545 --broadcast
# Deploy to testnet
forge script script/Deploy.s.sol --rpc-url $GOERLI_RPC_URL --broadcast --verify
# Deploy to mainnet
forge script script/Deploy.s.sol --rpc-url $MAINNET_RPC_URL --broadcast --verify --slow
Real-World Example: Uniswap V3 Testing
Test Strategy
| Test Type | Coverage | Tools |
|---|---|---|
| Unit | Individual functions | Forge Test |
| Integration | Pool interactions | Fork Testing |
| Fuzz | Random amounts | Fuzz Testing |
| Invariant | State consistency | Invariant Testing |
Example: Testing Swap
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "@uniswap/v3-periphery/contracts/libraries/SqrtPriceMath.sol";
contract UniswapTest is Test {
function setUp() public {
vm.createSelectFork("mainnet", 18000000);
}
function testSwapExactInput() public {
// Test swap against real Uniswap V3 pool
address router = 0xE592427A0AEce92De3Edee1F18E0157C05861564";
// Swap 1 ETH for USDC
// ... implementation
}
function testFuzzSwap(uint256 amountIn) public {
vm.assume(amountIn > 0 && amountIn <= 100 ether);
// Fuzz test swap with random amounts
// ... implementation
}
}
Trade-offs
| Decision | Option A | Option B | Recommendation |
|---|---|---|---|
| Testing | Forge | Hardhat | Forge for speed |
| Language | Solidity tests | JS/TS tests | Solidity for unit tests |
| Forking | Forge | Hardhat | Similar capabilities |
| Deployment | Forge Script | Hardhat | Forge for simplicity |
Interview Questions
-
Compare Foundry's Forge testing with Hardhat testing. What are the trade-offs?
Forge tests are written in Solidity, providing direct contract interaction and faster execution. Hardhat uses JavaScript/TypeScript, offering more familiar syntax and richer ecosystem. Forge is faster, Hardhat has better debugging tools. Use Forge for performance-critical tests, Hardhat for complex scenarios.
-
Explain invariant testing and how it differs from fuzz testing.
Fuzz testing generates random inputs for individual functions. Invariant testing performs stateful fuzzing, calling multiple functions in sequence and verifying invariants (always-true conditions) hold after each sequence. Invariant testing catches complex state corruption bugs.
-
How do cheatcodes work in Foundry and what are some essential cheatcodes for testing?
Cheatcodes are special functions in the
vminterface that manipulate the EVM state. Essential ones:vm.prank(impersonate address),vm.deal(set balance),vm.warp(set timestamp),vm.expectRevert(assert reverts),vm.assume(fuzz assumptions).
Quiz Questions
-
What command starts a local Ethereum node in Foundry?
- A) forge node
- B) cast node
- C) anvil
- D) chisel
Answer: C -
anvilstarts a local Ethereum node for development. -
How do you run fuzz tests in Forge?
- A) forge test --fuzz
- B) forge fuzz
- C) forge test --match-test testFuzz
- D) fuzz test in Solidity
Answer: C - Functions starting with
testFuzzare automatically run as fuzz tests. -
What is the purpose of
vm.prankin Foundry tests?- A) Deploy contracts
- B) Set account balance
- C) Impersonate an address
- D) Set block timestamp
Answer: C -
vm.prank(addr)makes the next call come from the specified address.