Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Glossary

Constant Product Formula (x * y = k)

The Constant Product Market Maker (CPMM) formula is a mathematical invariant where the product of two token reserves in a liquidity pool (x * y) must equal a constant (k), determining asset prices algorithmically.
Chainscore © 2026
definition
DEFINITION

What is the Constant Product Formula (x * y = k)?

The foundational mathematical model governing liquidity in automated market makers (AMMs).

The Constant Product Formula, expressed as x * y = k, is the core algorithm that determines asset pricing and liquidity in an automated market maker (AMM) pool, most famously used by Uniswap v2. In this equation, x and y represent the reserves of two different tokens in the pool, and k is a constant product that must remain unchanged by any trade. This invariant ensures that as the quantity of one token in the pool decreases (is purchased), the quantity of the other must increase (is sold) in a hyperbolic relationship, which automatically sets the exchange rate based on the ratio of the reserves.

The formula's primary function is to provide continuous liquidity without requiring traditional order books. When a trader swaps token A for token B, they deposit A into the pool and withdraw B, altering the reserve ratio. The new price is calculated to satisfy (x + Δx) * (y - Δy) = k. This mechanism introduces slippage: the larger the trade relative to the pool's liquidity, the greater the price impact, as the change in reserves moves the price further along the curve. The constant k only changes when liquidity providers add or remove funds from the pool, scaling the curve proportionally.

While elegant, the basic constant product model has limitations, notably impermanent loss, where liquidity providers can suffer losses relative to simply holding the assets due to price divergence. It also assumes trading occurs along a smooth curve, which can be exploited through large trades. Despite this, its simplicity and permissionless nature made it revolutionary. Variations like the Constant Sum Formula (for stablecoins) or Curve's StableSwap invariant have since been developed to optimize for specific asset pairs, but x * y = k remains the foundational model for generalized decentralized trading.

how-it-works
AUTOMATED MARKET MAKER MECHANICS

How the Constant Product Formula Works

An explanation of the foundational mathematical model used by decentralized exchanges like Uniswap to provide liquidity and determine asset prices algorithmically.

The Constant Product Formula is the core algorithm governing many Automated Market Makers (AMMs), most famously Uniswap v2, which maintains a fixed product of the reserves of two assets in a liquidity pool. Expressed as x * y = k, where x and y represent the quantities of two tokens (e.g., ETH and DAI) and k is a constant, the formula ensures that any trade must change the reserves in a way that keeps their product unchanged. This creates an inverse relationship between the two assets: as the quantity of one token in the pool decreases (bought by a trader), its price increases relative to the other, a mechanism known as bonding curve pricing.

The formula's primary function is to provide continuous liquidity and a deterministic price for trades without relying on an order book. When a user swaps Δx amount of token A for token B, the pool calculates the corresponding output Δy such that (x + Δx) * (y - Δy) = k. This calculation inherently introduces slippage—the difference between the expected and executed price—which increases with the size of the trade relative to the pool's liquidity. The liquidity depth, determined by the size of k, directly impacts this slippage; larger pools with more capital can support larger trades with less price impact.

A critical property of this model is that the pool can never be fully depleted of either asset, as the required amount of one token to drain the other approaches infinity. However, it also leads to impermanent loss for liquidity providers (LPs). When the market price of the two assets diverges from the pool's ratio, LPs are exposed to a loss relative to simply holding the assets, as the automated rebalancing via the constant product formula sells the appreciating asset and buys the depreciating one. This is the fundamental trade-off for earning trading fees.

While elegant in its simplicity, the basic x * y = k model has limitations, such as high slippage for large trades and inefficient capital allocation across all price ranges. Newer AMM designs, like Uniswap v3's concentrated liquidity, build upon this foundation by allowing LPs to allocate capital within specific price ranges, effectively making k a variable within those bounds to provide greater capital efficiency while still relying on the constant product invariant as the underlying engine for price discovery within the active tick.

key-features
MECHANICS

Key Features of the CPMM Model

The Constant Product Market Maker (CPMM) model, defined by the invariant formula x * y = k, is the foundational algorithm for most decentralized exchanges. Its core features create predictable, automated liquidity.

01

The Invariant Formula

