コンテンツへスキップ
Volume 2

The Automated Market Maker Mathematics Handbook

Mastering Constant Product Formulas and Liquidity Pool Algorithms

The code is the market, and the math is the law.

Strategic Objectives

• Master the core geometry of Constant Product Market Makers.

• Derive exact formulas for slippage and price impact.

• Understand the rigorous calculus behind impermanent loss.

• Optimize liquidity provision using advanced algorithmic curves.

The Core Challenge

Traditional order books fail in decentralized environments, leaving developers and traders struggling to quantify slippage and liquidity risk.

01

Foundations of Automated Exchanges

Transitioning from Order Books to Algorithms
You will explore the fundamental shift from human-intermediated trading to algorithmic execution. By understanding this foundation, you set the stage for why deterministic mathematical formulas are necessary to replace centralized matching engines.
The Limitations of Traditional Order Books
Why Human Intermediation Introduces Friction

Examine the operational constraints, liquidity bottlenecks, and latency issues inherent in centralized order book exchanges. Discuss how manual matching and market fragmentation create inefficiencies that motivate algorithmic alternatives.

Emergence of Algorithmic Trading
From Manual Orders to Deterministic Execution

Introduce the rise of programmatic trading strategies and automated execution engines. Highlight the transition from discretionary human decisions to reproducible algorithmic rules that can operate at scale and speed.

Conceptual Framework of Automated Market Makers
Core Principles Behind Constant Product Pools

Lay the groundwork for understanding AMMs by explaining how liquidity pools, pricing functions, and deterministic formulas replace the traditional bid-ask spread. Discuss why predictable outcomes are critical for decentralized environments.

02

The Constant Product Invariant

Understanding the x * y = k Equation
You will dissect the core equation that powers the majority of DeFi. This chapter ensures you grasp how maintaining a constant product forces price discovery and dictates the relationship between paired assets.
Foundations of the Constant Product Formula
The mathematical heartbeat of AMMs

Introduce the x * y = k equation, explaining its origin, structure, and why it serves as the backbone for decentralized liquidity pools. Discuss the conceptual meaning of 'k' as a constant and its implications for asset balance.

Price Discovery Through Invariant Maintenance
How the equation dictates market behavior

Explain how preserving the constant product enforces price changes automatically when trades occur, highlighting the mathematical link between trade size and price impact.

Liquidity Pools and Asset Pairing
Understanding x and y in practical terms

Break down the mechanics of paired assets in pools, demonstrating how liquidity ratios shift and how the invariant guides the permissible trades without external intervention.

03

Geometric Interpretations of Liquidity

Hyperbolas and Bonding Curves
You will visualize the math by mapping liquidity onto geometric planes. This perspective allows you to see how the curve's shape directly influences trading constraints and asset availability at different price points.
Liquidity as Geometry
Why Market Behavior Can Be Plotted on a Plane

Introduces the conceptual shift from viewing liquidity as a pool of tokens to understanding it as a geometric structure. The section explains how asset reserves can be represented as coordinates on a two-dimensional plane, setting the stage for interpreting trading activity as movement along a mathematical curve.

The Constant Product Curve
From Algebraic Constraint to Visual Shape

Explains how the constant product formula produces a distinctive curve when plotted on a reserve plane. The section interprets the relationship between two assets as a mathematical constraint that forms a hyperbolic shape, illustrating why trades must move along this curve rather than freely across the plane.

Anatomy of a Hyperbola
Understanding the Shape Behind Automated Markets

Breaks down the key geometric properties of a hyperbola and relates them to liquidity pools. Concepts such as branches, asymptotes, and curvature are translated into intuitive interpretations about how asset balances evolve during trading activity.

04

Precision and Fixed-Point Arithmetic

Handling Decimals in Smart Contracts
You will learn how to manage mathematical precision in environments without floating-point support. This is critical for you to prevent rounding errors that could lead to fund drainage or broken invariants in your pool.
Why Numerical Precision Matters in Automated Market Makers
The Hidden Risk Behind Small Rounding Errors

Introduces the role of numerical precision in Automated Market Maker systems. This section explains how seemingly small rounding deviations can compound through swaps, liquidity updates, and fee calculations, potentially breaking the mathematical invariants that protect liquidity pools.

The Absence of Floating-Point Arithmetic in Smart Contracts
Why Blockchain Virtual Machines Prefer Deterministic Integers

Explores the architectural reasons smart contract platforms avoid floating-point arithmetic. It explains determinism requirements in distributed consensus systems and how integer-only computation environments shape the mathematical design of AMM protocols.

