The Mathematics of Constant Product Markets | AMMs on XRPL | XRP Academy - XRP Academy
3 free lessons remaining this month

Free preview access resets monthly

Upgrade for Unlimited
Skip to main content
beginner65 min

The Mathematics of Constant Product Markets

Learning Objectives

Derive the constant product formula and explain why it produces liquidity

Calculate spot price and execution price for any trade size

Quantify slippage as a function of trade size and pool depth

Prove the relationship between price impact and trade size mathematically

Apply these formulas to real XRPL AMM pools

Many AMM users treat the constant product formula as a black box. They deposit tokens, make trades, and accept whatever price the protocol offers. This works until it doesn't—until slippage exceeds expectations, or impermanent loss confuses, or a trade executes at a price that seems wrong.

  • Verify whether a quoted price is correct
  • Calculate expected slippage before executing
  • Understand exactly why impermanent loss occurs
  • Evaluate whether a pool is efficient for your needs

This lesson builds that understanding from the ground up. If you follow the derivations, you'll not only understand how AMMs work but why they must work this way given their design constraints.


THE FUNDAMENTAL EQUATION

x × y = k

Where:
├── x = Quantity of Token A in the pool
├── y = Quantity of Token B in the pool
├── k = The constant product (invariant)
└── After any trade: x_new × y_new = k (unchanged)

This single equation defines:
├── The price at any moment
├── The price after any trade
├── The slippage for any trade size
├── The relationship between all variables
└── Everything about AMM behavior
```

The term "constant product" comes from the constraint that the product of the two token quantities must remain constant through all trades.

INVARIANT DEMONSTRATION

Initial pool state:
├── x = 10,000 XRP
├── y = 25,000 RLUSD
└── k = 10,000 × 25,000 = 250,000,000

After a trade (buying XRP with RLUSD):
├── x decreases (XRP removed)
├── y increases (RLUSD added)
├── But x_new × y_new must still equal 250,000,000
└── This constraint determines the price

Why this matters:
├── No external oracle needed
├── Price emerges from pool state
├── Self-balancing system
├── Arbitrageurs correct mispricings
└── Simple but powerful
```

Spot Price is the instantaneous price for an infinitesimally small trade.

SPOT PRICE DERIVATION

Given: x × y = k

Price of A in terms of B = dy/dx at the current state

Taking the differential of both sides:
x × dy + y × dx = 0 (since dk = 0, k is constant)

Rearranging:
dy/dx = -y/x

The negative sign indicates:
├── As x increases, y must decrease
├── Buying A requires giving up B
└── This is the exchange relationship

Spot Price of A in terms of B:
P_A = y/x

Spot Price of B in terms of A:
P_B = x/y

Example:
├── Pool: 10,000 XRP, 25,000 RLUSD
├── Price of XRP = 25,000/10,000 = 2.5 RLUSD
├── Price of RLUSD = 10,000/25,000 = 0.4 XRP
└── Reciprocal relationship always holds
```

The constant product formula describes a rectangular hyperbola. This geometric interpretation helps visualize AMM behavior.

GEOMETRIC INTERPRETATION

The equation x × y = k describes a hyperbola in the x-y plane

Properties:
├── Curve never touches either axis
├── Infinite liquidity at extreme prices
├── Liquidity decreases as you move toward axes
├── Slope at any point = -y/x (the price)

Visual intuition:
├── Near origin: Both balances small, price volatile
├── Far from origin: Large balances, stable prices
├── Trade moves you along the curve
├── Large trades = large movement = large price change

Why hyperbola matters:
├── Guarantees liquidity exists at ANY price
├── But liquidity thins at extreme prices
├── Trade-off between coverage and efficiency
└── Concentrated liquidity (Uniswap v3) addresses this
```


When you make a trade, you don't get the spot price—you get the execution price, which accounts for the price moving as you trade.

EXECUTION PRICE DERIVATION

Setup:
├── Pool: x tokens of A, y tokens of B
├── Trader wants to buy Δx tokens of A
├── Trader must provide Δy tokens of B
├── After trade: (x - Δx)(y + Δy) = k = x × y

Solving for Δy:
(x - Δx)(y + Δy) = xy
xy + xΔy - yΔx - ΔxΔy = xy
xΔy - yΔx - ΔxΔy = 0
xΔy = yΔx + ΔxΔy
xΔy = Δx(y + Δy)
Δy = Δx(y + Δy)/x

Rearranging:
Δy = (y × Δx)/(x - Δx)

This is the amount of B required to buy Δx of A

Execution price:
P_exec = Δy/Δx = y/(x - Δx)

