Book a free call

How to Implement an AMM Step by Step

An AMM is a pool of two tokens priced by a formula. Implementing one means choosing the model, writing the pool contract and testing it before launch.

Hertiv engineering teamReviewed by a senior engineer
5 min read
How to Implement an AMM Step by Step
On this page

Short answer

An automated market maker, or AMM, is a smart contract that holds a pool of two tokens and prices swaps with a formula instead of an order book. Implementing one means choosing the pricing model, writing the pool and token handling, and testing it thoroughly before anyone deposits funds.

What is an AMM, and what does implementing one involve?

An automated market maker is a smart contract that holds reserves of two tokens and lets anyone swap between them at a price set by a formula. There is no order book and no counterparty: the pool itself is the other side of every trade.

Implementing an AMM means building the pool contract, the maths that sets the price, the logic that mints and burns liquidity shares, and the safety checks that stop bad trades. You also need a way for users to add liquidity, remove it, and collect fees.

The work splits into four parts: the pricing model, the pool contract, the liquidity token, and the front end or router that users call. The contract is the hard part; the front end is a convenience layer on top. What an AMM is explains the model in plain terms.

Which AMM model should you choose?

The pricing model is the first decision, because it sets how the pool behaves when trades are large or when the two tokens should stay near the same price.

Model How it prices Best for
Constant product x times y stays constant General token pairs
Stable swap Flatter curve near 1 to 1 Stablecoins and pegged assets
Concentrated liquidity Liquidity in a price range Capital-efficient pools
Weighted pools Unequal token weights Index-style pools

Constant product is the simplest model and the right default for a first AMM: two reserves, one formula, and price that moves with every trade. Stable swap fits pairs that should track each other, while concentrated liquidity and weighted pools add complexity that only pays off when you need it.

What do you need before you start coding?

Before you write the pool contract, you need the token pair, the fee, the chain and the safety rules written down. These choices shape the contract, so changing them later means rewriting and re-testing.

  • Token pair. Which two tokens, and are both standard ERC-20 tokens with normal transfer behaviour?
  • Fee. A common starting point is 0.3% per swap, paid to liquidity providers.
  • Chain. Gas costs and finality differ by chain, and they change how often users will trade.
  • Oracle need. Decide whether the pool needs an external price feed, for example to guard against manipulation.
  • Access control. Decide who can pause the pool, change fees or upgrade the contract, and how that power is held.

Write these decisions in a short spec before coding. A spec forces the team to agree on the maths and the edge cases, and it gives auditors something to check the code against. AMM cost covers what using a pool costs a trader.

How do you implement an AMM, step by step?

You implement an AMM by building the pool contract in small, tested pieces: reserves and pricing first, then liquidity shares, then fees, then safety checks.

  1. Set up the project. Use a standard framework such as Hardhat or Foundry, with a test network and a linting setup.
  2. Write the pool state. Store the two token addresses and the two reserve amounts, and a function that reads them together.
  3. Add the pricing maths. For constant product, keep x times y constant: a swap in of one token must leave the product unchanged after the trade.
  4. Add liquidity shares. Mint pool tokens when users deposit, in proportion to the pool size, and burn them on withdrawal.
  5. Add the fee. Take the fee from the input amount before the pricing maths runs, and send it to the pool reserves.
  6. Add safety checks. Reject zero amounts, check deadlines, guard against reentrancy, and set a minimum output for each swap.
  7. Build a router. A thin contract or front-end helper that moves tokens into the pool and returns the output in one call.

Keep each step small and test it before moving on. A pool contract that is hard to test is usually a contract with too much logic in one function.

How do you test an AMM before launch?

You test an AMM by checking the maths, the edge cases and the attacks before anyone deposits real funds. Testing is where most AMM projects should spend their time, because a pricing bug is a direct loss of funds.

  • Unit tests. Test every function: swaps, deposits, withdrawals, fees and every revert condition.
  • Property tests. Check invariants that must always hold, such as the product of reserves never falling after a swap.
  • Simulation. Run many random trades and check that prices, fees and shares stay consistent.
  • Edge cases. Test the first deposit, tiny amounts, huge amounts, and a pool drained to near zero.
  • Audit. Get an independent review before launch, and re-check fixes after it.

