本文へ移動
Contact

TECHFUND
Media

Hi AUDIT
2025/6/10

DeFi AMM Math from First Principles — Part 1: Uniswap

Introduction

Every time you swap ETH for USDC on-chain, a piece of math determines your price and here is the math from Uniswap that revolutionized the Defi Industry

x * y = k

But how does it really work?

Let us understand it in this article, we’ll unpack the mechanics of the constant product AMM from first principles. This is for people like me - people who Uniswap’s saw x * y = k equation, nodded like we got it… and then closed the tab confused.

This article is my attempt to explain AMM math the way I wish someone had explained it to me - not just what the formulas are, but why they exist and how they behave.

If you stick through till the end, you’ll grasp in one day which took me weeks to truly sink in.

Let’s start from the absolute basics and work our way toward designing AMM like Uniswap, Curve, and beyond.

If you've got curiosity and a bit of patience - you're in the right place.


Table of Contents

Why AMM?

Users swap tokens to manage their portfolios, use DeFi apps, and make payments within the crypto world. Swapping allows users to move seamlessly between tokens as their needs change.

For example, if someone expects ETH’s price to go up, they might swap USDC (a stablecoin) for ETH to get exposure; or if they want to play it safe, they’ll swap ETH back to USDC or other stablecoins.

If you have USDC and want to swap it with ETH, the only option earlier was to go to centralized exchanges like Binance or Coinbase. You put in your order to sell USDC and buy ETH, some seller puts their order to sell ETH and buy USDC, the order matches, and you get the ETH.

But what are the risks users have faced with this model? Let’s understand:

  1. Attacker can steal your entire ETH - because CEXs maintain centralized keys for all users. If an attacker gains access, all your ETH is gone (see WazirX hack).

  2. Centralization risks - Can freeze accounts, act under political pressure, and delist coins.

  3. No access to new DeFi tokens.

  4. No limit on the fee cap being set by CEX providers.

  5. Can’t interact with DeFi directly - you must withdraw first; no smart contract access (e.g., no yield farming).

  6. Mediators between sellers and buyers - exactly what blockchains were built to avoid.

So how do we solve this? That’s where AMMs—Automated Market Makers—come in. They offer a solution to all the problems above by leveraging the power of decentralization which I call by the people, to the people, for the people. You’ll soon see what that really means.

Let’s walk through how to design one, step by step.


Step 1: Decide the Hosting Platform for AMM

If we are building an AMM solution we need first to architect and decide the tech stack. So first question is: where exactly should the new solution be hosted? On a blockchain? Blockchains come with many benefits: security, public accessibility, and transparency for everyone - features that many CEXs do not offer to this extent.

Why do AMMs need blockchains?

Because every swap must be:

  • Public – accessible to everyone

  • Immutable – so no one can cheat

  • Secure – resistant to hacks and exploits

  • Composable – natively callable by other DeFi smart contract to unlock more opportunities and profits

Blockchains are designed exactly for this.


Step 2: Decide the Swap Equation

Maintaining an order book with 1,000 sellers and 800 buyers - each with their own pricing - is very expensive and complex. But without an order book, how do we decide how much ETH you get for your USDC?

That’s where Automated Market Makers shine - they replace order books with a simple math equation that sets the price, updates it automatically, and balances trades without needing any mediators in between. That's the beauty of AMMs and Blockchains combined.

Instead of matching buy/sell orders, we create a pool in the AMM protocol with good amounts of Token A and Token B and allow swapping on them guided by math formulas.

So what is the math formula we should be using to make sure prices are adjusted automatically and trades remain balanced?

Let’s try this equation first. This is called the Constant Sum Model.

x + y = k

Where:
- x = total number of Token A in the pool
- y = total number of Token B in the pool
- k = total sum of Token A and Token B

Example

If a pool has 100 ETH + 100 USDC = 200 (x + y = k),

Swapping 10 ETH gives exactly 10 USDC.

Do you see any problem in this?

Yes, there are multiple problems:

  1. 1 ETH is priced at $3,000+ in the market, so getting just 10 USDC for 10 ETH is a massive loss for the user who is depositing 10 ETH in the above example.

  2. This equation will be helpful only when we have 1:1 pricing. For example, both USDC and DAI are almost equal to $1, so swapping 1 USDC we expect around 1 DAI, which the above equation solves. But there is one inherent problem in it which is called Arbitrage and here is an example: Pool: 100 DAI + 100 USDC = 200 If market prices DAI at $0.99, you can: Buy cheap DAI from market at $0.99 Swap 100 DAI → 100 USDC in the pool (free $1 profit per DAI) Repeat until the pool is drained

This is known as arbitrage, and many arbitrage bots constantly look for these opportunities. There’s nothing wrong with making a profit - but at what cost?

The AMM loses all funds to arbitrage.

The main goal of the protocol is to keep trading active - it should never stop. So pure x + y = k is never used because it’s economically unstable.


Step 3: The Real Swap Equation That Changed DeFi

Now, what math equation should we use to avoid the above problems? How can we stop the pool from getting drained?

