AMM Logic
Back to AMM: Automated Market Maker
Introduction
The logic behind XRPL's AMM is critical for understanding how prices are determined, LP tokens are calculated, and trades execute. This chapter provides a deep dive into the constant product formula, swap calculations, LP token minting/burning, and the precision handling that ensures numerical correctness.
Location: src/xrpld/app/misc/AMMHelpers.cpp and AMMHelpers.h
The Constant Product Formula
Core Invariant
XRPL's AMM uses the constant product formula, popularized by Uniswap:
x * y = kWhere:
x= Balance of Asset 1y= Balance of Asset 2k= Constant product (invariant)
How It Works
After every trade, the product of the two asset balances must remain constant (or increase slightly due to fees):
The inequality (>=) accounts for trading fees, which slightly increase k over time, benefiting liquidity providers.
Price Determination
The spot price of Asset1 in terms of Asset2 is:
As traders buy Asset1:
A decreases (removed from pool)
B increases (added to pool)
Price of Asset1 increases (B/A grows)
This creates automatic price discovery through supply and demand.
Swap Formulas
Swap Asset In (swapAssetIn)
Given an input amount, calculate the output amount.
Formula:
Where:
Location: src/xrpld/app/misc/AMMHelpers.h:443-505
Example:
Swap Asset Out (swapAssetOut)
Given a desired output amount, calculate the required input.
Formula:
Location: src/xrpld/app/misc/AMMHelpers.h:517-578
Rounding Strategy
Critical Design Decision: Rounding always favors the AMM pool.
swapAssetIn: Output is rounded down (less tokens out)swapAssetOut: Input is rounded up (more tokens required)
This ensures the pool never loses value due to rounding errors.
LP Token Calculations
Initial LP Tokens (ammLPTokens)
When creating a pool, initial LP tokens are the geometric mean:
Location: src/xrpld/app/misc/AMMHelpers.cpp:5-17
Why Geometric Mean?
Prevents manipulation by depositing unequal values
Initial depositor cannot "steal" value from pool
LP tokens represent true fractional ownership
LP Tokens for Deposit (lpTokensOut)
Calculate LP tokens received for depositing assets.
Proportional Deposit (Both Assets)
When depositing proportionally (same ratio as pool):
No trading fee charged for proportional deposits.
Single Asset Deposit
Equation 3 from AMMHelpers.cpp:
Where:
t= LP tokens receivedT= Total LP tokensb= Deposit amountB= Pool balance of deposited assetf1= 1 - tradingFeef2= (1 - tradingFee/2) / f1
Location: src/xrpld/app/misc/AMMHelpers.h:131-187
Assets Required for LP Tokens (ammAssetIn)
Calculate how much asset is needed for specific LP tokens.
Equation 4 (inverse of Equation 3):
LP Tokens to Burn (lpTokensIn)
Calculate LP tokens needed for a specific withdrawal.
Equation 7:
Where:
t= LP tokens to burnT= Total LP tokensR= withdrawal / poolBalancec= R * fee + 2 - fee
Assets for LP Token Burn (ammAssetOut)
Calculate assets received for burning LP tokens.
Equation 8:
Fee Calculations
Fee Multipliers
Constants:
Fee Ranges
Minimum: 0 (no fee)
Maximum: 1000 basis points (1%)
Typical: 30-100 basis points (0.03% - 0.1%)
Auction Slot Discount
Auction slot holders pay reduced fees:
Quality and Price Calculations
Spot Price Quality
The "quality" represents the exchange rate for offers:
For AMM, the spot price quality is:
Quality Matching with CLOB
The pathfinding engine needs AMM offers that match CLOB quality.
Location: src/xrpld/app/misc/AMMHelpers.h:310-420
Precision and Overflow Handling
Number Type
XRPL uses a custom Number type for AMM calculations:
Precision Amendments
Several amendments improve precision handling:
fixUniversalNumber
Required for AMM (precision improvements)
fixAMMv1_1
Rounding improvements
fixAMMv1_3
Precision loss compensation
fixAMMOverflowOffer
Overflow in offer calculation
Rounding Strategies
Invariant Checking
After every operation, verify the pool invariant:
Worked Examples
Example 1: Simple Swap
Example 2: LP Token Minting
Example 3: Single Asset Deposit
Summary
The AMM mathematics ensure:
Fair Pricing: Constant product formula provides automatic price discovery
LP Protection: Geometric mean prevents initial deposit manipulation
Fee Collection: Trading fees increase pool value over time
Numerical Safety: Careful rounding always favors the pool
CLOB Integration: Quality matching enables fair competition
Understanding these formulas is essential for:
Implementing AMM features
Debugging price discrepancies
Building AMM analytics tools
Auditing pool behavior
References to Source Code
src/xrpld/app/misc/AMMHelpers.cpp- Core calculationssrc/xrpld/app/misc/AMMHelpers.h- Formula implementationssrc/xrpld/app/misc/AMMCore.h- Constantssrc/libxrpl/basics/Number.cpp- Precision arithmetic
Cross-References
AMM Architecture - Data structures
AMM Transactions - How formulas are used
AMM Pathfinding - Quality matching in practice
Last updated

