Core Idea of Uniswap V2 - constant product AMM

This formula ensures that trades adjust the reserves proportionally, causing the price (the ratio of reserves) to change dynamically based on supply and demand.

Swap’s math intuition

  1. xy = k, This invariant is maintained
  2. Example, token0 = 1 and token1 = 1000 Effectively, the liquidity provider is saying 1 token0 = 1000 token1 so x = 1, y 1000 and k = 1000

Example1: Swap 0.5 token0 in for token1

  1. Now let's say a user wants to Swap 0.5 token0 in for token1 Effective balance to swap = 0.5 * 0.997 ≈ 0.4985 (0.3% goes to fees) Now, we need to figure out how much 0.4985 token0 is equal to in token1 and return that to user
  2. This is "constant product" AMM, it maintains the product invariant, so

(x + Δx) * (y - Δy) = k

we want Δy, so

Δy = y - (k / (x + Δx))

= 1000 - (1000/ (1+ 0.4985) = 332.67 This is what the user will get 332.67 token1 for his 0.5 token0. New reserves: ~1.5 token0 AND ~667.33 token1 (k≈1000.5). 5. This means that after the swap, in the pool 1.5 token0 = 667.33 token1 or 1 token0 = 667.33/1.5 = 444.89 token1

So the price in the pool changed from 1 token0 = 1000 token1 to 1 token0 = 444.89 token1

Example2: Swap 500 token1 in for token0

Effective balance to be swapped = 500*0.997 = 498.5

new reserve1 = 1000+498.5

(x - Δx) * (y + Δy) = k