We manage your security to weather the AI storm →

← Resource Hub

How to Write Invariants for DeFi: 64 Examples

By Daniel GelfandPublished 6 min read

Part of our guide to smart contract audits

How to Write Invariants for DeFi: 64 Examples

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.

Watch: How to Write Invariants for DeFi: 64 Examples 1:35
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.

CheckWhat to assert
Market liquidityMorpho Blue: total borrow assets ≤ total supply assets.
Supply sharesPer market, supplier shares including fee-recipient shares sum to recorded supply shares.
Debt sharesSummed borrower shares equal recorded market debt shares.
Settled singleton custody · exact-transfer tokensPer token, custody ≥ collateral + supplied assets − borrowed assets.
Health on successAfter borrowing or withdrawing collateral with debt, require health at the validation price.
Accrual without lossOn nonnegative interest accrual alone, modeled supplier value per share does not fall.
Liquidation boundsSeized collateral and repaid shares ≤ respective starting balances.
Immediate-writeoff designsWhen liquidation exhausts collateral, clear residual debt shares.
Market isolationPreselect unrelated market: balances and shares stay unchanged unless call or callbacks target it.
Fixed maturityMaturity 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]

CheckWhat to assert
V2 swap productAdjusted balance product ≥ old reserve product × 1,000².
V2 reserve updateUpdated reserves equal balances; donations need not update reserves.
Minimum-enforcing swapsOutput meets minimum; verify net gain on exact-transfer routes without other recipient flows.
Position boundsLower tick < upper tick.
Tick spacingInitialized boundaries align with the tick grid.
Active liquidity · post-swap tick conventionRecorded liquidity equals the sum across in-range positions. Reconcile signed tick-crossing deltas separately.
Liquidity round tripFull mint/burn round trip restores global liquidity absent other liquidity changes.
Accrued position feesNew fees equal inside-range fee-growth delta times prior liquidity, with scaling and rounding.
StableSwap outputSettled output matches independent prediction within derived tolerance.
Baseline Value backing after vault switch or exitRecorded 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.

CheckWhat to assert
Deposit previewShares minted ≥ previewDeposit for identical assets.
Mint previewAssets charged ≤ previewMint for identical shares.
Withdraw previewShares burned ≤ previewWithdraw for identical assets.
Redeem previewAssets delivered ≥ previewRedeem for identical shares.
Conversion roundingBoth conversions round an independently modeled rational result down.
Synchronous ERC-4626 maximumsNever overstate vault limits; maxDeposit and maxMint assume unlimited payer assets.
Share supplyHolder share balances, including fee and escrow balances, sum to recorded supply; exclude virtual offsets.
Neutral round trip · design propertyImmediately redeem only newly minted shares; no rounding profit.
Escrow coverageEscrow covers claimable assets, not necessarily pending requests.
Request lifecycleSeparate claims consume only claimable amounts, without double payment.
Matching nonzero IDs within one vaultRequests become claimable together at one exchange rate, with pro-rata partial fulfillment.
Async previewsBoth 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]

CheckWhat to assert
Open interestBy market and side, recorded exposure matches summed open sizes in consistent units.
Exposure capSuccessful exposure increases respect the cap at execution, except where venue policy permits.
Initial marginOpenings and increases meet initial margin at execution, including fees and adjustments.
Successful trader collateral withdrawalRemaining open positions meet venue post-withdrawal margin rules at validation valuation.
Reserved collateralReserved USD ≤ collateral value on the same valuation basis.
Pool reallocationBacking moves preserve exposure; pool allocations sum to recorded market allocation.
Accrued funding debits and creditsBy asset and interval, reconcile using specified residuals; separate later settlements, claims and borrowing fees.
Payout backingAfter realized payouts, eligible reserves cover earmarked credits.
Order locksA locked liquidity order cannot fill before its lock period ends.
Closing reconciliationFull closes remove exposure and release backing once.
European cash-settled option payoutActual payout matches payoff at finalized expiry price, converted and rounded in settlement units.
Fully collateralized optionsCover 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]

