Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Guides

How to Implement Automated Market Maker (AMM) Logic

This guide walks through implementing core AMM logic in Solidity, covering the constant product formula, liquidity management, and swap execution with practical code.
Chainscore © 2026
introduction
CORE MECHANICS

Introduction to AMM Implementation

Automated Market Makers (AMMs) are the foundational smart contracts that power decentralized exchanges like Uniswap and Curve. This guide explains the core mathematical logic behind constant product and stable swap AMMs.

An Automated Market Maker (AMM) is a decentralized exchange protocol that uses a mathematical formula to price assets. Instead of matching buy and sell orders in an order book, traders swap tokens against a liquidity pool, a smart contract holding reserves of two or more tokens. The most common formula is the constant product invariant x * y = k, popularized by Uniswap V2. Here, x and y represent the reserves of two tokens in the pool, and k is a constant. When a trader buys token y with token x, the pool's x increases and y decreases, but their product must always equal k. This relationship automatically determines the swap price and creates slippage: larger trades cause greater price impact.

Implementing a basic constant product AMM requires calculating the output amount for a given input. The formula Δy = (y * Δx) / (x + Δx) determines how much token y (Δy) a user receives for depositing Δx of token x. A 0.3% fee is typically deducted from the input amount before the swap calculation. In Solidity, the core swap function involves ensuring the invariant k is maintained after fees and verifying the pool has sufficient reserves. Developers must also implement liquidity provision functions that allow users to deposit paired assets in the correct ratio to mint LP tokens, which represent their share of the pool.

For stablecoin pairs (e.g., USDC/DAI), the constant product model creates excessive slippage. Stable swap AMMs like Curve's Stableswap use a hybrid invariant: A * (x + y) + (x * y) = A * (D^2) + (D^3 / (4*x*y)). This formula creates a "flatter" curve within a price range near 1:1, offering significantly lower slippage for like-valued assets. The variable A is an amplification coefficient set by governance; a higher A makes the curve flatter. Implementing this requires more complex math, often using the Newton's method for approximation within the contract to solve for D (the total liquidity) and output amounts.

