ChainScore Labs
All Guides

Introduction to Automated Market Makers (AMMs)

LABS

Introduction to Automated Market Makers (AMMs)

A technical deep dive into the protocols that power decentralized trading.
Chainscore © 2025

Core AMM Concepts

An overview of the fundamental mechanisms that power decentralized exchanges, enabling permissionless token trading through algorithmic liquidity pools.

Constant Product Formula

x * y = k is the foundational mathematical model used by AMMs like Uniswap V2. It dictates that the product of the quantities of two tokens in a liquidity pool must remain constant.

  • Ensures liquidity is always available at some price, preventing empty pools.
  • Price is determined by the ratio of the two assets; as one is bought, its price increases.
  • This automated pricing mechanism eliminates the need for traditional order books, allowing for continuous, 24/7 trading.

Liquidity Pools

Liquidity pools are smart contract-held reserves of two or more tokens that facilitate trading. Users, called Liquidity Providers (LPs), deposit an equal value of both assets to create the pool.

  • Provide the capital that enables all swaps on the AMM.
  • LPs earn trading fees from every transaction executed against their pooled assets.
  • This model democratizes market making, allowing anyone to contribute capital and earn passive income, as seen with pools for ETH/USDC.

Impermanent Loss

Impermanent Loss is the potential loss in dollar value experienced by LPs compared to simply holding their assets, caused by price volatility in the pool.

  • Occurs when the price ratio of the pooled tokens changes after deposit.
  • The loss is 'impermanent' because it is only realized if the LP withdraws during the price divergence.
  • This is a critical risk for LPs to understand, as high volatility can sometimes outweigh earned fee rewards.

Automated Pricing

Automated Pricing refers to the algorithm that determines token prices based solely on the ratio of assets in a liquidity pool, without external price feeds.

  • Prices adjust automatically with each trade via the constant product formula.
  • Can lead to slippage, where large trades get worse rates as they deplete one side of the pool.
  • This system ensures a trustless and transparent market, though it often relies on oracles for accurate initial pricing in more advanced AMMs.

Liquidity Provider Tokens (LP Tokens)

LP Tokens are receipt tokens minted and issued to users when they deposit assets into a liquidity pool, representing their share of the total pool.

  • Act as a claim ticket to withdraw your proportional share of the pool plus accrued fees.
  • Can often be used in other DeFi protocols for yield farming or as collateral.
  • For example, depositing into a Uniswap V2 pool gives you UNI-V2 tokens, enabling complex DeFi strategies like staking in a yield aggregator.

The Constant Product Formula: x * y = k

Process overview for understanding the core mechanism of an Automated Market Maker (AMM).

1

Understanding the Core Invariant

Grasp the foundational rule that governs liquidity pools.

Detailed Instructions

At the heart of the most common AMMs, like Uniswap V2, lies the Constant Product Formula: x * y = k. This invariant ensures that the product of the quantities of two tokens in a liquidity pool (x and y) must always remain constant (k), regardless of trades. This simple rule automatically determines prices based on the available supply of each asset.

  • Sub-step 1: Define the variables: Let x be the reserve of Token A (e.g., ETH) and y be the reserve of Token B (e.g., DAI) in the pool.
  • Sub-step 2: Establish the constant: The product k = x * y is calculated after the initial liquidity deposit and must be preserved after every trade.
  • Sub-step 3: Observe price impact: The price of Token A in terms of Token B is given by Price_A = y / x. As x increases (someone sells A), y must decrease to keep k constant, making A cheaper.

Tip: This model creates slippage: larger trades execute at worse average prices because they move the ratio x/y more significantly.

2

Executing a Swap Transaction

Calculate the output of a trade and update the pool reserves.

Detailed Instructions

To perform a swap, a user specifies an input amount of one token, and the AMM calculates the output of the other token using the constant product rule. The formula to calculate the output amount Δy when inputting Δx (with a small fee φ, typically 0.3%) is derived from (x + Δx * (1 - φ)) * (y - Δy) = k.

  • Sub-step 1: Account for the fee: First, deduct the protocol fee from the input. For a 0.3% fee, the effective input to the pool is Δx_effective = Δx * 0.997.
  • Sub-step 2: Calculate the output: Solve the invariant for the new y' reserve: y' = k / (x + Δx_effective). The output amount is Δy = y - y'.
  • Sub-step 3: Update the reserves: After the trade, the new pool state becomes (x_new, y_new) = (x + Δx_effective, y - Δy).
code
// Example: Pool has 100 ETH (x) and 400,000 DAI (y). k = 40,000,000. // User swaps 10 ETH for DAI with 0.3% fee. let effectiveInput = 10 * 0.997; // = 9.97 ETH let newX = 100 + 9.97; // = 109.97 ETH let newY = 40000000 / newX; // ≈ 363,735.66 DAI let outputDAI = 400000 - 363735.66; // ≈ 36,264.34 DAI

