SKIP TO CONTENT
Security

Invariant

A condition that must always remain true regardless of what operations are performed on a system.

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
AMM DEXs:
  • x * y = k (constant product formula)
  • LP shares represent fair pool ownership
  • No tokens created from nothing
Staking:
  • 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 tools

Invariant 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.

Examples

  • Uniswap V2 invariant: reserves x reserves = k
  • Lending protocols: collateral >= debt x factor

See this concept in action across live DeFi protocols.

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

GET EARLY ACCESSArrow right