Key insight:
├── As Δx approaches 0: P_exec → y/x (spot price)
├── As Δx increases: P_exec increases
├── Denominator (x - Δx) decreases as you buy more
└── This is why large trades have worse prices
```

EXECUTION PRICE EXAMPLE

Pool state:
├── x = 100,000 XRP
├── y = 250,000 RLUSD
├── k = 25,000,000,000
├── Spot price = 250,000/100,000 = 2.50 RLUSD/XRP

Trade 1: Buy 100 XRP (0.1% of pool)
├── Δy = (250,000 × 100)/(100,000 - 100)
├── Δy = 25,000,000/99,900
├── Δy = 250.25 RLUSD
├── Execution price = 250.25/100 = 2.5025 RLUSD/XRP
├── Price impact = (2.5025 - 2.50)/2.50 = 0.1%
└── Minimal slippage

Trade 2: Buy 1,000 XRP (1% of pool)
├── Δy = (250,000 × 1,000)/(100,000 - 1,000)
├── Δy = 250,000,000/99,000
├── Δy = 2,525.25 RLUSD
├── Execution price = 2,525.25/1,000 = 2.5253 RLUSD/XRP
├── Price impact = (2.5253 - 2.50)/2.50 = 1.01%
└── Noticeable slippage

Trade 3: Buy 10,000 XRP (10% of pool)
├── Δy = (250,000 × 10,000)/(100,000 - 10,000)
├── Δy = 2,500,000,000/90,000
├── Δy = 27,777.78 RLUSD
├── Execution price = 27,777.78/10,000 = 2.7778 RLUSD/XRP
├── Price impact = (2.7778 - 2.50)/2.50 = 11.11%
└── Significant slippage

Pattern: Price impact scales roughly with trade size as % of pool
```

SLIPPAGE DERIVATION

Slippage = (Execution Price - Spot Price) / Spot Price

Spot price: P_spot = y/x
Execution price: P_exec = y/(x - Δx)

Slippage = [y/(x - Δx) - y/x] / [y/x]
= [y·x - y·(x - Δx)] / [(x - Δx)·y]
= [yx - yx + yΔx] / [y(x - Δx)]
= Δx / (x - Δx)

Simplified slippage formula:
Slippage = Δx / (x - Δx)

Where Δx/x is the trade size as fraction of pool

For small trades (Δx << x):
Slippage ≈ Δx/x

This means:
├── 1% of pool → ~1% slippage
├── 5% of pool → ~5.3% slippage
├── 10% of pool → ~11.1% slippage
├── 20% of pool → ~25% slippage
└── Slippage accelerates for larger trades
```

SLIPPAGE REFERENCE TABLE
Trade Size (% of pool) Slippage
    0.1%           |   0.10%
    0.5%           |   0.50%
    1.0%           |   1.01%
    2.0%           |   2.04%
    3.0%           |   3.09%
    5.0%           |   5.26%
   10.0%           |  11.11%
   15.0%           |  17.65%
   20.0%           |  25.00%
   25.0%           |  33.33%
   50.0%           | 100.00%

Key observations:
├── Slippage is roughly linear for small trades
├── Accelerates significantly above 10%
├── At 50% of pool, you pay 2x spot price
├── Buying entire pool: Approaches infinity
└── This is why pool size matters!
```


After a trade executes, the pool composition changes, and so does the spot price.

POST-TRADE PRICE

Before trade:
├── Pool: x₀ = 100,000 XRP, y₀ = 250,000 RLUSD
├── k = 25,000,000,000
└── Price = 2.50 RLUSD/XRP

Buy 10,000 XRP:
├── Pay Δy = 27,777.78 RLUSD (calculated earlier)
├── New pool: x₁ = 90,000 XRP, y₁ = 277,777.78 RLUSD
├── Verify: 90,000 × 277,777.78 = 25,000,000,020 ≈ k ✓
└── New price = 277,777.78/90,000 = 3.0864 RLUSD/XRP

Price impact:
├── Started at 2.50 RLUSD/XRP
├── Ended at 3.0864 RLUSD/XRP
├── Price moved 23.46%
└── Your trade moved the market