CheckWhat to assert
Token supplyAll balances, including protocol and escrow, sum to totalSupply.
Ordinary transfersSuccessful FiatToken transfers leave totalSupply unchanged.
Mint authorityRestricted minting requires an active minter.
FiatToken mint deltasSupply and recipient balance rise by minted amount; mint allowance falls equally.
FiatToken burn deltasSupply and burner balance decrease equally; mint allowance does not replenish.
Pause scopeProhibited balance and supply changes stop; permitted admin actions remain available.
Blocklist scopeProhibited transfers, mints and burns fail; test approvals separately under the target version's policy.
Mint availabilityWhere policy promises availability, blocklist changes preserve authorized mints outside pauses.
Vat debtIn rad: debt = sum(Art × rate) + vice across collateral types.
Debt ceilingsPositive 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]

CheckWhat to assert
Matched burn/mint snapshotsSupply plus unsettled mint obligations equals starting supply plus external issuance minus permanent burns.
Lock/mint · escrow-only backingPaired escrow covers remote supply, pending mints and pending releases.
Token-pair isolationERC-20 releases debit only matching escrow pairs.
Message authorityBind credit to authorized source, destination domain, asset, recipient and any route-specific caller restriction.
CCTP V2 replay · destination receiverAt most one successful delivery per nonce. Count any fee mint within that delivery.
Atomic CCTP V2 EVM receiptFailed delivery leaves credit and nonce unchanged.
Finality gateFinalized credits require the route's finality evidence.
Fee reconciliationCCTP V2: recipient mint + executed fee = source burn; executed fee ≤ message maximum.
Decimal integrityShared and reconstructed destination amounts fit their types; account for hop remainders.
CCTP V2 EVM expiry · Arbitrum-stack: Ethereum L1For 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]

Sources

  1. Guardian: Tenor Lending Protocol Audit Report, L-26
  2. Guardian: Poolshark Limit Audit Report
  3. Guardian: Nashpoint Protocol Audit Report
  4. Guardian: MUX Perps Audit Report
  5. Ethereum Improvement Proposals: ERC-4626: Tokenized Vaults
  6. LayerZero: LayerZero OFT Technical Reference
  7. Foundry: Foundry Invariant Testing Guide
  8. Morpho: Morpho Blue Core Lending Contract
  9. Morpho: Morpho Blue Formal Verification Specifications
  10. Uniswap: Uniswap V2 Pair Contract
  11. Guardian: Baseline Markets AMM Audit Report, C-03
  12. Curve Finance: Curve StableSwap-NG Pool Contract
  13. Guardian: GMX V2.2.1 Audit Report, M-24
  14. Circle: Circle FiatToken Design
  15. Circle: Circle Reserve Transparency and Assurance
  16. Guardian: USDT0 Tether Contracts Upgrade Audit Report, I-04
  17. Circle: Circle CCTP Technical Guide
  18. Guardian: USDT0 MultiHopComposer Audit Report, L-02
  19. Circle: Circle CCTP V2 Token Messenger Source
  20. Ethereum Improvement Proposals: ERC-20: Token Standard
  21. Optimism: Optimism Standard Bridge Source
  22. Ethereum Improvement Proposals: ERC-7540: Asynchronous ERC-4626 Tokenized Vaults
  23. Uniswap: Uniswap v3 Core Whitepaper
  24. GMX: GMX Synthetics Protocol Documentation
  25. Opyn: Opyn v2 Options Documentation
  26. Sky: Sky DSS Vat Accounting Source
  27. Circle: Circle CCTP V2 Message Transmitter Source
  28. Guardian: Loan Meme Protocol Vault Audit Report, I-03
  29. Antonio Viggiano: A Comparative Analysis of Smart Contract Fuzzers’ Effectiveness