Free 30-min Web3 Consultation
Book Now
Smart Contract Security Audits
Learn More
Custom DeFi Protocol Development
Explore
Full-Stack Web3 dApp Development
View Services
Free 30-min Web3 Consultation
Book Now
Smart Contract Security Audits
Learn More
Custom DeFi Protocol Development
Explore
Full-Stack Web3 dApp Development
View Services
Free 30-min Web3 Consultation
Book Now
Smart Contract Security Audits
Learn More
Custom DeFi Protocol Development
Explore
Full-Stack Web3 dApp Development
View Services
Free 30-min Web3 Consultation
Book Now
Smart Contract Security Audits
Learn More
Custom DeFi Protocol Development
Explore
Full-Stack Web3 dApp Development
View Services
LABS
Guides

How to Explain Pool Invariants

A technical guide explaining the mathematical invariants that govern automated market makers (AMMs) like Uniswap V2, with derivations and code examples.
Chainscore © 2026
introduction
DEFI MECHANICS

Introduction to Pool Invariants

Pool invariants are the mathematical rules that govern automated market makers (AMMs), determining how liquidity pools calculate prices and manage token reserves.

In decentralized finance (DeFi), an automated market maker (AMM) replaces traditional order books with a liquidity pool—a smart contract holding reserves of two or more tokens. The pool invariant is the constant mathematical formula that defines the relationship between these reserves. The most famous example is the Constant Product Market Maker (CPMM) used by Uniswap V2, where the invariant is x * y = k. Here, x and y represent the reserve amounts of two tokens, and k is a constant that must remain unchanged by any trade, ensuring the product of the reserves is preserved.

The invariant is the core mechanism for price discovery. In a CPMM, the price of token X in terms of token Y is derived from the ratio of the reserves: Price_X = y / x. When a trader buys token X, they decrease its reserve (x), which causes the price to increase according to the invariant k. This creates the slippage effect—larger trades execute at progressively worse prices because they move the ratio further from the initial state. This simple, deterministic formula allows anyone to calculate output amounts and ensures the pool never runs out of liquidity, though reserves can become extremely imbalanced.

Beyond the constant product model, other invariants optimize for different use cases. Balancer uses a Constant Mean Market Maker (CMMM) with the invariant x^w_x * y^w_y * z^w_z = k, where assets can have customizable weights (w). Curve Finance employs a StableSwap invariant, which combines CPMM with a constant sum formula to create a "levered" curve. This design offers extremely low slippage for trades between stablecoins or pegged assets (like wBTC and renBTC) that are expected to maintain a 1:1 ratio, while still protecting against arbitrage if the peg breaks.

Understanding the invariant is crucial for liquidity providers (LPs). The formula dictates their exposure to impermanent loss—the divergence loss experienced when the price ratio of the deposited assets changes compared to simply holding them. When LPs add funds, they must deposit tokens in the exact current reserve ratio to maintain the invariant's k value. Their share of the pool is represented by LP tokens, which are minted proportionally to their contribution. The invariant ensures that fees from trades accrue fairly to all LPs based on this share.

For developers, interacting with a pool's invariant is done through the smart contract. A typical swap function will calculate the required output using the invariant, deduct a fee, and then enforce that the new reserves satisfy the constant. For example, a simplified Solidity check for a CPMM swap might look like:

solidity
require((reserveX - amountOut) * (reserveY + amountIn) >= reserveX * reserveY);

This ensures the product k does not decrease after the trade and fees. Auditing this logic is fundamental to pool security.

In summary, the pool invariant is the non-negotiable rulebook for an AMM. It defines everything from pricing and slippage to LP rewards and protocol fees. When analyzing any DeFi pool—whether for trading, providing liquidity, or building on top—the first question should always be: what is its invariant? This understanding reveals the pool's behavior, risks, and optimal use cases in the broader DeFi ecosystem.

prerequisites
PREREQUISITES

How to Explain Pool Invariants

Understanding the mathematical rules that govern automated market makers (AMMs) is essential for developers building or interacting with DeFi protocols.

A pool invariant is a mathematical equation that defines the relationship between the assets in a liquidity pool. It is the core rule that ensures the pool's value is preserved during trades, regardless of price fluctuations. The most famous example is the Constant Product Formula, x * y = k, used by Uniswap V2. Here, x and y represent the reserves of two tokens, and k is a constant. Any trade must change the reserves in a way that the product k remains unchanged, which automatically determines the execution price.

