SKIP TO CONTENT
Security

Invariant Testing

Testing methodology that verifies properties that must always hold regardless of transaction sequences.

What is Invariant Testing?

Invariant testing is a testing methodology that verifies properties that must always remain true about a smart contract's state, regardless of what sequence of transactions occurs. Unlike unit tests that check specific scenarios, invariant tests ensure fundamental protocol properties hold across all possible interaction sequences, catching violations that individual tests might miss.

How it Works

Invariant tests define properties that should always be true, then automatically generate random sequences of valid transactions to try breaking those properties.

The invariant testing process involves:

  1. Property Definition: Define what must always be true (e.g., total supply equals sum of balances)
  2. Handler Creation: Write functions that perform valid protocol interactions
  3. Random Sequence Generation: Fuzzer creates sequences of handler calls
  4. Invariant Checking: After each sequence, verify all invariants hold
  5. Shrinking: When violations found, minimize the failing sequence
  6. Analysis: Debug the minimal failing case to understand the vulnerability

Foundry's invariant testing and Echidna are the primary tools for Solidity invariant testing.

Practical Example

A lending protocol might define invariants like "total borrowed never exceeds total supplied" and "user cannot withdraw more than their balance." By running thousands of random interaction sequences, invariant tests might discover that a specific sequence of deposit, borrow, and interest accrual violates these properties. MakerDAO uses extensive invariant testing to ensure their collateralization invariants hold.

Why it Matters

Invariant testing catches complex multi-step vulnerabilities that individual unit tests miss. Many DeFi exploits require specific sequences of actions, exactly what invariant testing explores. Combined with fuzzing and formal verification, invariant testing provides powerful assurance that protocol fundamentals remain sound under all conditions.

Fensory evaluates protocol security practices including invariant testing coverage, helping users identify projects with comprehensive testing that validates core protocol properties.

Examples

  • MakerDAO uses invariant testing to ensure collateralization properties hold
  • Foundry invariant testing discovered vulnerabilities in lending protocol interest calculations

From definition to application. Explore real opportunities.

Track live yields, compare protocols, and build your DeFi portfolio with Fensory.

GET EARLY ACCESSArrow right