What is an invariant in smart contracts?

An invariant is a property of contract state that must hold after every transaction, whoever sends it and in whatever order. For a token, no balance exceeds the total supply, and in a lending market every loan is backed by enough collateral. Hunting for an exploit means hunting for a sequence of calls that ends with one of these properties false.

Last updated . 2 minute read. By the QuillAudits Team.

What do invariants look like in real protocols?

Trail of Bits uses the token rule as its example (Trail of Bits).

Protocol Invariant What breaks it
Token No balance exceeds the total supply A mint path that skips the supply update
Vault Assets held cover what all shares can redeem Rounding in favor of the caller
Lending market An account that acts stays above its liquidation threshold A new function that skips the health check
AMM The product of the reserves doesn't fall after a swap Fee math the final check no longer matches

How does a contract enforce an invariant?

Some contracts check an invariant before a function can finish, so a violating transaction reverts. In Uniswap V2, swap takes a 0.3% fee off the input and reverts with UniswapV2: K if the product of the adjusted balances is below the product of the old reserves (ethereum.org).

A check modeled on the Uniswap V2 swap (illustrative, not audited code) ConstantProductCheck.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

contract ConstantProductCheck {
    uint256 public reserve0;
    uint256 public reserve1;

    error InvariantBroken();

    function _checkK(uint256 balance0, uint256 balance1, uint256 in0, uint256 in1) internal view {
        // Fee off the input, then both sides compared at the same 1,000x scale.
        uint256 adjusted0 = balance0 * 1000 - in0 * 3;
        uint256 adjusted1 = balance1 * 1000 - in1 * 3;
        if (adjusted0 * adjusted1 < reserve0 * reserve1 * 1000 ** 2) revert InvariantBroken();
    }
}

What happens when the check stops matching the code?

Protocol Uranium Finance
Date 28 April 2021
Chain BNB Chain
Loss over $50M across 26 pairs
What happened Uranium Finance, a Uniswap V2 fork, scaled the fee math in its swap to 10,000 but kept 1,000 in the constant product check. The check then compared numbers on different scales and passed trades that took far more than they paid in.
Sources Immunefi

How do you test invariants?

Write each invariant as a function that passes or fails, then test it three ways. Invariant testing runs random sequences of calls and checks the property after each one, fuzzing varies the inputs of a single function, and formal verification tries to prove the property for every input.

FAQ

Is an invariant the same as an assert?

No, the invariant is the property, and an assert or require is one way to check it while the code runs. Many invariants are too expensive to check on chain, such as the sum of every balance, so they live in tests instead.

What is the difference between a function-level and a system-level invariant?

Trail of Bits separates the two: a function-level invariant is about one computation, such as a fee never exceeding the amount, and a system-level invariant spans the whole state, such as a protocol staying solvent.

Sources

QuillShield is building the security layer between AI and money, so you can keep shipping between audits.

Sign-up is free, and new accounts get $50 in credit, good for up to half of an order.

  1. 1Sign up and import a repo
  2. 2See the exact price before anything is charged
  3. 3Approve it, and the audit starts