TickMath

Git Source

Authors: Aloe Labs, Inc., Modified from Uniswap and Aperture Finance

Computes sqrt price for ticks of size 1.0001, i.e. \(\sqrt{1.0001^{tick}}\) as fixed point Q64.96 numbers. Supports prices between \(2^{-128}\) and \(2^{128}\)

State Variables

MIN_TICK

The minimum tick that may be passed to getSqrtRatioAtTick computed from \( log_{1.0001}2^{-128} \)

int24 internal constant MIN_TICK = -887272;

MAX_TICK

The maximum tick that may be passed to getSqrtRatioAtTick computed from \( log_{1.0001}2^{128} \)

int24 internal constant MAX_TICK = 887272;

MIN_SQRT_RATIO

The minimum value that can be returned from getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)

uint160 internal constant MIN_SQRT_RATIO = 4295128739;

MAX_SQRT_RATIO

The maximum value that can be returned from getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)

uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;

MAX_SQRT_RATIO_MINUS_MIN_SQRT_RATIO_MINUS_ONE

A threshold used for optimized bounds check, equals MAX_SQRT_RATIO - MIN_SQRT_RATIO - 1

uint160 private constant MAX_SQRT_RATIO_MINUS_MIN_SQRT_RATIO_MINUS_ONE =
    1461446703485210103287273052203988822378723970342 - 4295128739 - 1;

Functions

getSqrtRatioAtTick

Calculates \( \sqrt{1.0001^{tick}} * 2^{96} \)

Throws if |tick| > max tick

function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96);

Parameters

NameTypeDescription
tickint24The input tick for the above formula

Returns

NameTypeDescription
sqrtPriceX96uint160A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) at the given tick

getTickAtSqrtRatio

Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio

Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may ever return.

function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick);

Parameters

NameTypeDescription
sqrtPriceX96uint160The sqrt ratio for which to compute the tick as a Q64.96

Returns

NameTypeDescription
tickint24The greatest tick for which the ratio is less than or equal to the input ratio

floor

Rounds down to the nearest tick where tick % tickSpacing == 0

Ensure tick +/- tickSpacing does not overflow or underflow int24

function floor(int24 tick, int24 tickSpacing) internal pure returns (int24);

Parameters

NameTypeDescription
tickint24The tick to round
tickSpacingint24The tick spacing to round to

Returns

NameTypeDescription
<none>int24the floored tick

ceil

Rounds up to the nearest tick where tick % tickSpacing == 0

Ensure tick +/- tickSpacing does not overflow or underflow int24

function ceil(int24 tick, int24 tickSpacing) internal pure returns (int24);

Parameters

NameTypeDescription
tickint24The tick to round
tickSpacingint24The tick spacing to round to

Returns

NameTypeDescription
<none>int24the ceiled tick