Why Foundry Became the Default Solidity Testing Framework
Foundry, built by Paradigm, compiles and runs tests faster than Hardhat in most benchmarks — often 10–20x faster on large codebases. Its test files are written in Solidity, not JavaScript or TypeScript, which means no context-switching and full access to low-level EVM primitives. As of 2024, the majority of new DeFi protocols publish Foundry-based test suites alongside their audits.
But fast tests and many tests are not the same as secure code. The Euler Finance hack ($197M) happened despite a large test suite. The root cause — a flawed health check function — was a logic error that unit tests never exercised. That's the gap this guide addresses.
Setting Up Foundry From Scratch
Install Foundry using foundryup:
curl -L https://foundry.paradigm.xyz | bash
foundryupInitialize a new project:
forge init my-protocol
cd my-protocolYour project structure will look like this:
my-protocol/
├── src/ # Your Solidity contracts
├── test/ # Foundry test files (.t.sol)
├── script/ # Deployment scripts
└── foundry.toml # ConfigurationWriting Your First Foundry Unit Test
Every Foundry test contract inherits from forge-std/Test.sol. Test functions must be prefixed with test. Functions prefixed with testFail are expected to revert.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20;import "forge-std/Test.sol";
import "../src/Vault.sol";contract VaultTest is Test {
Vault public vault;
address public owner = address(0xA);
address public attacker = address(0xB);function setUp() public { vm.prank(owner); vault = new Vault(); } function test_DepositIncreasesBalance() public { vm.deal(address(this), 1 ether); vault.deposit{value: 1 ether}(); assertEq(vault.balanceOf(address(this)), 1 ether); } function testFail_UnauthorizedWithdraw() public { vm.prank(attacker); vault.adminWithdraw(1 ether); // should revert }
}
Run with: forge test -vv
Foundry Fuzzing: Where It Gets Powerful
Foundry's built-in fuzzer generates random inputs for any function parameter. Replace test prefix functions with typed parameters to activate fuzzing automatically — no configuration needed.
function testFuzz_DepositAndWithdraw(uint256 amount) public {
// Bound the input to realistic values
amount = bound(amount, 1 wei, 100 ether);vm.deal(address(this), amount); vault.deposit{value: amount}(); uint256 balanceBefore = address(this).balance; vault.withdraw(amount); assertEq(address(this).balance, balanceBefore + amount);
}
By default, Foundry runs 256 fuzz iterations. Increase this in foundry.toml for critical functions:
[fuzz]
runs = 10000
seed = 0x1The fuzzer will try to find inputs that break your assertions. This catches arithmetic edge cases, boundary conditions, and unexpected reverts that static unit tests never cover.
Invariant Testing: Defining Protocol-Level Rules
Invariant tests (also called stateful fuzzing) let you define properties that must always hold — regardless of what sequence of function calls an attacker makes. This is closer to formal verification than standard fuzzing.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;import "forge-std/Test.sol";
import "../src/Vault.sol";contract VaultInvariantTest is Test {
Vault public vault;function setUp() public { vault = new Vault(); // Tell Foundry which contracts to call randomly targetContract(address(vault)); } // This invariant must ALWAYS hold function invariant_TotalAssetsMatchDeposits() public view { assertEq( address(vault).balance, vault.totalDeposited() ); } function invariant_NoUserExceedsTotalBalance() public view { assertTrue( vault.balanceOf(msg.sender) <= address(vault).balance ); }
}
Run invariant tests with: forge test --match-contract Invariant
This is where Foundry truly shines for security — the framework will generate arbitrary call sequences and try to break your invariants. A single violated invariant can expose a reentrancy bug, a balance accounting error, or a flash loan attack vector.
Fork Testing Against Live Mainnet State
Foundry's fork testing lets you test against real deployed contracts and real state. This is essential for protocols that integrate with Uniswap, Aave, Compound, or any other live protocol.
// foundry.toml
[rpc_endpoints]
mainnet = "https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY"function setUp() public {
// Fork mainnet at a specific block for reproducibility
vm.createSelectFork("mainnet", 19_500_000);
}
function test_FlashLoanAttackVector() public {
// Now you have access to real Aave pools, real token balances
// Test your protocol's behavior in realistic DeFi conditions
address aavePool = 0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2;
// ... interact with live contracts
}
Fork tests catch integration bugs that local mocks hide. If your mock ERC20 behaves differently than the real USDC contract (fee-on-transfer, non-standard return values), fork testing reveals it.
Cheatcodes: Foundry's Testing Superpower
The vm cheatcode interface gives you control over EVM state that would be impossible in production testing:
vm.prank(address)— Next call will come from this addressvm.deal(address, amount)— Set ETH balancevm.warp(timestamp)— Set block timestampvm.roll(blockNumber)— Set block numbervm.expectRevert(bytes)— Assert the next call reverts with specific errorvm.expectEmit()— Assert specific events are emittedvm.store(address, slot, value)— Write directly to storage slots
function test_TimelockBypass() public {
vault.initiateWithdraw();// Try to withdraw before timelock expires — should fail vm.expectRevert(Vault.TimelockNotExpired.selector); vault.executeWithdraw(); // Advance time past timelock period vm.warp(block.timestamp + 7 days + 1); // Now it should succeed vault.executeWithdraw();
}
Vulnerabilities Foundry Tests Commonly Miss
Foundry's testing framework is excellent, but it tests what you tell it to test. There are entire vulnerability classes that fall outside what developers naturally write test cases for:
- Access control misconfiguration — A developer writes tests for the happy path but doesn't enumerate every privileged function and test unauthorized callers systematically.
- Centralization risks — A single
ownerkey that can drain funds, freeze users, or upgrade contracts. Tests pass because the owner always behaves correctly in test environments. - Incorrect slippage or deadline parameters — Swap integrations that pass zero slippage or no deadline to DEX routers. Tests mock the router and never catch it.
- Read-only reentrancy — The attacking contract doesn't need to call back into your vault — it reads a stale price from a view function during another protocol's callback. Extremely hard to write a fuzz test for without knowing the attack pattern.
- Integer precision loss in fee calculations — Rounding errors accumulate over thousands of transactions. Standard fuzz tests with bounded inputs rarely expose this.
Integrating AI Auditing Into Your Foundry Workflow
The highest-coverage security workflow combines Foundry's dynamic testing with AI-powered static analysis. They're complementary — not redundant. Foundry tests execution paths you define. AI auditing reads every line of your source code and pattern-matches against known vulnerability signatures, logic anti-patterns, and economic attack vectors without needing test cases.
Here's how to integrate both into a CI workflow:
# .github/workflows/security.yml
name: Security Checkson: [push, pull_request]
jobs:
foundry-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: foundry-rs/foundry-toolchain@v1
- name: Run Forge Tests
run: forge test --fuzz-runs 1000 -vvv
- name: Run Invariant Tests
run: forge test --match-contract Invariant --fuzz-runs 5000AI audit runs on PR — catches what tests miss
ai-audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Submit to AI Auditor
run: |
curl -X POST https://smartcontractauditor.ai/api/audit
-F "files=@src/Vault.sol"
-F "files=@src/Token.sol"
In practice, a strong workflow looks like this: write Foundry unit and fuzz tests during development, run AI auditing on every PR to catch new code introducing access control or logic issues, and run full invariant test suites in staging before each deployment.
Real Vulnerability Example: What Each Layer Catches
Consider this flawed staking contract:
contract StakingPool {
mapping(address => uint256) public stakedAmount;
mapping(address => uint256) public rewardDebt;
uint256 public accRewardPerShare;function withdraw(uint256 amount) external { require(stakedAmount[msg.sender] >= amount); // BUG: Rewards calculated AFTER updating state stakedAmount[msg.sender] -= amount; uint256 pending = stakedAmount[msg.sender] * accRewardPerShare - rewardDebt[msg.sender]; rewardDebt[msg.sender] = stakedAmount[msg.sender] * accRewardPerShare; payable(msg.sender).transfer(pending); // Also sends principal — reentrancy possible before here }
}
- Foundry unit test: Passes if tested with a single user following normal flow
- Foundry fuzz test: May catch the reward miscalculation with extreme amounts
- Foundry invariant test: Will catch it if you define
invariant_RewardsNeverExceedPool - AI auditing: Flags the reentrancy pattern, the state-update-before-transfer ordering, and the reward calculation logic flaw immediately — without needing a test case written for it
Foundry Best Practices Summary
- Use
bound()instead ofvm.assume()to avoid fuzzer discard waste - Write at least one invariant test per core accounting property
- Always fork test against mainnet for external protocol integrations
- Separate test files by concern:
Unit.t.sol,Fuzz.t.sol,Invariant.t.sol,Fork.t.sol - Use
forge coverageto identify untested code paths — then audit those paths with AI tools - Pin fork block numbers for reproducible CI runs
SmartContractAuditor.ai detects reentrancy patterns, access control misconfigurations, integer overflow edge cases, and economic logic flaws in under 60 seconds — free to start at https://smartcontractauditor.ai. Run it alongside your Foundry suite before every deployment.