Skip to main content
Helpful?

SwapMath

Git Source | Generated with forge doc

Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.

State Variables

MAX_SWAP_FEE

the swap fee is represented in hundredths of a bip, so the max is 100%

the swap fee is the total fee on a swap, including both LP and Protocol fee

uint256 internal constant MAX_SWAP_FEE = 1e6;

Functions

getSqrtPriceTarget

Computes the sqrt price target for the next swap step

function getSqrtPriceTarget(bool zeroForOne, uint160 sqrtPriceNextX96, uint160 sqrtPriceLimitX96)
internal
pure
returns (uint160 sqrtPriceTargetX96);

Parameters

NameTypeDescription
zeroForOneboolThe direction of the swap, true for currency0 to currency1, false for currency1 to currency0
sqrtPriceNextX96uint160The Q64.96 sqrt price for the next initialized tick
sqrtPriceLimitX96uint160The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value after the swap. If one for zero, the price cannot be greater than this value after the swap

Returns

NameTypeDescription
sqrtPriceTargetX96uint160The price target for the next swap step

computeSwapStep

Computes the result of swapping some amount in, or amount out, given the parameters of the swap

If the swap's amountSpecified is negative, the combined fee and input amount will never exceed the absolute value of the remaining amount.

feePips must be no larger than MAX_SWAP_FEE for this function. We ensure that before setting a fee using LPFeeLibrary.isValid.

function computeSwapStep(
uint160 sqrtPriceCurrentX96,
uint160 sqrtPriceTargetX96,
uint128 liquidity,
int256 amountRemaining,
uint24 feePips
) internal pure returns (uint160 sqrtPriceNextX96, uint256 amountIn, uint256 amountOut, uint256 feeAmount);

Parameters

NameTypeDescription
sqrtPriceCurrentX96uint160The current sqrt price of the pool
sqrtPriceTargetX96uint160The price that cannot be exceeded, from which the direction of the swap is inferred
liquidityuint128The usable liquidity
amountRemainingint256How much input or output amount is remaining to be swapped in/out
feePipsuint24The fee taken from the input amount, expressed in hundredths of a bip

Returns

NameTypeDescription
sqrtPriceNextX96uint160The price after swapping the amount in/out, not to exceed the price target
amountInuint256The amount to be swapped in, of either currency0 or currency1, based on the direction of the swap
amountOutuint256The amount to be received, of either currency0 or currency1, based on the direction of the swap
feeAmountuint256The amount of input that will be taken as a fee
Helpful?