To explain invariants effectively, you must distinguish between the formula's state and its mechanism. The state is the current k value, a snapshot of pool liquidity. The mechanism is the smart contract logic that enforces the rule for every swap, mint, and burn. For instance, when a user swaps token A for token B, the contract calculates the required output using the invariant, ensuring (x + Δx) * (y - Δy) = k. This calculation inherently creates slippage, as larger trades move the price along the curve defined by the invariant.

Beyond constant product, different AMM designs use other invariants optimized for specific use cases. Curve Finance pools for stablecoin pairs use a StableSwap invariant that combines constant product with a constant sum formula, creating a flatter curve within a price range to reduce slippage for pegged assets. Balancer pools generalize to multiple assets with a Constant Mean Invariant, like x^w_x * y^w_y * z^w_z = k, where w represents each asset's weight. Each invariant makes a trade-off between capital efficiency, slippage, and impermanent loss.

When discussing invariants, always ground the explanation in concrete outcomes for users and liquidity providers (LPs). The invariant directly determines: the price impact of a trade, the impermanent loss experienced by LPs when prices diverge, and the pool's arbitrage resistance. A change in k only occurs when liquidity is added or removed (minting/burning LP tokens). This is a critical point: trades rebalance the pool along the curve, while liquidity events shift the entire curve, resetting the constant.

For a practical explanation, walk through a simple code snippet. The core swap function in a constant product AMM can be distilled to a few lines of logic that enforce the invariant. This demonstrates how the abstract math translates into enforceable blockchain code. Understanding this bridge between theory and implementation is key for developers auditing, forking, or designing new AMMs.

key-concepts-text
AMM FUNDAMENTALS

Core Concepts: The Constant Product Invariant

The constant product formula is the mathematical engine behind automated market makers like Uniswap V2. This guide explains how it enables decentralized trading without order books.

Automated Market Makers (AMMs) like Uniswap use a simple mathematical rule, the constant product invariant, to price assets and manage liquidity. The core formula is x * y = k, where x and y represent the reserves of two tokens in a pool (e.g., ETH and DAI), and k is a constant. This rule ensures that the product of the two token reserves always remains the same, regardless of trades. The price of one token in terms of the other is derived from the ratio of the reserves (price = y / x). As traders buy one token, its reserve decreases, causing its price to increase non-linearly according to the curve defined by the invariant.

The constant product model creates a predictable slippage curve. For a large trade relative to the pool size, the price impact is significant because the formula must maintain k. This is a core trade-off: deeper liquidity (a larger k) reduces slippage for traders. The formula is implemented directly in the pool's smart contract. Here's a simplified view of the pricing logic in Solidity:

solidity
function getOutputAmount(uint inputAmount, uint inputReserve, uint outputReserve) internal pure returns (uint) {
    uint inputAmountWithFee = inputAmount * 997; // 0.3% fee
    uint numerator = inputAmountWithFee * outputReserve;
    uint denominator = (inputReserve * 1000) + inputAmountWithFee;
    return numerator / denominator;
}

This function calculates how much outputReserve token a user receives for a given inputAmount, after deducting a 0.3% fee, while preserving the k constant.

Understanding this invariant is crucial for liquidity providers (LPs). When an LP deposits an equal value of both tokens, they receive liquidity provider tokens representing their share of the pool. Their share of the fees is proportional to this stake. However, LPs are exposed to impermanent loss, which occurs when the price ratio of the deposited assets changes compared to when they were deposited. The constant product curve means LPs effectively sell the appreciating asset and buy the depreciating one as arbitrageurs rebalance the pool to match the external market price. This loss is 'impermanent' because it is only realized if the LP withdraws while the prices are diverged.

derivation-and-math
CONSTANT PRODUCT AMM

Deriving the Swap Formula

This guide explains the mathematical invariant that governs token swaps in Uniswap V2-style automated market makers.

At the core of a constant product automated market maker (AMM) like Uniswap V2 is a simple but powerful formula: x * y = k. Here, x and y represent the reserves of two tokens in a liquidity pool, and k is a constant. This invariant must hold true before and after every swap. The product of the two token reserves is constant, meaning if you increase one reserve by buying that token, you must decrease the other reserve proportionally to keep k unchanged. This relationship creates the price curve and determines the execution price for any given trade size.

To derive the swap output, we start with the invariant. Let's say a trader wants to swap Δx amount of token X for some amount Δy of token Y. After the swap, the new reserves will be (x + Δx) for token X and (y - Δy) for token Y. The invariant requires that (x + Δx) * (y - Δy) = k. Since k is also equal to the initial product x * y, we can set up the equation: (x + Δx) * (y - Δy) = x * y. Solving this for Δy gives us the exact amount of token Y the trader will receive.

