To test a smart contract, combine five kinds of tests. Unit tests check each function’s behavior. Fuzz tests check that rules hold for random inputs. Invariant tests check that rules hold after random sequences of calls. Fork tests check integrations against real chain state. End-to-end tests check the contract through the app that uses it. Static analysis and audits sit beside these and replace none of them.
This page maps each type to the bug it catches, using one small contract. Foundry examples ran with Foundry 1.5.1 (forge-std 1.17.0, Solidity 0.8.33). If you use Hardhat, the ideas carry over, and the sections link to deeper posts with both tools where I have them.
What smart contract testing covers
Smart contracts differ from ordinary backend code in three ways that shape the testing. Deployed code usually cannot be patched. Anyone can call any public function in any order, with any input. And the code often holds money. So the question is less “does it do what the spec says” and more “can anyone make it do something the spec forbids”. The longer comparison is in Web2 vs Web3 testing.
That leads to a test mix with more emphasis on adversarial inputs and on properties than a typical web service gets.
The contract used in all examples
A vault. Users deposit an ERC-20 asset and receive shares in proportion to the vault’s total assets. Redeeming burns shares and pays out the proportional assets. Both directions round down.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IERC20 {
function balanceOf(address) external view returns (uint256);
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
}
contract Vault {
error ZeroShares();
IERC20 public immutable asset;
uint256 public totalShares;
mapping(address => uint256) public sharesOf;
constructor(IERC20 _asset) {
asset = _asset;
}
function totalAssets() public view returns (uint256) {
return asset.balanceOf(address(this));
}
function previewDeposit(uint256 assets) public view returns (uint256) {
return totalShares == 0 ? assets : (assets * totalShares) / totalAssets();
}
function previewRedeem(uint256 shares) public view returns (uint256) {
return totalShares == 0 ? 0 : (shares * totalAssets()) / totalShares;
}
function deposit(uint256 assets) external returns (uint256 shares) {
shares = previewDeposit(assets);
if (shares == 0) revert ZeroShares();
asset.transferFrom(msg.sender, address(this), assets);
sharesOf[msg.sender] += shares;
totalShares += shares;
}
function redeem(uint256 shares) external returns (uint256 assets) {
assets = previewRedeem(shares);
sharesOf[msg.sender] -= shares;
totalShares -= shares;
asset.transfer(msg.sender, assets);
}
}
The tests use a small MockToken with mint, approve, transfer and transferFrom.
Which test catches what
| Test type | Catches | Misses | Effort | Typical tool |
|---|---|---|---|---|
| Unit | Wrong logic, missing guards, wrong events | Inputs you did not think of, multi-call bugs | Low | Foundry, Hardhat |
| Fuzz | Edge-case inputs, rounding, overflow | Bugs that need a particular call order | Low to medium | Foundry, Echidna, Medusa |
| Invariant | Broken accounting across call sequences | Properties you did not write down | Medium | Foundry, Echidna, Medusa |
| Fork | Wrong assumptions about real protocols and tokens | Your own logic, future state changes | Medium | Foundry, Hardhat |
| Integration and E2E | Frontend and contract disagreeing on ABI, chain, units | Deep contract logic | High | Playwright, Hardhat or Anvil node |
| Static analysis | Known bad patterns, unchecked calls | Business logic errors | Low | Slither |
| Audit | Design flaws, economic attacks | Anything outside the scope and time | High | Human reviewers |
Unit tests
A unit test calls one function in a known state and asserts everything it should change. Start here, because every other layer builds on contracts that already behave in the simple cases.
contract VaultUnitTest is Test {
MockToken token;
Vault vault;
address alice = makeAddr("alice");
function setUp() public {
token = new MockToken();
vault = new Vault(IERC20(address(token)));
token.mint(alice, 1_000e18);
vm.prank(alice);
token.approve(address(vault), type(uint256).max);
}
function test_firstDepositMintsOneToOne() public {
vm.prank(alice);
uint256 shares = vault.deposit(100e18);
assertEq(shares, 100e18);
assertEq(vault.sharesOf(alice), 100e18);
assertEq(vault.totalAssets(), 100e18);
}
function test_cannotRedeemMoreThanOwned() public {
vm.prank(alice);
vault.deposit(100e18);
vm.prank(alice);
vm.expectRevert(stdError.arithmeticError);
vault.redeem(101e18);
}
}
Bug it catches. In August 2022 the Nomad bridge lost about $190M. Rekt’s account says that the exploit transaction called process() directly, without the message having been proved first. A negative unit test, “processing an unproven message must revert”, is the kind of check that targets that mistake. The lesson for your own suite is to write as many tests for what must fail as for what must succeed.
Reverts, events, access control and rounding each have a pattern worth following. They are in unit test patterns for Solidity. Reentrancy needs an attacker contract and is covered in testing for reentrancy. If you are starting from nothing, the automated testing setup guide shows the Hardhat toolchain and CI.
Fuzz tests
A fuzz test is a unit test with parameters. The runner calls it many times with generated values. State the rule, bound the inputs, and assert the rule.
The rule here: a deposit followed by an immediate redeem should never return more than was put in, whatever the share price is.
function testFuzz_roundTripNeverProfits(uint96 first, uint96 donation, uint96 amount) public {
first = uint96(bound(first, 1, 1_000e18));
donation = uint96(bound(donation, 0, 1_000e18));
amount = uint96(bound(amount, 1, 1_000e18));
// Seed the vault, then skew the share price with a donation.
token.mint(address(this), first);
token.approve(address(vault), first);
vault.deposit(first);
token.mint(address(vault), donation);
token.mint(alice, amount);
vm.startPrank(alice);
token.approve(address(vault), amount);
uint256 before = token.balanceOf(alice);
try vault.deposit(amount) returns (uint256 shares) {
uint256 back = vault.redeem(shares);
assertLe(back, amount, "round trip made money");
assertLe(token.balanceOf(alice), before, "balance grew");
} catch {}
vm.stopPrank();
}
Bug it catches. I changed previewDeposit to round up, so depositors receive slightly more shares than they paid for. A hand-written unit test with round numbers passes, because round numbers divide cleanly. The fuzz test failed with round trip made money: 2 > 1, a gain of one wei from a particular combination of seed, donation and amount. Rounding in the wrong direction is one of the most common arithmetic bugs in vault and AMM code, and fuzzing finds it quickly.
Fuzzing also has limits. Each run is one call, so it cannot find a bug that needs three calls in a specific order.
Invariant tests
An invariant test states what must always be true and lets the runner pick sequences of calls. You write a handler contract that exposes the calls you want explored, and invariants that Foundry checks after every call.
contract PillarInvariantTest is Test {
Vault vault;
Handler handler; // calls deposit and redeem for two actors with bounded inputs
function setUp() public {
MockToken token = new MockToken();
vault = new Vault(IERC20(address(token)));
handler = new Handler(vault, token);
targetContract(address(handler));
}
function invariant_sharesAddUp() public view {
uint256 sum;
for (uint256 i = 0; i < handler.actorsLength(); i++) {
sum += vault.sharesOf(handler.actors(i));
}
assertEq(sum, vault.totalShares());
}
function invariant_vaultCanPayEveryHolder() public view {
uint256 owed;
for (uint256 i = 0; i < handler.actorsLength(); i++) {
owed += vault.previewRedeem(vault.sharesOf(handler.actors(i)));
}
assertLe(owed, vault.totalAssets());
}
}
The handler is about thirty lines: for each action it picks an actor, bounds the amount, funds and approves, then calls the vault.
Bug it catches. I commented out totalShares -= shares in redeem. invariant_sharesAddUp failed after a deposit and a redeem. The solvency invariant kept passing in the same run, which is a reminder to write several invariants about one system. In March 2023, Euler Finance lost about $197M. Rekt describes a donateToReserves function that did not check the health of the donor’s position. Accounting properties like “every position stays healthy after any call” are what invariant tests express, across all functions at once.
Invariant testing has its own setup cost and its own ways to get things wrong. I wrote it up separately with eight invariants for a vault and the failing runs from breaking it three ways.
Fork tests
A fork test runs against a copy of real chain state. Use it to check assumptions about contracts you do not control. Here the vault takes real USDC, which is a proxy contract with its own behavior.
contract VaultForkTest is Test {
address constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
function setUp() public {
vm.createSelectFork(vm.envString("MAINNET_RPC_URL"), 19_000_000);
}
function test_vaultWorksWithRealUsdc() public {
Vault vault = new Vault(IERC20(USDC));
address alice = makeAddr("alice");
deal(USDC, alice, 1_000e6);
vm.startPrank(alice);
(bool ok,) = USDC.call(abi.encodeWithSignature("approve(address,uint256)", address(vault), 1_000e6));
require(ok);
uint256 shares = vault.deposit(1_000e6);
vault.redeem(shares);
vm.stopPrank();
assertEq(IERC20(USDC).balanceOf(alice), 1_000e6);
}
}
The vault’s minimal IERC20 has no approve, so the test calls it with a raw call. Everything else goes through the same vault code that runs against the mock, now with a token that has six decimals and a proxy in front of it.
Bug it catches. Wrong assumptions about decimals, return values or fees. A mock token with 18 decimals and no quirks can hide every one of them. The block number is pinned, because an unpinned fork gives different results over time. When it helps and when it misleads is the subject of fork testing against mainnet state.
Integration and end-to-end tests
The contract can be correct and the product still broken. The frontend can use the wrong ABI, send an amount in the wrong units, or assume a chain ID that the wallet is not on. Integration tests deploy the contracts to a local node and drive them through the same code the app uses. End-to-end tests go one step further and click through the real UI with a wallet.
Keep this layer thin. A handful of flows, such as connect, approve, deposit and redeem, is enough. Details are in integration testing web3 smart contracts and frontends, and test accounts and balances for those flows are covered in creating test data for DeFi.
Bug it catches. A deposit button that sends 1 meaning one token, which the contract reads as one wei.
Choosing the mix for your contract
You do not need every layer at the same depth for every contract. This is how I would weigh them, as a starting point and not a rule.
| Contract type | Lean on | Why |
|---|---|---|
| Token with fees or roles | Unit, fuzz | Few moving parts, arithmetic and permissions dominate |
| Vault, lending pool, AMM | Fuzz, invariant, fork | Shared accounting and external tokens produce the bugs |
| NFT mint or marketplace | Unit, integration | Limits, approvals and metadata are the failure points |
| Upgradeable proxy | Unit, upgrade tests, static analysis | Storage layout and initializers break first |
| Contract that calls other protocols | Fork, reentrancy tests | Your assumptions about their behavior are the risk |
Whichever row you are in, the order of work stays the same. Unit tests first, because they are cheap and everything else assumes the basics work. Then the layer your row names. Then the checklist below.
Static analysis, upgrades, gas and audits
These are not tests in the same sense, but they belong in the same plan.
- Static analysis such as Slither reads the code and flags known patterns: unchecked return values, state changes after external calls, missing access modifiers. It runs in seconds, so put it in CI.
- Upgrade tests matter when the contract sits behind a proxy. They check storage layout, initializer protection and that old state survives the new implementation. See testing smart contract upgrades.
- Gas tests catch regressions in cost. Gas optimization through testing covers snapshots and reports.
- NFT contracts have their own edge cases around minting, approvals and metadata, listed in testing NFT smart contracts.
- Audits bring reviewers who look at design and economic attacks, which tests rarely cover. They do not replace a test suite. Auditors work faster and find more when the repository already has one.
Tests show that the cases you thought of work. Audits and analysis look for the cases you did not.
A 10-point checklist
- Every external function has a unit test for the success path and one for each revert.
- Every privileged function has a test where an unauthorized caller is rejected.
- Every revert assertion names the error, not just “reverts”.
- Arithmetic is tested at zero, one, the maximum, and either side of every cap.
- Each rule that holds for all inputs has a fuzz test with bounded inputs.
- Each system-wide rule, such as solvency or supply conservation, is an invariant with a handler that includes every state-changing function.
- Each external call to an untrusted address has a reentrancy test with an attacker contract.
- Each integration with a live protocol or token has a fork test pinned to a block.
- A few end-to-end flows cover the contract through the frontend, on a local chain.
- Tests and static analysis run on every push, and each important test has been seen to fail once, by deleting the line it protects.
FAQ
Which test should I write first? Unit tests for the happy path and the reverts. Then add fuzz tests for any function with arithmetic, then invariants for anything that holds funds.
Is 100% line coverage enough? No. Coverage tells you which lines ran, not which behaviors were checked. A line can execute inside a test that asserts nothing about it. Use coverage to find untested code, and use the delete-the-line check to find weak tests.
Do I need Foundry, or is Hardhat enough? For unit and integration tests, either works. For fuzzing, invariants and fork tests, Foundry has them built in, and with Hardhat you reach for plugins or separate tools such as Echidna or Medusa. Many teams use Foundry for contract tests and Hardhat or Playwright for the app layer.
How much testing is enough before an audit? Enough that an auditor can run the suite, read it, and see which properties you consider important. The cost side of that decision is in how much web3 testing really costs.
Next step
Take your most important contract and fill in the checklist. Mark each of the ten points yes, partial or no, and start with the “no” at the lowest number. If you want a second pair of eyes on a test suite before an audit, see how I work with web3 teams.