We need an equation where:

  • Large swaps impact the price (aka slippage)

  • The more you buy, the more expensive it becomes (as per market nature: more demand, less supply)

  • Liquidity doesn't fully disappear - it just gets expensive

This is the final equation introduced by Uniswap. It’s called the Constant Product Model.

x * y = k

Where:
- x = total number of Token A in the pool
- y = total number of Token B in the pool
- k = constant product of the two

Spot price
P = y/x

This equation:

  • Adapts to market conditions

  • Prevents easy exploits

  • Keeps liquidity balanced

Example Why x * y = k Works

Initial Pool

  • Token A reserve: x = 5

  • Token B reserve: y = 5

Constant product:
k = x * y = 5 * 5 = 25

Spot price:
P = y / x = 5 / 5 = 1 B per A

Trader buys 1 A

New A reserve:
x′ = 5 – 1 = 4

Solve for new B reserve:
y′ = k / x′ = 25 / 4 = 6.25

B paid by trader (Δy):
Δy = y′ – y = 6.25 – 5 = 1.25 B

After the Trade

  • Pool is now (4 A, 6.25 B)

  • Trader gave 1.25 B and received 1 A

New spot price:
P′ = y′ / x′ = 6.25 / 4 = 1.5625 B per A

Key Takeaways

  • You paid 1.25 B for that 1 A (more than the initial 1 B), because buying A makes it scarcer.

  • The pool remains liquid—no matter how many you buy, there’s always a price.

  • Price adjusts automatically from 1.00 to 1.56 B/A through the math alone.

This illustrates how x * y = k enforces dynamic pricing, and P = y/x gives the instantaneous exchange rate. With this we now know user can’t drain all of one token without pushing the price sky-high.

Result: A dynamic, self-correcting market — no oracles, no limit orders, just math. So as you buy ETH (reduce y, increase x), the price increases - this is how AMMs simulate real-world supply/demand

The price of tokens isn't fixed - it's dynamic based on the above equation.

How does equation solves the problems mentioned above?

  1. Self-Correcting Prices (No Manual Intervention)

    Prices automatically adjust based on supply/demand:

    If ETH demand ↑ → Price ↑ If ETH demand ↓ → Price ↓

    Example:

    ETH is $1,800 on Coinbase but $2,000 in the AMM Arbitrageurs buy ETH on Coinbase and sell it to the AMM Profits continue until prices match

    No need for centralized price feeds. Arbitrage is healthy — as long as it doesn’t drain the pool completely.

b. Ensures Liquidity Never Runs Out

  • k must stay constant → liquidity never hits zero

  • Even if someone buys 99 ETH out of 100: Remaining pool: 1 ETH + 2,000,000 USDC Next ETH costs 2,000,000 USDC

Result: The pool always has liquidity — just at worse rates. This avoids draining it entirely.

As x → 0, y → ∞ because k = x * y must hold.

So even if there's just 0.01 ETH left, the price becomes astronomical — not 0.

This is what prevents draining the pool entirely.


Step 4: Who are Liquidity Providers (LPs)?

In Step 2, we said the pool holds good amounts of Token A and Token B. But where do these tokens come from?

From Liquidity Providers.

  • If the pool has no USDC, how will you swap 10 ETH?

  • It’s critical for the pool to have both tokens to enable trading.

So how do we encourage users to add their tokens to the pool?

We reward them.

Whenever a user swaps tokens, they pay a small fee.

This fee is:

  • Partially sent to the protocol

  • Remaining is distributed to liquidity providers

This is a major difference from CEXs — where fees go only to the exchange. Here, they also go to the liquidity providers who decided to participate and contribute. It is important to encourage liquidity providers because more liquidity means a better market and price stability.

The liquidity providers don’t just swap — they contribute to the market. And in return, they earn from the system.

Let’s move to next step which will break down how trades are executed, how fees are calculated, and how LP shares are minted and tracked.


Step 5: Know the Underlying Maths

  1. Swap Execution with Fee

    Trader submits Δx of Token A (e.g. 10 ETH)

    Fee (0.3%) is deducted from input:

    Δx_afterFee = Δx × (1 – 0.003) = 10 × 0.997 = 9.97 ETH where Δx => Token Input

    Constant‐product update (x * y = k):

    k = x * y k = 100 ETH × 200 000 USDC = 20 000 000

    x′ = x + Δx_afterFee = 100 + 9.97 = 109.97 ETH

    y′ = k / x′ ≈ 20 000 000 / 109.97 ≈ 181 868 USDC

    Output to trader: Δy = y – y′ = 200,000 – 181,868 ≈ 18,132 USDC

    Result: Trader pays 10 ETH, receives ~18,132 USDC. Pool ends at (109.97 ETH, 181 868 USDC).

    Because the 0.03 ETH fee remains in the pool, the new invariant k′ > k, so Liqudity provider value compounds over time and will be claimed by them when Redeeming LP tokens

  2. How Liquidity providers Earn

    Initial setup: Pool = 100 ETH + 200 000 USDC Alice adds 10 ETH + 20,000 USDC (10% share), receives LP tokens

    Trade generates 0.03 ETH in fees:

    LPs split 90% → 0.027 ETH Protocol keeps 10% → 0.003 ETH

    Pool after trade:

    ETH = 109.97 USDC = 181 868

    Alice’s share remains 10%

    Withdrawal yields:

    ~10% of 109.97 ETH ≈ 10.997 ETH ~10% of 181 868 USDC ≈ 18 186.8 USDC

    Value: ~($21,994 + $18,187) = $40,181 (> initial $40,000)

    Key takeaway:

    LPs earn passive fees proportional to volume—more trades → more fees → higher LP returns.

    Now lets move to the last step where we secure our AMMs.


