How to Write Invariants for DeFi: 64 Examples
Part of our guide to smart contract audits

Quick answer. Test that balances and claims reconcile, eligible assets cover liabilities, rounding and caps follow the spec, and only authorized actors move value. Check that state transitions happen once where required and that eligible users can exit after realistic sequences of calls.
Video transcript
A good DeFi invariant tells you what must hold and when. Start by asking whether balances add up, claims are backed, and eligible users can still exit.
Pin the commit and define the scope, units and exceptions. Use an independent tally at settlement and snapshots to check what each successful action changed. At the end of the run, try the exits users are eligible to make.
In lending, add up borrower debt shares and match the sum to the market's recorded total. In an automated market maker, check that a successful swap delivers at least the promised minimum.
A pending request isn't necessarily ready to pay. In a vault with funded withdrawal escrow, track pending requests separately from claimable assets. Escrow must cover those claims, and each payment must reduce the claimable balance.
Check successful exposure increases against execution-time caps, barring written venue exceptions. For stablecoins, check mint permissions and reconcile onchain supply without assuming offchain backing. For bridges, check route finality and verify at most one successful delivery per canonical ID, like CCTP version two's destination nonce.
A passing fuzz run means no evaluated assertion failed at the configured check points. The run can still miss intermediate states or leave branches unvisited.
Read the full checklist for all sixty-four examples and when they apply, or talk to Guardian about an invariant fuzzing audit.
Invariant Categories
Learn how to write invariants with 64 checks adapted from public Guardian reports or derived from primary specs. Our Foundry invariant testing guide covers harness setup.[1, 2, 3, 4, 5, 6]
Specify scope, units, observation point and exceptions.
Pin the commit. Record supported token behavior, oracle assumptions and permitted configuration changes.
At settlement, check state invariants against independent tallies. Compare action postconditions using before-and-after snapshots; test eligible exits at run end.[7]
Count successes meeting test premises separately from reverts.
An invariant fuzzing audit tests accounting across call sequences.
Lending Protocol Invariants
Price moves or interest accrual can make healthy borrowers liquidatable.[8, 9]
Guardian's Tenor report flagged an assertion failing on valid limit-order transitions. Reconcile movements between order states.[1]
Group collateral by collateral token; supply and borrows by loan token, across markets.
In Morpho Blue, writeoffs deduct equal bad-debt amounts from aggregate borrow and supply assets, excluding repayment.
| Check | What to assert |
|---|---|
| Market liquidity | Morpho Blue: total borrow assets ≤ total supply assets. |
| Supply shares | Per market, supplier shares including fee-recipient shares sum to recorded supply shares. |
| Debt shares | Summed borrower shares equal recorded market debt shares. |
| Settled singleton custody · exact-transfer tokens | Per token, custody ≥ collateral + supplied assets − borrowed assets. |
| Health on success | After borrowing or withdrawing collateral with debt, require health at the validation price. |
| Accrual without loss | On nonnegative interest accrual alone, modeled supplier value per share does not fall. |
| Liquidation bounds | Seized collateral and repaid shares ≤ respective starting balances. |
| Immediate-writeoff designs | When liquidation exhausts collateral, clear residual debt shares. |
| Market isolation | Preselect unrelated market: balances and shares stay unchanged unless call or callbacks target it. |
| Fixed maturity | Maturity exceeds initialization timestamp, within the design's range. |
AMM Invariant Examples
Canonical Uniswap V2 input per token: max(0, post-swap balance − old reserve + output). Each adjusted balance equals 1,000 × balance − 3 × input.[10]
Baseline Markets C-03 found vault exits could understate tracked reserves by omitting funds outside the vault.[11]
Model StableSwap output with fixed rates and amplification, applying fees and rounding.[12]
| Check | What to assert |
|---|---|
| V2 swap product | Adjusted balance product ≥ old reserve product × 1,000². |
| V2 reserve update | Updated reserves equal balances; donations need not update reserves. |
| Minimum-enforcing swaps | Output meets minimum; verify net gain on exact-transfer routes without other recipient flows. |
| Position bounds | Lower tick < upper tick. |
| Tick spacing | Initialized boundaries align with the tick grid. |
| Active liquidity · post-swap tick convention | Recorded liquidity equals the sum across in-range positions. Reconcile signed tick-crossing deltas separately. |
| Liquidity round trip | Full mint/burn round trip restores global liquidity absent other liquidity changes. |
| Accrued position fees | New fees equal inside-range fee-growth delta times prior liquidity, with scaling and rounding. |
| StableSwap output | Settled output matches independent prediction within derived tolerance. |
| Baseline Value backing after vault switch or exit | Recorded reserves match the independent tally and are ≥ circulating supply × Baseline Value. |
Vault Invariant Examples
Compare each synchronous preview with successful execution under the same transaction conditions.[5]
Nashpoint's published suite tracks pending requests separately from funded withdrawal claims.[3]
Hypothetical fee-free end-of-run check: claim 30 of 50 claimable asset units. Recipient gains 30, escrow loses 30, and 20 stay claimable, with no other transfers.
For the round trip, exclude donations, strategy PnL, oracle moves, rebates and reward changes. Keep deposit/redemption rate shifts.
| Check | What to assert |
|---|---|
| Deposit preview | Shares minted ≥ previewDeposit for identical assets. |
| Mint preview | Assets charged ≤ previewMint for identical shares. |
| Withdraw preview | Shares burned ≤ previewWithdraw for identical assets. |
| Redeem preview | Assets delivered ≥ previewRedeem for identical shares. |
| Conversion rounding | Both conversions round an independently modeled rational result down. |
| Synchronous ERC-4626 maximums | Never overstate vault limits; maxDeposit and maxMint assume unlimited payer assets. |
| Share supply | Holder share balances, including fee and escrow balances, sum to recorded supply; exclude virtual offsets. |
| Neutral round trip · design property | Immediately redeem only newly minted shares; no rounding profit. |
| Escrow coverage | Escrow covers claimable assets, not necessarily pending requests. |
| Request lifecycle | Separate claims consume only claimable amounts, without double payment. |
| Matching nonzero IDs within one vault | Requests become claimable together at one exchange rate, with pro-rata partial fulfillment. |
| Async previews | Both corresponding previews revert on the async side. |
Perps and Derivatives
Test cap cuts separately from trades, including specified risk-reducing actions above cap.
GMX M-24 found the reviewed payout check used gross liquidity, omitting backing for positive-impact credits.[13]
| Check | What to assert |
|---|---|
| Open interest | By market and side, recorded exposure matches summed open sizes in consistent units. |
| Exposure cap | Successful exposure increases respect the cap at execution, except where venue policy permits. |
| Initial margin | Openings and increases meet initial margin at execution, including fees and adjustments. |
| Successful trader collateral withdrawal | Remaining open positions meet venue post-withdrawal margin rules at validation valuation. |
| Reserved collateral | Reserved USD ≤ collateral value on the same valuation basis. |
| Pool reallocation | Backing moves preserve exposure; pool allocations sum to recorded market allocation. |
| Accrued funding debits and credits | By asset and interval, reconcile using specified residuals; separate later settlements, claims and borrowing fees. |
| Payout backing | After realized payouts, eligible reserves cover earmarked credits. |
| Order locks | A locked liquidity order cannot fill before its lock period ends. |
| Closing reconciliation | Full closes remove exposure and release backing once. |
| European cash-settled option payout | Actual payout matches payoff at finalized expiry price, converted and rounded in settlement units. |
| Fully collateralized options | Cover maximum net payout at the design's collateral-check boundary. |
Stablecoin Supply and Debt
Onchain supply cannot verify offchain reserve value or custody. Circle publishes separate disclosures.[14, 15]
USDT0 I-04 found that blocklisting the zero-address sentinel could stop authorized mints in reviewed code.[16]
| Check | What to assert |
|---|---|
| Token supply | All balances, including protocol and escrow, sum to totalSupply. |
| Ordinary transfers | Successful FiatToken transfers leave totalSupply unchanged. |
| Mint authority | Restricted minting requires an active minter. |
| FiatToken mint deltas | Supply and recipient balance rise by minted amount; mint allowance falls equally. |
| FiatToken burn deltas | Supply and burner balance decrease equally; mint allowance does not replenish. |
| Pause scope | Prohibited balance and supply changes stop; permitted admin actions remain available. |
| Blocklist scope | Prohibited transfers, mints and burns fail; test approvals separately under the target version's policy. |
| Mint availability | Where policy promises availability, blocklist changes preserve authorized mints outside pauses. |
| Vat debt | In rad: debt = sum(Art × rate) + vice across collateral types. |
| Debt ceilings | Positive Vat frob draws respect collateral-type and system ceilings at execution. |
Bridge Settlement Invariants
Match causally consistent chain snapshots. Reconcile provisional credits separately from finalized balances; count each obligation or credited representation once.[6, 17]
Normalize units. USDT0 L-02 found coarser outbound precision could leave a remainder without a recovery record.[18]
Expired Fast Transfer attestations fail. Eligible replacements retain the surviving source burn and nonce.[19]
Supply includes frozen balances and fees paid to recipients, not permanent burns. Bridge mints aren't external issuance.[14, 20]
Pending mints: locked, unminted. Pending releases: burned remotely, awaiting escrow release.[21]
| Check | What to assert |
|---|---|
| Matched burn/mint snapshots | Supply plus unsettled mint obligations equals starting supply plus external issuance minus permanent burns. |
| Lock/mint · escrow-only backing | Paired escrow covers remote supply, pending mints and pending releases. |
| Token-pair isolation | ERC-20 releases debit only matching escrow pairs. |
| Message authority | Bind credit to authorized source, destination domain, asset, recipient and any route-specific caller restriction. |
| CCTP V2 replay · destination receiver | At most one successful delivery per nonce. Count any fee mint within that delivery. |
| Atomic CCTP V2 EVM receipt | Failed delivery leaves credit and nonce unchanged. |
| Finality gate | Finalized credits require the route's finality evidence. |
| Fee reconciliation | CCTP V2: recipient mint + executed fee = source burn; executed fee ≤ message maximum. |
| Decimal integrity | Shared and reconstructed destination amounts fit their types; account for hop remainders. |
| CCTP V2 EVM expiry · Arbitrum-stack: Ethereum L1 | For nonzero expirationBlock, the token messenger requires block.number < expirationBlock. |
Test the accounting your protocol depends on
If your protocol moves value across pools, queues or chains, talk to Guardian about an invariant fuzzing audit for the accounting and settlement rules those components share.
Frequently Asked Questions
Does a passing fuzz campaign prove an invariant?
No. No evaluated assertion failed at configured observation points. Intermediate states or unvisited branches can escape checks.[7]
Can an ERC-4626 preview tell me whether a deposit is allowed?
No. On a synchronous vault, previewDeposit ignores deposit limits but includes deposit fees. A quote can be valid even when deposits are disabled.[5]
Must an ERC-7540 vault let users cancel pending requests?
No. ERC-7540 leaves cancellation optional. If your vault offers it, test how a cancellation affects the pending balance and what the user actually recovers.[22]
Related reading
- AMM Vulnerabilities: Constant Product, StableSwap and CLMM
- DeFi Security: Risks and Controls by Protocol Type
- Formal Verification vs Fuzzing vs Audit: Which Do You Need?
Sources
- Guardian: Tenor Lending Protocol Audit Report, L-26
- Guardian: Poolshark Limit Audit Report
- Guardian: Nashpoint Protocol Audit Report
- Guardian: MUX Perps Audit Report
- Ethereum Improvement Proposals: ERC-4626: Tokenized Vaults
- LayerZero: LayerZero OFT Technical Reference
- Foundry: Foundry Invariant Testing Guide
- Morpho: Morpho Blue Core Lending Contract
- Morpho: Morpho Blue Formal Verification Specifications
- Uniswap: Uniswap V2 Pair Contract
- Guardian: Baseline Markets AMM Audit Report, C-03
- Curve Finance: Curve StableSwap-NG Pool Contract
- Guardian: GMX V2.2.1 Audit Report, M-24
- Circle: Circle FiatToken Design
- Circle: Circle Reserve Transparency and Assurance
- Guardian: USDT0 Tether Contracts Upgrade Audit Report, I-04
- Circle: Circle CCTP Technical Guide
- Guardian: USDT0 MultiHopComposer Audit Report, L-02
- Circle: Circle CCTP V2 Token Messenger Source
- Ethereum Improvement Proposals: ERC-20: Token Standard
- Optimism: Optimism Standard Bridge Source
- Ethereum Improvement Proposals: ERC-7540: Asynchronous ERC-4626 Tokenized Vaults
- Uniswap: Uniswap v3 Core Whitepaper
- GMX: GMX Synthetics Protocol Documentation
- Opyn: Opyn v2 Options Documentation
- Sky: Sky DSS Vat Accounting Source
- Circle: Circle CCTP V2 Message Transmitter Source
- Guardian: Loan Meme Protocol Vault Audit Report, I-03
- Antonio Viggiano: A Comparative Analysis of Smart Contract Fuzzers’ Effectiveness