Critical considerations for AMM implementation include security and gas optimization. Reentrancy guards (using Checks-Effects-Interactions pattern or OpenZeppelin's ReentrancyGuard), proper decimal handling (e.g., using 1e18 for scaling), and overflow protection are essential. For production, most developers fork and customize audited codebases like Uniswap V2's core contracts or the Vyper-based Curve pool contracts. Understanding these core mechanics is the first step to building advanced DeFi primitives like concentrated liquidity (Uniswap V3) or integrating AMM logic into broader protocols for lending or derivatives.

prerequisites
PREREQUISITES

How to Implement Automated Market Maker (AMM) Logic

Before building an AMM, you need a solid foundation in core blockchain concepts and smart contract development.

To implement AMM logic, you must first understand the underlying blockchain infrastructure. This requires proficiency in a smart contract language like Solidity (for Ethereum and EVM chains) or Rust (for Solana). You'll need to be comfortable with concepts like state variables, functions, and events. Familiarity with development frameworks such as Hardhat, Foundry, or Anchor is essential for testing and deployment. A working knowledge of token standards, particularly ERC-20, is non-negotiable, as AMMs primarily facilitate trades between these fungible assets.

The mathematical core of an AMM is its bonding curve, which defines the relationship between the reserves of two tokens in a pool. The most common model is the Constant Product Market Maker (x * y = k), popularized by Uniswap V2. In this model, the product of the quantities of two tokens (x and y) must remain constant (k) before and after a trade, which automatically determines the price. Understanding this formula, along with concepts like slippage (price impact of a trade size) and impermanent loss (divergence loss for liquidity providers), is critical for implementing swap and liquidity functions correctly.

You will need to interact with existing contracts and infrastructure. This includes knowing how to use oracles like Chainlink for price feeds if your AMM requires external price data, and understanding decentralized governance mechanisms if the protocol will be community-owned. Security is paramount; you must be adept at writing secure code to prevent common vulnerabilities like reentrancy attacks, integer overflows, and front-running. Auditing your code or using formal verification tools should be part of your development lifecycle.

Finally, practical implementation involves designing several key smart contract components: a factory contract to deploy new liquidity pools, a pair/pool contract that holds reserves and executes swaps, and a router contract that handles the complex logic for user-facing operations (e.g., adding liquidity with optimal token ratios). You should study the source code of established AMMs like Uniswap V2 (for its elegant simplicity) or Uniswap V3 (for concentrated liquidity) to see these patterns in action.

core-math-explanation
AMM FUNDAMENTALS

Core Mathematical Model: The Constant Product Formula

The Constant Product Formula is the foundational algorithm behind decentralized exchanges like Uniswap V2. It enables permissionless trading by algorithmically pricing assets based on their relative scarcity within a liquidity pool.

At the heart of an Automated Market Maker (AMM) is a simple, deterministic mathematical rule. The Constant Product Formula states that for a liquidity pool containing two assets, X and Y, the product of their quantities must remain constant. This is expressed as x * y = k, where x is the reserve of token X, y is the reserve of token Y, and k is the constant product. This invariant ensures that as one token is purchased from the pool, its reserve decreases, causing its price relative to the other token to increase non-linearly. This mechanism of bonding curves automatically adjusts prices based on supply and demand without an order book.

To calculate the output amount when swapping, you solve the invariant. If a trader wants to swap Δx amount of token X for token Y, the new reserve of X becomes x + Δx. To keep k constant, the new reserve of Y must be y' = k / (x + Δx). The amount of Y the trader receives, Δy, is the difference: Δy = y - y'. This yields the core swap formula: Δy = y - (k / (x + Δx)). This calculation is performed on-chain for every trade, and the resulting price impact increases with the size of the trade relative to the pool's liquidity.

Implementing this in a smart contract involves managing the reserves and enforcing the invariant. Below is a simplified Solidity code snippet demonstrating the core logic. The contract updates the reserve state after verifying the trader has supplied sufficient input tokens and that the output amount is positive.

solidity
// Simplified AMM swap function (no fees)
function swap(uint amountXIn) public returns (uint amountYOut) {
    uint newReserveX = reserveX + amountXIn;
    // Calculate new reserveY using constant product formula: k = x * y
    uint newReserveY = (reserveX * reserveY) / newReserveX;
    // Amount of Y to send to trader
    amountYOut = reserveY - newReserveY;
    // Update state reserves
    reserveX = newReserveX;
    reserveY = newReserveY;
}

In production AMMs like Uniswap, a 0.3% trading fee is added to the model. This fee is deducted from the input amount before the swap calculation, and the fee liquidity is added back to the reserves, incrementally increasing k and rewarding liquidity providers. The formula with a fee φ (e.g., 0.003) becomes: (x + Δx * (1 - φ)) * (y - Δy) = k. This small modification is crucial for sustainability, as it ensures the pool is not depleted by arbitrageurs and generates yield from trading volume. The fee also affects the effective exchange rate received by the trader.

Understanding this model is key to analyzing impermanent loss and pool dynamics. When the external market price of the two assets diverges, arbitrageurs trade against the pool to rebalance its price, changing the ratio of reserves. Liquidity providers own a share of both reserves, so their portfolio value compared to simply holding the assets can decrease—this is impermanent loss. The Constant Product Formula's convex curve shape dictates the magnitude of this loss, which is highest for large price movements. Developers use this model to simulate returns and risks when designing or interacting with DeFi protocols.

key-concepts
IMPLEMENTATION GUIDE

Key AMM Components

To build an Automated Market Maker, you must understand its core mathematical and smart contract components. This guide breaks down the essential logic.

01

Constant Product Formula (x*y=k)

The foundational algorithm for most AMMs like Uniswap V2. It ensures liquidity is always available by maintaining a constant product of token reserves.

  • Price is determined by the ratio of the two tokens in the pool.
  • Impermanent Loss occurs when the price ratio changes between deposit and withdrawal.
  • Slippage increases with trade size relative to pool depth. For a pool with 100 ETH and 200,000 USDC (k=20,000,000), swapping 10 ETH yields approximately 18,181 USDC.
02

Liquidity Provider (LP) Tokens

ERC-20 tokens minted to represent a provider's share of the pool. They are the key to tracking ownership and fees.

  • Minted on deposit: When you add 1 ETH and 2000 USDC, you receive LP tokens proportional to your contribution.
  • Redeemed for underlying: Burning LP tokens returns your share of the pool's current reserves, plus accrued fees.
  • Fee accrual: Trading fees (e.g., 0.3%) are added to the pool, increasing the value of each LP token over time.
03

Router Contract

The primary user-facing contract that handles all trade and liquidity operations. It ensures safety and optimal routing.

  • Manages swap paths: Can route trades through multiple pools for better prices.
  • Enforces deadlines: Transactions revert if not mined within a set block time, protecting users.
  • Calculates optimal amounts: Uses the constant product formula to determine output amounts and validate minimums set by the user.
04

Price Oracle

AMMs provide a decentralized source of price data. Uniswap V2 introduced the time-weighted average price (TWAP) oracle.

  • Cumulative price: The contract stores the cumulative price sum at the start of each block.
  • TWAP calculation: Oracles like Chainlink can read this storage to compute an average price over a time window (e.g., 30 minutes).
  • Manipulation resistance: Large single-block price swings are averaged out, providing a robust feed for other DeFi protocols.
05

Fee Structure & Distribution

Fees incentivize liquidity providers and protocol development. Implementation varies by AMM version.

  • Protocol Fee: A percentage (e.g., 1/6th of the 0.3% fee in Uniswap V3) can be directed to a treasury.
  • LP Fee: The remaining fee is added to the pool's reserves, benefiting all liquidity providers.
  • Dynamic Fees: Some AMMs like Balancer allow pools to set custom fee percentages (e.g., 0.01% to 1%).
implementing-pool-contract
CORE LOGIC

Step 1: Implementing the Pool Contract

The pool contract is the central smart contract that holds the liquidity and executes the core Automated Market Maker (AMM) logic, such as the constant product formula x * y = k.

An AMM pool contract manages two token reserves and defines the pricing algorithm. The most common is the constant product formula popularized by Uniswap V2, where the product of the two reserve amounts must remain constant before and after a trade (reserveA * reserveB = k). This formula determines the exchange rate: the price impact of a trade increases non-linearly as the pool's liquidity is depleted. The contract must also track the total supply of liquidity provider (LP) tokens, which represent a share of the pooled assets.

The contract requires several key functions. The swap function allows users to trade one token for another, updating the reserves according to the formula and charging a small fee (e.g., 0.3%) that is added to the reserves. The mint function issues new LP tokens when a user adds liquidity, calculating the amount based on the current reserves to maintain fair ownership. Conversely, the burn function destroys LP tokens and returns the proportional share of both underlying tokens to the user who is removing liquidity.

A critical implementation detail is the handling of the initial liquidity deposit. The first depositor sets the initial price ratio. To prevent manipulation, many protocols, like Uniswap V2, lock a minimum amount of LP tokens (sent to address zero) on the first mint. All subsequent price calculations and LP token minting are based on the updated k constant. The contract must also implement a flash loan-resistant design by performing all balance checks and state updates within a single transaction.

Here is a simplified Solidity snippet for the core swap logic, excluding fees for clarity:

solidity
function swap(uint amountAOut, address to) external {
    uint reserveA = reserve0;
    uint reserveB = reserve1;
    require(amountAOut < reserveA, "Insufficient liquidity");
    
    uint amountBIn = getAmountIn(amountAOut, reserveA, reserveB);
    require(IERC20(tokenB).transferFrom(msg.sender, address(this), amountBIn), "Transfer failed");
    
    _update(reserveA - amountAOut, reserveB + amountBIn);
    require(IERC20(tokenA).transfer(to, amountAOut), "Transfer failed");
}

function getAmountIn(uint amountAOut, uint reserveA, uint reserveB) internal pure returns (uint amountBIn) {
    // amountBIn = (reserveB * amountAOut) / (reserveA - amountAOut)
    amountBIn = (reserveB * amountAOut) / (reserveA - amountAOut);
}

Security is paramount. The contract must guard against common vulnerabilities: - Reentrancy attacks: Use the checks-effects-interactions pattern. - Rounding errors: Favor integer math and decide on rounding direction (always in favor of the pool). - Oracle manipulation: If the pool price is used as an oracle, consider implementing a time-weighted average price (TWAP) like Uniswap V2. The contract should also emit standard events (Swap, Mint, Burn) for off-chain indexing and user interface updates.

After deploying the core pool contract, the next step is to build a factory contract that can create instances of these pools for any ERC-20 token pair. This factory ensures a single canonical pool for each pair, manages the pair addressing scheme (often using create2), and serves as a registry for the entire protocol's liquidity.

implementing-swap-logic
CORE MECHANICS

Step 2: Implementing Swap Logic

This section details the mathematical formulas and smart contract logic that power token swaps in an Automated Market Maker (AMM).

At the heart of every AMM is the constant product formula: x * y = k. Here, x and y represent the reserves of two tokens in a liquidity pool, and k is a constant. This invariant ensures that the product of the reserves remains unchanged before and after a trade. When a user swaps token A for token B, they deposit Δx of token A into the pool. To maintain the constant k, the pool must calculate and output Δy of token B, where (x + Δx) * (y - Δy) = k. The resulting amount is derived by solving for Δy: Δy = y - (k / (x + Δx)).

Implementing this in a smart contract requires handling fees and preventing rounding errors. A standard approach deducts a protocol fee (e.g., 0.3%) from the input amount Δx before the swap calculation. The fee is kept in the pool, incrementally increasing the value of k and rewarding liquidity providers. The core swap function must also account for slippage, which is the difference between the expected and actual output price due to the trade's size relative to pool liquidity. Contracts typically require a user to specify a minimum output amount to protect against front-running and excessive slippage.

Here is a simplified Solidity function outline for a swap:

solidity
function swap(uint amountIn, uint minAmountOut) external {
    uint fee = amountIn * protocolFee / 10000;
    uint amountInAfterFee = amountIn - fee;
    uint newReserveX = reserveX + amountInAfterFee;
    uint newReserveY = constantK / newReserveX;
    uint amountOut = reserveY - newReserveY;
    require(amountOut >= minAmountOut, "Slippage too high");
    // Update reserves and transfer tokens...
}

This logic ensures the pool's invariant is maintained, fees are collected, and users are protected from unfavorable trades.

Beyond the basic constant product model, advanced AMMs implement concentrated liquidity (like Uniswap V3) or stable swap curves (like Curve Finance). Concentrated liquidity allows liquidity providers to set custom price ranges, making capital efficiency the primary innovation. The swap math becomes more complex, involving virtual reserves and piecewise calculations within ticks. Understanding the foundational x*y=k model is essential before exploring these advanced designs, as they all build upon the same core principles of invariant preservation and fee mechanics.

implementing-liquidity-logic
CORE AMM MECHANICS

Step 3: Implementing Liquidity Provision Logic

This section details the mathematical and smart contract logic for adding and removing liquidity from a constant product AMM pool.

The core of an Automated Market Maker (AMM) is its invariant function, which defines the mathematical relationship between the assets in a pool. The most common model is the constant product formula x * y = k, where x and y are the reserves of two tokens and k is a constant. This formula ensures that the product of the reserves remains unchanged by trades, creating a predictable price curve where price is the ratio of the reserves. When a liquidity provider (LP) deposits assets, they must do so in a ratio that maintains the current price, minting them new LP tokens representing their share of the pool.

To implement deposit logic, your smart contract must calculate how many LP tokens to mint. First, determine the pool's total supply of LP tokens. If it's the first deposit, the minted amount is sqrt(reserveA * reserveB). For subsequent deposits, the amount is (amountA / reserveA) * totalSupply. The contract must enforce that the user deposits both tokens in the exact current reserve ratio to prevent dilution. A critical check is ensuring the minted tokens are greater than zero to avoid locking funds. Uniswap V2's UniswapV2Pair.sol is the canonical implementation of this logic.

The withdrawal function is the inverse. A user burns their LP tokens to redeem their proportional share of both reserve assets. The amount of each token returned is calculated as (liquidity / totalSupply) * reserveA and (liquidity / totalSupply) * reserveB. The contract must transfer these amounts to the user and safely burn the LP tokens. Always perform these transfers after updating the internal state reserves to prevent reentrancy attacks, a best practice formalized in the Checks-Effects-Interactions pattern. This ensures the contract's state is consistent before any external calls.

Beyond basic deposits, consider implementing features like protocol fees. Many AMMs collect a small fee (e.g., 0.05%) on trades, which is distributed to LPs. This can be done by inflating the value of k over time or by minting extra LP tokens to a fee address. Furthermore, your contract must accurately track accumulated fees per LP position, which is complex without external helper contracts. Many modern AMMs use concentrated liquidity, which requires tracking fees per tick or price range, a significant increase in logic complexity compared to the simple constant product pool described here.

When testing your implementation, focus on edge cases: the first deposit, tiny deposits that round to zero LP tokens, massive deposits that could overflow calculations, and withdrawals that drain the pool. Use a framework like Foundry or Hardhat to simulate these scenarios. The security of the liquidity provision logic is paramount, as bugs can lead to permanent loss of user funds. Always audit your code or use well-audited libraries like the Solidity SDK from Uniswap Labs.

CORE LOGIC

Comparison of AMM Pricing Models

Key differences between the most common constant function market maker (CFMM) formulas used in decentralized exchanges.

Pricing ModelConstant Product (Uniswap v2)StableSwap (Curve)Concentrated Liquidity (Uniswap v3)

Mathematical Formula

x * y = k

(x + y) + (D / (x * y)) = D

x * y = k (within a price range)

Primary Use Case

Volatile asset pairs

Stablecoin/pegged asset pairs

Capital-efficient volatile pairs

Capital Efficiency

Price Impact for Trades

High for large trades

Very low near peg

Configurable by liquidity provider

Impermanent Loss Risk

High

Very Low

High (outside chosen range)

Typical Swap Fee

0.3%

0.04%

0.05% - 1.0% (tiered)

Liquidity Distribution

Uniform across all prices

Concentrated at peg (e.g., 1.0)

Concentrated in custom price ranges

Oracle Feasibility

Time-weighted average price (TWAP)

Needs external oracle for robustness

Built-in TWAP oracle

fee-mechanisms
FEE MECHANISMS AND LP INCENTIVES

How to Implement Automated Market Maker (AMM) Logic

A technical guide to building the core logic of a constant product AMM, focusing on swap calculations, fee collection, and liquidity provider incentive structures.

An Automated Market Maker (AMM) is a decentralized exchange protocol that uses a mathematical formula to price assets. The most common model is the constant product formula x * y = k, where x and y are the reserves of two tokens in a pool, and k is a constant. This invariant ensures that the product of the reserves remains unchanged by trades. When a user swaps token A for token B, they add Δx to the x reserve and receive Δy from the y reserve, causing the price to move along a bonding curve. The core swap logic calculates the output amount based on this invariant and an applied fee.

Implementing the swap function requires precise calculation to maintain the invariant and deduct fees. First, calculate the output amount Δy a user should receive for an input Δx before fees: Δy = y - (k / (x + Δx)). A protocol fee (e.g., 0.05% for Uniswap v2) is then applied. This is typically deducted from the input amount, so the actual Δx used in the invariant calculation is reduced. The fee is added to the pool's reserves, incrementally increasing the value of each liquidity provider's (LP) share. This mechanism ensures LPs are compensated for impermanent loss and providing capital.

Liquidity providers earn fees proportional to their share of the pool. When an LP deposits assets, they receive LP tokens, which represent a claim on the pool's underlying reserves and accrued fees. The exchange rate of LP tokens increases as fees accumulate. For example, if an LP owns 10% of the pool's LP tokens, they are entitled to 10% of the total reserves upon withdrawal, which will be larger than their initial deposit due to collected fees. This automated fee distribution is the primary incentive for LPs. Smart contracts must accurately track total LP token supply and calculate share values using reserve balances.

A basic Solidity implementation highlights these concepts. The swap function would: 1) Ensure input amount > 0, 2) Calculate k from current reserves, 3) Deduct fee from input amount (e.g., inputAmount * 997 / 1000 for a 0.3% fee), 4) Calculate new reserve of input token, 5) Solve the constant product formula for the output token amount, 6) Update reserves and transfer tokens. The mint function for adding liquidity calculates LP tokens based on the deposit's proportional value relative to existing reserves, protecting LPs from dilution.

