Build a Constant-Product AMM on Rootstock (Testnet)
A Constant-Product Automated Market Maker (AMM) is a decentralized exchange mechanism that maintains liquidity using the formula x * y = k, where the product of two token reserves remains constant after swaps.
By the end of this tutorial, you will have:
- A working
SimpleAMMconstant‑product AMM contract deployed on Rootstock testnet - A Hardhat test suite that validates add/remove liquidity and swaps
- A basic example of how to wire the contract into a frontend
Prerequisites
Prerequisites: Follow the Shared Setup Guide before starting.
For background concepts, token standards, and security review, see Rootstock DeFi Developer Guide.
This tutorial is a minimal implementation for learning and experimentation. Before shipping to production, review Rootstock DeFi Developer Guide and get professional audits.
Our SimpleAMM Contract
We'll build a contract that supports:
- Adding liquidity
- Removing liquidity
- Swapping token A for token B (and vice versa)
- Computing swap amounts
1. Contract Setup and State Variables
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract SimpleAMM {
IERC20 public tokenA;
IERC20 public tokenB;
uint256 public reserveA;
uint256 public reserveB;
uint256 public totalLiquidity;
mapping(address => uint256) public liquidity;
// Events for tracking
event LiquidityAdded(address indexed provider, uint256 amountA, uint256 amountB);
event LiquidityRemoved(address indexed provider, uint256 amountA, uint256 amountB);
event Swapped(address indexed swapper, address tokenIn, uint256 amountIn, address tokenOut, uint256 amountOut);
constructor(address _tokenA, address _tokenB) {
tokenA = IERC20(_tokenA);
tokenB = IERC20(_tokenB);
}
// ... functions will go here
}
Explanation:
-
tokenA and tokenB are the ERC-20 tokens the pool will trade.
-
reserveA and reserveB track the current reserves in the pool.
-
totalLiquidity is the total supply of LP tokens.
-
liquidity maps each address to their LP token balance.
-
Events help off-chain monitoring (e.g., for a frontend).