foundry-invariant-kit
v0.1.2
Published
Generate Foundry invariant and fuzz test scaffolds (ERC-20, ERC-4626, experimental lending) from a Solidity contract.
Maintainers
Readme
foundry-invariant-kit
Generate a Foundry invariant/fuzz test scaffold from a Solidity contract.
This tool generates a starting point for your own invariant testing. It is
not a guarantee of correctness or security. A green run means only that the
generated properties held for the inputs the fuzzer tried. You must review the
generated properties, fix every TODO, and add the properties that are specific
to your protocol.
Quick start
Needs Node 18+ and Foundry. Example with a plain OpenZeppelin ERC-20:
forge init mytoken && cd mytoken
forge install OpenZeppelin/openzeppelin-contracts
echo '@openzeppelin/=lib/openzeppelin-contracts/' > remappings.txt
cat > src/MyToken.sol <<'EOF'
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract MyToken is ERC20 {
constructor() ERC20("My Token", "MTK") {}
}
EOF
npx foundry-invariant-kit init --type erc20 --contract src/MyToken.sol
forge test --match-contract MyTokenInvariantTestThis writes test/invariant/MyToken/ (Handler, Invariant test, notes) and the suite passes: the handler drives mint, transfer, approve and transferFrom across three actors, and the supply, balance and allowance properties hold. With Foundry's default invariant settings the run takes about 30 seconds; the foundry.toml settings below make it faster.
Usage
# from the root of a Foundry project (forge-std installed)
npx foundry-invariant-kit init --type erc20 --contract src/MyToken.sol
npx foundry-invariant-kit init --type erc4626 --contract src/MyVault.sol --name MyVault --out test/invariant
forge test --match-contract MyVaultInvariantTestOptions: --type (required), --contract (required), --name (needed when the
file has more than one contract), --out (default test/invariant), --force
(overwrite). Output goes to <out>/<ContractName>/.
Suggested foundry.toml:
[invariant]
runs = 64
depth = 64
fail_on_revert = falseCatch runs where every handler call reverted (--require-progress, new in 0.1.2)
With fail_on_revert = false, reverted handler calls are discarded silently, so a suite whose actions all revert still passes (see foundry-rs/foundry#5726). --require-progress adds an afterInvariant() hook that sums the handler's per-action success counters and fails the run if none succeeded. Example with a pool whose functions all require(!paused):
$ npx foundry-invariant-kit init --type lending --contract src/PausedPool.sol
$ forge test --match-contract PausedPoolInvariantTest
Suite result: ok. 1 passed; 0 failed # vacuous green
$ npx foundry-invariant-kit init --type lending --contract src/PausedPool.sol --force --require-progress
$ forge test --match-contract PausedPoolInvariantTest
[FAIL: no handler action succeeded in this run: every call reverted: 0 <= 0] ...On the ERC-20 quick-start token the same flag passes. Needs a Foundry version with afterInvariant() support.
Supported types
| type | generates | properties |
|---|---|---|
| erc20 | Handler (mint via deal, transfer, approve, transferFrom; bounded, pranked actors, ghost flags), Invariant.t.sol, README note | totalSupply == sum of tracked balances; transfers never change totalSupply; transfers move exactly the amount; no balance exceeds totalSupply; allowance set/spent as expected |
| erc4626 | Handler (deposit, mint, withdraw, redeem, donate, deposit-redeem round trip, conversion checks), mock asset, Invariant.t.sol, README note | convertToShares/convertToAssets round trip never favors the user; previewDeposit <= deposit result (and previewMint/Withdraw/Redeem conservative); no shares for zero assets; deposit-then-redeem cannot profit; solvency asset.balanceOf(vault) >= previewRedeem(totalSupply); vault asset balance covers totalAssets; totalSupply == sum of tracked shares |
| lending | EXPERIMENTAL. Handler actions for any deposit/withdraw/borrow/repay(uint256) and liquidate(address[,uint256]) found, mock asset, an explicit account-health hook (collateralValue/debtValue/isHealthy in the Handler) | total borrows <= total deposits; cash + borrows cover deposits; a successful borrow/withdraw leaves the account within LTV; every tracked actor stays healthy; repay never increases debt; repay never credits more than the pool received; liquidation only succeeds on unhealthy positions |
Limitations
- The Solidity reader is a simple pattern-based parser, not a compiler. It finds the constructor, public/external functions and public state variables. Unusual syntax may be missed.
- Constructor arguments get placeholder values (
0,address(this), a name string, the mock asset for vault/lending). Unknown types are emitted asTODOand will not compile until you fix them. - ERC-20 balances are created with forge-std
deal(..., true). Tokens with non-standard storage, fees, rebasing or transfer hooks need a custom mint action and adjusted properties. - ERC-4626 suites use a plain mock asset. Fee-on-transfer assets, strategies
that move assets out of the vault, fees, and caps (
maxDepositetc.) need extra handling;invariant_assetsHeldCoverTotalAssetsassumes the vault holds its assets. - Only tracked actors are summed; add any other holders (treasury, fee recipient).
- The lending type is experimental. Its account-health hook is wired automatically only when the pool exposes
healthFactor(address)(healthy means >= 1e18), per-account getters such ascollateralOf/depositsplusdebtOf/borrowBalanceOf/debts(healthy means debt * 10000 <= collateral * LTV, with LTV fromltvBps()or--ltv-bps, default 7500), orgetUserAccountData(address)(Aave-style return order assumed). Collateral and debt are compared 1:1 in the same unit: there is no oracle, price movement or interest accrual in the harness. If none of these are found, the hook is generated as NOT CONFIGURED and the health properties pass trivially until you fill it in. - Lending properties that are still UNPROVEN (no buggy sample has made them fail yet): "total borrows never exceed total deposits", the withdraw half of "a successful borrow/withdraw stays within LTV", and liquidation succeeding on a genuinely unhealthy position (the harness has no price moves or interest, so only "liquidation is blocked on healthy positions" is validated). Treat the lending type as EXPERIMENTAL.
- Sum checks see tracked holders only. The ERC-20
totalSupply == sum of balancesand the ERC-4626totalSupply == sum of sharesinvariants (andno balance exceeds totalSupply) only look at the three actors, the test contract and the handler. Balances or shares held at any other address (fee recipients, treasuries, contracts the token calls into) are invisible to them, so a bug that moves value to an untracked address can pass, and a protocol that legitimately mints to another address will fail until you add that holder to the sum.
Development
npm test # node --test, generator tests
cd examples && ./install-deps.sh && forge test # installs pinned forge-std bd8c870 + OZ v5.1.0 into examples/lib, then runs the samples (see VALIDATION.md)The examples/ project contains safe and deliberately buggy samples; the buggy
suites are expected to fail.
Want a hand with a pre-audit review of a Solidity project? The Smart Contract Pre-Audit Review Pack is a self-review aid with a 66-item checklist, a 40-point audit-readiness scoring sheet and scope/known-issues/threat-model templates. It is not an audit and gives no security guarantee ($19, our own paid product).
License
MIT
