SolidityIn

Building a simple AMM

Lesson 23 of 40 · DeFi

An automated market maker, or AMM, lets people trade tokens without an order book. Instead of matching buyers and sellers, a contract holds a pool of two tokens, and the price comes from the ratio between them. Uniswap made this design popular.

The classic rule is the constant product formula, x times y equals k. If the pool holds x of token A and y of token B, a trade must leave the product at least as large as before. Buying token B removes some B from the pool, so the pool must receive enough A to keep the product from falling.

The bigger your trade compared to the pool, the worse your price gets. This effect is called slippage. A swap function should let the caller set a minimum amount to receive, so a price move between signing and mining cannot cost more than they accept.

Real pools also charge a fee, usually 0.3 percent, which stays in the pool and rewards the people who supply liquidity. The example below keeps balances as plain numbers to show only the swap math. Never use the spot price from a single pool as an oracle, because a large trade can move it.

contract MiniPool {
    uint256 public reserveA = 1000e18;
    uint256 public reserveB = 1000e18;

    // How much B you receive for amountIn of A, after a 0.3% fee
    function quoteAForB(uint256 amountIn) public view returns (uint256) {
        uint256 inWithFee = amountIn * 997;
        return (inWithFee * reserveB) / (reserveA * 1000 + inWithFee);
    }
    function swapAForB(uint256 amountIn, uint256 minOut) external returns (uint256 out) {
        out = quoteAForB(amountIn);
        require(out >= minOut, "Slippage too high");
        reserveA += amountIn;
        reserveB -= out;
    }
}

Try it yourself

Call quoteAForB with 1e18 and then with 500e18 and compare the amounts you receive per unit. Then add a swapBForA function that works in the other direction.

Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.

Quick check: What does slippage mean?