Expanding the equation: x*y - x*Δy + Δx*y - Δx*Δy = x*y. The x*y terms cancel out. We are left with -x*Δy + Δx*y - Δx*Δy = 0. Rearranging to solve for Δy, we get Δy = (Δx * y) / (x + Δx). This is the fundamental swap formula for a constant product AMM. The output Δy depends on the input amount Δx and the current pool reserves. Notice the formula includes the (x + Δx) term in the denominator, which introduces the price impact—the larger your trade relative to the pool's liquidity, the worse the effective exchange rate becomes.

In practice, AMMs apply a fee, typically 0.3%, to the input amount. The fee is deducted before the swap calculation, so the formula becomes Δy = (Δx * (1 - fee) * y) / (x + Δx * (1 - fee)). For a 0.3% fee, (1 - fee) is 0.997. This fee is added to the pool's reserves, incrementally increasing the value of k and rewarding liquidity providers. Understanding this derivation is essential for predicting trade outcomes, calculating slippage, and designing efficient trading strategies on decentralized exchanges.

invariant-variants
BEYOND CONSTANT PRODUCT

Other AMM Invariant Models

While the x*y=k constant product formula is foundational, modern AMMs use specialized invariants for different assets and use cases.

CORE MODELS

Comparison of AMM Invariant Functions

A technical comparison of the mathematical functions that define liquidity pool behavior in major AMM protocols.

Invariant FunctionMathematical FormulaPrimary Use CaseImpermanent Loss ProfileExample Protocols

Constant Product (Uniswap V2)

x * y = k

General-purpose token pairs

High for volatile pairs

Uniswap V2, SushiSwap

Constant Sum (StableSwap)

x + y = k

Stablecoin/pegged asset pairs

Low (near 1:1 assets)

Curve Finance (basic pool)

StableSwap Invariant (Curve)

A * (x + y) + D = A * D^n + D^{n+1}/(x * y)

Low-slippage stablecoin swaps

Very low

Curve (2pool, 3pool)

Concentrated Liquidity (Uniswap V3)

x * y = k (within a price range)

Capital-efficient custom ranges

Variable (depends on range)

Uniswap V3

Weighted Geometric Mean (Balancer)

∏ (B_i)^{w_i} = k

Multi-token pools, custom weights

Variable (depends on weights)

Balancer V2

dYdX / Perpetual Invariant

Designed for perpetual futures

Perpetual swap funding rates

Not applicable (derivatives)

dYdX, Perpetual Protocol

Liquidity Book (Trader Joe)

L = √(x * y) (bin-based)

Zero-slippage at discrete ticks

Predictable within bins

Trader Joe V2.1

code-implementation
TUTORIAL

Implementing the Invariant in Code

A practical guide to translating the constant product formula into executable smart contract logic for automated market makers.

The core of a constant product AMM like Uniswap V2 is the invariant x * y = k, where x and y are the reserves of two tokens and k is a constant. In a smart contract, this formula is not just a mathematical rule but the enforcement mechanism for every swap. The contract must ensure that after any trade, the product of the new reserves is equal to or greater than the previous k. This check prevents the pool from being drained and defines the swap's price impact.

To implement this, you start by storing the reserve amounts for each token. When a user requests to swap Δx amount of token A for token B, you calculate the output amount Δy the user should receive. The calculation solves for the new y reserve given the new x reserve: (x + Δx) * (y - Δy) = k. Rearranged, the output is Δy = y - (k / (x + Δx)). The contract must then verify that Δy is positive and that the calculated amount respects a minimum output limit set by the user to protect against front-running.

A critical step is handling fees. Most AMMs deduct a protocol fee (e.g., 0.3%) from the input amount before applying the invariant. For an input Δx, the amount actually added to the pool is Δx * (1 - fee). The fee is kept in the pool, slightly increasing k for each trade and rewarding liquidity providers. The code must perform this adjustment precisely to avoid rounding errors, which is why Solidity libraries like FixedPoint or the use of uint256 with careful multiplication/division order are essential.

Here is a simplified Solidity function skeleton demonstrating the swap logic:

solidity
function swap(uint amountIn, uint minAmountOut) external returns (uint amountOut) {
    (uint reserveX, uint reserveY) = getReserves();
    uint amountInWithFee = amountIn * 997 / 1000; // 0.3% fee
    uint newReserveX = reserveX + amountInWithFee;
    uint newReserveY = reserveY * reserveX / newReserveX; // Derived from k = x*y
    amountOut = reserveY - newReserveY;
    require(amountOut >= minAmountOut, "Insufficient output");
    updateReserves(newReserveX, newReserveY);
}

