本文へ移動
Contact

TECHFUND
Media

Hi AUDIT
2025/7/7

DeFi AMM Math from First Principles — Part 2: Curve's StableSwap

Introduction

Last week, we explored how the xy = k formula used by Uniswap v2 works Read it here if you haven’t already.

This time, we’ll look at why that same formula doesn’t work well for stablecoins (like DAI and USDC), and how Curve Finance solved this problem with StableSwap math model. We’ll walk through:

  • Why Uniswap’s math creates huge losses for stablecoin trades

  • Why “obvious” fixes are dangerous

  • How Curve blends two formulas together

  • How to actually compute swaps using their method

  • Why this is one of DeFi’s most elegant AMM designs


Step 1: Why x * y = k Breaks for Stablecoins

Uniswap uses the formula x * y = k to keep pool balance. If one token is bought, its price increases automatically (supply ↓, price ↑). This is perfect for volatile assets.

But it fails for stablecoins. Why?

Imagine swapping 10,000 USDC for DAI in a 10M/10M pool:

def get_amount_out_no_fee(amount_in, reserve_in, reserve_out):
    assert amount_in > 0, "INSUFFICIENT_INPUT_AMOUNT"
    assert reserve_in > 0 and reserve_out > 0, "INSUFFICIENT_LIQUIDITY"

    numerator = amount_in * reserve_out
    denominator = reserve_in + amount_in
    return numerator // denominator

# Swap 1M USDC into DAI from a 10M/10M pool
print(get_amount_out_no_fee(1_000_000, 10_000_000, 10_000_000))
# Output: ~909,090 DAI → ~9.1% slippage

Wait, both tokens are $1! Why am I losing $900?

That’s called slippage. And for stablecoins, you don’t expect this. Swaps should stay close to 1:1.


Step 2: Slippage Gets Worse With Bigger Trades

Try swapping 5 million USDC:

# Swap 5M USDC into DAI from a 10M/10M pool
print(get_amount_out_no_fee(1_000_000, 10_000_000, 10_000_000))
# Output: ~3,333,333 DAI → ~33.3% slippage

Even though the tokens are both supposed to be worth $1, Uniswap punishes large trades with worse and worse prices. That’s intentional for normal tokens, but terrible for stablecoins.


Step 3: Visualizing the Problem

Plot x * y = k on Desmos.

You’ll see a hyperbola.

Interpretation

  • x-axis = reserve of token X (e.g., USDC)

  • y-axis = reserve of token Y (e.g., DAI)

  • Every point on the curve keeps xy = k constant.

This is the price curve.

  • When you add USDC, you move right

  • DAI gets removed, so y drops

  • The slope of the curve (price) increases

  • Bigger trades → worse exchange rate

So you lose value—even between two $1 tokens.


Step 4: Constant Sum

Let’s try a 1:1 swap formula:

def constant_sum_swap(reserve_in, reserve_out, amount_in):
# Perfect 1:1 swaps
    amount_out = amount_in
    return amount_out

This gives perfect swaps. Zero slippage. Sounds perfect, right?

Wrong.

What if one token depegs?

Let’s say USDC drops to $0.50.

Someone can send 10M USDC (now worth $5M) and get 10M DAI (worth $10M). Instant $5M profit.

The pool gets drained.

Constant sum = unsafe if prices diverge.


Step 5: Curve’s Smart Idea — Combine Both Worlds

Curve didn’t use just one formula. They created a hybrid version:

Use constant sum when the pool is balanced (low slippage) and shift toward constant product when it’s unbalanced (to protect).

It’s like this:

  • Balanced pool → x + y = D behaviour → Perfect for 1:1 swaps, but unsafe if a token depegs

  • Imbalanced pool → xy = (D/2)^2 behaviour → Protects against drain, but causes slippage even when tokens are equal in value

These are opposite behaviours. So Curve wanted to interpolate between them — act like sum when near balance, and like product when imbalanced. So curve has combined them with a parameter A which will decide where to shift more

Curve brought a special parameter A which will decides where to shift the current curve based on the market conditions

This gives you:

  • Smooth swaps around 1:1

  • Drain protection when things get risky

#combined equation
xy + x+y  =  (D/2)^2 + D

After introducing the A parameter and combining the behaviours of xy and D without changing the underlying equation we arrive at this form of the equation.

Curve whitepaper has different equation but above is simple representation of it which is a simplified equation and basically same

A detailed explanation of this equation and its curve behaviour is available in Cyfrin’s Updraft course, which is currently one of the best resources on Curve. I highly recommend going through it. The equation ensures the swap curve transitions smoothly between constant sum and constant product, and the A parameter controls how aggressively the curve shifts between these two behaviors.


Step 6: Understanding the Parameters (D, A, n)

D = Total Liquidity

Think of D like Uniswap’s k, but more flexible. It holds total pool value.

For 3 tokens:

  • Sum: x + y + z = D

  • Product: (x * y * z)^(1/3) = D / 3

A = Amplification

Controls how close to 1:1 the curve behaves:

  • A = 0 → full slippage (Uniswap-style)

  • A = 100 → good for stables

  • A = 10,000 → nearly flat swaps (dangerous if abused)

n = Number of tokens

For 2 tokens: (D / 2)^2

For 3 tokens: (D / 3)^3

For n tokens: (D / n)^n

This generalizes the math for multi-asset pools.


Step 7: Newton’s Method — Solving the Curve Equation

Here’s the tricky part: the final Curve formula can’t be solved directly and easily like xy=k equations. It’s hard to derive a direct solution from the equation, and the calculations are too heavy to do on-chain without optimization

So Curve uses Newton’s Method, which simplifies the calculation On-chain, the core functions are:

  • get_D() → computes the invariant

  • get_y() → computes how much token you’ll get in return

You can see this in Curve’s Vyper code:

Stableswap.vy on GitHub

Or check this tutorial:

Cyfrin’s Newton Method Visualized


Step 8: Final Curve Equation (Whitepaper)

Now that you’ve gone through the background, the Curve whitepaper becomes much easier to understand. I highly recommend reading it

Here’s what Curve actually uses:

📄 StableSwap Paper (PDF)

Once you understand the above steps, this equation makes a lot more sense.


Step 9: Try Building It Yourself

Best way to learn it?

Take pen and paper, recall all the formulas, and derive them by hand. Then, code a mini StableSwap clone that implements Newton’s method for calculating get_D and get_y


Conclusion: Why Curve's Design Is So Good

  • Elegant: Merges two classic AMM formulas

  • Safe: Minimizes slippage and increases resistance to depegs

  • Flexible: Controlled A for any market condition

Curve solves a hard problem with clean math. It’s simple once you get the intuition.

In Part 3, we’ll cover:

  • How Curve handles crypto-stable pairs (e.g., ETH/stETH)

  • Security considerations on Curve AMMs


Special thanks to the Curve team for creating one of DeFi's most elegant protocols. Special thanks to Smart Contract Programmer and Cyfrin Updraft for explaining it all so clearly

Author: Ashish Lachuria

Security Researcher Intern at TECHFUND

Hi AUDIT

Hi AUDIT is a high speed, high quality, best price security audit service, providing automated audit SaaS and consulting for web3 startups.
View More