This creates arbitrage opportunity:
├── If external market price is still 2.50
├── Arbitrageur can sell XRP to pool at 3.0864
├── Buy XRP externally at 2.50
├── Profit on difference
└── This restores the price
```

LIQUIDITY-SLIPPAGE RELATIONSHIP

The same dollar trade has different slippage in different pools:

$10,000 trade in small pool:
├── Pool: 10,000 XRP + 25,000 RLUSD ($50,000 total)
├── Trade: Buy ~4,000 XRP (40% of XRP reserves)
├── Slippage = 0.40/(1-0.40) = 66.7%
└── Execution is terrible

$10,000 trade in medium pool:
├── Pool: 100,000 XRP + 250,000 RLUSD ($500,000 total)
├── Trade: Buy ~4,000 XRP (4% of reserves)
├── Slippage = 0.04/(1-0.04) = 4.17%
└── Execution is acceptable

$10,000 trade in large pool:
├── Pool: 1,000,000 XRP + 2,500,000 RLUSD ($5,000,000 total)
├── Trade: Buy ~4,000 XRP (0.4% of reserves)
├── Slippage = 0.004/(1-0.004) = 0.40%
└── Execution is excellent

Key insight:
├── 10× liquidity → ~10× less slippage
├── Pool depth determines execution quality
├── This is why TVL matters
└── And why XRPL's small pools are a limitation
```

EFFECTIVE LIQUIDITY CONCEPT

Not all TVL is equal for execution quality:

Constant product (Uniswap v2, XRPL):
├── Liquidity spread across infinite price range
├── Most liquidity is "far" from current price
├── Only fraction is "active" near market
└── Capital inefficient

Example:
├── Pool TVL: $1,000,000
├── Effective liquidity at ±2% of current price: ~$40,000
├── 96% of liquidity sits unused at extreme prices
└── This is the "capital efficiency problem"

Concentrated liquidity (Uniswap v3):
├── LPs specify price range
├── All capital active within that range
├── Much better execution
├── But: Requires active management, more IL risk

XRPL AMM uses constant product:
├── Same capital efficiency limitations
├── Simpler for LPs (no range management)
├── Trade-off accepted for simplicity
└── May evolve in future amendments


---

In practice, AMMs charge fees. The fee reduces the amount you receive.

INCORPORATING FEES

Standard model (without fees):
Δy = (y × Δx)/(x - Δx)

With fee (f = 0.3% = 0.003):
├── Fee is taken from input
├── Effective input: Δx × (1 - f)
├── This increases cost to trader

Adjusted formula:
Δy = (y × Δx × (1-f))/(x - Δx × (1-f))

Example with 0.3% fee:
├── Pool: 100,000 XRP, 250,000 RLUSD
├── Buy 1,000 XRP
├── Without fee: Pay 2,525.25 RLUSD
├── With fee: Pay 2,525.25/(1-0.003) = 2,532.84 RLUSD
├── Additional cost: 7.59 RLUSD (0.3%)
└── Fee goes to LPs

Alternative interpretation:
├── You're buying 1,000 XRP with RLUSD
├── Pool uses your RLUSD as if 0.3% less
├── Results in same execution but higher cost
└── Fee is always paid by trader
```

Sometimes you know how much you want to spend, not how much you want to buy.

SPENDING A FIXED AMOUNT

Question: How much XRP can I buy with 5,000 RLUSD?

Setup:
├── Pool: x = 100,000 XRP, y = 250,000 RLUSD
├── k = 25,000,000,000
├── Spending: Δy = 5,000 RLUSD
└── Find: Δx = ?

Using constant product:
(x - Δx)(y + Δy) = xy

Solving for Δx:
(x - Δx) = xy/(y + Δy)
Δx = x - xy/(y + Δy)
Δx = x(y + Δy - y)/(y + Δy)
Δx = x × Δy/(y + Δy)

Calculation:
Δx = 100,000 × 5,000/(250,000 + 5,000)
Δx = 500,000,000/255,000
Δx = 1,960.78 XRP

Verify:
├── New pool: 98,039.22 XRP, 255,000 RLUSD
├── Product: 98,039.22 × 255,000 = 25,000,001,100 ≈ k ✓
├── Effective price: 5,000/1,960.78 = 2.55 RLUSD/XRP
└── vs spot price 2.50 = 2% slippage
```

FULL TRADE ANALYSIS WORKFLOW

Step 1: Gather pool data
├── Token A balance: x
├── Token B balance: y
├── Fee rate: f
└── Calculate k = x × y

Step 2: Determine trade direction
├── Buying A with B: You provide Δy, receive Δx
├── Selling A for B: You provide Δx, receive Δy
└── Formulas differ by direction

Step 3: Calculate without fees
├── Buying Δx of A: Δy = y×Δx/(x-Δx)
├── Spending Δy for A: Δx = x×Δy/(y+Δy)
└── Use appropriate formula

Step 4: Apply fee
├── Multiply cost by 1/(1-f) if paying B
├── Or multiply received by (1-f) if receiving B
└── Fee always reduces trader value