The Fixed-Point Representation Model
Simulating Decimals Using Scaled Integers

Presents the core idea of fixed-point arithmetic and how decimal values are encoded using scaled integers. The section explains scaling factors, implicit decimal positions, and how this representation allows smart contracts to safely approximate real-number calculations.

05

Calculus of Price Impact

Deriving Instantaneous Price Deviations
You will apply differential calculus to determine how a single trade shifts the market price. Mastering these derivatives helps you quantify the sensitivity of a pool's price to trade size.
From Discrete Trades to Continuous Sensitivity
Why Automated Markets Require Calculus

Introduces the conceptual transition from observing price changes after discrete swaps to modeling instantaneous price movement using continuous mathematics. The section frames automated market makers as smooth mathematical systems where infinitesimal trades reveal the true structure of price sensitivity.

The Constant Product Curve as a Differentiable System
Viewing Liquidity Pools as Mathematical Functions

Recasts the constant product invariant as a continuous curve in reserve space. The liquidity pool becomes a function whose geometry determines how price evolves. This framing prepares the reader to apply calculus directly to reserve balances and price ratios.

Deriving the Instantaneous Price Function
Extracting Market Price from Reserve Geometry

Derives the price expression from the pool’s invariant and explains how price emerges as a slope within the reserve curve. The section shows how the marginal exchange rate corresponds to the derivative of the reserve relationship.

06

The Mechanics of Slippage

Calculating Execution Discrepancies
You will analyze the difference between expected and executed prices. This chapter provides you with the formulas to predict and mitigate the costs of large trades within a finite liquidity depth.
Defining Slippage in Automated Markets
Why Expected Prices Diverge from Execution

Introduces the concept of slippage as the gap between the price a trader anticipates and the price actually received during execution. The section reframes the classical finance definition of slippage within the context of automated market makers, where deterministic formulas and finite liquidity pools create predictable yet unavoidable price movement during trades.

Liquidity Depth and the Geometry of Price Movement
How Finite Reserves Shape Trade Outcomes

Explores how liquidity depth determines the sensitivity of prices to trade size. The section explains why shallow pools produce large price movements and why deeper pools dampen slippage. Mathematical intuition is developed around how reserve balances respond to incremental trades within automated liquidity pools.

Deriving Slippage from the Constant Product Formula
Mathematical Consequences of x·y = k

Derives slippage directly from the invariant governing constant product market makers. By modeling the relationship between input trade size and resulting reserve adjustments, the section demonstrates how the invariant curve generates nonlinear price movement and quantifies the resulting execution discrepancy.

07

Liquidity Provider Tokens

Mathematical Representation of Pool Ownership
You will investigate how pool shares are minted and burned. This ensures you understand the proportional logic that governs how rewards and underlying assets are distributed to participants.
Ownership as a Mathematical Abstraction
From Deposited Assets to Quantified Pool Shares

Introduces the conceptual transformation of deposited assets into liquidity provider tokens. The section frames LP tokens as mathematical representations of ownership within a pooled financial system, establishing how proportional accounting replaces direct asset custody in automated market makers.

Genesis of a Liquidity Pool
Initial Deposits and the First Share Calculation

Explains the mathematical process used when a liquidity pool is created and the first liquidity providers define the initial supply of LP tokens. The section examines how early deposits establish the baseline ratio of tokens and how the first proportional ownership is encoded.

Minting Pool Shares
How New Liquidity Converts Into Additional Ownership Units

Analyzes the formula used to mint new LP tokens when liquidity providers add assets to an existing pool. The section demonstrates how the system preserves proportional fairness by issuing new shares relative to the contributor’s fraction of total pool value.

08

Impermanent Loss Theory

Quantifying Opportunity Cost in Volatile Markets
You will dive into the most significant risk for liquidity providers. By modeling price divergence, you will learn to calculate exactly how much value is lost compared to simply holding the assets.
Understanding Impermanent Loss
Defining the Hidden Cost of Liquidity Provision

Introduce the concept of impermanent loss as the divergence in value between holding assets in a liquidity pool versus holding them outside. Explain why it is 'impermanent' and how market volatility influences its magnitude.

Mathematical Modeling of Price Divergence
Calculating Losses with Constant Product Formulas

Develop formulas that quantify impermanent loss based on asset price changes. Use constant product AMM equations to model different scenarios of divergence and their impact on pooled assets.

Case Studies in Volatile Markets
Real-World Examples of Impermanent Loss

Analyze historical price swings and their effect on liquidity providers. Compare the theoretical impermanent loss calculations to actual outcomes to illustrate practical significance.

09

Virtual Reserves and Capital Efficiency