Step 6: Secure your AMM — Common Attacks and How to Prevent Them

Always build secure AMM from day 0. If you skip it early, everyone loses:

  • Users → lose funds due to exploits

  • Liquidity Providers → suffer impermanent loss or unfair share

  • Protocol Builders → reputation and treasury wiped

  • Protocol Integrators → get rugged through faulty pricing


Here are few Key Principles

  • Simulate attack vectors (e.g. reserve manipulation, price spoofing)

  • Handle edge cases (zero liquidity, malicious first depositors)

  • Use defensive design (slippage, TWAPs, delayed actions)

  • Write tests that break things, not just pass happy paths

  • Assume your contracts are public and attackers are watching

Top AMM Attacks

1. Sandwich Attack

An attacker sees your swap coming (e.g. buy ETH) and:

  1. Front-runs: Buys ETH before you → price goes up

  2. You swap: You get less ETH

  3. Back-runs: Sells ETH after you → profits from your trade

You get sandwiched, they profit.

Mitigation:

  • Use tight slippage (minAmountOut)

  • Trade via private relayers (e.g. Flashbots, MEV Blocker)

  • Split large trades across time/pools


2. Reserve Manipulation (Oracle Attack)

Protocol uses getReserves() to read price:

price = tokenB / tokenA

Attacker swaps large amount to skew price, then:

  • Borrows, mints, or triggers logic based on fake price

  • Reserves revert later, but protocol already lost assets

Example:

Fake price makes a token seem cheap — attacker buys lots at a discount.

Mitigation:

  • Use TWAP oracles over multiple blocks

  • Enforce minimum liquidity for price validity

  • Delay sensitive actions (like lending/minting) by 1+ blocks


3. Inflation Attack on AMMs

Attack scenario:

  1. A new AMM pool is deployed (empty).

  2. Attacker adds 1 wei of token A and token B → receives 1 LP token.

  3. Attacker sends 1000e18 tokens of A and B directly to the pool (no LP mint).

  4. Calls sync() → pool updates reserves.

  5. Now, attacker’s 1 LP token represents all the liquidity (≈ 2000e18).

  6. Now Other LPs must now match that full amount (1000e18 + 1 wei tokens) to get 1 LP token (or get nothing)

    Result: Pool is griefed — normal users can’t provide liquidity due to inflated LP value. LP token economics are broken

Mitigation:

Burn MINIMUM_LIQUIDITY on First Mint

When totalSupply == 0 (first mint):

  • Mint MINIMUM_LIQUIDITY = 1000 LP tokens to address(0) (burn address).

  • Subtract it from actual LPs given to the first user.

uint public constant MINIMUM_LIQUIDITY = 1000;

if (totalSupply() == 0) {
    liquidity = sqrt(amount0 * amount1) - MINIMUM_LIQUIDITY;
    _mint(address(0), MINIMUM_LIQUIDITY); // lock forever
}
...

First LP provider can’t control 100% of the pool. LP token price remains fair for future liquidity providers.


Tip: AMMs are simple math (x * y = k), but small design flaws = big exploits. Always assume attackers are watching, simulating, and front-running.

Summary of Key Concepts

  • Constant Product Rule: x * y = k ensures liquidity and price stability.

  • Automated Pricing: P = y / x adjusts algorithmically with trades.

  • No Liquidity Crises: Reserves can’t be fully drained (unlike x + y = k).

  • Slippage: Larger trades face higher price impact due to Δy non-linearity.

  • Arbitrage Incentives: Traders align AMM prices with external markets.

  • Fee Mechanics: Fees grow k over time, rewarding liquidity providers.

  • Common Attack vectors: Secure your AMM from day 1

Here is a quest for you

Before moving to next article, here’s a quest for you. This will help you solidify the understanding

Take a pen and paper, and calculate the input amount required when a user wants a specific output token amount, using the constant product invariant x * y = k.

Assume fees are deducted from the output token, and make sure you include the fee in your calculation

Here is the solution to it but check it only after you have genuinely attempted it.

Congrats if you're still with me—by now, you've grasped the basic core mechanics of DeFi AMMs.

In the next article, we'll dive into Curve-style DeFi AMM math, which explains why x * y = k equation doesn't work well with stablecoins like DAI and USDC 🙂. Curve takes this math to the next level. Lets understand it in next part. We will also learn how to use desmos to visualize our maths equations on the graph

Author: Ashish Lachuria

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