The constant product automated market maker (CPMM), pioneered by Alan Lu and Vitalik Buterin and popularized globally by Uniswap v1 and v2, is the foundational building block of decentralized finance. Prior to the constant product model, decentralized exchange attempts relied on traditional order books, which failed due to high transaction gas fees and low blockchain throughput. The CPMM solved this by replacing order matching with a deterministic mathematical curve, enabling continuous, autonomous liquidity for any token pair without intermediaries.
Understanding the exact mathematical derivations governing constant product pools is essential for algorithmic traders, smart contract developers, and liquidity providers seeking to optimize capital deployment and minimize execution slippage.
The Constant Product Invariant
A constant product pool maintains reserves of two distinct tokens: Token X (quantity x) and Token Y (quantity y). The pool enforces the fundamental invariant that the product of its reserves must remain constant across all trades, before accounting for liquidity provider fees:
Where k is the invariant constant. Because k is fixed, the relationship between reserves describes a rectangular hyperbola in the first quadrant of the Cartesian plane. As reserve x increases, reserve y must decrease asymptotically, ensuring that the pool can never be completely drained of either asset, regardless of how large a trade is executed.
Derivation of the Swap Output Equation with Protocol Fees
When a trader deposits an amount \Delta x of Token X into the pool, they receive an amount \Delta y of Token Y. In contemporary decentralized exchanges, a protocol fee \phi (typically 0.30%, so \phi = 0.003) is deducted from the input amount. The effective input added to the pool reserve is therefore \Delta x \cdot (1-\phi).
To preserve the invariant k after the trade:
Expanding and solving for \Delta y yields the canonical swap output equation:
This closed-form equation demonstrates that output \Delta y is strictly concave with respect to input \Delta x. As trade volume grows relative to pool reserve x, each incremental unit of Token X yields diminishing quantities of Token Y.
Marginal Spot Price versus Effective Execution Price
The marginal spot price P_{\text{spot}} of Token X in terms of Token Y is defined as the negative infinitesimal derivative of the curve:
However, no trader ever executes an infinitesimal trade. The effective execution price P_{\text{eff}} realized by a swapper is the ratio of actual output received to input supplied:
Because x + \Delta x \cdot (1-\phi) > x, the effective price P_{\text{eff}} is strictly lower than the pre-trade spot price P_{\text{spot}}. The relative difference between these two quantities defines the deterministic price impact of the trade:
Reserve Rebalancing Dynamics After a Swap
After the trade executes, the fee fraction \Delta x \cdot \phi is retained in the pool reserves, slightly increasing the invariant k from k_{\text{old}} to k_{\text{new}}:
This subtle growth in k represents the real economic yield captured by passive liquidity providers. Over time, as trade volume flows through the pool, k expands monotonically, meaning that liquidity provider shares represent claims against an increasingly large basket of underlying tokens.
Comparative Performance Across AMM Invariant Models
| Invariant Model | Mathematical Formula | Slippage Profile | Ideal Asset Pair |
|---|---|---|---|
| Constant Product (Uniswap v2) | x · y = k | Moderate across wide price spectrum | Uncorrelated pairs (ETH/USDC) |
| Constant Sum | x + y = k | Zero slippage until pool completely drains | Pegged assets (High risk of drainage) |
| Stableswap (Curve) | Hybrid: A · (x+y) + D = A·D + D^3/(4xy) | Extremely low slippage near peg | Pegged assets (USDC/USDT, stETH/ETH) |
| Weighted Pool (Balancer) | ∏ B_i^{w_i} = k | Configurable curvature based on weights | Multi-asset index funds (80/20 pools) |
Slippage Bounds and Protection in Smart Contracts
Because market conditions can shift between transaction broadcast and block inclusion, decentralized routers enforce a minimum output bound \Delta y_{\text{min}} passed as an input parameter:
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
If the realized output \Delta y < \text{amountOutMin} due to front-running or volatile pool rebalancing, the smart contract immediately reverts the transaction, protecting the trader from catastrophic slippage extraction.
ChangeNOW Non-Custodial Algorithmic Pricing
ChangeNOW incorporates these constant product derivations into its real-time multi-source routing engine. By evaluating pool depths across hundreds of decentralized exchanges simultaneously, ChangeNOW calculates the precise price impact curve for each prospective route, ensuring traders receive the optimal market rate without manually calculating slippage tolerances.
Security Checklist for Constant Product AMM Integration
- Always enforce strict positive
amountOutMinbounds derived from real-time off-chain price quotes. - Ensure contracts check
block.timestamp ≤ deadlineto prevent miners from holding transactions until market conditions become unfavorable. - Guard against fee-on-transfer tokens: always calculate actual balance deltas rather than relying on raw input parameters.
- Avoid using instantaneous
y/xpool ratios as pricing oracles; always implement Time-Weighted Average Price (TWAP) oracles. - Verify that mathematical calculations utilize checked arithmetic or safe math libraries to prevent overflow vulnerabilities.