The Constant Product Formula (x * y = k) is the core mathematical rule governing the CPMM. It states that the product of the quantities of two assets in a liquidity pool (x and y) must always equal a constant (k). This invariant ensures that as one asset is purchased from the pool, the price of the other adjusts automatically to maintain the constant product, creating a continuous pricing curve.

02

Automated Price Discovery

Prices are not set by an order book but are derived directly from the pool's reserves. The spot price for swapping asset X for asset Y is given by the ratio of their reserves (y / x). As trades are executed, the reserves change, causing the price to move along a predictable curve, ensuring the pool always has a price and liquidity.

03

Impermanent Loss Mechanism

A critical consequence for liquidity providers (LPs). Impermanent Loss occurs when the price ratio of the pooled assets changes after deposit. LPs end up with a portfolio value less than if they had simply held the assets, due to the pool's rebalancing via arbitrage. The loss is 'impermanent' if prices return to the original ratio.

04

Slippage & Price Impact

Large trades cause significant price impact because they move the pool's reserves substantially along the x*y=k curve. This results in slippage—the difference between the expected and executed price. The larger the trade relative to the pool's liquidity, the higher the slippage, protecting the pool from being drained in a single transaction.

05

Arbitrage Incentive

The CPMM model relies on external arbitrageurs to correct price deviations. If the pool's price differs from the broader market (e.g., on centralized exchanges), arbitrageurs profit by trading against the pool until its price aligns. This mechanism is essential for keeping DEX prices accurate and is a primary source of fees for LPs.

06

Liquidity Provider (LP) Tokens

When users deposit assets into a CPMM pool, they receive LP tokens representing their proportional share of the pool. These tokens are fungible, tradeable, and accrue trading fees. To withdraw their underlying assets plus fees, LPs must burn their LP tokens, redeeming their share of the updated reserves.

visual-explainer
AUTOMATED MARKET MAKER MECHANICS

Visualizing the Constant Product Curve

A geometric exploration of the foundational formula governing liquidity pools in decentralized exchanges.

The Constant Product Curve is the graphical representation of the automated market maker (AMM) formula x * y = k, where x and y represent the reserves of two assets in a liquidity pool, and k is a constant product. This relationship creates a hyperbolic curve that visually defines all possible exchange rates between the two tokens. The curve's fundamental property is that any trade must move the reserve point along this line, ensuring the product k remains unchanged, which in turn dictates the price impact of each transaction.

The curve's shape is non-linear and demonstrates infinite liquidity. As the quantity of one token in the pool approaches zero, the price of that token, represented by the slope of the curve's tangent line, approaches infinity. This ensures the pool never runs completely dry of either asset. The steepness of the curve at any given point illustrates slippage: large trades cause significant movement along the curve, resulting in a worse effective price for the trader compared to the initial spot price.

Visualizing this curve clarifies key AMM concepts. The price is determined by the ratio of the reserves (price = y / x). Adding or removing liquidity shifts the entire curve outward or inward, increasing or decreasing k but maintaining the same reserve ratio and thus the same price. This is why providing liquidity is often called "staking on a curve." The visualization starkly contrasts with order book models, which use discrete price levels, by showing a continuous spectrum of prices determined solely by pool composition.

In practice, the constant product curve is the engine for popular decentralized exchanges like Uniswap V2. Its simplicity and deterministic pricing provide predictable, on-chain liquidity without intermediaries. However, the visualization also reveals its primary limitation: significant capital inefficiency for stable asset pairs (like USDC/DAI), as large portions of the curve represent prices far from the intended 1:1 peg, leading to high slippage. This inefficiency spurred the development of concentrated liquidity and other curve types.

examples
IMPLEMENTATIONS

Protocols Using the Constant Product Formula

The Constant Product Formula, expressed as x * y = k, is the foundational automated market maker (AMM) model. These protocols use it to facilitate decentralized token swaps without order books.

02

PancakeSwap V2

A leading Constant Product AMM on the BNB Chain, optimizing for lower fees and higher throughput.

  • Chain Specific: Built for the BNB Smart Chain's performance characteristics.
  • Syrup Pools: Added yield farming incentives atop core AMM functionality.
  • Fee Model: Typically uses a 0.25% trading fee, with a portion used for token buyback and burn.
03

SushiSwap