Concentrating Liquidity Within Ranges
You will study advanced AMM designs that focus liquidity on specific price ticks. This allows you to understand how 'virtual' math can make a pool behave as if it has significantly more depth than it actually does.
The Concept of Capital Efficiency in AMMs
Maximizing Liquidity Impact per Unit Capital

Explore the theoretical foundations of capital efficiency within automated market makers, emphasizing how efficiently deployed liquidity can reduce slippage and increase trading depth without requiring additional funds.

Virtual Reserves and Liquidity Concentration
Simulating Depth with Focused Capital

Introduce the idea of virtual reserves and how AMMs can mathematically allocate liquidity across narrow price ranges, making pools behave as if they have more capital than they actually hold.

Range Orders and Tick-Based Liquidity
Precision Control Over Pool Behavior

Explain how liquidity providers define active ranges (ticks) in AMMs, including formulas for capital allocation, and how these choices impact effective liquidity and trading efficiency.

10

The Constant Sum Alternative

Zero-Slippage Trading Models
You will contrast the constant product model with linear invariants. Understanding the sum formula helps you see the trade-offs between infinite liquidity depth and fixed-price execution.
Introduction to Constant Sum Models
Why Linear Invariants Matter in AMMs

Introduce the constant sum invariant as an alternative to the widely used constant product model. Discuss its theoretical foundation in linear relationships and highlight the unique zero-slippage property that makes it attractive for certain trading scenarios.

Mathematical Framework
Formulating the Constant Sum Equation

Present the algebraic representation of a constant sum AMM, including how token balances maintain a fixed total. Compare and contrast with the hyperbolic curve of constant product pools, emphasizing the linearity and predictable pricing of sum-based models.

Trade Mechanics and Zero Slippage
Execution Dynamics in Linear Pools

Explore how trades execute along a linear invariant with fixed pricing, highlighting the zero-slippage property. Discuss limitations such as finite liquidity and the inability to accommodate large trades beyond pool capacity.

11

Hybrid Invariants

The Mathematics of Stablecoin Swaps
You will examine complex curves used for assets of equal value. By learning how these equations converge, you can build or use pools that offer extremely low slippage for pegged assets.
Introduction to Hybrid Invariants
Blending Constant Sum and Constant Product Models

Define hybrid invariants and explain their relevance in AMMs for stablecoins. Introduce the concept of combining constant sum and constant product curves to achieve both capital efficiency and low slippage.

Mathematical Foundations
Equations and Convergence Principles

Explore the core equations underlying hybrid curves, focusing on how iterative methods like Newton's method help determine precise swap outcomes and ensure convergence in near-equal value asset pools.

Curve Analysis and Stability
Behavior Near Pegged Asset Equilibria

Analyze how hybrid invariant curves behave around the target exchange rate, including sensitivity to deviations and mechanisms that maintain minimal slippage for stablecoins.

12

Multi-Asset Liquidity Pools

N-Dimensional Constant Product Formulas
You will expand your knowledge from pairs to portfolios. You will learn how the geometric mean allows for pools with multiple assets, each maintaining its own weight and mathematical balance.
From Token Pairs to Asset Portfolios
Why Automated Market Makers Expand Beyond Two-Asset Pools

This section introduces the conceptual leap from traditional two-token constant product pools to multi-asset liquidity pools. It explains the limitations of pairwise markets, the benefits of portfolio-style liquidity, and how multi-asset pools enable more flexible trading environments where several assets coexist within a single mathematical system.

The Mathematical Role of the Geometric Mean
Why Multiplicative Balance Governs Multi-Asset Pools

This section explains how the geometric mean provides the mathematical foundation for maintaining balance among multiple assets simultaneously. It contrasts additive and multiplicative averages, demonstrating why the geometric mean naturally preserves proportional relationships across assets in an automated market maker environment.

Generalizing the Constant Product Invariant
Extending the Formula to N Dimensions

This section develops the mathematical generalization of the constant product invariant from two variables to many variables. It explains how the invariant becomes the product of all asset balances raised to their respective weights, forming an N-dimensional surface that governs the pool's equilibrium.

13

Fee Internalization Algorithms

The Impact of Trading Fees on Invariants
You will analyze how fees are injected back into the 'k' value. This chapter shows you how the pool grows over time and how the math of compounding benefits long-term liquidity providers.
From Static Invariant to Growth Engine
Why Trading Fees Transform the Constant Product Model

This section introduces the conceptual shift from viewing the constant product invariant as a static constraint to understanding it as a growth mechanism once fees are internalized. It explains how the introduction of trading fees subtly alters the system’s behavior by allowing value to accumulate inside the pool, setting the stage for long-term invariant expansion.

