- name
- uniswap-math
- description
- Use when working with Uniswap pricing math, tick calculations, liquidity formulas, or Q64.96 fixed-point arithmetic. Covers TickMath, SqrtPriceMath, SwapMath, FullMath, TickBitmap, LiquidityAmounts, Position library, and all key formulas for concentrated liquidity AMMs.
# Uniswap Concentrated Liquidity Math
## Q64.96 Fixed-Point Arithmetic
Uniswap V3/V4 stores prices as Q64.96 fixed-point numbers representing the **square root** of the price ratio. This encoding fits in `uint160` and enables efficient swap math without division.
```
sqrtPriceX96 = √(price) × 2⁹⁶
```
- 64 bits for the integer part, 96 bits for the fractional part
- Stored as `uint160` — fits alongside `int24 tick` and `uint128 liquidity` in the pool's `Slot0`
- Price of token1 in terms of token0: `price = (sqrtPriceX96 / 2⁹⁶)²`
- Inverse conversion: `sqrtPriceX96 = √(price) × 2⁹⁶`
### Why Store √P Instead of P
1. The core swap formulas only need `√P`, never `P` directly
2. `amount1 = L × Δ√P` is a simple multiplication — no square root at runtime
3. `amount0 = L × Δ(1/√P)` avoids computing reciprocals of prices
4. Avoids the precision loss of squaring and rooting during swaps
### Decimal Normalization
Prices are always in **raw token units** — you must account for decimals manually.
```
token0 = WETH (18 decimals)
token1 = USDC (6 decimals)
Human-readable price: 1 ETH = 3000 USDC
Raw price (token1/token0) = 3000 × 10⁶ / 10¹⁸ = 3000 × 10⁻¹²
sqrtPrice = √(3000 × 10⁻¹²) = √(3 × 10⁻⁹) ≈ 5.47722558 × 10⁻⁵
sqrtPriceX96 = 5.47722558 × 10⁻⁵ × 2⁹⁶ ≈ 4_339_505_179_874_779_489_878_115
```
For a pair where both tokens have 18 decimals (e.g., WETH/DAI at price 3000):
```
Raw price = 3000 (decimals cancel)
sqrtPrice = √3000 ≈ 54.7722558
sqrtPriceX96 = 54.7722558 × 2⁹⁶ ≈ 4_339_505_179_874_779_163_484_739_850_572_800
```
### Converting sqrtPriceX96 to Human Price
```solidity
// In Solidity — use FullMath to avoid overflow
uint256 priceX192 = FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, 1);
// priceX192 is price * 2^192, divide by 2^192 to get raw price
// For display: rawPrice * 10^(decimals0 - decimals1) = human price
```
```python
# In Python (offchain)
def sqrtPriceX96_to_price(sqrtPriceX96, decimals0, decimals1):
price = (sqrtPriceX96 / 2**96) ** 2
adjusted = price * 10 ** (decimals0 - decimals1)
return adjusted
# ETH/USDC: sqrtPriceX96 = 4_339_505_179_874_779_489_878_115
sqrtPriceX96_to_price(4_339_505_179_874_779_489_878_115, 18, 6)
# ≈ 3000.0
```
## TickMath Library
**Import:** `import {TickMath} from "v4-core/src/libraries/TickMath.sol";`
### Constants
```solidity
int24 internal constant MIN_TICK = -887272;
int24 internal constant MAX_TICK = 887272;
int24 internal constant MIN_TICK_SPACING = 1;
int24 internal constant MAX_TICK_SPACING = type(int16).max; // 32767
uint160 internal constant MIN_SQRT_PRICE = 4295128739;
uint160 internal constant MAX_SQRT_PRICE =
1461446703485210103287273052203988822378723970342;
```
`MIN_SQRT_PRICE` and `MAX_SQRT_PRICE` correspond to the prices at `MIN_TICK` and `MAX_TICK`. The pool's `sqrtPriceX96` is always in `(MIN_SQRT_PRICE, MAX_SQRT_PRICE)` — strictly exclusive.
### Core Functions
```solidity
/// @notice Returns the sqrt price at the given tick as a Q64.96
/// @dev Reverts if |tick| > MAX_TICK
function getSqrtPriceAtTick(int24 tick)
internal pure returns (uint160 sqrtPriceX96);
/// @notice Returns the tick at the given sqrt price
/// @dev Returns the largest tick whose price ≤ sqrtPriceX96
/// @dev sqrtPriceX96 must be in (MIN_SQRT_PRICE, MAX_SQRT_PRICE)
function getTickAtSqrtPrice(uint160 sqrtPriceX96)
internal pure returns (int24 tick);
/// @notice Returns the maximum usable tick for a given tick spacing
function maxUsableTick(int24 tickSpacing)
internal pure returns (int24);
/// @notice Returns the minimum usable tick for a given tick spacing
function minUsableTick(int24 tickSpacing)
internal pure returns (int24);
```
### Tick-Price Relationship
Each tick `i` maps to a price: **P(i) = 1.0001ⁱ**
Every tick is exactly 1 basis point (0.01%) away from its neighbors. This is the key invariant of concentrated liquidity — prices are spaced geometrically, not linearly.
```
tick = 0 → price = 1.0
tick = 1 → price = 1.0001
tick = -1 → price = 0.99990001...
tick = 100 → price ≈ 1.01005
tick = 10000 → price ≈ 2.71828 (≈ e)
tick = 23028 → price ≈ 10.0
tick = 46054 → price ≈ 100.0
tick = 69082 → price ≈ 1000.0
tick = -69082 → price ≈ 0.001
tick = 887272 → price ≈ 3.40 × 10³⁸ (near uint128 max)
```
Useful relationship: `tick ≈ ln(price) / ln(1.0001) ≈ ln(price) × 10000`
### Tick Spacing
Only ticks divisible by `tickSpacing` can be initialized with liquidity positions. Common tick spacings:
| Fee Tier | Tick Spacing | Price Granularity |
|----------|-------------|-------------------|
| 1 bps (0.01%) | 1 | Every tick — stablecoin pairs |
| 5 bps (0.05%) | 10 | 0.10% between usable ticks |
| 30 bps (0.30%) | 60 | 0.60% between usable ticks |
| 100 bps (1.00%) | 200 | 2.00% between usable ticks |
```solidity
// Usable ticks for tickSpacing = 60:
// ..., -120, -60, 0, 60, 120, 180, ...
int24 maxUsable = TickMath.maxUsableTick(60); // 887220
int24 minUsable = TickMath.minUsableTick(60); // -887220
```
### getTickAtSqrtPrice Floor Behavior
`getTickAtSqrtPrice` returns the **largest tick** where `getSqrtPriceAtTick(tick) <= sqrtPriceX96`. This is a floor operation. The current tick always satisfies:
```
getSqrtPriceAtTick(tick) <= currentSqrtPrice < getSqrtPriceAtTick(tick + 1)
```
## SqrtPriceMath Library
**Import:** `import {SqrtPriceMath} from "v4-core/src/libraries/SqrtPriceMath.sol";`
This library computes token amounts from liquidity and price changes, and computes new prices from token amounts. Every function is aware of rounding direction.
### Amount Delta Functions
```solidity
/// @notice Gets the token0 delta for a liquidity and price range
function getAmount0Delta(
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
uint128 liquidity,
bool roundUp
) internal pure returns (uint256 amount0);
/// @notice Gets the token1 delta for a liquidity and price range
function getAmount1Delta(
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
uint128 liquidity,
bool roundUp
) internal pure returns (uint256 amount1);
```
**Signed overloads** exist that accept `int128 liquidity` — positive for adding liquidity (user pays, round up), negative for removing (user receives, round down):
```solidity
function getAmount0Delta(
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
int128 liquidity
) internal pure returns (int256 amount0);
function getAmount1Delta(
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
int128 liquidity
) internal pure returns (int256 amount1);
```
### Core Formulas
For a position spanning `[√P_a, √P_b]` where `√P_a < √P_b`:
```
√P_b - √P_a
amount0 = L × ─────────────────
√P_a × √P_b
amount1 = L × (√P_b - √P_a)
```
Equivalently:
```
amount0 = L × (1/√P_a - 1/√P_b)
amount1 = L × (√P_b - √P_a)
```
**Intuition:** token0 is the "x" asset in xy=k. As price rises (more token1 per token0), the position holds less token0 and more token1. At `√P >= √P_b`, the position is entirely token1. At `√P <= √P_a`, entirely token0.
### Next Price Functions
```solidity
/// @notice Gets next sqrt price given token0 input/output
function getNextSqrtPriceFromAmount0RoundingUp(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amount,
bool add
) internal pure returns (uint160);
/// @notice Gets next sqrt price given token1 input/output
function getNextSqrtPriceFromAmount1RoundingDown(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amount,
bool add
) internal pure returns (uint160);
/// @notice Gets next sqrt price from an exact input amount
function getNextSqrtPriceFromInput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountIn,
bool zeroForOne
) internal pure returns (uint160);
/// @notice Gets next sqrt price from an exact output amount
function getNextSqrtPriceFromOutput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountOut,
bool zeroForOne
) internal pure returns (uint160);
```
**Next price from token0 amount:**
```
When adding token0 (buying token1): price decreases
√P_next = L × √P / (L + amount0 × √P)
When removing token0 (selling token1): price increases
√P_next = L × √P / (L - amount0 × √P)
```
**Next price from token1 amount:**
```
When adding token1 (buying token0): price increases
√P_next = √P + amount1 / L
When removing token1 (selling token0): price decreases
√P_next = √P - amount1 / L
```
### Rounding Convention
| Scenario | Amount0 | Amount1 | Price |
|----------|---------|---------|-------|
| User pays (add liquidity, swap input) | Round UP | Round UP | Round towards protocol benefit |
| User receives (remove liquidity, swap output) | Round DOWN | Round DOWN | Round towards protocol benefit |
The protocol must never undercharge or overpay. Every rounding decision favors the pool.
## SwapMath Library
**Import:** `import {SwapMath} from "v4-core/src/libraries/SwapMath.sol";`
### Constants
```solidity
uint24 internal constant MAX_SWAP_FEE = 1e6; // 100% — denominated in hundredths of a bip
```
Fee is in units of hundredths of a basis point (1/100 of 0.01% = 0.0001%). So `3000` = 0.30%, `500` = 0.05%, `10000` = 1.00%.
### Core Functions
```solidity
/// @notice Returns the target sqrt price, clamped to the price limit
function getSqrtPriceTarget(
bool zeroForOne,
uint160 sqrtPriceNextX96,
uint160 sqrtPriceLimitX96
) internal pure returns (uint160 sqrtPriceTargetX96);
/// @notice Computes a single step within a swap
function computeSwapStep(
uint160 sqrtPriceCurrentX96,
uint160 sqrtPriceTargetX96,
uint128 liquidity,
int256 amountRemaining,
uint24 feePips
) internal pure returns (
uint160 sqrtPriceNextX96,
uint256 amountIn,
uint256 amountOut,
uint256 feeAmount
);
```
### The Swap Loop
Every swap in Uniswap V3/V4 executes as a loop of steps across tick boundaries:
```
1. Start at current sqrtPrice and tick
2. LOOP:
a. Find the next initialized tick in the swap direction (via TickBitmap)
b. Clamp the target price to the user's price limit
c. Call computeSwapStep(current, target, liquidity, remaining, fee)
d. Update amountRemaining by subtracting amountIn + feeAmount (exact input)
or amountOut (exact output)
e. Accumulate fee growth: feeGrowthGlobal += feeAmount / liquidity
f. If sqrtPriceNext reached the tick boundary:
- Cross the tick: add/subtract the tick's liquidityNet from active liquidity
- Update current tick
g. If amountRemaining == 0 or sqrtPrice hits limit → exit loop
3. Update pool state: sqrtPrice, tick, liquidity, feeGrowthGlobal
```
### computeSwapStep Internals
For **exact input** (`amountRemaining > 0`):
```
1. Calculate amountIn to move price from current to target
2. If amountIn + fee <= remaining:
- Price reaches target: sqrtPriceNext = target
- Fee = remaining - amountIn (entire remainder is fee, capped)
3. Else:
- Only partial move: compute sqrtPriceNext from input (after fee deduction)
- amountRemainingLessFee = amountRemaining * (1e6 - feePips) / 1e6
- sqrtPriceNext = getNextSqrtPriceFromInput(current, liquidity, amountRemainingLessFee)
4. Compute amountOut from the actual price movement
5. Fee = amountIn calculated from movement, then:
feeAmount = amountRemaining - amountIn (for exact input, fee is the delta)
```
For **exact output** (`amountRemaining < 0`):
```
1. Calculate amountOut to move price from current to target
2. If amountOut <= |remaining|:
- Price reaches target
3. Else:
- Partial move: compute sqrtPriceNext from output
4. Compute amountIn from the actual price movement
5. feeAmount = mulDivRoundingUp(amountIn, feePips, 1e6 - feePips)
```
### zeroForOne Direction
| `zeroForOne` | Direction | Price Movement | token0 | token1 |
|---|---|---|---|---|
| `true` | Sell token0, buy token1 | Price decreases (√P goes down) | Input | Output |
| `false` | Sell token1, buy token0 | Price increases (√P goes up) | Output | Input |
## FullMath Library
**Import:** `import {FullMath} from "v4-core/src/libraries/FullMath.sol";`
```solidity
/// @notice 512-bit multiply then divide: (a × b) / denominator
/// @dev Will not overflow for any inputs where the result fits in uint256
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result);
/// @notice Same as mulDiv but rounds up
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result);
```
`FullMath.mulDiv` computes `(a * b) / d` with a 512-bit intermediate product, preventing overflow when `a * b > type(uint256).max`. This is essential for Q64.96 math where multiplying two `uint160` values can produce up to 320 bits.
**Usage pattern in amount calculations:**
```solidity
// amount0 = liquidity * (sqrtPriceB - sqrtPriceA) / (sqrtPriceA * sqrtPriceB)
amount0 = FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION, // L * 2^96
sqrtPriceBX96 - sqrtPriceAX96,
sqrtPriceBX96
) / sqrtPriceAX96;
```
### UnsafeMath
**Import:** `import {UnsafeMath} from "v4-core/src/libraries/UnsafeMath.sol";`
```solidity
function divRoundingUp(uint256 x, uint256 d) internal pure returns (uint256);
```
Used internally where the caller has already validated inputs. Saves gas by skipping overflow checks.
## TickBitmap Library
**Import:** `import {TickBitmap} from "v4-core/src/libraries/TickBitmap.sol";`
Ticks that have liquidity positions starting or ending at them are "initialized." The bitmap provides efficient lookup of the next initialized tick during swaps.
### Storage Layout
```
The bitmap is a mapping(int16 => uint256):
- The key (wordPos) is the tick index divided by 256
- Each bit in the uint256 represents one compressed tick
- Compressed tick = actual tick / tickSpacing
tick → compressed = tick / tickSpacing
compressed → wordPos = compressed >> 8 (arithmetic shift, so int16)
compressed → bitPos = compressed % 256 (uint8, always positive modulo)
```
### Functions
```solidity
/// @notice Compresses a tick by the tick spacing
function compress(int24 tick, int24 tickSpacing)
internal pure returns (int24 compressed);
/// @notice Returns word position and bit position within the word
function position(int24 tick)
internal pure returns (int16 wordPos, uint8 bitPos);
/// @notice Toggles the initialized state of a tick
function flipTick(
mapping(int16 => uint256) storage self,
int24 tick,
int24 tickSpacing
) internal;
Voir sur GitHub