Test on a public testnet with real users if you can. Testnet trading finds front-end and rounding issues that unit tests miss, and it costs nothing but time. Liquidity pool cost explains what providers pay and earn.

Example (hypothetical): a two-token pool in numbers

Example (hypothetical): a team launches a pool with 100,000 TOKEN-A and 50,000 TOKEN-B. The constant product is 100,000 times 50,000, which is 5,000,000,000, and the starting price is 0.5 TOKEN-B per TOKEN-A.

A trader swaps 1,000 TOKEN-A into the pool. The new TOKEN-A reserve is 101,000, so the new TOKEN-B reserve must be 5,000,000,000 divided by 101,000, which is about 49,505. The trader receives 50,000 minus 49,505, or about 495 TOKEN-B.

With a 0.3% fee, the fee is 3 TOKEN-A, so only 997 TOKEN-A enters the pricing maths. The new reserve is then 5,000,000,000 divided by 100,997, or about 49,506, and the trader receives about 494 TOKEN-B. The fee stays in the pool and goes to liquidity providers over time.

What are the common mistakes?

The most common AMM implementation mistakes are getting the maths wrong at the edges, skipping reentrancy protection, and launching without an audit.

  • Rounding errors. Integer maths rounds down; check that tiny trades and the first deposit cannot break the pool.
  • No reentrancy guard. A token that calls back into the pool during a transfer can drain funds if the state updates after the call.
  • Missing minimum output. Without a slippage limit, a trader can be front-run into a bad price.
  • Fee maths in the wrong place. The fee must be taken before pricing, or the product invariant breaks.
  • Launching unaudited. A pool holding user funds needs an independent review, not just passing tests.
  • Ignoring the first deposit. The first liquidity provider sets the price; a bad first deposit can lock the pool at a wrong ratio.

If the AMM is part of a larger exchange, a DEX development partner can help with the pool design, the router and the audit preparation.

Key takeaways

  • An AMM prices swaps with a formula, so there is no order book and no counterparty
  • Constant product is the simplest model and the right default for a first AMM
  • Decide the token pair, fee, chain and access control before writing code
  • Build in small, tested pieces: reserves, pricing, shares, fees, then safety checks
  • Test the maths, the edge cases and the attacks — then get an audit before launch

Frequently asked questions

Do I need an order book to run an AMM?

No. An AMM replaces the order book with a pricing formula and a pool of tokens. Traders swap against the pool, and the price moves with each trade. The pool contract, not a list of orders, sets the price.

What is the simplest AMM model to implement?

Constant product, where the product of the two reserves stays the same after every trade. It needs one formula, works for most token pairs, and is the easiest model to test and audit. Start there unless your pair needs a flatter curve.

How much does it cost to implement an AMM?

It depends on scope, chain and audit. The main costs are development time, testing, an independent audit and deployment gas. A simple pool on a low-fee chain is a small project; a feature-rich exchange with routing and oracles is much larger.

Can I implement an AMM without writing Solidity?

You can fork an existing AMM, but you still need to read and understand the code before you deploy it. Copying a contract you do not understand is risky, because a small change can break the pricing maths or the safety checks.

What is impermanent loss in an AMM?

It is the loss liquidity providers face when the price of the pooled tokens moves apart. The pool sells the token that rises and buys the one that falls, so providers can end with less value than if they had held the tokens. Fees offset it, but do not always cover it.

Do AMMs need an audit?

Yes, before real funds go in. An AMM holds user deposits and its pricing maths is the attack surface. Tests catch bugs you thought of; an audit looks for the ones you did not. Budget for the audit as part of the build, not as an afterthought.

Found this useful? Share it.
Hertiv engineering team

Written from projects we build for clients: blockchain systems in production. Every post is reviewed by a senior engineer before publishing and updated when practice changes.

About HertivHow we work

Building a decentralised exchange and need the pool contract designed?

A senior engineer replies within one business day. Or see our DEX Development service.

Book a free call

Keep reading

All posts

Tell us what you want to build

A senior engineer reads every request and replies within one business day with questions, a rough range, or a call link.

  • NDA on request before any details
  • You own all code, models and IP
  • US, UK and EU time-zone overlap

Your email app should open with your message ready to send. If it does not, write to [email protected].

Prefer email? Write to [email protected]
Estimate costBook a call