The Mechanics of Fee Injection
How Swap Fees Enter the Liquidity Pool

This section analyzes the operational path of trading fees in automated market makers. It explains how fees are deducted from swaps and retained within the liquidity pool balances, increasing reserves and indirectly raising the invariant. The discussion focuses on the algorithmic steps through which fee internalization occurs during each transaction.

Invariant Drift and the Expansion of k
Mathematical Consequences of Fee Retention

This section explores the mathematical implications of internalized fees on the constant product formula. It demonstrates how the invariant gradually increases as trading activity accumulates fees within the pool, producing a slow upward drift in the value of k. The section explains how this effect emerges naturally from repeated swaps without external capital inflows.

14

Path Independence in Swaps

The Logic of Multi-Hop Routing
You will discover why the order of operations matters in nested trades. Mastering path independence ensures you can calculate the most efficient route across multiple liquidity pools.
Why Trade Paths Matter in Automated Markets
From Single Pool Swaps to Complex Routing

Introduces the concept of trade paths in decentralized exchanges. The section explains how simple swaps evolve into multi-hop transactions when liquidity is fragmented across pools. It frames the routing problem: determining how a token travels across multiple pools to reach the desired asset.

The Mathematical Meaning of Path Independence
When Order of Operations Does Not Change the Outcome

Explores the mathematical principle of path independence and how it applies to swap calculations. The section explains how some transformations yield identical results regardless of the route taken, while others accumulate differences depending on the sequence of steps.

Constant Product Pools and Sequential Price Impact
How Each Hop Alters the Next Trade

Examines how constant product liquidity pools modify price through each trade. The section shows how slippage compounds across sequential swaps and why the mathematical structure of each pool affects the final output amount.

15

Arbitrage Equilibrium Math

Mathematical Convergence with External Markets
You will model how external price pressure forces the AMM back to global market rates. This helps you understand the mechanical 'correction' that keeps on-chain prices accurate.
Price Divergence Between AMMs and External Markets
How isolated liquidity pools drift away from global prices

This section introduces the conditions that allow an automated market maker to temporarily diverge from the broader market price of an asset. It explains how discrete trades, liquidity pool imbalances, and delayed information flow can create price discrepancies between on-chain pools and centralized exchanges. The section frames these deviations as the starting point for arbitrage-driven correction.

Constant Product Pricing and Local Market Quotes
Deriving the internal exchange rate of a liquidity pool

This section examines how constant product formulas generate instantaneous prices inside an automated market maker. It shows how the marginal price emerges from reserve ratios and how trades alter the slope of the pricing curve. Understanding this local pricing mechanism is essential to modeling when and how arbitrage opportunities appear.

Arbitrage as a Corrective Force
Profit-driven trades that restore global price alignment

This section explains the economic logic of arbitrage within automated market maker ecosystems. When a pool price diverges from the external market price, traders exploit the difference by executing offsetting trades across markets. These profit-seeking actions simultaneously generate returns for arbitrageurs and push the AMM back toward the prevailing global price.

16

Oracle Math and Time-Weighted Averages

Resisting Price Manipulation
You will learn how to derive secure price data from AMM history. By understanding TWAP calculations, you can build systems that are resistant to short-term volatility and flash-loan attacks.
Why Automated Market Makers Need Secure Price Oracles
The vulnerability of instantaneous prices

Introduces the fundamental challenge of extracting reliable price signals from automated market makers. This section explains why spot prices derived directly from liquidity pool ratios are highly sensitive to short-term trades and can be manipulated. It frames the need for mathematically grounded oracle mechanisms that convert volatile on-chain data into stable reference prices.

From Spot Price to Time-Aware Measurement
The intuition behind time-weighted pricing

Develops the conceptual shift from instantaneous price readings to time-weighted observations. The section explains how averaging prices across time intervals filters noise and dampens manipulation attempts, introducing the intuition behind time-weighted averaging before formal mathematical derivation.

Deriving the Time-Weighted Average Price Formula
Integrating price over time

Presents the mathematical derivation of the time-weighted average price as an integral of price with respect to time. The section explains discrete approximations used in blockchain environments, where block timestamps replace continuous time, and demonstrates how TWAP becomes a weighted mean of observed prices across time intervals.

17

Dynamic Weighting Schemes

Time-Dependent Bonding Curves
You will investigate curves that change over time. This math is essential for you to understand Liquidity Bootstrapping Pools (LBPs) and how they prevent front-running during initial token distributions.
Introduction to Dynamic Weights
Why Time Matters in Liquidity Pools

