ETH Price: $3,172.44 (-1.57%)

Contract

0x3a56CE3923d1fa82e13744acEe8Df44F47520BC5

Overview

ETH Balance

0 ETH

ETH Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

View more zero value Internal Transactions in Advanced View mode

Advanced mode:

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
EverlongALMFeed

Compiler Version
v0.8.26+commit.8a97fa7a

Optimization Enabled:
No with 200 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.26;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {LiquidityAmounts} from "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol";
import {PositionKey} from "@uniswap/v3-periphery/contracts/libraries/PositionKey.sol";
import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import {FullMath} from "@uniswap/v3-core/contracts/libraries/FullMath.sol";
import {PropMath} from "src/libraries/PropMath.sol";
import {ISpotOracle} from "src/interfaces/core/oracles/ISpotOracle.sol";
import {IAsset} from "src/interfaces/utils/tokens/IAsset.sol";
import {IPriceFeed} from "src/interfaces/core/oracles/IPriceFeed.sol";
import {IEverlongALM} from "src/interfaces/core/alm/IEverlongALM.sol";

/**
 * @title EverlongALMFeed
 * @author Everlong Labs
 * @notice Spot oracle for Everlong Vault ALM
 * @dev Doesn't support token0 and token1 with >18 decimals
 */
contract EverlongALMFeed is ISpotOracle {
    using SafeCast for uint;
    using TickMath for int24;

    error ALMFeed_InvalidAddress();

    uint256 constant WAD = 1e18;
    uint24 public constant HUNDRED_PERCENT = 1e6;

    IPriceFeed immutable priceFeed;
    IEverlongALM immutable vault;
    IUniswapV3Pool immutable pool;
    address immutable token0Oracle;
    address immutable token1Oracle;
    address immutable token0;
    address immutable token1;
    uint8 immutable decimals0;
    uint8 immutable decimals1;

    constructor(address _vault, address _priceFeed) {
        vault = IEverlongALM(_vault);
        pool = IUniswapV3Pool(vault.pool());
        priceFeed = IPriceFeed(_priceFeed);
        token0 = address(IEverlongALM(_vault).token0());
        token1 = address(IEverlongALM(_vault).token1());
        decimals0 = IAsset(token0).decimals();
        decimals1 = IAsset(token1).decimals();

        if (
            _vault == address(0) ||
            _priceFeed == address(0) ||
            address(pool) == address(0) ||
            token0 == address(0) ||
            token1 == address(0) ||
            decimals0 == 0 ||
            decimals1 == 0
        ) {
            revert ALMFeed_InvalidAddress();
        }
    }

    function fetchPrice() external view returns (uint) {
        uint256 priceToken0 = priceFeed.fetchPrice(token0);
        uint256 priceToken1 = priceFeed.fetchPrice(token1);

        uint256 decimalMultiplier;
        uint256 decimalDivider;
        uint256 decimalDifference = PropMath._getAbsoluteDifference(decimals0, decimals1);
        if (decimals0 >= decimals1) {
            decimalMultiplier = 1;
            decimalDivider = 10 ** decimalDifference;
        } else {
            decimalMultiplier = 10 ** decimalDifference;
            decimalDivider = 1;
        }

        uint256 priceRatio = (priceToken0 * decimalMultiplier * WAD) / (priceToken1 * decimalDivider);

        uint160 priceSqrtRatioX96 = SafeCast.toUint160((Math.sqrt(priceRatio) * (2 ** 96)) / 1e9);

        (uint256 reserves0, uint256 reserves1) = _getReserves(priceSqrtRatioX96);

        uint256 normalizedReserve0 = reserves0 * (10 ** (18 - decimals0));
        uint256 normalizedReserve1 = reserves1 * (10 ** (18 - decimals1));

        uint256 totalSupply = vault.totalSupply();

        if (totalSupply == 0) return 0;

        uint256 totalValue = normalizedReserve0 * priceToken0 + normalizedReserve1 * priceToken1;

        return totalValue / totalSupply;
    }

    function _getReserves(uint160 priceSqrtRatioX96) internal view returns (uint256 reserves0, uint256 reserves1) {
        uint256 fees0;
        uint256 fees1;
        int24[2][3] memory positions = vault.getPositions();
        (, int24 tick,,,,,) = pool.slot0();
        for (uint256 i; i < 3; i++) {
            (uint256 reserve0, uint256 reserve1, uint256 fee0, uint256 fee1) = _getUnderlyingBalancesAtPrice(priceSqrtRatioX96, tick, positions[i][0], positions[i][1]);
            reserves0 += reserve0;
            reserves1 += reserve1;
            fees0 += fee0;
            fees1 += fee1;
        }

        (fees0, fees1) = _subtractProtocolFee(fees0, fees1);

        // add any leftover in contract to current holdings, useful if `emergencyBurn` is used
        reserves0 += fees0 + vault.getBalance0();
        reserves1 += fees1 + vault.getBalance1();
    }

    function _getUnderlyingBalancesAtPrice(
        uint160 sqrtRatioX96,
        int24 tick,
        int24 lowerTick,
        int24 upperTick
    ) internal view returns (uint256 amount0Current, uint256 amount1Current, uint256 fee0, uint256 fee1) {
        (uint128 liquidity, uint256 feeGrowthInside0Last, uint256 feeGrowthInside1Last, uint128 tokensOwed0, uint128 tokensOwed1) = _position(lowerTick, upperTick);

        if (liquidity == 0) return (0, 0, 0, 0);

        // compute current holdings from liquidity
        (amount0Current, amount1Current) = LiquidityAmounts.getAmountsForLiquidity(sqrtRatioX96, lowerTick.getSqrtRatioAtTick(), upperTick.getSqrtRatioAtTick(), liquidity);

        // compute current fees earned
        fee0 = _computeFeesEarned(true, feeGrowthInside0Last, tick, lowerTick, upperTick, liquidity) + uint256(tokensOwed0);
        fee1 = _computeFeesEarned(false, feeGrowthInside1Last, tick, lowerTick, upperTick, liquidity) + uint256(tokensOwed1);
    }

    function _computeFeesEarned(bool isZero, uint256 feeGrowthInsideLast, int24 tick, int24 lowerTick, int24 upperTick, uint128 liquidity) private view returns (uint256 fee) {
        uint256 feeGrowthOutsideLower;
        uint256 feeGrowthOutsideUpper;
        uint256 feeGrowthGlobal;
        if (isZero) {
            feeGrowthGlobal = pool.feeGrowthGlobal0X128();
            (,, feeGrowthOutsideLower,,,,,) = pool.ticks(lowerTick);
            (,, feeGrowthOutsideUpper,,,,,) = pool.ticks(upperTick);
        } else {
            feeGrowthGlobal = pool.feeGrowthGlobal1X128();
            (,,, feeGrowthOutsideLower,,,,) = pool.ticks(lowerTick);
            (,,, feeGrowthOutsideUpper,,,,) = pool.ticks(upperTick);
        }

        unchecked {
            // calculate fee growth below
            uint256 feeGrowthBelow;
            if (tick >= lowerTick) {
                feeGrowthBelow = feeGrowthOutsideLower;
            } else {
                feeGrowthBelow = feeGrowthGlobal - feeGrowthOutsideLower;
            }

            // calculate fee growth above
            uint256 feeGrowthAbove;
            if (tick < upperTick) {
                feeGrowthAbove = feeGrowthOutsideUpper;
            } else {
                feeGrowthAbove = feeGrowthGlobal - feeGrowthOutsideUpper;
            }

            uint256 feeGrowthInside = feeGrowthGlobal - feeGrowthBelow - feeGrowthAbove;
            fee = FullMath.mulDiv(liquidity, feeGrowthInside - feeGrowthInsideLast, 0x100000000000000000000000000000000);
        }
    }

    function _subtractProtocolFee(uint256 _fee0, uint256 _fee1) internal view returns (uint256 fee0, uint256 fee1) {
        uint24 protocolFee = vault.protocolFee();

        fee0 = _fee0 - _fee0 * protocolFee / HUNDRED_PERCENT;
        fee1 = _fee1 - _fee1 * protocolFee / HUNDRED_PERCENT;
    }

    function _position(int24 tickLower, int24 tickUpper)
        internal
        view
        returns (uint128, uint256, uint256, uint128, uint128)
    {
        bytes32 positionKey = PositionKey.compute(address(vault), tickLower, tickUpper);
        return pool.positions(positionKey);
    }
}