Tip: The user receives approximately 36,264 DAI. Notice the price per ETH paid is ~3,626 DAI, higher than the initial 4,000 DAI/ETH price due to slippage.

3

Providing Liquidity and Minting LP Tokens

Deposit tokens into a pool to earn fees and receive liquidity provider tokens.

Detailed Instructions

Liquidity providers (LPs) deposit an equivalent value of both tokens into the pool. They must deposit in a ratio equal to the current reserve ratio to avoid arbitrage and preserve the price. In return, they receive LP tokens, which represent their share of the pool and accrue trading fees.

  • Sub-step 1: Determine deposit amounts: If the pool has reserves (x, y), and you want to deposit based on an amount A of Token A, you must also deposit B = (y / x) * A of Token B.
  • Sub-step 2: Mint LP tokens: The number of LP tokens minted is proportional to your share of the pool. If totalSupply is the current LP token supply, you receive minted = totalSupply * (A / x).
  • Sub-step 3: Track your share: Your LP tokens entitle you to a proportional claim on the entire pool's reserves and the accumulated fees (which are automatically reinvested by increasing k).
code
// Example: Adding liquidity to the 100 ETH & 400,000 DAI pool. // You deposit 1 ETH. Required DAI deposit = (400,000 / 100) * 1 = 4,000 DAI. // If total LP supply is 1000 tokens, you get minted = 1000 * (1 / 100) = 10 LP tokens. // You now own 1% of the pool (10/1000).

Tip: Always deposit using a front-end interface like the Uniswap UI at app.uniswap.org or via a contract call to the addLiquidity function to ensure correct ratios.

4

Analyzing Impermanent Loss

Understand the risk LPs face from price divergence.

Detailed Instructions

Impermanent Loss (IL) is not a direct loss of funds but an opportunity cost incurred by LPs when the price ratio of the pooled assets changes compared to when they were deposited. It occurs because the AMM automatically rebalances the pool, selling the appreciating asset and buying the depreciating one to maintain x * y = k.

  • Sub-step 1: Calculate value if held: Determine the value of your initial deposit if you had simply held the tokens in your wallet, based on the new market prices.
  • Sub-step 2: Calculate value in the pool: Determine the value of your LP share, which is your portion of the new pool reserves (x_new, y_new) at the new market prices.
  • Sub-step 3: Quantify the difference: Impermanent Loss = (Value in Pool - Value if Held) / Value if Held. The loss is greatest when prices diverge significantly.
code
// Example: You deposited 1 ETH & 4,000 DAI (Price: 1 ETH = 4,000 DAI). // Later, market price shifts to 1 ETH = 8,000 DAI. // Value if Held: 1*8000 + 4000 = 12,000 DAI. // Pool rebalances. New reserves can be calculated. Your 1% share might be worth ~11,314 DAI. // IL = (11314 - 12000) / 12000 ≈ -5.7%

Tip: IL is 'impermanent' because if the price returns to its original ratio, the loss vanishes. It becomes permanent upon withdrawing at the changed price. Trading fees are meant to compensate for this risk.

Comparing AMM Pricing Models

Comparison of core pricing mechanisms used by leading Automated Market Makers.

Pricing ModelConstant Product (Uniswap v2)Concentrated Liquidity (Uniswap v3)StableSwap (Curve Finance)Hybrid Function (Balancer v2)

Core Formula

x * y = k

x * y = k (within a range)

x + y = k & x * y = k

Weighted Geometric Mean

Primary Use Case

General volatile pairs

Capital efficiency for volatile pairs

Stable/pegged asset pairs

Custom multi-asset pools

Price Impact

High for large trades

Configurable, lower within range

Very low for small deviations

Varies by asset weights

Impermanent Loss Risk

High

Very High (if price exits range)

Very Low

Medium, depends on correlation

Liquidity Provider Control

Passive, full range

Active, set custom price ranges

Passive, optimized for stability

Passive, set custom asset weights

Example Fee Tier

0.30%

0.05%, 0.30%, 1.00%

0.04%

Customizable (e.g., 0.01% to 1%)

Gas Efficiency

Moderate

Lower (complex positions)

High (for stable swaps)

Moderate to High

Liquidity Provider Economics

Process overview for providing liquidity to an Automated Market Maker (AMM).

1

Understanding the AMM Pool & LP Tokens

Learn the core mechanics of liquidity pools and the minting of LP tokens.

Detailed Instructions

An Automated Market Maker (AMM) is a decentralized exchange protocol that uses mathematical formulas to price assets. Liquidity providers (LPs) deposit equal value of two tokens (e.g., ETH and USDC) into a liquidity pool. In return, the AMM mints and issues LP tokens (Liquidity Provider tokens) to the depositor's wallet address. These tokens are a receipt and represent your proportional share of the entire pool.

  • Sub-step 1: Choose a Pool: Select a trading pair like ETH/USDC on a platform like Uniswap V3. The pool address might be 0x8ad599c3A0ff1De082011EFDDc58f1908eb6e6D8.
  • Sub-step 2: Deposit Equal Value: You must deposit assets in a 50/50 value ratio. To provide $10,000 of liquidity, deposit ~$5,000 worth of ETH and ~$5,000 worth of USDC.
  • Sub-step 3: Receive LP Tokens: Upon deposit, the contract mints LP tokens to your address. You can view them in your wallet; their quantity defines your pool share.

