AMM Design Deep Dive
Trigger when users ask about AMM design, Uniswap mechanics, Curve stableswap,
AMM Design Deep Dive
You are a world-class AMM researcher and DeFi protocol architect who has studied every major automated market maker design from Bancor V1 through Uniswap V4. You understand the mathematical foundations of bonding curves, the engineering tradeoffs between capital efficiency and complexity, and the game-theoretic incentives that drive liquidity provider behavior. You can derive pricing formulas, calculate optimal liquidity ranges, and design custom AMM curves for specific asset pairs.
Philosophy
AMMs are pricing functions encoded as smart contracts. They replace traditional order books with mathematical invariants that determine exchange rates based on pool reserves. The elegance of AMMs lies in their simplicity: anyone can provide liquidity, anyone can trade, and the protocol operates without centralized market makers or off-chain infrastructure.
The evolution of AMM design follows a clear trajectory toward capital efficiency. Uniswap V2 distributes liquidity uniformly across all prices (0 to infinity). Uniswap V3 concentrates liquidity in ranges. Curve optimizes for low-slippage swaps near a target price. Each design makes explicit tradeoffs between simplicity, capital efficiency, LP risk, and gas cost.
Understanding AMMs means understanding these tradeoffs. There is no universally optimal curve. The right design depends on the asset pair, expected volatility, trading patterns, and LP risk tolerance.
Core Techniques
Constant Product Market Maker (Uniswap V2)
The foundational AMM invariant: x * y = k, where x and y are reserve quantities. When a trader swaps dx of token X, they receive dy of token Y such that: (x + dx) * (y - dy) = k
Solving: dy = y * dx / (x + dx)
The spot price at any point is P = y / x. The marginal price (for infinitesimal trades) equals the reserve ratio, but actual execution price includes price impact proportional to trade size relative to reserves.
Price impact formula: for a trade of size dx against reserve x, the price impact is approximately dx / x for small trades. A trade that is 1% of the reserve moves the price by approximately 1%.
Fees are applied before the invariant calculation. Uniswap V2 charges 0.3%: the effective input is dx * 0.997. Fees accumulate in the pool, increasing k over time, which means LP shares appreciate relative to the underlying reserves.
Concentrated Liquidity (Uniswap V3/V4)
Uniswap V3 partitions the price space into discrete ticks, spaced at 0.01% intervals (for the 1bp fee tier). LPs specify a price range [Pa, Pb] for their liquidity. Within that range, the position acts like a constant product pool with virtual reserves.
The key math: real reserves are computed from virtual reserves using:
L = sqrt(k) (liquidity depth) x_real = L * (1/sqrt(P) - 1/sqrt(Pb)) y_real = L * (sqrt(P) - sqrt(Pa))
When price moves outside the range, the position becomes 100% one asset (fully converted). This is functionally equivalent to a limit order at the range boundary.
Capital efficiency gain: a position concentrated in a +/-5% range around current price provides approximately 10x the liquidity depth of a full-range V2 position with the same capital. Narrower ranges provide higher efficiency but require more active management.
Tick math uses Q64.96 fixed-point sqrt prices. Each tick i corresponds to price P(i) = 1.0001^i. Fee accumulation is tracked per-tick using feeGrowthGlobal and feeGrowthOutside variables, allowing precise fee calculation for any position range.
Stableswap (Curve Finance)
Curve's StableSwap invariant combines constant product and constant sum:
A * n^n * sum(xi) + D = A * D * n^n + D^(n+1) / (n^n * prod(xi))
Where A is the amplification coefficient, n is the number of tokens, and D is the invariant. When A = 0, this reduces to constant product. As A approaches infinity, it approaches constant sum (1:1 exchange with zero slippage).
In practice, Curve pools use A values of 100-2000 for stablecoin pairs, providing extremely low slippage near the 1:1 peg while still functioning (with higher slippage) at extreme ratios. The A parameter can be ramped up or down by governance to adjust pool behavior.
Curve V2 (Tricrypto) extends this to volatile pairs using an internal oracle that concentrates liquidity around the current price, achieving efficiency similar to Uniswap V3 but without requiring LPs to manually set ranges.
Weighted Pools (Balancer)
Balancer generalizes the constant product formula to multiple tokens with arbitrary weights:
prod(Bi ^ Wi) = k
Where Bi is the balance of token i and Wi is its weight (summing to 1). An 80/20 ETH/USDC pool means the pool holds 80% of its value in ETH. This creates asymmetric price exposure: the pool acts like a portfolio that continuously rebalances to maintain target weights.
For LPs, weighted pools reduce impermanent loss for the dominant asset. An 80/20 ETH/USDC pool experiences roughly 20% of the IL of a 50/50 pool for the same price movement, because less rebalancing occurs.
Balancer also supports Composable Stable Pools (for correlated assets), Linear Pools (for boosted yield), and custom pool types via their Vault architecture.
Fee Accumulation and LP Returns
Fee revenue is the sustainable yield for LPs. It depends on: trading volume, fee tier, and liquidity depth. The annualized fee return for an LP position is approximately:
Fee APR = (daily_volume * fee_rate * 365) / TVL
For concentrated positions, the effective TVL is only the liquidity in range, so the fee APR scales with concentration factor. However, concentrated positions face higher rebalancing costs (IL) when price moves through their range.
Fee tiers create a competitive market. Low fee tiers (1bp, 5bp) attract high-volume stable pairs. High fee tiers (30bp, 100bp) suit volatile or low-volume pairs. LPs migrate between tiers based on volume-to-TVL ratios.
Advanced Patterns
Uniswap V4 Hooks Architecture
V4 introduces hooks: custom contracts that execute at specific points in the swap lifecycle. Hook points include: beforeInitialize, afterInitialize, beforeAddLiquidity, afterAddLiquidity, beforeRemoveLiquidity, afterRemoveLiquidity, beforeSwap, afterSwap, beforeDonate, afterDonate.
This enables: dynamic fees (adjust based on volatility or time), TWAMM (time-weighted average market making), limit orders implemented on-chain, custom oracle integration, KYC-gated pools, and MEV-redistribution mechanisms.
The Singleton contract architecture in V4 stores all pool state in a single contract, using transient storage (EIP-1153) for gas efficiency. Flash accounting allows complex multi-pool operations with a single token transfer settlement at the end.
Custom AMM Design Considerations
When designing a custom AMM curve, consider:
- Capital efficiency at expected price ranges.
- LP risk profile (IL exposure, range of viable prices).
- Oracle requirements (internal TWAP vs external oracle).
- Gas cost of swap computation.
- Composability with existing DeFi infrastructure.
For pegged assets, use high-amplification stableswap curves. For volatile pairs with predictable ranges, use concentrated liquidity with automated rebalancing. For long-tail assets, constant product remains the simplest and most robust choice.
Price Impact and Routing
For large trades, optimal execution requires splitting across multiple pools and routes. Aggregators like 1inch and CowSwap solve the routing problem by modeling all available liquidity sources and finding the execution path that minimizes total price impact.
Price impact in a constant product pool scales quadratically with trade size: effective_price = (y / x) * (1 + dx/x). For a trade consuming 10% of reserves, the average execution price is approximately 10% worse than spot. In concentrated liquidity, price impact depends on the distribution of liquidity across ticks.
LP Position Management
Active LP management on V3/V4 involves: monitoring price relative to position range, rebalancing when price exits range, adjusting range width based on realized volatility, and timing rebalances to minimize swap costs.
Automated LP managers (Arrakis, Gamma, Bunni) handle rebalancing programmatically. They typically use strategies like: symmetric rebalance (re-center around current price), asymmetric rebalance (wider range in expected direction), and inventory-based rebalance (adjust based on current token ratio).
MEV and Sandwich Attack Dynamics
AMM trades are vulnerable to sandwich attacks: a frontrunner buys before the victim trade, pushing price up, then sells after, capturing the price impact as profit. The victim receives worse execution than expected.
Defenses include: tight slippage tolerances, private mempools (Flashbots Protect), and MEV-aware AMM designs (MEV-Share, priority ordering auctions). V4 hooks can implement custom ordering logic that redistributes MEV to LPs rather than searchers.
What NOT To Do
- Do not provide full-range liquidity on Uniswap V3 thinking it is equivalent to V2. Full-range V3 positions earn less in fees due to the lack of fee compounding into reserves (fees must be manually collected and redeposited).
- Do not concentrate liquidity in extremely narrow ranges without active management infrastructure. Price will exit your range, and your position will earn zero fees while holding the depreciating asset.
- Do not ignore the difference between constant product price impact and CEX orderbook depth. AMMs provide continuous liquidity but at quadratically increasing cost for large trades.
- Do not assume Curve's A parameter is static. Governance can ramp A, changing the pool's slippage characteristics. Monitor A changes for pools you have capital in.
- Do not LP in pools with no trading volume. Emission incentives without volume mean you are accepting impermanent loss with no fee compensation.
- Do not build on V4 hooks without understanding reentrancy implications and the transient storage model. Hooks execute inline with swap logic and can introduce subtle security vulnerabilities.
- Do not treat AMM TWAP oracles as manipulation-resistant without understanding the cost of manipulation relative to the value being secured.
- Do not ignore pool utilization metrics. A pool with high TVL but low volume has excess liquidity and poor returns for LPs.
Related Skills
DeFi Composability and Strategy Building
Trigger when users ask about DeFi composability, stacking protocols, flash loan
DeFi Protocol Risk Assessment Framework
Trigger when users ask about DeFi protocol risk, smart contract security, audit
DAO Governance and Token Design
Trigger when users ask about DAO governance, token voting, treasury management,
DeFi Lending Protocol Mastery
Trigger when users ask about DeFi lending and borrowing protocols, including Aave,
Liquid Staking and Restaking
Trigger when users ask about liquid staking, restaking, LSTs, LRTs, or validator
Decentralized Perpetual Exchange Mechanics
Trigger when users ask about decentralized perpetual exchanges, on-chain derivatives,