Source Code
Overview
ETH Balance
0 ETH
ETH Value
$0.00View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Cross-Chain Transactions
Loading...
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.
Contract Source Code Verified (Exact Match)
Contract Name:
ALMGetters
Compiler Version
v0.8.26+commit.8a97fa7a
Optimization Enabled:
Yes with 1 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.26;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {PositionKey} from "@uniswap/v3-periphery/contracts/libraries/PositionKey.sol";
import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import {PropMath} from "src/libraries/PropMath.sol";
import {PriceLib} from "src/libraries/PriceLib.sol";
import {IEverlongALM} from "src/interfaces/core/alm/IEverlongALM.sol";
import {IAsset} from "src/interfaces/utils/tokens/IAsset.sol";
import {ALMLib} from "src/core/alm/library/ALMLib.sol";
library EverlongALMStorageLib {
// keccak256(abi.encode(uint(keccak256("openzeppelin.storage.EverlongALM")) - 1)) & ~bytes32(uint(0xff))
bytes32 internal constant EVERLONG_ALM_STORAGE_LOC = 0xb4801203179a1f53d2a89513756c4fddeb24d0f949ce9fc7cf03114c341dc500;
uint256 internal constant MANAGER_SLOT = 5;
uint256 internal constant PENDING_MANAGER_SLOT = 6;
uint256 internal constant REBALANCE_DELEGATE_SLOT = 7;
uint256 internal constant DEPOSIT_DELEGATE_SLOT = 8;
uint256 internal constant MAX_TOTAL_SUPPLY_SLOT = 9;
uint256 internal constant ACCRUED_PROTOCOL_FEES_SLOT = 10;
uint256 internal constant PARAMS_SLOT = 11;
uint256 internal constant RANGE_SLOT = 12;
uint256 internal constant RATIO_SLOT = 13;
uint256 internal constant SWAPPER_DATA_SLOT = 14;
uint256 internal constant GETTERS_SLOT = 15;
// PARAMS_SLOT bit offsets
uint256 internal constant PROTOCOL_FEE_OFFSET = 32;
uint256 internal constant PENDING_PROTOCOL_FEE_OFFSET = 56;
uint256 internal constant WIDE_RANGE_WEIGHT_OFFSET = 80;
uint256 internal constant BASE_THRESHOLD_OFFSET = 104;
uint256 internal constant LIMIT_THRESHOLD_OFFSET = 128;
uint256 internal constant WIDE_THRESHOLD_OFFSET = 152;
uint256 internal constant MIN_TICK_MOVE_OFFSET = 176;
uint256 internal constant TICK_SPACING_OFFSET = 200;
uint256 internal constant MAX_TWAP_DEVIATION_OFFSET = 224;
// RANGE_SLOT bit offsets
uint256 internal constant TWAP_DURATION_OFFSET = 0;
uint256 internal constant WIDE_LOWER_OFFSET = 32;
uint256 internal constant WIDE_UPPER_OFFSET = 56;
uint256 internal constant BASE_LOWER_OFFSET = 80;
uint256 internal constant BASE_UPPER_OFFSET = 104;
uint256 internal constant LIMIT_LOWER_OFFSET = 128;
uint256 internal constant LIMIT_UPPER_OFFSET = 152;
uint256 internal constant LAST_TICK_OFFSET = 176;
uint256 internal constant LAST_TIMESTAMP_OFFSET = 200;
// RATIO_SLOT bit offsets
uint256 internal constant MAX_TICK_OFFSET = 0;
uint256 internal constant SWAP_DEVIATION_THRESHOLD_OFFSET = 24;
uint256 internal constant RATIO_DEVIATION_THRESHOLD_OFFSET = 48;
uint256 internal constant REBALANCE_DELEGATE_COOLDOWN_OFFSET = 72;
uint256 internal constant LAST_RATIO_DEV_UPDATE_TIMESTAMP_OFFSET = 96;
uint256 internal constant MAX_RATIO_DEV_THRESHOLD_INCREASE_OFFSET = 136;
function managerSlot() internal pure returns (bytes32) {
return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + MANAGER_SLOT);
}
function pendingManagerSlot() internal pure returns (bytes32) {
return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + PENDING_MANAGER_SLOT);
}
function rebalanceDelegateSlot() internal pure returns (bytes32) {
return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + REBALANCE_DELEGATE_SLOT);
}
function depositDelegateSlot() internal pure returns (bytes32) {
return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + DEPOSIT_DELEGATE_SLOT);
}
function maxTotalSupplySlot() internal pure returns (bytes32) {
return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + MAX_TOTAL_SUPPLY_SLOT);
}
function accruedProtocolFeesSlot() internal pure returns (bytes32) {
return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + ACCRUED_PROTOCOL_FEES_SLOT);
}
function paramsSlot() internal pure returns (bytes32) {
return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + PARAMS_SLOT);
}
function rangeSlot() internal pure returns (bytes32) {
return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + RANGE_SLOT);
}
function ratioSlot() internal pure returns (bytes32) {
return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + RATIO_SLOT);
}
function swapperDataSlot() internal pure returns (bytes32) {
return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + SWAPPER_DATA_SLOT);
}
function gettersSlot() internal pure returns (bytes32) {
return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + GETTERS_SLOT);
}
}
interface IALMGetters {
error EV_PeriodNotElapsed();
error EV_TickNotMoved();
error EV_PriceOutOfBounds();
error EV_TwapPriceDeviation();
error EV_SwapSlippageExceeded(uint256 receivedValue, uint256 sentValue);
error EV_InsufficientSwapOutput(uint256 actual, uint256 required);
error EV_RatioDeviationExceeded(uint256 tokenInValue, uint256 tokenOutValue);
function getTotalAmounts(bool roundUp) external view returns (uint256 total0, uint256 total1);
function getPositionAmounts(int24 tickLower, int24 tickUpper, bool roundUp) external view returns (uint256 amount0, uint256 amount1);
function checkCanRebalance() external view;
function checkPriceNearTwap() external view;
function getTwap() external view returns (int24);
function checkMaxSlippageAndRatioDeviation(
IEverlongALM.ExternalRebalanceParams memory params,
uint256 tokenOutBalanceBefore,
address tokenIn,
address tokenOut,
uint256 sentPrice,
uint256 receivedPrice
) external view;
}
contract ALMGetters is IALMGetters {
using PriceLib for uint256;
IEverlongALM immutable public alm;
IUniswapV3Pool immutable public pool;
uint24 constant HUNDRED_PERCENT = 1e6;
constructor (address _alm, address _pool) {
alm = IEverlongALM(_alm);
/// @dev Assumes pool never changes
pool = IUniswapV3Pool(_pool);
}
// ─── extSloads helpers ───────────────────────────────────────────
function _loadSlot(bytes32 slot) private view returns (uint256 word) {
bytes32[] memory slots = new bytes32[](1);
slots[0] = slot;
word = uint256(alm.extSloads(slots)[0]);
}
function _loadCoreSlots() private view returns (uint256 params, uint256 ranges, uint256 ratios) {
bytes32[] memory slots = new bytes32[](3);
slots[0] = EverlongALMStorageLib.paramsSlot();
slots[1] = EverlongALMStorageLib.rangeSlot();
slots[2] = EverlongALMStorageLib.ratioSlot();
bytes32[] memory r = alm.extSloads(slots);
params = uint256(r[0]);
ranges = uint256(r[1]);
ratios = uint256(r[2]);
}
function _loadParams() private view returns (uint256) {
return _loadSlot(EverlongALMStorageLib.paramsSlot());
}
function _loadRange() private view returns (uint256) {
return _loadSlot(EverlongALMStorageLib.rangeSlot());
}
function _loadRatios() private view returns (uint256) {
return _loadSlot(EverlongALMStorageLib.ratioSlot());
}
function _decodeUint24(uint256 word, uint256 offset) private pure returns (uint24) {
return uint24(word >> offset);
}
function _decodeInt24(uint256 word, uint256 offset) private pure returns (int24) {
return int24(uint24(word >> offset));
}
function getters() public view returns (address) {
return address(uint160(_loadSlot(EverlongALMStorageLib.gettersSlot())));
}
function isSwapperWhitelisted(address swapper) public view returns (bool) {
bytes32[] memory slots = new bytes32[](1);
slots[0] = keccak256(abi.encode(swapper, EverlongALMStorageLib.swapperDataSlot()));
return uint256(alm.extSloads(slots)[0]) != 0;
}
// ─── extSloads-backed getters ─────────────────────────────────────
function manager() public view returns (address) {
return address(uint160(_loadSlot(EverlongALMStorageLib.managerSlot())));
}
function pendingManager() public view returns (address) {
return address(uint160(_loadSlot(EverlongALMStorageLib.pendingManagerSlot())));
}
function rebalanceDelegate() public view returns (address) {
return address(uint160(_loadSlot(EverlongALMStorageLib.rebalanceDelegateSlot())));
}
function depositDelegate() public view returns (address) {
return address(uint160(_loadSlot(EverlongALMStorageLib.depositDelegateSlot())));
}
function maxTotalSupply() public view returns (uint256) {
return _loadSlot(EverlongALMStorageLib.maxTotalSupplySlot());
}
function accruedProtocolFees0() public view returns (uint128) {
uint256 word = _loadSlot(EverlongALMStorageLib.accruedProtocolFeesSlot());
return uint128(word);
}
function accruedProtocolFees1() public view returns (uint128) {
uint256 word = _loadSlot(EverlongALMStorageLib.accruedProtocolFeesSlot());
return uint128(word >> 128);
}
function period() public view returns (uint32) {
return uint32(_loadParams());
}
function protocolFee() public view returns (uint24) {
return _decodeUint24(_loadParams(), EverlongALMStorageLib.PROTOCOL_FEE_OFFSET);
}
function pendingProtocolFee() public view returns (uint24) {
uint24 pendingProtocolFeePlusOne = _decodeUint24(_loadParams(), EverlongALMStorageLib.PENDING_PROTOCOL_FEE_OFFSET);
return pendingProtocolFeePlusOne == 0 ? 0 : pendingProtocolFeePlusOne - 1;
}
function wideRangeWeight() public view returns (uint24) {
return _decodeUint24(_loadParams(), EverlongALMStorageLib.WIDE_RANGE_WEIGHT_OFFSET);
}
function baseThreshold() public view returns (int24) {
return _decodeInt24(_loadParams(), EverlongALMStorageLib.BASE_THRESHOLD_OFFSET);
}
function limitThreshold() public view returns (int24) {
return _decodeInt24(_loadParams(), EverlongALMStorageLib.LIMIT_THRESHOLD_OFFSET);
}
function wideThreshold() public view returns (int24) {
return _decodeInt24(_loadParams(), EverlongALMStorageLib.WIDE_THRESHOLD_OFFSET);
}
function minTickMove() public view returns (int24) {
return _decodeInt24(_loadParams(), EverlongALMStorageLib.MIN_TICK_MOVE_OFFSET);
}
function tickSpacing() public view returns (int24) {
return _decodeInt24(_loadParams(), EverlongALMStorageLib.TICK_SPACING_OFFSET);
}
function maxTwapDeviation() public view returns (int24) {
return _decodeInt24(_loadParams(), EverlongALMStorageLib.MAX_TWAP_DEVIATION_OFFSET);
}
function twapDuration() public view returns (uint32) {
return uint32(_loadRange() >> EverlongALMStorageLib.TWAP_DURATION_OFFSET);
}
function lastTick() public view returns (int24) {
return _decodeInt24(_loadRange(), EverlongALMStorageLib.LAST_TICK_OFFSET);
}
function lastTimestamp() public view returns (uint40) {
return uint40(_loadRange() >> EverlongALMStorageLib.LAST_TIMESTAMP_OFFSET);
}
function swapDeviationThreshold() public view returns (uint24) {
return _decodeUint24(_loadRatios(), EverlongALMStorageLib.SWAP_DEVIATION_THRESHOLD_OFFSET);
}
function ratioDeviationThreshold() public view returns (uint24) {
return _decodeUint24(_loadRatios(), EverlongALMStorageLib.RATIO_DEVIATION_THRESHOLD_OFFSET);
}
function rebalanceDelegateCooldown() public view returns (uint24) {
return _decodeUint24(_loadRatios(), EverlongALMStorageLib.REBALANCE_DELEGATE_COOLDOWN_OFFSET);
}
function lastRatioDeviationThresholdUpdateTimestamp() public view returns (uint40) {
return uint40(_loadRatios() >> EverlongALMStorageLib.LAST_RATIO_DEV_UPDATE_TIMESTAMP_OFFSET);
}
function maxRatioDeviationThresholdIncrease() public view returns (uint24) {
return _decodeUint24(_loadRatios(), EverlongALMStorageLib.MAX_RATIO_DEV_THRESHOLD_INCREASE_OFFSET);
}
function getTotalAmounts(bool roundUp) public view override returns (uint256 total0, uint256 total1) {
int24[2][3] memory positions = alm.getPositions();
(uint256 wideAmount0, uint256 wideAmount1) = getPositionAmounts(positions[0][0], positions[0][1], roundUp);
(uint256 baseAmount0, uint256 baseAmount1) = getPositionAmounts(positions[1][0], positions[1][1], roundUp);
(uint256 limitAmount0, uint256 limitAmount1) = getPositionAmounts(positions[2][0], positions[2][1], roundUp);
total0 = alm.getBalance0() + wideAmount0 + baseAmount0 + limitAmount0;
total1 = alm.getBalance1() + wideAmount1 + baseAmount1 + limitAmount1;
}
/**
* @notice Amounts of token0 and token1 held in vault's position. Includes
* owed fees but excludes the proportion of fees that will be paid to the
* protocol. Doesn't include fees accrued since last poke.
*/
function getPositionAmounts(int24 tickLower, int24 tickUpper, bool roundUp)
public
view
returns (uint256 amount0, uint256 amount1)
{
(uint128 liquidity,,, uint128 tokensOwed0, uint128 tokensOwed1) = _position(tickLower, tickUpper);
(amount0, amount1) = ALMLib._amountsForLiquidity(address(pool), tickLower, tickUpper, liquidity, roundUp);
// Subtract protocol and manager fees
uint256 paramsWord = _loadParams();
uint24 _protocolFee = _decodeUint24(paramsWord, EverlongALMStorageLib.PROTOCOL_FEE_OFFSET);
uint128 protocolFees0 = tokensOwed0 * _protocolFee / HUNDRED_PERCENT;
uint128 protocolFees1 = tokensOwed1 * _protocolFee / HUNDRED_PERCENT;
amount0 += tokensOwed0 - protocolFees0;
amount1 += tokensOwed1 - protocolFees1;
}
function checkCanRebalance() public view {
checkPriceNearTwap();
(uint256 paramsWord, uint256 rangesWord, uint256 ratiosWord) = _loadCoreSlots();
uint40 _lastTimestamp = uint40(rangesWord >> EverlongALMStorageLib.LAST_TIMESTAMP_OFFSET);
int24 lastTick = _decodeInt24(rangesWord, EverlongALMStorageLib.LAST_TICK_OFFSET);
int24 baseThreshold = _decodeInt24(paramsWord, EverlongALMStorageLib.BASE_THRESHOLD_OFFSET);
int24 limitThreshold = _decodeInt24(paramsWord, EverlongALMStorageLib.LIMIT_THRESHOLD_OFFSET);
int24 tickSpacing = _decodeInt24(paramsWord, EverlongALMStorageLib.TICK_SPACING_OFFSET);
uint32 _period = uint32(paramsWord);
int24 minTickMove_ = _decodeInt24(paramsWord, EverlongALMStorageLib.MIN_TICK_MOVE_OFFSET);
// check enough time has passed
if (block.timestamp < (_lastTimestamp + _period)) revert EV_PeriodNotElapsed();
// check price has moved enough
(, int24 tick,,,,,) = pool.slot0();
int24 tickMove = tick > lastTick ? tick - lastTick : lastTick - tick;
if (_lastTimestamp != 0 && tickMove < minTickMove_) revert EV_TickNotMoved();
// check price not too close to boundary
int24 maxThreshold = baseThreshold > limitThreshold ? baseThreshold : limitThreshold;
if (
!(
tick >= TickMath.MIN_TICK + maxThreshold + tickSpacing
&& tick <= TickMath.MAX_TICK - maxThreshold - tickSpacing
)
) revert EV_PriceOutOfBounds();
}
function checkPriceNearTwap() public view {
(, int24 tick,,,,,) = pool.slot0();
int24 twap = getTwap();
int24 twapDeviation = tick > twap ? tick - twap : twap - tick;
if (twapDeviation > maxTwapDeviation()) revert EV_TwapPriceDeviation();
}
/// @dev Fetches time-weighted average price in ticks from Uniswap pool.
function getTwap() public view returns (int24) {
uint32 _twapDuration = twapDuration();
uint32[] memory secondsAgo = new uint32[](2);
secondsAgo[0] = _twapDuration;
secondsAgo[1] = 0;
(int56[] memory tickCumulatives,) = pool.observe(secondsAgo);
return int24((tickCumulatives[1] - tickCumulatives[0]) / int56(uint56((_twapDuration))));
}
function checkMaxSlippageAndRatioDeviation(
IEverlongALM.ExternalRebalanceParams memory params,
uint256 tokenOutBalanceBefore,
address tokenIn,
address tokenOut,
uint256 sentPrice,
uint256 receivedPrice
) external view {
uint256 tokenOutBalanceAfter = params.isZeroForOne ? alm.getBalance1() : alm.getBalance0();
uint8 tokenInDecimals = IAsset(tokenIn).decimals();
uint8 tokenOutDecimals = IAsset(tokenOut).decimals();
uint256 ratiosWord = _loadRatios();
uint24 _swapDeviationThreshold = _decodeUint24(ratiosWord, EverlongALMStorageLib.SWAP_DEVIATION_THRESHOLD_OFFSET);
uint24 _ratioDeviationThreshold = _decodeUint24(ratiosWord, EverlongALMStorageLib.RATIO_DEVIATION_THRESHOLD_OFFSET);
{
uint256 amountOut = tokenOutBalanceAfter - tokenOutBalanceBefore;
uint256 sentValue = _assetValue(params.sentAmount, sentPrice, tokenInDecimals);
{
uint256 receivedValue = _assetValue(amountOut, receivedPrice, tokenOutDecimals);
if (receivedValue < sentValue * (HUNDRED_PERCENT - _swapDeviationThreshold) / HUNDRED_PERCENT) {
revert EV_SwapSlippageExceeded(receivedValue, sentValue);
}
}
if (amountOut < params.minRebalanceOut) {
revert EV_InsufficientSwapOutput(amountOut, params.minRebalanceOut);
}
}
(uint256 total0, uint256 total1) = alm.getTotalAmounts();
uint256 totalTokenIn = params.isZeroForOne ? total0 : total1;
uint256 totalTokenOut = params.isZeroForOne ? total1 : total0;
uint256 tokenInBalanceValue = _assetValue(totalTokenIn, sentPrice, tokenInDecimals);
uint256 tokenOutBalanceValue = _assetValue(totalTokenOut, receivedPrice, tokenOutDecimals);
uint256 maxDelta = Math.min(tokenInBalanceValue, tokenOutBalanceValue) * _ratioDeviationThreshold / HUNDRED_PERCENT;
if (!PropMath._isApproxEqAbs(tokenInBalanceValue, tokenOutBalanceValue, maxDelta)) {
revert EV_RatioDeviationExceeded(tokenInBalanceValue, tokenOutBalanceValue);
}
}
/// @dev Wrapper around `IUniswapV3Pool.positions()`.
function _position(int24 tickLower, int24 tickUpper)
internal
view
returns (uint128, uint256, uint256, uint128, uint128)
{
bytes32 positionKey = PositionKey.compute(address(alm), tickLower, tickUpper);
return pool.positions(positionKey);
}
/// @dev Returned in WAD
function _assetValue(uint256 amount, uint256 price, uint8 decimals) internal pure returns (uint256) {
return amount.convertToValue(price, decimals);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// 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; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
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 for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the 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.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // 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 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10**64) {
value /= 10**64;
result += 64;
}
if (value >= 10**32) {
value /= 10**32;
result += 32;
}
if (value >= 10**16) {
value /= 10**16;
result += 16;
}
if (value >= 10**8) {
value /= 10**8;
result += 8;
}
if (value >= 10**4) {
value /= 10**4;
result += 4;
}
if (value >= 10**2) {
value /= 10**2;
result += 2;
}
if (value >= 10**1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
}
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import {IUniswapV3PoolImmutables} from './pool/IUniswapV3PoolImmutables.sol';
import {IUniswapV3PoolState} from './pool/IUniswapV3PoolState.sol';
import {IUniswapV3PoolDerivedState} from './pool/IUniswapV3PoolDerivedState.sol';
import {IUniswapV3PoolActions} from './pool/IUniswapV3PoolActions.sol';
import {IUniswapV3PoolOwnerActions} from './pool/IUniswapV3PoolOwnerActions.sol';
import {IUniswapV3PoolErrors} from './pool/IUniswapV3PoolErrors.sol';
import {IUniswapV3PoolEvents} from './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolErrors,
IUniswapV3PoolEvents
{
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
library PositionKey {
/// @dev Returns the key of the position in the core library
function compute(
address owner,
int24 tickLower,
int24 tickUpper
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(owner, tickLower, tickUpper));
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @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 {
error T();
error R();
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @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 ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
if (absTick > uint256(int256(MAX_TICK))) revert T();
uint256 ratio = absTick & 0x1 != 0
? 0xfffcb933bd6fad37aa2d162d1a594001
: 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// 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 getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
// second inequality must be < because the price can never reach the price at the max tick
if (!(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO)) revert R();
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
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; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
library PropMath {
uint256 internal constant DECIMAL_PRECISION = 1e18;
/* Precision for Nominal ICR (independent of price). Rationale for the value:
*
* - Making it “too high” could lead to overflows.
* - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division.
*
* This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39,
* and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator.
*
*/
uint256 internal constant NICR_PRECISION = 1e20;
function _min(uint256 _a, uint256 _b) internal pure returns (uint256) {
return (_a < _b) ? _a : _b;
}
function _max(uint256 _a, uint256 _b) internal pure returns (uint256) {
return (_a >= _b) ? _a : _b;
}
/*
* Multiply two decimal numbers and use normal rounding rules:
* -round product up if 19'th mantissa digit >= 5
* -round product down if 19'th mantissa digit < 5
*
* Used only inside the exponentiation, _decPow().
*/
function decMul(uint256 x, uint256 y) internal pure returns (uint256 decProd) {
uint256 prod_xy = x * y;
decProd = (prod_xy + (DECIMAL_PRECISION / 2)) / DECIMAL_PRECISION;
}
/*
* _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n.
*
* Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity.
*
* Called by two functions that represent time in units of minutes:
* 1) PositionManager._calcDecayedBaseRate
* 2) CommunityIssuance._getCumulativeIssuanceFraction
*
* The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals
* "minutes in 1000 years": 60 * 24 * 365 * 1000
*
* If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be
* negligibly different from just passing the cap, since:
*
* In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years
* In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible
*/
function _decPow(uint256 _base, uint256 _minutes) internal pure returns (uint256) {
if (_minutes > 525600000) {
_minutes = 525600000;
} // cap to avoid overflow
if (_minutes == 0) {
return DECIMAL_PRECISION;
}
uint256 y = DECIMAL_PRECISION;
uint256 x = _base;
uint256 n = _minutes;
// Exponentiation-by-squaring
while (n > 1) {
if (n % 2 == 0) {
x = decMul(x, x);
n = n / 2;
} else {
// if (n % 2 != 0)
y = decMul(x, y);
x = decMul(x, x);
n = (n - 1) / 2;
}
}
return decMul(x, y);
}
function _getAbsoluteDifference(uint256 _a, uint256 _b) internal pure returns (uint256) {
return (_a >= _b) ? _a - _b : _b - _a;
}
function _computeNominalCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {
if (_debt > 0) {
return (_coll * NICR_PRECISION) / _debt;
}
// Return the maximal value for uint256 if the Position has a debt of 0. Represents "infinite" CR.
else {
// if (_debt == 0)
return 2 ** 256 - 1;
}
}
function _computeCR(uint256 _coll, uint256 _debt, uint256 _price) internal pure returns (uint256) {
if (_debt > 0) {
uint256 newCollRatio = (_coll * _price) / _debt;
return newCollRatio;
}
// Return the maximal value for uint256 if the Position has a debt of 0. Represents "infinite" CR.
else {
// if (_debt == 0)
return 2 ** 256 - 1;
}
}
function _computeCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {
if (_debt > 0) {
uint256 newCollRatio = (_coll) / _debt;
return newCollRatio;
}
// Return the maximal value for uint256 if the Position has a debt of 0. Represents "infinite" CR.
else {
// if (_debt == 0)
return 2 ** 256 - 1;
}
}
function _isApproxEqAbs(uint256 a, uint256 b, uint256 tolerance) internal pure returns (bool) {
return a > b ? (a - b) <= tolerance : (b - a) <= tolerance;
}
function _isWithinToleranceAbove(
uint256 a,
uint256 b,
uint256 tolerance
) internal pure returns (bool) {
if (a < b) return false;
return (a - b) <= tolerance;
}
function _isWithinToleranceBelow(
uint256 a,
uint256 b,
uint256 tolerance
) internal pure returns (bool) {
if (a > b) return false;
return (b - a) <= tolerance;
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
library PriceLib {
using Math for uint;
// WAD adjusted result
function convertToValue(uint amount, uint price, uint8 decimals) internal pure returns (uint) {
return amount * price / 10 ** decimals;
}
function convertToAmount(uint amountInUsd, uint collPrice, uint8 collDecimals, Math.Rounding rounding) internal pure returns (uint) {
if (collPrice == 0 || amountInUsd == 0) {
return 0;
}
return amountInUsd.mulDiv(10 ** collDecimals, collPrice, rounding);
}
// Coll decimal adjust amount result
function convertAssetsToCollAmount(uint assets, uint collPrice, uint debtTokenPrice, uint8 vaultDecimals, uint8 collDecimals, Math.Rounding rounding) internal pure returns (uint) {
uint assetsUsdValue = assets.mulDiv(debtTokenPrice, 10 ** vaultDecimals, rounding);
if (collPrice != 0) {
return convertToAmount(assetsUsdValue, collPrice, collDecimals, rounding);
} else {
return 0;
}
}
function convertCollAmountToAssets(uint collAmount, uint collPrice, uint debtTokenPrice, uint8 vaultDecimals, uint8 collDecimals) internal pure returns (uint) {
uint collUsdValue = collAmount * collPrice / 10 ** collDecimals;
if (debtTokenPrice != 0) {
return collUsdValue * 10 ** vaultDecimals / debtTokenPrice;
} else {
return 0;
}
}
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.26;
import {IERC20, SafeERC20} from "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {IPriceFeed} from "src/interfaces/core/oracles/IPriceFeed.sol";
import {IALMGetters} from "src/core/alm/getters/ALMGetters.sol";
import {SwappersLib} from "src/libraries/SwappersLib.sol";
interface IEverlongALM {
/**
* @param pool Underlying Uniswap V3 pool address
* @param manager Address of manager who can set parameters and call rebalance
* @param rebalanceDelegate Address of an additional wallet that can call rebalance
* @param maxTotalSupply Cap on the total supply of vault shares
* @param wideRangeWeight Proportion of liquidity in wide range multiplied by 1e6
* @param wideThreshold Half of the wide order width in ticks
* @param baseThreshold Half of the base order width in ticks
* @param limitThreshold Limit order width in ticks
* @param period Can only rebalance if this length of time (in seconds) has passed
* @param minTickMove Can only rebalance if price has moved at least this much
* @param maxTwapDeviation Max deviation (in ticks) from the TWAP during rebalance or deposit
* @param twapDuration TWAP duration in seconds for maxTwapDeviation check
* @param protocolFee % Fee charged to cover protocol costs, in BP
* @param name name of the vault to be created
* @param symbol symbol of the vault to be created
*/
struct VaultParams {
address owner;
address pool;
address priceFeed;
address manager;
address rebalanceDelegate;
address depositDelegate;
uint24 protocolFee; // In 1e6
uint256 maxTotalSupply;
uint24 wideRangeWeight; // In 1e6
int24 wideThreshold;
int24 baseThreshold;
int24 limitThreshold;
uint32 period;
int24 minTickMove;
int24 maxTwapDeviation;
uint32 twapDuration;
string name;
string symbol;
uint24 swapDeviationThreshold; // In 1e6
uint24 ratioDeviationThreshold; // In 1e6
uint24 rebalanceDelegateCooldown; // In seconds
uint24 maxRatioDeviationThresholdIncrease; // In 1e6
address[] initialWhitelistedSwappers;
address getters;
}
struct EverlongALMStorage {
address owner;
IUniswapV3Pool pool;
IPriceFeed priceFeed;
IERC20 token0;
IERC20 token1;
address manager;
address pendingManager;
address rebalanceDelegate;
address depositDelegate;
uint256 maxTotalSupply;
uint128 accruedProtocolFees0;
uint128 accruedProtocolFees1;
uint32 period;
uint24 protocolFee;
uint24 pendingProtocolFee;
uint24 wideRangeWeight;
int24 baseThreshold;
int24 limitThreshold;
int24 wideThreshold;
int24 minTickMove;
int24 tickSpacing;
int24 maxTwapDeviation;
uint32 twapDuration;
int24 wideLower;
int24 wideUpper;
int24 baseLower;
int24 baseUpper;
int24 limitLower;
int24 limitUpper;
int24 lastTick;
uint40 lastTimestamp;
int24 maxTick;
uint24 swapDeviationThreshold; // In 1e6
uint24 ratioDeviationThreshold; // In 1e6
uint24 rebalanceDelegateCooldown; // In seconds
uint40 lastRatioDeviationThresholdUpdateTimestamp;
uint24 maxRatioDeviationThresholdIncrease; // In 1e6
SwappersLib.SwapperData swapperData;
IALMGetters getters;
}
struct BurnContext {
uint256 wideAmount0;
uint256 wideAmount1;
uint256 baseAmount0;
uint256 baseAmount1;
uint256 limitAmount0;
uint256 limitAmount1;
}
struct ExternalRebalanceParams {
bool isZeroForOne;
uint256 sentAmount;
address swapper;
bytes payload;
uint256 minRebalanceOut;
}
function deposit(uint256, uint256, uint256, uint256, address) external returns (uint256, uint256, uint256);
function withdraw(uint256, uint256, uint256, address) external returns (uint256, uint256);
function extSloads(bytes32[] memory slots) external view returns (bytes32[] memory values);
function getTotalAmounts() external view returns (uint256, uint256);
function getBalance0() external view returns (uint256);
function getBalance1() external view returns (uint256);
function rebalance() external;
// state variables
function pool() external view returns (IUniswapV3Pool);
function protocolFee() external view returns (uint24);
function getPositions() external view returns (int24[2][3] memory);
function token0() external view returns (address);
function token1() external view returns (address);
function totalSupply() external view returns (uint256);
function balanceOf(address) external view returns (uint256);
event Deposit(address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1);
event Withdraw(address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1);
event CollectFees(
uint256 feesToVault0,
uint256 feesToVault1,
uint256 feesToProtocol0,
uint256 feesToProtocol1
);
event Snapshot(int24 tick, uint256 totalAmount0, uint256 totalAmount1, uint256 totalSupply);
event CollectProtocol(uint256 amount0, uint256 amount1);
event UpdateManager(address manager);
event UpdatePendingManager(address manager);
event UpdateRebalanceDelegate(address delegate);
event UpdateDepositDelegate(address delegate);
event UpdateProtocolFee(uint24 protocolFee);
event UpdateBaseThreshold(int24 threshold);
event UpdateLimitThreshold(int24 threshold);
event UpdateWideRangeWeight(uint24 weight);
event UpdateWideThreshold(int24 threshold);
event UpdatePeriod(uint32 period);
event UpdateMinTickMove(int24 minTickMove);
event UpdateMaxTwapDeviation(int24 maxTwapDeviation);
event UpdateTwapDuration(uint32 twapDuration);
event UpdateMaxTotalSupply(uint256 maxTotalSupply);
event UpdateSwapDeviationThreshold(uint24 swapDeviationThreshold);
event UpdateRatioDeviationThreshold(uint24 ratioDeviationThreshold);
event UpdateRebalanceDelegateCooldown(uint24 rebalanceDelegateCooldown);
event UpdateMaxRatioDeviationThresholdIncrease(uint24 maxRatioDeviationThresholdIncrease);
event UpdateGetters(address getters);
// Errors
error EV_ZeroAddress();
error EV_WideRangeWeight();
error EV_MinTickMove();
error EV_MaxTwapDeviation();
error EV_TwapDuration();
error EV_ThresholdsCannotBeSame();
error EV_ThresholdNotPositive();
error EV_ThresholdNotMultipleOfTickSpacing();
error EV_NotDepositDelegate();
error EV_ZeroDepositAmount();
error EV_InvalidRecipient();
error EV_ZeroShares();
error EV_Amount0Min();
error EV_Amount1Min();
error EV_MaxTotalSupply();
error EV_NotManagerOrRebalanceDelegate();
error EV_NotPool();
error EV_NotGovernance();
error EV_ProtocolFee();
error EV_ProtocolFeeTooHigh();
error EV_NotManager();
error EV_SweepToken();
error EV_NotPendingManager();
error EV_InsufficientBalance(uint256 available, uint256 required);
error EV_SwapDeviationThreshold();
error EV_RatioDeviationThreshold();
error EV_RebalanceDelegateCooldown();
error EV_MaxRatioDeviationThresholdIncrease();
error EV_RatioDeviationThresholdIncreaseExceeded(uint24 proposedThreshold, uint256 maxAllowedThreshold);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
interface IAsset is IERC20 {
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.26;
import {LiquidityAmounts} from "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol";
import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import {SqrtPriceMath} from "@uniswap/v3-core/contracts/libraries/SqrtPriceMath.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
library ALMLib {
uint24 constant MINIMUM_LIQUIDITY = 1e3;
error EV_ZeroCross();
/// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`.
function _liquidityForAmounts(
int24 tickLower,
int24 tickUpper,
uint256 amount0,
uint256 amount1,
uint160 sqrtRatioX96
) external pure returns (uint128) {
return LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amount0,
amount1
);
}
/**
* @notice Computes the token0 and token1 value for a given amount of liquidity,
* respecting rounding for deposit/withdraw to align with uniswap's approach when providing/removing liquidity.
*/
function _amountsForLiquidity(address pool, int24 tickLower, int24 tickUpper, uint128 liquidity, bool roundUp)
external
view
returns (uint256 amount0, uint256 amount1)
{
(uint160 sqrtRatioX96,,,,,,) = IUniswapV3Pool(pool).slot0();
uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
if (sqrtRatioAX96 > sqrtRatioBX96) {
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
}
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = SqrtPriceMath.getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = SqrtPriceMath.getAmount0Delta(sqrtRatioX96, sqrtRatioBX96, liquidity, roundUp);
amount1 = SqrtPriceMath.getAmount1Delta(sqrtRatioAX96, sqrtRatioX96, liquidity, roundUp);
} else {
amount1 = SqrtPriceMath.getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp);
}
}
/// @dev Calculates the largest possible `amount0` and `amount1` such that
/// they're in the same proportion as total amounts, but not greater than
/// `amount0Desired` and `amount1Desired` respectively.
function _calcSharesAndAmounts(
uint256 _totalSupply,
uint256 total0,
uint256 total1,
uint256 amount0Desired,
uint256 amount1Desired
)
external
view
returns (uint256 shares, uint256 amount0, uint256 amount1)
{
// If total supply > 0, vault can't be empty
assert(_totalSupply == 0 || total0 > 0 || total1 > 0);
if (_totalSupply == 0) {
// For first deposit, just use the amounts desired
amount0 = amount0Desired;
amount1 = amount1Desired;
shares = (amount0 > amount1 ? amount0 : amount1) - MINIMUM_LIQUIDITY;
} else if (total0 == 0) {
amount1 = amount1Desired;
shares = amount1 * _totalSupply / total1;
} else if (total1 == 0) {
amount0 = amount0Desired;
shares = amount0 * _totalSupply / total0;
} else {
uint256 cross0 = amount0Desired * total1;
uint256 cross1 = amount1Desired * total0;
uint256 cross = cross0 > cross1 ? cross1 : cross0;
if (cross == 0) revert EV_ZeroCross();
// Round up amounts
amount0 = (cross - 1) / total1 + 1;
amount1 = (cross - 1) / total0 + 1;
shares = cross * _totalSupply / total0 / total1;
}
}
/// @dev Ensures tick is within the maximum range boundaries
function _boundTick(int24 tick, int24 _maxTick) external pure returns (int24) {
if (tick < -_maxTick) {
return -_maxTick;
}
if (tick > _maxTick) {
return _maxTick;
}
return tick;
}
/// @dev Rounds tick down towards negative infinity so that it's a multiple
/// of `tickSpacing`.
function _floor(int24 tick, int24 tickSpacing) external pure returns (int24) {
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) compressed--;
return compressed * tickSpacing;
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// @return tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// @return observationIndex The index of the last oracle observation that was written,
/// @return observationCardinality The current maximum number of observations stored in the pool,
/// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// @return feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
/// @return The liquidity at the current price of the pool
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper
/// @return liquidityNet how much liquidity changes when the pool price crosses the tick,
/// @return feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// @return feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// @return tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// @return secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// @return secondsOutside the seconds spent on the other side of the tick from the current tick,
/// @return initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return liquidity The amount of liquidity in the position,
/// @return feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// @return feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// @return tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// @return tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// @return tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// @return secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// @return initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @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
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Errors emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolErrors {
error LOK();
error TLU();
error TLM();
error TUM();
error AI();
error M0();
error M1();
error AS();
error IIA();
error L();
error F0();
error F1();
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 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 price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IPriceFeed {
struct FeedType {
address spotOracle;
bool isCollVault;
}
event NewOracleRegistered(address token, address chainlinkAggregator, address underlyingDerivative);
event PriceFeedStatusUpdated(address token, address oracle, bool isWorking);
event PriceRecordUpdated(address indexed token, uint256 _price);
event NewCollVaultRegistered(address collVault, bool enable);
event NewSpotOracleRegistered(address token, address spotOracle);
function fetchPrice(address _token) external view returns (uint256);
function getMultiplePrices(address[] memory _tokens) external view returns (uint256[] memory prices);
function setOracle(
address _token,
address _chainlinkOracle,
uint32 _heartbeat,
uint16 _staleThreshold,
address underlyingDerivative
) external;
function whitelistCollateralVault(address _collateralVaultShareToken, bool enable) external;
function setSpotOracle(address _token, address _spotOracle) external;
function MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND() external view returns (uint256);
function CORE() external view returns (address);
function RESPONSE_TIMEOUT() external view returns (uint256);
function TARGET_DIGITS() external view returns (uint256);
function guardian() external view returns (address);
function oracleRecords(
address
)
external
view
returns (
address chainLinkOracle,
uint8 decimals,
uint32 heartbeat,
uint16 staleThreshold,
address underlyingDerivative
);
function isCollVault(address _collateralVaultShareToken) external view returns (bool);
function isStableBPT(address _oracle) external view returns (bool);
function isWeightedBPT(address _oracle) external view returns (bool);
function getSpotOracle(address _token) external view returns (address);
function feedType(address _token) external view returns (FeedType memory);
function owner() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {UtilsLib} from "./UtilsLib.sol";
library SwappersLib {
using UtilsLib for bytes;
error SwapperNotWhitelisted();
event SwapperAdded(address indexed swapRouter, bool status);
struct SwapperData {
mapping(address => bool) whitelistedSwappers;
}
function addWhitelistedSwapper(SwapperData storage self, address _swapRouter, bool status) internal {
self.whitelistedSwappers[_swapRouter] = status;
emit SwapperAdded(_swapRouter, status);
}
function executeSwap(SwapperData storage self, address swapRouter, bytes memory dexCalldata) internal {
if (!self.whitelistedSwappers[swapRouter]) revert SwapperNotWhitelisted();
(bool success, bytes memory retData) = swapRouter.call(dexCalldata);
if (!success) {
retData.bubbleUpRevert();
}
}
}// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; import "../token/ERC20/IERC20.sol";
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol';
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
unchecked {
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
unchecked {
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, 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 amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @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
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
unchecked {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @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 amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
unchecked {
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
}
/// @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,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import {SafeCast} from './SafeCast.sol';
import {FullMath} from './FullMath.sol';
import {UnsafeMath} from './UnsafeMath.sol';
import {FixedPoint96} from './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;
/// @notice Gets the next sqrt price given a delta of token0
/// @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 token0 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of token0 to add or remove from virtual reserves
/// @param add Whether to add or remove the amount of token0
/// @return The price after adding or removing amount, depending on add
function getNextSqrtPriceFromAmount0RoundingUp(
uint160 sqrtPX96,
uint128 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;
if ((product = amount * sqrtPX96) / 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;
// if the product overflows, we know the denominator underflows
// in addition, we must check that the denominator does not underflow
require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);
uint256 denominator = numerator1 - product;
return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
}
}
}
/// @notice Gets the next sqrt price given a delta of token1
/// @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 token1 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of token1 to add, or remove, from virtual reserves
/// @param add Whether to add, or remove, the amount of token1
/// @return The price after adding or removing `amount`
function getNextSqrtPriceFromAmount1RoundingDown(
uint160 sqrtPX96,
uint128 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)
);
require(sqrtPX96 > quotient);
// always fits 160 bits
unchecked {
return uint160(sqrtPX96 - quotient);
}
}
}
/// @notice Gets the next sqrt price given an input amount of token0 or token1
/// @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 token0, or token1, is being swapped in
/// @param zeroForOne Whether the amount in is token0 or token1
/// @return sqrtQX96 The price after adding the input amount to token0 or token1
function getNextSqrtPriceFromInput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountIn,
bool zeroForOne
) internal pure returns (uint160 sqrtQX96) {
require(sqrtPX96 > 0);
require(liquidity > 0);
// 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 token0 or token1
/// @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 token0, or token1, is being swapped out
/// @param zeroForOne Whether the amount out is token0 or token1
/// @return sqrtQX96 The price after removing the output amount of token0 or token1
function getNextSqrtPriceFromOutput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountOut,
bool zeroForOne
) internal pure returns (uint160 sqrtQX96) {
require(sqrtPX96 > 0);
require(liquidity > 0);
// 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 sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up or down
/// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices
function getAmount0Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundUp
) internal pure returns (uint256 amount0) {
unchecked {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;
require(sqrtRatioAX96 > 0);
return
roundUp
? UnsafeMath.divRoundingUp(
FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),
sqrtRatioAX96
)
: FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;
}
}
/// @notice Gets the amount1 delta between two prices
/// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up, or down
/// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices
function getAmount1Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundUp
) internal pure returns (uint256 amount1) {
unchecked {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
roundUp
? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)
: FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
}
/// @notice Helper that gets signed token0 delta
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount0 delta
/// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices
function getAmount0Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
int128 liquidity
) internal pure returns (int256 amount0) {
unchecked {
return
liquidity < 0
? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
: getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
}
}
/// @notice Helper that gets signed token1 delta
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount1 delta
/// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices
function getAmount1Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
int128 liquidity
) internal pure returns (int256 amount1) {
unchecked {
return
liquidity < 0
? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
: getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
library UtilsLib {
error DexCalldataTooShort();
function getSelector(bytes memory data) internal pure returns (bytes4 selector) {
if (data.length < 4) {
revert DexCalldataTooShort();
}
selector = bytes4(data);
}
function bubbleUpRevert(bytes memory reason) internal pure {
assembly {
revert(add(reason, 0x20), mload(reason))
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}// 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; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
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 {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
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 {
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 precoditions 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 < type(uint256).max);
result++;
}
}
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.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: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.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 has unspecified behavior, and must 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 {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}{
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin-upgradeable/contracts/=lib/openzeppelin-contracts-upgradeable/contracts/",
"forge-std/=lib/forge-std/src/",
"@uniswap/v3-core/=lib/v3-core/",
"@uniswap/v3-periphery/=lib/v3-periphery/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"v3-core/=lib/v3-core/contracts/",
"v3-periphery/=lib/v3-periphery/contracts/"
],
"optimizer": {
"enabled": true,
"runs": 1
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "cancun",
"viaIR": false,
"libraries": {
"src/core/alm/getters/ALMGetters.sol": {
"ALMLib": "0x6c4e0f30ee76a1c360387a0504f32c991d46f817"
}
}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"_alm","type":"address"},{"internalType":"address","name":"_pool","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"actual","type":"uint256"},{"internalType":"uint256","name":"required","type":"uint256"}],"name":"EV_InsufficientSwapOutput","type":"error"},{"inputs":[],"name":"EV_PeriodNotElapsed","type":"error"},{"inputs":[],"name":"EV_PriceOutOfBounds","type":"error"},{"inputs":[{"internalType":"uint256","name":"tokenInValue","type":"uint256"},{"internalType":"uint256","name":"tokenOutValue","type":"uint256"}],"name":"EV_RatioDeviationExceeded","type":"error"},{"inputs":[{"internalType":"uint256","name":"receivedValue","type":"uint256"},{"internalType":"uint256","name":"sentValue","type":"uint256"}],"name":"EV_SwapSlippageExceeded","type":"error"},{"inputs":[],"name":"EV_TickNotMoved","type":"error"},{"inputs":[],"name":"EV_TwapPriceDeviation","type":"error"},{"inputs":[],"name":"accruedProtocolFees0","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"accruedProtocolFees1","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"alm","outputs":[{"internalType":"contract IEverlongALM","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"baseThreshold","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"checkCanRebalance","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"bool","name":"isZeroForOne","type":"bool"},{"internalType":"uint256","name":"sentAmount","type":"uint256"},{"internalType":"address","name":"swapper","type":"address"},{"internalType":"bytes","name":"payload","type":"bytes"},{"internalType":"uint256","name":"minRebalanceOut","type":"uint256"}],"internalType":"struct IEverlongALM.ExternalRebalanceParams","name":"params","type":"tuple"},{"internalType":"uint256","name":"tokenOutBalanceBefore","type":"uint256"},{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint256","name":"sentPrice","type":"uint256"},{"internalType":"uint256","name":"receivedPrice","type":"uint256"}],"name":"checkMaxSlippageAndRatioDeviation","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[],"name":"checkPriceNearTwap","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[],"name":"depositDelegate","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"bool","name":"roundUp","type":"bool"}],"name":"getPositionAmounts","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"roundUp","type":"bool"}],"name":"getTotalAmounts","outputs":[{"internalType":"uint256","name":"total0","type":"uint256"},{"internalType":"uint256","name":"total1","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTwap","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getters","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"swapper","type":"address"}],"name":"isSwapperWhitelisted","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastRatioDeviationThresholdUpdateTimestamp","outputs":[{"internalType":"uint40","name":"","type":"uint40"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastTick","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastTimestamp","outputs":[{"internalType":"uint40","name":"","type":"uint40"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"limitThreshold","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"manager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxRatioDeviationThresholdIncrease","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxTotalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxTwapDeviation","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minTickMove","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingProtocolFee","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"period","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pool","outputs":[{"internalType":"contract IUniswapV3Pool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolFee","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ratioDeviationThreshold","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rebalanceDelegate","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rebalanceDelegateCooldown","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"swapDeviationThreshold","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tickSpacing","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"twapDuration","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"wideRangeWeight","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"wideThreshold","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"}]Contract Creation Code
60c0604052348015600e575f80fd5b5060405161237b38038061237b833981016040819052602b91605b565b6001600160a01b039182166080521660a0526087565b80516001600160a01b03811681146056575f80fd5b919050565b5f8060408385031215606b575f80fd5b6072836041565b9150607e602084016041565b90509250929050565b60805160a05161226a6101115f395f81816101c8015281816104210152818161082e015281816109c401528181610bc901526116c401525f818161032f015281816105490152818161062b015281816106ce01528181610db301528181610e380152818161105701528181611233015281816113700152818161152e0152611641015261226a5ff3fe608060405234801561000f575f80fd5b506004361061019f575f3560e01c806316c3e29d146101a357806316f0115b146101c357806319d8ac611461020257806326d89545146102205780632ab4d0521461023d578063345d90e2146102535780633dfa5d871461025d578063466360fc14610265578063479f9c011461028157806347c570fd14610289578063481c6a75146102aa5780634efed314146102b25780635d752a9a146102ba5780635da07868146102c25780636317732e146102ca5780636a37b9d0146102d257806371bd0ea7146102da578063854360ef146102e257806392340fdf146102ea578063a00fa77f146102f2578063a00fff6f14610312578063a87bab9c1461031a578063b0e21e8a14610322578063b8f6eb8a1461032a578063c11c64e514610351578063c3fa0e3b14610364578063ce9e07581461036c578063d0c93a7c14610374578063da10f2c61461037c578063e7c7cb9114610384578063eac0839e1461038c578063eae989a21461039f578063ef78d4fd146103a7578063f9ed2c2c146103af578063fdb2fe59146103d2575b5f80fd5b6101ab6103da565b60405160029190910b81526020015b60405180910390f35b6101ea7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020016101ba565b61020a6103f1565b60405164ffffffffff90911681526020016101ba565b610228610403565b60405163ffffffff90911681526020016101ba565b61024561040d565b6040519081526020016101ba565b61025b61041e565b005b6101ab61050e565b61026d610520565b60405162ffffff90911681526020016101ba565b61026d610532565b61029c610297366004611837565b610544565b6040516101ba929190611852565b6101ea610778565b6101ea610784565b6101ab610790565b6101ea6108ff565b6101ea61090b565b6101ab610917565b61025b610929565b6101ab610b46565b61020a610b52565b6102fa610b5d565b6040516001600160801b0390911681526020016101ba565b6101ea610b73565b6101ab610b7f565b61026d610b91565b6101ea7f000000000000000000000000000000000000000000000000000000000000000081565b61029c61035f36600461186e565b610ba3565b61026d610d29565b61026d610d61565b6101ab610d73565b61026d610d85565b6101ab610d97565b61025b61039a366004611941565b610da9565b6102fa611186565b610228611199565b6103c26103bd366004611a77565b6111a2565b60405190151581526020016101ba565b61026d6112cf565b5f6103ec6103e66112e1565b60801c90565b905090565b5f60c86103fc6112ed565b901c905090565b5f806103fc6112ed565b5f6103ec6104196112f9565b611317565b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa15801561047b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061049f9190611ab3565b50505050509150505f6104b0610790565b90505f8160020b8360020b136104cf576104ca8383611b51565b6104d9565b6104d98284611b51565b90506104e3610d97565b60020b8160020b13156105095760405163318b805360e01b815260040160405180910390fd5b505050565b5f6103ec61051a6112ed565b60b01c90565b5f6103ec61052c6112e1565b60501c90565b5f6103ec61053e611409565b60181c90565b5f805f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663802758606040518163ffffffff1660e01b815260040160c060405180830381865afa1580156105a3573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105c79190611b76565b805180516020909101519192505f9182916105e29188610ba3565b60208086015180519101519294509092505f918291610601918a610ba3565b604087015180516020909101519294509092505f918291610622918c610ba3565b915091508184877f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663629d94056040518163ffffffff1660e01b8152600401602060405180830381865afa158015610685573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106a99190611c39565b6106b39190611c50565b6106bd9190611c50565b6106c79190611c50565b98508083867f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166341aec5386040518163ffffffff1660e01b8152600401602060405180830381865afa158015610728573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061074c9190611c39565b6107569190611c50565b6107609190611c50565b61076a9190611c50565b975050505050505050915091565b5f6103ec610419611415565b5f6103ec61041961142e565b5f8061079a610403565b6040805160028082526060820183529293505f92909160208301908036833701905050905081815f815181106107d2576107d2611c25565b602002602001019063ffffffff16908163ffffffff16815250505f8160018151811061080057610800611c25565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81525f906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063883bdbfd90610863908590600401611c63565b5f60405180830381865afa15801561087d573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526108a49190810190611d40565b5090508263ffffffff16815f815181106108c0576108c0611c25565b6020026020010151826001815181106108db576108db611c25565b60200260200101516108ed9190611e0a565b6108f79190611e4b565b935050505090565b5f6103ec610419611447565b5f6103ec610419611460565b5f6103ec6109236112e1565b60981c90565b61093161041e565b5f805f61093c611479565b9194509250905060c882901c5f6109538460b01c90565b90505f6109608660681c90565b90505f61096d8760801c90565b90505f61097a8860c81c90565b9050875f6109888260b01c90565b905061099a63ffffffff831688611e87565b64ffffffffff164210156109c157604051639c733bed60e01b815260040160405180910390fd5b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610a1e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a429190611ab3565b50505050509150505f8760020b8260020b13610a6757610a628289611b51565b610a71565b610a718883611b51565b905064ffffffffff891615801590610a8e57508260020b8160020b125b15610aac57604051633ebd928560e11b815260040160405180910390fd5b5f8660020b8860020b13610ac05786610ac2565b875b905085610ad382620d89e719611ea4565b610add9190611ea4565b60020b8360020b12158015610b1a57508581610afc620d89e719611ec9565b610b069190611b51565b610b109190611b51565b60020b8360020b13155b610b37576040516369585dd360e11b815260040160405180910390fd5b50505050505050505050505050565b5f6103ec61051a6112e1565b5f60606103fc611409565b5f80610b6a610419611609565b60801c92915050565b5f6103ec610419611622565b5f6103ec610b8b6112e1565b60681c90565b5f6103ec610b9d6112e1565b60201c90565b5f805f805f610bb2888861163b565b6040516317f6f9f160e31b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016600482015260028e810b60248301528d900b60448201526001600160801b03861660648201528b151560848201529497509095509350736c4e0f30ee76a1c360387a0504f32c991d46f8179263bfb7cf88925060a40190506040805180830381865af4158015610c5b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c7f9190611ee9565b90955093505f610c8d6112e1565b90505f610c9a8260201c90565b90505f620f4240610cb062ffffff841687611f0b565b610cba9190611f34565b90505f620f4240610cd062ffffff851687611f0b565b610cda9190611f34565b9050610ce68287611f62565b610cf9906001600160801b03168a611c50565b9850610d058186611f62565b610d18906001600160801b031689611c50565b975050505050505050935093915050565b5f80610d3c610d366112e1565b60381c90565b905062ffffff811615610d5957610d54600182611f81565b610d5b565b5f5b91505090565b5f6103ec610d6d611409565b60301c90565b5f6103ec610d7f6112e1565b60c81c90565b5f6103ec610d91611409565b60481c90565b5f6103ec610da36112e1565b60e01c90565b85515f90610e36577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663629d94056040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e0d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e319190611c39565b610eb6565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166341aec5386040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e92573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610eb69190611c39565b90505f856001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ef5573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f199190611f9c565b90505f856001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f58573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f7c9190611f9c565b90505f610f87611409565b90505f610f948260181c90565b90505f610fa18360301c90565b90505f610fae8c88611fb5565b90505f610fc08e602001518b89611749565b90505f610fce838b89611749565b9050620f4240610fde8682611f81565b610fed9062ffffff1684611fc8565b610ff79190611fdf565b8110156110245780826040516336fbbfad60e21b815260040161101b929190611852565b60405180910390fd5b508d608001518210156110515760808e0151604051635db6cb8760e11b815261101b918491600401611852565b50505f807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663c4a7761e6040518163ffffffff1660e01b81526004016040805180830381865afa1580156110b0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110d49190611ee9565b915091505f8e5f01516110e757816110e9565b825b90505f8f5f01516110fa57836110fc565b825b90505f61110a838e8c611749565b90505f611118838e8c611749565b90505f620f424062ffffff891661112f858561175d565b6111399190611fc8565b6111439190611fdf565b9050611150838383611774565b6111715782826040516331e43bb760e01b815260040161101b929190611852565b50505050505050505050505050505050505050565b5f80611193610419611609565b92915050565b5f6103ec6112e1565b6040805160018082528183019092525f9182919060208083019080368337019050509050826111cf6117a3565b604080516001600160a01b03909316602084015282015260600160405160208183030381529060405280519060200120815f8151811061121157611211611c25565b6020908102919091010152604051637784c68560e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690637784c68590611268908490600401611ff2565b5f60405180830381865afa158015611282573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526112a99190810190612029565b5f815181106112ba576112ba611c25565b60200260200101515f1c5f1415915050919050565b5f6103ec6112db611409565b60881c90565b5f6103ec6104196117bc565b5f6103ec6104196117d5565b5f61131260095f80516020612215833981519152611c50565b919050565b6040805160018082528183019092525f918291906020808301908036833701905050905082815f8151811061134e5761134e611c25565b6020908102919091010152604051637784c68560e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690637784c685906113a5908490600401611ff2565b5f60405180830381865afa1580156113bf573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526113e69190810190612029565b5f815181106113f7576113f7611c25565b60200260200101515f1c915050919050565b5f6103ec6104196117ee565b5f61131260055f80516020612215833981519152611c50565b5f61131260085f80516020612215833981519152611c50565b5f61131260075f80516020612215833981519152611c50565b5f611312600f5f80516020612215833981519152611c50565b604080516003808252608082019092525f9182918291829190602082016060803683370190505090506114aa6117bc565b815f815181106114bc576114bc611c25565b6020026020010181815250506114d06117d5565b816001815181106114e3576114e3611c25565b6020026020010181815250506114f76117ee565b8160028151811061150a5761150a611c25565b6020908102919091010152604051637784c68560e01b81525f906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690637784c68590611563908590600401611ff2565b5f60405180830381865afa15801561157d573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526115a49190810190612029565b9050805f815181106115b8576115b8611c25565b60200260200101515f1c9450806001815181106115d7576115d7611c25565b60200260200101515f1c9350806002815181106115f6576115f6611c25565b60200260200101515f1c92505050909192565b5f611312600a5f80516020612215833981519152611c50565b5f61131260065f80516020612215833981519152611c50565b604080517f000000000000000000000000000000000000000000000000000000000000000060601b6001600160601b03191660208083019190915260e885811b603484015284901b60378301528251601a818403018152603a90920190925280519101205f908190819081908190819060405163514ea4bf60e01b8152600481018290529091507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063514ea4bf9060240160a060405180830381865afa158015611711573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061173591906120cf565b939c929b5090995097509095509350505050565b5f611755848484611807565b949350505050565b5f81831061176b578161176d565b825b9392505050565b5f82841161178e57816117878585611fb5565b1115611755565b816117998486611fb5565b1115949350505050565b5f611312600e5f80516020612215833981519152611c50565b5f611312600b5f80516020612215833981519152611c50565b5f611312600c5f80516020612215833981519152611c50565b5f611312600d5f80516020612215833981519152611c50565b5f61181382600a612206565b61181d8486611fc8565b6117559190611fdf565b8015158114611834575f80fd5b50565b5f60208284031215611847575f80fd5b813561176d81611827565b918252602082015260400190565b8060020b8114611834575f80fd5b5f805f60608486031215611880575f80fd5b833561188b81611860565b9250602084013561189b81611860565b915060408401356118ab81611827565b809150509250925092565b634e487b7160e01b5f52604160045260245ffd5b60405160a081016001600160401b03811182821017156118ec576118ec6118b6565b60405290565b604051601f8201601f191681016001600160401b038111828210171561191a5761191a6118b6565b604052919050565b6001600160a01b0381168114611834575f80fd5b803561131281611922565b5f805f805f8060c08789031215611956575f80fd5b86356001600160401b0381111561196b575f80fd5b870160a0818a03121561197c575f80fd5b6119846118ca565b813561198f81611827565b81526020828101359082015260408201356119a981611922565b604082015260608201356001600160401b038111156119c6575f80fd5b8201601f81018b136119d6575f80fd5b80356001600160401b038111156119ef576119ef6118b6565b611a02601f8201601f19166020016118f2565b8181528c6020838501011115611a16575f80fd5b816020840160208301375f60209282018301526060840152608093840135938301939093525096508701359450611a4f60408801611936565b9350611a5d60608801611936565b9598949750929560808101359460a0909101359350915050565b5f60208284031215611a87575f80fd5b813561176d81611922565b805161ffff81168114611312575f80fd5b805160ff81168114611312575f80fd5b5f805f805f805f60e0888a031215611ac9575f80fd5b8751611ad481611922565b6020890151909750611ae581611860565b9550611af360408901611a92565b9450611b0160608901611a92565b9350611b0f60808901611a92565b9250611b1d60a08901611aa3565b915060c0880151611b2d81611827565b8091505092959891949750929550565b634e487b7160e01b5f52601160045260245ffd5b600282810b9082900b03627fffff198112627fffff8213171561119357611193611b3d565b5f60c08284031215611b86575f80fd5b82601f830112611b94575f80fd5b611b9e60606118f2565b8060c0840185811115611baf575f80fd5b8460405b82821015611c195787601f830112611bc9575f80fd5b611bd2816118f2565b808284018a811115611be2575f80fd5b845b81811015611c05578051611bf781611860565b845260209384019301611be4565b505086525060209094019390810190611bb3565b50919695505050505050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215611c49575f80fd5b5051919050565b8082018082111561119357611193611b3d565b602080825282518282018190525f918401906040840190835b81811015611ca057835163ffffffff16835260209384019390920191600101611c7c565b509095945050505050565b5f6001600160401b03821115611cc357611cc36118b6565b5060051b60200190565b5f82601f830112611cdc575f80fd5b8151611cef611cea82611cab565b6118f2565b8082825260208201915060208360051b860101925085831115611d10575f80fd5b602085015b83811015611d36578051611d2881611922565b835260209283019201611d15565b5095945050505050565b5f8060408385031215611d51575f80fd5b82516001600160401b03811115611d66575f80fd5b8301601f81018513611d76575f80fd5b8051611d84611cea82611cab565b8082825260208201915060208360051b850101925087831115611da5575f80fd5b6020840193505b82841015611dd55783518060060b8114611dc4575f80fd5b825260209384019390910190611dac565b6020870151909550925050506001600160401b03811115611df4575f80fd5b611e0085828601611ccd565b9150509250929050565b600682810b9082900b03667fffffffffffff198112667fffffffffffff8213171561119357611193611b3d565b634e487b7160e01b5f52601260045260245ffd5b5f8160060b8360060b80611e6157611e61611e37565b667fffffffffffff1982145f1982141615611e7e57611e7e611b3d565b90059392505050565b64ffffffffff818116838216019081111561119357611193611b3d565b600281810b9083900b01627fffff8113627fffff198212171561119357611193611b3d565b5f8160020b627fffff198103611ee157611ee1611b3d565b5f0392915050565b5f8060408385031215611efa575f80fd5b505080516020909101519092909150565b6001600160801b038181168382160290811690818114611f2d57611f2d611b3d565b5092915050565b5f6001600160801b03831680611f4c57611f4c611e37565b6001600160801b03929092169190910492915050565b6001600160801b03828116828216039081111561119357611193611b3d565b62ffffff828116828216039081111561119357611193611b3d565b5f60208284031215611fac575f80fd5b61176d82611aa3565b8181038181111561119357611193611b3d565b808202811582820484141761119357611193611b3d565b5f82611fed57611fed611e37565b500490565b602080825282518282018190525f918401906040840190835b81811015611ca057835183526020938401939092019160010161200b565b5f60208284031215612039575f80fd5b81516001600160401b0381111561204e575f80fd5b8201601f8101841361205e575f80fd5b805161206c611cea82611cab565b8082825260208201915060208360051b85010192508683111561208d575f80fd5b6020840193505b828410156120af578351825260209384019390910190612094565b9695505050505050565b80516001600160801b0381168114611312575f80fd5b5f805f805f60a086880312156120e3575f80fd5b6120ec866120b9565b6020870151604088015191965094509250612109606087016120b9565b9150612117608087016120b9565b90509295509295909350565b6001815b600184111561215e5780850481111561214257612142611b3d565b600184161561215057908102905b60019390931c928002612127565b935093915050565b5f8261217457506001611193565b8161218057505f611193565b816001811461219657600281146121a0576121bc565b6001915050611193565b60ff8411156121b1576121b1611b3d565b50506001821b611193565b5060208310610133831016604e8410600b84101617156121df575081810a611193565b6121eb5f198484612123565b805f19048211156121fe576121fe611b3d565b029392505050565b5f61176d60ff84168361216656feb4801203179a1f53d2a89513756c4fddeb24d0f949ce9fc7cf03114c341dc500a2646970667358221220c4c9a4efe45ba8aa892f4dcc1b0e75825dcfd53abbe6390feefda7ab421300ef64736f6c634300081a003300000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c0000000000000000000000009c6779f6fc6cba48496c9a02ca855dac46e322bf
Deployed Bytecode
0x608060405234801561000f575f80fd5b506004361061019f575f3560e01c806316c3e29d146101a357806316f0115b146101c357806319d8ac611461020257806326d89545146102205780632ab4d0521461023d578063345d90e2146102535780633dfa5d871461025d578063466360fc14610265578063479f9c011461028157806347c570fd14610289578063481c6a75146102aa5780634efed314146102b25780635d752a9a146102ba5780635da07868146102c25780636317732e146102ca5780636a37b9d0146102d257806371bd0ea7146102da578063854360ef146102e257806392340fdf146102ea578063a00fa77f146102f2578063a00fff6f14610312578063a87bab9c1461031a578063b0e21e8a14610322578063b8f6eb8a1461032a578063c11c64e514610351578063c3fa0e3b14610364578063ce9e07581461036c578063d0c93a7c14610374578063da10f2c61461037c578063e7c7cb9114610384578063eac0839e1461038c578063eae989a21461039f578063ef78d4fd146103a7578063f9ed2c2c146103af578063fdb2fe59146103d2575b5f80fd5b6101ab6103da565b60405160029190910b81526020015b60405180910390f35b6101ea7f0000000000000000000000009c6779f6fc6cba48496c9a02ca855dac46e322bf81565b6040516001600160a01b0390911681526020016101ba565b61020a6103f1565b60405164ffffffffff90911681526020016101ba565b610228610403565b60405163ffffffff90911681526020016101ba565b61024561040d565b6040519081526020016101ba565b61025b61041e565b005b6101ab61050e565b61026d610520565b60405162ffffff90911681526020016101ba565b61026d610532565b61029c610297366004611837565b610544565b6040516101ba929190611852565b6101ea610778565b6101ea610784565b6101ab610790565b6101ea6108ff565b6101ea61090b565b6101ab610917565b61025b610929565b6101ab610b46565b61020a610b52565b6102fa610b5d565b6040516001600160801b0390911681526020016101ba565b6101ea610b73565b6101ab610b7f565b61026d610b91565b6101ea7f00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c81565b61029c61035f36600461186e565b610ba3565b61026d610d29565b61026d610d61565b6101ab610d73565b61026d610d85565b6101ab610d97565b61025b61039a366004611941565b610da9565b6102fa611186565b610228611199565b6103c26103bd366004611a77565b6111a2565b60405190151581526020016101ba565b61026d6112cf565b5f6103ec6103e66112e1565b60801c90565b905090565b5f60c86103fc6112ed565b901c905090565b5f806103fc6112ed565b5f6103ec6104196112f9565b611317565b5f7f0000000000000000000000009c6779f6fc6cba48496c9a02ca855dac46e322bf6001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa15801561047b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061049f9190611ab3565b50505050509150505f6104b0610790565b90505f8160020b8360020b136104cf576104ca8383611b51565b6104d9565b6104d98284611b51565b90506104e3610d97565b60020b8160020b13156105095760405163318b805360e01b815260040160405180910390fd5b505050565b5f6103ec61051a6112ed565b60b01c90565b5f6103ec61052c6112e1565b60501c90565b5f6103ec61053e611409565b60181c90565b5f805f7f00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c6001600160a01b031663802758606040518163ffffffff1660e01b815260040160c060405180830381865afa1580156105a3573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105c79190611b76565b805180516020909101519192505f9182916105e29188610ba3565b60208086015180519101519294509092505f918291610601918a610ba3565b604087015180516020909101519294509092505f918291610622918c610ba3565b915091508184877f00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c6001600160a01b031663629d94056040518163ffffffff1660e01b8152600401602060405180830381865afa158015610685573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106a99190611c39565b6106b39190611c50565b6106bd9190611c50565b6106c79190611c50565b98508083867f00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c6001600160a01b03166341aec5386040518163ffffffff1660e01b8152600401602060405180830381865afa158015610728573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061074c9190611c39565b6107569190611c50565b6107609190611c50565b61076a9190611c50565b975050505050505050915091565b5f6103ec610419611415565b5f6103ec61041961142e565b5f8061079a610403565b6040805160028082526060820183529293505f92909160208301908036833701905050905081815f815181106107d2576107d2611c25565b602002602001019063ffffffff16908163ffffffff16815250505f8160018151811061080057610800611c25565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81525f906001600160a01b037f0000000000000000000000009c6779f6fc6cba48496c9a02ca855dac46e322bf169063883bdbfd90610863908590600401611c63565b5f60405180830381865afa15801561087d573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526108a49190810190611d40565b5090508263ffffffff16815f815181106108c0576108c0611c25565b6020026020010151826001815181106108db576108db611c25565b60200260200101516108ed9190611e0a565b6108f79190611e4b565b935050505090565b5f6103ec610419611447565b5f6103ec610419611460565b5f6103ec6109236112e1565b60981c90565b61093161041e565b5f805f61093c611479565b9194509250905060c882901c5f6109538460b01c90565b90505f6109608660681c90565b90505f61096d8760801c90565b90505f61097a8860c81c90565b9050875f6109888260b01c90565b905061099a63ffffffff831688611e87565b64ffffffffff164210156109c157604051639c733bed60e01b815260040160405180910390fd5b5f7f0000000000000000000000009c6779f6fc6cba48496c9a02ca855dac46e322bf6001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610a1e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a429190611ab3565b50505050509150505f8760020b8260020b13610a6757610a628289611b51565b610a71565b610a718883611b51565b905064ffffffffff891615801590610a8e57508260020b8160020b125b15610aac57604051633ebd928560e11b815260040160405180910390fd5b5f8660020b8860020b13610ac05786610ac2565b875b905085610ad382620d89e719611ea4565b610add9190611ea4565b60020b8360020b12158015610b1a57508581610afc620d89e719611ec9565b610b069190611b51565b610b109190611b51565b60020b8360020b13155b610b37576040516369585dd360e11b815260040160405180910390fd5b50505050505050505050505050565b5f6103ec61051a6112e1565b5f60606103fc611409565b5f80610b6a610419611609565b60801c92915050565b5f6103ec610419611622565b5f6103ec610b8b6112e1565b60681c90565b5f6103ec610b9d6112e1565b60201c90565b5f805f805f610bb2888861163b565b6040516317f6f9f160e31b81526001600160a01b037f0000000000000000000000009c6779f6fc6cba48496c9a02ca855dac46e322bf16600482015260028e810b60248301528d900b60448201526001600160801b03861660648201528b151560848201529497509095509350736c4e0f30ee76a1c360387a0504f32c991d46f8179263bfb7cf88925060a40190506040805180830381865af4158015610c5b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c7f9190611ee9565b90955093505f610c8d6112e1565b90505f610c9a8260201c90565b90505f620f4240610cb062ffffff841687611f0b565b610cba9190611f34565b90505f620f4240610cd062ffffff851687611f0b565b610cda9190611f34565b9050610ce68287611f62565b610cf9906001600160801b03168a611c50565b9850610d058186611f62565b610d18906001600160801b031689611c50565b975050505050505050935093915050565b5f80610d3c610d366112e1565b60381c90565b905062ffffff811615610d5957610d54600182611f81565b610d5b565b5f5b91505090565b5f6103ec610d6d611409565b60301c90565b5f6103ec610d7f6112e1565b60c81c90565b5f6103ec610d91611409565b60481c90565b5f6103ec610da36112e1565b60e01c90565b85515f90610e36577f00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c6001600160a01b031663629d94056040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e0d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e319190611c39565b610eb6565b7f00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c6001600160a01b03166341aec5386040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e92573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610eb69190611c39565b90505f856001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ef5573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f199190611f9c565b90505f856001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f58573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f7c9190611f9c565b90505f610f87611409565b90505f610f948260181c90565b90505f610fa18360301c90565b90505f610fae8c88611fb5565b90505f610fc08e602001518b89611749565b90505f610fce838b89611749565b9050620f4240610fde8682611f81565b610fed9062ffffff1684611fc8565b610ff79190611fdf565b8110156110245780826040516336fbbfad60e21b815260040161101b929190611852565b60405180910390fd5b508d608001518210156110515760808e0151604051635db6cb8760e11b815261101b918491600401611852565b50505f807f00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c6001600160a01b031663c4a7761e6040518163ffffffff1660e01b81526004016040805180830381865afa1580156110b0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110d49190611ee9565b915091505f8e5f01516110e757816110e9565b825b90505f8f5f01516110fa57836110fc565b825b90505f61110a838e8c611749565b90505f611118838e8c611749565b90505f620f424062ffffff891661112f858561175d565b6111399190611fc8565b6111439190611fdf565b9050611150838383611774565b6111715782826040516331e43bb760e01b815260040161101b929190611852565b50505050505050505050505050505050505050565b5f80611193610419611609565b92915050565b5f6103ec6112e1565b6040805160018082528183019092525f9182919060208083019080368337019050509050826111cf6117a3565b604080516001600160a01b03909316602084015282015260600160405160208183030381529060405280519060200120815f8151811061121157611211611c25565b6020908102919091010152604051637784c68560e01b81526001600160a01b037f00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c1690637784c68590611268908490600401611ff2565b5f60405180830381865afa158015611282573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526112a99190810190612029565b5f815181106112ba576112ba611c25565b60200260200101515f1c5f1415915050919050565b5f6103ec6112db611409565b60881c90565b5f6103ec6104196117bc565b5f6103ec6104196117d5565b5f61131260095f80516020612215833981519152611c50565b919050565b6040805160018082528183019092525f918291906020808301908036833701905050905082815f8151811061134e5761134e611c25565b6020908102919091010152604051637784c68560e01b81526001600160a01b037f00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c1690637784c685906113a5908490600401611ff2565b5f60405180830381865afa1580156113bf573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526113e69190810190612029565b5f815181106113f7576113f7611c25565b60200260200101515f1c915050919050565b5f6103ec6104196117ee565b5f61131260055f80516020612215833981519152611c50565b5f61131260085f80516020612215833981519152611c50565b5f61131260075f80516020612215833981519152611c50565b5f611312600f5f80516020612215833981519152611c50565b604080516003808252608082019092525f9182918291829190602082016060803683370190505090506114aa6117bc565b815f815181106114bc576114bc611c25565b6020026020010181815250506114d06117d5565b816001815181106114e3576114e3611c25565b6020026020010181815250506114f76117ee565b8160028151811061150a5761150a611c25565b6020908102919091010152604051637784c68560e01b81525f906001600160a01b037f00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c1690637784c68590611563908590600401611ff2565b5f60405180830381865afa15801561157d573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526115a49190810190612029565b9050805f815181106115b8576115b8611c25565b60200260200101515f1c9450806001815181106115d7576115d7611c25565b60200260200101515f1c9350806002815181106115f6576115f6611c25565b60200260200101515f1c92505050909192565b5f611312600a5f80516020612215833981519152611c50565b5f61131260065f80516020612215833981519152611c50565b604080517f00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c60601b6001600160601b03191660208083019190915260e885811b603484015284901b60378301528251601a818403018152603a90920190925280519101205f908190819081908190819060405163514ea4bf60e01b8152600481018290529091507f0000000000000000000000009c6779f6fc6cba48496c9a02ca855dac46e322bf6001600160a01b03169063514ea4bf9060240160a060405180830381865afa158015611711573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061173591906120cf565b939c929b5090995097509095509350505050565b5f611755848484611807565b949350505050565b5f81831061176b578161176d565b825b9392505050565b5f82841161178e57816117878585611fb5565b1115611755565b816117998486611fb5565b1115949350505050565b5f611312600e5f80516020612215833981519152611c50565b5f611312600b5f80516020612215833981519152611c50565b5f611312600c5f80516020612215833981519152611c50565b5f611312600d5f80516020612215833981519152611c50565b5f61181382600a612206565b61181d8486611fc8565b6117559190611fdf565b8015158114611834575f80fd5b50565b5f60208284031215611847575f80fd5b813561176d81611827565b918252602082015260400190565b8060020b8114611834575f80fd5b5f805f60608486031215611880575f80fd5b833561188b81611860565b9250602084013561189b81611860565b915060408401356118ab81611827565b809150509250925092565b634e487b7160e01b5f52604160045260245ffd5b60405160a081016001600160401b03811182821017156118ec576118ec6118b6565b60405290565b604051601f8201601f191681016001600160401b038111828210171561191a5761191a6118b6565b604052919050565b6001600160a01b0381168114611834575f80fd5b803561131281611922565b5f805f805f8060c08789031215611956575f80fd5b86356001600160401b0381111561196b575f80fd5b870160a0818a03121561197c575f80fd5b6119846118ca565b813561198f81611827565b81526020828101359082015260408201356119a981611922565b604082015260608201356001600160401b038111156119c6575f80fd5b8201601f81018b136119d6575f80fd5b80356001600160401b038111156119ef576119ef6118b6565b611a02601f8201601f19166020016118f2565b8181528c6020838501011115611a16575f80fd5b816020840160208301375f60209282018301526060840152608093840135938301939093525096508701359450611a4f60408801611936565b9350611a5d60608801611936565b9598949750929560808101359460a0909101359350915050565b5f60208284031215611a87575f80fd5b813561176d81611922565b805161ffff81168114611312575f80fd5b805160ff81168114611312575f80fd5b5f805f805f805f60e0888a031215611ac9575f80fd5b8751611ad481611922565b6020890151909750611ae581611860565b9550611af360408901611a92565b9450611b0160608901611a92565b9350611b0f60808901611a92565b9250611b1d60a08901611aa3565b915060c0880151611b2d81611827565b8091505092959891949750929550565b634e487b7160e01b5f52601160045260245ffd5b600282810b9082900b03627fffff198112627fffff8213171561119357611193611b3d565b5f60c08284031215611b86575f80fd5b82601f830112611b94575f80fd5b611b9e60606118f2565b8060c0840185811115611baf575f80fd5b8460405b82821015611c195787601f830112611bc9575f80fd5b611bd2816118f2565b808284018a811115611be2575f80fd5b845b81811015611c05578051611bf781611860565b845260209384019301611be4565b505086525060209094019390810190611bb3565b50919695505050505050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215611c49575f80fd5b5051919050565b8082018082111561119357611193611b3d565b602080825282518282018190525f918401906040840190835b81811015611ca057835163ffffffff16835260209384019390920191600101611c7c565b509095945050505050565b5f6001600160401b03821115611cc357611cc36118b6565b5060051b60200190565b5f82601f830112611cdc575f80fd5b8151611cef611cea82611cab565b6118f2565b8082825260208201915060208360051b860101925085831115611d10575f80fd5b602085015b83811015611d36578051611d2881611922565b835260209283019201611d15565b5095945050505050565b5f8060408385031215611d51575f80fd5b82516001600160401b03811115611d66575f80fd5b8301601f81018513611d76575f80fd5b8051611d84611cea82611cab565b8082825260208201915060208360051b850101925087831115611da5575f80fd5b6020840193505b82841015611dd55783518060060b8114611dc4575f80fd5b825260209384019390910190611dac565b6020870151909550925050506001600160401b03811115611df4575f80fd5b611e0085828601611ccd565b9150509250929050565b600682810b9082900b03667fffffffffffff198112667fffffffffffff8213171561119357611193611b3d565b634e487b7160e01b5f52601260045260245ffd5b5f8160060b8360060b80611e6157611e61611e37565b667fffffffffffff1982145f1982141615611e7e57611e7e611b3d565b90059392505050565b64ffffffffff818116838216019081111561119357611193611b3d565b600281810b9083900b01627fffff8113627fffff198212171561119357611193611b3d565b5f8160020b627fffff198103611ee157611ee1611b3d565b5f0392915050565b5f8060408385031215611efa575f80fd5b505080516020909101519092909150565b6001600160801b038181168382160290811690818114611f2d57611f2d611b3d565b5092915050565b5f6001600160801b03831680611f4c57611f4c611e37565b6001600160801b03929092169190910492915050565b6001600160801b03828116828216039081111561119357611193611b3d565b62ffffff828116828216039081111561119357611193611b3d565b5f60208284031215611fac575f80fd5b61176d82611aa3565b8181038181111561119357611193611b3d565b808202811582820484141761119357611193611b3d565b5f82611fed57611fed611e37565b500490565b602080825282518282018190525f918401906040840190835b81811015611ca057835183526020938401939092019160010161200b565b5f60208284031215612039575f80fd5b81516001600160401b0381111561204e575f80fd5b8201601f8101841361205e575f80fd5b805161206c611cea82611cab565b8082825260208201915060208360051b85010192508683111561208d575f80fd5b6020840193505b828410156120af578351825260209384019390910190612094565b9695505050505050565b80516001600160801b0381168114611312575f80fd5b5f805f805f60a086880312156120e3575f80fd5b6120ec866120b9565b6020870151604088015191965094509250612109606087016120b9565b9150612117608087016120b9565b90509295509295909350565b6001815b600184111561215e5780850481111561214257612142611b3d565b600184161561215057908102905b60019390931c928002612127565b935093915050565b5f8261217457506001611193565b8161218057505f611193565b816001811461219657600281146121a0576121bc565b6001915050611193565b60ff8411156121b1576121b1611b3d565b50506001821b611193565b5060208310610133831016604e8410600b84101617156121df575081810a611193565b6121eb5f198484612123565b805f19048211156121fe576121fe611b3d565b029392505050565b5f61176d60ff84168361216656feb4801203179a1f53d2a89513756c4fddeb24d0f949ce9fc7cf03114c341dc500a2646970667358221220c4c9a4efe45ba8aa892f4dcc1b0e75825dcfd53abbe6390feefda7ab421300ef64736f6c634300081a0033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c0000000000000000000000009c6779f6fc6cba48496c9a02ca855dac46e322bf
-----Decoded View---------------
Arg [0] : _alm (address): 0x84cC12b9C456B4382E4d9aa12AeA133943cFD36c
Arg [1] : _pool (address): 0x9c6779f6fc6CbA48496c9A02Ca855DAC46E322Bf
-----Encoded View---------------
2 Constructor Arguments found :
Arg [0] : 00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c
Arg [1] : 0000000000000000000000009c6779f6fc6cba48496c9a02ca855dac46e322bf
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 34 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
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.