Advanced AMMs like Uniswap v3 introduce concentrated liquidity, allowing LPs to provide capital within specific price ranges. This increases capital efficiency but requires more complex logic to track multiple liquidity positions and fees accrued within each tick interval. The fee calculation must aggregate earnings across all active ticks where a swap occurred. Understanding the basic constant product model is essential before tackling these advanced implementations, as they build upon the same core principles of invariant preservation and fee-based LP incentives.

AMM IMPLEMENTATION

Frequently Asked Questions

Common developer questions and solutions for building and troubleshooting Automated Market Maker logic, from constant product formulas to advanced features like fee-on-transfer tokens.

The constant product formula, x * y = k, is the foundational invariant for AMMs like Uniswap V2. Here, x and y represent the reserves of two tokens in a pool, and k is a constant that must remain unchanged before and after a trade.

Price is not stored but derived from the ratio of reserves. The spot price of token A in terms of token B is Price_A = y / x. When a trader swaps Δx of token A for token B, they receive Δy. The new reserves become x' = x + Δx and y' = y - Δy. The invariant requires that (x + Δx) * (y - Δy) = k. Solving for Δy gives the output amount: Δy = y - (k / (x + Δx)).

This creates a sliding price where large swaps incur greater price impact, a key concept for liquidity providers and arbitrageurs.