// 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);
        }
    }
}

File 3 of 39 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.0;

/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {
    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.2._
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v2.5._
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.2._
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v2.5._
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v2.5._
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v2.5._
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v2.5._
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     *
     * _Available since v3.0._
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.7._
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.7._
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     *
     * _Available since v3.0._
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}

File 4 of 39 : IUniswapV3Pool.sol
// 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;

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);
        }
    }
}

File 6 of 39 : PositionKey.sol
// 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.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: 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;
    }
}

File 10 of 39 : ISpotOracle.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

interface ISpotOracle {
    function fetchPrice() external view returns (uint);
}

// 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: 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: 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: 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);
}

File 19 of 39 : IUniswapV3PoolErrors.sol
// 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();
}

File 20 of 39 : IUniswapV3PoolEvents.sol
// 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);
}

File 21 of 39 : FixedPoint96.sol
// 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;
}

File 22 of 39 : IERC20.sol
// 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: 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);
    }
}

File 24 of 39 : ALMGetters.sol
// 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

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 (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
// 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;

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 {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: 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))
        }
    }
}

File 33 of 39 : IERC20.sol
// 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";

File 34 of 39 : IERC165.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";

File 35 of 39 : Errors.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: 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) (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);
}

// 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))
        }
    }
}

Settings
{
  "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": false,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": false
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_vault","type":"address"},{"internalType":"address","name":"_priceFeed","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"ALMFeed_InvalidAddress","type":"error"},{"inputs":[],"name":"T","type":"error"},{"inputs":[],"name":"HUNDRED_PERCENT","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"fetchPrice","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]

