Automated Market Makers (AMM) Mathematics: From Constant Product (xy=k) to Concentrated Liquidity
By NorwegianSpark Editorial — written with AI assistance and reviewed by the NorwegianSpark SA editorial team | Last updated: 2026-03-15
This article contains affiliate links. We may earn a commission at no extra cost to you. Full disclosure
The Constant Product Invariant: Differentials, Pricing & Slippage Mechanics
Automated Market Makers (AMMs) fundamentally transformed decentralized finance by replacing traditional central limit order books (CLOBs)—which require continuous off-chain order matching and high transaction throughput—with deterministic on-chain liquidity pools governed by mathematical bonding curves.
The seminal primitive of the AMM ecosystem is the Constant Product Market Maker (CPMM), formalized by Vitalik Buterin and popularized by Uniswap v1 and v2. A CPMM pool maintains reserve balances of two tokens, and . The protocol enforces the continuous invariant:
where remains strictly constant in the absence of fee accrual or liquidity deposits/withdrawals.
The marginal instantaneous spot price of token in terms of token is given by the negative derivative of the invariant curve:
When a trader swaps an input amount into the pool to receive an output amount (accounting for a protocol fee fraction , typically for a fee tier), the new reserve state must satisfy:
Solving algebraically for the exact output amount :
The effective execution price received by the trader is:
The divergence between the marginal spot price and the execution price constitutes Price Impact (slippage). As increases relative to the pool reserve , the execution price degrades hyperbolically. This mathematical curvature creates asymptotic resistance against capital drain, guaranteeing that an AMM pool can never be completely depleted of either asset regardless of trade size.
Impermanent Loss (Divergence Loss): Rigorous Calculus Derivation
When a Liquidity Provider (LP) deposits equal value of tokens and into a constant product pool, their capital exposure diverges from a passive buy-and-hold portfolio whenever the relative market price of the assets shifts. This opportunity cost is formally known as Impermanent Loss (or more accurately, Divergence Loss).
Let the initial reserves be at initial price . The initial value of the LP portfolio is:
Assume the external market price shifts by a ratio . Arbitrageurs will trade against the pool until the internal pool price matches . Since and :
The new total value of the LP position inside the pool is:
Conversely, if the LP had simply held the initial tokens in a wallet, the value of the passive holding portfolio would be:
The ratio of the LP position value to the holding value represents the Impermanent Loss function :
Because the geometric mean is strictly less than the arithmetic mean for all , is non-positive for all price changes. If the price doubles (), the LP suffers an impermanent loss of . If the price quadruples (), the loss is . For an LP position to be net profitable, cumulative trading fee yield must exceed the mathematical divergence loss over the holding period.
Uniswap v3 Concentrated Liquidity: Virtual Invariant Curves & Tick Spacing
While Uniswap v2 was elegant, it suffered from severe capital inefficiency: liquidity was uniformly distributed across the entire price spectrum from to . For stable pairs (like USDC/USDT) that trade in a narrow band around , over of deposited capital sat completely idle in the tails of the bonding curve.
Uniswap v3 introduced Concentrated Liquidity, allowing LPs to allocate capital within discrete, customized price intervals .
Inside the active range , the pool operates on a virtual constant product curve:
where is the Liquidity Density of the position.
The relationship between liquidity , token reserves and , and the price interval boundaries is given by:
When the spot price moves:
- If : The position is composed entirely of token .
- If : The position is composed entirely of token .
- If : The position holds an active mixture of and , earning of swap fees passing through the tick range.
By concentrating liquidity in a tight price band, an LP achieves the same fee-earning capital efficiency as an LP in Uniswap v2 depositing more capital. However, this amplification also scales impermanent loss exposure linearly within the band: if the spot price breaks out of the range, the position stops earning fees entirely and is left holding of the depreciating asset.
Tick Math & Q64.96 Fixed-Point Arithmetic in EVM Bytecode
To implement continuous virtual curves efficiently within the EVM without floating-point arithmetic hardware, Uniswap v3 discretizes the continuous price spectrum into discrete logarithmic Ticks.
The price at integer tick index is defined as:
where each tick represents a 1 basis point () price movement ().
The square root of price is represented on-chain as a 160-bit fixed-point integer in Q64.96 format (64 bits for the integer component, 96 bits for the fractional component):
To compute token swaps and tick transitions without rounding error or overflow:
- Ticks are grouped into Tick Spacings (e.g., 10 for fee tier, 60 for fee tier, 200 for fee tier).
- The pool maintains a Tick Bitmap (a 256-bit word array mapping initialized ticks) allowing the EVM opcode
BYTEand bit-shift operations to find the next initialized tick in a single execution loop step with minimum gas overhead. - When a large trade crosses an initialized tick boundary, the pool contract dynamically adds or subtracts liquidity from the global active pool accumulator, adjusting the local slope of the invariant instantaneously.
## Time-Weighted Average Price (TWAP) Oracles: Arithmetic vs. Geometric Accumulators
Decentralized applications require tamper-resistant on-chain price oracles to value collateral and execute liquidations. Reading the instantaneous spot price from an AMM pool inside a single transaction is catastrophic, as attackers can manipulate spot reserves using multi-million-dollar flash loans at zero upfront capital cost.
To eliminate flash loan price manipulation, Uniswap introduced Time-Weighted Average Price (TWAP) oracles.
In Uniswap v2, the pool maintains an arithmetic price accumulator:
The time-weighted arithmetic mean price over interval is:
In Uniswap v3, the oracle was upgraded to an on-chain Geometric Mean TWAP based on tick accumulators:
The geometric mean possesses a critical mathematical property: . Unlike arithmetic TWAPs where the quote currency choice introduces subtle pricing distortion, geometric TWAPs maintain absolute mathematical symmetry across token pairs. Manipulating a 30-minute TWAP requires an attacker to hold an artificial price imbalance across multiple consecutive blocks, subjecting them to immense arbitrage loss from external market makers.
Modern AMM Frontiers: Dynamic Fees, LVR & CoW Swaps
The frontier of decentralized market making focuses on solving Loss-Versus-Rebalancing (LVR), formalized by Tim Roughgarden and Andrea Canidio.
LVR measures the permanent structural economic loss suffered by passive AMM LPs relative to an ideal rebalanced reference portfolio due to toxic arbitrage flow. Whenever external off-chain centralized exchange prices move, latency arbitrageurs immediately execute stale-price swaps against the on-chain AMM pool, extracting value before honest retail volume arrives.
Emerging protocol designs to mitigate LVR include:
- Dynamic Fee Hooks (Uniswap v4): LPs can attach custom Solidity hook contracts to pool lifecycle events (
beforeSwap,afterSwap). Pools dynamically expand swap fees during periods of high market volatility (widening the bid-ask spread to deter toxic arbitrage) and compress fees during calm regimes to attract retail flow. - Batch Auctions & CoW Protocol (Coincidence of Wants): Swaps are collected in discrete off-chain batches and executed at a uniform clearing price, allowing peer-to-peer volume to match without paying AMM spreads and completely neutralizing frontrunning.
- Asymmetric Bonding Curves (Curve v2 & Maverick): Dynamic recalibration algorithms that autonomously shift the center of concentrated liquidity toward exponential moving averages, reducing manual LP rebalancing costs.
## Frequently asked questions
Why is Impermanent Loss called "impermanent"?
Because if the relative prices of the deposited tokens return to their original ratio when entered, the divergence loss disappears entirely, leaving the LP with their initial assets plus accumulated fees.
What happens when a Uniswap v3 position goes out of range?
The position converts 100% into the less valuable or falling asset and stops earning trading fees completely until the market spot price moves back into the specified tick interval.
How does Uniswap v3 prevent overflow in tick math?
Uniswap v3 uses fixed-point Q64.96 arithmetic and bounds the maximum tick index to [-887272, 887272], ensuring sqrtPriceX96 values safely fit within a uint160 storage word.
Related reading
- AMM sandwich attacks and toxic order flow — Understand how MEV searchers exploit AMM slippage tolerances via liquidity sandwiching.
- DeFi oracle price feeds and TWAP integration — See how AMM geometric mean TWAP oracles are integrated into money market lending contracts.
## Sources
- Uniswap v2 Core Whitepaper — Uniswap
- Uniswap v3 Core Whitepaper (Concentrated Liquidity) — Uniswap
No contributor to this article holds a professional cryptography or security credential. Every technical claim above is sourced to primary protocol documentation rather than to personal authority — follow the sources and verify anything you intend to act on.
Not financial advice. Crypto assets are volatile and can lose value. This article describes how protocols work, not what you should buy.
Content on AICryptoCoin is for informational purposes only and does not constitute financial advice. Always do your own research and consult a qualified financial advisor before making investment decisions.
Related Articles
Perpetual Futures & On-Chain Derivatives: Funding Rates, Virtual AMMs & Margin Systems
15 min
Protocol Deep DivesLiquid Staking, Restaking & Shared Security: EigenLayer, LSTs & Economic Security Pooling
15 min
Protocol Deep DivesLending Protocols & Algorithmic Debt: Collateralization, Liquidations & Oracle Dynamics
15 min