Section 3 of 4

Learn
+5 Shields

The Math Behind Pricing

The Math Behind Pricing

The Constant Product Invariant

Every AMM uses a mathematical invariant to determine prices. The simplest and most influential is the constant product formula:

x * y = k

When someone swaps token A for token B, they deposit dx of token A. The contract calculates how much token B (dy) to return such that the product remains constant:

(x + dx) * (y - dy) = k

Solving for dy:

dy = y * dx / (x + dx)

This is the output amount before fees. Uniswap V2 charges 0.3% on the input:

dy = (y * dx * 997) / (x * 1000 + dx * 997)

How Other Invariants Differ

Curve's StableSwap: Uses a hybrid of constant product and constant sum (x + y = k). The amplification parameter A controls how close the curve is to constant sum (low slippage for similar-priced assets) vs constant product (works at any price). Perfect for stablecoin pairs.

Balancer's Weighted Math: Generalizes constant product to arbitrary weights. Instead of 50/50, you can have 80/20 or any ratio. The invariant becomes a product of reserves raised to their weights: x^w1 * y^w2 = k.

QuantAMM's Temporal Functions: Weights change dynamically over time. The pool auto-rebalances based on momentum, mean reversion, or custom strategies. The invariant is recalculated at each block.

Why This Matters for Security

Each invariant has unique attack surfaces. Constant product is vulnerable to flash loan price manipulation. StableSwap can break when assets depeg. Weighted pools can be exploited through weight manipulation. Understanding the math is the first step to understanding the vulnerabilities.

Verify Your Understanding

Write the constant product formula used by Uniswap V2.

Three variables, one equation. The product of two token reserves equals...

Knowledge Check

Answer correctly to earn lynx

Verify your understanding