AMM & Liquidity Pools
Automated Market Makers (AMMs) replaced order books in DeFi with mathematical formulas. The constant product formula (x × y = k) used by Uniswap V2 enabled billions in daily volume with zero human market makers.
Building a Simple AMM
AMM core concepts:
- Liquidity Pool: reserves of two tokens (e.g., ETH + USDC)
- Constant product formula: x × y = k
- x = reserve of token A, y = reserve of token B
- k must stay constant after any swap (excluding fees)
- Price = ratio of reserves: price_A = y / x (in token B units)
- Slippage = price impact from the trade size vs pool size
Swap mechanics:
- Trader sends dx of token A
- Pool calculates dy from formula: (x + dx)(y - dy) = k
- dy = y - k/(x + dx) = y × dx / (x + dx)
- Fee (e.g., 0.3%) taken from dx before formula applies
LP (Liquidity Provider):
- Deposits both tokens in current ratio
- Receives LP tokens = proportional share of pool
- Earns swap fees proportional to their LP shareCommon Mistakes
- Not implementing minimum output (slippage protection) — always include a minAmountOut parameter and check it. Without it, MEV bots sandwich every swap and steal value.
- Forgetting the minimum liquidity lock — Uniswap V2 burns MINIMUM_LIQUIDITY LP tokens to prevent the first LP from manipulating the price to zero after removing all liquidity.
- Using integer division before multiplication — (a / b) * c loses precision. Always multiply first: (a * c) / b.
Tip
Tip
Practice AMM Liquidity Pools in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Once deployed, smart contracts are immutable — code is law
Practice Task
Note
Practice Task — (1) Write a working example of AMM Liquidity Pools from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with AMM Liquidity Pools is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready web3 code.
Key Takeaways
- Automated Market Makers (AMMs) replaced order books in DeFi with mathematical formulas.
- Not implementing minimum output (slippage protection) — always include a minAmountOut parameter and check it. Without it, MEV bots sandwich every swap and steal value.
- Forgetting the minimum liquidity lock — Uniswap V2 burns MINIMUM_LIQUIDITY LP tokens to prevent the first LP from manipulating the price to zero after removing all liquidity.
- Using integer division before multiplication — (a / b) * c loses precision. Always multiply first: (a * c) / b.