6101a0604052348015610010575f80fd5b50604051612cda380380612cda83398181016040528101906100329190610545565b8173ffffffffffffffffffffffffffffffffffffffff1660a08173ffffffffffffffffffffffffffffffffffffffff168152505060a05173ffffffffffffffffffffffffffffffffffffffff166316f0115b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156100b1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906100d591906105be565b73ffffffffffffffffffffffffffffffffffffffff1660c08173ffffffffffffffffffffffffffffffffffffffff16815250508073ffffffffffffffffffffffffffffffffffffffff1660808173ffffffffffffffffffffffffffffffffffffffff16815250508173ffffffffffffffffffffffffffffffffffffffff16630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa158015610185573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906101a991906105e9565b73ffffffffffffffffffffffffffffffffffffffff166101208173ffffffffffffffffffffffffffffffffffffffff16815250508173ffffffffffffffffffffffffffffffffffffffff1663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa158015610226573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061024a91906105e9565b73ffffffffffffffffffffffffffffffffffffffff166101408173ffffffffffffffffffffffffffffffffffffffff16815250506101205173ffffffffffffffffffffffffffffffffffffffff1663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156102ca573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906102ee919061064a565b60ff166101608160ff16815250506101405173ffffffffffffffffffffffffffffffffffffffff1663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610348573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061036c919061064a565b60ff166101808160ff16815250505f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614806103df57505f73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16145b8061041757505f73ffffffffffffffffffffffffffffffffffffffff1660c05173ffffffffffffffffffffffffffffffffffffffff16145b8061045057505f73ffffffffffffffffffffffffffffffffffffffff166101205173ffffffffffffffffffffffffffffffffffffffff16145b8061048957505f73ffffffffffffffffffffffffffffffffffffffff166101405173ffffffffffffffffffffffffffffffffffffffff16145b8061049957505f6101605160ff16145b806104a957505f6101805160ff16145b156104e0576040517ff190776000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5050610675565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f610514826104eb565b9050919050565b6105248161050a565b811461052e575f80fd5b50565b5f8151905061053f8161051b565b92915050565b5f806040838503121561055b5761055a6104e7565b5b5f61056885828601610531565b925050602061057985828601610531565b9150509250929050565b5f61058d8261050a565b9050919050565b61059d81610583565b81146105a7575f80fd5b50565b5f815190506105b881610594565b92915050565b5f602082840312156105d3576105d26104e7565b5b5f6105e0848285016105aa565b91505092915050565b5f602082840312156105fe576105fd6104e7565b5b5f61060b84828501610531565b91505092915050565b5f60ff82169050919050565b61062981610614565b8114610633575f80fd5b50565b5f8151905061064481610620565b92915050565b5f6020828403121561065f5761065e6104e7565b5b5f61066c84828501610636565b91505092915050565b60805160a05160c05160e05161010051610120516101405161016051610180516125916107495f395f818161021701528181610242015261038501525f81816101f301528181610266015261033e01525f61016f01525f60b401525f50505f50505f81816106dd01528181610ca10152818161123a015281816112c90152818161138401528181611444015281816114d3015261158f01525f81816103cc0152818161064d0152818161084e015281816108f301528181610b750152610c7701525f81816078015261013301526125915ff3fe608060405234801561000f575f80fd5b5060043610610034575f3560e01c80630fdb11cf146100385780636ed93dd014610056575b5f80fd5b610040610074565b60405161004d9190611934565b60405180910390f35b61005e6104b8565b60405161006b919061196a565b60405180910390f35b5f807f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663ace1798e7f00000000000000000000000000000000000000000000000000000000000000006040518263ffffffff1660e01b81526004016100ef91906119c2565b602060405180830381865afa15801561010a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061012e9190611a12565b90505f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663ace1798e7f00000000000000000000000000000000000000000000000000000000000000006040518263ffffffff1660e01b81526004016101aa91906119c2565b602060405180830381865afa1580156101c5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906101e99190611a12565b90505f805f61023e7f000000000000000000000000000000000000000000000000000000000000000060ff167f000000000000000000000000000000000000000000000000000000000000000060ff166104bf565b90507f000000000000000000000000000000000000000000000000000000000000000060ff167f000000000000000000000000000000000000000000000000000000000000000060ff16106102a5576001925080600a61029e9190611b99565b91506102b9565b80600a6102b29190611b99565b9250600191505b5f82856102c69190611be3565b670de0b6b3a764000085886102db9190611be3565b6102e59190611be3565b6102ef9190611c51565b90505f61032a633b9aca006c01000000000000000000000000610311856104ee565b61031b9190611be3565b6103259190611c51565b6105e4565b90505f8061033783610646565b915091505f7f000000000000000000000000000000000000000000000000000000000000000060126103699190611c8d565b600a6103759190611cc1565b836103809190611be3565b90505f7f000000000000000000000000000000000000000000000000000000000000000060126103b09190611c8d565b600a6103bc9190611cc1565b836103c79190611be3565b90505f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610433573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104579190611a12565b90505f8103610474575f9c505050505050505050505050506104b5565b5f8b836104819190611be3565b8d8561048d9190611be3565b6104979190611d0b565b905081816104a59190611c51565b9d50505050505050505050505050505b90565b620f424081565b5f818310156104d95782826104d49190611d3e565b6104e6565b81836104e59190611d3e565b5b905092915050565b5f8082036104fe575f90506105df565b5f600161050a8461099f565b901c6001901b9050600181848161052457610523611c24565b5b048201901c9050600181848161053d5761053c611c24565b5b048201901c9050600181848161055657610555611c24565b5b048201901c9050600181848161056f5761056e611c24565b5b048201901c9050600181848161058857610587611c24565b5b048201901c905060018184816105a1576105a0611c24565b5b048201901c905060018184816105ba576105b9611c24565b5b048201901c90506105db818285816105d5576105d4611c24565b5b04610a76565b9150505b919050565b5f73ffffffffffffffffffffffffffffffffffffffff801682111561063e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063590611df1565b60405180910390fd5b819050919050565b5f805f805f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663802758606040518163ffffffff1660e01b815260040160c060405180830381865afa1580156106b4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106d89190612031565b90505f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff16633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610744573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610768919061211c565b50505050509150505f5b6003811015610839575f805f806107e88c87898860038110610797576107966121b9565b5b60200201515f600281106107ae576107ad6121b9565b5b60200201518a89600381106107c6576107c56121b9565b5b60200201516001600281106107de576107dd6121b9565b5b6020020151610a8e565b9350935093509350838b6107fc9190611d0b565b9a50828a61080a9190611d0b565b995081896108189190611d0b565b985080886108269190611d0b565b9750505050508080600101915050610772565b506108448484610b70565b80945081955050507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663629d94056040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108b5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108d99190611a12565b846108e49190611d0b565b866108ef9190611d0b565b95507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166341aec5386040518163ffffffff1660e01b8152600401602060405180830381865afa15801561095a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061097e9190611a12565b836109899190611d0b565b856109949190611d0b565b945050505050915091565b5f805f90505f608084901c11156109be57608083901c92506080810190505b5f604084901c11156109d857604083901c92506040810190505b5f602084901c11156109f257602083901c92506020810190505b5f601084901c1115610a0c57601083901c92506010810190505b5f600884901c1115610a2657600883901c92506008810190505b5f600484901c1115610a4057600483901c92506004810190505b5f600284901c1115610a5a57600283901c92506002810190505b5f600184901c1115610a6d576001810190505b80915050919050565b5f818310610a845781610a86565b825b905092915050565b5f805f805f805f805f610aa18b8b610c6c565b945094509450945094505f856fffffffffffffffffffffffffffffffff1603610ada575f805f8098509850985098505050505050610b65565b610afc8d610aea8d60020b610d4c565b610af68d60020b610d4c565b8861113d565b809950819a505050816fffffffffffffffffffffffffffffffff16610b266001868f8f8f8b61122e565b610b309190611d0b565b9650806fffffffffffffffffffffffffffffffff16610b535f858f8f8f8b61122e565b610b5d9190611d0b565b955050505050505b945094509450949050565b5f805f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663b0e21e8a6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610bdc573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c009190612210565b9050620f424062ffffff168162ffffff1686610c1c9190611be3565b610c269190611c51565b85610c319190611d3e565b9250620f424062ffffff168162ffffff1685610c4d9190611be3565b610c579190611c51565b84610c629190611d3e565b9150509250929050565b5f805f805f80610c9d7f000000000000000000000000000000000000000000000000000000000000000089896116cd565b90507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663514ea4bf826040518263ffffffff1660e01b8152600401610cf89190612253565b60a060405180830381865afa158015610d13573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d3791906122b1565b95509550955095509550509295509295909350565b5f805f8360020b12610d61578260020b610d68565b8260020b5f035b90507ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff276185f0360020b811115610dc9576040517f2bc80f3a00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f806001831603610deb57700100000000000000000000000000000000610dfd565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690505f6002831614610e365760806ffff97272373d413259a46990580e213a8202901c90505b5f6004831614610e5a5760806ffff2e50f5f656932ef12357cf3c7fdcc8202901c90505b5f6008831614610e7e5760806fffe5caca7e10e4e61c3624eaa0941cd08202901c90505b5f6010831614610ea25760806fffcb9843d60f6159c9db58835c9266448202901c90505b5f6020831614610ec65760806fff973b41fa98c081472e6896dfb254c08202901c90505b5f6040831614610eea5760806fff2ea16466c96a3843ec78b326b528618202901c90505b5f6080831614610f0e5760806ffe5dee046a99a2a811c461f1969c30538202901c90505b5f610100831614610f335760806ffcbe86c7900a88aedcffc83b479aa3a48202901c90505b5f610200831614610f585760806ff987a7253ac413176f2b074cf7815e548202901c90505b5f610400831614610f7d5760806ff3392b0822b70005940c7a398e4b70f38202901c90505b5f610800831614610fa25760806fe7159475a2c29b7443b29c7fa6e889d98202901c90505b5f611000831614610fc75760806fd097f3bdfd2022b8845ad8f792aa58258202901c90505b5f612000831614610fec5760806fa9f746462d870fdf8a65dc1f90e061e58202901c90505b5f6140008316146110115760806f70d869a156d2a1b890bb3df62baf32f78202901c90505b5f6180008316146110365760806f31be135f97d08fd981231505542fcfa68202901c90505b5f6201000083161461105c5760806f09aa508b5b7a84e1c677de54f3e99bc98202901c90505b5f620200008316146110815760806e5d6af8dedb81196699c329225ee6048202901c90505b5f620400008316146110a55760806d2216e584f5fa1ea926041bedfe988202901c90505b5f620800008316146110c75760806b048a170391f7dc42444e8fa28202901c90505b5f8460020b131561110657807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8161110257611101611c24565b5b0490505b5f640100000000828161111c5761111b611c24565b5b061461112957600161112b565b5f5b60ff16602082901c0192505050919050565b5f808373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff16111561117e57838580955081965050505b8473ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff16116111c3576111bc858585611702565b9150611225565b8373ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff16101561121657611202868585611702565b915061120f8587856117c3565b9050611224565b6112218585856117c3565b90505b5b94509492505050565b5f805f808915611442577f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663f30583996040518163ffffffff1660e01b8152600401602060405180830381865afa1580156112a1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112c59190611a12565b90507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663f30dba93886040518263ffffffff1660e01b81526004016113209190612337565b61010060405180830381865afa15801561133c573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061136091906123f5565b909192939495965090919293949550909192935090919250909150905050809350507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663f30dba93876040518263ffffffff1660e01b81526004016113db9190612337565b61010060405180830381865afa1580156113f7573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061141b91906123f5565b9091929394959650909192939495509091929350909192509091509050508092505061164a565b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663461413196040518163ffffffff1660e01b8152600401602060405180830381865afa1580156114ab573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114cf9190611a12565b90507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663f30dba93886040518263ffffffff1660e01b815260040161152a9190612337565b61010060405180830381865afa158015611546573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061156a91906123f5565b90919293949596509091929394955090919293945090919250909150905050809350507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663f30dba93876040518263ffffffff1660e01b81526004016115e69190612337565b61010060405180830381865afa158015611602573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061162691906123f5565b90919293949596509091929394955090919293945090919250909150905050809250505b5f8760020b8960020b1261166057839050611666565b83820390505b5f8760020b8a60020b121561167d57839050611683565b83830390505b5f818385030390506116bb886fffffffffffffffffffffffffffffffff168d830370010000000000000000000000000000000061184e565b96505050505050509695505050505050565b5f8383836040516020016116e39392919061251f565b6040516020818303038152906040528051906020012090509392505050565b5f8273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16111561174257828480945081955050505b8373ffffffffffffffffffffffffffffffffffffffff166117ab606060ff16846fffffffffffffffffffffffffffffffff16901b86860373ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff1661184e565b816117b9576117b8611c24565b5b0490509392505050565b5f8273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16111561180357828480945081955050505b611845826fffffffffffffffffffffffffffffffff1685850373ffffffffffffffffffffffffffffffffffffffff166c0100000000000000000000000061184e565b90509392505050565b5f805f80198587098587029250828110838203039150505f8103611883575f8411611877575f80fd5b83820492505050611915565b80841161188e575f80fd5b5f8486880990508281118203915080830392505f85865f0316905080860495508084049350600181825f0304019050808302841793505f600287600302189050808702600203810290508087026002038102905080870260020381029050808702600203810290508087026002038102905080870260020381029050808502955050505050505b9392505050565b5f819050919050565b61192e8161191c565b82525050565b5f6020820190506119475f830184611925565b92915050565b5f62ffffff82169050919050565b6119648161194d565b82525050565b5f60208201905061197d5f83018461195b565b92915050565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6119ac82611983565b9050919050565b6119bc816119a2565b82525050565b5f6020820190506119d55f8301846119b3565b92915050565b5f604051905090565b5f80fd5b6119f18161191c565b81146119fb575f80fd5b50565b5f81519050611a0c816119e8565b92915050565b5f60208284031215611a2757611a266119e4565b5b5f611a34848285016119fe565b91505092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f8160011c9050919050565b5f808291508390505b6001851115611abf57808604811115611a9b57611a9a611a3d565b5b6001851615611aaa5780820291505b8081029050611ab885611a6a565b9450611a7f565b94509492505050565b5f82611ad75760019050611b92565b81611ae4575f9050611b92565b8160018114611afa5760028114611b0457611b33565b6001915050611b92565b60ff841115611b1657611b15611a3d565b5b8360020a915084821115611b2d57611b2c611a3d565b5b50611b92565b5060208310610133831016604e8410600b8410161715611b685782820a905083811115611b6357611b62611a3d565b5b611b92565b611b758484846001611a76565b92509050818404811115611b8c57611b8b611a3d565b5b81810290505b9392505050565b5f611ba38261191c565b9150611bae8361191c565b9250611bdb7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8484611ac8565b905092915050565b5f611bed8261191c565b9150611bf88361191c565b9250828202611c068161191c565b91508282048414831517611c1d57611c1c611a3d565b5b5092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f611c5b8261191c565b9150611c668361191c565b925082611c7657611c75611c24565b5b828204905092915050565b5f60ff82169050919050565b5f611c9782611c81565b9150611ca283611c81565b9250828203905060ff811115611cbb57611cba611a3d565b5b92915050565b5f611ccb8261191c565b9150611cd683611c81565b9250611d037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8484611ac8565b905092915050565b5f611d158261191c565b9150611d208361191c565b9250828201905080821115611d3857611d37611a3d565b5b92915050565b5f611d488261191c565b9150611d538361191c565b9250828203905081811115611d6b57611d6a611a3d565b5b92915050565b5f82825260208201905092915050565b7f53616665436173743a2076616c756520646f65736e27742066697420696e20315f8201527f3630206269747300000000000000000000000000000000000000000000000000602082015250565b5f611ddb602783611d71565b9150611de682611d81565b604082019050919050565b5f6020820190508181035f830152611e0881611dcf565b9050919050565b5f80fd5b5f601f19601f8301169050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b611e5982611e13565b810181811067ffffffffffffffff82111715611e7857611e77611e23565b5b80604052505050565b5f611e8a6119db565b9050611e968282611e50565b919050565b5f67ffffffffffffffff821115611eb557611eb4611e23565b5b602082029050919050565b5f80fd5b5f67ffffffffffffffff821115611ede57611edd611e23565b5b602082029050919050565b5f8160020b9050919050565b611efe81611ee9565b8114611f08575f80fd5b50565b5f81519050611f1981611ef5565b92915050565b5f611f31611f2c84611ec4565b611e81565b90508060208402830185811115611f4b57611f4a611ec0565b5b835b81811015611f745780611f608882611f0b565b845260208401935050602081019050611f4d565b5050509392505050565b5f82601f830112611f9257611f91611e0f565b5b6002611f9f848285611f1f565b91505092915050565b5f611fba611fb584611e9b565b611e81565b90508060408402830185811115611fd457611fd3611ec0565b5b835b81811015611ffd5780611fe98882611f7e565b845260208401935050604081019050611fd6565b5050509392505050565b5f82601f83011261201b5761201a611e0f565b5b6003612028848285611fa8565b91505092915050565b5f60c08284031215612046576120456119e4565b5b5f61205384828501612007565b91505092915050565b61206581611983565b811461206f575f80fd5b50565b5f815190506120808161205c565b92915050565b5f61ffff82169050919050565b61209c81612086565b81146120a6575f80fd5b50565b5f815190506120b781612093565b92915050565b6120c681611c81565b81146120d0575f80fd5b50565b5f815190506120e1816120bd565b92915050565b5f8115159050919050565b6120fb816120e7565b8114612105575f80fd5b50565b5f81519050612116816120f2565b92915050565b5f805f805f805f60e0888a031215612137576121366119e4565b5b5f6121448a828b01612072565b97505060206121558a828b01611f0b565b96505060406121668a828b016120a9565b95505060606121778a828b016120a9565b94505060806121888a828b016120a9565b93505060a06121998a828b016120d3565b92505060c06121aa8a828b01612108565b91505092959891949750929550565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b6121ef8161194d565b81146121f9575f80fd5b50565b5f8151905061220a816121e6565b92915050565b5f60208284031215612225576122246119e4565b5b5f612232848285016121fc565b91505092915050565b5f819050919050565b61224d8161223b565b82525050565b5f6020820190506122665f830184612244565b92915050565b5f6fffffffffffffffffffffffffffffffff82169050919050565b6122908161226c565b811461229a575f80fd5b50565b5f815190506122ab81612287565b92915050565b5f805f805f60a086880312156122ca576122c96119e4565b5b5f6122d78882890161229d565b95505060206122e8888289016119fe565b94505060406122f9888289016119fe565b935050606061230a8882890161229d565b925050608061231b8882890161229d565b9150509295509295909350565b61233181611ee9565b82525050565b5f60208201905061234a5f830184612328565b92915050565b5f81600f0b9050919050565b61236581612350565b811461236f575f80fd5b50565b5f815190506123808161235c565b92915050565b5f8160060b9050919050565b61239b81612386565b81146123a5575f80fd5b50565b5f815190506123b681612392565b92915050565b5f63ffffffff82169050919050565b6123d4816123bc565b81146123de575f80fd5b50565b5f815190506123ef816123cb565b92915050565b5f805f805f805f80610100898b031215612412576124116119e4565b5b5f61241f8b828c0161229d565b98505060206124308b828c01612372565b97505060406124418b828c016119fe565b96505060606124528b828c016119fe565b95505060806124638b828c016123a8565b94505060a06124748b828c01612072565b93505060c06124858b828c016123e1565b92505060e06124968b828c01612108565b9150509295985092959890939650565b5f8160601b9050919050565b5f6124bc826124a6565b9050919050565b5f6124cd826124b2565b9050919050565b6124e56124e0826119a2565b6124c3565b82525050565b5f8160e81b9050919050565b5f612501826124eb565b9050919050565b61251961251482611ee9565b6124f7565b82525050565b5f61252a82866124d4565b60148201915061253a8285612508565b60038201915061254a8284612508565b60038201915081905094935050505056fea2646970667358221220474bca3dd77f9110c17b6496030d7748ab2e55798f7a6a72dd9f8e3358c0547564736f6c634300081a003300000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c000000000000000000000000d9069e3f3eeb45d4e05b765142ba28f3beb96f7a