conclusion-next-steps
IMPLEMENTATION SUMMARY

Conclusion and Next Steps

You have now built the core logic for a basic Automated Market Maker. This guide covered the foundational constant product formula, liquidity management, and swap execution.

The constant product formula x * y = k is the cornerstone of AMMs like Uniswap V2. By maintaining this invariant, the pool provides continuous liquidity, with prices determined algorithmically by the ratio of the two reserve assets. Your implementation should include precise, overflow-protected calculations for getAmountOut to determine swap outputs and getAmountIn for required input amounts, using integer math to avoid floating-point errors.

For production, this basic logic must be extended with critical security and economic features. Implement a protocol fee mechanism (e.g., a 0.05% fee sent to a treasury), a deadline parameter to protect users from stale transactions, and slippage tolerance checks. You must also add events for all state changes (Swap, Mint, Burn) to allow off-chain indexers to track pool activity, which is essential for front-ends and analytics.

Next, integrate your AMM logic with a user interface. Use a library like ethers.js or viem to connect to your deployed contract. A basic UI needs functions to: approve token spends, addLiquidity, removeLiquidity, and swapExactTokensForTokens. For price displays, call the getReserves function and calculate the current price as reserve1 / reserve0.

To deepen your understanding, study the source code of established AMMs. The Uniswap V2 Core contracts are the canonical reference for the constant product model. For more advanced concepts, examine Uniswap V3 with its concentrated liquidity or Balancer V2 with its weighted pools and asset manager architecture.

Finally, consider the broader ecosystem. Your AMM can be composed with other DeFi primitives: use it as a price oracle for lending protocols, integrate flash loans for arbitrage, or allow liquidity positions to be tokenized as NFTs for use in other financial applications. The constant product AMM is a foundational building block for decentralized finance.

How to Implement Automated Market Maker (AMM) Logic | ChainScore Guides