A community-owned fork of Uniswap V2 that introduced a governance token (SUSHI) and a sustainable revenue model for liquidity providers.

  • Key Differentiator: The xSushi model directs 0.05% of all swap fees to SUSHI stakers.
  • Multi-chain: Deployed across Ethereum, Arbitrum, Polygon, and other Layer 2 networks.
  • Evolution: Has expanded beyond the basic CPMM into a full DeFi suite.
05

Curve Finance

Modifies the Constant Product Formula with a StableSwap invariant optimized for low-slippage swaps between pegged assets (e.g., stablecoins, wrapped assets).

  • Hybrid Invariant: Combines the Constant Product curve with a constant sum curve, creating a "flatter" region near parity.
  • Specialization: Extremely capital-efficient for like-kind assets but uses the standard CPMM for all other trades.
  • veTokenomics: Pioneered the vote-escrow model for governance and fee distribution.
06

Trader Joe v1 (Avalanche)

The native Constant Product AMM and liquidity hub on the Avalanche blockchain.

  • Chain Native: Designed for Avalanche's sub-second finality and low costs.
  • Liquidity Book: While v1 used the standard CPMM, its v2 introduced an innovative discrete liquidity bin model.
  • Growth Engine: Combined swaps, lending, and farming into a single protocol interface.
advantages
KEY PROPERTIES

Advantages of the Constant Product Model

The Constant Product Formula, expressed as x * y = k, underpins the most common type of automated market maker (AMM). Its design yields several fundamental advantages for decentralized trading.

01

Guaranteed Liquidity

The formula ensures a pool always has liquidity for trades, as the product of the two reserve quantities (x * y) must remain constant (k). This prevents the pool from being fully drained of either asset, enabling continuous trading. The price adjusts algorithmically based on the changing ratio of reserves.

02

Simplicity & Predictability

The mechanism is mathematically straightforward, making it easy for developers to implement and for users to audit. Price impact for a given trade size is deterministic and can be calculated precisely before execution using the formula: Δy = (Δx * y) / (x + Δx). This transparency is a core tenet of DeFi.

03

Permissionless Market Creation

Anyone can create a trading pair for any two ERC-20 tokens by depositing an initial seed of both assets. This eliminates the need for centralized listing processes or order books, enabling the rapid emergence of long-tail asset markets that would be illiquid or non-existent on traditional exchanges.

05

Composable Foundation

The constant product function serves as a primitive that other DeFi protocols can integrate and build upon. It is used within lending protocols for liquidations, by aggregators for routing, and in more complex AMM designs like concentrated liquidity (Uniswap V3), which segments the curve into customizable price ranges.

06

Incentive Alignment for LPs

Liquidity providers (LPs) earn fees from every trade, proportional to their share of the pool. The constant product model creates a predictable, automated fee structure. However, LPs are exposed to impermanent loss, which occurs when the price ratio of the deposited assets diverges from the ratio at deposit.

limitations-considerations
CONSTANT PRODUCT FORMULA

Limitations and Considerations

While foundational to Automated Market Makers (AMMs), the constant product formula (x * y = k) has inherent trade-offs and constraints that impact liquidity providers and traders.

01

Impermanent Loss (Divergence Loss)

Liquidity providers face impermanent loss when the price of the pooled assets diverges from the price at deposit. This is an opportunity cost, not a realized loss, but it can become permanent if the price never returns to its original ratio. The loss is caused by the AMM's rebalancing mechanism, which sells the appreciating asset and buys the depreciating one to maintain the constant product k. Loss magnitude increases with higher price volatility.

02

Slippage and Price Impact

Large trades cause significant price impact because each unit traded moves the price along the bonding curve. The formula dictates that price = y/x. For a trade size Δx, the price received deteriorates non-linearly. This makes the model inefficient for large orders relative to pool depth, often requiring traders to split transactions or accept high slippage. Slippage is a direct function of the trade size and the liquidity depth (the value of k).

03

Capital Inefficiency

Liquidity is distributed uniformly along the entire price curve (from 0 to ∞), but most trading activity occurs around the current market price. This means a significant portion of capital is reserved for theoretically extreme prices, where it rarely gets utilized. Compared to order book models or concentrated liquidity AMMs, the classic constant product formula has lower capital efficiency, requiring more total value locked (TVL) to achieve the same level of liquidity near the market price.

04

Oracle Vulnerability & Manipulation

