An automated market maker, or AMM, replaces the order book of a traditional exchange with a pool of two tokens and a rule. Anyone can trade against the pool, and anyone can deposit tokens to earn a share of the trading fees. The rule that most pools in this family start from is astonishingly small: multiply the two reserves and keep the product from falling. It is called the constant-product formula, and it is a great way to learn how decentralized exchanges actually work.
In this post I'll build a small pool in Solidity, step by step, and test the properties that matter. It is a teaching example, not a product: I'll list what it leaves out at the end, and the list is long.
The idea in one equation
If the pool holds x of token A and y of token B, the invariant is x * y = k. A trader who adds some A must take out enough B that the product doesn't go down. Uniswap's documentation describes it this way: the pool prices tokens with the formula, and k is a value that must stay constant or increase after every trade. A consequence is that a larger trade, relative to the size of the pool, moves the price more. That effect is called price impact, and it is a feature of the design, not a bug.
Take a pool with 1,000 of each token, so k = 1,000,000. If you put in 10 of token A (ignoring fees for a moment), the pool has 1,010 A, so it must keep B at 1,000,000 / 1,010 = 990.1. You receive about 9.9 B. The price you got is slightly worse than 1:1 because you moved the pool.
Adding the fee
Real pools charge a fee. The original Uniswap whitepaper applies a 0.3% fee by reducing the amount paid in before the invariant is enforced. In integer arithmetic that becomes:
amountInWithFee = amountIn * 997
amountOut = (amountInWithFee * reserveOut) / (reserveIn * 1000 + amountInWithFee)
The multiplication by 997 and 1,000 avoids fractions, since Solidity has no floating point. The fee stays in the pool, so k actually grows with each trade. That is how liquidity providers get paid.
The contract
The pool has four jobs: accept deposits and issue shares, let providers withdraw, quote prices and execute swaps. The shares are an ordinary ERC-20 token (a liquidity-provider token) built on OpenZeppelin, so they can be transferred or used elsewhere.
MiniAMM.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
/// @notice Teaching example of a constant-product pool (x * y = k) with a 0.3% fee.
/// Not audited, no oracle, no protection against fee-on-transfer or rebasing tokens.
contract MiniAMM is ERC20 {
using SafeERC20 for IERC20;
IERC20 public immutable token0;
IERC20 public immutable token1;
uint256 public reserve0;
uint256 public reserve1;
uint256 public constant MINIMUM_LIQUIDITY = 1_000;
event Swap(address indexed trader, address tokenIn, uint256 amountIn, uint256 amountOut);
error InsufficientOutput(uint256 got, uint256 wanted);
error InvalidToken();
error ZeroAmount();
constructor(IERC20 a, IERC20 b) ERC20("Mini LP", "MLP") {
token0 = a;
token1 = b;
}
function addLiquidity(uint256 amount0Desired, uint256 amount1Desired) external returns (uint256 shares) {
uint256 amount0 = amount0Desired;
uint256 amount1 = amount1Desired;
if (reserve0 != 0 || reserve1 != 0) {
// Deposit in the pool's current ratio so the deposit does not move the price.
uint256 amount1Optimal = (amount0Desired * reserve1) / reserve0;
if (amount1Optimal <= amount1Desired) {
amount1 = amount1Optimal;
} else {
amount0 = (amount1Desired * reserve0) / reserve1;
}
}
if (amount0 == 0 || amount1 == 0) revert ZeroAmount();
token0.safeTransferFrom(msg.sender, address(this), amount0);
token1.safeTransferFrom(msg.sender, address(this), amount1);
if (totalSupply() == 0) {
shares = Math.sqrt(amount0 * amount1) - MINIMUM_LIQUIDITY;
_mint(address(0xdead), MINIMUM_LIQUIDITY); // permanently locked, guards against a tiny first pool
} else {
shares = Math.min((amount0 * totalSupply()) / reserve0, (amount1 * totalSupply()) / reserve1);
}
_mint(msg.sender, shares);
reserve0 += amount0;
reserve1 += amount1;
}
function removeLiquidity(uint256 shares) external returns (uint256 amount0, uint256 amount1) {
amount0 = (shares * reserve0) / totalSupply();
amount1 = (shares * reserve1) / totalSupply();
_burn(msg.sender, shares);
reserve0 -= amount0;
reserve1 -= amount1;
token0.safeTransfer(msg.sender, amount0);
token1.safeTransfer(msg.sender, amount1);
}
function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) public pure returns (uint256) {
uint256 amountInWithFee = amountIn * 997; // 0.3% fee
return (amountInWithFee * reserveOut) / (reserveIn * 1000 + amountInWithFee);
}
function swap(IERC20 tokenIn, uint256 amountIn, uint256 minAmountOut) external returns (uint256 amountOut) {
if (amountIn == 0) revert ZeroAmount();
bool zeroForOne;
if (address(tokenIn) == address(token0)) zeroForOne = true;
else if (address(tokenIn) != address(token1)) revert InvalidToken();
(IERC20 tIn, IERC20 tOut, uint256 rIn, uint256 rOut) =
zeroForOne ? (token0, token1, reserve0, reserve1) : (token1, token0, reserve1, reserve0);
amountOut = getAmountOut(amountIn, rIn, rOut);
if (amountOut < minAmountOut) revert InsufficientOutput(amountOut, minAmountOut); // slippage guard
tIn.safeTransferFrom(msg.sender, address(this), amountIn);
tOut.safeTransfer(msg.sender, amountOut);
if (zeroForOne) { reserve0 += amountIn; reserve1 -= amountOut; }
else { reserve1 += amountIn; reserve0 -= amountOut; }
emit Swap(msg.sender, address(tokenIn), amountIn, amountOut);
}
}
A few details worth explaining:
- First deposit. The first provider sets the price, so shares are the geometric mean
sqrt(amount0 * amount1), which doesn't depend on which token you call "first". I lock 1,000 share units forever at an unusable address. The code comment says what it is for: it guards against a pool seeded with a tiny amount. Locking a small minimum is a known defence against manipulation of the first-share price. I haven't audited that choice here, so treat it as a design note. - Later deposits. Providers must deposit in the pool's current ratio, otherwise they would move the price for free. The function calculates the best amounts from what the caller offers and takes shares in proportion.
- Slippage guard.
swaptakes aminAmountOutand reverts if the pool would give less. Between the moment a user signs a transaction and the moment it executes, the price can move, so every swap needs this protection. - SafeERC20 and custom errors. Transfers go through
safeTransferFrom, which reverts on failure, and errors are custom errors with data (InsufficientOutput(got, wanted)), which cost less than long strings and are easier to handle. - Internal reserves. The pool tracks its reserves in storage rather than reading its token balances. That keeps the maths predictable, but it also means tokens sent to the contract directly are ignored.
Tests that check the maths
MiniAMM.ts
import { expect } from "chai";
import { network } from "hardhat";
const { ethers, networkHelpers } = await network.create();
const e = ethers.parseEther;
async function deploy() {
const [lp, trader] = await ethers.getSigners();
const a = await ethers.deployContract("MockERC20", ["Token A", "AAA"]);
const b = await ethers.deployContract("MockERC20", ["Token B", "BBB"]);
const amm = await ethers.deployContract("MiniAMM", [await a.getAddress(), await b.getAddress()]);
const ammAddr = await amm.getAddress();
for (const t of [a, b]) {
await t.mint(lp.address, e("100000"));
await t.mint(trader.address, e("1000"));
await t.connect(lp).approve(ammAddr, ethers.MaxUint256);
await t.connect(trader).approve(ammAddr, ethers.MaxUint256);
}
await amm.connect(lp).addLiquidity(e("1000"), e("1000"));
return { a, b, amm, lp, trader };
}
describe("MiniAMM", function () {
it("mints sqrt(x*y) shares minus the locked minimum on first deposit", async function () {
const { amm, lp } = await networkHelpers.loadFixture(deploy);
expect(await amm.balanceOf(lp.address)).to.equal(e("1000") - 1000n);
expect(await amm.totalSupply()).to.equal(e("1000"));
});
it("swap output matches the constant-product formula with a 0.3% fee", async function () {
const { a, b, amm, trader } = await networkHelpers.loadFixture(deploy);
const amountIn = e("10");
const expected = (amountIn * 997n * e("1000")) / (e("1000") * 1000n + amountIn * 997n);
await amm.connect(trader).swap(await a.getAddress(), amountIn, 0n);
expect(await b.balanceOf(trader.address)).to.equal(e("1000") + expected);
});
it("k never decreases after a swap (the fee stays in the pool)", async function () {
const { a, amm, trader } = await networkHelpers.loadFixture(deploy);
const k0 = (await amm.reserve0()) * (await amm.reserve1());
await amm.connect(trader).swap(await a.getAddress(), e("50"), 0n);
const k1 = (await amm.reserve0()) * (await amm.reserve1());
expect(k1).to.be.gte(k0);
});
it("a bigger trade gets a worse price (price impact)", async function () {
const { amm } = await networkHelpers.loadFixture(deploy);
const small = await amm.getAmountOut(e("1"), e("1000"), e("1000"));
const big = await amm.getAmountOut(e("100"), e("1000"), e("1000"));
expect(small * 100n).to.be.gt(big); // 100x the input gets less than 100x the output
});
it("reverts when the output is below the trader's minimum (slippage guard)", async function () {
const { a, amm, trader } = await networkHelpers.loadFixture(deploy);
await expect(amm.connect(trader).swap(await a.getAddress(), e("10"), e("10")))
.to.be.revertedWithCustomError(amm, "InsufficientOutput");
});
it("removing all liquidity returns a proportional share", async function () {
const { a, b, amm, lp } = await networkHelpers.loadFixture(deploy);
const shares = await amm.balanceOf(lp.address);
const beforeA = await a.balanceOf(lp.address);
await amm.connect(lp).removeLiquidity(shares);
expect((await a.balanceOf(lp.address)) - beforeA).to.equal((shares * e("1000")) / e("1000"));
expect(await b.balanceOf(await amm.getAddress())).to.equal(1000n); // only the locked minimum remains
});
});
All six pass. The most informative ones:
- Swap matches the formula. The test calculates the expected output in the test itself using BigInt arithmetic and compares it with the trader's balance change. A test that only checks "balance went up" would pass a broken formula.
- k never decreases. After a 50-token swap, the product of the reserves is greater than or equal to the starting product. This invariant is the heart of the design and is exactly what you would want a fuzz test or a formal tool to hammer on.
- Price impact. Putting in 100 times as much returns less than 100 times as much.
- Slippage. A swap whose output is below the minimum reverts with the custom error.
What the tests do not cover
I ran the suite with Hardhat's --coverage flag. MiniAMM.sol came out at 78.05% line coverage and 70.91% statement coverage. The uncovered lines are exactly the paths I did not write tests for: adding liquidity to a pool that already has reserves (the ratio logic and the share formula for later deposits), the zero-amount and invalid-token reverts, and swapping in the opposite direction (token B for token A). So those paths are untested in this post, and the second-deposit maths in particular deserves its own tests before anyone trusts it. Coverage is a blunt tool, but it is excellent at catching this kind of blind spot.
Price impact in numbers
To see how impact scales, I computed the output of the same formula for a pool of 1,000 and 1,000, including the 0.3% fee (plain arithmetic, checked in Python):
| You put in | You receive | Effective price (out per 1 in) |
|---|---|---|
| 1 | 0.9960 | 0.9960 |
| 10 | 9.8716 | 0.9872 |
| 100 | 90.6611 | 0.9066 |
A trade of 1% of the pool costs you about 1.3% versus the ideal 1:1 price; a trade of 10% costs about 9.3%. Those figures include the 0.3% fee, so for the smallest trade most of the 0.4% gap is the fee itself. The lesson: pool depth is everything. A pool ten times deeper gives a given trade roughly a tenth of the impact.
What this example leaves out
Real pools handle all of these, and you would too before using real money:
- Reentrancy protection. Tokens with callbacks can re-enter. Add a guard on swap and liquidity functions, and read the reentrancy post for why.
- Unusual tokens. Fee-on-transfer tokens and rebasing tokens break the assumption that the amount sent equals the amount received. The contract's own header says so.
- Oracles. Don't use a pool's instantaneous price as a trusted price feed for other contracts. A large trade can move it within one transaction. That is a well-known source of exploits and one reason time-weighted prices exist.
- Deadlines. A swap that sits pending for minutes can execute at a stale price. Real routers add a deadline parameter on top of the slippage limit.
- Impermanent loss. Liquidity providers can end up with less value than if they had just held the tokens when prices move. Anyone depositing real funds should understand that tradeoff first. This post doesn't model it.
- Sandwich attacks. Public pending transactions can be front-run and back-run. Slippage limits help, but don't eliminate it.
- Rounding. Integer division always rounds down. Ensure that rounding favors the pool and not the trader, and test tiny amounts.
Exercises that teach the most
- Cover the gaps. Write tests for a second liquidity deposit (including an unbalanced one), the reverse swap direction and the reverts, until coverage shows them covered.
- Add a deadline parameter to
swapand test that late transactions revert. - Write a property test that runs random swaps and liquidity changes and asserts that
knever decreases and the contract's token balance is at least its reserves. - Add a reentrancy guard and write an attacker token that tries to re-enter during
transferFrom. - Break it on purpose. Change 997 to 1000 (no fee), run the tests, and see which fail. Then change the rounding direction and see which of your tests notice.
Understanding this 100-line contract makes the bigger designs easier to read. It is education only: nothing here is investment advice or a recommendation to provide liquidity or trade anywhere.
Building DeFi or token infrastructure?
I build and test Solidity contracts with property checks, not just happy-path tests. If you want a review before an audit, get in touch.
See services Get in touchWhat I ran this against
- Hardhat 3.22.0 (Mocha + ethers template), @openzeppelin/contracts 5.6.1, ethers 6.17.0, solc 0.8.34, Node.js 24.22.1, run on 17 November 2026 on Hardhat's in-process simulated network. Six tests pass (and leave about a fifth of the lines uncovered, see below): first-deposit shares, swap output against the formula, k never decreasing, price impact, the slippage guard, and removing liquidity.
- Nothing was deployed to a testnet or mainnet, and the contracts are teaching examples that have not been audited. It has no reentrancy guard on swaps, no oracle, no protection against fee-on-transfer or rebasing tokens, and no protocol fee, so do not deploy it with real funds. The price-impact figures in this post are plain arithmetic on the formula, checked in Python, not market data.
Sources checked
- Uniswap v1 whitepaper, the original description of the "constant product formula" and the 0.3% trading fee applied before the invariant is enforced: app.uniswap.org/whitepaper.pdf.
- Uniswap documentation, "How Uniswap works": pools price tokens with
x * y = k, larger trades relative to pool depth move the price more (price impact): docs.uniswap.org.