Step 5: Calculate metrics
├── Execution price = Δy/Δx
├── Spot price = y/x
├── Slippage = (Exec - Spot)/Spot
├── Price impact = change in spot price after trade
└── Document all for analysis

Step 6: Compare alternatives
├── vs other AMM pools
├── vs order book DEX
├── vs centralized exchange
└── Choose best execution
```


POOL DRAINAGE IMPOSSIBILITY

Intuition: Why can't someone buy all the XRP in a pool?

Mathematical answer:
├── To buy x tokens (all XRP), you need infinite y tokens
├── As Δx → x, the formula Δy = y×Δx/(x-Δx) → ∞
├── The last token costs infinite amount
└── Pool can never be fully drained

Numerical demonstration:
├── Pool: 100,000 XRP, 250,000 RLUSD
├── Buy 99,000 XRP (99% of pool)
├── Δy = 250,000 × 99,000/(100,000 - 99,000)
├── Δy = 24,750,000,000/1,000 = 24,750,000 RLUSD
├── That's 99× the original RLUSD in pool!
└── And you still can't get the last 1,000 XRP

This property means:
├── Liquidity exists at any price (theoretically)
├── Extreme prices are extremely expensive
├── Pool always has some of each token
└── A core feature of constant product design
```

TRADE SYMMETRY

Property: The cost to buy X tokens equals the
amount received when selling X tokens (ignoring fees)

Proof:
├── Buy Δx of A, pay Δy of B
├── Δy = y×Δx/(x-Δx)

├── Now sell Δx of A, starting from new state:
├── New pool: (x-Δx), (y+Δy)
├── Selling Δx returns: (y+Δy)×Δx/((x-Δx)+Δx)
├── = (y+Δy)×Δx/x
├── Simplifying with Δy = y×Δx/(x-Δx):
├── = (y + y×Δx/(x-Δx))×Δx/x
├── = y×Δx/x + y×(Δx)²/(x(x-Δx))
├── This equals Δy ✓

What this means:
├── Round-trip (buy then sell) returns to original
├── No arbitrage from same-pool round trips
├── Pool is self-consistent
└── Important for mathematical soundness
```

MARGINAL VS AVERAGE PRICE

Marginal price: Price of next infinitesimal unit
Average price: Total cost / total units purchased

For constant product:
├── Marginal price varies continuously during trade
├── Starts at spot price, increases throughout
├── Average price is always between start and end marginal

Mathematical relationship:
├── Spot (start): P₀ = y/x
├── Spot (end): P₁ = (y+Δy)/(x-Δx)
├── Average: P_avg = Δy/Δx

Property: P₀ < P_avg < P₁ (when buying)

This is why slippage exists:
├── You pay average price, not spot price
├── Average includes all the marginal price increases
├── Larger trades = higher average
└── Cannot avoid without smaller orders
```


XRPL-SPECIFIC CONSIDERATIONS

Same formula:
├── XRPL uses constant product (x × y = k)
├── Mathematics identical to Uniswap v2
├── All derivations in this lesson apply
└── No XRPL-specific formula changes

Fee structure:
├── Pool creator sets fee tier (0.0% to 1.0%)
├── Fee goes to LP token holders
├── Continuous auction may provide additional LP revenue
└── Total LP revenue = Trading fees + Auction proceeds

Practical differences:
├── Much smaller pools (~$20-50M total TVL)
├── Higher relative slippage for same $ trade
├── Less arbitrageur activity to correct prices
├── Integration with order book provides alternatives
└── Must compare AMM vs order book execution
```

XRPL AMM CALCULATION EXAMPLE

Hypothetical XRPL pool (realistic scale):
├── Pool: 500,000 XRP + 1,250,000 RLUSD
├── Total value: ~$2,500,000 (assuming XRP = $2.50)
├── Fee: 0.5%
└── k = 625,000,000,000

Trade: Buy 10,000 XRP

Step 1: Calculate without fees
├── Δy = (1,250,000 × 10,000)/(500,000 - 10,000)
├── Δy = 12,500,000,000/490,000
├── Δy = 25,510.20 RLUSD

Step 2: Apply 0.5% fee
├── Actual cost = 25,510.20/(1-0.005)
├── Actual cost = 25,638.39 RLUSD

Step 3: Calculate metrics
├── Spot price: 1,250,000/500,000 = 2.50 RLUSD/XRP
├── Execution price: 25,638.39/10,000 = 2.564 RLUSD/XRP
├── Slippage: (2.564 - 2.50)/2.50 = 2.56%
├── Price impact: 10,000/490,000 = 2.04%
└── Fee component: 0.5%

Step 4: Compare to order book
├── Check XRPL DEX for 10,000 XRP order
├── If order book has 10,000 XRP at 2.51 = better
├── If order book has only 2,000 XRP at 2.51 = maybe split
├── This is why dual venue is valuable
└── XRPL pathfinding considers both
```