AMMs using this formula provide a native price feed, but these on-chain oracles are vulnerable to manipulation. A flash loan attack can artificially move the price in a low-liquidity pool with a large, temporary trade, skewing the oracle price for other protocols that rely on it (e.g., lending platforms). The cost of manipulation is roughly proportional to the square root of the liquidity (√k), making larger pools more secure but not immune.

05

Static Fee Model

Most implementations apply a fixed fee (e.g., 0.3%) on all trades, which is added to the liquidity pool, increasing k. This model does not dynamically adjust for market volatility or network congestion. During periods of high volatility, the static fee may not adequately compensate LPs for increased impermanent loss risk. It also doesn't optimize for maximum fee revenue versus volume, a trade-off explored by dynamic fee AMMs.

06

Comparison to Other AMM Curves

The constant product curve is one type of bonding curve. Key alternatives include:

  • Constant Sum (x + y = k): Zero slippage but vulnerable to depletion.
  • StableSwap/Curve (x * y = k * (x + y)^n): Hybrid curve for stablecoin pairs, minimizing slippage near parity.
  • Concentrated Liquidity (Uniswap v3): Allows LPs to allocate capital to specific price ranges, dramatically improving capital efficiency over the constant product baseline.
INVARIANT FUNCTION COMPARISON

Comparison with Other AMM Invariants

A technical comparison of the Constant Product formula against other common Automated Market Maker bonding curves, highlighting key trade-offs in capital efficiency, price impact, and liquidity provision.

Invariant / FeatureConstant Product (x * y = k)Constant Sum (x + y = k)StableSwap / Curve (x * y = k) + (x + y = k)Concentrated Liquidity (Uniswap v3)

Primary Invariant Formula

x * y = k

x + y = k

χ * D^(n+1) / (Π x_i) + (Σ x_i) = χ * D^n + D^(n+1) / (Π x_i)

x * y = L²

Price Impact Profile

High (convex)

Zero (linear)

Low near peg, high otherwise

Configurable (within a range)

Capital Efficiency

Low

High for pegged assets

Very high for pegged assets

Extremely high (up to 4000x)

Impermanent Loss Risk

High

Zero for pegged assets

Low near peg, high otherwise

High (amplified within range)

Optimal Asset Pair

Volatile/Disparate

Stable/Identical (e.g., USDC/USDT)

Stablecoins / Pegged Assets

Any (liquidity concentrated)

Liquidity Provider Flexibility

Passive (full range)

Passive (full range)

Passive (full range)

Active (price range selection)

Slippage for Small Trades

Low

Zero

Very low near peg

Configurably low

Protocol Examples

Uniswap v2, SushiSwap

Basic mStable pools

Curve Finance

Uniswap v3, PancakeSwap v3

etymology-history
ORIGINS OF AMM MECHANICS

Etymology and Historical Context

The Constant Product Formula, expressed as x * y = k, is the foundational pricing algorithm for automated market makers (AMMs). Its history is a story of academic theory meeting decentralized finance.

The Constant Product Formula is a mathematical invariant first formalized for decentralized finance in Vitalik Buterin's 2016 post, "Let’s run on-chain decentralized exchanges the way we run prediction markets." While the core mathematical concept of an invariant function for pricing was known in economics, its application to trustless, on-chain liquidity was revolutionary. The formula dictates that for a liquidity pool holding two assets, X and Y, the product of their quantities (x and y) must remain constant (k) before and after any trade. This simple rule automatically determines prices based solely on the ratio of assets in the pool, eliminating the need for traditional order books.

The first major implementation was in the Uniswap v1 protocol, launched by Hayden Adams in November 2018. Uniswap demonstrated that the constant product model could provide continuous liquidity for any token pair without intermediaries. Its success proved the viability of the automated market maker (AMM) model. The "constant product" invariant ensures the pool is never depleted of either asset—as the quantity of one asset approaches zero, its price in terms of the other approaches infinity, creating a theoretically boundless liquidity curve. This property is central to the model's resilience.

