Elastic Core Libraries
BaseSplitCodeFactory
Inherited by the Factory contract. Main purpose is to hold the Kyberswap Elastic Pool creation code in a separate address, since its creation code is close to the bytecode size limit of 24kB.
Taken from Balancer Labs's solidity utils repo. The only modification made is the unchecked keyword for sol 0.8 compatibility.
getCreationCodeContracts()
getCreationCodeContracts()
Returns the 2 addresses where the creation code of the contract created by this factory is stored.
getCreationCode()
getCreationCode()
Returns the creation code of the contract this factory creates.
CodeDeployer
Taken from Balancer Labs's solidity utils repo. Imported and used by the BaseSplitCodeFactory
contract to handle deployment.
FullMath
Taken from Mathemagic finale: muldiv - Remco Bloeman. Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision. Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits.
mulDivFloor()
mulDivFloor()
Returns (a * b / denominator)
rounded down.
Input | Type | Explanation |
---|---|---|
|
| multiplicand |
|
| multiplier |
|
| divisor |
mulDivCeiling()
mulDivCeiling()
Similar to mulDivFloor
, but rounded up.
LinkedList
A doubly linked list to be used for tick management.
Struct: Data
Field | Type | Explanation |
---|---|---|
|
| previous tick |
|
| next tick |
init()
init()
Initializes the LinkedList with the lowestValue and highestValue, where
lowestValue.previous = lowestValue
lowestValue.next
=highestValue
highestValue.previous = lowestValue
highestValue.next = highestValue
Field | Type | Explanation |
---|---|---|
|
| A mapping of |
|
| lowest value |
|
| highest value |
insert()
insert()
Inserts a new value into the LinkedList, given an existing lower value. The new value to be inserted should not be an existing value. Also, the condition lowerValue < newValue < lowerValue.next
should be satisfied.
Field | Type | Explanation |
---|---|---|
|
| A mapping of |
|
| value to be inserted |
|
| highest existing value in the linked list that is |
remove()
remove()
Removes an existing value from the LinkedList. Returns the next lowest value (existingValue.previous
).
Note that no removal is performed if removedValue
happens to be the lowestValue
or highestValue
passed in init()
.
Field | Type | Explanation |
---|---|---|
|
| A mapping of |
|
| value to be removed |
LiqDeltaMath
Contains a function to assist with the addition of signed liquidityDelta to unsigned liquidity.
applyLiquidityDelta()
applyLiquidityDelta()
Adds or remove uint128
liquidityDelta to uint128
liquidity
Field | Type | Explanation |
---|---|---|
|
| Liquidity to be adjusted |
|
| quantity change to be applied |
|
| true = add liquidity, false = remove liquidity |
MathConstants
Contains constants commonly used by multiple files.
QtyDeltaMath
Contains functions for calculating token0 and token1 quantites from differences in prices or from burning reinvestment tokens
getQtysForInitialLockup()
getQtysForInitialLockup()
Calculate the token0 and token1 quantities needed for unlocking the pool given an initial price and liquidity.
Input
Input Field | Type | Explanation |
---|---|---|
|
| initial sqrt price raised by |
|
| initial liquidity. should be |
Output
Return Field | Type | Explanation |
---|---|---|
|
| token0 quantity required |
|
| token1 quantity required |
calcRequiredQty0()
calcRequiredQty0()
Calculates the token0 quantity between 2 sqrt prices for a given liquidity quantity.
Note that the function assumes that upperSqrtP > lowerSqrtP
.
Input
Field | Type | Explanation |
---|---|---|
|
| the lower sqrt price |
|
| the upper sqrt price |
|
| liquidity quantity |
|
| true = add liquidity, false = remove liquidity |
Output
Type | Explanation |
---|---|
| token0 qty required for position with liquidity between the 2 sqrt prices |
Generally, if the return value > 0, it will be transferred into the pool. Conversely, if the return value < 0, it will be transferred out of the pool.
calcRequiredQty1()
calcRequiredQty1()
Calculates the token1 quantity between 2 sqrt prices for a given liquidity quantity.
Note that the function assumes that upperSqrtP > lowerSqrtP
.
Input
Field | Type | Explanation |
---|---|---|
|
| the lower sqrt price |
|
| the upper sqrt price |
|
| liquidity quantity |
|
| true = add liquidity, false = remove liquidity |
Output
Type | Explanation |
---|---|
| token0 qty required for position with liquidity between the 2 sqrt prices |
Generally, if the return value > 0, it will be transferred into the pool. Conversely, if the return value < 0, it will be transferred out of the pool.
getQty0FromBurnRTokens()
getQty0FromBurnRTokens()
Calculates the token0 quantity to be sent to the user for a given amount of reinvestment tokens to be burnt.
Input Field | Type | Explanation |
---|---|---|
|
| the current sqrt price |
|
| expected change in reinvestment liquidity due to the burning of reinvestment tokens |
getQty1FromBurnRTokens()
getQty1FromBurnRTokens()
Calculates the token1 quantity to be sent to the user for a given amount of reinvestment tokens to be burnt.
Input Field | Type | Explanation |
---|---|---|
|
| the current sqrt price |
|
| expected change in reinvestment liquidity due to the burning of reinvestment tokens |
divCeiling()
divCeiling()
Returns ceil(x / y)
. y
should not be zero.
QuadMath
getSmallerRootOfQuadEqn()
getSmallerRootOfQuadEqn()
Given a variant of the quadratic equation where , and , calculate the smaller root via the quadratic formula.
Returns
Input Field | Type | Explanation |
---|---|---|
|
| |
|
| |
|
|
sqrt()
sqrt()
Unchanged from DMMv1. Calculates the square root of a value using the Babylonian method.
ReinvestmentMath
Contains a helper function to calculate reinvestment tokens to be minted given an increase in reinvestment liquidity.
calcRMintQty()
calcRMintQty()
Given the difference between reinvestL
and reinvestLLast
, calculate how many reinvestment tokens are to be minted.
Input Field | Type | Explanation |
---|---|---|
|
| latest reinvestment liquidity value. Should be |
|
| reinvestmentLiquidityLast value |
|
| active base liquidity |
|
| total supply of reinvestment token |
SafeCast
Contains methods for safely casting between different types.
toUint32()
toUint32()
Casts a uint256
to a uint32
. Reverts on overflow.
toInt128()
toInt128()
Casts a uint128
to a int128
. Reverts on overflow.
toUint128()
toUint128()
Casts a uint256
to a uint128
. Reverts on overflow.
revToUint128()
revToUint128()
Given int128 y
, returns uint128 z = -y
.
toUint160()
toUint160()
Casts a uint256
to a uint160
. Reverts on overflow.
toInt256()
toInt256()
Casts a uint256
to a int256
. Reverts on overflow.
revToInt256()
revToInt256()
Cast a uint256
to a int256
and reverses the sign. Reverts on overflow.
revToUint256()
revToUint256()
Given int256 y
, returns uint256 z = -y
.
SwapMath
Contains the logic needed for computing swap input / output amounts and fees. The primary function to look at is computeSwapStep
, as it is where the bulk of the swap flow logic is in, and where calls to the other functions in the library are made.
computeSwapStep()
computeSwapStep()
Computes the actual swap input / output amounts to be deducted or added, the swap fee to be collected and the resulting price.
Inputs
Field | Type | Explanation |
---|---|---|
|
| active base liquidity + reinvestment liquidity |
|
| current sqrt price |
|
| sqrt price limit |
|
| swap fee in basis points |
|
| amount remaining to be used for the swap |
|
| true if |
|
| true if |
Outputs
Field | Type | Explanation |
---|---|---|
|
| actual amount to be used for the swap. >= 0 if |
|
| output qty (<= 0) to be accumulated if |
|
| collected swap fee, to be incremented to reinvest liquidity |
|
| new sqrt price after the computed swap step |
Note
nextSqrtP
should not exceed targetSqrtP
.
calcReachAmount()
calcReachAmount()
Calculates the amount needed to reach targetSqrtP
from currentSqrtP
. Note that currentSqrtP
and targetSqrtP
are casted from uint160 to uint256 as they are multiplied by TWO_BPS (20_000)
or feeInBps
.
The mathematical formulas are provided below for reference.
isExactInput | isToken0 | Formula |
---|---|---|
|
| (>0) |
|
| (>0) |
|
| (<0) |
|
| (<0) |
Note that while cases 1 and 3 and cases 2 and 4 are mathematically equivalent, the implementation differs by performing a double negation for the exact output cases. It takes the difference of and in the numerator (>0), then performing a second negation.
Input Field | Type | Formula Variable | Explanation |
---|---|---|---|
|
| active base liquidity + reinvestment liquidity | |
|
| current sqrt price | |
|
| sqrt price limit | |
|
| swap fee in basis points | |
|
| N.A. | true / false if specified swap amount refers to input / output amount respectively |
|
| N.A. | true / false if specified swap amount is in token0 / token1 respectively |
estimateIncrementalLiquidity()
estimateIncrementalLiquidity()
Estimates deltaL
, the swap fee to be collected based on amountSpecified. This is called only for the final swap step, where the next (temporary) tick will not be crossed.
In the case where exact input is specified, the formula is rather straightforward.
isToken0 | Formula |
---|---|
|
|
|
|
In the case where exact output is specified, a quadratic equation has to be solved. The desired result is the smaller root of the quadratic equation.
isToken0 | Formula |
---|---|
| |
|
Input Field | Type | Formula Variable | Explanation |
---|---|---|---|
|
|
| |
|
| active base liquidity + reinvestment liquidity | |
|
| current sqrt price | |
|
| swap fee in basis points | |
|
| N.A. | true / false if specified swap amount refers to input / output amount respectively |
|
| N.A. | true / false if specified swap amount is in token0 / token1 respectively |
calcIncrementalLiquidity()
calcIncrementalLiquidity()
Calculates deltaL
, the swap fee to be collected based on amountSpecified. This is called for an intermediate swap step, where the next (temporary) tick will be crossed.
The mathematical formulas are provided below for reference.
isExactInput | isToken0 | Formula |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
Inputs
Input Field | Type | Formula Variable | Explanation |
---|---|---|---|
|
| || |
|
|
| active base liquidity + reinvestment liquidity | |
|
| current sqrt price | |
|
| next sqrt price | |
|
| N.A. | true / false if specified swap amount refers to input / output amount respectively |
|
| N.A. | true / false if specified swap amount is in token0 / token1 respectively |
calcFinalPrice()
calcFinalPrice()
Calculates the sqrt price of the final swap step where the next (temporary) tick will not be crossed.
The mathematical formulas are provided below for reference.
isExactInput | isToken0 | Formula |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
Input
Input Field | Type | Formula Variable | Explanation |
---|---|---|---|
|
| || |
|
|
| active base liquidity + reinvestment liquidity | |
|
| collected swap fee | |
|
| current sqrt price | |
|
| N.A. | true / false if specified swap amount refers to input / output amount respectively |
|
| N.A. | true / false if specified swap amount is in token0 / token1 respectively |
calcReturnedAmount()
calcReturnedAmount()
Calculates returnedAmount
for the computeSwapStep
function. Rounds down when isExactInput = true
(calculating output < 0) so that we avoid sending too much. Conversely, rounds up when isExactInput = false
to ensure sufficient input > 0 will be received.
The mathematical formulas are provided below for reference.
isToken0 = true
The formula is actually the same, with the difference being made to the operands to ensure the price difference is non-negative.
isExactInput | Formula |
---|---|
| |
|
isToken0 = false
Input Field | Type | Formula Variable | Explanation |
---|---|---|---|
|
| active base liquidity + reinvestment liquidity | |
|
| current sqrt price | |
|
| next sqrt price | |
|
| collected swap fee | |
|
| N.A. | true / false if specified swap amount refers to input / output amount respectively |
|
| N.A. | true / false if specified swap amount is in token0 / token1 respectively |
TickMath
Contains functions for computing square root prices from ticks and vice versa. Adapted from Uniswap V3's TickMath library.
Constants
Field | Type | Value | Explanation |
---|---|---|---|
|
|
| Minimum possible tick = |
|
|
| Minimum possible tick = |
|
|
|
|
|
|
|
|
getSqrtRatioAtTick()
getSqrtRatioAtTick()
Given a int24 tick
, calculates .
getTickAtSqrtRatio()
getTickAtSqrtRatio()
Given a square root price ratio uint160 sqrtP
, calculates the greatest tick
such that getSqrtRatioAtTick(tick) <= sqrtP
.
Note that MIN_SQRT_RATIO <= sqrtP <= MAX_SQRT_RATIO
, otherwise the function will revert.
getMaxNumberTicks()
getMaxNumberTicks()
Used to calculate the maximum liquidity allowable per tick. This function calculates the maximum number of ticks that can be inserted into the LinkedList, given a tickDistance
.
Field | Type | Explanation |
---|---|---|
|
| Ticks can only be initialized at multiples of this value. |
Last updated