An overview of why static weights can be limiting in AMMs and how introducing time-dependent weighting enhances pool flexibility. Introduces the concept of dynamic bonding curves as a solution to front-running and imbalanced initial distributions.

Mathematical Foundations
Formulating Time-Varying Curves

Detailed exploration of the equations governing dynamic weighting, including linear, exponential, and logarithmic decay or growth functions. Explains how these curves influence token pricing over time within a pool.

Implementing Dynamic Weights in LBPs
Practical Applications and Algorithms

Step-by-step explanation of how to apply time-dependent weights in Liquidity Bootstrapping Pools. Includes algorithmic strategies for gradual weight shifts and examples showing how front-running is mitigated.

18

Non-Standard Invariants

Logarithmic and Custom Curves
You will push the boundaries of AMM design by exploring non-hyperbolic functions. This chapter prepares you to design bespoke financial instruments with unique risk-reward profiles.
Rethinking AMM Foundations
From Constant Product to Flexible Invariants

Introduce the concept of moving beyond traditional x*y=k models. Discuss why non-hyperbolic functions can better tailor liquidity dynamics for niche financial instruments.

Logarithmic Curve Mechanics
Integrating log-based pricing in pools

Explore how logarithmic curves can define price-slippage and liquidity sensitivity. Provide formulas for implementing log-based AMMs and analyze their risk-reward behavior compared to standard curves.

Custom Invariant Design
Crafting bespoke curves for specific strategies

Discuss the principles of designing arbitrary invariants. Examine how combining polynomial, logarithmic, and other non-linear functions creates unique liquidity profiles for targeted financial instruments.

19

Algorithmic Risk Assessment

Stress Testing Pool Parameters
You will use statistical simulations to test the robustness of your mathematical models. This ensures you can predict how a liquidity pool will behave under extreme market conditions.
Foundations of Algorithmic Risk in AMMs
Understanding exposure in liquidity pools

Introduce the types of risks inherent to automated market makers, including impermanent loss, slippage, and systemic shocks. Set the stage for why algorithmic stress testing is critical for pool stability.

Monte Carlo Simulations for Liquidity Pools
Applying random sampling to model extreme scenarios

Explain how Monte Carlo methods can simulate thousands of potential market movements to evaluate the performance of AMM formulas under volatile conditions. Highlight the flexibility of these simulations in representing unpredictable events.

Defining Stress Test Parameters
Selecting variables and boundaries for robust analysis

Detail the key parameters to vary in simulations, such as trade volume, volatility, liquidity depth, and fee structures. Discuss how to identify extreme but plausible scenarios to push pool formulas to their limits.

20

Gas Optimization for Math Operations

Efficient Computational Logic
You will bridge the gap between pure math and execution. You will learn to simplify complex formulas into computationally cheap operations, ensuring your AMM is viable on resource-constrained blockchains.
Profiling AMM Computations
Identifying Gas-Heavy Operations

Analyze typical mathematical operations in AMMs to pinpoint which computations consume the most blockchain resources. Introduce profiling techniques and metrics for assessing gas cost at a granular level.

Algebraic Simplification Techniques
Reducing Computational Steps

Demonstrate how to rewrite complex AMM formulas, such as constant product and weighted pool equations, to minimize operations without altering correctness. Discuss factoring, precomputing constants, and eliminating redundant calculations.

Integer Arithmetic and Fixed-Point Approximations
Precision Meets Efficiency

Explain the trade-offs between floating-point and integer math in smart contracts. Show how fixed-point arithmetic can maintain accuracy while reducing gas, including rounding strategies and overflow prevention.

21

The Future of Algorithmic Liquidity

Beyond Constant Function Market Makers
You will conclude your journey by looking at the next generation of financial engineering. This final chapter synthesizes everything you've learned to prepare you for the evolution of autonomous market design.
The Next Generation of AMMs
Evolving Beyond Constant Product Models

Explore the limitations of current constant function market makers and introduce emerging AMM designs that adapt dynamically to market conditions and liquidity profiles.

Algorithmic Design Innovations
Dynamic Formulas and Adaptive Pricing

Dive into cutting-edge algorithmic techniques that allow AMMs to optimize pricing curves, manage impermanent loss, and incorporate multi-asset pools for more efficient liquidity.

Synthetic Assets and Derivative Liquidity
Bridging AMMs and Financial Engineering

Examine how AMMs can support synthetic assets and complex derivative products, integrating risk hedging mechanisms traditionally found in financial engineering.

Available eBook Editions

Arabic
English
French
German
Italian
Japanese
Korean
Portuguese
Spanish
Turkish