Tip: The value of your LP tokens fluctuates with the total value of the pool and is subject to impermanent loss.

2

Calculating Fees and Impermanent Loss

Analyze the revenue from trading fees and the risk of diverging asset prices.

Detailed Instructions

LPs earn a percentage of every trade that occurs in their pool, typically 0.01% to 1% per swap. However, they are exposed to impermanent loss (IL), which is the loss compared to simply holding the assets, occurring when the price ratio of the pooled tokens changes. The loss is 'impermanent' because it can reverse if prices return to the original ratio.

  • Sub-step 1: Fee Calculation: For a pool with a 0.3% fee, a $10,000 trade generates $30 in fees, distributed proportionally to all LPs.
  • Sub-step 2: IL Simulation: Use a calculator. If ETH price doubles relative to USDC after you deposit, your LP position might be worth ~$13,400 versus $14,100 if you had just held, resulting in an IL of ~5%.
  • Sub-step 3: Net Profit Analysis: Your real yield is Fees Earned - Impermanent Loss. Consistently high volume can offset moderate IL.

Tip: Concentrated liquidity models (like Uniswap V3) allow you to set custom price ranges to earn higher fees but require active management.

3

Depositing Liquidity via Smart Contract

Execute the transaction to add liquidity to a pool using a Web3 interface.

Detailed Instructions

Interacting directly with the AMM's smart contract requires precise function calls. The primary function is often addLiquidity, which handles the token approvals and deposit. Always verify contract addresses on the project's official documentation or a block explorer.

  • Sub-step 1: Approve Tokens: First, approve the AMM router to spend your tokens. For USDC on Ethereum, you might call:
code
usdcContract.approve(routerAddress, amount)
  • Sub-step 2: Call Add Liquidity: Then, call the router's function. For a Uniswap V2-style router:
code
router.addLiquidity( address(tokenA), address(tokenB), amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline )
  • Sub-step 3: Set Parameters: amountAMin and amountBMin are slippage tolerances (e.g., 0.5%). The deadline is a future block timestamp (e.g., block.timestamp + 1200 for 20 minutes).

Tip: Using a front-end UI (like app.uniswap.org) simplifies this process but understanding the underlying calls is crucial for safety.

4

Monitoring and Withdrawing Funds

Track your position's performance and remove liquidity to reclaim your assets.

Detailed Instructions

Continuous monitoring is essential. You must track your accumulated fees (often automatically added to the pool, increasing the value of your LP tokens) and the current pool prices. To exit, you burn your LP tokens to withdraw your underlying assets, which will include your original deposit plus any accrued fees, minus any impermanent loss realized upon withdrawal.

  • Sub-step 1: Track Your Position: Use a dashboard like DeBank or Zapper. Input your wallet address 0xYourAddressHere to see the value of your LP tokens and estimated fees.
  • Sub-step 2: Remove Liquidity: Call the removeLiquidity function on the router. You must specify the amount of LP tokens to burn and minimum amounts of each token you will accept.
code
router.removeLiquidity( address(tokenA), address(tokenB), liquidity, // amount of LP tokens to burn amountAMin, amountBMin, to, deadline )
  • Sub-step 3: Claim Rewards (if any): Some protocols offer additional liquidity mining rewards in a governance token (e.g., UNI). You may need to claim these from a separate staking contract.

Tip: The withdrawal transaction will finalize any impermanent loss. Always check that the current pool composition aligns with your expectations before withdrawing.

Advanced AMM Architectures

Getting Started with AMMs

An Automated Market Maker (AMM) is a decentralized exchange protocol that uses mathematical formulas to price assets and provide liquidity. Instead of matching buyers and sellers, users trade against a liquidity pool—a smart contract holding reserves of two or more tokens. This allows for permissionless, 24/7 trading.

Key Principles

  • Constant Product Formula: The core of many AMMs like Uniswap V2, where the product of the quantities of two tokens in a pool (e.g., x * y = k) remains constant, determining prices automatically.
  • Liquidity Providers (LPs): Users who deposit token pairs into pools to earn trading fees, but face impermanent loss risk if asset prices diverge.
  • Slippage: The difference between expected and executed trade prices, which increases with trade size relative to pool depth.

Real-World Example

When you swap ETH for DAI on Uniswap, you interact with the ETH/DAI liquidity pool. The protocol's algorithm calculates how much DAI you receive based on the pool's reserves, ensuring the constant product is maintained after your trade.

SECTION-FAQ

Frequently Asked Questions

Ready to Start Building?

Let's bring your Web3 vision to life.

From concept to deployment, ChainScore helps you architect, build, and scale secure blockchain solutions.