SolidityIn

Code an Automated Market Maker (AMM) in Solidity from Scratch

November 9, 2026 · admin · Uncategorized

Automated Market Makers (AMMs) are the backbone of Decentralized Finance (DeFi). Pioneered by platforms like Uniswap, Curve, and Balancer, AMMs replace traditional order books with mathematical formulas that price assets algorithmically.

Understanding the Core Math: The Constant Product Formula

The most famous and intuitive AMM design is the Constant Product Market Maker (CPMM), popularized by Uniswap V2. It relies on a simple invariant equation:

x × y = k

Where:

  • x: Reserve balance of Token A.
  • y: Reserve balance of Token B.
  • k: Constant invariant that must remain unchanged (or increase) during a trade.

When a trader deposits an amount of Token A (Δx) into the pool, they must receive an amount of Token B (Δy) such that the product of the reserves remains equal to k:

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

Solving for Δy (output token amount):

Δy = (y × Δx) / (x + Δx)

System Architecture

To build a functional AMM pool, our smart contract must handle three primary actions:

  1. Add Liquidity: Users deposit equal-value ratios of Token0 and Token1 and receive LP (Liquidity Provider) tokens representing their share of the pool.
  2. Remove Liquidity: Users burn LP tokens to withdraw their proportional share of underlying reserves.
  3. Swap: Traders supply one token and receive the other based on the constant product formula.

Step-by-Step Implementation

1. Setting Up the Contract

We will inherit OpenZeppelin’s ERC-20 implementation so our pool contract can mint and burn its own LP shares natively.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract SimpleAMM is ERC20 {
IERC20 public immutable token0;
IERC20 public immutable token1;
uint256 public reserve0;
uint256 public reserve1;
constructor(address _token0, address _token1) ERC20("AMM Liquidity Provider", "AMM-LP") {
token0 = IERC20(_token0);
token1 = IERC20(_token1);
}
function _update(uint256 _reserve0, uint256 _reserve1) private {
reserve0 = _reserve0;
reserve1 = _reserve1;
}
}

2. Math Helpers: Square Root

When the very first liquidity provider deposits tokens, we calculate the initial LP shares using the geometric mean: sqrt(x × y). We need a basic helper function implementing the Babylonian method for square roots:

function _sqrt(uint256 y) private pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
function _min(uint256 x, uint256 y) private pure returns (uint256) {
return x < y ? x : y;
}

3. Adding Liquidity

Liquidity providers must supply both tokens in proportion to existing reserves to prevent altering the pool price. In return, they receive newly minted LP tokens.

function addLiquidity(uint256 _amount0, uint256 _amount1) external returns (uint256 shares) {
token0.transferFrom(msg.sender, address(this), _amount0);
token1.transferFrom(msg.sender, address(this), _amount1);
if (totalSupply() == 0) {
// Initial liquidity minting
shares = _sqrt(_amount0 * _amount1);
} else {
// Enforce existing pool ratio
shares = _min(
(_amount0 * totalSupply()) / reserve0,
(_amount1 * totalSupply()) / reserve1
);
}
require(shares > 0, "Shares minted must be greater than 0");
_mint(msg.sender, shares);
_update(token0.balanceOf(address(this)), token1.balanceOf(address(this)));
}

4. Removing Liquidity

When burning LP tokens, the provider receives their percentage share of both reserves:

function removeLiquidity(uint256 _shares) external returns (uint256 amount0, uint256 amount1) {
require(_shares > 0, "Shares must be > 0");
uint256 totalShares = totalSupply();
amount0 = (_shares * reserve0) / totalShares;
amount1 = (_shares * reserve1) / totalShares;
require(amount0 > 0 && amount1 > 0, "Insufficient liquidity redeemed");
_burn(msg.sender, _shares);
_update(reserve0 - amount0, reserve1 - amount1);
token0.transfer(msg.sender, amount0);
token1.transfer(msg.sender, amount1);
}

5. Swapping Tokens

Now, let’s implement the core trading mechanism. We include a standard 0.3% trading fee that remains inside the pool to reward liquidity providers.

function swap(address _tokenIn, uint256 _amountIn) external returns (uint256 amountOut) {
require(_tokenIn == address(token0) || _tokenIn == address(token1), "Invalid token");
require(_amountIn > 0, "Amount must be > 0");
bool isToken0 = _tokenIn == address(token0);
(IERC20 tokenIn, IERC20 tokenOut, uint256 resIn, uint256 resOut) = isToken0
? (token0, token1, reserve0, reserve1)
: (token1, token0, reserve1, reserve0);
tokenIn.transferFrom(msg.sender, address(this), _amountIn);
// Apply 0.3% fee: multiply by 997 / 1000
uint256 amountInWithFee = (_amountIn * 997) / 1000;
// Formula: dx * y / (x + dx)
amountOut = (resOut * amountInWithFee) / (resIn + amountInWithFee);
require(amountOut > 0, "Insufficient output amount");
tokenOut.transfer(msg.sender, amountOut);
_update(token0.balanceOf(address(this)), token1.balanceOf(address(this)));
}

Production Considerations

While the contract above is functional, production-ready AMMs (such as Uniswap V2/V3) implement critical safety layers:

  • Slippage Limits: Always allow callers to pass a minAmountOut parameter to protect against front-running and MEV attacks (e.g., Sandwich attacks).
  • Reentrancy Guard: State updates should follow the Checks-Effects-Interactions pattern or employ OpenZeppelin’s ReentrancyGuard.
  • Minimum Liquidity Lock: Prevent pool manipulation by locking a negligible amount (e.g., 1000 units) of LP tokens permanently upon the initial deposit.

Conclusion

By leveraging the x × y = k invariant and wrapping it inside an ERC-20 token interface, you have successfully written a decentralized exchange from scratch. This foundational pattern underpins hundreds of billions of dollars in transaction volume across EVM-compatible blockchains today.

Tags: , , ,