Deployed Bytecode

0x608060405234801561000f575f80fd5b5060043610610034575f3560e01c80630fdb11cf146100385780636ed93dd014610056575b5f80fd5b610040610074565b60405161004d9190611934565b60405180910390f35b61005e6104b8565b60405161006b919061196a565b60405180910390f35b5f807f000000000000000000000000d9069e3f3eeb45d4e05b765142ba28f3beb96f7a73ffffffffffffffffffffffffffffffffffffffff1663ace1798e7f0000000000000000000000000913da6da4b42f538b445599b46bb4622342cf526040518263ffffffff1660e01b81526004016100ef91906119c2565b602060405180830381865afa15801561010a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061012e9190611a12565b90505f7f000000000000000000000000d9069e3f3eeb45d4e05b765142ba28f3beb96f7a73ffffffffffffffffffffffffffffffffffffffff1663ace1798e7f0000000000000000000000000f26bbb8962d73bc891327f14db5162d5279899f6040518263ffffffff1660e01b81526004016101aa91906119c2565b602060405180830381865afa1580156101c5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906101e99190611a12565b90505f805f61023e7f000000000000000000000000000000000000000000000000000000000000000860ff167f000000000000000000000000000000000000000000000000000000000000001260ff166104bf565b90507f000000000000000000000000000000000000000000000000000000000000001260ff167f000000000000000000000000000000000000000000000000000000000000000860ff16106102a5576001925080600a61029e9190611b99565b91506102b9565b80600a6102b29190611b99565b9250600191505b5f82856102c69190611be3565b670de0b6b3a764000085886102db9190611be3565b6102e59190611be3565b6102ef9190611c51565b90505f61032a633b9aca006c01000000000000000000000000610311856104ee565b61031b9190611be3565b6103259190611c51565b6105e4565b90505f8061033783610646565b915091505f7f000000000000000000000000000000000000000000000000000000000000000860126103699190611c8d565b600a6103759190611cc1565b836103809190611be3565b90505f7f000000000000000000000000000000000000000000000000000000000000001260126103b09190611c8d565b600a6103bc9190611cc1565b836103c79190611be3565b90505f7f00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c73ffffffffffffffffffffffffffffffffffffffff166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610433573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104579190611a12565b90505f8103610474575f9c505050505050505050505050506104b5565b5f8b836104819190611be3565b8d8561048d9190611be3565b6104979190611d0b565b905081816104a59190611c51565b9d50505050505050505050505050505b90565b620f424081565b5f818310156104d95782826104d49190611d3e565b6104e6565b81836104e59190611d3e565b5b905092915050565b5f8082036104fe575f90506105df565b5f600161050a8461099f565b901c6001901b9050600181848161052457610523611c24565b5b048201901c9050600181848161053d5761053c611c24565b5b048201901c9050600181848161055657610555611c24565b5b048201901c9050600181848161056f5761056e611c24565b5b048201901c9050600181848161058857610587611c24565b5b048201901c905060018184816105a1576105a0611c24565b5b048201901c905060018184816105ba576105b9611c24565b5b048201901c90506105db818285816105d5576105d4611c24565b5b04610a76565b9150505b919050565b5f73ffffffffffffffffffffffffffffffffffffffff801682111561063e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063590611df1565b60405180910390fd5b819050919050565b5f805f805f7f00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c73ffffffffffffffffffffffffffffffffffffffff1663802758606040518163ffffffff1660e01b815260040160c060405180830381865afa1580156106b4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106d89190612031565b90505f7f0000000000000000000000009c6779f6fc6cba48496c9a02ca855dac46e322bf73ffffffffffffffffffffffffffffffffffffffff16633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610744573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610768919061211c565b50505050509150505f5b6003811015610839575f805f806107e88c87898860038110610797576107966121b9565b5b60200201515f600281106107ae576107ad6121b9565b5b60200201518a89600381106107c6576107c56121b9565b5b60200201516001600281106107de576107dd6121b9565b5b6020020151610a8e565b9350935093509350838b6107fc9190611d0b565b9a50828a61080a9190611d0b565b995081896108189190611d0b565b985080886108269190611d0b565b9750505050508080600101915050610772565b506108448484610b70565b80945081955050507f00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c73ffffffffffffffffffffffffffffffffffffffff1663629d94056040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108b5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108d99190611a12565b846108e49190611d0b565b866108ef9190611d0b565b95507f00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c73ffffffffffffffffffffffffffffffffffffffff166341aec5386040518163ffffffff1660e01b8152600401602060405180830381865afa15801561095a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061097e9190611a12565b836109899190611d0b565b856109949190611d0b565b945050505050915091565b5f805f90505f608084901c11156109be57608083901c92506080810190505b5f604084901c11156109d857604083901c92506040810190505b5f602084901c11156109f257602083901c92506020810190505b5f601084901c1115610a0c57601083901c92506010810190505b5f600884901c1115610a2657600883901c92506008810190505b5f600484901c1115610a4057600483901c92506004810190505b5f600284901c1115610a5a57600283901c92506002810190505b5f600184901c1115610a6d576001810190505b80915050919050565b5f818310610a845781610a86565b825b905092915050565b5f805f805f805f805f610aa18b8b610c6c565b945094509450945094505f856fffffffffffffffffffffffffffffffff1603610ada575f805f8098509850985098505050505050610b65565b610afc8d610aea8d60020b610d4c565b610af68d60020b610d4c565b8861113d565b809950819a505050816fffffffffffffffffffffffffffffffff16610b266001868f8f8f8b61122e565b610b309190611d0b565b9650806fffffffffffffffffffffffffffffffff16610b535f858f8f8f8b61122e565b610b5d9190611d0b565b955050505050505b945094509450949050565b5f805f7f00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c73ffffffffffffffffffffffffffffffffffffffff1663b0e21e8a6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610bdc573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c009190612210565b9050620f424062ffffff168162ffffff1686610c1c9190611be3565b610c269190611c51565b85610c319190611d3e565b9250620f424062ffffff168162ffffff1685610c4d9190611be3565b610c579190611c51565b84610c629190611d3e565b9150509250929050565b5f805f805f80610c9d7f00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c89896116cd565b90507f0000000000000000000000009c6779f6fc6cba48496c9a02ca855dac46e322bf73ffffffffffffffffffffffffffffffffffffffff1663514ea4bf826040518263ffffffff1660e01b8152600401610cf89190612253565b60a060405180830381865afa158015610d13573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d3791906122b1565b95509550955095509550509295509295909350565b5f805f8360020b12610d61578260020b610d68565b8260020b5f035b90507ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff276185f0360020b811115610dc9576040517f2bc80f3a00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f806001831603610deb57700100000000000000000000000000000000610dfd565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690505f6002831614610e365760806ffff97272373d413259a46990580e213a8202901c90505b5f6004831614610e5a5760806ffff2e50f5f656932ef12357cf3c7fdcc8202901c90505b5f6008831614610e7e5760806fffe5caca7e10e4e61c3624eaa0941cd08202901c90505b5f6010831614610ea25760806fffcb9843d60f6159c9db58835c9266448202901c90505b5f6020831614610ec65760806fff973b41fa98c081472e6896dfb254c08202901c90505b5f6040831614610eea5760806fff2ea16466c96a3843ec78b326b528618202901c90505b5f6080831614610f0e5760806ffe5dee046a99a2a811c461f1969c30538202901c90505b5f610100831614610f335760806ffcbe86c7900a88aedcffc83b479aa3a48202901c90505b5f610200831614610f585760806ff987a7253ac413176f2b074cf7815e548202901c90505b5f610400831614610f7d5760806ff3392b0822b70005940c7a398e4b70f38202901c90505b5f610800831614610fa25760806fe7159475a2c29b7443b29c7fa6e889d98202901c90505b5f611000831614610fc75760806fd097f3bdfd2022b8845ad8f792aa58258202901c90505b5f612000831614610fec5760806fa9f746462d870fdf8a65dc1f90e061e58202901c90505b5f6140008316146110115760806f70d869a156d2a1b890bb3df62baf32f78202901c90505b5f6180008316146110365760806f31be135f97d08fd981231505542fcfa68202901c90505b5f6201000083161461105c5760806f09aa508b5b7a84e1c677de54f3e99bc98202901c90505b5f620200008316146110815760806e5d6af8dedb81196699c329225ee6048202901c90505b5f620400008316146110a55760806d2216e584f5fa1ea926041bedfe988202901c90505b5f620800008316146110c75760806b048a170391f7dc42444e8fa28202901c90505b5f8460020b131561110657807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8161110257611101611c24565b5b0490505b5f640100000000828161111c5761111b611c24565b5b061461112957600161112b565b5f5b60ff16602082901c0192505050919050565b5f808373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff16111561117e57838580955081965050505b8473ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff16116111c3576111bc858585611702565b9150611225565b8373ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff16101561121657611202868585611702565b915061120f8587856117c3565b9050611224565b6112218585856117c3565b90505b5b94509492505050565b5f805f808915611442577f0000000000000000000000009c6779f6fc6cba48496c9a02ca855dac46e322bf73ffffffffffffffffffffffffffffffffffffffff1663f30583996040518163ffffffff1660e01b8152600401602060405180830381865afa1580156112a1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112c59190611a12565b90507f0000000000000000000000009c6779f6fc6cba48496c9a02ca855dac46e322bf73ffffffffffffffffffffffffffffffffffffffff1663f30dba93886040518263ffffffff1660e01b81526004016113209190612337565b61010060405180830381865afa15801561133c573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061136091906123f5565b909192939495965090919293949550909192935090919250909150905050809350507f0000000000000000000000009c6779f6fc6cba48496c9a02ca855dac46e322bf73ffffffffffffffffffffffffffffffffffffffff1663f30dba93876040518263ffffffff1660e01b81526004016113db9190612337565b61010060405180830381865afa1580156113f7573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061141b91906123f5565b9091929394959650909192939495509091929350909192509091509050508092505061164a565b7f0000000000000000000000009c6779f6fc6cba48496c9a02ca855dac46e322bf73ffffffffffffffffffffffffffffffffffffffff1663461413196040518163ffffffff1660e01b8152600401602060405180830381865afa1580156114ab573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114cf9190611a12565b90507f0000000000000000000000009c6779f6fc6cba48496c9a02ca855dac46e322bf73ffffffffffffffffffffffffffffffffffffffff1663f30dba93886040518263ffffffff1660e01b815260040161152a9190612337565b61010060405180830381865afa158015611546573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061156a91906123f5565b90919293949596509091929394955090919293945090919250909150905050809350507f0000000000000000000000009c6779f6fc6cba48496c9a02ca855dac46e322bf73ffffffffffffffffffffffffffffffffffffffff1663f30dba93876040518263ffffffff1660e01b81526004016115e69190612337565b61010060405180830381865afa158015611602573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061162691906123f5565b90919293949596509091929394955090919293945090919250909150905050809250505b5f8760020b8960020b1261166057839050611666565b83820390505b5f8760020b8a60020b121561167d57839050611683565b83830390505b5f818385030390506116bb886fffffffffffffffffffffffffffffffff168d830370010000000000000000000000000000000061184e565b96505050505050509695505050505050565b5f8383836040516020016116e39392919061251f565b6040516020818303038152906040528051906020012090509392505050565b5f8273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16111561174257828480945081955050505b8373ffffffffffffffffffffffffffffffffffffffff166117ab606060ff16846fffffffffffffffffffffffffffffffff16901b86860373ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff1661184e565b816117b9576117b8611c24565b5b0490509392505050565b5f8273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16111561180357828480945081955050505b611845826fffffffffffffffffffffffffffffffff1685850373ffffffffffffffffffffffffffffffffffffffff166c0100000000000000000000000061184e565b90509392505050565b5f805f80198587098587029250828110838203039150505f8103611883575f8411611877575f80fd5b83820492505050611915565b80841161188e575f80fd5b5f8486880990508281118203915080830392505f85865f0316905080860495508084049350600181825f0304019050808302841793505f600287600302189050808702600203810290508087026002038102905080870260020381029050808702600203810290508087026002038102905080870260020381029050808502955050505050505b9392505050565b5f819050919050565b61192e8161191c565b82525050565b5f6020820190506119475f830184611925565b92915050565b5f62ffffff82169050919050565b6119648161194d565b82525050565b5f60208201905061197d5f83018461195b565b92915050565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6119ac82611983565b9050919050565b6119bc816119a2565b82525050565b5f6020820190506119d55f8301846119b3565b92915050565b5f604051905090565b5f80fd5b6119f18161191c565b81146119fb575f80fd5b50565b5f81519050611a0c816119e8565b92915050565b5f60208284031215611a2757611a266119e4565b5b5f611a34848285016119fe565b91505092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f8160011c9050919050565b5f808291508390505b6001851115611abf57808604811115611a9b57611a9a611a3d565b5b6001851615611aaa5780820291505b8081029050611ab885611a6a565b9450611a7f565b94509492505050565b5f82611ad75760019050611b92565b81611ae4575f9050611b92565b8160018114611afa5760028114611b0457611b33565b6001915050611b92565b60ff841115611b1657611b15611a3d565b5b8360020a915084821115611b2d57611b2c611a3d565b5b50611b92565b5060208310610133831016604e8410600b8410161715611b685782820a905083811115611b6357611b62611a3d565b5b611b92565b611b758484846001611a76565b92509050818404811115611b8c57611b8b611a3d565b5b81810290505b9392505050565b5f611ba38261191c565b9150611bae8361191c565b9250611bdb7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8484611ac8565b905092915050565b5f611bed8261191c565b9150611bf88361191c565b9250828202611c068161191c565b91508282048414831517611c1d57611c1c611a3d565b5b5092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f611c5b8261191c565b9150611c668361191c565b925082611c7657611c75611c24565b5b828204905092915050565b5f60ff82169050919050565b5f611c9782611c81565b9150611ca283611c81565b9250828203905060ff811115611cbb57611cba611a3d565b5b92915050565b5f611ccb8261191c565b9150611cd683611c81565b9250611d037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8484611ac8565b905092915050565b5f611d158261191c565b9150611d208361191c565b9250828201905080821115611d3857611d37611a3d565b5b92915050565b5f611d488261191c565b9150611d538361191c565b9250828203905081811115611d6b57611d6a611a3d565b5b92915050565b5f82825260208201905092915050565b7f53616665436173743a2076616c756520646f65736e27742066697420696e20315f8201527f3630206269747300000000000000000000000000000000000000000000000000602082015250565b5f611ddb602783611d71565b9150611de682611d81565b604082019050919050565b5f6020820190508181035f830152611e0881611dcf565b9050919050565b5f80fd5b5f601f19601f8301169050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b611e5982611e13565b810181811067ffffffffffffffff82111715611e7857611e77611e23565b5b80604052505050565b5f611e8a6119db565b9050611e968282611e50565b919050565b5f67ffffffffffffffff821115611eb557611eb4611e23565b5b602082029050919050565b5f80fd5b5f67ffffffffffffffff821115611ede57611edd611e23565b5b602082029050919050565b5f8160020b9050919050565b611efe81611ee9565b8114611f08575f80fd5b50565b5f81519050611f1981611ef5565b92915050565b5f611f31611f2c84611ec4565b611e81565b90508060208402830185811115611f4b57611f4a611ec0565b5b835b81811015611f745780611f608882611f0b565b845260208401935050602081019050611f4d565b5050509392505050565b5f82601f830112611f9257611f91611e0f565b5b6002611f9f848285611f1f565b91505092915050565b5f611fba611fb584611e9b565b611e81565b90508060408402830185811115611fd457611fd3611ec0565b5b835b81811015611ffd5780611fe98882611f7e565b845260208401935050604081019050611fd6565b5050509392505050565b5f82601f83011261201b5761201a611e0f565b5b6003612028848285611fa8565b91505092915050565b5f60c08284031215612046576120456119e4565b5b5f61205384828501612007565b91505092915050565b61206581611983565b811461206f575f80fd5b50565b5f815190506120808161205c565b92915050565b5f61ffff82169050919050565b61209c81612086565b81146120a6575f80fd5b50565b5f815190506120b781612093565b92915050565b6120c681611c81565b81146120d0575f80fd5b50565b5f815190506120e1816120bd565b92915050565b5f8115159050919050565b6120fb816120e7565b8114612105575f80fd5b50565b5f81519050612116816120f2565b92915050565b5f805f805f805f60e0888a031215612137576121366119e4565b5b5f6121448a828b01612072565b97505060206121558a828b01611f0b565b96505060406121668a828b016120a9565b95505060606121778a828b016120a9565b94505060806121888a828b016120a9565b93505060a06121998a828b016120d3565b92505060c06121aa8a828b01612108565b91505092959891949750929550565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b6121ef8161194d565b81146121f9575f80fd5b50565b5f8151905061220a816121e6565b92915050565b5f60208284031215612225576122246119e4565b5b5f612232848285016121fc565b91505092915050565b5f819050919050565b61224d8161223b565b82525050565b5f6020820190506122665f830184612244565b92915050565b5f6fffffffffffffffffffffffffffffffff82169050919050565b6122908161226c565b811461229a575f80fd5b50565b5f815190506122ab81612287565b92915050565b5f805f805f60a086880312156122ca576122c96119e4565b5b5f6122d78882890161229d565b95505060206122e8888289016119fe565b94505060406122f9888289016119fe565b935050606061230a8882890161229d565b925050608061231b8882890161229d565b9150509295509295909350565b61233181611ee9565b82525050565b5f60208201905061234a5f830184612328565b92915050565b5f81600f0b9050919050565b61236581612350565b811461236f575f80fd5b50565b5f815190506123808161235c565b92915050565b5f8160060b9050919050565b61239b81612386565b81146123a5575f80fd5b50565b5f815190506123b681612392565b92915050565b5f63ffffffff82169050919050565b6123d4816123bc565b81146123de575f80fd5b50565b5f815190506123ef816123cb565b92915050565b5f805f805f805f80610100898b031215612412576124116119e4565b5b5f61241f8b828c0161229d565b98505060206124308b828c01612372565b97505060406124418b828c016119fe565b96505060606124528b828c016119fe565b95505060806124638b828c016123a8565b94505060a06124748b828c01612072565b93505060c06124858b828c016123e1565b92505060e06124968b828c01612108565b9150509295985092959890939650565b5f8160601b9050919050565b5f6124bc826124a6565b9050919050565b5f6124cd826124b2565b9050919050565b6124e56124e0826119a2565b6124c3565b82525050565b5f8160e81b9050919050565b5f612501826124eb565b9050919050565b61251961251482611ee9565b6124f7565b82525050565b5f61252a82866124d4565b60148201915061253a8285612508565b60038201915061254a8284612508565b60038201915081905094935050505056fea2646970667358221220474bca3dd77f9110c17b6496030d7748ab2e55798f7a6a72dd9f8e3358c0547564736f6c634300081a0033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c000000000000000000000000d9069e3f3eeb45d4e05b765142ba28f3beb96f7a

-----Decoded View---------------
Arg [0] : _vault (address): 0x84cC12b9C456B4382E4d9aa12AeA133943cFD36c
Arg [1] : _priceFeed (address): 0xD9069E3F3EEb45d4E05b765142ba28f3BeB96F7a

-----Encoded View---------------
2 Constructor Arguments found :
Arg [0] : 00000000000000000000000084cc12b9c456b4382e4d9aa12aea133943cfd36c
Arg [1] : 000000000000000000000000d9069e3f3eeb45d4e05b765142ba28f3beb96f7a


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
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.