WHY XRPL POOL SIZE MATTERS

Current XRPL AMM reality:
├── Largest pools: ~$1-5M TVL
├── Many pools: <$100K TVL
├── Compare to Uniswap pools: $10M-500M TVL
└── 10-100× smaller typical pool

Slippage implications:
├── $10K trade in $100K pool: ~10% slippage
├── $10K trade in $1M pool: ~1% slippage
├── $10K trade in $10M pool: ~0.1% slippage
└── Smaller pools = worse execution

Practical impact:
├── Large trades nearly impossible via AMM
├── Order book may be better for size
├── Arbitrageurs less active (less profit opportunity)
├── Prices may diverge from external markets longer
└── LPs face adverse selection with fewer arbitrageurs
```


The constant product formula is mathematically sound. It produces consistent, predictable behavior that has been battle-tested across billions in volume.

Slippage is deterministic. Given pool size and trade size, slippage can be calculated exactly before execution.

The formula creates guaranteed liquidity. Any trade can execute at some price, regardless of order book depth.

⚠️ Optimal fee levels for XRPL pools. The trade-off between LP compensation and trader costs is empirical.

⚠️ Whether constant product is optimal for XRPL. Concentrated liquidity could improve capital efficiency but adds complexity.

⚠️ How arbitrageurs will behave with small pools. Less profit opportunity may mean less price accuracy.

📌 Ignoring slippage calculations. Large trades in small pools can have catastrophic execution.

📌 Assuming all pools are equal. A $100K pool and a $10M pool have vastly different execution quality.

📌 Not comparing to order book. XRPL's order book DEX may offer better execution for many trades.

The mathematics of constant product AMMs is elegant, proven, and deterministic. Understanding these formulas lets you calculate exact costs before trading. However, mathematical soundness doesn't overcome economic limitations—XRPL's small pool sizes mean slippage will often be higher than on larger platforms. Always calculate before executing.


Assignment: Complete 10 calculation exercises demonstrating mastery of AMM mathematics.

Requirements:

Exercise Set A: Basic Calculations (4 problems)

  1. Spot Price Calculation

  2. Simple Trade Execution

  3. Trade with Fees

  4. Spending Fixed Amount

Exercise Set B: Analysis Problems (4 problems)

  1. Pool Comparison

  2. Slippage Table Construction

  3. Post-Trade Price Analysis

  4. Arbitrage Opportunity

Exercise Set C: Advanced Problems (2 problems)

  1. Fee Break-Even

  2. Multi-Hop Trade

  • Show all work for each problem

  • Include formulas used

  • Verify answers where possible (e.g., check k stays constant)

  • Provide brief interpretation of each result

  • Mathematical accuracy (40%)

  • Work shown and methodology (30%)

  • Formula application (20%)

  • Interpretation quality (10%)

Time Investment: 3-4 hours


Knowledge Check

Question 1 of 3

In a pool with 80,000 XRP and 200,000 RLUSD, what is the spot price of XRP?

  • Uniswap v2 whitepaper (formal proofs)
  • "An analysis of Uniswap markets" (Angeris et al.)
  • "Improved Price Oracles: Constant Function Market Makers" (Angeris & Chitra)
  • Uniswap documentation (mathematical appendix)
  • Paradigm research on AMM mathematics
  • Various DeFi educational courses
  • AMM slippage calculators
  • Pool analysis dashboards
  • Trading simulators

For Next Lesson:
With the basic mathematics understood, Lesson 3 will tackle the most misunderstood topic in AMM economics: impermanent loss. We'll derive the IL formula from first principles and understand exactly why LPs sometimes lose money even when prices return to entry levels.


End of Lesson 2

Total words: ~6,200
Estimated completion time: 65 minutes reading + 3-4 hours for deliverable

Key Takeaways

1

x × y = k is the complete model.

Every aspect of AMM behavior—price, slippage, execution—derives from this single equation.

2

Spot price = y/x, always.

The ratio of token quantities is the instantaneous price. Everything else builds from this.

3

Slippage ≈ Trade Size / Pool Size.

For small trades, slippage is roughly proportional to your trade as a percentage of the pool. Large trades face accelerating slippage.

4

Pool depth determines execution quality.

A 10× larger pool has roughly 10× less slippage for the same dollar trade. XRPL's smaller pools mean higher slippage.

5

Always calculate before trading.

The formulas let you know exact execution cost before submitting. Use them. ---