This code shows the fee deduction, the invariant calculation using integer math, and the crucial safety check.

Finally, after calculating and validating the swap, the contract must update the stored reserves and transfer tokens. It must also emit an event logging the trade details. For production use, you would integrate this core math into a well-audited contract architecture that includes reentrancy guards, access controls, and a robust oracle system like Uniswap's time-weighted average price (TWAP). The invariant is the mathematical heart, but its correct and secure implementation depends on the surrounding smart contract infrastructure.

POOL INVARIANTS

Common Mistakes and Edge Cases

Understanding the core mathematical rules of liquidity pools is essential for developers. This section addresses frequent misunderstandings and subtle bugs related to constant product and other invariant formulas.

The 'K' invariant error occurs when a swap calculation would violate the pool's constant product formula x * y = k. This is a protective check by the AMM contract. Common causes include:

  • Rounding errors in your math: Off-chain calculations using floating-point numbers can produce a result that, when converted to integer amounts on-chain, breaks the invariant. Always perform calculations using the same integer math as the smart contract.
  • Insufficient liquidity: The pool simply doesn't have enough of the output token to fulfill your requested amount at the current price. The invariant must hold before and after the swap.
  • Slippage tolerance too tight: If your slippage parameter is lower than the natural price impact of the trade, the transaction will revert. The contract verifies that (x_new * y_new) >= k after the swap.

Fix: Use the pool's own quote or getAmountOut functions for calculations, and ensure your slippage tolerance accounts for reasonable price movement.

POOL INVARIANTS

Frequently Asked Questions

Common developer questions about the mathematical rules that govern automated market makers and liquidity pools.

A pool invariant is a mathematical constant derived from the quantities of assets in a liquidity pool. It is the core equation that an Automated Market Maker (AMM) must maintain to determine prices and execute swaps without an order book. The most common is the Constant Product Formula x * y = k, used by Uniswap V2 and others.

This invariant ensures that for any trade, the product of the reserve amounts remains constant (minus fees). It's fundamental because:

  • Defines the price curve: The formula Price of X in terms of Y = y / x is derived from it.
  • Enforces liquidity: The pool can never be fully drained of a single asset, as k must stay positive.
  • Guarantees path independence: The final state depends only on net amounts, not the order of trades.
conclusion
KEY TAKEAWAYS

Conclusion and Next Steps

Understanding pool invariants is fundamental to designing and interacting with automated market makers (AMMs). This guide has covered the core mathematical models and their practical implications.

The constant product invariant (x * y = k) is the foundation for decentralized exchanges like Uniswap V2. Its key property is that liquidity is spread across all prices, preventing the pool from ever being fully drained. This model is simple and robust but suffers from high slippage for large trades and inefficient capital allocation. In practice, this means a pool with 1,000 ETH and 3,000,000 USDC will always maintain a product of 3,000,000,000, but the price impact of swapping 100 ETH will be significant.

Advanced models like the constant sum invariant (for stablecoin pairs), Stableswap/Curve's invariant (a hybrid for pegged assets), and Uniswap V3's concentrated liquidity address specific limitations. The Stableswap invariant, for example, approximates a constant sum near the peg to minimize slippage for like-valued assets, then curves outward to a constant product to protect against de-pegs. Uniswap V3 allows liquidity providers to concentrate capital within custom price ranges, dramatically increasing capital efficiency but introducing more complex management requirements.

For developers, the next step is implementation. Start by forking and studying the core swap, mint, and burn functions in the Uniswap V2 Core contracts. Pay close attention to how the constant product formula is applied to calculate output amounts and how the invariant k is preserved before and after each swap (minus fees). For concentrated liquidity, analyze the NonfungiblePositionManager in Uniswap V3 Periphery to understand how discrete liquidity positions are managed.

To deepen your research, explore academic papers and formal analyses. Vitalik Buterin's original blog post on constant product markets provides foundational theory. For concentrated liquidity, the Uniswap V3 whitepaper details the mathematics behind the L = √x * √y liquidity abstraction. Monitoring real-time data on platforms like Dune Analytics for metrics like impermanent loss, fee accrual, and capital efficiency across different invariant models is crucial for informed protocol design.

Finally, apply this knowledge by building. Create a simple constant product pool in a test environment, simulate trades, and observe the invariant. Then, experiment with a custom bonding curve or a basic implementation of concentrated liquidity. Understanding these invariants is not just academic; it's essential for auditing DeFi protocols, designing new AMMs, and making informed decisions as a liquidity provider in an increasingly complex ecosystem.