The historical significance of x * y = k extends beyond Uniswap. It became the canonical AMM formula, inspiring countless forks and variations. Its limitations, such as impermanent loss during high volatility and capital inefficiency, led to further innovation. Subsequent AMM designs, like Curve Finance's StableSwap (which combines constant product and constant sum invariants) and Uniswap v3's concentrated liquidity, are direct evolutionary responses to the trade-offs inherent in the original constant product model. Thus, this formula represents both the genesis of on-chain AMMs and a benchmark against which all newer designs are measured.

CONSTANT PRODUCT FORMULA

Frequently Asked Questions (FAQ)

The Constant Product Formula (x * y = k) is the foundational algorithm for Automated Market Makers (AMMs) like Uniswap. This section answers the most common technical and practical questions about its mechanics, applications, and implications.

The Constant Product Formula is the core mathematical invariant governing liquidity pools in Automated Market Makers (AMMs) like Uniswap V2. It states that for a pool containing two assets, the product of their quantities (x * y) must always equal a constant (k). This relationship, x * y = k, automatically determines prices and enables permissionless, algorithmic trading without order books.

When a trader swaps Asset A for Asset B, they add Δx of A to the pool and remove Δy of B. The formula ensures the new balances satisfy (x + Δx) * (y - Δy) = k. The price of A in terms of B is derived from the ratio of the reserves (price = y / x), and this price changes with each trade, creating slippage. The constant k only changes when liquidity providers add or remove funds from the pool.

further-reading
CONSTANT PRODUCT FORMULA

Further Reading & Technical Resources

Explore the mathematical foundations, practical implications, and advanced mechanisms built upon the core x * y = k invariant.

01

Mathematical Derivation & Price Impact

The formula x * y = k defines a hyperbolic curve where the price of asset X in terms of Y is given by the ratio of the reserves: Price_X = y / x. The price impact for a trade is non-linear; larger trades move the price more significantly along this curve. This is calculated as the difference between the spot price and the effective price received.

  • Example: If a pool has 100 ETH (x) and 300,000 USDC (y), k = 30,000,000. The spot price of ETH is 3,000 USDC. Swapping 1 ETH adds to x, reducing y to maintain k, resulting in slightly less than 3,000 USDC for the trader.
02

Impermanent Loss (Divergence Loss)

Impermanent loss is the opportunity cost liquidity providers (LPs) experience when the price ratio of the pooled assets changes compared to simply holding them. It's an inherent feature of the constant product formula, arising from the requirement to rebalance reserves along the curve to maintain k.

The loss is temporary (unrealized) until withdrawal and is maximized during high volatility. The loss magnitude can be calculated as a function of the price change ratio.

03

Comparison to Other AMM Curves

The constant product formula is one of several automated market maker (AMM) bonding curves, each with different liquidity and slippage properties.

  • Constant Sum (x + y = k): Zero slippage but vulnerable to depletion of one asset.
  • Constant Product (x * y = k): Provides infinite liquidity but variable price impact (used by Uniswap v2).
  • StableSwap/Curve (Hybrid): Approximates constant sum near parity and constant product elsewhere, optimized for stablecoin pairs.
  • Concentrated Liquidity: Allows LPs to set price ranges (Uniswap v3), making capital efficiency the variable.
04

Fee Integration & Protocol Implementation

In practice, the invariant is adjusted to account for trading fees, which are added to the pool's reserves. For a fee φ (e.g., 0.3%), the formula effectively becomes x' * y' = k', where the new constant k' increases with each trade, rewarding LPs.

Key implementation details:

  • Fees are typically taken in the input asset before the swap calculation.
  • The updated k represents the pool's growing total value from accrued fees.
  • This mechanism is foundational to protocols like Uniswap v2, SushiSwap, and the core of many decentralized exchanges.
05

Formal Verification & Security

The deterministic nature of the constant product formula allows for formal verification. Its properties—like conservation of the invariant k post-swap (excluding fees) and the absence of arbitrage under correct pricing—can be mathematically proven.

This makes the core contract logic highly secure against manipulation, assuming correct implementation. Audits focus on ensuring the formula is applied precisely and that fee math and rounding errors do not create vulnerabilities.

ENQUIRY

Get In Touch
today.

Our experts will offer a free quote and a 30min call to discuss your project.

NDA Protected
24h Response
Directly to Engineering Team
10+
Protocols Shipped
$20M+
TVL Overall
NDA Protected Directly to Engineering Team
Constant Product Formula (x * y = k) - AMM Glossary | ChainScore Glossary