Foundry Solidity Testing Framework
Overview
Foundry is a blazing-fast, portable, and modular toolkit for Ethereum development. It uses Solidity for tests, making it the most native testing framework for smart contracts.
Project Setup
# Install Foundry
curl -L https://foundry.paradigm.xyz | bash
foundryup
# Create new project
forge init my-foundry-project
cd my-foundry-project
# Project structure
āāā foundry.toml
āāā lib/
ā āāā forge-std/
āāā script/
ā āāā Deploy.s.sol
āāā src/
ā āāā Counter.sol
āāā test/
ā āāā Counter.t.sol
āāā remappings.txt
Configuration
# 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 = "./"}]
[profile.default.fuzz]
runs = 256
max_test_rejects = 65536
seed = "0x1"
[profile.default.invariant]
runs = 256
depth = 15
fail_on_revert = false
call_override = false
[profile.ci]
fuzz = { runs = 1024 }
invariant = { runs = 512, depth = 32 }
[rpc_endpoints]
mainnet = "https://eth-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}"
sepolia = "https://eth-sepolia.g.alchemy.com/v2/${ALCHEMY_API_KEY}"
polygon = "https://polygon-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}"
arbitrum = "https://arb-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}"
[etherscan]
mainnet = { key = "${ETHERSCAN_API_KEY}", url = "https://api.etherscan.io/api" }
sepolia = { key = "${ETHERSCAN_API_KEY}", url = "https://api-sepolia.etherscan.io/api" }
[fmt]
line_length = 120
tab_width = 4
bracket_spacing = false
int_types = "long"
multiline_func_header = "params_first"
quote_style = "double"
number_underscore = "preserve"
single_line_statement_blocks = "preserve"
Solidity-Native Testing
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "../src/MyToken.sol";
contract MyTokenTest is Test {
MyToken public token;
address public owner = address(this);
address public alice = makeAddr("alice");
address public bob = makeAddr("bob");
uint256 public constant INITIAL_SUPPLY = 1000 ether;
uint256 public constant MAX_SUPPLY = 1_000_000 ether;
function setUp() public {
token = new MyToken("Test Token", "TT", INITIAL_SUPPLY);
}
function testDeployment() public {
assertEq(token.name(), "Test Token");
assertEq(token.symbol(), "TT");
assertEq(token.decimals(), 18);
assertEq(token.totalSupply(), INITIAL_SUPPLY);
assertEq(token.balanceOf(owner), INITIAL_SUPPLY);
}
function testTransfer() public {
uint256 amount = 100 ether;
vm.prank(owner);
token.transfer(alice, amount);
assertEq(token.balanceOf(alice), amount);
assertEq(token.balanceOf(owner), INITIAL_SUPPLY - amount);
}
function testTransferEmitsEvent() public {
uint256 amount = 100 ether;
vm.prank(owner);
vm.expectEmit(true, true, true, true);
emit Transfer(owner, alice, amount);
token.transfer(alice, amount);
}
function testTransferFrom() public {
uint256 amount = 100 ether;
vm.prank(owner);
token.approve(alice, amount);
vm.prank(alice);
token.transferFrom(owner, bob, amount);
assertEq(token.balanceOf(bob), amount);
assertEq(token.allowance(owner, alice), 0);
}
function testTransferRevertsWhenInsufficientBalance() public {
vm.prank(alice);
vm.expectRevert(MyToken.InsufficientBalance.selector);
token.transfer(bob, 1 ether);
}
function testMint() public {
uint256 amount = 500 ether;
vm.prank(owner);
token.mint(alice, amount);
assertEq(token.balanceOf(alice), amount);
assertEq(token.totalSupply(), INITIAL_SUPPLY + amount);
}
function testMintRevertsWhenNotOwner() public {
vm.prank(alice);
vm.expectRevert("Ownable: caller is not the owner");
token.mint(alice, 1 ether);
}
function testMintRevertsWhenExceedsMaxSupply() public {
uint256 mintAmount = MAX_SUPPLY - INITIAL_SUPPLY + 1;
vm.prank(owner);
vm.expectRevert(MyToken.MaxSupplyExceeded.selector);
token.mint(alice, mintAmount);
}
}
Fuzz Testing
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "../src/Vault.sol";
contract VaultFuzzTest is Test {
Vault public vault;
function setUp() public {
vault = new Vault();
}
// Fuzz test - Foundry will generate random inputs
function testFuzzDeposit(uint256 amount) public {
// Bound the amount to reasonable values
amount = bound(amount, 1, 1000 ether);
vm.deal(address(this), amount);
vm.prank(address(this));
vault.deposit{value: amount}();
assertEq(vault.balanceOf(address(this)), amount);
assertEq(address(vault).balance, amount);
}
function testFuzzWithdraw(uint256 depositAmount, uint256 withdrawAmount) public {
depositAmount = bound(depositAmount, 1 ether, 100 ether);
withdrawAmount = bound(withdrawAmount, 0, depositAmount);
vm.deal(address(this), depositAmount);
vm.prank(address(this));
vault.deposit{value: depositAmount}();
vm.prank(address(this));
vault.withdraw(withdrawAmount);
assertEq(vault.balanceOf(address(this)), depositAmount - withdrawAmount);
}
function testFuzzTransfer(address from, address to, uint256 amount) public {
from = makeAddr("from");
to = makeAddr("to");
amount = bound(amount, 1, 1000 ether);
vm.deal(from, amount);
vm.prank(from);
vault.deposit{value: amount}();
uint256 transferAmount = bound(amount / 2, 0, amount);
vm.prank(from);
vault.transfer(to, transferAmount);
assertEq(vault.balanceOf(to), transferAmount);
assertEq(vault.balanceOf(from), amount - transferAmount);
}
function testFuzzMultiUserDeposit(
address[] memory users,
uint256[] memory amounts
) public {
users = boundArray(users, 1, 10);
amounts = boundArray(amounts, 1 ether, 100 ether);
uint256 totalDeposited = 0;
for (uint256 i = 0; i < users.length; i++) {
vm.deal(users[i], amounts[i]);
vm.prank(users[i]);
vault.deposit{value: amounts[i]}();
totalDeposited += amounts[i];
}
assertEq(address(vault).balance, totalDeposited);
}
function boundArray(uint256[] memory arr, uint256 min, uint256 max)
internal
pure
returns (uint256[] memory)
{
for (uint256 i = 0; i < arr.length; i++) {
arr[i] = bound(arr[i], min, max);
}
return arr;
}
}
Invariant Testing
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "../src/LendingPool.sol";
import "../src/Token.sol";
contract InvariantTest is Test {
LendingPool public pool;
Token public token;
address[] internal users;
function setUp() public {
token = new Token("Lending Token", "LT");
pool = new LendingPool(address(token));
// Create users
for (uint256 i = 0; i < 5; i++) {
address user = makeAddr(string(abi.encodePacked("user", i)));
users.push(user);
token.mint(user, 10_000 ether);
vm.prank(user);
token.approve(address(pool), type(uint256).max);
}
}
// Invariant: Total deposits must equal total borrows plus available liquidity
function invariant_poolBalance() public view {
uint256 totalDeposits = pool.totalDeposits();
uint256 totalBorrows = pool.totalBorrows();
uint256 availableLiquidity = token.balanceOf(address(pool));
assertEq(totalDeposits, totalBorrows + availableLiquidity);
}
// Invariant: No user should have more debt than their collateral
function invariant_userSolvency() public view {
for (uint256 i = 0; i < users.length; i++) {
uint256 collateral = pool.collateralOf(users[i]);
uint256 debt = pool.debtOf(users[i]);
// Collateral must be >= debt (simplified)
assertGe(collateral, debt);
}
}
// Invariant: Interest rate should never exceed max
function invariant_interestRateBounds() public view {
uint256 rate = pool.interestRate();
assertLe(rate, pool.MAX_INTEREST_RATE());
}
// Handler for controlled interactions
function targetContract() external view returns (address) {
return address(pool);
}
function deposit(uint256 amount) external {
amount = bound(amount, 1 ether, 100 ether);
address user = users[bound(uint256(keccak256(abi.encodePacked(block.timestamp, amount))), 0, users.length - 1)];
vm.deal(user, amount);
vm.prank(user);
pool.deposit{value: amount}();
}
function borrow(uint256 amount) external {
amount = bound(amount, 0.1 ether, 50 ether);
address user = users[bound(uint256(keccak256(abi.encodePacked(block.timestamp, amount))), 0, users.length - 1)];
vm.prank(user);
pool.borrow(amount);
}
}
Fork Testing
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
contract ForkTest is Test {
// Uniswap V2 Router on mainnet
address constant UNISWAP_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
// Fork mainnet at specific block
function setUp() public {
vm.createSelectFork(vm.envString("ETH_RPC_URL"), 18000000);
}
function testSwapOnUniswap() public {
address trader = makeAddr("trader");
uint256 amountIn = 1 ether;
// Give trader some ETH
vm.deal(trader, 10 ether);
// Get initial DAI balance
uint256 initialDaiBalance = IERC20(DAI).balanceOf(trader);
// Approve router
vm.startPrank(trader);
IERC20(WETH).approve(UNISWAP_ROUTER, amountIn);
// Swap ETH for DAI
uint256[] memory path = new uint256[](2);
path[0] = WETH;
path[1] = DAI;
IUniswapV2Router02(UNISWAP_ROUTER).swapExactETHForTokens(
0,
path,
trader,
block.timestamp + 300,
{value: amountIn}
);
vm.stopPrank();
// Check DAI balance increased
uint256 finalDaiBalance = IERC20(DAI).balanceOf(trader);
assertGt(finalDaiBalance, initialDaiBalance);
}
function testAaveDeposit() public {
address aave = 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9;
address trader = makeAddr("trader");
uint256 amount = 10 ether;
vm.deal(trader, 10 ether);
vm.startPrank(trader);
IERC20(WETH).approve(aave, amount);
// Deposit to Aave
IAaveLendingPool(aave).deposit(WETH, amount, trader, 0);
vm.stopPrank();
// Check aWETH balance
uint256 aWethBalance = IERC20(0x030bA81f1c18d280636F32af80b9AAd02Cf0854e).balanceOf(trader);
assertGt(aWethBalance, 0);
}
}
interface IERC20 {
function balanceOf(address) external view returns (uint256);
function approve(address, uint256) external returns (bool);
}
interface IUniswapV2Router02 {
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
}
interface IAaveLendingPool {
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
}
Gas Snapshot
# Run tests and generate gas snapshot
forge snapshot
# Compare with previous snapshot
forge snapshot --check
# Update snapshot
forge snapshot --update
# Output format
forge snapshot --format markdown
// gas-snapshot output
// | Contract | Method | Min | Max | Avg | Calls |
// |----------------------|---------------------------|-------|-------|-------|-------|
// | MyToken | transfer | 26432 | 28543 | 27487 | 100 |
// | MyToken | approve | 26432 | 28543 | 27487 | 100 |
// | MyToken | transferFrom | 46432 | 48543 | 47487 | 100 |
// | Vault | deposit | 46432 | 48543 | 47487 | 100 |
// | Vault | withdraw | 31432 | 33543 | 32487 | 100 |
Cheatcodes Reference
| Category | Cheatcode | Description |
|---|---|---|
| Account | vm.prank(addr) | Set msg.sender for next call |
vm.startPrank(addr) | Set msg.sender for all calls | |
vm.deal(addr, amount) | Set ETH balance | |
vm.etch(addr, code) | Set contract bytecode | |
| Time | vm.warp(timestamp) | Set block.timestamp |
vm.roll(blockNum) | Set block.number | |
| State | vm.snapshot() | Take snapshot |
vm.revertTo(id) | Revert to snapshot | |
vm.load(addr, slot) | Load storage slot | |
vm.store(addr, slot, val) | Store value to slot | |
| Expect | vm.expectRevert() | Expect revert |
vm.expectEmit() | Expect event emission | |
vm.expectCall() | Expect function call | |
| Fuzz | bound(val, min, max) | Bound fuzz input |
assume(condition) | Skip test if false | |
assertApproxEqAbs() | Approximate equality | |
| Fork | vm.createSelectFork() | Create and select fork |
vm.selectFork(id) | Select existing fork | |
vm.createFork() | Create fork without selecting |
// Cheatcode examples
contract CheatcodeExamples is Test {
function testCheatcodes() public {
// Account manipulation
address alice = makeAddr("alice");
vm.deal(alice, 100 ether);
assertEq(alice.balance, 100 ether);
// Time manipulation
vm.warp(block.timestamp + 1 days);
assertEq(block.timestamp, block.timestamp);
// Storage manipulation
address myContract = address(new MyContract());
vm.store(
myContract,
keccak256("myStorageSlot"),
bytes32(uint256(42))
);
// Expect revert
vm.expectRevert("Unauthorized");
myContract.restrictedFunction();
// Expect event
vm.expectEmit(true, true, false, true);
emit Transfer(address(0), alice, 100 ether);
token.transfer(alice, 100 ether);
}
}
Coverage Reports
# Generate coverage report
forge coverage
# Generate lcov report
forge coverage --report lcov
# Generate summary
forge coverage --summary
# Filter by contract
forge coverage --match-contract MyToken
| File | % Lines | % Statements | % Branches | % Functions |
|---|---|---|---|---|
| src/MyToken.sol | 100.00 | 100.00 | 100.00 | 100.00 |
| src/Vault.sol | 95.00 | 94.50 | 88.00 | 92.00 |
| src/LendingPool.sol | 88.00 | 87.50 | 75.00 | 85.00 |
| Total | 94.33 | 94.00 | 87.67 | 92.33 |
Comparison: Foundry vs Hardhat
| Feature | Foundry | Hardhat |
|---|---|---|
| Language | Solidity | JavaScript/TypeScript |
| Speed | 10-100x faster | Slower |
| Fuzz Testing | Native | Requires plugin |
| Invariant Testing | Native | Requires plugin |
| Gas Reporting | Built-in | Plugin |
| Coverage | Built-in | Plugin |
| Debugging | forge test -vvvv | console.log |
| Forking | Built-in | Built-in |
| Plugin System | Less mature | Very mature |
| Learning Curve | Steeper (Solidity) | Easier (JS/TS) |
| IDE Support | Good | Excellent |
| Community | Growing fast | Established |
Real-World Example: Testing Uniswap V2
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
contract UniswapV2ForkTest is Test {
IUniswapV2Factory public factory;
IUniswapV2Router02 public router;
address public WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
function setUp() public {
vm.createSelectFork(vm.envString("ETH_RPC_URL"));
factory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
}
function testCreatePair() public {
address pair = factory.createPair(WETH, DAI);
assertTrue(pair != address(0));
assertTrue(factory.getPair(WETH, DAI) == pair);
}
function testSwap() public {
address user = makeAddr("user");
uint256 amountIn = 1 ether;
vm.deal(user, 10 ether);
vm.startPrank(user);
// Approve
IERC20(WETH).approve(address(router), amountIn);
// Get amounts out
uint256[] memory path = new uint256[](2);
path[0] = WETH;
path[1] = DAI;
uint256[] memory amounts = router.getAmountsOut(amountIn, path);
uint256 amountOutMin = amounts[1] * 99 / 100; // 1% slippage
// Swap
router.swapExactETHForTokens(
amountOutMin,
path,
user,
block.timestamp + 300,
{value: amountIn}
);
vm.stopPrank();
// Verify
uint256 daiBalance = IERC20(DAI).balanceOf(user);
assertGt(daiBalance, 0);
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB) external returns (address pair);
function getPair(address tokenA, address tokenB) external view returns (address pair);
}
interface IUniswapV2Router02 {
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
}
Interview Questions
-
Why would you choose Foundry over Hardhat for a new project?
- Answer: Foundry offers 10-100x faster test execution, native fuzz and invariant testing in Solidity, built-in gas snapshots, and no JavaScript dependency. It's ideal for security-focused projects where thorough testing is critical. However, Hardhat has better plugin ecosystem and easier onboarding for JavaScript developers.
-
Explain the difference between fuzz testing and invariant testing.
- Answer: Fuzz testing provides random inputs to individual functions to find edge cases. Invariant testing defines system-wide properties that must always hold true, then uses fuzzing to find sequences of operations that break those invariants. Invariant testing is more powerful for finding complex bugs that require multiple state changes.
-
How do you handle state setup in Foundry tests?
- Answer: Foundry uses
setUp()function (called before each test),vm.prank()for impersonating addresses,vm.deal()for setting balances,vm.warp()for time manipulation, andvm.store()for direct storage manipulation. ThemakeAddr()cheatcode creates named addresses for better test readability.
- Answer: Foundry uses
Quiz Questions
-
What is the default number of fuzz runs in Foundry?
- A) 100
- B) 256
- C) 512
- D) 1000
-
Which cheatcode is used to impersonate an address?
- A)
vm.etch() - B)
vm.deal() - C)
vm.prank() - D)
vm.store()
- A)
-
What command generates a gas snapshot in Foundry?
- A)
forge snapshot - B)
forge gas - C)
forge report - D)
forge benchmark
- A)