What is an Invariant?
An invariant is a property or condition that must hold true at all times within a system, regardless of the operations performed. In smart contracts, invariants define the fundamental rules that can never be violated. If an invariant breaks, something has gone critically wrong.
Why Invariants Matter
Invariants capture the essential correctness properties of protocols:
- Security Boundaries: Define what's possible vs impossible
- Economic Soundness: Ensure protocol remains solvent
- Trust Assumptions: Codify what users can rely on
Common DeFi Invariants
Lending Protocols:- Total borrows <= total supplied liquidity
- User collateral >= user debt x collateral factor
- Interest accrues correctly over time
- x * y = k (constant product formula)
- LP shares represent fair pool ownership
- No tokens created from nothing
- Total rewards <= allocation budget
- Staked balance tracks correctly across operations
Invariant Testing
Fuzz Testing: Random inputs check if invariants hold Symbolic Execution: Mathematical analysis of all paths Property-Based Testing: Define properties, generate test cases Echidna/Foundry: Popular invariant testing toolsInvariant Violations in History
Major exploits often trace to broken invariants:
- Flash loan attacks violated assumed borrowing constraints
- Reentrancy bugs violated token balance invariants
- Price oracle manipulation broke assumed price accuracy
Writing Good Invariants
Strong invariants are:
- Complete: Cover all critical properties
- Precise: No ambiguity about what must hold
- Verifiable: Can be checked programmatically
- Minimal: Express core truths without redundancy
Invariants in Code
Invariants can be expressed as assertions that verify system state:
- Total supply equals sum of all balances
- Total borrows never exceeds total liquidity
- User health factor remains above liquidation threshold
Defense in Depth
Invariants work alongside:
- Access controls
- Rate limiting
- Pause mechanisms
- Emergency stops
Each layer protects different aspects of protocol security.