Source Code
Overview
ETH Balance
0 ETH
ETH Value
$0.00| Transaction Hash |
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
Latest 1 internal transaction
Advanced mode:
| Parent Transaction Hash | Block | From | To | |||
|---|---|---|---|---|---|---|
| 18138094 | 237 days ago | Contract Creation | 0 ETH |
Cross-Chain Transactions
Loading...
Loading
Contract Name:
BunniSwapMath
Compiler Version
v0.8.30+commit.73712a01
Optimization Enabled:
Yes with 100000000 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {IPoolManager, PoolKey} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {SafeCastLib} from "solady/utils/SafeCastLib.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import "./Math.sol";
import "../base/Errors.sol";
import "../base/Constants.sol";
import "../types/IdleBalance.sol";
import {SwapMath} from "./SwapMath.sol";
import {queryLDF} from "./QueryLDF.sol";
import {FullMathX96} from "./FullMathX96.sol";
import {SqrtPriceMath} from "./SqrtPriceMath.sol";
import {LiquidityAmounts} from "./LiquidityAmounts.sol";
import {ILiquidityDensityFunction} from "../interfaces/ILiquidityDensityFunction.sol";
library BunniSwapMath {
using TickMath for *;
using FullMathX96 for *;
using SafeCastLib for uint256;
using FixedPointMathLib for uint256;
/// @dev An infinitesimal fee rate is applied to naive swaps to protect against exact input vs exact output rate mismatches when swap amounts/liquidity are small.
/// The current value corresponds to 0.003%.
uint24 private constant EPSILON_FEE = 30;
struct BunniComputeSwapInput {
PoolKey key;
uint256 totalLiquidity;
uint256 liquidityDensityOfRoundedTickX96;
uint256 currentActiveBalance0;
uint256 currentActiveBalance1;
uint160 sqrtPriceX96;
int24 currentTick;
ILiquidityDensityFunction liquidityDensityFunction;
int24 arithmeticMeanTick;
bytes32 ldfParams;
bytes32 ldfState;
IPoolManager.SwapParams swapParams;
}
/// @notice Computes the result of a swap given the input parameters
/// @param input The input parameters for the swap
/// @return updatedSqrtPriceX96 The updated sqrt price after the swap
/// @return updatedTick The updated tick after the swap
/// @return inputAmount The input amount of the swap
/// @return outputAmount The output amount of the swap
function computeSwap(BunniComputeSwapInput calldata input)
external
view
returns (uint160 updatedSqrtPriceX96, int24 updatedTick, uint256 inputAmount, uint256 outputAmount)
{
bool zeroForOne = input.swapParams.zeroForOne;
bool exactIn = input.swapParams.amountSpecified < 0;
// initialize input and output amounts based on initial info
inputAmount = exactIn ? uint256(-input.swapParams.amountSpecified) : 0;
outputAmount = exactIn ? 0 : uint256(input.swapParams.amountSpecified);
// compute updated rounded tick liquidity
uint256 updatedRoundedTickLiquidity = (input.totalLiquidity * input.liquidityDensityOfRoundedTickX96) >> 96;
// initialize updatedTick to the current tick
updatedTick = input.currentTick;
// bound sqrtPriceLimitX96 by min/max possible values
uint160 sqrtPriceLimitX96 = input.swapParams.sqrtPriceLimitX96;
{
(uint160 minSqrtPrice, uint160 maxSqrtPrice) = (
TickMath.minUsableTick(input.key.tickSpacing).getSqrtPriceAtTick(),
TickMath.maxUsableTick(input.key.tickSpacing).getSqrtPriceAtTick()
);
// bound sqrtPriceLimit so that we never end up at an invalid rounded tick
if ((zeroForOne && sqrtPriceLimitX96 <= minSqrtPrice) || (!zeroForOne && sqrtPriceLimitX96 >= maxSqrtPrice))
{
sqrtPriceLimitX96 = zeroForOne ? minSqrtPrice + 1 : maxSqrtPrice - 1;
}
}
{
(int24 roundedTick, int24 nextRoundedTick) = roundTick(input.currentTick, input.key.tickSpacing);
uint160 naiveSwapResultSqrtPriceX96;
uint256 naiveSwapAmountIn;
uint256 naiveSwapAmountOut;
{
// handle the special case when we don't cross rounded ticks
if (updatedRoundedTickLiquidity != 0) {
// compute the resulting sqrt price using Uniswap math
int24 tickNext = zeroForOne ? roundedTick : nextRoundedTick;
uint160 sqrtPriceNextX96 = TickMath.getSqrtPriceAtTick(tickNext);
(naiveSwapResultSqrtPriceX96, naiveSwapAmountIn, naiveSwapAmountOut) = SwapMath.computeSwapStep({
sqrtPriceCurrentX96: input.sqrtPriceX96,
sqrtPriceTargetX96: SwapMath.getSqrtPriceTarget(zeroForOne, sqrtPriceNextX96, sqrtPriceLimitX96),
liquidity: updatedRoundedTickLiquidity,
amountRemaining: input.swapParams.amountSpecified,
feePips: 0
});
// check if naive swap exhausted the specified amount
if (
exactIn
? naiveSwapAmountIn == uint256(-input.swapParams.amountSpecified)
: naiveSwapAmountOut == uint256(input.swapParams.amountSpecified)
) {
// swap doesn't cross rounded tick
// compute the updated tick
// was initialized earlier as input.currentTick
if (naiveSwapResultSqrtPriceX96 == sqrtPriceNextX96) {
// Equivalent to `updatedTick = zeroForOne ? tickNext - 1 : tickNext;`
unchecked {
// cannot cast a bool to an int24 in Solidity
int24 _zeroForOne;
assembly {
_zeroForOne := zeroForOne
}
updatedTick = tickNext - _zeroForOne;
}
} else if (naiveSwapResultSqrtPriceX96 != input.sqrtPriceX96) {
// recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved
updatedTick = TickMath.getTickAtSqrtPrice(naiveSwapResultSqrtPriceX96);
}
// naiveSwapAmountOut should be at most the corresponding active balance
// this may be violated due to precision loss
naiveSwapAmountOut = FixedPointMathLib.min(
naiveSwapAmountOut, zeroForOne ? input.currentActiveBalance1 : input.currentActiveBalance0
);
// early return
return (naiveSwapResultSqrtPriceX96, updatedTick, naiveSwapAmountIn, naiveSwapAmountOut);
}
}
}
// swap crosses rounded tick
// need to use LDF to compute the swap
// compute updated sqrt ratio & tick
uint256 inverseCumulativeAmountFnInput;
if (exactIn) {
// exact input swap
inverseCumulativeAmountFnInput =
zeroForOne ? input.currentActiveBalance0 + inputAmount : input.currentActiveBalance1 + inputAmount;
} else {
// exact output swap
inverseCumulativeAmountFnInput =
zeroForOne ? input.currentActiveBalance1 - outputAmount : input.currentActiveBalance0 - outputAmount;
}
(
bool success,
int24 updatedRoundedTick,
uint256 cumulativeAmount0,
uint256 cumulativeAmount1,
uint256 swapLiquidity
) = input.liquidityDensityFunction.computeSwap(
input.key,
inverseCumulativeAmountFnInput,
input.totalLiquidity,
zeroForOne,
exactIn,
input.arithmeticMeanTick,
input.currentTick,
input.ldfParams,
input.ldfState
);
if (success) {
// edge case: LDF says we're still in the same rounded tick
// or in a rounded tick in the opposite direction as the swap
// meaning first naive swap was insufficient but it should have been
// use the result from the first naive swap
if (zeroForOne ? updatedRoundedTick >= roundedTick : updatedRoundedTick <= roundedTick) {
if (updatedRoundedTickLiquidity == 0) {
// no liquidity, return trivial swap
return (input.sqrtPriceX96, input.currentTick, 0, 0);
}
// compute the updated tick
// was initialized earlier as input.currentTick
int24 _tickNext = zeroForOne ? roundedTick : nextRoundedTick;
if (naiveSwapResultSqrtPriceX96 == TickMath.getSqrtPriceAtTick(_tickNext)) {
// Equivalent to `updatedTick = zeroForOne ? _tickNext - 1 : _tickNext;`
unchecked {
// cannot cast a bool to an int24 in Solidity
int24 _zeroForOne;
assembly {
_zeroForOne := zeroForOne
}
updatedTick = _tickNext - _zeroForOne;
}
} else if (naiveSwapResultSqrtPriceX96 != input.sqrtPriceX96) {
// recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved
updatedTick = TickMath.getTickAtSqrtPrice(naiveSwapResultSqrtPriceX96);
}
// naiveSwapAmountOut should be at most the corresponding active balance
// this may be violated due to precision loss
naiveSwapAmountOut = FixedPointMathLib.min(
naiveSwapAmountOut, zeroForOne ? input.currentActiveBalance1 : input.currentActiveBalance0
);
// early return
return (naiveSwapResultSqrtPriceX96, updatedTick, naiveSwapAmountIn, naiveSwapAmountOut);
}
// use Uniswap math to compute updated sqrt price
// the swap is called "partial swap"
// which always has the same exactIn and zeroForOne as the overall swap
(int24 tickStart, int24 tickNext) = zeroForOne
? (updatedRoundedTick + input.key.tickSpacing, updatedRoundedTick)
: (updatedRoundedTick, updatedRoundedTick + input.key.tickSpacing);
uint160 startSqrtPriceX96 = tickStart.getSqrtPriceAtTick();
// make sure the price limit is not reached
if (
(zeroForOne && sqrtPriceLimitX96 <= startSqrtPriceX96)
|| (!zeroForOne && sqrtPriceLimitX96 >= startSqrtPriceX96)
) {
uint160 sqrtPriceNextX96 = tickNext.getSqrtPriceAtTick();
// adjust the cumulativeAmount of the input token to be at least the corresponding currentActiveBalance
// we know that we're swapping in a different rounded tick as the starting one (based on the first naive swap)
// so this should be true but sometimes isn't due to precision error which is why the adjustment is necessary
if (zeroForOne) {
cumulativeAmount0 = FixedPointMathLib.max(cumulativeAmount0, input.currentActiveBalance0);
} else {
cumulativeAmount1 = FixedPointMathLib.max(cumulativeAmount1, input.currentActiveBalance1);
}
// perform naive swap within the updated rounded tick
bool hitSqrtPriceLimit;
if (swapLiquidity == 0 || sqrtPriceLimitX96 == startSqrtPriceX96) {
// don't move from the starting price
(naiveSwapResultSqrtPriceX96, naiveSwapAmountIn, naiveSwapAmountOut) = (startSqrtPriceX96, 0, 0);
} else {
// has swap liquidity, use Uniswap math to compute updated sqrt price and input/output amounts
int256 amountSpecifiedRemaining = exactIn
? -(inverseCumulativeAmountFnInput - (zeroForOne ? cumulativeAmount0 : cumulativeAmount1)).toInt256(
)
: ((zeroForOne ? cumulativeAmount1 : cumulativeAmount0) - inverseCumulativeAmountFnInput)
.toInt256();
(naiveSwapResultSqrtPriceX96, naiveSwapAmountIn, naiveSwapAmountOut) = SwapMath.computeSwapStep({
sqrtPriceCurrentX96: startSqrtPriceX96,
sqrtPriceTargetX96: SwapMath.getSqrtPriceTarget(zeroForOne, sqrtPriceNextX96, sqrtPriceLimitX96),
liquidity: swapLiquidity,
amountRemaining: amountSpecifiedRemaining,
feePips: EPSILON_FEE
});
if (naiveSwapResultSqrtPriceX96 == sqrtPriceLimitX96 && sqrtPriceLimitX96 != sqrtPriceNextX96) {
// give up if the swap hits the sqrt price limit
hitSqrtPriceLimit = true;
}
}
if (!hitSqrtPriceLimit) {
// initialize updatedTick to tickStart
updatedTick = tickStart;
// compute updatedTick
if (naiveSwapResultSqrtPriceX96 == sqrtPriceNextX96) {
// Equivalent to `updatedTick = zeroForOne ? tickNext - 1 : tickNext;`
unchecked {
// cannot cast a bool to an int24 in Solidity
int24 _zeroForOne;
assembly {
_zeroForOne := zeroForOne
}
updatedTick = tickNext - _zeroForOne;
}
} else if (naiveSwapResultSqrtPriceX96 != startSqrtPriceX96) {
// recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved
updatedTick = TickMath.getTickAtSqrtPrice(naiveSwapResultSqrtPriceX96);
}
// set updatedSqrtPriceX96
updatedSqrtPriceX96 = naiveSwapResultSqrtPriceX96;
if (
exactIn
? naiveSwapAmountIn == uint256(-input.swapParams.amountSpecified)
: naiveSwapAmountOut == uint256(input.swapParams.amountSpecified)
) {
// edge case: the partial swap consumed the entire amount specified
// return the result of the partial swap directly
// naiveSwapAmountOut should be at most the corresponding active balance
// this may be violated due to precision loss
naiveSwapAmountOut = FixedPointMathLib.min(
naiveSwapAmountOut,
zeroForOne ? input.currentActiveBalance1 : input.currentActiveBalance0
);
return (naiveSwapResultSqrtPriceX96, updatedTick, naiveSwapAmountIn, naiveSwapAmountOut);
}
if (
(zeroForOne && cumulativeAmount1 < naiveSwapAmountOut)
|| (!zeroForOne && cumulativeAmount0 < naiveSwapAmountOut)
) {
// in rare cases the rounding error can cause one of the active balances to be negative
// revert in such cases to avoid leaking value
revert BunniSwapMath__SwapFailed();
}
(uint256 updatedActiveBalance0, uint256 updatedActiveBalance1) = zeroForOne
? (cumulativeAmount0 + naiveSwapAmountIn, cumulativeAmount1 - naiveSwapAmountOut)
: (cumulativeAmount0 - naiveSwapAmountOut, cumulativeAmount1 + naiveSwapAmountIn);
// compute input and output token amounts
// NOTE: The rounding direction of all the values involved are correct:
// - cumulative amounts are rounded up
// - naiveSwapAmountIn is rounded up
// - naiveSwapAmountOut is rounded down
// - currentActiveBalance0 and currentActiveBalance1 are rounded down
// Overall this leads to inputAmount being rounded up and outputAmount being rounded down
// which is safe.
// Use subReLU so that when the computed output is somehow negative (most likely due to precision loss)
// we output 0 instead of reverting.
(inputAmount, outputAmount) = zeroForOne
? (
updatedActiveBalance0 - input.currentActiveBalance0,
subReLU(input.currentActiveBalance1, updatedActiveBalance1)
)
: (
updatedActiveBalance1 - input.currentActiveBalance1,
subReLU(input.currentActiveBalance0, updatedActiveBalance0)
);
return (updatedSqrtPriceX96, updatedTick, inputAmount, outputAmount);
}
}
}
}
// the sqrt price limit has been reached
(updatedSqrtPriceX96, updatedTick) = (
sqrtPriceLimitX96,
sqrtPriceLimitX96 == input.sqrtPriceX96 ? input.currentTick : sqrtPriceLimitX96.getTickAtSqrtPrice() // recompute tick unless we haven't moved
);
// Rounding directions:
// currentActiveBalance: down
// totalDensity: up
// updatedActiveBalance: up
(, uint256 totalDensity0X96, uint256 totalDensity1X96,,,,,) = queryLDF({
key: input.key,
sqrtPriceX96: updatedSqrtPriceX96,
tick: updatedTick,
arithmeticMeanTick: input.arithmeticMeanTick,
ldf: input.liquidityDensityFunction,
ldfParams: input.ldfParams,
ldfState: input.ldfState,
balance0: 0,
balance1: 0,
idleBalance: IdleBalanceLibrary.ZERO
});
(uint256 _updatedActiveBalance0, uint256 _updatedActiveBalance1) =
(totalDensity0X96.fullMulX96Up(input.totalLiquidity), totalDensity1X96.fullMulX96Up(input.totalLiquidity));
// Use subReLU so that when the computed output is somehow negative (most likely due to precision loss)
// we output 0 instead of reverting.
if (zeroForOne) {
(inputAmount, outputAmount) = (
_updatedActiveBalance0 - input.currentActiveBalance0,
subReLU(input.currentActiveBalance1, _updatedActiveBalance1)
);
} else {
(inputAmount, outputAmount) = (
_updatedActiveBalance1 - input.currentActiveBalance1,
subReLU(input.currentActiveBalance0, _updatedActiveBalance0)
);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice 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
library TickMath {
using CustomRevert for bytes4;
/// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
error InvalidTick(int24 tick);
/// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
error InvalidSqrtPrice(uint160 sqrtPriceX96);
/// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MAX_TICK = 887272;
/// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
int24 internal constant MIN_TICK_SPACING = 1;
/// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
int24 internal constant MAX_TICK_SPACING = type(int16).max;
/// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_PRICE = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
/// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
1461446703485210103287273052203988822378723970342 - 4295128739 - 1;
/// @notice Given a tickSpacing, compute the maximum usable tick
function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MAX_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Given a tickSpacing, compute the minimum usable tick
function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MIN_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
/// at the given tick
function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick;
assembly ("memory-safe") {
tick := signextend(2, tick)
// mask = 0 if tick >= 0 else -1 (all 1s)
let mask := sar(255, tick)
// if tick >= 0, |tick| = tick = 0 ^ tick
// if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
// either way, |tick| = mask ^ (tick + mask)
absTick := xor(mask, add(mask, tick))
}
if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);
// The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
// is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer
// Equivalent to:
// price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
// or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
uint256 price;
assembly ("memory-safe") {
price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
}
if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;
assembly ("memory-safe") {
// if (tick > 0) price = type(uint256).max / price;
if sgt(tick, 0) { price := div(not(0), price) }
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtPrice of the output price is always consistent
// `sub(shl(32, 1), 1)` is `type(uint32).max`
// `price + type(uint32).max` will not overflow because `price` fits in 192 bits
sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
}
}
}
/// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
// Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
// second inequality must be >= because the price can never reach the price at the max tick
// if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
// if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
}
uint256 price = uint256(sqrtPriceX96) << 32;
uint256 r = price;
uint256 msb = BitMath.mostSignificantBit(r);
if (msb >= 128) r = price >> (msb - 127);
else r = price << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number
// Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
// Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
// sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
// is changed, this may need to be changed too
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";
/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
/// @notice Thrown when a currency is not netted out after the contract is unlocked
error CurrencyNotSettled();
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice Thrown when unlock is called, but the contract is already unlocked
error AlreadyUnlocked();
/// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
error ManagerLocked();
/// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
error TickSpacingTooLarge(int24 tickSpacing);
/// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
error TickSpacingTooSmall(int24 tickSpacing);
/// @notice PoolKey must have currencies where address(currency0) < address(currency1)
error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);
/// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
/// or on a pool that does not have a dynamic swap fee.
error UnauthorizedDynamicLPFeeUpdate();
/// @notice Thrown when trying to swap amount of 0
error SwapAmountCannotBeZero();
///@notice Thrown when native currency is passed to a non native settlement
error NonzeroNativeValue();
/// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
error MustClearExactPositiveDelta();
/// @notice Emitted when a new pool is initialized
/// @param id The abi encoded hash of the pool key struct for the new pool
/// @param currency0 The first currency of the pool by address sort order
/// @param currency1 The second currency of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param hooks The hooks contract address for the pool, or address(0) if none
/// @param sqrtPriceX96 The price of the pool on initialization
/// @param tick The initial tick of the pool corresponding to the initialized price
event Initialize(
PoolId indexed id,
Currency indexed currency0,
Currency indexed currency1,
uint24 fee,
int24 tickSpacing,
IHooks hooks,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted when a liquidity position is modified
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that modified the pool
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param liquidityDelta The amount of liquidity that was added or removed
/// @param salt The extra data to make positions unique
event ModifyLiquidity(
PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
);
/// @notice Emitted for swaps between currency0 and currency1
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that initiated the swap call, and that received the callback
/// @param amount0 The delta of the currency0 balance of the pool
/// @param amount1 The delta of the currency1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of the price of the pool after the swap
/// @param fee The swap fee in hundredths of a bip
event Swap(
PoolId indexed id,
address indexed sender,
int128 amount0,
int128 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick,
uint24 fee
);
/// @notice Emitted for donations
/// @param id The abi encoded hash of the pool key struct for the pool that was donated to
/// @param sender The address that initiated the donate call
/// @param amount0 The amount donated in currency0
/// @param amount1 The amount donated in currency1
event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);
/// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
/// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
/// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
/// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
/// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
function unlock(bytes calldata data) external returns (bytes memory);
/// @notice Initialize the state for a given pool ID
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The pool key for the pool to initialize
/// @param sqrtPriceX96 The initial square root price
/// @return tick The initial tick of the pool
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
struct ModifyLiquidityParams {
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Modify the liquidity for the given pool
/// @dev Poke by calling with a zero liquidityDelta
/// @param key The pool to modify liquidity in
/// @param params The parameters for modifying the liquidity
/// @param hookData The data to pass through to the add/removeLiquidity hooks
/// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
/// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
/// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
/// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
/// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
external
returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}
/// @notice Swap against the given pool
/// @param key The pool to swap in
/// @param params The parameters for swapping
/// @param hookData The data to pass through to the swap hooks
/// @return swapDelta The balance delta of the address swapping
/// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
/// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
/// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
external
returns (BalanceDelta swapDelta);
/// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
/// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
/// Donors should keep this in mind when designing donation mechanisms.
/// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
/// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
/// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
/// Read the comments in `Pool.swap()` for more information about this.
/// @param key The key of the pool to donate to
/// @param amount0 The amount of currency0 to donate
/// @param amount1 The amount of currency1 to donate
/// @param hookData The data to pass through to the donate hooks
/// @return BalanceDelta The delta of the caller after the donate
function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
external
returns (BalanceDelta);
/// @notice Writes the current ERC20 balance of the specified currency to transient storage
/// This is used to checkpoint balances for the manager and derive deltas for the caller.
/// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
/// for native tokens because the amount to settle is determined by the sent value.
/// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
/// native funds, this function can be called with the native currency to then be able to settle the native currency
function sync(Currency currency) external;
/// @notice Called by the user to net out some value owed to the user
/// @dev Will revert if the requested amount is not available, consider using `mint` instead
/// @dev Can also be used as a mechanism for free flash loans
/// @param currency The currency to withdraw from the pool manager
/// @param to The address to withdraw to
/// @param amount The amount of currency to withdraw
function take(Currency currency, address to, uint256 amount) external;
/// @notice Called by the user to pay what is owed
/// @return paid The amount of currency settled
function settle() external payable returns (uint256 paid);
/// @notice Called by the user to pay on behalf of another address
/// @param recipient The address to credit for the payment
/// @return paid The amount of currency settled
function settleFor(address recipient) external payable returns (uint256 paid);
/// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
/// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
/// @dev This could be used to clear a balance that is considered dust.
/// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
function clear(Currency currency, uint256 amount) external;
/// @notice Called by the user to move value into ERC6909 balance
/// @param to The address to mint the tokens to
/// @param id The currency address to mint to ERC6909s, as a uint256
/// @param amount The amount of currency to mint
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function mint(address to, uint256 id, uint256 amount) external;
/// @notice Called by the user to move value from ERC6909 balance
/// @param from The address to burn the tokens from
/// @param id The currency address to burn from ERC6909s, as a uint256
/// @param amount The amount of currency to burn
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function burn(address from, uint256 id, uint256 amount) external;
/// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The key of the pool to update dynamic LP fees for
/// @param newDynamicLPFee The new dynamic pool LP fee
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe integer casting library that reverts on overflow.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeCastLib.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol)
/// @dev Optimized for runtime gas for very high number of optimizer runs (i.e. >= 1000000).
library SafeCastLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unable to cast to the target type due to overflow.
error Overflow();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* UNSIGNED INTEGER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Casts `x` to a uint8. Reverts on overflow.
function toUint8(uint256 x) internal pure returns (uint8) {
if (x >= 1 << 8) _revertOverflow();
return uint8(x);
}
/// @dev Casts `x` to a uint16. Reverts on overflow.
function toUint16(uint256 x) internal pure returns (uint16) {
if (x >= 1 << 16) _revertOverflow();
return uint16(x);
}
/// @dev Casts `x` to a uint24. Reverts on overflow.
function toUint24(uint256 x) internal pure returns (uint24) {
if (x >= 1 << 24) _revertOverflow();
return uint24(x);
}
/// @dev Casts `x` to a uint32. Reverts on overflow.
function toUint32(uint256 x) internal pure returns (uint32) {
if (x >= 1 << 32) _revertOverflow();
return uint32(x);
}
/// @dev Casts `x` to a uint40. Reverts on overflow.
function toUint40(uint256 x) internal pure returns (uint40) {
if (x >= 1 << 40) _revertOverflow();
return uint40(x);
}
/// @dev Casts `x` to a uint48. Reverts on overflow.
function toUint48(uint256 x) internal pure returns (uint48) {
if (x >= 1 << 48) _revertOverflow();
return uint48(x);
}
/// @dev Casts `x` to a uint56. Reverts on overflow.
function toUint56(uint256 x) internal pure returns (uint56) {
if (x >= 1 << 56) _revertOverflow();
return uint56(x);
}
/// @dev Casts `x` to a uint64. Reverts on overflow.
function toUint64(uint256 x) internal pure returns (uint64) {
if (x >= 1 << 64) _revertOverflow();
return uint64(x);
}
/// @dev Casts `x` to a uint72. Reverts on overflow.
function toUint72(uint256 x) internal pure returns (uint72) {
if (x >= 1 << 72) _revertOverflow();
return uint72(x);
}
/// @dev Casts `x` to a uint80. Reverts on overflow.
function toUint80(uint256 x) internal pure returns (uint80) {
if (x >= 1 << 80) _revertOverflow();
return uint80(x);
}
/// @dev Casts `x` to a uint88. Reverts on overflow.
function toUint88(uint256 x) internal pure returns (uint88) {
if (x >= 1 << 88) _revertOverflow();
return uint88(x);
}
/// @dev Casts `x` to a uint96. Reverts on overflow.
function toUint96(uint256 x) internal pure returns (uint96) {
if (x >= 1 << 96) _revertOverflow();
return uint96(x);
}
/// @dev Casts `x` to a uint104. Reverts on overflow.
function toUint104(uint256 x) internal pure returns (uint104) {
if (x >= 1 << 104) _revertOverflow();
return uint104(x);
}
/// @dev Casts `x` to a uint112. Reverts on overflow.
function toUint112(uint256 x) internal pure returns (uint112) {
if (x >= 1 << 112) _revertOverflow();
return uint112(x);
}
/// @dev Casts `x` to a uint120. Reverts on overflow.
function toUint120(uint256 x) internal pure returns (uint120) {
if (x >= 1 << 120) _revertOverflow();
return uint120(x);
}
/// @dev Casts `x` to a uint128. Reverts on overflow.
function toUint128(uint256 x) internal pure returns (uint128) {
if (x >= 1 << 128) _revertOverflow();
return uint128(x);
}
/// @dev Casts `x` to a uint136. Reverts on overflow.
function toUint136(uint256 x) internal pure returns (uint136) {
if (x >= 1 << 136) _revertOverflow();
return uint136(x);
}
/// @dev Casts `x` to a uint144. Reverts on overflow.
function toUint144(uint256 x) internal pure returns (uint144) {
if (x >= 1 << 144) _revertOverflow();
return uint144(x);
}
/// @dev Casts `x` to a uint152. Reverts on overflow.
function toUint152(uint256 x) internal pure returns (uint152) {
if (x >= 1 << 152) _revertOverflow();
return uint152(x);
}
/// @dev Casts `x` to a uint160. Reverts on overflow.
function toUint160(uint256 x) internal pure returns (uint160) {
if (x >= 1 << 160) _revertOverflow();
return uint160(x);
}
/// @dev Casts `x` to a uint168. Reverts on overflow.
function toUint168(uint256 x) internal pure returns (uint168) {
if (x >= 1 << 168) _revertOverflow();
return uint168(x);
}
/// @dev Casts `x` to a uint176. Reverts on overflow.
function toUint176(uint256 x) internal pure returns (uint176) {
if (x >= 1 << 176) _revertOverflow();
return uint176(x);
}
/// @dev Casts `x` to a uint184. Reverts on overflow.
function toUint184(uint256 x) internal pure returns (uint184) {
if (x >= 1 << 184) _revertOverflow();
return uint184(x);
}
/// @dev Casts `x` to a uint192. Reverts on overflow.
function toUint192(uint256 x) internal pure returns (uint192) {
if (x >= 1 << 192) _revertOverflow();
return uint192(x);
}
/// @dev Casts `x` to a uint200. Reverts on overflow.
function toUint200(uint256 x) internal pure returns (uint200) {
if (x >= 1 << 200) _revertOverflow();
return uint200(x);
}
/// @dev Casts `x` to a uint208. Reverts on overflow.
function toUint208(uint256 x) internal pure returns (uint208) {
if (x >= 1 << 208) _revertOverflow();
return uint208(x);
}
/// @dev Casts `x` to a uint216. Reverts on overflow.
function toUint216(uint256 x) internal pure returns (uint216) {
if (x >= 1 << 216) _revertOverflow();
return uint216(x);
}
/// @dev Casts `x` to a uint224. Reverts on overflow.
function toUint224(uint256 x) internal pure returns (uint224) {
if (x >= 1 << 224) _revertOverflow();
return uint224(x);
}
/// @dev Casts `x` to a uint232. Reverts on overflow.
function toUint232(uint256 x) internal pure returns (uint232) {
if (x >= 1 << 232) _revertOverflow();
return uint232(x);
}
/// @dev Casts `x` to a uint240. Reverts on overflow.
function toUint240(uint256 x) internal pure returns (uint240) {
if (x >= 1 << 240) _revertOverflow();
return uint240(x);
}
/// @dev Casts `x` to a uint248. Reverts on overflow.
function toUint248(uint256 x) internal pure returns (uint248) {
if (x >= 1 << 248) _revertOverflow();
return uint248(x);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIGNED INTEGER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Casts `x` to a int8. Reverts on overflow.
function toInt8(int256 x) internal pure returns (int8) {
unchecked {
if (((1 << 7) + uint256(x)) >> 8 == uint256(0)) return int8(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int16. Reverts on overflow.
function toInt16(int256 x) internal pure returns (int16) {
unchecked {
if (((1 << 15) + uint256(x)) >> 16 == uint256(0)) return int16(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int24. Reverts on overflow.
function toInt24(int256 x) internal pure returns (int24) {
unchecked {
if (((1 << 23) + uint256(x)) >> 24 == uint256(0)) return int24(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int32. Reverts on overflow.
function toInt32(int256 x) internal pure returns (int32) {
unchecked {
if (((1 << 31) + uint256(x)) >> 32 == uint256(0)) return int32(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int40. Reverts on overflow.
function toInt40(int256 x) internal pure returns (int40) {
unchecked {
if (((1 << 39) + uint256(x)) >> 40 == uint256(0)) return int40(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int48. Reverts on overflow.
function toInt48(int256 x) internal pure returns (int48) {
unchecked {
if (((1 << 47) + uint256(x)) >> 48 == uint256(0)) return int48(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int56. Reverts on overflow.
function toInt56(int256 x) internal pure returns (int56) {
unchecked {
if (((1 << 55) + uint256(x)) >> 56 == uint256(0)) return int56(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int64. Reverts on overflow.
function toInt64(int256 x) internal pure returns (int64) {
unchecked {
if (((1 << 63) + uint256(x)) >> 64 == uint256(0)) return int64(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int72. Reverts on overflow.
function toInt72(int256 x) internal pure returns (int72) {
unchecked {
if (((1 << 71) + uint256(x)) >> 72 == uint256(0)) return int72(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int80. Reverts on overflow.
function toInt80(int256 x) internal pure returns (int80) {
unchecked {
if (((1 << 79) + uint256(x)) >> 80 == uint256(0)) return int80(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int88. Reverts on overflow.
function toInt88(int256 x) internal pure returns (int88) {
unchecked {
if (((1 << 87) + uint256(x)) >> 88 == uint256(0)) return int88(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int96. Reverts on overflow.
function toInt96(int256 x) internal pure returns (int96) {
unchecked {
if (((1 << 95) + uint256(x)) >> 96 == uint256(0)) return int96(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int104. Reverts on overflow.
function toInt104(int256 x) internal pure returns (int104) {
unchecked {
if (((1 << 103) + uint256(x)) >> 104 == uint256(0)) return int104(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int112. Reverts on overflow.
function toInt112(int256 x) internal pure returns (int112) {
unchecked {
if (((1 << 111) + uint256(x)) >> 112 == uint256(0)) return int112(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int120. Reverts on overflow.
function toInt120(int256 x) internal pure returns (int120) {
unchecked {
if (((1 << 119) + uint256(x)) >> 120 == uint256(0)) return int120(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int128. Reverts on overflow.
function toInt128(int256 x) internal pure returns (int128) {
unchecked {
if (((1 << 127) + uint256(x)) >> 128 == uint256(0)) return int128(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int136. Reverts on overflow.
function toInt136(int256 x) internal pure returns (int136) {
unchecked {
if (((1 << 135) + uint256(x)) >> 136 == uint256(0)) return int136(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int144. Reverts on overflow.
function toInt144(int256 x) internal pure returns (int144) {
unchecked {
if (((1 << 143) + uint256(x)) >> 144 == uint256(0)) return int144(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int152. Reverts on overflow.
function toInt152(int256 x) internal pure returns (int152) {
unchecked {
if (((1 << 151) + uint256(x)) >> 152 == uint256(0)) return int152(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int160. Reverts on overflow.
function toInt160(int256 x) internal pure returns (int160) {
unchecked {
if (((1 << 159) + uint256(x)) >> 160 == uint256(0)) return int160(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int168. Reverts on overflow.
function toInt168(int256 x) internal pure returns (int168) {
unchecked {
if (((1 << 167) + uint256(x)) >> 168 == uint256(0)) return int168(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int176. Reverts on overflow.
function toInt176(int256 x) internal pure returns (int176) {
unchecked {
if (((1 << 175) + uint256(x)) >> 176 == uint256(0)) return int176(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int184. Reverts on overflow.
function toInt184(int256 x) internal pure returns (int184) {
unchecked {
if (((1 << 183) + uint256(x)) >> 184 == uint256(0)) return int184(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int192. Reverts on overflow.
function toInt192(int256 x) internal pure returns (int192) {
unchecked {
if (((1 << 191) + uint256(x)) >> 192 == uint256(0)) return int192(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int200. Reverts on overflow.
function toInt200(int256 x) internal pure returns (int200) {
unchecked {
if (((1 << 199) + uint256(x)) >> 200 == uint256(0)) return int200(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int208. Reverts on overflow.
function toInt208(int256 x) internal pure returns (int208) {
unchecked {
if (((1 << 207) + uint256(x)) >> 208 == uint256(0)) return int208(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int216. Reverts on overflow.
function toInt216(int256 x) internal pure returns (int216) {
unchecked {
if (((1 << 215) + uint256(x)) >> 216 == uint256(0)) return int216(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int224. Reverts on overflow.
function toInt224(int256 x) internal pure returns (int224) {
unchecked {
if (((1 << 223) + uint256(x)) >> 224 == uint256(0)) return int224(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int232. Reverts on overflow.
function toInt232(int256 x) internal pure returns (int232) {
unchecked {
if (((1 << 231) + uint256(x)) >> 232 == uint256(0)) return int232(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int240. Reverts on overflow.
function toInt240(int256 x) internal pure returns (int240) {
unchecked {
if (((1 << 239) + uint256(x)) >> 240 == uint256(0)) return int240(x);
_revertOverflow();
}
}
/// @dev Casts `x` to a int248. Reverts on overflow.
function toInt248(int256 x) internal pure returns (int248) {
unchecked {
if (((1 << 247) + uint256(x)) >> 248 == uint256(0)) return int248(x);
_revertOverflow();
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* OTHER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Casts `x` to a int8. Reverts on overflow.
function toInt8(uint256 x) internal pure returns (int8) {
if (x >= 1 << 7) _revertOverflow();
return int8(int256(x));
}
/// @dev Casts `x` to a int16. Reverts on overflow.
function toInt16(uint256 x) internal pure returns (int16) {
if (x >= 1 << 15) _revertOverflow();
return int16(int256(x));
}
/// @dev Casts `x` to a int24. Reverts on overflow.
function toInt24(uint256 x) internal pure returns (int24) {
if (x >= 1 << 23) _revertOverflow();
return int24(int256(x));
}
/// @dev Casts `x` to a int32. Reverts on overflow.
function toInt32(uint256 x) internal pure returns (int32) {
if (x >= 1 << 31) _revertOverflow();
return int32(int256(x));
}
/// @dev Casts `x` to a int40. Reverts on overflow.
function toInt40(uint256 x) internal pure returns (int40) {
if (x >= 1 << 39) _revertOverflow();
return int40(int256(x));
}
/// @dev Casts `x` to a int48. Reverts on overflow.
function toInt48(uint256 x) internal pure returns (int48) {
if (x >= 1 << 47) _revertOverflow();
return int48(int256(x));
}
/// @dev Casts `x` to a int56. Reverts on overflow.
function toInt56(uint256 x) internal pure returns (int56) {
if (x >= 1 << 55) _revertOverflow();
return int56(int256(x));
}
/// @dev Casts `x` to a int64. Reverts on overflow.
function toInt64(uint256 x) internal pure returns (int64) {
if (x >= 1 << 63) _revertOverflow();
return int64(int256(x));
}
/// @dev Casts `x` to a int72. Reverts on overflow.
function toInt72(uint256 x) internal pure returns (int72) {
if (x >= 1 << 71) _revertOverflow();
return int72(int256(x));
}
/// @dev Casts `x` to a int80. Reverts on overflow.
function toInt80(uint256 x) internal pure returns (int80) {
if (x >= 1 << 79) _revertOverflow();
return int80(int256(x));
}
/// @dev Casts `x` to a int88. Reverts on overflow.
function toInt88(uint256 x) internal pure returns (int88) {
if (x >= 1 << 87) _revertOverflow();
return int88(int256(x));
}
/// @dev Casts `x` to a int96. Reverts on overflow.
function toInt96(uint256 x) internal pure returns (int96) {
if (x >= 1 << 95) _revertOverflow();
return int96(int256(x));
}
/// @dev Casts `x` to a int104. Reverts on overflow.
function toInt104(uint256 x) internal pure returns (int104) {
if (x >= 1 << 103) _revertOverflow();
return int104(int256(x));
}
/// @dev Casts `x` to a int112. Reverts on overflow.
function toInt112(uint256 x) internal pure returns (int112) {
if (x >= 1 << 111) _revertOverflow();
return int112(int256(x));
}
/// @dev Casts `x` to a int120. Reverts on overflow.
function toInt120(uint256 x) internal pure returns (int120) {
if (x >= 1 << 119) _revertOverflow();
return int120(int256(x));
}
/// @dev Casts `x` to a int128. Reverts on overflow.
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) _revertOverflow();
return int128(int256(x));
}
/// @dev Casts `x` to a int136. Reverts on overflow.
function toInt136(uint256 x) internal pure returns (int136) {
if (x >= 1 << 135) _revertOverflow();
return int136(int256(x));
}
/// @dev Casts `x` to a int144. Reverts on overflow.
function toInt144(uint256 x) internal pure returns (int144) {
if (x >= 1 << 143) _revertOverflow();
return int144(int256(x));
}
/// @dev Casts `x` to a int152. Reverts on overflow.
function toInt152(uint256 x) internal pure returns (int152) {
if (x >= 1 << 151) _revertOverflow();
return int152(int256(x));
}
/// @dev Casts `x` to a int160. Reverts on overflow.
function toInt160(uint256 x) internal pure returns (int160) {
if (x >= 1 << 159) _revertOverflow();
return int160(int256(x));
}
/// @dev Casts `x` to a int168. Reverts on overflow.
function toInt168(uint256 x) internal pure returns (int168) {
if (x >= 1 << 167) _revertOverflow();
return int168(int256(x));
}
/// @dev Casts `x` to a int176. Reverts on overflow.
function toInt176(uint256 x) internal pure returns (int176) {
if (x >= 1 << 175) _revertOverflow();
return int176(int256(x));
}
/// @dev Casts `x` to a int184. Reverts on overflow.
function toInt184(uint256 x) internal pure returns (int184) {
if (x >= 1 << 183) _revertOverflow();
return int184(int256(x));
}
/// @dev Casts `x` to a int192. Reverts on overflow.
function toInt192(uint256 x) internal pure returns (int192) {
if (x >= 1 << 191) _revertOverflow();
return int192(int256(x));
}
/// @dev Casts `x` to a int200. Reverts on overflow.
function toInt200(uint256 x) internal pure returns (int200) {
if (x >= 1 << 199) _revertOverflow();
return int200(int256(x));
}
/// @dev Casts `x` to a int208. Reverts on overflow.
function toInt208(uint256 x) internal pure returns (int208) {
if (x >= 1 << 207) _revertOverflow();
return int208(int256(x));
}
/// @dev Casts `x` to a int216. Reverts on overflow.
function toInt216(uint256 x) internal pure returns (int216) {
if (x >= 1 << 215) _revertOverflow();
return int216(int256(x));
}
/// @dev Casts `x` to a int224. Reverts on overflow.
function toInt224(uint256 x) internal pure returns (int224) {
if (x >= 1 << 223) _revertOverflow();
return int224(int256(x));
}
/// @dev Casts `x` to a int232. Reverts on overflow.
function toInt232(uint256 x) internal pure returns (int232) {
if (x >= 1 << 231) _revertOverflow();
return int232(int256(x));
}
/// @dev Casts `x` to a int240. Reverts on overflow.
function toInt240(uint256 x) internal pure returns (int240) {
if (x >= 1 << 239) _revertOverflow();
return int240(int256(x));
}
/// @dev Casts `x` to a int248. Reverts on overflow.
function toInt248(uint256 x) internal pure returns (int248) {
if (x >= 1 << 247) _revertOverflow();
return int248(int256(x));
}
/// @dev Casts `x` to a int256. Reverts on overflow.
function toInt256(uint256 x) internal pure returns (int256) {
if (int256(x) >= 0) return int256(x);
_revertOverflow();
}
/// @dev Casts `x` to a uint256. Reverts on overflow.
function toUint256(int256 x) internal pure returns (uint256) {
if (x >= 0) return uint256(x);
_revertOverflow();
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
function _revertOverflow() private pure {
/// @solidity memory-safe-assembly
assembly {
// Store the function selector of `Overflow()`.
mstore(0x00, 0x35278d12)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error ExpOverflow();
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error FactorialOverflow();
/// @dev The operation failed, due to an overflow.
error RPowOverflow();
/// @dev The mantissa is too big to fit.
error MantissaOverflow();
/// @dev The operation failed, due to an multiplication overflow.
error MulWadFailed();
/// @dev The operation failed, due to an multiplication overflow.
error SMulWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error DivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error SDivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error MulDivFailed();
/// @dev The division failed, as the denominator is zero.
error DivFailed();
/// @dev The full precision multiply-divide operation failed, either due
/// to the result being larger than 256 bits, or a division by a zero.
error FullMulDivFailed();
/// @dev The output is undefined, as the input is less-than-or-equal to zero.
error LnWadUndefined();
/// @dev The input outside the acceptable domain.
error OutOfDomain();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The scalar of ETH and most ERC20s.
uint256 internal constant WAD = 1e18;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIMPLIFIED FIXED POINT OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if gt(x, div(not(0), y)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up.
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if iszero(eq(div(z, y), x)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := add(iszero(iszero(mod(z, WAD))), div(z, WAD))
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, WAD)
// Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
if iszero(mul(y, eq(sdiv(z, WAD), x))) {
mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up.
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `x` to the power of `y`.
/// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
/// Note: This function is an approximation.
function powWad(int256 x, int256 y) internal pure returns (int256) {
// Using `ln(x)` means `x` must be greater than 0.
return expWad((lnWad(x) * y) / int256(WAD));
}
/// @dev Returns `exp(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function expWad(int256 x) internal pure returns (int256 r) {
unchecked {
// When the result is less than 0.5 we return zero.
// This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
if (x <= -41446531673892822313) return r;
/// @solidity memory-safe-assembly
assembly {
// When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
// an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
if iszero(slt(x, 135305999368893231589)) {
mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
revert(0x1c, 0x04)
}
}
// `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
// for more intermediate precision and a binary basis. This base conversion
// is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
x = (x << 78) / 5 ** 18;
// Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
// of two such that exp(x) = exp(x') * 2**k, where k is an integer.
// Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
x = x - k * 54916777467707473351141471128;
// `k` is in the range `[-61, 195]`.
// Evaluate using a (6, 7)-term rational approximation.
// `p` is made monic, we'll multiply by a scale factor later.
int256 y = x + 1346386616545796478920950773328;
y = ((y * x) >> 96) + 57155421227552351082224309758442;
int256 p = y + x - 94201549194550492254356042504812;
p = ((p * y) >> 96) + 28719021644029726153956944680412240;
p = p * x + (4385272521454847904659076985693276 << 96);
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
int256 q = x - 2855989394907223263936484059900;
q = ((q * x) >> 96) + 50020603652535783019961831881945;
q = ((q * x) >> 96) - 533845033583426703283633433725380;
q = ((q * x) >> 96) + 3604857256930695427073651918091429;
q = ((q * x) >> 96) - 14423608567350463180887372962807573;
q = ((q * x) >> 96) + 26449188498355588339934803723976023;
/// @solidity memory-safe-assembly
assembly {
// Div in assembly because solidity adds a zero check despite the unchecked.
// The q polynomial won't have zeros in the domain as all its roots are complex.
// No scaling is necessary because p is already `2**96` too large.
r := sdiv(p, q)
}
// r should be in the range `(0.09, 0.25) * 2**96`.
// We now need to multiply r by:
// - The scale factor `s ≈ 6.031367120`.
// - The `2**k` factor from the range reduction.
// - The `1e18 / 2**96` factor for base conversion.
// We do this all at once, with an intermediate result in `2**213`
// basis, so the final right shift is always by a positive amount.
r = int256(
(uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
);
}
}
/// @dev Returns `ln(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function lnWad(int256 x) internal pure returns (int256 r) {
/// @solidity memory-safe-assembly
assembly {
// We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
// We do this by multiplying by `2**96 / 10**18`. But since
// `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
// and add `ln(2**96 / 10**18)` at the end.
// Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// We place the check here for more optimal stack operations.
if iszero(sgt(x, 0)) {
mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
revert(0x1c, 0x04)
}
// forgefmt: disable-next-item
r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
// Reduce range of x to (1, 2) * 2**96
// ln(2^k * x) = k * ln(2) + ln(x)
x := shr(159, shl(r, x))
// Evaluate using a (8, 8)-term rational approximation.
// `p` is made monic, we will multiply by a scale factor later.
// forgefmt: disable-next-item
let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
sar(96, mul(add(43456485725739037958740375743393,
sar(96, mul(add(24828157081833163892658089445524,
sar(96, mul(add(3273285459638523848632254066296,
x), x))), x))), x)), 11111509109440967052023855526967)
p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
// `q` is monic by convention.
let q := add(5573035233440673466300451813936, x)
q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
q := add(909429971244387300277376558375, sar(96, mul(x, q)))
// `p / q` is in the range `(0, 0.125) * 2**96`.
// Finalization, we need to:
// - Multiply by the scale factor `s = 5.549…`.
// - Add `ln(2**96 / 10**18)`.
// - Add `k * ln(2)`.
// - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
// The q polynomial is known not to have zeros in the domain.
// No scaling required because p is already `2**96` too large.
p := sdiv(p, q)
// Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
p := mul(1677202110996718588342820967067443963516166, p)
// Add `ln(2) * k * 5**18 * 2**192`.
// forgefmt: disable-next-item
p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
// Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
// Base conversion: mul `2**18 / 2**192`.
r := sar(174, p)
}
}
/// @dev Returns `W_0(x)`, denominated in `WAD`.
/// See: https://en.wikipedia.org/wiki/Lambert_W_function
/// a.k.a. Product log function. This is an approximation of the principal branch.
/// Note: This function is an approximation. Monotonically increasing.
function lambertW0Wad(int256 x) internal pure returns (int256 w) {
// forgefmt: disable-next-item
unchecked {
if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
(int256 wad, int256 p) = (int256(WAD), x);
uint256 c; // Whether we need to avoid catastrophic cancellation.
uint256 i = 4; // Number of iterations.
if (w <= 0x1ffffffffffff) {
if (-0x4000000000000 <= w) {
i = 1; // Inputs near zero only take one step to converge.
} else if (w <= -0x3ffffffffffffff) {
i = 32; // Inputs near `-1/e` take very long to converge.
}
} else if (uint256(w >> 63) == uint256(0)) {
/// @solidity memory-safe-assembly
assembly {
// Inline log2 for more performance, since the range is small.
let v := shr(49, w)
let l := shl(3, lt(0xff, v))
l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
c := gt(l, 60)
i := add(2, add(gt(l, 53), c))
}
} else {
int256 ll = lnWad(w = lnWad(w));
/// @solidity memory-safe-assembly
assembly {
// `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
i := add(3, iszero(shr(68, x)))
c := iszero(shr(143, x))
}
if (c == uint256(0)) {
do { // If `x` is big, use Newton's so that intermediate values won't overflow.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := mul(w, div(e, wad))
w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
}
if (p <= w) break;
p = w;
} while (--i != uint256(0));
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
return w;
}
}
do { // Otherwise, use Halley's for faster convergence.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := add(w, wad)
let s := sub(mul(w, e), mul(x, wad))
w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
}
if (p <= w) break;
p = w;
} while (--i != c);
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
// For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
// R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
if (c == uint256(0)) return w;
int256 t = w | 1;
/// @solidity memory-safe-assembly
assembly {
x := sdiv(mul(x, wad), t)
}
x = (t * (wad + lnWad(x)));
/// @solidity memory-safe-assembly
assembly {
w := sdiv(x, add(wad, t))
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* GENERAL NUMBER UTILITIES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `a * b == x * y`, with full precision.
function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0))))
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// 512-bit multiply `[p1 p0] = x * y`.
// Compute the product mod `2**256` and mod `2**256 - 1`
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that `product = p1 * 2**256 + p0`.
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`.
for {} 1 {} {
// If overflows.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
/*------------------- 512 by 256 division --------------------*/
// Make division exact by subtracting the remainder from `[p1 p0]`.
let r := mulmod(x, y, d) // Compute remainder using mulmod.
let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
// Make sure `z` is less than `2**256`. Also prevents `d == 0`.
// Placing the check here seems to give more optimal stack operations.
if iszero(gt(d, p1)) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
d := div(d, t) // Divide `d` by `t`, which is a power of two.
// Invert `d mod 2**256`
// Now that `d` is an odd number, it has an inverse
// modulo `2**256` such that `d * inv = 1 mod 2**256`.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, `d * inv = 1 mod 2**4`.
let inv := xor(2, mul(3, d))
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
z :=
mul(
// Divide [p1 p0] by the factors of two.
// Shift in bits from `p1` into `p0`. For this we need
// to flip `t` such that it is `2**256 / t`.
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
)
break
}
z := div(z, d)
break
}
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
/// Performs the full 512 bit calculation regardless.
function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z)))
let t := and(d, sub(0, d))
let r := mulmod(x, y, d)
d := div(d, t)
let inv := xor(2, mul(3, d))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
z :=
mul(
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv)
)
}
}
/// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Uniswap-v3-core under MIT license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
z = fullMulDiv(x, y, d);
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, d) {
z := add(z, 1)
if iszero(z) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Calculates `floor(x * y / 2 ** n)` with full precision.
/// Throws if result overflows a uint256.
/// Credit to Philogy under MIT license:
/// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
for {} 1 {} {
if iszero(or(iszero(x), eq(div(z, x), y))) {
let k := and(n, 0xff) // `n`, cleaned.
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
// | p1 | z |
// Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 |
// Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 |
// Check that final `z` doesn't overflow by checking that p1_0 = 0.
if iszero(shr(k, p1)) {
z := add(shl(sub(256, k), p1), shr(k, z))
break
}
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
z := shr(and(n, 0xff), z)
break
}
}
}
/// @dev Returns `floor(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := div(z, d)
}
}
/// @dev Returns `ceil(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(z, d))), div(z, d))
}
}
/// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`.
function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) {
/// @solidity memory-safe-assembly
assembly {
let g := n
let r := mod(a, n)
for { let y := 1 } 1 {} {
let q := div(g, r)
let t := g
g := r
r := sub(t, mul(r, q))
let u := x
x := y
y := sub(u, mul(y, q))
if iszero(r) { break }
}
x := mul(eq(g, 1), add(x, mul(slt(x, 0), n)))
}
}
/// @dev Returns `ceil(x / d)`.
/// Reverts if `d` is zero.
function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
if iszero(d) {
mstore(0x00, 0x65244e4e) // `DivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(x, d))), div(x, d))
}
}
/// @dev Returns `max(0, x - y)`. Alias for `saturatingSub`.
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `max(0, x - y)`.
function saturatingSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x + y)`.
function saturatingAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(0, lt(add(x, y), x)), add(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x * y)`.
function saturatingMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(or(iszero(x), eq(div(mul(x, y), x), y)), 1), mul(x, y))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `x != 0 ? x : y`, without branching.
function coalesce(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != bytes32(0) ? x : y`, without branching.
function coalesce(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != address(0) ? x : y`, without branching.
function coalesce(address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(shl(96, x))))
}
}
/// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
/// Reverts if the computation overflows.
function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
if x {
z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
let half := shr(1, b) // Divide `b` by 2.
// Divide `y` by 2 every iteration.
for { y := shr(1, y) } y { y := shr(1, y) } {
let xx := mul(x, x) // Store x squared.
let xxRound := add(xx, half) // Round to the nearest number.
// Revert if `xx + half` overflowed, or if `x ** 2` overflows.
if or(lt(xxRound, xx), shr(128, x)) {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
x := div(xxRound, b) // Set `x` to scaled `xxRound`.
// If `y` is odd:
if and(y, 1) {
let zx := mul(z, x) // Compute `z * x`.
let zxRound := add(zx, half) // Round to the nearest number.
// If `z * x` overflowed or `zx + half` overflowed:
if or(xor(div(zx, x), z), lt(zxRound, zx)) {
// Revert if `x` is non-zero.
if x {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
}
z := div(zxRound, b) // Return properly scaled `zxRound`.
}
}
}
}
}
/// @dev Returns the square root of `x`, rounded down.
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
// but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffffff, shr(r, x))))
z := shl(shr(1, r), z)
// Goal was to get `z*z*y` within a small factor of `x`. More iterations could
// get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
// We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
// That's not possible if `x < 256` but we can just verify those cases exhaustively.
// Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
// Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
// Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
// For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
// is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
// with largest error when `s = 1` and when `s = 256` or `1/256`.
// Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
// Then we can estimate `sqrt(y)` using
// `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
// There is no overflow risk here since `y < 2**136` after the first branch above.
z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If `x+1` is a perfect square, the Babylonian method cycles between
// `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
z := sub(z, lt(div(x, z), z))
}
}
/// @dev Returns the cube root of `x`, rounded down.
/// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
/// https://github.com/pcaversaccio/snekmate/blob/main/src/snekmate/utils/math.vy
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// Makeshift lookup table to nudge the approximate log2 result.
z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
// Newton-Raphson's.
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
// Round down.
z := sub(z, lt(div(x, mul(z, z)), z))
}
}
/// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
function sqrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
z = (1 + sqrt(x)) * 10 ** 9;
z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
}
/// @solidity memory-safe-assembly
assembly {
z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
}
}
/// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
z = (1 + cbrt(x)) * 10 ** 12;
z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
}
/// @solidity memory-safe-assembly
assembly {
let p := x
for {} 1 {} {
if iszero(shr(229, p)) {
if iszero(shr(199, p)) {
p := mul(p, 100000000000000000) // 10 ** 17.
break
}
p := mul(p, 100000000) // 10 ** 8.
break
}
if iszero(shr(249, p)) { p := mul(p, 100) }
break
}
let t := mulmod(mul(z, z), z, p)
z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
}
}
/// @dev Returns the factorial of `x`.
function factorial(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := 1
if iszero(lt(x, 58)) {
mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
revert(0x1c, 0x04)
}
for {} x { x := sub(x, 1) } { z := mul(z, x) }
}
}
/// @dev Returns the log2 of `x`.
/// Equivalent to computing the index of the most significant bit (MSB) of `x`.
/// Returns 0 if `x` is zero.
function log2(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000))
}
}
/// @dev Returns the log2 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log2Up(uint256 x) internal pure returns (uint256 r) {
r = log2(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(r, 1), x))
}
}
/// @dev Returns the log10 of `x`.
/// Returns 0 if `x` is zero.
function log10(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(x, 100000000000000000000000000000000000000)) {
x := div(x, 100000000000000000000000000000000000000)
r := 38
}
if iszero(lt(x, 100000000000000000000)) {
x := div(x, 100000000000000000000)
r := add(r, 20)
}
if iszero(lt(x, 10000000000)) {
x := div(x, 10000000000)
r := add(r, 10)
}
if iszero(lt(x, 100000)) {
x := div(x, 100000)
r := add(r, 5)
}
r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
}
}
/// @dev Returns the log10 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log10Up(uint256 x) internal pure returns (uint256 r) {
r = log10(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(exp(10, r), x))
}
}
/// @dev Returns the log256 of `x`.
/// Returns 0 if `x` is zero.
function log256(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(shr(3, r), lt(0xff, shr(r, x)))
}
}
/// @dev Returns the log256 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log256Up(uint256 x) internal pure returns (uint256 r) {
r = log256(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(shl(3, r), 1), x))
}
}
/// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
/// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
/// @solidity memory-safe-assembly
assembly {
mantissa := x
if mantissa {
if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
mantissa := div(mantissa, 1000000000000000000000000000000000)
exponent := 33
}
if iszero(mod(mantissa, 10000000000000000000)) {
mantissa := div(mantissa, 10000000000000000000)
exponent := add(exponent, 19)
}
if iszero(mod(mantissa, 1000000000000)) {
mantissa := div(mantissa, 1000000000000)
exponent := add(exponent, 12)
}
if iszero(mod(mantissa, 1000000)) {
mantissa := div(mantissa, 1000000)
exponent := add(exponent, 6)
}
if iszero(mod(mantissa, 10000)) {
mantissa := div(mantissa, 10000)
exponent := add(exponent, 4)
}
if iszero(mod(mantissa, 100)) {
mantissa := div(mantissa, 100)
exponent := add(exponent, 2)
}
if iszero(mod(mantissa, 10)) {
mantissa := div(mantissa, 10)
exponent := add(exponent, 1)
}
}
}
}
/// @dev Convenience function for packing `x` into a smaller number using `sci`.
/// The `mantissa` will be in bits [7..255] (the upper 249 bits).
/// The `exponent` will be in bits [0..6] (the lower 7 bits).
/// Use `SafeCastLib` to safely ensure that the `packed` number is small
/// enough to fit in the desired unsigned integer type:
/// ```
/// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
/// ```
function packSci(uint256 x) internal pure returns (uint256 packed) {
(x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
/// @solidity memory-safe-assembly
assembly {
if shr(249, x) {
mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
revert(0x1c, 0x04)
}
packed := or(shl(7, x), packed)
}
}
/// @dev Convenience function for unpacking a packed number from `packSci`.
function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
unchecked {
unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards zero.
function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = (x & y) + ((x ^ y) >> 1);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
function avg(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
/// @dev Returns the absolute value of `x`.
function abs(int256 x) internal pure returns (uint256 z) {
unchecked {
z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y))
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(int256 x, int256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), slt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), gt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), sgt(y, x)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(uint256 x, uint256 minValue, uint256 maxValue)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
}
}
/// @dev Returns greatest common divisor of `x` and `y`.
function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
for { z := x } y {} {
let t := y
y := mod(z, y)
z := t
}
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
internal
pure
returns (uint256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
unchecked {
if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
return a - fullMulDiv(a - b, t - begin, end - begin);
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
internal
pure
returns (int256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
// forgefmt: disable-next-item
unchecked {
if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
uint256(t - begin), uint256(end - begin)));
return int256(uint256(a) - fullMulDiv(uint256(a - b),
uint256(t - begin), uint256(end - begin)));
}
}
/// @dev Returns if `x` is an even number. Some people may need this.
function isEven(uint256 x) internal pure returns (bool) {
return x & uint256(1) == uint256(0);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RAW NUMBER OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(x, y)
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mod(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := smod(x, y)
}
}
/// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := addmod(x, y, d)
}
}
/// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mulmod(x, y, d)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {SafeCastLib} from "solady/utils/SafeCastLib.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import "../base/Constants.sol";
using FixedPointMathLib for int256;
using FixedPointMathLib for uint256;
/// @dev modified from solady
function dist(uint256 x, uint256 y) pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(mul(xor(sub(y, x), sub(x, y)), gt(x, y)), sub(y, x))
}
}
/// @dev modified from solady
function absDiff(uint256 x, uint256 y) pure returns (bool positive, uint256 diff) {
/// @solidity memory-safe-assembly
assembly {
positive := gt(x, y)
diff := xor(mul(xor(sub(y, x), sub(x, y)), gt(x, y)), sub(y, x))
}
}
function roundTick(int24 currentTick, int24 tickSpacing) pure returns (int24 roundedTick, int24 nextRoundedTick) {
int24 compressed = currentTick / tickSpacing;
if (currentTick < 0 && currentTick % tickSpacing != 0) compressed--; // round towards negative infinity
roundedTick = compressed * tickSpacing;
nextRoundedTick = roundedTick + tickSpacing;
}
function roundTickSingle(int24 currentTick, int24 tickSpacing) pure returns (int24 roundedTick) {
int24 compressed = currentTick / tickSpacing;
if (currentTick < 0 && currentTick % tickSpacing != 0) compressed--; // round towards negative infinity
roundedTick = compressed * tickSpacing;
}
function boundTick(int24 tick, int24 tickSpacing) pure returns (int24 boundedTick) {
(int24 minTick, int24 maxTick) = (TickMath.minUsableTick(tickSpacing), TickMath.maxUsableTick(tickSpacing));
return int24(FixedPointMathLib.clamp(tick, minTick, maxTick));
}
function weightedSum(uint256 value0, uint256 weight0, uint256 value1, uint256 weight1) pure returns (uint256) {
return (value0 * weight0 + value1 * weight1) / (weight0 + weight1);
}
/// @dev Converts xWad, the decimal index of a rounded tick scaled by WAD, to the corresponding rounded tick.
function xWadToRoundedTick(int256 xWad, int24 mu, int24 tickSpacing, bool roundUp) pure returns (int24) {
int24 x = SafeCastLib.toInt24(xWad / int256(WAD));
if (roundUp) {
if (xWad > 0 && xWad % int256(WAD) != 0) x++; // round towards positive infinity
} else {
if (xWad < 0 && xWad % int256(WAD) != 0) x--; // round towards negative infinity
}
return x * tickSpacing + mu;
}
function percentDelta(uint256 a, uint256 b) pure returns (uint256) {
uint256 absDelta = dist(a, b);
return FixedPointMathLib.divWad(absDelta, b);
}
/// @dev Returns ReLU(x - y) = max(x - y, 0)
function subReLU(uint256 x, uint256 y) pure returns (uint256) {
unchecked {
return x > y ? x - y : 0;
}
}
function divQ96RoundUp(uint256 value) pure returns (uint256) {
return (value + ((1 << 96) - 1)) >> 96;
}
function roundUpFullMulDivResult(uint256 x, uint256 y, uint256 d, uint256 resultRoundedDown)
pure
returns (uint256 result)
{
result = resultRoundedDown;
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, d) {
result := add(resultRoundedDown, 1)
if iszero(result) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; pragma abicoder v2; error BunniHub__Paused(); error BunniHub__ZeroInput(); error BunniHub__PastDeadline(); error BunniHub__Unauthorized(); error BunniHub__LDFCannotBeZero(); error BunniHub__MaxNonceReached(); error BunniHub__SlippageTooHigh(); error BunniHub__WithdrawalPaused(); error BunniHub__HookCannotBeZero(); error BunniHub__ZeroSharesMinted(); error BunniHub__InvalidLDFParams(); error BunniHub__InvalidHookParams(); error BunniHub__VaultFeeIncorrect(); error BunniHub__VaultAssetMismatch(); error BunniHub__GracePeriodExpired(); error BunniHub__HookNotWhitelisted(); error BunniHub__NoExpiredWithdrawal(); error BunniHub__MsgValueInsufficient(); error BunniHub__DepositAmountTooSmall(); error BunniHub__VaultDecimalsTooSmall(); error BunniHub__QueuedWithdrawalNotReady(); error BunniHub__BunniTokenNotInitialized(); error BunniHub__NeedToUseQueuedWithdrawal(); error BunniHub__InvalidRawTokenRatioBounds(); error BunniHub__VaultTookMoreThanRequested(); error BunniHub__QueuedWithdrawalNonexistent(); error BunniHub__MsgValueNotZeroWhenPoolKeyHasNoNativeToken(); error BunniToken__NotBunniHub(); error BunniToken__NotPoolManager(); error BunniHook__InvalidK(); error BunniHook__InvalidSwap(); error BunniHook__Unauthorized(); error BunniHook__InvalidModifier(); error BunniHook__InvalidActiveBlock(); error BunniHook__InsufficientOutput(); error BunniHook__HookFeeRecipientNotSet(); error BunniHook__InvalidRebalanceOrderHash(); error BunniHook__HookFeeRecipientAlreadySet(); error BunniHook__PrehookPostConditionFailed(); error BunniHook__RequestedOutputExceedsBalance(); error BunniSwapMath__SwapFailed();
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; pragma abicoder v2; uint256 constant WAD = 1e18; uint256 constant Q96 = 0x1000000000000000000000000; uint256 constant MAX_NONCE = 1e6; uint256 constant MIN_INITIAL_SHARES = 1e12; uint256 constant MAX_SWAP_FEE_RATIO = 2.88e20; // max ratio that avoids overflow in swap fee calculation, roughly sqrt(SWAP_FEE_BASE) * sqrt(sqrt((type(uint256).max - SWAP_FEE_BASE) / type(uint24).max) - 1) uint256 constant SWAP_FEE_BASE = 1e6; uint256 constant SWAP_FEE_BASE_SQUARED = 1e12; uint256 constant RAW_TOKEN_RATIO_BASE = 1e6; uint256 constant LN2_WAD = 693147180559945309; uint256 constant MAX_VAULT_FEE_ERROR = 1e6; uint256 constant MAX_CARDINALITY = 2 ** 24 - 1; uint56 constant WITHDRAW_DELAY = 1 minutes; uint56 constant WITHDRAW_GRACE_PERIOD = 3 minutes; uint256 constant REFERRAL_REWARD_PER_TOKEN_PRECISION = 1e30; uint256 constant MODIFIER_BASE = 1e6; uint256 constant MIN_DEPOSIT_BALANCE_INCREASE = 1e6; uint24 constant MAX_AMAMM_FEE = 0.1e6; uint256 constant REBALANCE_MAX_SLIPPAGE_BASE = 1e5; uint16 constant MAX_SURGE_HALFLIFE = 1 hours; uint16 constant MAX_SURGE_AUTOSTART_TIME = 1 hours; uint16 constant MAX_REBALANCE_MAX_SLIPPAGE = 0.25e5; // max value for rebalanceMaxSlippage is 25% uint16 constant MAX_REBALANCE_TWAP_SECONDS_AGO = 3 hours; uint16 constant MAX_REBALANCE_ORDER_TTL = 1 hours;
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import {subReLU} from "../lib/Math.sol";
type IdleBalance is bytes32;
using {equals as ==, notEqual as !=} for IdleBalance global;
using IdleBalanceLibrary for IdleBalance global;
function equals(IdleBalance bal, IdleBalance other) pure returns (bool) {
return IdleBalance.unwrap(bal) == IdleBalance.unwrap(other);
}
function notEqual(IdleBalance bal, IdleBalance other) pure returns (bool) {
return IdleBalance.unwrap(bal) != IdleBalance.unwrap(other);
}
library IdleBalanceLibrary {
using FixedPointMathLib for uint256;
using IdleBalanceLibrary for uint256;
uint256 private constant _BALANCE_MASK = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/// @dev Set isToken0 to true in ZERO to keep storage slots dirty
IdleBalance internal constant ZERO =
IdleBalance.wrap(bytes32(0x8000000000000000000000000000000000000000000000000000000000000000));
error IdleBalanceLibrary__BalanceOverflow();
function fromIdleBalance(IdleBalance idleBalance) internal pure returns (uint256 rawBalance, bool isToken0) {
uint256 mask = _BALANCE_MASK;
assembly ("memory-safe") {
isToken0 := shr(255, idleBalance)
rawBalance := and(mask, idleBalance)
}
}
function toIdleBalance(uint256 rawBalance, bool isToken0) internal pure returns (IdleBalance) {
// revert if balance overflows 255 bits
if (rawBalance > _BALANCE_MASK) revert IdleBalanceLibrary__BalanceOverflow();
// pack isToken0 and balance into a single uint256
bytes32 packed;
assembly ("memory-safe") {
packed := or(shl(255, isToken0), rawBalance)
}
return IdleBalance.wrap(packed);
}
function computeIdleBalance(uint256 activeBalance0, uint256 activeBalance1, uint256 balance0, uint256 balance1)
internal
pure
returns (IdleBalance)
{
(uint256 extraBalance0, uint256 extraBalance1) =
(subReLU(balance0, activeBalance0), subReLU(balance1, activeBalance1));
(uint256 extraBalanceProportion0, uint256 extraBalanceProportion1) =
(balance0 == 0 ? 0 : extraBalance0.divWad(balance0), balance1 == 0 ? 0 : extraBalance1.divWad(balance1));
bool isToken0 = extraBalanceProportion0 >= extraBalanceProportion1;
return (isToken0 ? extraBalance0 : extraBalance1).toIdleBalance(isToken0);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import {subReLU} from "./Math.sol";
import {SqrtPriceMath} from "./SqrtPriceMath.sol";
/// @title Computes the result of a swap within ticks
/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.
library SwapMath {
uint24 internal constant MAX_SWAP_FEE = 1e6;
/// @dev A minimum fee amount is applied to protect against exact input vs exact output rate mismatches when swap amounts/liquidity are small.
uint256 internal constant MIN_FEE_AMOUNT = 1e3;
/// @notice Computes the sqrt price target for the next swap step
/// @param zeroForOne The direction of the swap, true for currency0 to currency1, false for currency1 to currency0
/// @param sqrtPriceNextX96 The Q64.96 sqrt price for the next initialized tick
/// @param sqrtPriceLimitX96 The 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
/// @return sqrtPriceTargetX96 The price target for the next swap step
function getSqrtPriceTarget(bool zeroForOne, uint160 sqrtPriceNextX96, uint160 sqrtPriceLimitX96)
internal
pure
returns (uint160 sqrtPriceTargetX96)
{
assembly ("memory-safe") {
// a flag to toggle between sqrtPriceNextX96 and sqrtPriceLimitX96
// when zeroForOne == true, nextOrLimit reduces to sqrtPriceNextX96 >= sqrtPriceLimitX96
// sqrtPriceTargetX96 = max(sqrtPriceNextX96, sqrtPriceLimitX96)
// when zeroForOne == false, nextOrLimit reduces to sqrtPriceNextX96 < sqrtPriceLimitX96
// sqrtPriceTargetX96 = min(sqrtPriceNextX96, sqrtPriceLimitX96)
sqrtPriceNextX96 := and(sqrtPriceNextX96, 0xffffffffffffffffffffffffffffffffffffffff)
sqrtPriceLimitX96 := and(sqrtPriceLimitX96, 0xffffffffffffffffffffffffffffffffffffffff)
let nextOrLimit := xor(lt(sqrtPriceNextX96, sqrtPriceLimitX96), and(zeroForOne, 0x1))
let symDiff := xor(sqrtPriceNextX96, sqrtPriceLimitX96)
sqrtPriceTargetX96 := xor(sqrtPriceLimitX96, mul(symDiff, nextOrLimit))
}
}
/// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap
/// @dev If the swap's amountSpecified is negative, the combined fee and input amount will never exceed the absolute value of the remaining amount.
/// @param sqrtPriceCurrentX96 The current sqrt price of the pool
/// @param sqrtPriceTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred
/// @param liquidity The usable liquidity
/// @param amountRemaining How much input or output amount is remaining to be swapped in/out
/// @param feePips The fee taken from the input amount, expressed in hundredths of a bip
/// @return sqrtPriceNextX96 The price after swapping the amount in/out, not to exceed the price target
/// @return amountIn The amount to be swapped in, of either currency0 or currency1, based on the direction of the swap
/// @return amountOut The amount to be received, of either currency0 or currency1, based on the direction of the swap
/// @dev 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,
uint256 liquidity,
int256 amountRemaining,
uint24 feePips
) internal pure returns (uint160 sqrtPriceNextX96, uint256 amountIn, uint256 amountOut) {
bool exactIn = amountRemaining < 0;
uint256 feeAmount;
unchecked {
uint256 _feePips = feePips; // upcast once and cache
bool zeroForOne = sqrtPriceCurrentX96 >= sqrtPriceTargetX96;
if (exactIn) {
uint256 amountRemainingLessFee = FixedPointMathLib.min(
FullMath.mulDiv(uint256(-amountRemaining), MAX_SWAP_FEE - _feePips, MAX_SWAP_FEE),
subReLU(uint256(-amountRemaining), MIN_FEE_AMOUNT)
);
amountIn = zeroForOne
? SqrtPriceMath.getAmount0Delta(sqrtPriceTargetX96, sqrtPriceCurrentX96, liquidity, true)
: SqrtPriceMath.getAmount1Delta(sqrtPriceCurrentX96, sqrtPriceTargetX96, liquidity, true);
if (amountRemainingLessFee >= amountIn) {
// `amountIn` is capped by the target price
sqrtPriceNextX96 = sqrtPriceTargetX96;
feeAmount = _feePips == MAX_SWAP_FEE
? amountIn // amountIn is always 0 here, as amountRemainingLessFee == 0 and amountRemainingLessFee >= amountIn
: FixedPointMathLib.max(
FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_SWAP_FEE - _feePips), MIN_FEE_AMOUNT
);
} else {
// exhaust the remaining amount
amountIn = amountRemainingLessFee;
sqrtPriceNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(
sqrtPriceCurrentX96, liquidity, amountRemainingLessFee, zeroForOne
);
// we didn't reach the target, so take the remainder of the maximum input as fee
feeAmount = FixedPointMathLib.max(uint256(-amountRemaining) - amountIn, MIN_FEE_AMOUNT);
}
amountOut = zeroForOne
? SqrtPriceMath.getAmount1Delta(sqrtPriceNextX96, sqrtPriceCurrentX96, liquidity, false)
: SqrtPriceMath.getAmount0Delta(sqrtPriceCurrentX96, sqrtPriceNextX96, liquidity, false);
} else {
amountOut = zeroForOne
? SqrtPriceMath.getAmount1Delta(sqrtPriceTargetX96, sqrtPriceCurrentX96, liquidity, false)
: SqrtPriceMath.getAmount0Delta(sqrtPriceCurrentX96, sqrtPriceTargetX96, liquidity, false);
if (uint256(amountRemaining) >= amountOut) {
// `amountOut` is capped by the target price
sqrtPriceNextX96 = sqrtPriceTargetX96;
} else {
// cap the output amount to not exceed the remaining output amount
amountOut = uint256(amountRemaining);
sqrtPriceNextX96 =
SqrtPriceMath.getNextSqrtPriceFromOutput(sqrtPriceCurrentX96, liquidity, amountOut, zeroForOne);
}
amountIn = zeroForOne
? SqrtPriceMath.getAmount0Delta(sqrtPriceNextX96, sqrtPriceCurrentX96, liquidity, true)
: SqrtPriceMath.getAmount1Delta(sqrtPriceCurrentX96, sqrtPriceNextX96, liquidity, true);
// `feePips` cannot be `MAX_SWAP_FEE` for exact out
feeAmount = FixedPointMathLib.max(
FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_SWAP_FEE - _feePips), MIN_FEE_AMOUNT
);
}
}
// add fee back into amountIn
// ensure that amountIn <= |amountRemaining| if exactIn
if (exactIn) amountIn = FixedPointMathLib.min(amountIn + feeAmount, uint256(-amountRemaining));
else amountIn += feeAmount;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import "../types/IdleBalance.sol";
import {Q96} from "../base/Constants.sol";
import {FullMathX96} from "./FullMathX96.sol";
import {LiquidityAmounts} from "./LiquidityAmounts.sol";
import {roundTick, roundUpFullMulDivResult} from "./Math.sol";
import {ILiquidityDensityFunction} from "../interfaces/ILiquidityDensityFunction.sol";
using FullMathX96 for uint256;
using FixedPointMathLib for uint256;
/// @notice Queries the liquidity density function for the given pool and tick
/// @param key The pool key
/// @param sqrtPriceX96 The current sqrt price of the pool
/// @param tick The current tick of the pool
/// @param arithmeticMeanTick The TWAP oracle value
/// @param ldf The liquidity density function
/// @param ldfParams The parameters for the liquidity density function
/// @param ldfState The current state of the liquidity density function
/// @param balance0 The balance of token0 in the pool
/// @param balance1 The balance of token1 in the pool
/// @param idleBalance The idle balance of the pool, which is removed from the corresponding balance0/balance1
/// when computing totalLiquidity.
/// @return totalLiquidity The total liquidity in the pool
/// @return totalDensity0X96 The total density of token0 in the pool, scaled by Q96
/// @return totalDensity1X96 The total density of token1 in the pool, scaled by Q96
/// @return liquidityDensityOfRoundedTickX96 The liquidity density of the rounded tick, scaled by Q96
/// @return activeBalance0 The active balance of token0 in the pool, which is the amount used by swap liquidity
/// @return activeBalance1 The active balance of token1 in the pool, which is the amount used by swap liquidity
/// @return newLdfState The new state of the liquidity density function
/// @return shouldSurge Whether the pool should surge
function queryLDF(
PoolKey memory key,
uint160 sqrtPriceX96,
int24 tick,
int24 arithmeticMeanTick,
ILiquidityDensityFunction ldf,
bytes32 ldfParams,
bytes32 ldfState,
uint256 balance0,
uint256 balance1,
IdleBalance idleBalance
)
view
returns (
uint256 totalLiquidity,
uint256 totalDensity0X96,
uint256 totalDensity1X96,
uint256 liquidityDensityOfRoundedTickX96,
uint256 activeBalance0,
uint256 activeBalance1,
bytes32 newLdfState,
bool shouldSurge
)
{
(int24 roundedTick, int24 nextRoundedTick) = roundTick(tick, key.tickSpacing);
(uint160 roundedTickSqrtRatio, uint160 nextRoundedTickSqrtRatio) =
(TickMath.getSqrtPriceAtTick(roundedTick), TickMath.getSqrtPriceAtTick(nextRoundedTick));
uint256 density0RightOfRoundedTickX96;
uint256 density1LeftOfRoundedTickX96;
(
liquidityDensityOfRoundedTickX96,
density0RightOfRoundedTickX96,
density1LeftOfRoundedTickX96,
newLdfState,
shouldSurge
) = ldf.query(key, roundedTick, arithmeticMeanTick, tick, ldfParams, ldfState);
(uint256 density0OfRoundedTickX96, uint256 density1OfRoundedTickX96) = LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96, roundedTickSqrtRatio, nextRoundedTickSqrtRatio, liquidityDensityOfRoundedTickX96, true
);
totalDensity0X96 = density0RightOfRoundedTickX96 + density0OfRoundedTickX96;
totalDensity1X96 = density1LeftOfRoundedTickX96 + density1OfRoundedTickX96;
// modify balance0/balance1 to deduct the idle balance
// skip this if a surge happens since the idle balance will need to be recalculated
if (!shouldSurge) {
(uint256 balance, bool isToken0) = IdleBalanceLibrary.fromIdleBalance(idleBalance);
if (isToken0) {
balance0 = subReLU(balance0, balance);
} else {
balance1 = subReLU(balance1, balance);
}
}
if (balance0 != 0 || balance1 != 0) {
bool noToken0 = balance0 == 0 || totalDensity0X96 == 0;
bool noToken1 = balance1 == 0 || totalDensity1X96 == 0;
uint256 totalLiquidityEstimate0 = noToken0 ? 0 : balance0.fullMulDiv(Q96, totalDensity0X96);
uint256 totalLiquidityEstimate1 = noToken1 ? 0 : balance1.fullMulDiv(Q96, totalDensity1X96);
bool useLiquidityEstimate0 =
(totalLiquidityEstimate0 < totalLiquidityEstimate1 || totalDensity1X96 == 0) && totalDensity0X96 != 0;
if (useLiquidityEstimate0) {
totalLiquidity =
noToken0 ? 0 : roundUpFullMulDivResult(balance0, Q96, totalDensity0X96, totalLiquidityEstimate0);
(activeBalance0, activeBalance1) = (
noToken0 ? 0 : FixedPointMathLib.min(balance0, totalLiquidityEstimate0.fullMulX96(totalDensity0X96)),
noToken1 ? 0 : FixedPointMathLib.min(balance1, totalLiquidityEstimate0.fullMulX96(totalDensity1X96))
);
} else {
totalLiquidity =
noToken1 ? 0 : roundUpFullMulDivResult(balance1, Q96, totalDensity1X96, totalLiquidityEstimate1);
(activeBalance0, activeBalance1) = (
noToken0 ? 0 : FixedPointMathLib.min(balance0, totalLiquidityEstimate1.fullMulX96(totalDensity0X96)),
noToken1 ? 0 : FixedPointMathLib.min(balance1, totalLiquidityEstimate1.fullMulX96(totalDensity1X96))
);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
library FullMathX96 {
uint256 internal constant Q96 = 0x1000000000000000000000000;
/// @dev Calculates `floor(x * y / 2 ** 96)` with full precision.
/// Throws if result overflows a uint256.
/// Credit to Philogy under MIT license:
/// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
function fullMulX96(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
for {} 1 {} {
if iszero(or(iszero(x), eq(div(z, x), y))) {
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
// | p1 | z |
// Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 |
// Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 |
// Check that final `z` doesn't overflow by checking that p1_0 = 0.
if iszero(shr(96, p1)) {
z := add(shl(160, p1), shr(96, z))
break
}
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
z := shr(96, z)
break
}
}
}
function fullMulX96Up(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = fullMulX96(x, y);
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, Q96) {
z := add(z, 1)
if iszero(z) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {SafeCast} from "@uniswap/v4-core/src/libraries/SafeCast.sol";
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {UnsafeMath} from "@uniswap/v4-core/src/libraries/UnsafeMath.sol";
import {FixedPoint96} from "@uniswap/v4-core/src/libraries/FixedPoint96.sol";
/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
using SafeCast for uint256;
error InvalidPriceOrLiquidity();
error InvalidPrice();
error NotEnoughLiquidity();
error PriceOverflow();
/// @notice Gets the next sqrt price given a delta of currency0
/// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
/// price less in order to not send too much output.
/// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
/// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
/// @param sqrtPX96 The starting price, i.e. before accounting for the currency0 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of currency0 to add or remove from virtual reserves
/// @param add Whether to add or remove the amount of currency0
/// @return The price after adding or removing amount, depending on add
function getNextSqrtPriceFromAmount0RoundingUp(uint160 sqrtPX96, uint256 liquidity, uint256 amount, bool add)
internal
pure
returns (uint160)
{
// we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
if (amount == 0) return sqrtPX96;
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
if (add) {
unchecked {
uint256 product = amount * sqrtPX96;
if (product / amount == sqrtPX96) {
uint256 denominator = numerator1 + product;
if (denominator >= numerator1) {
// always fits in 160 bits
return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
}
}
}
// denominator is checked for overflow
return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96) + amount));
} else {
unchecked {
uint256 product = amount * sqrtPX96;
// if the product overflows, we know the denominator underflows
// in addition, we must check that the denominator does not underflow
// equivalent: if (product / amount != sqrtPX96 || numerator1 <= product) revert PriceOverflow();
assembly ("memory-safe") {
if iszero(
and(
eq(div(product, amount), and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
gt(numerator1, product)
)
) {
mstore(0, 0xf5c787f1) // selector for PriceOverflow()
revert(0x1c, 0x04)
}
}
uint256 denominator = numerator1 - product;
return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
}
}
}
/// @notice Gets the next sqrt price given a delta of currency1
/// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
/// price less in order to not send too much output.
/// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
/// @param sqrtPX96 The starting price, i.e., before accounting for the currency1 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of currency1 to add, or remove, from virtual reserves
/// @param add Whether to add, or remove, the amount of currency1
/// @return The price after adding or removing `amount`
function getNextSqrtPriceFromAmount1RoundingDown(uint160 sqrtPX96, uint256 liquidity, uint256 amount, bool add)
internal
pure
returns (uint160)
{
// if we're adding (subtracting), rounding down requires rounding the quotient down (up)
// in both cases, avoid a mulDiv for most inputs
if (add) {
uint256 quotient = (
amount <= type(uint160).max
? (amount << FixedPoint96.RESOLUTION) / liquidity
: FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
);
return (uint256(sqrtPX96) + quotient).toUint160();
} else {
uint256 quotient = (
amount <= type(uint160).max
? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
: FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
);
// equivalent: if (sqrtPX96 <= quotient) revert NotEnoughLiquidity();
assembly ("memory-safe") {
if iszero(gt(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff), quotient)) {
mstore(0, 0x4323a555) // selector for NotEnoughLiquidity()
revert(0x1c, 0x04)
}
}
// always fits 160 bits
unchecked {
return uint160(sqrtPX96 - quotient);
}
}
}
/// @notice Gets the next sqrt price given an input amount of currency0 or currency1
/// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
/// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
/// @param liquidity The amount of usable liquidity
/// @param amountIn How much of currency0, or currency1, is being swapped in
/// @param zeroForOne Whether the amount in is currency0 or currency1
/// @return uint160 The price after adding the input amount to currency0 or currency1
function getNextSqrtPriceFromInput(uint160 sqrtPX96, uint256 liquidity, uint256 amountIn, bool zeroForOne)
internal
pure
returns (uint160)
{
// equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
assembly ("memory-safe") {
if or(
iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
) {
mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
revert(0x1c, 0x04)
}
}
// round to make sure that we don't pass the target price
return zeroForOne
? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
: getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
}
/// @notice Gets the next sqrt price given an output amount of currency0 or currency1
/// @dev Throws if price or liquidity are 0 or the next price is out of bounds
/// @param sqrtPX96 The starting price before accounting for the output amount
/// @param liquidity The amount of usable liquidity
/// @param amountOut How much of currency0, or currency1, is being swapped out
/// @param zeroForOne Whether the amount out is currency1 or currency0
/// @return uint160 The price after removing the output amount of currency0 or currency1
function getNextSqrtPriceFromOutput(uint160 sqrtPX96, uint256 liquidity, uint256 amountOut, bool zeroForOne)
internal
pure
returns (uint160)
{
// equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
assembly ("memory-safe") {
if or(iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)), iszero(liquidity)) {
mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
revert(0x1c, 0x04)
}
}
// round to make sure that we pass the target price
return zeroForOne
? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
: getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
}
/// @notice Gets the amount0 delta between two prices
/// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
/// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up or down
/// @return uint256 Amount of currency0 required to cover a position of size liquidity between the two passed prices
function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 liquidity, bool roundUp)
internal
pure
returns (uint256)
{
unchecked {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
// equivalent: if (sqrtPriceAX96 == 0) revert InvalidPrice();
assembly ("memory-safe") {
if iszero(and(sqrtPriceAX96, 0xffffffffffffffffffffffffffffffffffffffff)) {
mstore(0, 0x00bfc921) // selector for InvalidPrice()
revert(0x1c, 0x04)
}
}
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
uint256 numerator2 = sqrtPriceBX96 - sqrtPriceAX96;
return roundUp
? UnsafeMath.divRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtPriceBX96), sqrtPriceAX96)
: FullMath.mulDiv(numerator1, numerator2, sqrtPriceBX96) / sqrtPriceAX96;
}
}
/// @notice Equivalent to: `a >= b ? a - b : b - a`
function absDiff(uint160 a, uint160 b) internal pure returns (uint256 res) {
assembly ("memory-safe") {
let diff :=
sub(and(a, 0xffffffffffffffffffffffffffffffffffffffff), and(b, 0xffffffffffffffffffffffffffffffffffffffff))
// mask = 0 if a >= b else -1 (all 1s)
let mask := sar(255, diff)
// if a >= b, res = a - b = 0 ^ (a - b)
// if a < b, res = b - a = ~~(b - a) = ~(-(b - a) - 1) = ~(a - b - 1) = (-1) ^ (a - b - 1)
// either way, res = mask ^ (a - b + mask)
res := xor(mask, add(mask, diff))
}
}
/// @notice Gets the amount1 delta between two prices
/// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up, or down
/// @return amount1 Amount of currency1 required to cover a position of size liquidity between the two passed prices
function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 liquidity, bool roundUp)
internal
pure
returns (uint256 amount1)
{
uint256 numerator = absDiff(sqrtPriceAX96, sqrtPriceBX96);
uint256 denominator = FixedPoint96.Q96;
uint256 _liquidity = uint256(liquidity);
/**
* Equivalent to:
* amount1 = roundUp
* ? FullMath.mulDivRoundingUp(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96)
* : FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);
* Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`.
*/
amount1 = FullMath.mulDiv(_liquidity, numerator, denominator);
assembly ("memory-safe") {
amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), roundUp))
}
}
/// @notice Helper that gets signed currency0 delta
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount0 delta
/// @return int256 Amount of currency0 corresponding to the passed liquidityDelta between the two prices
function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
internal
pure
returns (int256)
{
unchecked {
return liquidity < 0
? getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
: -getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
}
}
/// @notice Helper that gets signed currency1 delta
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount1 delta
/// @return int256 Amount of currency1 corresponding to the passed liquidityDelta between the two prices
function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
internal
pure
returns (int256)
{
unchecked {
return liquidity < 0
? getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
: -getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
}
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "./SqrtPriceMath.sol";
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 liquidity,
bool roundingUp
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = SqrtPriceMath.getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundingUp);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = SqrtPriceMath.getAmount0Delta(sqrtRatioX96, sqrtRatioBX96, liquidity, roundingUp);
amount1 = SqrtPriceMath.getAmount1Delta(sqrtRatioAX96, sqrtRatioX96, liquidity, roundingUp);
} else {
amount1 = SqrtPriceMath.getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundingUp);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
pragma abicoder v2;
import {PoolKey} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {LDFType} from "../types/LDFType.sol";
/// @title ILiquidityDensityFunction
/// @author zefram.eth
/// @notice Interface for liquidity density functions (LDFs) that dictate how liquidity is distributed over a pool's rounded ticks (each with `tickSpacing` ticks).
/// Each rounded tick is identified by its leftmost tick, which is a multiple of `tickSpacing`. The liquidity density of all rounded ticks should add up to 1, similar to probability density functions (PDFs).
/// Also contains functions for efficiently computing the cumulative amount of tokens in a consecutive range of rounded ticks, as well as their inverse functions. These are essential for computing swaps.
/// Enables arbitrary liquidity shapes, shifting liquidity across ticks, and switching from one liquidity shape to another.
interface ILiquidityDensityFunction {
/// @notice Queries the liquidity density function for the given pool and rounded tick.
/// Returns the density of the rounded tick, cumulative token densities at adjacent ticks, and state relevant info.
/// @param key The key of the Uniswap v4 pool
/// @param roundedTick The rounded tick to query
/// @param twapTick The TWAP tick. Is 0 if `twapSecondsAgo` is 0. It's up to `isValidParams` to ensure `twapSecondsAgo != 0` if the LDF uses the TWAP.
/// @param spotPriceTick The spot price tick.
/// @param ldfParams The parameters for the liquidity density function
/// @param ldfState The current state of the liquidity density function
/// @return liquidityDensityX96 The density of the rounded tick, scaled by Q96
/// @return cumulativeAmount0DensityX96 The cumulative token0 density in rounded ticks [roundedTick + tickSpacing, maxUsableTick], scaled by Q96
/// @return cumulativeAmount1DensityX96 The cumulative token1 density in rounded ticks [minUsableTick, roundedTick - tickSpacing], scaled by Q96
/// @return newLdfState The new state of the liquidity density function
/// @return shouldSurge Whether the pool should surge. Usually corresponds to whether the LDF has shifted / changed shape.
function query(
PoolKey calldata key,
int24 roundedTick,
int24 twapTick,
int24 spotPriceTick,
bytes32 ldfParams,
bytes32 ldfState
)
external
view
returns (
uint256 liquidityDensityX96,
uint256 cumulativeAmount0DensityX96,
uint256 cumulativeAmount1DensityX96,
bytes32 newLdfState,
bool shouldSurge
);
/// @notice Aggregates LDF queries used during a swap.
/// @dev A Bunni swap uses the inverseCumulativeAmount function to compute the rounded tick for which the cumulativeAmount is the closest to `inverseCumulativeAmountInput`
/// and <= `inverseCumulativeAmountInput`. This rounded tick is the starting point for swapping the remaining tokens, which is done via Uniswap math (not done in this function though).
/// @param key The key of the Uniswap v4 pool
/// @param inverseCumulativeAmountInput The input to the inverseCumulativeAmount function
/// @param totalLiquidity The total liquidity in the pool
/// @param zeroForOne Whether the input token is token0
/// @param exactIn Whether it's an exact input swap or an exact output swap
/// @param twapTick The TWAP tick. Is 0 if `twapSecondsAgo` is 0. It's up to `isValidParams` to ensure `twapSecondsAgo != 0` if the LDF uses the TWAP.
/// @param spotPriceTick The spot price tick.
/// @param ldfParams The parameters for the liquidity density function
/// @param ldfState The current state of the liquidity density function
/// @return success Whether the swap computation was successful
/// @return roundedTick The rounded tick to start the remainder swap from
/// @return cumulativeAmount0_ The cumulative amount of token0 to the right of the starting tick of the Uniswap swap
/// @return cumulativeAmount1_ The cumulative amount of token1 to the left of the starting tick of the Uniswap swap
/// @return swapLiquidity The liquidity used for the remainder swap
function computeSwap(
PoolKey calldata key,
uint256 inverseCumulativeAmountInput,
uint256 totalLiquidity,
bool zeroForOne,
bool exactIn,
int24 twapTick,
int24 spotPriceTick,
bytes32 ldfParams,
bytes32 ldfState
)
external
view
returns (
bool success,
int24 roundedTick,
uint256 cumulativeAmount0_,
uint256 cumulativeAmount1_,
uint256 swapLiquidity
);
/// @notice Computes the cumulative amount of token0 in the rounded ticks [roundedTick, maxUsableTick].
/// @param key The key of the Uniswap v4 pool
/// @param roundedTick The rounded tick to query
/// @param totalLiquidity The total liquidity in the pool
/// @param twapTick The TWAP tick. Is 0 if `twapSecondsAgo` is 0. It's up to `isValidParams` to ensure `twapSecondsAgo != 0` if the LDF uses the TWAP.
/// @param spotPriceTick The spot price tick.
/// @param ldfParams The parameters for the liquidity density function
/// @param ldfState The current state of the liquidity density function
/// @return The cumulative amount of token0 in the rounded ticks [roundedTick, maxUsableTick]
function cumulativeAmount0(
PoolKey calldata key,
int24 roundedTick,
uint256 totalLiquidity,
int24 twapTick,
int24 spotPriceTick,
bytes32 ldfParams,
bytes32 ldfState
) external view returns (uint256);
/// @notice Computes the cumulative amount of token1 in the rounded ticks [minUsableTick, roundedTick].
/// @param key The key of the Uniswap v4 pool
/// @param roundedTick The rounded tick to query
/// @param totalLiquidity The total liquidity in the pool
/// @param twapTick The TWAP tick. Is 0 if `twapSecondsAgo` is 0. It's up to `isValidParams` to ensure `twapSecondsAgo != 0` if the LDF uses the TWAP.
/// @param spotPriceTick The spot price tick.
/// @param ldfParams The parameters for the liquidity density function
/// @param ldfState The current state of the liquidity density function
/// @return The cumulative amount of token1 in the rounded ticks [minUsableTick, roundedTick]
function cumulativeAmount1(
PoolKey calldata key,
int24 roundedTick,
uint256 totalLiquidity,
int24 twapTick,
int24 spotPriceTick,
bytes32 ldfParams,
bytes32 ldfState
) external view returns (uint256);
/// @notice Checks if the given LDF parameters are valid.
/// @param key The key of the Uniswap v4 pool
/// @param twapSecondsAgo The time window for the TWAP
/// @param ldfParams The parameters for the liquidity density function
/// @param ldfType The type of LDF, see LDFType.sol for details.
/// @return Whether the parameters are valid
function isValidParams(PoolKey calldata key, uint24 twapSecondsAgo, bytes32 ldfParams, LDFType ldfType)
external
view
returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
/// @notice Returns the index of the most significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the most significant bit, must be greater than 0
/// @return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020500060203020504000106050205030304010505030400000000))
}
}
/// @notice Returns the index of the least significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the least significant bit, must be greater than 0
/// @return r the index of the least significant bit
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
// Isolate the least significant bit.
x := and(x, sub(0, x))
// For the upper 3 bits of the result, use a De Bruijn-like lookup.
// Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
// forgefmt: disable-next-item
r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
0x8040405543005266443200005020610674053026020000107506200176117077)))
// For the lower 5 bits of the result, use a De Bruijn lookup.
// forgefmt: disable-next-item
r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isAddressZero()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
// revert with NativeTransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
}
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success :=
and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
// revert with ERC20TransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
);
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isAddressZero()) {
return address(this).balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isAddressZero()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {IPoolManager} from "./IPoolManager.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
returns (bytes4);
/// @notice The hook called before liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterAddLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
/// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
function beforeSwap(
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params,
bytes calldata hookData
) external returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterSwap(
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Owner balance of an id.
/// @param owner The address of the owner.
/// @param id The id of the token.
/// @return amount The balance of the token.
function balanceOf(address owner, uint256 id) external view returns (uint256 amount);
/// @notice Spender allowance of an id.
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @return amount The allowance of the token.
function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);
/// @notice Checks if a spender is approved by an owner as an operator
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @return approved The approval status.
function isOperator(address owner, address spender) external view returns (bool approved);
/// @notice Transfers an amount of an id from the caller to a receiver.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Transfers an amount of an id from a sender to a receiver.
/// @param sender The address of the sender.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Approves an amount of an id to a spender.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always
function approve(address spender, uint256 id, uint256 amount) external returns (bool);
/// @notice Sets or removes an operator for the caller.
/// @param operator The address of the operator.
/// @param approved The approval status.
/// @return bool True, always
function setOperator(address operator, bool approved) external returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
/// @notice Thrown when protocol fee is set too high
error ProtocolFeeTooLarge(uint24 fee);
/// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
error InvalidCaller();
/// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
error ProtocolFeeCurrencySynced();
/// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
event ProtocolFeeControllerUpdated(address indexed protocolFeeController);
/// @notice Emitted when the protocol fee is updated for a pool.
event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);
/// @notice Given a currency address, returns the protocol fees accrued in that currency
/// @param currency The currency to check
/// @return amount The amount of protocol fees accrued in the currency
function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);
/// @notice Sets the protocol fee for the given pool
/// @param key The key of the pool to set a protocol fee for
/// @param newProtocolFee The fee to set
function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;
/// @notice Sets the protocol fee controller
/// @param controller The new protocol fee controller
function setProtocolFeeController(address controller) external;
/// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
/// @dev This will revert if the contract is unlocked
/// @param recipient The address to receive the protocol fees
/// @param currency The currency to withdraw
/// @param amount The amount of currency to withdraw
/// @return amountCollected The amount of currency successfully withdrawn
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
returns (uint256 amountCollected);
/// @notice Returns the current protocol fee controller address
/// @return address The current protocol fee controller address
function protocolFeeController() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice A BalanceDelta of 0
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
poolId := keccak256(poolKey, 0xa0)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
/// @notice Called by external contracts to access granular pool state
/// @param slot Key of slot to sload
/// @return value The value of the slot as bytes32
function extsload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access granular pool state
/// @param startSlot Key of slot to start sloading from
/// @param nSlots Number of slots to load into return value
/// @return values List of loaded values.
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);
/// @notice Called by external contracts to access sparse pool state
/// @param slots List of slots to SLOAD from.
/// @return values List of loaded values.
function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
/// @notice Called by external contracts to access transient storage of the contract
/// @param slot Key of slot to tload
/// @return value The value of the slot as bytes32
function exttload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access sparse transient pool state
/// @param slots List of slots to tload
/// @return values List of loaded values
function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0 = a * b; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
assembly ("memory-safe") {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly ("memory-safe") {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly ("memory-safe") {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (0 - denominator) & denominator;
// Divide denominator by power of two
assembly ("memory-safe") {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly ("memory-safe") {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly ("memory-safe") {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the preconditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) != 0) {
require(++result > 0);
}
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
using CustomRevert for bytes4;
error SafeCastOverflow();
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) SafeCastOverflow.selector.revertWith();
y = uint128(x);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
return int128(int256(x));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
/// @notice Returns ceil(x / y)
/// @dev division by 0 will return 0, and should be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, ceil(x / y)
function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly ("memory-safe") {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
/// @notice Calculates floor(a×b÷denominator)
/// @dev division by 0 will return 0, and should be checked externally
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result, floor(a×b÷denominator)
function simpleMulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
assembly ("memory-safe") {
result := div(mul(a, b), denominator)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
enum LDFType {
STATIC, // LDF does not change ever
DYNAMIC_NOT_STATEFUL, // LDF can change, does not use ldfState
DYNAMIC_AND_STATEFUL // LDF can change, uses ldfState
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
/// @notice Returns an account's balance in the token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
/// @notice A BeforeSwapDelta of 0
BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);
/// extracts int128 from the upper 128 bits of the BeforeSwapDelta
/// returned by beforeSwap
function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
assembly ("memory-safe") {
deltaSpecified := sar(128, delta)
}
}
/// extracts int128 from the lower 128 bits of the BeforeSwapDelta
/// returned by beforeSwap and afterSwap
function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
assembly ("memory-safe") {
deltaUnspecified := signextend(15, delta)
}
}
}{
"remappings": [
"@uniswap/v4-core/=lib/v4-core/",
"solmate/src/=lib/solmate/src/",
"solmate/utils/=lib/solmate/src/utils/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
"biddog/=lib/biddog/src/",
"clones-with-immutable-args/=lib/clones-with-immutable-args/src/",
"create3-factory/=lib/create3-factory/",
"ds-test/=lib/clones-with-immutable-args/lib/ds-test/src/",
"erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"flood-contracts/=lib/flood-contracts/",
"forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
"forge-std/=lib/forge-std/src/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"leb128-nooffset/=lib/flood-contracts/lib/leb128-nooffset/src/",
"leb128/=lib/flood-contracts/lib/leb128-nooffset/src/",
"multicaller/=lib/multicaller/src/",
"openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"permit2/=lib/permit2/",
"solady/=lib/solady/src/",
"v4-core/=lib/v4-core/src/"
],
"optimizer": {
"enabled": true,
"runs": 100000000
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "cancun",
"viaIR": true,
"libraries": {}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[],"name":"BunniSwapMath__SwapFailed","type":"error"},{"inputs":[{"components":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"IHooks"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"totalLiquidity","type":"uint256"},{"internalType":"uint256","name":"liquidityDensityOfRoundedTickX96","type":"uint256"},{"internalType":"uint256","name":"currentActiveBalance0","type":"uint256"},{"internalType":"uint256","name":"currentActiveBalance1","type":"uint256"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"internalType":"int24","name":"currentTick","type":"int24"},{"internalType":"contract ILiquidityDensityFunction","name":"liquidityDensityFunction","type":"ILiquidityDensityFunction"},{"internalType":"int24","name":"arithmeticMeanTick","type":"int24"},{"internalType":"bytes32","name":"ldfParams","type":"bytes32"},{"internalType":"bytes32","name":"ldfState","type":"bytes32"},{"components":[{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"int256","name":"amountSpecified","type":"int256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct IPoolManager.SwapParams","name":"swapParams","type":"tuple"}],"internalType":"struct BunniSwapMath.BunniComputeSwapInput","name":"input","type":"tuple"}],"name":"computeSwap","outputs":[{"internalType":"uint160","name":"updatedSqrtPriceX96","type":"uint160"},{"internalType":"int24","name":"updatedTick","type":"int24"},{"internalType":"uint256","name":"inputAmount","type":"uint256"},{"internalType":"uint256","name":"outputAmount","type":"uint256"}],"stateMutability":"view","type":"function"}]Contract Creation Code
608080604052346019576128a8908161001e823930815050f35b5f80fdfe60a06040526004361015610011575f80fd5b5f3560e01c63eded936414610024575f80fd5b6102407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261008a5760806100596101b6565b9173ffffffffffffffffffffffffffffffffffffffff6040519416845260020b602084015260408301526060820152f35b5f80fd5b7f800000000000000000000000000000000000000000000000000000000000000081146100ba575f0390565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b919082039182116100ba57565b919082018092116100ba57565b90601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0910116810190811067ffffffffffffffff82111761014257604052565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b5190811515820361008a57565b9060020b9060020b01907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000008212627fffff8313176100ba57565b6101e43515156101e4350361008a575f610204351215611990576101dc6102043561008e565b5f610204351215611987575f5b9160c435918260a435029260a43584041460a4351517156100ba576101443560020b610144350361008a5761014435906102243573ffffffffffffffffffffffffffffffffffffffff8116810361008a578060805260643560020b6064350361008a5760643560020b1561195a5761028e60643560020b7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff27618056064350260020b611996565b906102a960643560020b620d89e8056064350260020b611996565b906101e4359081611922575b81156118ea575b5061181d575b50506102d360643561014435611d08565b925f5f935f988860601c6112d2575b5f6102043512156112a357506101e43515611291576103039060e4356100f4565b915b73ffffffffffffffffffffffffffffffffffffffff6101643516610164350361008a576101843560020b610184350361008a575f926040517fd5fac4930000000000000000000000000000000000000000000000000000000081526004359573ffffffffffffffffffffffffffffffffffffffff871680880361008a5760048301526024359873ffffffffffffffffffffffffffffffffffffffff8a168a0361008a5773ffffffffffffffffffffffffffffffffffffffff8a1660248401526044359b62ffffff8d16808e0361008a5760448501525f9d60643560020b60648601526084359a73ffffffffffffffffffffffffffffffffffffffff8c16808d0361008a5760848701528660a487015260a43560c48701526101e435151560e48701525f61020435126101048701526101843560020b6101248701526101443560020b6101448701526101a4356101648701526101c43561018487015260a0866101a48173ffffffffffffffffffffffffffffffffffffffff61016435165afa9889156109f6575f985f965f965f995f9d611228575b5087968a9c610a13575b50505050505050505050505050506101243573ffffffffffffffffffffffffffffffffffffffff81169081810361008a575060805173ffffffffffffffffffffffffffffffffffffffff1603610a015761008a5761014435945b856080519760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261008a576040519360a0850185811067ffffffffffffffff821117610142576040528452602084019586526040840192835261008a5762ffffff9173ffffffffffffffffffffffffffffffffffffffff60608501956064358752608086019081525f9661059b60643560020b86611d08565b969094846105b16105ab88611996565b99611996565b9b816040519b7f685056ff000000000000000000000000000000000000000000000000000000008d52511660048c0152511660248a0152511660448801525160020b60648701525116608485015260020b60a48401526101843560020b60c484015260020b60e48301526101a4356101048301526101c43561012483015260a0826101448173ffffffffffffffffffffffffffffffffffffffff61016435165afa9384156109f6575f5f915f945f97610996575b506106d4935f9392919084828273ffffffffffffffffffffffffffffffffffffffff8083169082161161098b575b505060805173ffffffffffffffffffffffffffffffffffffffff8381169116116109255750916106c7916106ce94936121ef565b905b6100f4565b926100f4565b921561091d575b8115918280158094610916575b61075b575b505061070b91506107019060a435906121b5565b9160a435906121b5565b906101e4351561073b576107229060e435906100e7565b90610104358181111561073457039091565b50505f9091565b9061074a9061010435906100e7565b9060e4358181111561073457039091565b809361090d575b8290841561083f5750505f925b841580610836575b156108065780156107b9579061070b938361070194935f5b50156107a3575050505f5b505b905f6106ed565b6107ac916125de565b818110908218021861079a565b83836c0100000000000000000000000084096107e1575b938361070194939261070b9661078f565b509190600184019384156107f95793929091926107d0565b63ae47f7025f526004601cfd5b61070b93506107019291901561081f57505f5b5061079c565b610829825f6125de565b8181109082180218610819565b50821515610777565b818360601b916c010000000000000000000000008584041417021561086657045b9261076f565b90507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6c01000000000000000000000000830981811082019003836c010000000000000000000000008409845f03851691808611156107f95782860480600302600218808202600203028082026002030280820260020302808202600203028082026002030280910260020302936001848483030494805f03040192119003021702610860565b82159350610762565b505f6106e8565b5f91506106db565b6106ce94955073ffffffffffffffffffffffffffffffffffffffff839492931673ffffffffffffffffffffffffffffffffffffffff60805116105f146109815750610977816106ce93946080516121ef565b9260805190612311565b926106ce92612311565b935091505f80610693565b94509550505060a0823d60a0116109ee575b816109b560a09383610101565b8101031261008a576106d490825160208401516040850151916109df60806060880151970161016f565b90919295509690919293610665565b3d91506109a8565b6040513d5f823e3d90fd5b50610a0d608051611df7565b946104fe565b6101e43515611219578260020b8a60020b12155b61110f57505050505050506101e4355f146110fa578d61008a57610a4d6064358461017c565b92915b610a5984611996565b916101e435806110c2575b801561107c575b610a7a575b80808080806104a4565b610a8384611996565b956101e4351561106557505060e4358181119082180218965b5f9581159081801561102e575b15610c7e575050505f935f9382965b610a7057979e50959c50939a99509197509550935073ffffffffffffffffffffffffffffffffffffffff80891692168203610c4d575050506101e435900360020b955b845f610204351215610c4257610b136102043561008e565b83145b610c1657506101e43580610c0d575b8015610bf6575b610bce576101e43515610bb557610b4d9291610b47916100f4565b946100e7565b925b6101e43515610b8757610b659060e435906100e7565b926101043581811115610b7e5703925b92915b93929190565b50505f92610b75565b92610b969061010435906100e7565b9260e43581811115610bac5703925b9291610b78565b50505f92610ba5565b610bc892610bc2916100e7565b946100f4565b92610b4f565b7f03576820000000000000000000000000000000000000000000000000000000005f5260045ffd5b506101e435156101e435610b2c5750828110610b2c565b50828610610b25565b94505093506101e4355f14610c395761010435925b949392818110908218021890565b60e43592610c2b565b610204358414610b16565b73ffffffffffffffffffffffffffffffffffffffff91929993501614610afb579550610c7884611df7565b95610afb565b91969095909490915f61020435121561100c57610cb1610cac610cb6926101e4355f14611005578c906100e7565b6121a0565b61008e565b60805173ffffffffffffffffffffffffffffffffffffffff90811690841681811890821160016101e43516180218965f5f83129873ffffffffffffffffffffffffffffffffffffffff81169073ffffffffffffffffffffffffffffffffffffffff88169180831015948c5f14610f1a57508c865f03610d38620f4222826123fb565b906103e8811115610f13577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc18015b818110908218021891865f14610ee25750610d82908a846121ef565b935b848210610e7a5750509a5f93610d9f620f4222601e86612358565b806103e8116103e882180218945b5015610e6957610ddd9173ffffffffffffffffffffffffffffffffffffffff8d16038060ff1d9081011890612381565b985b15610e5957610df791610df1916100f4565b9161008e565b8181109082180218955b959473ffffffffffffffffffffffffffffffffffffffff88816080511691829116149081610e38575b5015610ab857506001610ab8565b905073ffffffffffffffffffffffffffffffffffffffff841614155f610e2a565b610e6392506100f4565b95610e01565b610e7591508b88612288565b610ddd565b949350809c9150926fffffffffffffffffffffffffffffffff821615831517610ed5578015610ec557610eae8d838b6126a0565b9c86015f03806103e8116103e88218021894610dad565b610ed08d838b6127e0565b610eae565b634f2461b85f526004601cfd5b6c0100000000000000000000000060019186038060ff1d90810118610f078185612381565b93091515160193610d84565b505f610d66565b9b949c9350828d5f14610ff257610f3a91038060ff1d9081011884612381565b9a5b8b8610610fbf57509a5b15610f785750610f5790868b6121ef565b610f66620f4222601e83612358565b806103e8116103e88218021891610ddf565b6c0100000000000000000000000060019173ffffffffffffffffffffffffffffffffffffffff8d1690038060ff1d90810118610fb48185612381565b930915151601610f57565b9a50508399811517610ed5578a15610fe257610fdc848389612711565b9a610f46565b610fed848389612643565b610fdc565b5050610fff83828a612288565b9a610f3c565b8b906100e7565b610cac611023916101e4355f14611028578a6100e7565b610cb6565b8b6100e7565b5073ffffffffffffffffffffffffffffffffffffffff841673ffffffffffffffffffffffffffffffffffffffff6080511614610aa9565b915097965061010435818111908218021895610a9c565b506101e435156101e435610a6b575073ffffffffffffffffffffffffffffffffffffffff831673ffffffffffffffffffffffffffffffffffffffff608051161015610a6b565b5073ffffffffffffffffffffffffffffffffffffffff831673ffffffffffffffffffffffffffffffffffffffff608051161115610a64565b5f9d506111096064358461017c565b91610a50565b9c509c509c509c509d9c509d509d5050505050505060601c156111e5576101e435156111dd5750905b73ffffffffffffffffffffffffffffffffffffffff61115683611996565b73ffffffffffffffffffffffffffffffffffffffff86169116810361119e5750506101e435900360020b935b6101e43515610c39576101043592949392818110908218021890565b90959150610124359073ffffffffffffffffffffffffffffffffffffffff82169182810361008a5750146111825793506111d782611df7565b93611182565b905090611138565b505050925050506101243573ffffffffffffffffffffffffffffffffffffffff8116810361008a579061014435905f905f90565b8260020b8a60020b1315610a27565b97509b5096509850955060a0843d60a011611289575b8161124b60a09383610101565b8101031261008a5761125c8461016f565b956020850151988960020b8a0361008a5760408601519660806060880151970151989a9796989b5f61049a565b3d915061123e565b61129e90610104356100f4565b610303565b90506101e435156112c1576112bb90610104356100e7565b91610305565b6112cd9060e4356100e7565b6112bb565b98509350506101e435156118165781925b6112ec84611996565b9073ffffffffffffffffffffffffffffffffffffffff6101243516610124350361008a5760805173ffffffffffffffffffffffffffffffffffffffff90811690831681811890821160016101e43516180218985f9973ffffffffffffffffffffffffffffffffffffffff8116905f61020435125f1461166357610204355f03611378620f4240826123fb565b906103e881111561165c577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc18015b80821890821102186101243573ffffffffffffffffffffffffffffffffffffffff16831161160b576113df8c60601c61012435846121ef565b9c5b8d821061156c5750509a5f916113fb620f42405f84612358565b806103e8116103e882180218925b506101243573ffffffffffffffffffffffffffffffffffffffff16106115565761145c8c73ffffffffffffffffffffffffffffffffffffffff8061012435169116038060ff1d908101188c60601c612381565b915b5f61020435121561154857611472916100f4565b61147e6102043561008e565b81811090821802185b819b819881965f61020435125f1461153d576114a56102043561008e565b84145b6114b65750505050506102e2565b97985098509998509950995050505073ffffffffffffffffffffffffffffffffffffffff808616911681145f1461150f5750506101e435900360020b936101e43515610c39576101043592949392818110908218021890565b9095915073ffffffffffffffffffffffffffffffffffffffff6101243516146111825793506111d782611df7565b6102043585146114a8565b611551916100f4565b611487565b6115678b60601c8d61012435612288565b61145c565b929150809c50906fffffffffffffffffffffffffffffffff8c60601c161573ffffffffffffffffffffffffffffffffffffffff61012435161517610ed5576101243573ffffffffffffffffffffffffffffffffffffffff1681116115f5576115db8d8d60601c610124356126a0565b9c61020435015f03806103e8116103e88218021892611409565b6116068d8d60601c610124356127e0565b6115db565b8b60016c010000000000000000000000008573ffffffffffffffffffffffffffffffffffffffff6101243516038060ff1d9081011861164d818560601c612381565b9360601c09151516019c6113e1565b505f6113a6565b909a506101243573ffffffffffffffffffffffffffffffffffffffff168b116117fe57896116b773ffffffffffffffffffffffffffffffffffffffff61012435168d038060ff1d908101188260601c612381565b915b61020435831161177c57809c5b6101243573ffffffffffffffffffffffffffffffffffffffff161061171657506116f79060601c610124358d6121ef565b611705620f42405f83612358565b806103e8116103e88218021861145e565b6c0100000000000000000000000061176d73ffffffffffffffffffffffffffffffffffffffff6001931673ffffffffffffffffffffffffffffffffffffffff6101243516038060ff1d90810118809460601c612381565b928d60601c09151516016116f7565b505050610204358960601c1573ffffffffffffffffffffffffffffffffffffffff61012435161517610ed5576101243573ffffffffffffffffffffffffffffffffffffffff168b116117e457896117dd610204358260601c61012435612711565b809c6116c6565b896117f9610204358260601c61012435612643565b6117dd565b896118108160601c8361012435612288565b916116b9565b83926112e3565b6101e43515611867575073ffffffffffffffffffffffffffffffffffffffff600191160173ffffffffffffffffffffffffffffffffffffffff81116100ba575b6080525f806102c2565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff915073ffffffffffffffffffffffffffffffffffffffff160173ffffffffffffffffffffffffffffffffffffffff81111561185d577f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b6101e435159150816118fe575b505f6102bc565b905073ffffffffffffffffffffffffffffffffffffffff808316911610155f6118f7565b905073ffffffffffffffffffffffffffffffffffffffff831673ffffffffffffffffffffffffffffffffffffffff82161115906102b5565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b610204356101e9565b5f6101dc565b60020b908160ff1d82810118620d89e88111611cdc5763ffffffff9192600182167001fffcb933bd6fad37aa2d162d1a59400102700100000000000000000000000000000000189160028116611cc0575b60048116611ca4575b60088116611c88575b60108116611c6c575b60208116611c50575b60408116611c34575b60808116611c18575b6101008116611bfc575b6102008116611be0575b6104008116611bc4575b6108008116611ba8575b6110008116611b8c575b6120008116611b70575b6140008116611b54575b6180008116611b38575b620100008116611b1c575b620200008116611b01575b620400008116611ae6575b6208000016611acd575b5f12611aa6575b0160201c90565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff04611a9f565b6b048a170391f7dc42444e8fa290910260801c90611a98565b6d2216e584f5fa1ea926041bedfe9890920260801c91611a8e565b916e5d6af8dedb81196699c329225ee6040260801c91611a83565b916f09aa508b5b7a84e1c677de54f3e99bc90260801c91611a78565b916f31be135f97d08fd981231505542fcfa60260801c91611a6d565b916f70d869a156d2a1b890bb3df62baf32f70260801c91611a63565b916fa9f746462d870fdf8a65dc1f90e061e50260801c91611a59565b916fd097f3bdfd2022b8845ad8f792aa58250260801c91611a4f565b916fe7159475a2c29b7443b29c7fa6e889d90260801c91611a45565b916ff3392b0822b70005940c7a398e4b70f30260801c91611a3b565b916ff987a7253ac413176f2b074cf7815e540260801c91611a31565b916ffcbe86c7900a88aedcffc83b479aa3a40260801c91611a27565b916ffe5dee046a99a2a811c461f1969c30530260801c91611a1d565b916fff2ea16466c96a3843ec78b326b528610260801c91611a14565b916fff973b41fa98c081472e6896dfb254c00260801c91611a0b565b916fffcb9843d60f6159c9db58835c9266440260801c91611a02565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c916119f9565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c916119f0565b916ffff97272373d413259a46990580e213a0260801c916119e7565b827f8b86327a000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b91909160020b8260020b90811561195a577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82147fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000008214166100ba5781810590825f82129182611de8575b5050611d97575b60020b02918260020b9283036100ba57611d94908361017c565b90565b60020b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff80000081146100ba577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01611d7a565b0760020b15159050825f611d73565b73fffd8963efd1fc6a506488495d951d516396168273ffffffffffffffffffffffffffffffffffffffff7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffefffd895d8301161161215e5777ffffffffffffffffffffffffffffffffffffffff000000008160201b1680811561008a5760ff826fffffffffffffffffffffffffffffffff1060071b83811c67ffffffffffffffff1060061b1783811c63ffffffff1060051b1783811c61ffff1060041b1783811c821060031b177f07060605060205000602030205040001060502050303040105050304000000006f8421084210842108cc6318c6db6d54be85831c1c601f161a17169160808310155f1461215257507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8182011c5b800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c80029081607f1c8260ff1c1c80029283607f1c8460ff1c1c80029485607f1c8660ff1c1c80029687607f1c8860ff1c1c80029889607f1c8a60ff1c1c80029a8b607f1c8c60ff1c1c80029c8d80607f1c9060ff1c1c800260cd1c6604000000000000169d60cc1c6608000000000000169c60cb1c6610000000000000169b60ca1c6620000000000000169a60c91c6640000000000000169960c81c6680000000000000169860c71c670100000000000000169760c61c670200000000000000169660c51c670400000000000000169560c41c670800000000000000169460c31c671000000000000000169360c21c672000000000000000169260c11c674000000000000000169160c01c67800000000000000016907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff800160401b1717171717171717171717171717693627a301d71055774c85027ffffffffffffffffffffffffffffffffffd709b7e5480fba5a50fed5e62ffc556810160801d60020b906fdb2df09e81959a81455e260799a0632f0160801d60020b918282145f1461210f5750905090565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff61214384611996565b161161214d575090565b905090565b905081607f031b611f27565b73ffffffffffffffffffffffffffffffffffffffff907f61487524000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b5f811215611d94576335278d125f526004601cfd5b91906c01000000000000000000000000906121d081856125de565b93096121d857565b906001019081156107f957565b811561195a570490565b9073ffffffffffffffffffffffffffffffffffffffff811673ffffffffffffffffffffffffffffffffffffffff831611612282575b73ffffffffffffffffffffffffffffffffffffffff82169283156122765773ffffffffffffffffffffffffffffffffffffffff61226a938184169303169060601b612358565b90808206151591040190565b62bfc9215f526004601cfd5b90612224565b73ffffffffffffffffffffffffffffffffffffffff821673ffffffffffffffffffffffffffffffffffffffff82161161230b575b73ffffffffffffffffffffffffffffffffffffffff811691821561227657611d949373ffffffffffffffffffffffffffffffffffffffff612306938184169303169060601b61253f565b6121e5565b906122bc565b6c010000000000000000000000009073ffffffffffffffffffffffffffffffffffffffff80600194169116038060ff1d9081011861234f8185612381565b93091515160190565b92919061236682828661253f565b93821561195a570961237457565b9060010190811561008a57565b90808202917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff828209918380841093039280840393846c01000000000000000000000000111561008a57146123f2576c01000000000000000000000000910990828211900360a01b910360601c1790565b50505060601c90565b818102907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83820990828083109203918083039283620f4240111561008a571461247a577fde8f6cefed634549b62c77574f722e1ac57e23f24d8fd5cb790fb65668c2613993620f4240910990828211900360fa1b910360061c170290565b5050620f424091500490565b908160601b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6c0100000000000000000000000084099282808510940393808503948584111561008a5714612538576c0100000000000000000000000082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b5091500490565b91818302917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8185099383808610950394808603958685111561008a57146125d6579082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b505091500490565b818102918082840414821517156125f757505060601c90565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff910981811082019003908160601c156126385763ae47f7025f526004601cfd5b60601c9060a01b0190565b9190811561269b5773ffffffffffffffffffffffffffffffffffffffff9060601b921691828202918383831191840414161561268e57611d949261268992820391612358565b612829565b63f5c787f15f526004601cfd5b505090565b9091801561270b5773ffffffffffffffffffffffffffffffffffffffff809360601b9216808202816126d284836121e5565b146126f3575b50906106c96126e792846121e5565b80820615159104011690565b83018381106126d857915061270792612358565b1690565b50905090565b919073ffffffffffffffffffffffffffffffffffffffff82116127845773ffffffffffffffffffffffffffffffffffffffff9160601b908082061515910401915b1690808211156127775773ffffffffffffffffffffffffffffffffffffffff91031690565b634323a5555f526004601cfd5b61279c816c010000000000000000000000008461253f565b91811561195a576c0100000000000000000000000090096127d4575b73ffffffffffffffffffffffffffffffffffffffff9091612752565b600101806127b8575f80fd5b611d94926126899273ffffffffffffffffffffffffffffffffffffffff919082821161281a576128129160601b6121e5565b915b166100f4565b61282391612486565b91612814565b9073ffffffffffffffffffffffffffffffffffffffff821691820361284a57565b7f93dafdf1000000000000000000000000000000000000000000000000000000005f5260045ffdfea26469706673582212208d022e53bd8376943d1cc048f1f7c87d1c3c530557938886360e9d668cb368c764736f6c634300081e0033
Deployed Bytecode
0x60a06040526004361015610011575f80fd5b5f3560e01c63eded936414610024575f80fd5b6102407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261008a5760806100596101b6565b9173ffffffffffffffffffffffffffffffffffffffff6040519416845260020b602084015260408301526060820152f35b5f80fd5b7f800000000000000000000000000000000000000000000000000000000000000081146100ba575f0390565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b919082039182116100ba57565b919082018092116100ba57565b90601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0910116810190811067ffffffffffffffff82111761014257604052565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b5190811515820361008a57565b9060020b9060020b01907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000008212627fffff8313176100ba57565b6101e43515156101e4350361008a575f610204351215611990576101dc6102043561008e565b5f610204351215611987575f5b9160c435918260a435029260a43584041460a4351517156100ba576101443560020b610144350361008a5761014435906102243573ffffffffffffffffffffffffffffffffffffffff8116810361008a578060805260643560020b6064350361008a5760643560020b1561195a5761028e60643560020b7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff27618056064350260020b611996565b906102a960643560020b620d89e8056064350260020b611996565b906101e4359081611922575b81156118ea575b5061181d575b50506102d360643561014435611d08565b925f5f935f988860601c6112d2575b5f6102043512156112a357506101e43515611291576103039060e4356100f4565b915b73ffffffffffffffffffffffffffffffffffffffff6101643516610164350361008a576101843560020b610184350361008a575f926040517fd5fac4930000000000000000000000000000000000000000000000000000000081526004359573ffffffffffffffffffffffffffffffffffffffff871680880361008a5760048301526024359873ffffffffffffffffffffffffffffffffffffffff8a168a0361008a5773ffffffffffffffffffffffffffffffffffffffff8a1660248401526044359b62ffffff8d16808e0361008a5760448501525f9d60643560020b60648601526084359a73ffffffffffffffffffffffffffffffffffffffff8c16808d0361008a5760848701528660a487015260a43560c48701526101e435151560e48701525f61020435126101048701526101843560020b6101248701526101443560020b6101448701526101a4356101648701526101c43561018487015260a0866101a48173ffffffffffffffffffffffffffffffffffffffff61016435165afa9889156109f6575f985f965f965f995f9d611228575b5087968a9c610a13575b50505050505050505050505050506101243573ffffffffffffffffffffffffffffffffffffffff81169081810361008a575060805173ffffffffffffffffffffffffffffffffffffffff1603610a015761008a5761014435945b856080519760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261008a576040519360a0850185811067ffffffffffffffff821117610142576040528452602084019586526040840192835261008a5762ffffff9173ffffffffffffffffffffffffffffffffffffffff60608501956064358752608086019081525f9661059b60643560020b86611d08565b969094846105b16105ab88611996565b99611996565b9b816040519b7f685056ff000000000000000000000000000000000000000000000000000000008d52511660048c0152511660248a0152511660448801525160020b60648701525116608485015260020b60a48401526101843560020b60c484015260020b60e48301526101a4356101048301526101c43561012483015260a0826101448173ffffffffffffffffffffffffffffffffffffffff61016435165afa9384156109f6575f5f915f945f97610996575b506106d4935f9392919084828273ffffffffffffffffffffffffffffffffffffffff8083169082161161098b575b505060805173ffffffffffffffffffffffffffffffffffffffff8381169116116109255750916106c7916106ce94936121ef565b905b6100f4565b926100f4565b921561091d575b8115918280158094610916575b61075b575b505061070b91506107019060a435906121b5565b9160a435906121b5565b906101e4351561073b576107229060e435906100e7565b90610104358181111561073457039091565b50505f9091565b9061074a9061010435906100e7565b9060e4358181111561073457039091565b809361090d575b8290841561083f5750505f925b841580610836575b156108065780156107b9579061070b938361070194935f5b50156107a3575050505f5b505b905f6106ed565b6107ac916125de565b818110908218021861079a565b83836c0100000000000000000000000084096107e1575b938361070194939261070b9661078f565b509190600184019384156107f95793929091926107d0565b63ae47f7025f526004601cfd5b61070b93506107019291901561081f57505f5b5061079c565b610829825f6125de565b8181109082180218610819565b50821515610777565b818360601b916c010000000000000000000000008584041417021561086657045b9261076f565b90507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6c01000000000000000000000000830981811082019003836c010000000000000000000000008409845f03851691808611156107f95782860480600302600218808202600203028082026002030280820260020302808202600203028082026002030280910260020302936001848483030494805f03040192119003021702610860565b82159350610762565b505f6106e8565b5f91506106db565b6106ce94955073ffffffffffffffffffffffffffffffffffffffff839492931673ffffffffffffffffffffffffffffffffffffffff60805116105f146109815750610977816106ce93946080516121ef565b9260805190612311565b926106ce92612311565b935091505f80610693565b94509550505060a0823d60a0116109ee575b816109b560a09383610101565b8101031261008a576106d490825160208401516040850151916109df60806060880151970161016f565b90919295509690919293610665565b3d91506109a8565b6040513d5f823e3d90fd5b50610a0d608051611df7565b946104fe565b6101e43515611219578260020b8a60020b12155b61110f57505050505050506101e4355f146110fa578d61008a57610a4d6064358461017c565b92915b610a5984611996565b916101e435806110c2575b801561107c575b610a7a575b80808080806104a4565b610a8384611996565b956101e4351561106557505060e4358181119082180218965b5f9581159081801561102e575b15610c7e575050505f935f9382965b610a7057979e50959c50939a99509197509550935073ffffffffffffffffffffffffffffffffffffffff80891692168203610c4d575050506101e435900360020b955b845f610204351215610c4257610b136102043561008e565b83145b610c1657506101e43580610c0d575b8015610bf6575b610bce576101e43515610bb557610b4d9291610b47916100f4565b946100e7565b925b6101e43515610b8757610b659060e435906100e7565b926101043581811115610b7e5703925b92915b93929190565b50505f92610b75565b92610b969061010435906100e7565b9260e43581811115610bac5703925b9291610b78565b50505f92610ba5565b610bc892610bc2916100e7565b946100f4565b92610b4f565b7f03576820000000000000000000000000000000000000000000000000000000005f5260045ffd5b506101e435156101e435610b2c5750828110610b2c565b50828610610b25565b94505093506101e4355f14610c395761010435925b949392818110908218021890565b60e43592610c2b565b610204358414610b16565b73ffffffffffffffffffffffffffffffffffffffff91929993501614610afb579550610c7884611df7565b95610afb565b91969095909490915f61020435121561100c57610cb1610cac610cb6926101e4355f14611005578c906100e7565b6121a0565b61008e565b60805173ffffffffffffffffffffffffffffffffffffffff90811690841681811890821160016101e43516180218965f5f83129873ffffffffffffffffffffffffffffffffffffffff81169073ffffffffffffffffffffffffffffffffffffffff88169180831015948c5f14610f1a57508c865f03610d38620f4222826123fb565b906103e8811115610f13577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc18015b818110908218021891865f14610ee25750610d82908a846121ef565b935b848210610e7a5750509a5f93610d9f620f4222601e86612358565b806103e8116103e882180218945b5015610e6957610ddd9173ffffffffffffffffffffffffffffffffffffffff8d16038060ff1d9081011890612381565b985b15610e5957610df791610df1916100f4565b9161008e565b8181109082180218955b959473ffffffffffffffffffffffffffffffffffffffff88816080511691829116149081610e38575b5015610ab857506001610ab8565b905073ffffffffffffffffffffffffffffffffffffffff841614155f610e2a565b610e6392506100f4565b95610e01565b610e7591508b88612288565b610ddd565b949350809c9150926fffffffffffffffffffffffffffffffff821615831517610ed5578015610ec557610eae8d838b6126a0565b9c86015f03806103e8116103e88218021894610dad565b610ed08d838b6127e0565b610eae565b634f2461b85f526004601cfd5b6c0100000000000000000000000060019186038060ff1d90810118610f078185612381565b93091515160193610d84565b505f610d66565b9b949c9350828d5f14610ff257610f3a91038060ff1d9081011884612381565b9a5b8b8610610fbf57509a5b15610f785750610f5790868b6121ef565b610f66620f4222601e83612358565b806103e8116103e88218021891610ddf565b6c0100000000000000000000000060019173ffffffffffffffffffffffffffffffffffffffff8d1690038060ff1d90810118610fb48185612381565b930915151601610f57565b9a50508399811517610ed5578a15610fe257610fdc848389612711565b9a610f46565b610fed848389612643565b610fdc565b5050610fff83828a612288565b9a610f3c565b8b906100e7565b610cac611023916101e4355f14611028578a6100e7565b610cb6565b8b6100e7565b5073ffffffffffffffffffffffffffffffffffffffff841673ffffffffffffffffffffffffffffffffffffffff6080511614610aa9565b915097965061010435818111908218021895610a9c565b506101e435156101e435610a6b575073ffffffffffffffffffffffffffffffffffffffff831673ffffffffffffffffffffffffffffffffffffffff608051161015610a6b565b5073ffffffffffffffffffffffffffffffffffffffff831673ffffffffffffffffffffffffffffffffffffffff608051161115610a64565b5f9d506111096064358461017c565b91610a50565b9c509c509c509c509d9c509d509d5050505050505060601c156111e5576101e435156111dd5750905b73ffffffffffffffffffffffffffffffffffffffff61115683611996565b73ffffffffffffffffffffffffffffffffffffffff86169116810361119e5750506101e435900360020b935b6101e43515610c39576101043592949392818110908218021890565b90959150610124359073ffffffffffffffffffffffffffffffffffffffff82169182810361008a5750146111825793506111d782611df7565b93611182565b905090611138565b505050925050506101243573ffffffffffffffffffffffffffffffffffffffff8116810361008a579061014435905f905f90565b8260020b8a60020b1315610a27565b97509b5096509850955060a0843d60a011611289575b8161124b60a09383610101565b8101031261008a5761125c8461016f565b956020850151988960020b8a0361008a5760408601519660806060880151970151989a9796989b5f61049a565b3d915061123e565b61129e90610104356100f4565b610303565b90506101e435156112c1576112bb90610104356100e7565b91610305565b6112cd9060e4356100e7565b6112bb565b98509350506101e435156118165781925b6112ec84611996565b9073ffffffffffffffffffffffffffffffffffffffff6101243516610124350361008a5760805173ffffffffffffffffffffffffffffffffffffffff90811690831681811890821160016101e43516180218985f9973ffffffffffffffffffffffffffffffffffffffff8116905f61020435125f1461166357610204355f03611378620f4240826123fb565b906103e881111561165c577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc18015b80821890821102186101243573ffffffffffffffffffffffffffffffffffffffff16831161160b576113df8c60601c61012435846121ef565b9c5b8d821061156c5750509a5f916113fb620f42405f84612358565b806103e8116103e882180218925b506101243573ffffffffffffffffffffffffffffffffffffffff16106115565761145c8c73ffffffffffffffffffffffffffffffffffffffff8061012435169116038060ff1d908101188c60601c612381565b915b5f61020435121561154857611472916100f4565b61147e6102043561008e565b81811090821802185b819b819881965f61020435125f1461153d576114a56102043561008e565b84145b6114b65750505050506102e2565b97985098509998509950995050505073ffffffffffffffffffffffffffffffffffffffff808616911681145f1461150f5750506101e435900360020b936101e43515610c39576101043592949392818110908218021890565b9095915073ffffffffffffffffffffffffffffffffffffffff6101243516146111825793506111d782611df7565b6102043585146114a8565b611551916100f4565b611487565b6115678b60601c8d61012435612288565b61145c565b929150809c50906fffffffffffffffffffffffffffffffff8c60601c161573ffffffffffffffffffffffffffffffffffffffff61012435161517610ed5576101243573ffffffffffffffffffffffffffffffffffffffff1681116115f5576115db8d8d60601c610124356126a0565b9c61020435015f03806103e8116103e88218021892611409565b6116068d8d60601c610124356127e0565b6115db565b8b60016c010000000000000000000000008573ffffffffffffffffffffffffffffffffffffffff6101243516038060ff1d9081011861164d818560601c612381565b9360601c09151516019c6113e1565b505f6113a6565b909a506101243573ffffffffffffffffffffffffffffffffffffffff168b116117fe57896116b773ffffffffffffffffffffffffffffffffffffffff61012435168d038060ff1d908101188260601c612381565b915b61020435831161177c57809c5b6101243573ffffffffffffffffffffffffffffffffffffffff161061171657506116f79060601c610124358d6121ef565b611705620f42405f83612358565b806103e8116103e88218021861145e565b6c0100000000000000000000000061176d73ffffffffffffffffffffffffffffffffffffffff6001931673ffffffffffffffffffffffffffffffffffffffff6101243516038060ff1d90810118809460601c612381565b928d60601c09151516016116f7565b505050610204358960601c1573ffffffffffffffffffffffffffffffffffffffff61012435161517610ed5576101243573ffffffffffffffffffffffffffffffffffffffff168b116117e457896117dd610204358260601c61012435612711565b809c6116c6565b896117f9610204358260601c61012435612643565b6117dd565b896118108160601c8361012435612288565b916116b9565b83926112e3565b6101e43515611867575073ffffffffffffffffffffffffffffffffffffffff600191160173ffffffffffffffffffffffffffffffffffffffff81116100ba575b6080525f806102c2565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff915073ffffffffffffffffffffffffffffffffffffffff160173ffffffffffffffffffffffffffffffffffffffff81111561185d577f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b6101e435159150816118fe575b505f6102bc565b905073ffffffffffffffffffffffffffffffffffffffff808316911610155f6118f7565b905073ffffffffffffffffffffffffffffffffffffffff831673ffffffffffffffffffffffffffffffffffffffff82161115906102b5565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b610204356101e9565b5f6101dc565b60020b908160ff1d82810118620d89e88111611cdc5763ffffffff9192600182167001fffcb933bd6fad37aa2d162d1a59400102700100000000000000000000000000000000189160028116611cc0575b60048116611ca4575b60088116611c88575b60108116611c6c575b60208116611c50575b60408116611c34575b60808116611c18575b6101008116611bfc575b6102008116611be0575b6104008116611bc4575b6108008116611ba8575b6110008116611b8c575b6120008116611b70575b6140008116611b54575b6180008116611b38575b620100008116611b1c575b620200008116611b01575b620400008116611ae6575b6208000016611acd575b5f12611aa6575b0160201c90565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff04611a9f565b6b048a170391f7dc42444e8fa290910260801c90611a98565b6d2216e584f5fa1ea926041bedfe9890920260801c91611a8e565b916e5d6af8dedb81196699c329225ee6040260801c91611a83565b916f09aa508b5b7a84e1c677de54f3e99bc90260801c91611a78565b916f31be135f97d08fd981231505542fcfa60260801c91611a6d565b916f70d869a156d2a1b890bb3df62baf32f70260801c91611a63565b916fa9f746462d870fdf8a65dc1f90e061e50260801c91611a59565b916fd097f3bdfd2022b8845ad8f792aa58250260801c91611a4f565b916fe7159475a2c29b7443b29c7fa6e889d90260801c91611a45565b916ff3392b0822b70005940c7a398e4b70f30260801c91611a3b565b916ff987a7253ac413176f2b074cf7815e540260801c91611a31565b916ffcbe86c7900a88aedcffc83b479aa3a40260801c91611a27565b916ffe5dee046a99a2a811c461f1969c30530260801c91611a1d565b916fff2ea16466c96a3843ec78b326b528610260801c91611a14565b916fff973b41fa98c081472e6896dfb254c00260801c91611a0b565b916fffcb9843d60f6159c9db58835c9266440260801c91611a02565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c916119f9565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c916119f0565b916ffff97272373d413259a46990580e213a0260801c916119e7565b827f8b86327a000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b91909160020b8260020b90811561195a577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82147fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000008214166100ba5781810590825f82129182611de8575b5050611d97575b60020b02918260020b9283036100ba57611d94908361017c565b90565b60020b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff80000081146100ba577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01611d7a565b0760020b15159050825f611d73565b73fffd8963efd1fc6a506488495d951d516396168273ffffffffffffffffffffffffffffffffffffffff7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffefffd895d8301161161215e5777ffffffffffffffffffffffffffffffffffffffff000000008160201b1680811561008a5760ff826fffffffffffffffffffffffffffffffff1060071b83811c67ffffffffffffffff1060061b1783811c63ffffffff1060051b1783811c61ffff1060041b1783811c821060031b177f07060605060205000602030205040001060502050303040105050304000000006f8421084210842108cc6318c6db6d54be85831c1c601f161a17169160808310155f1461215257507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8182011c5b800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c80029081607f1c8260ff1c1c80029283607f1c8460ff1c1c80029485607f1c8660ff1c1c80029687607f1c8860ff1c1c80029889607f1c8a60ff1c1c80029a8b607f1c8c60ff1c1c80029c8d80607f1c9060ff1c1c800260cd1c6604000000000000169d60cc1c6608000000000000169c60cb1c6610000000000000169b60ca1c6620000000000000169a60c91c6640000000000000169960c81c6680000000000000169860c71c670100000000000000169760c61c670200000000000000169660c51c670400000000000000169560c41c670800000000000000169460c31c671000000000000000169360c21c672000000000000000169260c11c674000000000000000169160c01c67800000000000000016907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff800160401b1717171717171717171717171717693627a301d71055774c85027ffffffffffffffffffffffffffffffffffd709b7e5480fba5a50fed5e62ffc556810160801d60020b906fdb2df09e81959a81455e260799a0632f0160801d60020b918282145f1461210f5750905090565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff61214384611996565b161161214d575090565b905090565b905081607f031b611f27565b73ffffffffffffffffffffffffffffffffffffffff907f61487524000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b5f811215611d94576335278d125f526004601cfd5b91906c01000000000000000000000000906121d081856125de565b93096121d857565b906001019081156107f957565b811561195a570490565b9073ffffffffffffffffffffffffffffffffffffffff811673ffffffffffffffffffffffffffffffffffffffff831611612282575b73ffffffffffffffffffffffffffffffffffffffff82169283156122765773ffffffffffffffffffffffffffffffffffffffff61226a938184169303169060601b612358565b90808206151591040190565b62bfc9215f526004601cfd5b90612224565b73ffffffffffffffffffffffffffffffffffffffff821673ffffffffffffffffffffffffffffffffffffffff82161161230b575b73ffffffffffffffffffffffffffffffffffffffff811691821561227657611d949373ffffffffffffffffffffffffffffffffffffffff612306938184169303169060601b61253f565b6121e5565b906122bc565b6c010000000000000000000000009073ffffffffffffffffffffffffffffffffffffffff80600194169116038060ff1d9081011861234f8185612381565b93091515160190565b92919061236682828661253f565b93821561195a570961237457565b9060010190811561008a57565b90808202917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff828209918380841093039280840393846c01000000000000000000000000111561008a57146123f2576c01000000000000000000000000910990828211900360a01b910360601c1790565b50505060601c90565b818102907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83820990828083109203918083039283620f4240111561008a571461247a577fde8f6cefed634549b62c77574f722e1ac57e23f24d8fd5cb790fb65668c2613993620f4240910990828211900360fa1b910360061c170290565b5050620f424091500490565b908160601b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6c0100000000000000000000000084099282808510940393808503948584111561008a5714612538576c0100000000000000000000000082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b5091500490565b91818302917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8185099383808610950394808603958685111561008a57146125d6579082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b505091500490565b818102918082840414821517156125f757505060601c90565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff910981811082019003908160601c156126385763ae47f7025f526004601cfd5b60601c9060a01b0190565b9190811561269b5773ffffffffffffffffffffffffffffffffffffffff9060601b921691828202918383831191840414161561268e57611d949261268992820391612358565b612829565b63f5c787f15f526004601cfd5b505090565b9091801561270b5773ffffffffffffffffffffffffffffffffffffffff809360601b9216808202816126d284836121e5565b146126f3575b50906106c96126e792846121e5565b80820615159104011690565b83018381106126d857915061270792612358565b1690565b50905090565b919073ffffffffffffffffffffffffffffffffffffffff82116127845773ffffffffffffffffffffffffffffffffffffffff9160601b908082061515910401915b1690808211156127775773ffffffffffffffffffffffffffffffffffffffff91031690565b634323a5555f526004601cfd5b61279c816c010000000000000000000000008461253f565b91811561195a576c0100000000000000000000000090096127d4575b73ffffffffffffffffffffffffffffffffffffffff9091612752565b600101806127b8575f80fd5b611d94926126899273ffffffffffffffffffffffffffffffffffffffff919082821161281a576128129160601b6121e5565b915b166100f4565b61282391612486565b91612814565b9073ffffffffffffffffffffffffffffffffffffffff821691820361284a57565b7f93dafdf1000000000000000000000000000000000000000000000000000000005f5260045ffdfea26469706673582212208d022e53bd8376943d1cc048f1f7c87d1c3c530557938886360e9d668cb368c764736f6c634300081e0033
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in ETH
0
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.