S Price: $0.067702 (+2.05%)
Gas: 55 Gwei

Contract

0x5966E2aC5C3eFaD98F0D57aD92539eF31a06519A

Overview

S Balance

Sonic LogoSonic LogoSonic Logo0 S

S Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
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:
PoolManagerV2

Compiler Version
v0.8.24+commit.e11b9ed9

Optimization Enabled:
Yes with 200 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {IGaugeV3} from "./interfaces/IGaugeV3.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {INonfungiblePositionManager} from "./interfaces/INonfungiblePositionManager.sol";
import {IRamsesV3Factory} from "./interfaces/IRamsesV3Factory.sol";
import {IRamsesV3PoolActions} from "./interfaces/IRamsesV3PoolActions.sol";
import {ISwapRouter} from "./interfaces/ISwapRouter.sol";
import {IVoter} from "./interfaces/IVoter.sol";
import {IFeeDistributor} from "./interfaces/IFeeDistributor.sol";
import {IVoteModule} from "./interfaces/IVoteModule.sol";
import {OptimalSwap, V3PoolCallee} from "./library/OptimalSwap.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {FullMath, FixedPoint96} from "./library/LiquidityAmounts.sol";

contract PoolManagerV2 is Initializable, AccessControlUpgradeable, IERC721Receiver {
    using SafeERC20 for IERC20;

    bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE");

    address public constant ADMIN_ADDRESS = 0x3402Ebe2AD564FF3CA90513fF1a1935364179f6c;
    address public constant VOTER_ADDRESS = 0x9F59398D0a397b2EEB8a6123a6c7295cB0b0062D;
    address public constant ROUTER_ADDRESS = 0x5543c6176FEb9B4b179078205d7C29EEa2e2d695;
    address public constant XSHADOW_ADDRESS = 0x5050bc082FF4A74Fb6B0B04385dEfdDB114b2424;
    address public constant EXECUTOR_ADDRESS = 0x38569E5F28921537499Da81ED14d32b5B4CE95aE;
    address public constant RAMSES_V3_FACTORY = 0xcD2d0637c94fe77C2896BbCBB174cefFb08DE6d7;
    address public constant NFP_MANAGER_ADDRESS = 0x12E66C8F215DdD5d48d150c8f46aD0c6fB0F4406;
    address public constant VOTE_MODULE_ADDRESS = 0xDCB5A24ec708cc13cee12bFE6799A78a79b666b4;
    address public constant X33_ADAPTER_ADDRESS = 0x9710E10A8f6FbA8C391606fee18614885684548d;
    address public constant FEE_DISTRIBUTOR_ADDRESS = 0x392dA14E4B78A634859b5655AF7878d431fB350d; // not found in list but getting rewards from him

    IVoter public constant voter = IVoter(VOTER_ADDRESS);
    ISwapRouter public constant router = ISwapRouter(ROUTER_ADDRESS);
    IVoteModule public constant voteModule = IVoteModule(VOTE_MODULE_ADDRESS);
    IRamsesV3Factory public constant shadowV3Factory = IRamsesV3Factory(RAMSES_V3_FACTORY);
    IFeeDistributor public constant feeDistributor = IFeeDistributor(FEE_DISTRIBUTOR_ADDRESS);
    INonfungiblePositionManager public constant positionManager = INonfungiblePositionManager(NFP_MANAGER_ADDRESS);

    struct Position {
        int24 tickLower;
        int24 tickUpper;
        uint128 liquidity;
        bool isActive;
        uint256 tokenId;
    }

    int24 public maxTick;
    int24 public minTick;
    int24 public tickSpacing;
    int24 public maxTickMovement;
    uint256 public swapSlippage;
    uint256 public mintSlippage;
    uint256 public x33SharesAccumulated;

    IERC20 public token0;
    IERC20 public token1;
    IGaugeV3 public gaugeV3;
    Position public currentPosition;
    IRamsesV3PoolActions public pool;

    uint256[] public pastNftIds;
    uint256[] public currentNftIds;

    event SlippageUpdated(uint256 newSlippage);
    event MinAndMaxTickSet(int24 minTick, int24 maxTick);
    event FundsWithdrawn(uint256 amount0, uint256 amount1);
    event FeesCollected(uint256 tokenId, uint256 amount0, uint256 amount1);
    event LiquidityWithdrawn(uint256 tokenId, uint256 amount0, uint256 amount1);
    event PositionRebalanced(uint256 newTokenId, int24 newTickLower, int24 newTickUpper);
    event TokensSwapped(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);
    event PositionCreated(uint256 tokenId, int24 tickLower, int24 tickUpper, uint128 liquidity);

    error UnfavorableSwap(); // 0x4cc54e84
    error SlippageTooHigh(); // 0x850c6f76
    error InvalidTickRange(); // 0x064847d0
    error NotPositionManager(); // 0x20fdc658
    error PositionNotInRange(); // 0x0a49cb55
    error PositionIsNotActive(); // 0xebb0360f
    error PositionAlreadyActive(); // 0xa37d9646

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /// @notice Initializes the contract with required addresses and roles
    /// @param _token0 Address of the first token in the pair
    /// @param _token1 Address of the second token in the pair
    /// @param _tickSpacing The tick spacing for the pool
    /// @param _minTick The minimum tick for the pool
    /// @param _maxTick The maximum tick for the pool
    function initialize(address _token0, address _token1, int24 _tickSpacing, int24 _minTick, int24 _maxTick)
        public
        initializer
    {
        __AccessControl_init();

        minTick = _minTick;
        maxTick = _maxTick;
        tickSpacing = _tickSpacing;
        maxTickMovement = _tickSpacing * 3;

        token0 = IERC20(_token0);
        token1 = IERC20(_token1);

        gaugeV3 = IGaugeV3(voter.gaugeForClPool(_token0, _token1, _tickSpacing));
        pool = IRamsesV3PoolActions(shadowV3Factory.getPool(_token0, _token1, _tickSpacing));

        if (_tickSpacing == 1) {
            swapSlippage = 1;
        } else if (_tickSpacing == 50) {
            swapSlippage = 10;
        } else if (_tickSpacing == 100) {
            swapSlippage = 20;
        }
        mintSlippage = 1;

        IERC721(NFP_MANAGER_ADDRESS).setApprovalForAll(msg.sender, true);

        _grantRole(DEFAULT_ADMIN_ROLE, ADMIN_ADDRESS);
        _grantRole(EXECUTOR_ROLE, ADMIN_ADDRESS);
        _grantRole(EXECUTOR_ROLE, EXECUTOR_ADDRESS);
        _grantRole(EXECUTOR_ROLE, msg.sender); // granting to PoolManagerFactory

        IERC20(XSHADOW_ADDRESS).approve(X33_ADAPTER_ADDRESS, type(uint256).max);
    }

    /// @notice Rebalances the current liquidity position if it's out of range
    /// @dev Withdraws from the current position if active, then creates a new position with optimal tick range
    function rebalancePosition(uint256 amountOutMinimum) external onlyRole(EXECUTOR_ROLE) {
        if (!isPositionOutOfRange()) return;

        if (currentPosition.isActive) {
            _withdrawLiquidityAndCollectFees(currentPosition.liquidity, currentPosition.tokenId);
        }

        (int24 newTickLower, int24 newTickUpper) = _calculateOptimalTickRange();

        (uint256 finalAmount0, uint256 finalAmount1) = _balanceTokensToOptimalRatio(
            token0.balanceOf(address(this)),
            token1.balanceOf(address(this)),
            newTickLower,
            newTickUpper,
            amountOutMinimum
        );

        _createPosition(finalAmount0, finalAmount1, newTickLower, newTickUpper);

        emit PositionRebalanced(currentPosition.tokenId, newTickLower, newTickUpper);

        (, int24 currentTick,,,,,) = pool.slot0();
        if (currentTick < newTickLower || currentTick > newTickUpper) revert PositionNotInRange();
    }

    /// @notice Withdraws all liquidity from the current position and collects accrued fees
    /// @dev Decreases liquidity to zero and collects all tokens back to contract
    function withdrawAllLiquidityAndCollectFees()
        public
        onlyRole(EXECUTOR_ROLE)
        returns (uint256 collectedAmount0, uint256 collectedAmount1)
    {
        uint256 tokenId = currentPosition.tokenId;
        (,,,,, uint128 liquidity,,,,) = positionManager.positions(tokenId);
        return _withdrawLiquidityAndCollectFees(liquidity, tokenId);
    }

    /// @notice Withdraws the specified amount of liquidity from the current position and collects accrued fees
    /// @dev Decreases partial liquidity from the current position and collects accrued fees
    /// @param liquidity Amount of liquidity to withdraw
    function withdrawLiquidityAndCollectFees(uint128 liquidity)
        public
        onlyRole(EXECUTOR_ROLE)
        returns (uint256 collectedAmount0, uint256 collectedAmount1)
    {
        uint256 tokenId = currentPosition.tokenId;
        return _withdrawLiquidityAndCollectFees(liquidity, tokenId);
    }

    /// @notice Function to withdraw all tokens from the contract
    /// @dev Withdraws from any active position and transfers all tokens to the caller
    function withdrawFunds() external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (currentPosition.isActive) withdrawAllLiquidityAndCollectFees();

        uint256 amount0 = token0.balanceOf(address(this));
        uint256 amount1 = token1.balanceOf(address(this));

        token0.safeTransfer(msg.sender, amount0);
        token1.safeTransfer(msg.sender, amount1);

        delete currentPosition;
        emit FundsWithdrawn(amount0, amount1);
    }

    /// @notice Function to withdraw all reward tokens from the contract
    /// @param otherTokenRewards Array of additional reward tokens to withdraw
    function withdrawTokenRewards(address[] memory otherTokenRewards) external onlyRole(DEFAULT_ADMIN_ROLE) {
        address[] memory tokenRewards = gaugeV3.getRewardTokens();
        uint256 length = tokenRewards.length;

        for (uint256 i = 0; i < length; i++) {
            if (tokenRewards[i] == XSHADOW_ADDRESS) continue;
            uint256 amount = IERC20(tokenRewards[i]).balanceOf(address(this));
            IERC20(tokenRewards[i]).safeTransfer(msg.sender, amount);
        }

        length = otherTokenRewards.length;
        if (length == 0) return;
        for (uint256 i = 0; i < length; i++) {
            uint256 amount = IERC20(otherTokenRewards[i]).balanceOf(address(this));
            IERC20(otherTokenRewards[i]).safeTransfer(msg.sender, amount);
        }
    }

    /// @notice Updates the swap slippage tolerance
    /// @param _newSlippage The new slippage tolerance
    /// @dev The slippage tolerance is used to check the amount of error allowed in the swap calculation.
    function setSwapSlippage(uint256 _newSlippage) external onlyRole(EXECUTOR_ROLE) {
        if (_newSlippage > 99) revert SlippageTooHigh();
        swapSlippage = _newSlippage;
        emit SlippageUpdated(_newSlippage);
    }

    /// @notice Updates the mint slippage tolerance
    /// @param _newSlippage The new slippage tolerance
    /// @dev The slippage tolerance is used to check the amount of error allowed in the mint calculation.
    function setMintSlippage(uint256 _newSlippage) external onlyRole(EXECUTOR_ROLE) {
        if (_newSlippage > 99) revert SlippageTooHigh();
        mintSlippage = _newSlippage;
        emit SlippageUpdated(_newSlippage);
    }

    /// @notice Sets the minimum and maximum tick for the pool
    /// @param _minTick The minimum tick
    /// @param _maxTick The maximum tick
    function setMinAndMaxTick(int24 _minTick, int24 _maxTick) external onlyRole(EXECUTOR_ROLE) {
        if (_minTick < -887280 || _maxTick > 887280) revert InvalidTickRange();
        minTick = _minTick;
        maxTick = _maxTick;
        emit MinAndMaxTickSet(_minTick, _maxTick);
    }

    /// @notice Claims past rewards for a specific NFT
    /// @param tokenId The ID of the NFT to claim rewards for
    function claimPastRewards(uint256 tokenId) external onlyRole(DEFAULT_ADMIN_ROLE) {
        gaugeV3.getReward(tokenId, gaugeV3.getRewardTokens());
    }

    /// @notice Updates the current NFT IDs
    /// @dev This function updates the current NFT IDs by moving the past NFT IDs to the current NFT IDs
    function updateCurrentNftIds() external onlyRole(EXECUTOR_ROLE) {
        uint256 length = currentNftIds.length;
        for (uint256 i = 0; i < length; i++) {
            if (currentNftIds[i] == currentPosition.tokenId) continue;
            pastNftIds.push(currentNftIds[i]);
        }

        currentNftIds = new uint256[](0);
        currentNftIds.push(currentPosition.tokenId);
    }

    /// @notice Swaps xShadow tokens to x33 tokens
    /// @dev This function swaps xShadow tokens to x33 tokens using the x33 adapter
    function swapXshadowTox33Tokens() external onlyRole(EXECUTOR_ROLE) {
        uint256 xShadowBalance = IERC20(XSHADOW_ADDRESS).balanceOf(address(this));
        if (xShadowBalance == 0) return;
        x33SharesAccumulated += IERC4626(X33_ADAPTER_ADDRESS).deposit(xShadowBalance, address(this));
    }

    /// @notice Gets rewards from the vote module
    /// @dev This function is used to get rewards from the vote module
    function getRewardsFromVoteModule() external onlyRole(EXECUTOR_ROLE) {
        voteModule.getReward();
    }

    /// @notice Claims incentives from the voter
    /// @dev This function is used to claim incentives from the voter
    function claimingIncentivesFromVoter() external onlyRole(EXECUTOR_ROLE) {
        address[] memory _feeDistributors = new address[](1);
        _feeDistributors[0] = FEE_DISTRIBUTOR_ADDRESS;

        address[] memory _tokens = feeDistributor.getRewardTokens();
        address[][] memory tokens = new address[][](1);
        tokens[0] = new address[](_tokens.length);

        for (uint256 i = 0; i < _tokens.length; i++) {
            tokens[0][i] = _tokens[i];
        }
        voter.claimIncentives(address(this), _feeDistributors, tokens);
    }

    /// @notice Checks if the current position is out of range
    /// @dev A position is out of range if current position is not active, or if the current tick is outside the position's range
    /// @return True if the position is out of range, false otherwise
    function isPositionOutOfRange() public view returns (bool) {
        if (!currentPosition.isActive) return true;

        (, int24 currentTick,,,,,) = pool.slot0();
        if (!_isTickMovementSafe(currentTick)) return false;

        return currentTick < currentPosition.tickLower || currentTick >= currentPosition.tickUpper;
    }

    /// @notice Returns the current NFT IDs
    /// @return The current NFT IDs
    function getCurrentNftIds() external view returns (uint256[] memory) {
        return currentNftIds;
    }

    /// @notice Returns the past NFT IDs
    /// @return The past NFT IDs
    function getPastNftIds() external view returns (uint256[] memory) {
        return pastNftIds;
    }

    /// @notice Calculates the optimal swap amount for slippage. MEANT TO BE STATIC CALL ONLY!
    /// @dev Withdraws from the current position if active, then calculates the optimal swap amount
    /// @return amountIn The amount of tokenIn to swap
    /// @return zeroForOne True if the swap is from token0 to token1, false otherwise
    /// @return token0 The address of token0
    /// @return token1 The address of token1
    function calculateOptimalSwapForSlippageStaticCall()
        external
        onlyRole(EXECUTOR_ROLE)
        returns (uint256, bool, address, address)
    {
        if (currentPosition.isActive) {
            _withdrawLiquidityAndCollectFees(currentPosition.liquidity, currentPosition.tokenId);
        }
        (int24 newTickLower, int24 newTickUpper) = _calculateOptimalTickRange();

        (uint256 amountIn,, bool zeroForOne,) = OptimalSwap.getOptimalSwap(
            V3PoolCallee.wrap(address(pool)),
            newTickLower,
            newTickUpper,
            token0.balanceOf(address(this)),
            token1.balanceOf(address(this))
        );

        return (amountIn, zeroForOne, address(token0), address(token1));
    }

    /// @notice Calculates the minimum amount out for a given amount in (inaccurate)
    /// @dev This method is used only when minAmountOut is not passed from the executor
    /// @param tokenIn The address of the token in
    /// @param tokenOut The address of the token out
    /// @param amountIn The amount of token in
    /// @return The minimum amount out
    function calculateMinAmountOut(address tokenIn, address tokenOut, uint256 amountIn) public view returns (uint256) {
        address USDC_e = 0x29219dd400f2Bf60E5a23d13Be72B486D4038894;
        address USDT = 0x6047828dc181963ba44974801FF68e538dA5eaF9;
        uint256 decimalsIn = 18;
        uint256 decimalsOut = 18;

        (uint160 sqrtPriceX96,,,,,,) = pool.slot0();
        bool zeroForOne = tokenIn < tokenOut;
        uint256 priceX96 = FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint96.Q96);

        uint256 expectedAmountOut;
        if (zeroForOne) {
            // amountOut = amountIn * price
            expectedAmountOut = FullMath.mulDiv(amountIn, priceX96, FixedPoint96.Q96);
        } else {
            // amountOut = amountIn / price
            expectedAmountOut = FullMath.mulDiv(amountIn, FixedPoint96.Q96, priceX96);
        }

        if (tokenIn == USDC_e || tokenIn == USDT) decimalsIn = 6;
        if (tokenOut == USDC_e || tokenOut == USDT) decimalsOut = 6;

        return expectedAmountOut * (100 - swapSlippage) / 100;
    }

    /// @notice Sets the maximum tick movement
    /// @param _maxTickMovement The maximum tick movement
    function setMaxTickMovement(int24 _maxTickMovement) external onlyRole(EXECUTOR_ROLE) {
        maxTickMovement = _maxTickMovement;
    }

    function _withdrawLiquidityAndCollectFees(uint128 liquidity, uint256 tokenId)
        internal
        returns (uint256 collectedAmount0, uint256 collectedAmount1)
    {
        if (!currentPosition.isActive) revert PositionIsNotActive();

        uint256 withdrawnAmount0 = 0;
        uint256 withdrawnAmount1 = 0;

        if (liquidity > 0) {
            (withdrawnAmount0, withdrawnAmount1) = positionManager.decreaseLiquidity(
                INonfungiblePositionManager.DecreaseLiquidityParams({
                    tokenId: tokenId,
                    liquidity: liquidity,
                    amount0Min: 0,
                    amount1Min: 0,
                    deadline: block.timestamp + 300
                })
            );
            emit LiquidityWithdrawn(tokenId, withdrawnAmount0, withdrawnAmount1);
        }

        (collectedAmount0, collectedAmount1) = positionManager.collect(
            INonfungiblePositionManager.CollectParams({
                tokenId: tokenId,
                recipient: address(this),
                amount0Max: type(uint128).max,
                amount1Max: type(uint128).max
            })
        );

        delete currentPosition;

        uint256 feesAmount0 = collectedAmount0 - withdrawnAmount0;
        uint256 feesAmount1 = collectedAmount1 - withdrawnAmount1;

        emit FeesCollected(tokenId, feesAmount0, feesAmount1);
    }

    /// @notice Balances token amounts to achieve the optimal ratio for the given tick range
    /// @dev Uses OptimalSwap library to calculate and execute the optimal swap
    /// @param amount0 The current amount of token0
    /// @param amount1 The current amount of token1
    /// @param tickLower The lower tick of the target range
    /// @param tickUpper The upper tick of the target range
    /// @return finalAmount0 The final amount of token0 after balancing
    /// @return finalAmount1 The final amount of token1 after balancing
    function _balanceTokensToOptimalRatio(
        uint256 amount0,
        uint256 amount1,
        int24 tickLower,
        int24 tickUpper,
        uint256 amountOutMinimum
    ) internal returns (uint256 finalAmount0, uint256 finalAmount1) {
        (uint256 amountIn,, bool zeroForOne,) =
            OptimalSwap.getOptimalSwap(V3PoolCallee.wrap(address(pool)), tickLower, tickUpper, amount0, amount1);

        if (amountIn > 0) {
            if (zeroForOne) {
                if (amountIn > amount0) revert UnfavorableSwap();
                _swapTokens(address(token0), address(token1), amountIn, amountOutMinimum);
            } else {
                if (amountIn > amount1) revert UnfavorableSwap();
                _swapTokens(address(token1), address(token0), amountIn, amountOutMinimum);
            }
        }

        finalAmount0 = token0.balanceOf(address(this));
        finalAmount1 = token1.balanceOf(address(this));

        return (finalAmount0, finalAmount1);
    }

    /// @notice Swaps tokens using the Ramses V3 Swap Router
    /// @dev Gets a quote first, then executes the swap with 1% slippage tolerance
    /// @param tokenIn The address of the token to swap from
    /// @param tokenOut The address of the token to swap to
    /// @param amountToSwap The amount of tokenIn to swap
    /// @return amountOut The amount of tokenOut received
    function _swapTokens(address tokenIn, address tokenOut, uint256 amountToSwap, uint256 amountOutMinimum)
        internal
        returns (uint256 amountOut)
    {
        if (amountToSwap == 0) return 0;

        if (amountOutMinimum == 0) {
            amountOutMinimum = calculateMinAmountOut(tokenIn, tokenOut, amountToSwap);
        }

        IERC20(tokenIn).safeIncreaseAllowance(address(router), amountToSwap);
        amountOut = router.exactInputSingle(
            ISwapRouter.ExactInputSingleParams({
                tokenIn: tokenIn,
                tokenOut: tokenOut,
                tickSpacing: tickSpacing,
                recipient: address(this),
                deadline: block.timestamp + 300,
                amountIn: amountToSwap,
                amountOutMinimum: amountOutMinimum,
                sqrtPriceLimitX96: 0
            })
        );

        emit TokensSwapped(tokenIn, tokenOut, amountToSwap, amountOut);

        return amountOut;
    }

    /// @notice Creates a new liquidity position
    /// @dev Mints a new position NFT and updates the currentPosition struct
    /// @param amount0 The amount of token0 to add to the position
    /// @param amount1 The amount of token1 to add to the position
    /// @param tickLower The lower tick of the position's range
    /// @param tickUpper The upper tick of the position's range
    function _createPosition(uint256 amount0, uint256 amount1, int24 tickLower, int24 tickUpper) internal {
        if (currentPosition.isActive) revert PositionAlreadyActive();

        token0.safeIncreaseAllowance(address(positionManager), amount0);
        token1.safeIncreaseAllowance(address(positionManager), amount1);

        (uint256 tokenId, uint128 liquidity,,) = positionManager.mint(
            INonfungiblePositionManager.MintParams({
                token0: address(token0),
                token1: address(token1),
                tickSpacing: tickSpacing,
                tickLower: tickLower,
                tickUpper: tickUpper,
                amount0Desired: amount0,
                amount1Desired: amount1,
                amount0Min: amount0 * (100 - mintSlippage) / 100,
                amount1Min: amount1 * (100 - mintSlippage) / 100,
                recipient: address(this),
                deadline: block.timestamp + 300
            })
        );

        currentPosition.tokenId = tokenId;
        currentPosition.isActive = true;
        currentPosition.liquidity = liquidity;
        currentPosition.tickLower = tickLower;
        currentPosition.tickUpper = tickUpper;

        currentNftIds.push(tokenId);

        emit PositionCreated(tokenId, tickLower, tickUpper, liquidity);
    }

    /// @notice Checks if a tick movement is within safe bounds
    /// @dev Ensures the tick is within global bounds and not too far from the current position
    /// @param newTick The new tick to check
    /// @return True if the tick movement is safe, false otherwise
    function _isTickMovementSafe(int24 newTick) internal view returns (bool) {
        if (newTick < minTick || newTick > maxTick) return false;

        if (!currentPosition.isActive) return true;

        int24 tickDelta = newTick > currentPosition.tickLower
            ? newTick - currentPosition.tickLower
            : currentPosition.tickLower - newTick;

        return tickDelta <= maxTickMovement;
    }

    /// @notice Calculates the optimal tick range for a new position based on current pool state
    /// @dev Current tick should be between minTick and maxTick
    /// @return tickLower The lower tick of the range
    /// @return tickUpper The upper tick of the range
    function _calculateOptimalTickRange() internal view returns (int24 tickLower, int24 tickUpper) {
        (, int24 currentTick,,,,,) = pool.slot0();

        if (currentTick < 0) {
            tickLower = ((currentTick - (tickSpacing - 1)) / tickSpacing) * tickSpacing;
        } else {
            tickLower = (currentTick / tickSpacing) * tickSpacing;
        }

        tickUpper = tickLower + tickSpacing;

        return (tickLower, tickUpper);
    }

    /// @notice Called by the position manager when a position is minted
    /// @dev Implements IERC721Receiver for NFT transfers
    function onERC721Received(address, address, uint256, bytes calldata) external view override returns (bytes4) {
        if (msg.sender != address(positionManager)) revert NotPositionManager();
        return this.onERC721Received.selector;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;


    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
    struct AccessControlStorage {
        mapping(bytes32 role => RoleData) _roles;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;

    function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
        assembly {
            $.slot := AccessControlStorageLocation
        }
    }

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        AccessControlStorage storage $ = _getAccessControlStorage();
        bytes32 previousAdminRole = getRoleAdmin(role);
        $._roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (!hasRole(role, account)) {
            $._roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (hasRole(role, account)) {
            $._roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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);
}

File 4 of 27 : IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.20;

/**
 * @title ERC-721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC-721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

interface IGaugeV3 {
    error NOT_AUTHORIZED();
    error NOT_VOTER();
    error NOT_GT_ZERO(uint256 amt);
    error CANT_CLAIM_FUTURE();
    error RETRO();

    /// @notice Emitted when a reward notification is made.
    /// @param from The address from which the reward is notified.
    /// @param reward The address of the reward token.
    /// @param amount The amount of rewards notified.
    /// @param period The period for which the rewards are notified.
    event NotifyReward(
        address indexed from,
        address indexed reward,
        uint256 amount,
        uint256 period
    );

    /// @notice Emitted when a bribe is made.
    /// @param from The address from which the bribe is made.
    /// @param reward The address of the reward token.
    /// @param amount The amount of tokens bribed.
    /// @param period The period for which the bribe is made.
    event Bribe(
        address indexed from,
        address indexed reward,
        uint256 amount,
        uint256 period
    );

    /// @notice Emitted when rewards are claimed.
    /// @param period The period for which the rewards are claimed.
    /// @param _positionHash The identifier of the NFP for which rewards are claimed.
    /// @param receiver The address of the receiver of the claimed rewards.
    /// @param reward The address of the reward token.
    /// @param amount The amount of rewards claimed.
    event ClaimRewards(
        uint256 period,
        bytes32 _positionHash,
        address receiver,
        address reward,
        uint256 amount
    );

    /// @notice Emitted when a new reward token was pushed to the rewards array
    event RewardAdded(address reward);

    /// @notice Emitted when a reward token was removed from the rewards array
    event RewardRemoved(address reward);

    /// @notice Retrieves the value of the firstPeriod variable.
    /// @return The value of the firstPeriod variable.
    function firstPeriod() external returns (uint256);

    /// @notice Retrieves the total supply of a specific token for a given period.
    /// @param period The period for which to retrieve the total supply.
    /// @param token The address of the token for which to retrieve the total supply.
    /// @return The total supply of the specified token for the given period.
    function tokenTotalSupplyByPeriod(
        uint256 period,
        address token
    ) external view returns (uint256);

    /// @notice Retrieves the getTokenTotalSupplyByPeriod of the current period.
    /// @dev included to support voter's left() check during distribute().
    /// @param token The address of the token for which to retrieve the remaining amount.
    /// @return The amount of tokens left to distribute in this period.
    function left(address token) external view returns (uint256);

    /// @notice Retrieves the reward rate for a specific reward address.
    /// @dev this method returns the base rate without boost
    /// @param token The address of the reward for which to retrieve the reward rate.
    /// @return The reward rate for the specified reward address.
    function rewardRate(address token) external view returns (uint256);

    /// @notice Retrieves the claimed amount for a specific period, position hash, and user address.
    /// @param period The period for which to retrieve the claimed amount.
    /// @param _positionHash The identifier of the NFP for which to retrieve the claimed amount.
    /// @param reward The address of the token for the claimed amount.
    /// @return The claimed amount for the specified period, token ID, and user address.
    function periodClaimedAmount(
        uint256 period,
        bytes32 _positionHash,
        address reward
    ) external view returns (uint256);

    /// @notice Retrieves the last claimed period for a specific token, token ID combination.
    /// @param token The address of the reward token for which to retrieve the last claimed period.
    /// @param _positionHash The identifier of the NFP for which to retrieve the last claimed period.
    /// @return The last claimed period for the specified token and token ID.
    function lastClaimByToken(
        address token,
        bytes32 _positionHash
    ) external view returns (uint256);

    /// @notice Retrieves the reward address at the specified index in the rewards array.
    /// @param index The index of the reward address to retrieve.
    /// @return The reward address at the specified index.
    function rewards(uint256 index) external view returns (address);

    /// @notice Checks if a given address is a valid reward.
    /// @param reward The address to check.
    /// @return A boolean indicating whether the address is a valid reward.
    function isReward(address reward) external view returns (bool);

    /// @notice Returns an array of reward token addresses.
    /// @return An array of reward token addresses.
    function getRewardTokens() external view returns (address[] memory);

    /// @notice Returns the hash used to store positions in a mapping
    /// @param owner The address of the position owner
    /// @param index The index of the position
    /// @param tickLower The lower tick boundary of the position
    /// @param tickUpper The upper tick boundary of the position
    /// @return _hash The hash used to store positions in a mapping
    function positionHash(
        address owner,
        uint256 index,
        int24 tickLower,
        int24 tickUpper
    ) external pure returns (bytes32);

    /*
    /// @notice Retrieves the liquidity and boosted liquidity for a specific NFP.
    /// @param tokenId The identifier of the NFP.
    /// @return liquidity The liquidity of the position token.
    function positionInfo(
        uint256 tokenId
    ) external view returns (uint128 liquidity);
    */

    /// @notice Returns the amount of rewards earned for an NFP.
    /// @param token The address of the token for which to retrieve the earned rewards.
    /// @param tokenId The identifier of the specific NFP for which to retrieve the earned rewards.
    /// @return reward The amount of rewards earned for the specified NFP and tokens.
    function earned(
        address token,
        uint256 tokenId
    ) external view returns (uint256 reward);

    /// @notice Returns the amount of rewards earned during a period for an NFP.
    /// @param period The period for which to retrieve the earned rewards.
    /// @param token The address of the token for which to retrieve the earned rewards.
    /// @param tokenId The identifier of the specific NFP for which to retrieve the earned rewards.
    /// @return reward The amount of rewards earned for the specified NFP and tokens.
    function periodEarned(
        uint256 period,
        address token,
        uint256 tokenId
    ) external view returns (uint256);

    /// @notice Retrieves the earned rewards for a specific period, token, owner, index, tickLower, and tickUpper.
    /// @param period The period for which to retrieve the earned rewards.
    /// @param token The address of the token for which to retrieve the earned rewards.
    /// @param owner The address of the owner for which to retrieve the earned rewards.
    /// @param index The index for which to retrieve the earned rewards.
    /// @param tickLower The tick lower bound for which to retrieve the earned rewards.
    /// @param tickUpper The tick upper bound for which to retrieve the earned rewards.
    /// @return The earned rewards for the specified period, token, owner, index, tickLower, and tickUpper.
    function periodEarned(
        uint256 period,
        address token,
        address owner,
        uint256 index,
        int24 tickLower,
        int24 tickUpper
    ) external view returns (uint256);

    /// @notice Retrieves the earned rewards for a specific period, token, owner, index, tickLower, and tickUpper.
    /// @dev used by getReward() and saves gas by saving states
    /// @param period The period for which to retrieve the earned rewards.
    /// @param token The address of the token for which to retrieve the earned rewards.
    /// @param owner The address of the owner for which to retrieve the earned rewards.
    /// @param index The index for which to retrieve the earned rewards.
    /// @param tickLower The tick lower bound for which to retrieve the earned rewards.
    /// @param tickUpper The tick upper bound for which to retrieve the earned rewards.
    /// @param caching Whether to cache the results or not.
    /// @return The earned rewards for the specified period, token, owner, index, tickLower, and tickUpper.
    function cachePeriodEarned(
        uint256 period,
        address token,
        address owner,
        uint256 index,
        int24 tickLower,
        int24 tickUpper,
        bool caching
    ) external returns (uint256);

    /// @notice Notifies the contract about the amount of rewards to be distributed for a specific token.
    /// @param token The address of the token for which to notify the reward amount.
    /// @param amount The amount of rewards to be distributed.
    function notifyRewardAmount(address token, uint256 amount) external;

    /// @notice Retrieves the reward amount for a specific period, NFP, and token addresses.
    /// @param period The period for which to retrieve the reward amount.
    /// @param tokens The addresses of the tokens for which to retrieve the reward amount.
    /// @param tokenId The identifier of the specific NFP for which to retrieve the reward amount.
    /// @param receiver The address of the receiver of the reward amount.
    function getPeriodReward(
        uint256 period,
        address[] calldata tokens,
        uint256 tokenId,
        address receiver
    ) external;

    /// @notice Retrieves the rewards for a specific period, set of tokens, owner, index, tickLower, tickUpper, and receiver.
    /// @param period The period for which to retrieve the rewards.
    /// @param tokens An array of token addresses for which to retrieve the rewards.
    /// @param owner The address of the owner for which to retrieve the rewards.
    /// @param index The index for which to retrieve the rewards.
    /// @param tickLower The tick lower bound for which to retrieve the rewards.
    /// @param tickUpper The tick upper bound for which to retrieve the rewards.
    /// @param receiver The address of the receiver of the rewards.
    function getPeriodReward(
        uint256 period,
        address[] calldata tokens,
        address owner,
        uint256 index,
        int24 tickLower,
        int24 tickUpper,
        address receiver
    ) external;

    /// @notice retrieves rewards based on an NFP id and an array of tokens
    function getReward(uint256 tokenId, address[] memory tokens) external;
    /// @notice retrieves rewards based on an array of NFP ids and an array of tokens
    function getReward(
        uint256[] calldata tokenIds,
        address[] memory tokens
    ) external;
    /// @notice get reward for an owner of an NFP
    function getRewardForOwner(
        uint256 tokenId,
        address[] memory tokens
    ) external;

    function addRewards(address reward) external;

    function removeRewards(address reward) external;

    /// @notice Notifies rewards for periods greater than current period
    /// @dev does not push fees
    /// @dev requires reward token to be whitelisted
    function notifyRewardAmountForPeriod(
        address token,
        uint256 amount,
        uint256 period
    ) external;

    /// @notice Notifies rewards for the next period
    /// @dev does not push fees
    /// @dev requires reward token to be whitelisted
    function notifyRewardAmountNextPeriod(
        address token,
        uint256 amount
    ) external;

    function getReward(
        address owner,
        uint256 index,
        int24 tickLower,
        int24 tickUpper,
        address[] memory tokens,
        address receiver
    ) external;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager {
    /// @notice Returns the position information associated with a given token ID.
    /// @dev Throws if the token ID is not valid.
    /// @param tokenId The ID of the token that represents the position
    /// @return token0 The address of the token0 for a specific pool
    /// @return token1 The address of the token1 for a specific pool
    /// @return tickSpacing The tickSpacing the pool
    /// @return tickLower The lower end of the tick range for the position
    /// @return tickUpper The higher end of the tick range for the position
    /// @return liquidity The liquidity of the position
    /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
    /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
    /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
    /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
    function positions(uint256 tokenId)
        external
        view
        returns (
            address token0,
            address token1,
            int24 tickSpacing,
            int24 tickLower,
            int24 tickUpper,
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    struct MintParams {
        address token0;
        address token1;
        int24 tickSpacing;
        int24 tickLower;
        int24 tickUpper;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        address recipient;
        uint256 deadline;
    }

    /// @notice Creates a new position wrapped in a NFT
    /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
    /// a method does not exist, i.e. the pool is assumed to be initialized.
    /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
    /// @return tokenId The ID of the token that represents the minted position
    /// @return liquidity The amount of liquidity for this position
    /// @return amount0 The amount of token0
    /// @return amount1 The amount of token1
    function mint(MintParams calldata params)
        external
        payable
        returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);

    struct IncreaseLiquidityParams {
        uint256 tokenId;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
    /// @param params tokenId The ID of the token for which liquidity is being increased,
    /// amount0Desired The desired amount of token0 to be spent,
    /// amount1Desired The desired amount of token1 to be spent,
    /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
    /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
    /// deadline The time by which the transaction must be included to effect the change
    /// @return liquidity The new liquidity amount as a result of the increase
    /// @return amount0 The amount of token0 to acheive resulting liquidity
    /// @return amount1 The amount of token1 to acheive resulting liquidity
    function increaseLiquidity(IncreaseLiquidityParams calldata params)
        external
        payable
        returns (uint128 liquidity, uint256 amount0, uint256 amount1);

    struct DecreaseLiquidityParams {
        uint256 tokenId;
        uint128 liquidity;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    /// @notice Decreases the amount of liquidity in a position and accounts it to the position
    /// @param params tokenId The ID of the token for which liquidity is being decreased,
    /// amount The amount by which liquidity will be decreased,
    /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
    /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
    /// deadline The time by which the transaction must be included to effect the change
    /// @return amount0 The amount of token0 accounted to the position's tokens owed
    /// @return amount1 The amount of token1 accounted to the position's tokens owed
    function decreaseLiquidity(DecreaseLiquidityParams calldata params)
        external
        payable
        returns (uint256 amount0, uint256 amount1);

    struct CollectParams {
        uint256 tokenId;
        address recipient;
        uint128 amount0Max;
        uint128 amount1Max;
    }

    /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
    /// @param params tokenId The ID of the NFT for which tokens are being collected,
    /// recipient The account that should receive the tokens,
    /// amount0Max The maximum amount of token0 to collect,
    /// amount1Max The maximum amount of token1 to collect
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);

    /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
    /// must be collected first.
    /// @param tokenId The ID of the token that is being burned
    function burn(uint256 tokenId) external payable;

    /// @notice Claims gauge rewards from liquidity incentives for a specific tokenId
    /// @param tokenId The ID of the token to claim rewards from
    /// @param tokens an array of reward tokens to claim
    function getReward(uint256 tokenId, address[] calldata tokens) external;
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

/// @title The interface for the Ramses V3 Factory
/// @notice The Ramses V3 Factory facilitates creation of Ramses V3 pools and control over the protocol fees
interface IRamsesV3Factory {
    /// @notice Returns the pool address for a given pair of tokens and a tickSpacing, or address 0 if it does not exist
    /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
    /// @dev unlike UniswapV3, we map via the tickSpacing rather than the fee tier
    /// @param tokenA The contract address of either token0 or token1
    /// @param tokenB The contract address of the other token
    /// @param tickSpacing The tickSpacing of the pool
    /// @return pool The pool address
    function getPool(address tokenA, address tokenB, int24 tickSpacing) external view returns (address pool);
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IRamsesV3PoolState} from "./IRamsesV3PoolState.sol";

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IRamsesV3PoolActions is IRamsesV3PoolState {
    /// @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 index The index 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,
        uint256 index,
        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 index The index of the position to be 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,
        uint256 index,
        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 index The index for which the liquidity will be burned
    /// @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(uint256 index, 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.7.5;

/// @dev original UniswapV3 callbacks maintained to ensure seamless integrations

/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
    /// @dev In the implementation you must pay the pool tokens owed for the swap.
    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
    function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external;
}

/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        int24 tickSpacing;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another token
    /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);

    struct ExactInputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);

    struct ExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        int24 tickSpacing;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another token
    /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);

    struct ExactOutputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

interface IVoter {
    /// @notice returns the gauge address of a CL pool
    /// @param tokenA address of token A in the pair
    /// @param tokenB address of token B in the pair
    /// @param tickSpacing tickspacing of the pool
    /// @return gauge address of the gauge
    function gaugeForClPool(address tokenA, address tokenB, int24 tickSpacing) external view returns (address gauge);

    /// @notice claim concentrated liquidity gauge rewards for specific NFP token ids
    /// @param _gauges array of gauges
    /// @param _tokens two dimensional array for the tokens to claim
    /// @param _nfpTokenIds two dimensional array for the NFPs
    function claimClGaugeRewards(
        address[] calldata _gauges,
        address[][] calldata _tokens,
        uint256[][] calldata _nfpTokenIds
    ) external;

    /// @notice claim arbitrary rewards from specific feeDists
    /// @param owner address of the owner
    /// @param _feeDistributors address of the feeDists
    /// @param _tokens two dimensional array for the tokens to claim
    function claimIncentives(address owner, address[] calldata _feeDistributors, address[][] calldata _tokens)
        external;
}

File 12 of 27 : IFeeDistributor.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

interface IFeeDistributor {
    /// @notice gives an array of reward tokens for the feedist
    /// @return _rewards array of rewards
    function getRewardTokens() external view returns (address[] memory _rewards);
}

File 13 of 27 : IVoteModule.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

interface IVoteModule {
    /// @notice claims pending rebase rewards
    function getReward() external;
}

File 14 of 27 : OptimalSwap.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.4.0 >=0.5.0 >=0.8.4 >=0.8.8 ^0.8.4;

// node_modules/@aperture_finance/uni-v3-lib/src/BitMath.sol

/// @title BitMath
/// @author Aperture Finance
/// @author Modified from Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibBit.sol)
/// @dev This library provides functionality for computing bit properties of an unsigned integer
library BitMath {
    /// @notice Returns the index of the most significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @dev The function satisfies the property:
    ///     If x == 0, r == 0. Otherwise
    ///     x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)
    /// @param x the value for which to compute the most significant bit
    /// @return r the index of the most significant bit
    function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
        assembly {
            // r = x >= 2**128 ? 128 : 0
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            // r += (x >> r) >= 2**64 ? 64 : 0
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            // r += (x >> r) >= 2**32 ? 32 : 0
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            r := or(
                r,
                byte(
                    and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                    0x0706060506020504060203020504030106050205030304010505030400000000
                )
            )
        }
    }

    /// @notice Returns the index of the least significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @dev The function satisfies the property:
    ///     If x == 0, r == 0. Otherwise
    ///     (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)
    /// @param x the value for which to compute the least significant bit
    /// @return r the index of the least significant bit
    function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
        assembly {
            // Isolate the least significant bit, x = x & -x = x & (~x + 1)
            x := and(x, sub(0, x))

            // r = x >= 2**128 ? 128 : 0
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            // r += (x >> r) >= 2**64 ? 64 : 0
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            // r += (x >> r) >= 2**32 ? 32 : 0
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))

            // For the remaining 32 bits, use a De Bruijn lookup.
            // https://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup
            r := or(
                r,
                byte(
                    and(div(0xd76453e0, shr(r, x)), 0x1f),
                    0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405
                )
            )
        }
    }
}

// node_modules/@aperture_finance/uni-v3-lib/src/SafeCast.sol

/// @title Safe casting methods
/// @author Aperture Finance
/// @author Modified from Uniswap (https://github.com/uniswap/v3-core/blob/main/contracts/libraries/SafeCast.sol)
/// @notice Contains methods for safely casting between types
library SafeCast {
    /// @notice Cast a uint256 to a uint160, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return The downcasted integer, now type uint160
    function toUint160(uint256 x) internal pure returns (uint160) {
        if (x >= 1 << 160) revert();
        return uint160(x);
    }

    /// @notice Cast a uint256 to a uint128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return The downcasted integer, now type uint128
    function toUint128(uint256 x) internal pure returns (uint128) {
        if (x >= 1 << 128) revert();
        return uint128(x);
    }

    /// @notice Cast a int256 to a int128, revert on overflow or underflow
    /// @param x The int256 to be downcasted
    /// @return The downcasted integer, now type int128
    function toInt128(int256 x) internal pure returns (int128) {
        unchecked {
            if (((1 << 127) + uint256(x)) >> 128 == uint256(0)) return int128(x);
            revert();
        }
    }

    /// @notice Cast a uint256 to a int256, revert on overflow
    /// @param x The uint256 to be casted
    /// @return The casted integer, now type int256
    function toInt256(uint256 x) internal pure returns (int256) {
        if (int256(x) >= 0) return int256(x);
        revert();
    }

    /// @notice Cast a uint256 to a int128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return The downcasted integer, now type int128
    function toInt128(uint256 x) internal pure returns (int128) {
        if (x >= 1 << 127) revert();
        return int128(int256(x));
    }
}

// node_modules/@aperture_finance/uni-v3-lib/src/TernaryLib.sol

/// @title Library for efficient ternary operations
/// @author Aperture Finance
library TernaryLib {
    /// @notice Equivalent to the ternary operator: `condition ? a : b`
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256 res) {
        assembly {
            res := xor(b, mul(xor(a, b), condition))
        }
    }

    /// @notice Equivalent to the ternary operator: `condition ? a : b`
    function ternary(bool condition, address a, address b) internal pure returns (address res) {
        assembly {
            res := xor(b, mul(xor(a, b), condition))
        }
    }

    /// @notice Equivalent to: `uint256(x < 0 ? -x : x)`
    function abs(int256 x) internal pure returns (uint256 y) {
        assembly {
            // mask = 0 if x >= 0 else -1
            let mask := sar(255, x)
            // If x >= 0, |x| = x = 0 ^ x
            // If x < 0, |x| = ~~|x| = ~(-|x| - 1) = ~(x - 1) = -1 ^ (x - 1)
            // Either case, |x| = mask ^ (x + mask)
            y := xor(mask, add(mask, x))
        }
    }

    /// @notice Equivalent to: `a > b ? a - b : b - a`
    function absDiff(uint256 a, uint256 b) internal pure returns (uint256 res) {
        assembly {
            // The diff between two `uint256` may overflow `int256`
            let diff0 := sub(a, b)
            let diff1 := sub(b, a)
            res := xor(diff1, mul(xor(diff0, diff1), gt(a, b)))
        }
    }

    /// @notice Equivalent to: `a > b ? a - b : b - a`
    function absDiffU160(uint160 a, uint160 b) internal pure returns (uint256 res) {
        assembly {
            let diff := sub(a, b)
            let mask := sar(255, diff)
            res := xor(mask, add(mask, diff))
        }
    }

    /// @notice Equivalent to: `a < b ? a : b`
    function min(uint256 a, uint256 b) internal pure returns (uint256 res) {
        assembly {
            res := xor(b, mul(xor(a, b), lt(a, b)))
        }
    }

    /// @notice Equivalent to: `a > b ? a : b`
    function max(uint256 a, uint256 b) internal pure returns (uint256 res) {
        assembly {
            res := xor(b, mul(xor(a, b), gt(a, b)))
        }
    }

    /// @notice Equivalent to: `condition ? (b, a) : (a, b)`
    function switchIf(bool condition, uint256 a, uint256 b) internal pure returns (uint256, uint256) {
        assembly {
            let diff := mul(xor(a, b), condition)
            a := xor(a, diff)
            b := xor(b, diff)
        }
        return (a, b);
    }

    /// @notice Equivalent to: `condition ? (b, a) : (a, b)`
    function switchIf(bool condition, address a, address b) internal pure returns (address, address) {
        assembly {
            let diff := mul(xor(a, b), condition)
            a := xor(a, diff)
            b := xor(b, diff)
        }
        return (a, b);
    }

    /// @notice Sorts two addresses and returns them in ascending order
    function sort2(address a, address b) internal pure returns (address, address) {
        assembly {
            let diff := mul(xor(a, b), lt(b, a))
            a := xor(a, diff)
            b := xor(b, diff)
        }
        return (a, b);
    }

    /// @notice Sorts two uint256s and returns them in ascending order
    function sort2(uint256 a, uint256 b) internal pure returns (uint256, uint256) {
        assembly {
            let diff := mul(xor(a, b), lt(b, a))
            a := xor(a, diff)
            b := xor(b, diff)
        }
        return (a, b);
    }

    /// @notice Sorts two uint160s and returns them in ascending order
    function sort2U160(uint160 a, uint160 b) internal pure returns (uint160, uint160) {
        assembly {
            let diff := mul(xor(a, b), lt(b, a))
            a := xor(a, diff)
            b := xor(b, diff)
        }
        return (a, b);
    }
}

// node_modules/@aperture_finance/uni-v3-lib/src/UnsafeMath.sol

/// @title Math functions that do not check inputs or outputs
/// @author Aperture Finance
/// @author Modified from Uniswap (https://github.com/uniswap/v3-core/blob/main/contracts/libraries/UnsafeMath.sol)
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
    function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := add(x, y)
        }
    }

    function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := sub(x, y)
        }
    }

    function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := mul(x, y)
        }
    }

    function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := div(x, y)
        }
    }

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

// node_modules/@uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolActions.sol

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

// node_modules/@uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol

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

// node_modules/@uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolEvents.sol

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

// node_modules/@uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolImmutables.sol

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

// node_modules/@uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolOwnerActions.sol

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

// node_modules/@uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolState.sol

/// @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
    /// 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.
    /// observationIndex The index of the last oracle observation that was written,
    /// observationCardinality The current maximum number of observations stored in the pool,
    /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
    /// 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
    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,
    /// liquidityNet how much liquidity changes when the pool price crosses the tick,
    /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
    /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
    /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
    /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
    /// secondsOutside the seconds spent on the other side of the tick from the current tick,
    /// 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,
    /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
    /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
    /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
    /// Returns 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,
    /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
    /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
    /// Returns 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
        );
}

// node_modules/@uniswap/v3-core/contracts/libraries/FixedPoint96.sol

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

// node_modules/solady/src/utils/FixedPointMathLib.sol

/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The operation failed, as the output exceeds the maximum value of uint256.
    error ExpOverflow();

    /// @dev The operation failed, as the output exceeds the maximum value of uint256.
    error FactorialOverflow();

    /// @dev The operation failed, due to an overflow.
    error RPowOverflow();

    /// @dev The mantissa is too big to fit.
    error MantissaOverflow();

    /// @dev The operation failed, due to an multiplication overflow.
    error MulWadFailed();

    /// @dev The operation failed, due to an multiplication overflow.
    error SMulWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error DivWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error SDivWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error MulDivFailed();

    /// @dev The division failed, as the denominator is zero.
    error DivFailed();

    /// @dev The full precision multiply-divide operation failed, either due
    /// to the result being larger than 256 bits, or a division by a zero.
    error FullMulDivFailed();

    /// @dev The output is undefined, as the input is less-than-or-equal to zero.
    error LnWadUndefined();

    /// @dev The input outside the acceptable domain.
    error OutOfDomain();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The scalar of ETH and most ERC20s.
    uint256 internal constant WAD = 1e18;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*              SIMPLIFIED FIXED POINT OPERATIONS             */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Equivalent to `(x * y) / WAD` rounded down.
    function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
            if mul(y, gt(x, div(not(0), y))) {
                mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := div(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down.
    function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
            if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
                mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := sdiv(z, WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
    function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
    function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded up.
    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
            if mul(y, gt(x, div(not(0), y))) {
                mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
    function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down.
    function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
            if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
                mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := div(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down.
    function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, WAD)
            // Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
            if iszero(and(iszero(iszero(y)), eq(sdiv(z, WAD), x))) {
                mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := sdiv(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
    function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
    function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded up.
    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
            if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
                mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
    function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
        }
    }

    /// @dev Equivalent to `x` to the power of `y`.
    /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
    /// Note: This function is an approximation.
    function powWad(int256 x, int256 y) internal pure returns (int256) {
        // Using `ln(x)` means `x` must be greater than 0.
        return expWad((lnWad(x) * y) / int256(WAD));
    }

    /// @dev Returns `exp(x)`, denominated in `WAD`.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
    /// Note: This function is an approximation. Monotonically increasing.
    function expWad(int256 x) internal pure returns (int256 r) {
        unchecked {
            // When the result is less than 0.5 we return zero.
            // This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
            if (x <= -41446531673892822313) return r;

            /// @solidity memory-safe-assembly
            assembly {
                // When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
                // an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
                if iszero(slt(x, 135305999368893231589)) {
                    mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
                    revert(0x1c, 0x04)
                }
            }

            // `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
            // for more intermediate precision and a binary basis. This base conversion
            // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
            x = (x << 78) / 5 ** 18;

            // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
            // of two such that exp(x) = exp(x') * 2**k, where k is an integer.
            // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
            int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
            x = x - k * 54916777467707473351141471128;

            // `k` is in the range `[-61, 195]`.

            // Evaluate using a (6, 7)-term rational approximation.
            // `p` is made monic, we'll multiply by a scale factor later.
            int256 y = x + 1346386616545796478920950773328;
            y = ((y * x) >> 96) + 57155421227552351082224309758442;
            int256 p = y + x - 94201549194550492254356042504812;
            p = ((p * y) >> 96) + 28719021644029726153956944680412240;
            p = p * x + (4385272521454847904659076985693276 << 96);

            // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
            int256 q = x - 2855989394907223263936484059900;
            q = ((q * x) >> 96) + 50020603652535783019961831881945;
            q = ((q * x) >> 96) - 533845033583426703283633433725380;
            q = ((q * x) >> 96) + 3604857256930695427073651918091429;
            q = ((q * x) >> 96) - 14423608567350463180887372962807573;
            q = ((q * x) >> 96) + 26449188498355588339934803723976023;

            /// @solidity memory-safe-assembly
            assembly {
                // Div in assembly because solidity adds a zero check despite the unchecked.
                // The q polynomial won't have zeros in the domain as all its roots are complex.
                // No scaling is necessary because p is already `2**96` too large.
                r := sdiv(p, q)
            }

            // r should be in the range `(0.09, 0.25) * 2**96`.

            // We now need to multiply r by:
            // - The scale factor `s ≈ 6.031367120`.
            // - The `2**k` factor from the range reduction.
            // - The `1e18 / 2**96` factor for base conversion.
            // We do this all at once, with an intermediate result in `2**213`
            // basis, so the final right shift is always by a positive amount.
            r = int256(
                (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
            );
        }
    }

    /// @dev Returns `ln(x)`, denominated in `WAD`.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
    /// Note: This function is an approximation. Monotonically increasing.
    function lnWad(int256 x) internal pure returns (int256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            // We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
            // We do this by multiplying by `2**96 / 10**18`. But since
            // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
            // and add `ln(2**96 / 10**18)` at the end.

            // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // We place the check here for more optimal stack operations.
            if iszero(sgt(x, 0)) {
                mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
                revert(0x1c, 0x04)
            }
            // forgefmt: disable-next-item
            r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))

            // Reduce range of x to (1, 2) * 2**96
            // ln(2^k * x) = k * ln(2) + ln(x)
            x := shr(159, shl(r, x))

            // Evaluate using a (8, 8)-term rational approximation.
            // `p` is made monic, we will multiply by a scale factor later.
            // forgefmt: disable-next-item
            let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
                sar(96, mul(add(43456485725739037958740375743393,
                sar(96, mul(add(24828157081833163892658089445524,
                sar(96, mul(add(3273285459638523848632254066296,
                    x), x))), x))), x)), 11111509109440967052023855526967)
            p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
            p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
            p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
            // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.

            // `q` is monic by convention.
            let q := add(5573035233440673466300451813936, x)
            q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
            q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
            q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
            q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
            q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
            q := add(909429971244387300277376558375, sar(96, mul(x, q)))

            // `p / q` is in the range `(0, 0.125) * 2**96`.

            // Finalization, we need to:
            // - Multiply by the scale factor `s = 5.549…`.
            // - Add `ln(2**96 / 10**18)`.
            // - Add `k * ln(2)`.
            // - Multiply by `10**18 / 2**96 = 5**18 >> 78`.

            // The q polynomial is known not to have zeros in the domain.
            // No scaling required because p is already `2**96` too large.
            p := sdiv(p, q)
            // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
            p := mul(1677202110996718588342820967067443963516166, p)
            // Add `ln(2) * k * 5**18 * 2**192`.
            // forgefmt: disable-next-item
            p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
            // Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
            p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
            // Base conversion: mul `2**18 / 2**192`.
            r := sar(174, p)
        }
    }

    /// @dev Returns `W_0(x)`, denominated in `WAD`.
    /// See: https://en.wikipedia.org/wiki/Lambert_W_function
    /// a.k.a. Product log function. This is an approximation of the principal branch.
    /// Note: This function is an approximation. Monotonically increasing.
    function lambertW0Wad(int256 x) internal pure returns (int256 w) {
        // forgefmt: disable-next-item
        unchecked {
            if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
            int256 wad = int256(WAD);
            int256 p = x;
            uint256 c; // Whether we need to avoid catastrophic cancellation.
            uint256 i = 4; // Number of iterations.
            if (w <= 0x1ffffffffffff) {
                if (-0x4000000000000 <= w) {
                    i = 1; // Inputs near zero only take one step to converge.
                } else if (w <= -0x3ffffffffffffff) {
                    i = 32; // Inputs near `-1/e` take very long to converge.
                }
            } else if (uint256(w >> 63) == uint256(0)) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Inline log2 for more performance, since the range is small.
                    let v := shr(49, w)
                    let l := shl(3, lt(0xff, v))
                    l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
                        0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
                    w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
                    c := gt(l, 60)
                    i := add(2, add(gt(l, 53), c))
                }
            } else {
                int256 ll = lnWad(w = lnWad(w));
                /// @solidity memory-safe-assembly
                assembly {
                    // `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
                    w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
                    i := add(3, iszero(shr(68, x)))
                    c := iszero(shr(143, x))
                }
                if (c == uint256(0)) {
                    do { // If `x` is big, use Newton's so that intermediate values won't overflow.
                        int256 e = expWad(w);
                        /// @solidity memory-safe-assembly
                        assembly {
                            let t := mul(w, div(e, wad))
                            w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
                        }
                        if (p <= w) break;
                        p = w;
                    } while (--i != uint256(0));
                    /// @solidity memory-safe-assembly
                    assembly {
                        w := sub(w, sgt(w, 2))
                    }
                    return w;
                }
            }
            do { // Otherwise, use Halley's for faster convergence.
                int256 e = expWad(w);
                /// @solidity memory-safe-assembly
                assembly {
                    let t := add(w, wad)
                    let s := sub(mul(w, e), mul(x, wad))
                    w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
                }
                if (p <= w) break;
                p = w;
            } while (--i != c);
            /// @solidity memory-safe-assembly
            assembly {
                w := sub(w, sgt(w, 2))
            }
            // For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
            // R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
            if (c == uint256(0)) return w;
            int256 t = w | 1;
            /// @solidity memory-safe-assembly
            assembly {
                x := sdiv(mul(x, wad), t)
            }
            x = (t * (wad + lnWad(x)));
            /// @solidity memory-safe-assembly
            assembly {
                w := sdiv(x, add(wad, t))
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  GENERAL NUMBER UTILITIES                  */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Calculates `floor(x * y / d)` with full precision.
    /// Throws if result overflows a uint256 or when `d` is zero.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
    function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            // 512-bit multiply `[p1 p0] = x * y`.
            // Compute the product mod `2**256` and mod `2**256 - 1`
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that `product = p1 * 2**256 + p0`.

            // Temporarily use `result` as `p0` to save gas.
            result := mul(x, y) // Lower 256 bits of `x * y`.
            for {} 1 {} {
                // If overflows.
                if iszero(mul(or(iszero(x), eq(div(result, x), y)), d)) {
                    let mm := mulmod(x, y, not(0))
                    let p1 := sub(mm, add(result, lt(mm, result))) // Upper 256 bits of `x * y`.

                    /*------------------- 512 by 256 division --------------------*/

                    // Make division exact by subtracting the remainder from `[p1 p0]`.
                    let r := mulmod(x, y, d) // Compute remainder using mulmod.
                    let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
                    // Make sure the result is less than `2**256`. Also prevents `d == 0`.
                    // Placing the check here seems to give more optimal stack operations.
                    if iszero(gt(d, p1)) {
                        mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                        revert(0x1c, 0x04)
                    }
                    d := div(d, t) // Divide `d` by `t`, which is a power of two.
                    // Invert `d mod 2**256`
                    // Now that `d` is an odd number, it has an inverse
                    // modulo `2**256` such that `d * inv = 1 mod 2**256`.
                    // Compute the inverse by starting with a seed that is correct
                    // correct for four bits. That is, `d * inv = 1 mod 2**4`.
                    let inv := xor(2, mul(3, d))
                    // Now use Newton-Raphson iteration to improve the precision.
                    // Thanks to Hensel's lifting lemma, this also works in modular
                    // arithmetic, doubling the correct bits in each step.
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
                    result :=
                        mul(
                            // Divide [p1 p0] by the factors of two.
                            // Shift in bits from `p1` into `p0`. For this we need
                            // to flip `t` such that it is `2**256 / t`.
                            or(
                                mul(sub(p1, gt(r, result)), add(div(sub(0, t), t), 1)),
                                div(sub(result, r), t)
                            ),
                            mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
                        )
                    break
                }
                result := div(result, d)
                break
            }
        }
    }

    /// @dev Calculates `floor(x * y / d)` with full precision.
    /// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
    /// Performs the full 512 bit calculation regardless.
    function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
        internal
        pure
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := mul(x, y)
            let mm := mulmod(x, y, not(0))
            let p1 := sub(mm, add(result, lt(mm, result)))
            let t := and(d, sub(0, d))
            let r := mulmod(x, y, d)
            d := div(d, t)
            let inv := xor(2, mul(3, d))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            result :=
                mul(
                    or(mul(sub(p1, gt(r, result)), add(div(sub(0, t), t), 1)), div(sub(result, r), t)),
                    mul(sub(2, mul(d, inv)), inv)
                )
        }
    }

    /// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
    /// Throws if result overflows a uint256 or when `d` is zero.
    /// Credit to Uniswap-v3-core under MIT license:
    /// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
    function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
        result = fullMulDiv(x, y, d);
        /// @solidity memory-safe-assembly
        assembly {
            if mulmod(x, y, d) {
                result := add(result, 1)
                if iszero(result) {
                    mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                    revert(0x1c, 0x04)
                }
            }
        }
    }

    /// @dev Returns `floor(x * y / d)`.
    /// Reverts if `x * y` overflows, or `d` is zero.
    function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
            if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
                mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                revert(0x1c, 0x04)
            }
            z := div(z, d)
        }
    }

    /// @dev Returns `ceil(x * y / d)`.
    /// Reverts if `x * y` overflows, or `d` is zero.
    function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
            if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
                mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(z, d))), div(z, d))
        }
    }

    /// @dev Returns `ceil(x / d)`.
    /// Reverts if `d` is zero.
    function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(d) {
                mstore(0x00, 0x65244e4e) // `DivFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(x, d))), div(x, d))
        }
    }

    /// @dev Returns `max(0, x - y)`.
    function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(gt(x, y), sub(x, y))
        }
    }

    /// @dev Returns `condition ? x : y`, without branching.
    function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := xor(x, mul(xor(x, y), iszero(condition)))
        }
    }

    /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
    /// Reverts if the computation overflows.
    function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
            if x {
                z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
                let half := shr(1, b) // Divide `b` by 2.
                // Divide `y` by 2 every iteration.
                for { y := shr(1, y) } y { y := shr(1, y) } {
                    let xx := mul(x, x) // Store x squared.
                    let xxRound := add(xx, half) // Round to the nearest number.
                    // Revert if `xx + half` overflowed, or if `x ** 2` overflows.
                    if or(lt(xxRound, xx), shr(128, x)) {
                        mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                        revert(0x1c, 0x04)
                    }
                    x := div(xxRound, b) // Set `x` to scaled `xxRound`.
                    // If `y` is odd:
                    if and(y, 1) {
                        let zx := mul(z, x) // Compute `z * x`.
                        let zxRound := add(zx, half) // Round to the nearest number.
                        // If `z * x` overflowed or `zx + half` overflowed:
                        if or(xor(div(zx, x), z), lt(zxRound, zx)) {
                            // Revert if `x` is non-zero.
                            if x {
                                mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                                revert(0x1c, 0x04)
                            }
                        }
                        z := div(zxRound, b) // Return properly scaled `zxRound`.
                    }
                }
            }
        }
    }

    /// @dev Returns the square root of `x`, rounded down.
    function sqrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
            z := 181 // The "correct" value is 1, but this saves a multiplication later.

            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.

            // Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
            // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
            let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffffff, shr(r, x))))
            z := shl(shr(1, r), z)

            // Goal was to get `z*z*y` within a small factor of `x`. More iterations could
            // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
            // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
            // That's not possible if `x < 256` but we can just verify those cases exhaustively.

            // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
            // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
            // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.

            // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
            // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
            // with largest error when `s = 1` and when `s = 256` or `1/256`.

            // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
            // Then we can estimate `sqrt(y)` using
            // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.

            // There is no overflow risk here since `y < 2**136` after the first branch above.
            z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.

            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))

            // If `x+1` is a perfect square, the Babylonian method cycles between
            // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
            z := sub(z, lt(div(x, z), z))
        }
    }

    /// @dev Returns the cube root of `x`, rounded down.
    /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
    /// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy
    /// Formally verified by xuwinnie:
    /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
    function cbrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // Makeshift lookup table to nudge the approximate log2 result.
            z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
            // Newton-Raphson's.
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            // Round down.
            z := sub(z, lt(div(x, mul(z, z)), z))
        }
    }

    /// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
    function sqrtWad(uint256 x) internal pure returns (uint256 z) {
        unchecked {
            if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
            z = (1 + sqrt(x)) * 10 ** 9;
            z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
        }
        /// @solidity memory-safe-assembly
        assembly {
            z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
        }
    }

    /// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
    /// Formally verified by xuwinnie:
    /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
    function cbrtWad(uint256 x) internal pure returns (uint256 z) {
        unchecked {
            if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
            z = (1 + cbrt(x)) * 10 ** 12;
            z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
        }
        /// @solidity memory-safe-assembly
        assembly {
            let p := x
            for {} 1 {} {
                if iszero(shr(229, p)) {
                    if iszero(shr(199, p)) {
                        p := mul(p, 100000000000000000) // 10 ** 17.
                        break
                    }
                    p := mul(p, 100000000) // 10 ** 8.
                    break
                }
                if iszero(shr(249, p)) { p := mul(p, 100) }
                break
            }
            let t := mulmod(mul(z, z), z, p)
            z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
        }
    }

    /// @dev Returns the factorial of `x`.
    function factorial(uint256 x) internal pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := 1
            if iszero(lt(x, 58)) {
                mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
                revert(0x1c, 0x04)
            }
            for {} x { x := sub(x, 1) } { result := mul(result, x) }
        }
    }

    /// @dev Returns the log2 of `x`.
    /// Equivalent to computing the index of the most significant bit (MSB) of `x`.
    /// Returns 0 if `x` is zero.
    function log2(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0x0706060506020504060203020504030106050205030304010505030400000000))
        }
    }

    /// @dev Returns the log2 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log2Up(uint256 x) internal pure returns (uint256 r) {
        r = log2(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(shl(r, 1), x))
        }
    }

    /// @dev Returns the log10 of `x`.
    /// Returns 0 if `x` is zero.
    function log10(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(lt(x, 100000000000000000000000000000000000000)) {
                x := div(x, 100000000000000000000000000000000000000)
                r := 38
            }
            if iszero(lt(x, 100000000000000000000)) {
                x := div(x, 100000000000000000000)
                r := add(r, 20)
            }
            if iszero(lt(x, 10000000000)) {
                x := div(x, 10000000000)
                r := add(r, 10)
            }
            if iszero(lt(x, 100000)) {
                x := div(x, 100000)
                r := add(r, 5)
            }
            r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
        }
    }

    /// @dev Returns the log10 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log10Up(uint256 x) internal pure returns (uint256 r) {
        r = log10(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(exp(10, r), x))
        }
    }

    /// @dev Returns the log256 of `x`.
    /// Returns 0 if `x` is zero.
    function log256(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(shr(3, r), lt(0xff, shr(r, x)))
        }
    }

    /// @dev Returns the log256 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log256Up(uint256 x) internal pure returns (uint256 r) {
        r = log256(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(shl(shl(3, r), 1), x))
        }
    }

    /// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
    /// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
    function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
        /// @solidity memory-safe-assembly
        assembly {
            mantissa := x
            if mantissa {
                if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
                    mantissa := div(mantissa, 1000000000000000000000000000000000)
                    exponent := 33
                }
                if iszero(mod(mantissa, 10000000000000000000)) {
                    mantissa := div(mantissa, 10000000000000000000)
                    exponent := add(exponent, 19)
                }
                if iszero(mod(mantissa, 1000000000000)) {
                    mantissa := div(mantissa, 1000000000000)
                    exponent := add(exponent, 12)
                }
                if iszero(mod(mantissa, 1000000)) {
                    mantissa := div(mantissa, 1000000)
                    exponent := add(exponent, 6)
                }
                if iszero(mod(mantissa, 10000)) {
                    mantissa := div(mantissa, 10000)
                    exponent := add(exponent, 4)
                }
                if iszero(mod(mantissa, 100)) {
                    mantissa := div(mantissa, 100)
                    exponent := add(exponent, 2)
                }
                if iszero(mod(mantissa, 10)) {
                    mantissa := div(mantissa, 10)
                    exponent := add(exponent, 1)
                }
            }
        }
    }

    /// @dev Convenience function for packing `x` into a smaller number using `sci`.
    /// The `mantissa` will be in bits [7..255] (the upper 249 bits).
    /// The `exponent` will be in bits [0..6] (the lower 7 bits).
    /// Use `SafeCastLib` to safely ensure that the `packed` number is small
    /// enough to fit in the desired unsigned integer type:
    /// ```
    ///     uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
    /// ```
    function packSci(uint256 x) internal pure returns (uint256 packed) {
        (x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
        /// @solidity memory-safe-assembly
        assembly {
            if shr(249, x) {
                mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
                revert(0x1c, 0x04)
            }
            packed := or(shl(7, x), packed)
        }
    }

    /// @dev Convenience function for unpacking a packed number from `packSci`.
    function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
        unchecked {
            unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
        }
    }

    /// @dev Returns the average of `x` and `y`. Rounds towards zero.
    function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = (x & y) + ((x ^ y) >> 1);
        }
    }

    /// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
    function avg(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = (x >> 1) + (y >> 1) + (x & y & 1);
        }
    }

    /// @dev Returns the absolute value of `x`.
    function abs(int256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(sar(255, x), add(sar(255, x), x))
        }
    }

    /// @dev Returns the absolute distance between `x` and `y`.
    function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(mul(xor(sub(y, x), sub(x, y)), gt(x, y)), sub(y, x))
        }
    }

    /// @dev Returns the absolute distance between `x` and `y`.
    function dist(int256 x, int256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(mul(xor(sub(y, x), sub(x, y)), sgt(x, y)), sub(y, x))
        }
    }

    /// @dev Returns the minimum of `x` and `y`.
    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), lt(y, x)))
        }
    }

    /// @dev Returns the minimum of `x` and `y`.
    function min(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), slt(y, x)))
        }
    }

    /// @dev Returns the maximum of `x` and `y`.
    function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), gt(y, x)))
        }
    }

    /// @dev Returns the maximum of `x` and `y`.
    function max(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), sgt(y, x)))
        }
    }

    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
    function clamp(uint256 x, uint256 minValue, uint256 maxValue)
        internal
        pure
        returns (uint256 z)
    {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
            z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
        }
    }

    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
    function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
            z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
        }
    }

    /// @dev Returns greatest common divisor of `x` and `y`.
    function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            for { z := x } y {} {
                let t := y
                y := mod(z, y)
                z := t
            }
        }
    }

    /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
    /// with `t` clamped between `begin` and `end` (inclusive).
    /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
    /// If `begins == end`, returns `t <= begin ? a : b`.
    function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
        internal
        pure
        returns (uint256)
    {
        if (begin > end) {
            t = ~t;
            begin = ~begin;
            end = ~end;
        }
        if (t <= begin) return a;
        if (t >= end) return b;
        unchecked {
            if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
            return a - fullMulDiv(a - b, t - begin, end - begin);
        }
    }

    /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
    /// with `t` clamped between `begin` and `end` (inclusive).
    /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
    /// If `begins == end`, returns `t <= begin ? a : b`.
    function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
        internal
        pure
        returns (int256)
    {
        if (begin > end) {
            t = int256(~uint256(t));
            begin = int256(~uint256(begin));
            end = int256(~uint256(end));
        }
        if (t <= begin) return a;
        if (t >= end) return b;
        // forgefmt: disable-next-item
        unchecked {
            if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b) - uint256(a),
                uint256(t) - uint256(begin), uint256(end) - uint256(begin)));
            return int256(uint256(a) - fullMulDiv(uint256(a) - uint256(b),
                uint256(t) - uint256(begin), uint256(end) - uint256(begin)));
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   RAW NUMBER OPERATIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns `x + y`, without checking for overflow.
    function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x + y;
        }
    }

    /// @dev Returns `x + y`, without checking for overflow.
    function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x + y;
        }
    }

    /// @dev Returns `x - y`, without checking for underflow.
    function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x - y;
        }
    }

    /// @dev Returns `x - y`, without checking for underflow.
    function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x - y;
        }
    }

    /// @dev Returns `x * y`, without checking for overflow.
    function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x * y;
        }
    }

    /// @dev Returns `x * y`, without checking for overflow.
    function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x * y;
        }
    }

    /// @dev Returns `x / y`, returning 0 if `y` is zero.
    function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(x, y)
        }
    }

    /// @dev Returns `x / y`, returning 0 if `y` is zero.
    function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(x, y)
        }
    }

    /// @dev Returns `x % y`, returning 0 if `y` is zero.
    function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mod(x, y)
        }
    }

    /// @dev Returns `x % y`, returning 0 if `y` is zero.
    function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := smod(x, y)
        }
    }

    /// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
    function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := addmod(x, y, d)
        }
    }

    /// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
    function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mulmod(x, y, d)
        }
    }
}

// node_modules/@aperture_finance/uni-v3-lib/src/FullMath.sol

/// @title Contains 512-bit math functions
/// @author Aperture Finance
/// @author Modified from Uniswap (https://github.com/uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol)
/// @author Credit to Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @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 {
    /// @dev The full precision multiply-divide operation failed, either due
    /// to the result being larger than 256 bits, or a division by a zero.
    error FullMulDivFailed();

    /// @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) {
        return FixedPointMathLib.fullMulDiv(a, b, denominator);
    }

    /// @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) {
        return FixedPointMathLib.fullMulDivUp(a, b, denominator);
    }

    /// @notice Calculates a * b / 2^96 with full precision.
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @return result The 256-bit result
    function mulDivQ96(uint256 a, uint256 b) internal pure returns (uint256 result) {
        assembly ("memory-safe") {
            // 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`.

            // Least significant 256 bits of the product.
            let prod0 := mul(a, b)
            let mm := mulmod(a, b, not(0))
            // Most significant 256 bits of the product.
            let prod1 := sub(mm, add(prod0, lt(mm, prod0)))

            // Make sure the result is less than `2**256`.
            if iszero(gt(0x1000000000000000000000000, prod1)) {
                // Store the function selector of `FullMulDivFailed()`.
                mstore(0x00, 0xae47f702)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            // Divide [prod1 prod0] by 2^96.
            result := or(shr(96, prod0), shl(160, prod1))
        }
    }

    /// @notice Calculates a * b / 2^128 with full precision.
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @return result The 256-bit result
    function mulDivQ128(uint256 a, uint256 b) internal pure returns (uint256 result) {
        assembly ("memory-safe") {
            // 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`.

            // Least significant 256 bits of the product.
            let prod0 := mul(a, b)
            let mm := mulmod(a, b, not(0))
            // Most significant 256 bits of the product.
            let prod1 := sub(mm, add(prod0, lt(mm, prod0)))

            // Make sure the result is less than `2**256`.
            if iszero(gt(0x100000000000000000000000000000000, prod1)) {
                // Store the function selector of `FullMulDivFailed()`.
                mstore(0x00, 0xae47f702)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            // Divide [prod1 prod0] by 2^128.
            result := or(shr(128, prod0), shl(128, prod1))
        }
    }

    /// @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
    function sqrt(uint256 x) internal pure returns (uint256) {
        return FixedPointMathLib.sqrt(x);
    }
}

// node_modules/@aperture_finance/uni-v3-lib/src/TickMath.sol

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @author Aperture Finance
/// @author Modified from Uniswap (https://github.com/uniswap/v3-core/blob/main/contracts/libraries/TickMath.sol)
/// @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 {
    /// @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 = 887272;

    /// @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;
    /// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_RATIO - MIN_SQRT_RATIO - 1`
    uint160 internal constant MAX_SQRT_RATIO_MINUS_MIN_SQRT_RATIO_MINUS_ONE =
        1461446703485210103287273052203988822378723970342 - 4295128739 - 1;

    /// @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 {
            int256 tick256;
            assembly {
                tick256 := tick
            }
            uint256 absTick = TernaryLib.abs(tick256);
            /// @solidity memory-safe-assembly
            assembly {
                // Equivalent: if (absTick > MAX_TICK) revert("T");
                if gt(absTick, MAX_TICK) {
                    // selector "Error(string)", [0x1c, 0x20)
                    mstore(0, 0x08c379a0)
                    // abi encoding offset
                    mstore(0x20, 0x20)
                    // reason string length 1 and 'T', [0x5f, 0x61)
                    mstore(0x41, 0x0154)
                    // 4 byte selector + 32 byte offset + 32 byte length + 1 byte reason
                    revert(0x1c, 0x45)
                }
            }

            // Equivalent to:
            //     ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
            //     or ratio = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
            uint256 ratio;
            assembly {
                ratio := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
            }
            // Iterate through 1th to 19th bit of absTick because MAX_TICK < 2**20
            // Equivalent to:
            //      for i in range(1, 20):
            //          if absTick & 2 ** i:
            //              ratio = ratio * (2 ** 128 / 1.0001 ** (2 ** (i - 1))) / 2 ** 128
            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;

            assembly {
                // if (tick > 0) ratio = type(uint256).max / ratio;
                if sgt(tick, 0) {
                    ratio := div(not(0), 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 := shr(32, add(ratio, sub(shl(32, 1), 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) {
        // Equivalent: if (sqrtPriceX96 < MIN_SQRT_RATIO || sqrtPriceX96 >= MAX_SQRT_RATIO) revert("R");
        // second inequality must be >= because the price can never reach the price at the max tick
        /// @solidity memory-safe-assembly
        assembly {
            // if sqrtPriceX96 < MIN_SQRT_RATIO, the `sub` underflows and `gt` is true
            // if sqrtPriceX96 >= MAX_SQRT_RATIO, sqrtPriceX96 - MIN_SQRT_RATIO > MAX_SQRT_RATIO - MIN_SQRT_RATIO - 1
            if gt(sub(sqrtPriceX96, MIN_SQRT_RATIO), MAX_SQRT_RATIO_MINUS_MIN_SQRT_RATIO_MINUS_ONE) {
                // selector "Error(string)", [0x1c, 0x20)
                mstore(0, 0x08c379a0)
                // abi encoding offset
                mstore(0x20, 0x20)
                // reason string length 1 and 'R', [0x5f, 0x61)
                mstore(0x41, 0x0152)
                // 4 byte selector + 32 byte offset + 32 byte length + 1 byte reason
                revert(0x1c, 0x45)
            }
        }

        // Find the most significant bit of `sqrtPriceX96`, 160 > msb >= 32.
        uint8 msb;
        assembly {
            let x := sqrtPriceX96
            msb := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            msb := or(msb, shl(6, lt(0xffffffffffffffff, shr(msb, x))))
            msb := or(msb, shl(5, lt(0xffffffff, shr(msb, x))))
            msb := or(msb, shl(4, lt(0xffff, shr(msb, x))))
            msb := or(msb, shl(3, lt(0xff, shr(msb, x))))
            msb := or(
                msb,
                byte(
                    and(0x1f, shr(shr(msb, x), 0x8421084210842108cc6318c6db6d54be)),
                    0x0706060506020504060203020504030106050205030304010505030400000000
                )
            )
        }

        // 2**(msb - 95) > sqrtPrice >= 2**(msb - 96)
        // the integer part of log_2(sqrtPrice) * 2**64 = (msb - 96) << 64, 8.64 number
        int256 log_2X64;
        assembly {
            log_2X64 := shl(64, sub(msb, 96))

            // Get the first 128 significant figures of `sqrtPriceX96`.
            // r = sqrtPriceX96 / 2**(msb - 127), where 2**128 > r >= 2**127
            // sqrtPrice = 2**(msb - 96) * r / 2**127, in floating point math
            // Shift left first because 160 > msb >= 32. If we shift right first, we'll lose precision.
            let r := shr(sub(msb, 31), shl(96, sqrtPriceX96))

            // Approximate `log_2X64` to 14 binary digits after decimal
            // log_2X64 = (msb - 96) * 2**64 + f_0 * 2**63 + f_1 * 2**62 + ......
            // sqrtPrice**2 = 2**(2 * (msb - 96)) * (r / 2**127)**2 = 2**(2 * log_2X64 / 2**64) = 2**(2 * (msb - 96) + f_0)
            // 2**f_0 = (r / 2**127)**2 = r**2 / 2**255 * 2
            // f_0 = 1 if (r**2 >= 2**255) else 0
            // sqrtPrice**2 = 2**(2 * (msb - 96) + f_0) * r**2 / 2**(254 + f_0) = 2**(2 * (msb - 96) + f_0) * r' / 2**127
            // r' = r**2 / 2**(127 + f_0)
            // sqrtPrice**4 = 2**(4 * (msb - 96) + 2 * f_0) * (r' / 2**127)**2
            //     = 2**(4 * log_2X64 / 2**64) = 2**(4 * (msb - 96) + 2 * f_0 + f_1)
            // 2**(f_1) = (r' / 2**127)**2
            // f_1 = 1 if (r'**2 >= 2**255) else 0

            // Check whether r >= sqrt(2) * 2**127
            // 2**256 > r**2 >= 2**254
            let square := mul(r, r)
            // f = (r**2 >= 2**255)
            let f := slt(square, 0)
            // r = r**2 >> 128 if r**2 >= 2**255 else r**2 >> 127
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(63, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(62, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(61, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(60, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(59, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(58, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(57, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(56, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(55, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(54, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(53, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(52, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(51, f), log_2X64)

            log_2X64 := or(shl(50, slt(mul(r, r), 0)), log_2X64)
        }

        // sqrtPrice = sqrt(1.0001^tick)
        // tick = log_{sqrt(1.0001)}(sqrtPrice) = log_2(sqrtPrice) / log_2(sqrt(1.0001))
        // 2**64 / log_2(sqrt(1.0001)) = 255738958999603826347141
        int24 tickLow;
        int24 tickHi;
        assembly {
            let log_sqrt10001 := mul(log_2X64, 255738958999603826347141) // 128.128 number
            tickLow := sar(128, sub(log_sqrt10001, 3402992956809132418596140100660247210))
            tickHi := sar(128, add(log_sqrt10001, 291339464771989622907027621153398088495))
        }

        // Equivalent: tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
        if (tickLow != tickHi) {
            uint160 sqrtRatioAtTickHi = getSqrtRatioAtTick(tickHi);
            assembly {
                tick := sub(tickHi, gt(sqrtRatioAtTickHi, sqrtPriceX96))
            }
        } else {
            tick = tickHi;
        }
    }
}

// node_modules/@aperture_finance/uni-v3-lib/src/SqrtPriceMath.sol

/// @title Functions based on Q64.96 sqrt price and liquidity
/// @author Aperture Finance
/// @author Modified from Uniswap (https://github.com/uniswap/v3-core/blob/main/contracts/libraries/SqrtPriceMath.sol)
/// @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 _sqrtPX96;
        assembly {
            numerator1 := shl(96, liquidity)
            _sqrtPX96 := sqrtPX96
        }

        if (add) {
            unchecked {
                uint256 product = amount * _sqrtPX96;
                // checks for overflow
                if (UnsafeMath.div(product, amount) == _sqrtPX96) {
                    uint256 denominator = numerator1 + product;
                    // checks for overflow
                    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, UnsafeMath.div(numerator1, _sqrtPX96) + amount));
        } else {
            uint256 denominator;
            assembly ("memory-safe") {
                // if the product overflows, we know the denominator underflows
                // in addition, we must check that the denominator does not underflow
                let product := mul(amount, _sqrtPX96)
                if iszero(and(eq(div(product, amount), _sqrtPX96), gt(numerator1, product))) {
                    revert(0, 0)
                }
                denominator := sub(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 nextSqrtPrice The price after adding or removing `amount`
    function getNextSqrtPriceFromAmount1RoundingDown(
        uint160 sqrtPX96,
        uint128 liquidity,
        uint256 amount,
        bool add
    ) internal pure returns (uint160 nextSqrtPrice) {
        uint256 _liquidity;
        assembly {
            _liquidity := liquidity
        }
        // 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 >> 160 == 0
                    ? UnsafeMath.div((amount << FixedPoint96.RESOLUTION), _liquidity)
                    : FullMath.mulDiv(amount, FixedPoint96.Q96, _liquidity)
            );

            nextSqrtPrice = (uint256(sqrtPX96) + quotient).toUint160();
        } else {
            uint256 quotient = (
                amount >> 160 == 0
                    ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, _liquidity)
                    : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, _liquidity)
            );
            assembly ("memory-safe") {
                if iszero(gt(sqrtPX96, quotient)) {
                    revert(0, 0)
                }
                // always fits 160 bits
                nextSqrtPrice := sub(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) {
        assembly ("memory-safe") {
            if or(iszero(sqrtPX96), iszero(liquidity)) {
                revert(0, 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) {
        assembly ("memory-safe") {
            if or(iszero(sqrtPX96), iszero(liquidity)) {
                revert(0, 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 assumed to be lower otherwise swapped
    /// @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) {
        (sqrtRatioAX96, sqrtRatioBX96) = TernaryLib.sort2U160(sqrtRatioAX96, sqrtRatioBX96);
        assembly ("memory-safe") {
            if iszero(sqrtRatioAX96) {
                revert(0, 0)
            }
        }
        uint256 numerator1;
        uint256 numerator2;
        assembly {
            numerator1 := shl(96, liquidity)
            numerator2 := sub(sqrtRatioBX96, sqrtRatioAX96)
        }
        /**
         * Equivalent to:
         *   roundUp
         *       ? FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96).divRoundingUp(sqrtRatioAX96)
         *       : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;
         * If `md = mulDiv(n1, n2, srb) == mulDivRoundingUp(n1, n2, srb)`, then `mulmod(n1, n2, srb) == 0`.
         * Add `roundUp && md % sra > 0` to `div(md, sra)`.
         * If `md = mulDiv(n1, n2, srb)` and `mulDivRoundingUp(n1, n2, srb)` differs by 1 and `sra > 0`,
         * then `(md + 1).divRoundingUp(sra) == md.div(sra) + 1` whether `sra` fully divides `md` or not.
         */
        uint256 mulDivResult = FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96);
        assembly {
            amount0 := add(
                div(mulDivResult, sqrtRatioAX96),
                and(gt(or(mod(mulDivResult, sqrtRatioAX96), mulmod(numerator1, numerator2, sqrtRatioBX96)), 0), roundUp)
            )
        }
    }

    /// @notice Gets the amount1 delta between two prices
    /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
    /// @param sqrtRatioAX96 A sqrt price assumed to be lower otherwise swapped
    /// @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) {
        uint256 numerator = TernaryLib.absDiffU160(sqrtRatioAX96, sqrtRatioBX96);
        uint256 denominator = FixedPoint96.Q96;
        uint256 _liquidity;
        assembly {
            // avoid implicit upcasting
            _liquidity := liquidity
        }
        /**
         * Equivalent to:
         *   amount1 = roundUp
         *       ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)
         *       : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
         * Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`.
         */
        amount1 = FullMath.mulDivQ96(_liquidity, numerator);
        assembly {
            amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), roundUp))
        }
    }

    /// @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) {
        /**
         * Equivalent to:
         *   amount0 = liquidity < 0
         *       ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
         *       : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
         */
        bool roundUp;
        uint256 mask;
        uint128 liquidityAbs;
        assembly {
            // mask = 0 if liquidity >= 0 else -1
            mask := sar(255, liquidity)
            // roundUp = 1 if liquidity >= 0 else 0
            roundUp := iszero(mask)
            liquidityAbs := xor(mask, add(mask, liquidity))
        }
        // amount0Abs = liquidity / sqrt(lower) - liquidity / sqrt(upper) < type(uint224).max
        // always fits in 224 bits, no need for toInt256()
        uint256 amount0Abs = getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, liquidityAbs, roundUp);
        assembly {
            // If liquidity >= 0, amount0 = |amount0| = 0 ^ |amount0|
            // If liquidity < 0, amount0 = -|amount0| = ~|amount0| + 1 = (-1) ^ |amount0| - (-1)
            amount0 := sub(xor(amount0Abs, mask), mask)
        }
    }

    /// @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) {
        /**
         * Equivalent to:
         *   amount1 = liquidity < 0
         *       ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
         *       : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
         */
        bool roundUp;
        uint256 mask;
        uint128 liquidityAbs;
        assembly {
            // mask = 0 if liquidity >= 0 else -1
            mask := sar(255, liquidity)
            // roundUp = 1 if liquidity >= 0 else 0
            roundUp := iszero(mask)
            liquidityAbs := xor(mask, add(mask, liquidity))
        }
        // amount1Abs = liquidity * (sqrt(upper) - sqrt(lower)) < type(uint192).max
        // always fits in 192 bits, no need for toInt256()
        uint256 amount1Abs = getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, liquidityAbs, roundUp);
        assembly {
            // If liquidity >= 0, amount1 = |amount1| = 0 ^ |amount1|
            // If liquidity < 0, amount1 = -|amount1| = ~|amount1| + 1 = (-1) ^ |amount1| - (-1)
            amount1 := sub(xor(amount1Abs, mask), mask)
        }
    }
}

// node_modules/@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.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,
    IUniswapV3PoolEvents
{

}

// node_modules/@aperture_finance/uni-v3-lib/src/PoolCaller.sol

// User defined value types are introduced in Solidity v0.8.8.
// https://blog.soliditylang.org/2021/09/27/user-defined-value-types/

type V3PoolCallee is address;
using PoolCaller for V3PoolCallee global;

/// @title Uniswap v3 Pool Caller
/// @author Aperture Finance
/// @notice Gas efficient library to call `IUniswapV3Pool` assuming the pool exists.
/// @dev Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// However, this is safe because "Note that you do not need to update the free memory pointer if there is no following
/// allocation, but you can only use memory starting from the current offset given by the free memory pointer."
/// according to https://docs.soliditylang.org/en/latest/assembly.html#memory-safety.
library PoolCaller {
    /// @dev Makes a staticcall to a pool with only the selector and returns a memory word.
    function staticcall_0i_1o(V3PoolCallee pool, bytes4 selector) internal view returns (uint256 res) {
        assembly ("memory-safe") {
            // Write the function selector into memory.
            mstore(0, selector)
            // We use 4 because of the length of our calldata.
            // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
            if iszero(staticcall(gas(), pool, 0, 4, 0, 0x20)) {
                revert(0, 0)
            }
            res := mload(0)
        }
    }

    /// @dev Makes a staticcall to a pool with only the selector and returns two memory words.
    function staticcall_0i_2o(V3PoolCallee pool, bytes4 selector) internal view returns (uint256 res0, uint256 res1) {
        assembly ("memory-safe") {
            // Write the function selector into memory.
            mstore(0, selector)
            // We use 4 because of the length of our calldata.
            // We use 0 and 64 to copy up to 64 bytes of return data into the scratch space.
            if iszero(staticcall(gas(), pool, 0, 4, 0, 0x40)) {
                revert(0, 0)
            }
            res0 := mload(0)
            res1 := mload(0x20)
        }
    }

    /// @dev Makes a staticcall to a pool with one argument.
    function staticcall_1i_0o(
        V3PoolCallee pool,
        bytes4 selector,
        uint256 arg,
        uint256 out,
        uint256 outsize
    ) internal view {
        assembly ("memory-safe") {
            // Write the abi-encoded calldata into memory.
            mstore(0, selector)
            mstore(4, arg)
            // We use 36 because of the length of our calldata.
            if iszero(staticcall(gas(), pool, 0, 0x24, out, outsize)) {
                revert(0, 0)
            }
        }
    }

    /// @dev Equivalent to `IUniswapV3Pool.fee`
    /// @param pool Uniswap v3 pool
    function fee(V3PoolCallee pool) internal view returns (uint24 f) {
        uint256 res = staticcall_0i_1o(pool, IUniswapV3PoolImmutables.fee.selector);
        assembly {
            f := res
        }
    }

    /// @dev Equivalent to `IUniswapV3Pool.tickSpacing`
    /// @param pool Uniswap v3 pool
    function tickSpacing(V3PoolCallee pool) internal view returns (int24 ts) {
        uint256 res = staticcall_0i_1o(pool, IUniswapV3PoolImmutables.tickSpacing.selector);
        assembly {
            ts := res
        }
    }

    /// @dev Equivalent to `IUniswapV3Pool.slot0`
    /// @param pool Uniswap v3 pool
    function slot0(
        V3PoolCallee pool
    )
        internal
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        )
    {
        bytes4 selector = IUniswapV3PoolState.slot0.selector;
        assembly ("memory-safe") {
            // Get a pointer to some free memory.
            let fmp := mload(0x40)
            // Write the function selector into memory.
            mstore(0, selector)
            // We use 4 because of the length of our calldata.
            // We copy up to 224 bytes of return data after fmp.
            if iszero(staticcall(gas(), pool, 0, 4, fmp, 0xe0)) {
                revert(0, 0)
            }
            sqrtPriceX96 := mload(fmp)
            tick := mload(add(fmp, 0x20))
            observationIndex := mload(add(fmp, 0x40))
            observationCardinality := mload(add(fmp, 0x60))
            observationCardinalityNext := mload(add(fmp, 0x80))
            feeProtocol := mload(add(fmp, 0xa0))
            unlocked := mload(add(fmp, 0xc0))
        }
    }

    /// @dev Equivalent to `(uint160 sqrtPriceX96, int24 tick, , , , , ) = pool.slot0()`
    /// @param pool Uniswap v3 pool
    function sqrtPriceX96AndTick(V3PoolCallee pool) internal view returns (uint160 sqrtPriceX96, int24 tick) {
        (uint256 res0, uint256 res1) = staticcall_0i_2o(pool, IUniswapV3PoolState.slot0.selector);
        assembly {
            sqrtPriceX96 := res0
            tick := res1
        }
    }

    /// @dev Equivalent to `IUniswapV3Pool.feeGrowthGlobal0X128`
    /// @param pool Uniswap v3 pool
    function feeGrowthGlobal0X128(V3PoolCallee pool) internal view returns (uint256 f) {
        f = staticcall_0i_1o(pool, IUniswapV3PoolState.feeGrowthGlobal0X128.selector);
    }

    /// @dev Equivalent to `IUniswapV3Pool.feeGrowthGlobal1X128`
    /// @param pool Uniswap v3 pool
    function feeGrowthGlobal1X128(V3PoolCallee pool) internal view returns (uint256 f) {
        f = staticcall_0i_1o(pool, IUniswapV3PoolState.feeGrowthGlobal1X128.selector);
    }

    /// @dev Equivalent to `IUniswapV3Pool.protocolFees`
    /// @param pool Uniswap v3 pool
    function protocolFees(V3PoolCallee pool) internal view returns (uint128 token0, uint128 token1) {
        (uint256 res0, uint256 res1) = staticcall_0i_2o(pool, IUniswapV3PoolState.protocolFees.selector);
        assembly {
            token0 := res0
            token1 := res1
        }
    }

    /// @dev Equivalent to `IUniswapV3Pool.liquidity`
    /// @param pool Uniswap v3 pool
    function liquidity(V3PoolCallee pool) internal view returns (uint128 l) {
        uint256 res = staticcall_0i_1o(pool, IUniswapV3PoolState.liquidity.selector);
        assembly {
            l := res
        }
    }

    // info stored for each initialized individual tick
    struct TickInfo {
        // the total position liquidity that references this tick
        uint128 liquidityGross;
        // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left),
        int128 liquidityNet;
        // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
        // only has relative meaning, not absolute — the value depends on when the tick is initialized
        uint256 feeGrowthOutside0X128;
        uint256 feeGrowthOutside1X128;
        // the cumulative tick value on the other side of the tick
        int56 tickCumulativeOutside;
        // the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick)
        // only has relative meaning, not absolute — the value depends on when the tick is initialized
        uint160 secondsPerLiquidityOutsideX128;
        // the seconds spent on the other side of the tick (relative to the current tick)
        // only has relative meaning, not absolute — the value depends on when the tick is initialized
        uint32 secondsOutside;
        // true iff the tick is initialized, i.e. the value is exactly equivalent to the expression liquidityGross != 0
        // these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks
        bool initialized;
    }

    /// @dev Equivalent to `IUniswapV3Pool.ticks`
    /// @param pool Uniswap v3 pool
    function ticks(V3PoolCallee pool, int24 tick) internal view returns (TickInfo memory info) {
        uint256 _tick;
        uint256 out;
        assembly {
            // Pad int24 to 32 bytes.
            _tick := signextend(2, tick)
            out := info
        }
        // We copy up to 256 bytes of return data at info's pointer.
        staticcall_1i_0o(pool, IUniswapV3PoolState.ticks.selector, _tick, out, 0x100);
    }

    /// @dev Equivalent to `( , int128 liquidityNet, , , , , , ) = pool.ticks(tick)`
    /// @param pool Uniswap v3 pool
    function liquidityNet(V3PoolCallee pool, int24 tick) internal view returns (int128 ln) {
        uint256 _tick;
        assembly {
            // Pad int24 to 32 bytes.
            _tick := signextend(2, tick)
        }
        // We use 0 and 64 to copy up to 64 bytes of return data into the scratch space.
        staticcall_1i_0o(pool, IUniswapV3PoolState.ticks.selector, _tick, 0, 0x40);
        assembly ("memory-safe") {
            ln := mload(0x20)
        }
    }

    /// @dev Equivalent to `IUniswapV3Pool.tickBitmap`
    /// @param pool Uniswap v3 pool
    /// @param wordPos The key in the mapping containing the word in which the bit is stored
    function tickBitmap(V3PoolCallee pool, int16 wordPos) internal view returns (uint256 tickWord) {
        uint256 _wordPos;
        assembly {
            // Pad int16 to 32 bytes.
            _wordPos := signextend(1, wordPos)
        }
        // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
        staticcall_1i_0o(pool, IUniswapV3PoolState.tickBitmap.selector, _wordPos, 0, 0x20);
        assembly ("memory-safe") {
            tickWord := mload(0)
        }
    }

    // info stored for each user's position
    struct PositionInfo {
        // the amount of liquidity owned by this position
        uint128 liquidity;
        // fee growth per unit of liquidity as of the last update to liquidity or fees owed
        uint256 feeGrowthInside0LastX128;
        uint256 feeGrowthInside1LastX128;
        // the fees owed to the position owner in token0/token1
        uint128 tokensOwed0;
        uint128 tokensOwed1;
    }

    /// @dev Equivalent to `IUniswapV3Pool.positions`
    /// @param pool Uniswap v3 pool
    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
    function positions(V3PoolCallee pool, bytes32 key) internal view returns (PositionInfo memory info) {
        uint256 out;
        assembly {
            out := info
        }
        // We copy up to 160 bytes of return data at info's pointer.
        staticcall_1i_0o(pool, IUniswapV3PoolState.positions.selector, uint256(key), out, 0xa0);
    }

    /// @dev Equivalent to `IUniswapV3Pool.observations`
    /// @param pool Uniswap v3 pool
    /// @param index The element of the observations array to fetch
    /// @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(
        V3PoolCallee pool,
        uint256 index
    )
        internal
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        )
    {
        uint256 fmp;
        assembly ("memory-safe") {
            // Get a pointer to some free memory.
            fmp := mload(0x40)
        }
        // We copy up to 128 bytes of return data at the free memory pointer.
        staticcall_1i_0o(pool, IUniswapV3PoolState.observations.selector, index, fmp, 0x80);
        assembly ("memory-safe") {
            blockTimestamp := mload(fmp)
            tickCumulative := mload(add(fmp, 0x20))
            secondsPerLiquidityCumulativeX128 := mload(add(fmp, 0x40))
            initialized := mload(add(fmp, 0x60))
        }
    }

    /// @dev Equivalent to `IUniswapV3Pool.swap`
    /// @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 pool Uniswap v3 pool
    /// @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(
        V3PoolCallee pool,
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes memory data
    ) internal returns (int256 amount0, int256 amount1) {
        bytes4 selector = IUniswapV3PoolActions.swap.selector;
        assembly ("memory-safe") {
            // Get a pointer to some free memory.
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 4), recipient)
            mstore(add(fmp, 0x24), zeroForOne)
            mstore(add(fmp, 0x44), amountSpecified)
            mstore(add(fmp, 0x64), sqrtPriceLimitX96)
            // Use 160 for the offset of `data` in calldata.
            mstore(add(fmp, 0x84), 0xa0)
            // length = data.length + 32
            let length := add(mload(data), 0x20)
            // TODO: Use `mcopy`
            // Call the identity precompile 0x04 to copy `data` into calldata.
            pop(staticcall(gas(), 0x04, data, length, add(fmp, 0xa4), length))
            // We use `196 + data.length` for the length of our calldata.
            // We use 0 and 64 to copy up to 64 bytes of return data into the scratch space.
            if iszero(
                and(
                    // The arguments of `and` are evaluated from right to left.
                    eq(returndatasize(), 0x40), // Ensure `returndatasize` is 64.
                    call(gas(), pool, 0, fmp, add(0xa4, length), 0, 0x40)
                )
            ) {
                // It is safe to overwrite the free memory pointer 0x40 and the zero pointer 0x60 here before exiting
                // because a contract obtains a freshly cleared instance of memory for each message call.
                returndatacopy(0, 0, returndatasize())
                // Bubble up the revert reason.
                revert(0, returndatasize())
            }
            // Read the return data.
            amount0 := mload(0)
            amount1 := mload(0x20)
        }
    }
}

// node_modules/@aperture_finance/uni-v3-lib/src/SwapMath.sol

/// @title Computes the result of a swap within ticks
/// @author Aperture Finance
/// @author Modified from Uniswap (https://github.com/uniswap/v3-core/blob/main/contracts/libraries/SwapMath.sol)
/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.
library SwapMath {
    uint256 internal constant MAX_FEE_PIPS = 1e6;

    /// @notice Computes the sqrt price target for the next swap step
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param sqrtPriceNextX96 The Q64.96 sqrt price for the next initialized tick
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value
    /// after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @return sqrtPriceTargetX96 The price target for the next swap step
    function getSqrtPriceTarget(
        bool zeroForOne,
        uint160 sqrtPriceNextX96,
        uint160 sqrtPriceLimitX96
    ) internal pure returns (uint160 sqrtPriceTargetX96) {
        assembly {
            // a flag to toggle between sqrtPriceNextX96 and sqrtPriceLimitX96
            // when zeroForOne == true, nextOrLimit reduces to sqrtPriceNextX96 >= sqrtPriceLimitX96
            // sqrtPriceTargetX96 = max(sqrtPriceNextX96, sqrtPriceLimitX96)
            // when zeroForOne == false, nextOrLimit reduces to sqrtPriceNextX96 < sqrtPriceLimitX96
            // sqrtPriceTargetX96 = min(sqrtPriceNextX96, sqrtPriceLimitX96)
            let nextOrLimit := xor(lt(sqrtPriceNextX96, sqrtPriceLimitX96), zeroForOne)
            let symDiff := xor(sqrtPriceNextX96, sqrtPriceLimitX96)
            sqrtPriceTargetX96 := xor(sqrtPriceLimitX96, mul(symDiff, nextOrLimit))
        }
    }

    /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap
    /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive
    /// @param sqrtRatioCurrentX96 The current sqrt price of the pool
    /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred
    /// @param liquidity The usable liquidity
    /// @param amountRemaining How much input or output amount is remaining to be swapped in/out
    /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip
    /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target
    /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap
    /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap
    /// @return feeAmount The amount of input that will be taken as a fee
    function computeSwapStep(
        uint160 sqrtRatioCurrentX96,
        uint160 sqrtRatioTargetX96,
        uint128 liquidity,
        int256 amountRemaining,
        uint24 feePips
    ) internal pure returns (uint160 sqrtRatioNextX96, uint256 amountIn, uint256 amountOut, uint256 feeAmount) {
        unchecked {
            uint256 _feePips = feePips; // cast once and cache
            bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;
            bool exactOut = amountRemaining < 0;

            if (!exactOut) {
                uint256 amountRemainingLessFee = FullMath.mulDiv(
                    uint256(amountRemaining),
                    MAX_FEE_PIPS - _feePips,
                    MAX_FEE_PIPS
                );
                amountIn = zeroForOne
                    ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)
                    : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);
                if (amountRemainingLessFee >= amountIn) {
                    // `amountIn` is capped by the target price
                    sqrtRatioNextX96 = sqrtRatioTargetX96;
                    feeAmount = FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_FEE_PIPS - _feePips);
                } else {
                    // exhaust the remaining amount
                    amountIn = amountRemainingLessFee;
                    sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(
                        sqrtRatioCurrentX96,
                        liquidity,
                        amountRemainingLessFee,
                        zeroForOne
                    );
                    // we didn't reach the target, so take the remainder of the maximum input as fee
                    feeAmount = uint256(amountRemaining) - amountIn;
                }
                amountOut = zeroForOne
                    ? SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false)
                    : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);
            } else {
                amountOut = zeroForOne
                    ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)
                    : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);
                if (uint256(-amountRemaining) >= amountOut) {
                    // `amountOut` is capped by the target price
                    sqrtRatioNextX96 = sqrtRatioTargetX96;
                } else {
                    // cap the output amount to not exceed the remaining output amount
                    amountOut = uint256(-amountRemaining);
                    sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(
                        sqrtRatioCurrentX96,
                        liquidity,
                        amountOut,
                        zeroForOne
                    );
                }
                amountIn = zeroForOne
                    ? SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true)
                    : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);
                feeAmount = FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_FEE_PIPS - _feePips);
            }
        }
    }

    /// @notice Computes the result of swapping some amount in given the parameters of the swap
    /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive
    /// @param sqrtRatioCurrentX96 The current sqrt price of the pool
    /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred
    /// @param liquidity The usable liquidity
    /// @param amountRemaining How much input amount is remaining to be swapped in
    /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip
    /// @return sqrtRatioNextX96 The price after swapping the amount in, not to exceed the price target
    /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap
    /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap
    function computeSwapStepExactIn(
        uint160 sqrtRatioCurrentX96,
        uint160 sqrtRatioTargetX96,
        uint128 liquidity,
        uint256 amountRemaining,
        uint256 feePips
    ) internal pure returns (uint160 sqrtRatioNextX96, uint256 amountIn, uint256 amountOut) {
        bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;
        uint256 amountRemainingLessFee = FullMath.mulDiv(
            amountRemaining,
            UnsafeMath.sub(MAX_FEE_PIPS, feePips),
            MAX_FEE_PIPS
        );
        amountIn = zeroForOne
            ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)
            : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);
        if (amountRemainingLessFee >= amountIn) {
            // `amountIn` is capped by the target price
            sqrtRatioNextX96 = sqrtRatioTargetX96;
            // add the fee amount
            amountIn = FullMath.mulDivRoundingUp(amountIn, MAX_FEE_PIPS, UnsafeMath.sub(MAX_FEE_PIPS, feePips));
        } else {
            // exhaust the remaining amount
            amountIn = amountRemaining;
            sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(
                sqrtRatioCurrentX96,
                liquidity,
                amountRemainingLessFee,
                zeroForOne
            );
        }
        amountOut = zeroForOne
            ? SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false)
            : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);
    }

    /// @notice Computes the result of swapping some amount out, given the parameters of the swap
    /// @param sqrtRatioCurrentX96 The current sqrt price of the pool
    /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred
    /// @param liquidity The usable liquidity
    /// @param amountRemaining How much output amount is remaining to be swapped out
    /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip
    /// @return sqrtRatioNextX96 The price after swapping the amount out, not to exceed the price target
    /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap
    /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap
    function computeSwapStepExactOut(
        uint160 sqrtRatioCurrentX96,
        uint160 sqrtRatioTargetX96,
        uint128 liquidity,
        uint256 amountRemaining,
        uint256 feePips
    ) internal pure returns (uint160 sqrtRatioNextX96, uint256 amountIn, uint256 amountOut) {
        bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;
        amountOut = zeroForOne
            ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)
            : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);
        if (amountRemaining >= amountOut) {
            // `amountOut` is capped by the target price
            sqrtRatioNextX96 = sqrtRatioTargetX96;
        } else {
            // cap the output amount to not exceed the remaining output amount
            amountOut = amountRemaining;
            sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(
                sqrtRatioCurrentX96,
                liquidity,
                amountRemaining,
                zeroForOne
            );
        }
        amountIn = FullMath.mulDivRoundingUp(
            zeroForOne
                ? SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true)
                : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true),
            MAX_FEE_PIPS,
            UnsafeMath.sub(MAX_FEE_PIPS, feePips)
        );
    }
}

// node_modules/@aperture_finance/uni-v3-lib/src/TickBitmap.sol

/// @title Packed tick initialized state library
/// @author Aperture Finance
/// @author Modified from Uniswap (https://github.com/uniswap/v3-core/blob/main/contracts/libraries/TickBitmap.sol)
/// @notice Stores a packed mapping of tick index to its initialized state
/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.
library TickBitmap {
    /// @dev round towards negative infinity
    function compress(int24 tick, int24 tickSpacing) internal pure returns (int24 compressed) {
        // compressed = tick / tickSpacing;
        // if (tick < 0 && tick % tickSpacing != 0) compressed--;
        assembly {
            compressed := sub(
                sdiv(tick, tickSpacing),
                // if (tick < 0 && tick % tickSpacing != 0) then tick % tickSpacing < 0, vice versa
                slt(smod(tick, tickSpacing), 0)
            )
        }
    }

    /// @notice Computes the position in the mapping where the initialized bit for a tick lives
    /// @param tick The tick for which to compute the position
    /// @return wordPos The key in the mapping containing the word in which the bit is stored
    /// @return bitPos The bit position in the word where the flag is stored
    function position(int24 tick) internal pure returns (int16 wordPos, uint8 bitPos) {
        assembly {
            // signed arithmetic shift right
            wordPos := sar(8, tick)
            bitPos := and(tick, 0xff)
        }
    }

    /// @notice Flips the initialized state for a given tick from false to true, or vice versa
    /// @param self The mapping in which to flip the tick
    /// @param tick The tick to flip
    /// @param tickSpacing The spacing between usable ticks
    function flipTick(mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing) internal {
        assembly ("memory-safe") {
            // ensure that the tick is spaced
            if smod(tick, tickSpacing) {
                revert(0, 0)
            }
            tick := sdiv(tick, tickSpacing)
            // calculate the storage slot corresponding to the tick
            // wordPos = tick >> 8
            mstore(0, sar(8, tick))
            mstore(0x20, self.slot)
            // the slot of self[wordPos] is keccak256(abi.encode(wordPos, self.slot))
            let slot := keccak256(0, 0x40)
            // mask = 1 << bitPos = 1 << (tick % 256)
            // self[wordPos] ^= mask
            sstore(slot, xor(sload(slot), shl(and(tick, 0xff), 1)))
        }
    }

    /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either
    /// to the left (less than or equal to) or right (greater than) of the given tick
    /// @param self The mapping in which to compute the next initialized tick
    /// @param tick The starting tick
    /// @param tickSpacing The spacing between usable ticks
    /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)
    /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick
    /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks
    function nextInitializedTickWithinOneWord(
        mapping(int16 => uint256) storage self,
        int24 tick,
        int24 tickSpacing,
        bool lte
    ) internal view returns (int24 next, bool initialized) {
        unchecked {
            int24 compressed = compress(tick, tickSpacing);

            if (lte) {
                (int16 wordPos, uint8 bitPos) = position(compressed);
                // all the 1s at or to the right of the current bitPos
                uint256 masked;
                assembly ("memory-safe") {
                    // mask = (1 << (bitPos + 1)) - 1 = (2 << bitPos) - 1
                    // (2 << bitPos) may overflow but fine since 2 << 255 = 0
                    let mask := sub(shl(bitPos, 2), 1)
                    // masked = self[wordPos] & mask
                    mstore(0, wordPos)
                    mstore(0x20, self.slot)
                    masked := and(sload(keccak256(0, 0x40)), mask)
                }

                // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word
                initialized = masked != 0;
                // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
                if (initialized) {
                    uint8 msb = BitMath.mostSignificantBit(masked);
                    assembly {
                        next := mul(add(sub(compressed, bitPos), msb), tickSpacing)
                    }
                } else {
                    assembly {
                        next := mul(sub(compressed, bitPos), tickSpacing)
                    }
                }
            } else {
                // start from the word of the next tick, since the current tick state doesn't matter
                (int16 wordPos, uint8 bitPos) = position(++compressed);
                // all the 1s at or to the left of the bitPos
                uint256 masked;
                assembly ("memory-safe") {
                    // mask = ~((1 << bitPos) - 1) = -((1 << bitPos) - 1) - 1 = -(1 << bitPos)
                    let mask := sub(0, shl(bitPos, 1))
                    // masked = self[wordPos] & mask
                    mstore(0, wordPos)
                    mstore(0x20, self.slot)
                    masked := and(sload(keccak256(0, 0x40)), mask)
                }

                // if there are no initialized ticks to the left of the current tick, return leftmost in the word
                initialized = masked != 0;
                // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
                if (initialized) {
                    uint8 lsb = BitMath.leastSignificantBit(masked);
                    assembly {
                        next := mul(add(sub(compressed, bitPos), lsb), tickSpacing)
                    }
                } else {
                    assembly {
                        next := mul(add(sub(compressed, bitPos), 255), tickSpacing)
                    }
                }
            }
        }
    }

    /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either
    /// to the left (less than or equal to) or right (greater than) of the given tick
    /// @param pool Uniswap v3 pool
    /// @param tick The starting tick
    /// @param tickSpacing The spacing between usable ticks
    /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)
    /// @param lastWordPos The last accessed word position in the Bitmap. Set it to `type(int16).min` for the first call.
    /// @param lastWord The last accessed word in the Bitmap
    /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick
    /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks
    /// @return wordPos The word position of the next initialized tick in the Bitmap
    /// @return tickWord The word of the next initialized tick in the Bitmap
    function nextInitializedTickWithinOneWord(
        V3PoolCallee pool,
        int24 tick,
        int24 tickSpacing,
        bool lte,
        int16 lastWordPos,
        uint256 lastWord
    ) internal view returns (int24 next, bool initialized, int16 wordPos, uint256 tickWord) {
        int24 compressed = compress(tick, tickSpacing);
        uint8 bitPos;
        uint256 masked;

        if (lte) {
            (wordPos, bitPos) = position(compressed);
            // Reuse the same word if the position doesn't change
            tickWord = wordPos == lastWordPos ? lastWord : pool.tickBitmap(wordPos);
            assembly {
                // mask = (1 << (bitPos + 1)) - 1 = (2 << bitPos) - 1
                // (2 << bitPos) may overflow but fine since 2 << 255 = 0
                let mask := sub(shl(bitPos, 2), 1)
                // all the 1s at or to the right of the current bitPos
                masked := and(tickWord, mask)
            }

            // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word
            initialized = masked != 0;
            // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
            if (!initialized) {
                assembly {
                    next := mul(sub(compressed, bitPos), tickSpacing)
                }
            } else {
                uint8 msb = BitMath.mostSignificantBit(masked);
                assembly {
                    next := mul(add(sub(compressed, bitPos), msb), tickSpacing)
                }
            }
        } else {
            // start from the word of the next tick, since the current tick state doesn't matter
            unchecked {
                (wordPos, bitPos) = position(++compressed);
            }
            // Reuse the same word if the position doesn't change
            tickWord = wordPos == lastWordPos ? lastWord : pool.tickBitmap(wordPos);
            assembly {
                // mask = ~((1 << bitPos) - 1) = -((1 << bitPos) - 1) - 1 = -(1 << bitPos)
                let mask := sub(0, shl(bitPos, 1))
                // all the 1s at or to the left of the bitPos
                masked := and(tickWord, mask)
            }

            // if there are no initialized ticks to the left of the current tick, return leftmost in the word
            initialized = masked != 0;
            // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
            if (!initialized) {
                assembly {
                    next := mul(add(sub(compressed, bitPos), 255), tickSpacing)
                }
            } else {
                uint8 lsb = BitMath.leastSignificantBit(masked);
                assembly {
                    next := mul(add(sub(compressed, bitPos), lsb), tickSpacing)
                }
            }
        }
    }

    /// @notice Returns the next initialized tick not limited to the same word as the tick that is either
    /// to the left (less than or equal to) or right (greater than) of the given tick
    /// @dev It is assumed that the next initialized tick exists.
    /// @param pool Uniswap v3 pool
    /// @param tick The starting tick
    /// @param tickSpacing The spacing between usable ticks
    /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)
    /// @param lastWordPos The last accessed word position in the Bitmap. Set it to `type(int16).min` for the first call.
    /// @param lastWord The last accessed word in the Bitmap
    /// @return next The next initialized tick
    /// @return wordPos The word position of the next initialized tick in the Bitmap
    /// @return tickWord The word of the next initialized tick in the Bitmap
    function nextInitializedTick(
        V3PoolCallee pool,
        int24 tick,
        int24 tickSpacing,
        bool lte,
        int16 lastWordPos,
        uint256 lastWord
    ) internal view returns (int24 next, int16 wordPos, uint256 tickWord) {
        unchecked {
            int24 compressed = compress(tick, tickSpacing);
            uint8 bitPos;
            uint256 masked;
            uint8 sb;
            if (lte) {
                (wordPos, bitPos) = position(compressed);
                // Reuse the same word if the position doesn't change
                tickWord = wordPos == lastWordPos ? lastWord : pool.tickBitmap(wordPos);
                assembly {
                    // mask = (1 << (bitPos + 1)) - 1 = (2 << bitPos) - 1
                    // (2 << bitPos) may overflow but fine since 2 << 255 = 0
                    let mask := sub(shl(bitPos, 2), 1)
                    // all the 1s at or to the right of the current bitPos
                    masked := and(tickWord, mask)
                }
                while (masked == 0) {
                    // Always query the next word to the left
                    masked = tickWord = pool.tickBitmap(--wordPos);
                }
                sb = BitMath.mostSignificantBit(masked);
            } else {
                // start from the word of the next tick, since the current tick state doesn't matter
                (wordPos, bitPos) = position(++compressed);
                // Reuse the same word if the position doesn't change
                tickWord = wordPos == lastWordPos ? lastWord : pool.tickBitmap(wordPos);
                assembly {
                    // mask = ~((1 << bitPos) - 1) = -((1 << bitPos) - 1) - 1 = -(1 << bitPos)
                    let mask := sub(0, shl(bitPos, 1))
                    // all the 1s at or to the left of the bitPos
                    masked := and(tickWord, mask)
                }
                while (masked == 0) {
                    // Always query the next word to the right
                    masked = tickWord = pool.tickBitmap(++wordPos);
                }
                sb = BitMath.leastSignificantBit(masked);
            }
            // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
            assembly {
                // next = (wordPos * 256 + sb) * tickSpacing
                next := mul(add(shl(8, wordPos), sb), tickSpacing)
            }
        }
    }
}

// src/libraries/OptimalSwap.sol

/// @title Optimal Swap Library
/// @author Aperture Finance
/// @notice Optimal library for optimal double-sided Uniswap v3 liquidity provision using closed form solution
library OptimalSwap {
    using TickMath for int24;
    using FullMath for uint256;
    using UnsafeMath for uint256;

    uint256 internal constant MAX_FEE_PIPS = 1e6;

    error Invalid_Pool();
    error Invalid_Tick_Range();
    error Math_Overflow();

    struct SwapState {
        // liquidity in range after swap, accessible by `mload(state)`
        uint128 liquidity;
        // sqrt(price) after swap, accessible by `mload(add(state, 0x20))`
        uint256 sqrtPriceX96;
        // tick after swap, accessible by `mload(add(state, 0x40))`
        int24 tick;
        // The desired amount of token0 to add liquidity, `mload(add(state, 0x60))`
        uint256 amount0Desired;
        // The desired amount of token1 to add liquidity, `mload(add(state, 0x80))`
        uint256 amount1Desired;
        // sqrt(price) at the lower tick, `mload(add(state, 0xa0))`
        uint256 sqrtRatioLowerX96;
        // sqrt(price) at the upper tick, `mload(add(state, 0xc0))`
        uint256 sqrtRatioUpperX96;
        // the fee taken from the input amount, expressed in hundredths of a bip
        // accessible by `mload(add(state, 0xe0))`
        uint256 feePips;
        // the tick spacing of the pool, accessible by `mload(add(state, 0x100))`
        int24 tickSpacing;
    }

    /// @notice Get swap amount, output amount, swap direction for double-sided optimal deposit
    /// @dev Given the elegant analytic solution and custom optimizations to Uniswap libraries,
    /// the amount of gas is at the order of 10k depending on the swap amount and the number of ticks crossed,
    /// an order of magnitude less than that achieved by binary search, which can be calculated on-chain.
    /// @param pool Uniswap v3 pool
    /// @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 amount0Desired The desired amount of token0 to be spent
    /// @param amount1Desired The desired amount of token1 to be spent
    /// @return amountIn The optimal swap amount
    /// @return amountOut Expected output amount
    /// @return zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @return sqrtPriceX96 The sqrt(price) after the swap
    function getOptimalSwap(
        V3PoolCallee pool,
        int24 tickLower,
        int24 tickUpper,
        uint256 amount0Desired,
        uint256 amount1Desired
    ) internal view returns (uint256 amountIn, uint256 amountOut, bool zeroForOne, uint160 sqrtPriceX96) {
        if (amount0Desired == 0 && amount1Desired == 0) return (0, 0, false, 0);
        if (tickLower >= tickUpper || tickLower < TickMath.MIN_TICK || tickUpper > TickMath.MAX_TICK)
            revert Invalid_Tick_Range();
        // Ensure the pool exists.
        assembly ("memory-safe") {
            let poolCodeSize := extcodesize(pool)
            if iszero(poolCodeSize) {
                // revert Invalid_Pool()
                mstore(0, 0x01ac05a5)
                revert(0x1c, 0x04)
            }
        }
        // intermediate state cache
        SwapState memory state;
        // Populate `SwapState` with hardcoded offsets.
        {
            int24 tick;
            (sqrtPriceX96, tick) = pool.sqrtPriceX96AndTick();
            assembly ("memory-safe") {
                // state.tick = tick
                mstore(add(state, 0x40), tick)
            }
        }
        {
            uint128 liquidity = pool.liquidity();
            uint256 feePips = pool.fee();
            int24 tickSpacing = pool.tickSpacing();
            assembly ("memory-safe") {
                // state.liquidity = liquidity
                mstore(state, liquidity)
                // state.sqrtPriceX96 = sqrtPriceX96
                mstore(add(state, 0x20), sqrtPriceX96)
                // state.amount0Desired = amount0Desired
                mstore(add(state, 0x60), amount0Desired)
                // state.amount1Desired = amount1Desired
                mstore(add(state, 0x80), amount1Desired)
                // state.feePips = feePips
                mstore(add(state, 0xe0), feePips)
                // state.tickSpacing = tickSpacing
                mstore(add(state, 0x100), tickSpacing)
            }
        }
        uint160 sqrtRatioLowerX96 = tickLower.getSqrtRatioAtTick();
        uint160 sqrtRatioUpperX96 = tickUpper.getSqrtRatioAtTick();
        assembly ("memory-safe") {
            // state.sqrtRatioLowerX96 = sqrtRatioLowerX96
            mstore(add(state, 0xa0), sqrtRatioLowerX96)
            // state.sqrtRatioUpperX96 = sqrtRatioUpperX96
            mstore(add(state, 0xc0), sqrtRatioUpperX96)
        }
        zeroForOne = isZeroForOne(amount0Desired, amount1Desired, sqrtPriceX96, sqrtRatioLowerX96, sqrtRatioUpperX96);
        // Simulate optimal swap by crossing ticks until the direction reverses.
        crossTicks(pool, state, sqrtPriceX96, zeroForOne);
        // Active liquidity at the last tick of optimal swap
        uint128 liquidityLast;
        // sqrt(price) at the last tick of optimal swap
        uint160 sqrtPriceLastTickX96;
        // Remaining amount of token0 to add liquidity at the last tick
        uint256 amount0LastTick;
        // Remaining amount of token1 to add liquidity at the last tick
        uint256 amount1LastTick;
        assembly ("memory-safe") {
            // liquidityLast = state.liquidity
            liquidityLast := mload(state)
            // sqrtPriceLastTickX96 = state.sqrtPriceX96
            sqrtPriceLastTickX96 := mload(add(state, 0x20))
            // amount0LastTick = state.amount0Desired
            amount0LastTick := mload(add(state, 0x60))
            // amount1LastTick = state.amount1Desired
            amount1LastTick := mload(add(state, 0x80))
        }
        unchecked {
            if (!zeroForOne) {
                // The last tick is out of range. There are two cases:
                // 1. There is not enough token1 to swap to reach the lower tick.
                // 2. There is no initialized tick between the last tick and the lower tick.
                if (sqrtPriceLastTickX96 < sqrtRatioLowerX96) {
                    sqrtPriceX96 = SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown(
                        sqrtPriceLastTickX96,
                        liquidityLast,
                        amount1LastTick.mulDiv(MAX_FEE_PIPS - state.feePips, MAX_FEE_PIPS),
                        true
                    );
                    // The final price is out of range. Simply consume all token1.
                    if (sqrtPriceX96 < sqrtRatioLowerX96) {
                        amountIn = amount1Desired;
                    }
                    // Swap to the lower tick and update the state.
                    else {
                        amount1LastTick -= SqrtPriceMath
                            .getAmount1Delta(sqrtPriceLastTickX96, sqrtRatioLowerX96, liquidityLast, true)
                            .mulDiv(MAX_FEE_PIPS, MAX_FEE_PIPS - state.feePips);
                        amount0LastTick += SqrtPriceMath.getAmount0Delta(
                            sqrtPriceLastTickX96,
                            sqrtRatioLowerX96,
                            liquidityLast,
                            false
                        );
                        sqrtPriceLastTickX96 = sqrtRatioLowerX96;
                        state.sqrtPriceX96 = sqrtPriceLastTickX96;
                        state.amount0Desired = amount0LastTick;
                        state.amount1Desired = amount1LastTick;
                    }
                }
                // The final price is in range. Use the closed form solution.
                if (sqrtPriceLastTickX96 >= sqrtRatioLowerX96) {
                    sqrtPriceX96 = solveOptimalOneForZero(state);
                    amountIn =
                        amount1Desired -
                        amount1LastTick +
                        SqrtPriceMath.getAmount1Delta(sqrtPriceX96, sqrtPriceLastTickX96, liquidityLast, true).mulDiv(
                            MAX_FEE_PIPS,
                            MAX_FEE_PIPS - state.feePips
                        );
                }
                amountOut =
                    amount0LastTick -
                    amount0Desired +
                    SqrtPriceMath.getAmount0Delta(sqrtPriceX96, sqrtPriceLastTickX96, liquidityLast, false);
            } else {
                // The last tick is out of range. There are two cases:
                // 1. There is not enough token0 to swap to reach the upper tick.
                // 2. There is no initialized tick between the last tick and the upper tick.
                if (sqrtPriceLastTickX96 > sqrtRatioUpperX96) {
                    sqrtPriceX96 = SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp(
                        sqrtPriceLastTickX96,
                        liquidityLast,
                        amount0LastTick.mulDiv(MAX_FEE_PIPS - state.feePips, MAX_FEE_PIPS),
                        true
                    );
                    // The final price is out of range. Simply consume all token0.
                    if (sqrtPriceX96 >= sqrtRatioUpperX96) {
                        amountIn = amount0Desired;
                    }
                    // Swap to the upper tick and update the state.
                    else {
                        amount0LastTick -= SqrtPriceMath
                            .getAmount0Delta(sqrtRatioUpperX96, sqrtPriceLastTickX96, liquidityLast, true)
                            .mulDiv(MAX_FEE_PIPS, MAX_FEE_PIPS - state.feePips);
                        amount1LastTick += SqrtPriceMath.getAmount1Delta(
                            sqrtRatioUpperX96,
                            sqrtPriceLastTickX96,
                            liquidityLast,
                            false
                        );
                        sqrtPriceLastTickX96 = sqrtRatioUpperX96;
                        state.sqrtPriceX96 = sqrtPriceLastTickX96;
                        state.amount0Desired = amount0LastTick;
                        state.amount1Desired = amount1LastTick;
                    }
                }
                // The final price is in range. Use the closed form solution.
                if (sqrtPriceLastTickX96 <= sqrtRatioUpperX96) {
                    sqrtPriceX96 = solveOptimalZeroForOne(state);
                    amountIn =
                        amount0Desired -
                        amount0LastTick +
                        SqrtPriceMath.getAmount0Delta(sqrtPriceX96, sqrtPriceLastTickX96, liquidityLast, true).mulDiv(
                            MAX_FEE_PIPS,
                            MAX_FEE_PIPS - state.feePips
                        );
                }
                amountOut =
                    amount1LastTick -
                    amount1Desired +
                    SqrtPriceMath.getAmount1Delta(sqrtPriceX96, sqrtPriceLastTickX96, liquidityLast, false);
            }
        }
    }

    /// @dev Check if the remaining amount is enough to cross the next initialized tick.
    // If so, check whether the swap direction changes for optimal deposit. If so, we swap too much and the final sqrt
    // price must be between the current tick and the next tick. Otherwise the next tick must be crossed.
    function crossTicks(V3PoolCallee pool, SwapState memory state, uint160 sqrtPriceX96, bool zeroForOne) private view {
        // the next tick to swap to from the current tick in the swap direction
        int24 tickNext;
        // Ensure the initial `wordPos` doesn't coincide with the starting tick's.
        int16 wordPos = type(int16).min;
        // a word in `pool.tickBitmap`
        uint256 tickWord;

        do {
            (tickNext, wordPos, tickWord) = TickBitmap.nextInitializedTick(
                pool,
                state.tick,
                state.tickSpacing,
                zeroForOne,
                wordPos,
                tickWord
            );
            // sqrt(price) for the next tick (1/0)
            uint160 sqrtPriceNextX96 = tickNext.getSqrtRatioAtTick();
            // The desired amount of token0 to add liquidity after swap
            uint256 amount0Desired;
            // The desired amount of token1 to add liquidity after swap
            uint256 amount1Desired;

            unchecked {
                if (!zeroForOne) {
                    // Abuse `amount1Desired` to store `amountIn` to avoid stack too deep errors.
                    (sqrtPriceX96, amount1Desired, amount0Desired) = SwapMath.computeSwapStepExactIn(
                        uint160(state.sqrtPriceX96),
                        sqrtPriceNextX96,
                        state.liquidity,
                        state.amount1Desired,
                        state.feePips
                    );
                    amount0Desired = state.amount0Desired + amount0Desired;
                    amount1Desired = state.amount1Desired - amount1Desired;
                } else {
                    // Abuse `amount0Desired` to store `amountIn` to avoid stack too deep errors.
                    (sqrtPriceX96, amount0Desired, amount1Desired) = SwapMath.computeSwapStepExactIn(
                        uint160(state.sqrtPriceX96),
                        sqrtPriceNextX96,
                        state.liquidity,
                        state.amount0Desired,
                        state.feePips
                    );
                    amount0Desired = state.amount0Desired - amount0Desired;
                    amount1Desired = state.amount1Desired + amount1Desired;
                }
            }

            // If the remaining amount is large enough to consume the current tick and the optimal swap direction
            // doesn't change, continue crossing ticks.
            if (sqrtPriceX96 != sqrtPriceNextX96) break;
            if (
                isZeroForOne(
                    amount0Desired,
                    amount1Desired,
                    sqrtPriceX96,
                    state.sqrtRatioLowerX96,
                    state.sqrtRatioUpperX96
                ) != zeroForOne
            ) {
                break;
            } else {
                int128 liquidityNet = pool.liquidityNet(tickNext);
                assembly ("memory-safe") {
                    // If we're moving leftward, we interpret `liquidityNet` as the opposite sign.
                    // If zeroForOne, liquidityNet = -liquidityNet = ~liquidityNet + 1 = -1 ^ liquidityNet + 1.
                    // Therefore, liquidityNet = -zeroForOne ^ liquidityNet + zeroForOne.
                    liquidityNet := add(zeroForOne, xor(sub(0, zeroForOne), liquidityNet))
                    // `liquidity` is the first in `SwapState`
                    mstore(state, add(mload(state), liquidityNet))
                    // state.sqrtPriceX96 = sqrtPriceX96
                    mstore(add(state, 0x20), sqrtPriceX96)
                    // state.tick = zeroForOne ? tickNext - 1 : tickNext
                    mstore(add(state, 0x40), sub(tickNext, zeroForOne))
                    // state.amount0Desired = amount0Desired
                    mstore(add(state, 0x60), amount0Desired)
                    // state.amount1Desired = amount1Desired
                    mstore(add(state, 0x80), amount1Desired)
                }
            }
        } while (true);
    }

    /// @dev Analytic solution for optimal swap between two nearest initialized ticks swapping token0 to token1
    /// @param state Pool state at the last tick of optimal swap
    /// @return sqrtPriceFinalX96 sqrt(price) after optimal swap
    function solveOptimalZeroForOne(SwapState memory state) private pure returns (uint160 sqrtPriceFinalX96) {
        /**
         * root = (sqrt(b^2 + 4ac) + b) / 2a
         * `a` is in the order of `amount0Desired`. `b` is in the order of `liquidity`.
         * `c` is in the order of `amount1Desired`.
         * `a`, `b`, `c` are signed integers in two's complement but typed as unsigned to avoid unnecessary casting.
         */
        uint256 a;
        uint256 b;
        uint256 c;
        uint256 sqrtPriceX96;
        unchecked {
            uint256 liquidity;
            uint256 sqrtRatioUpperX96;
            uint256 feePips;
            uint256 FEE_COMPLEMENT;
            assembly ("memory-safe") {
                // liquidity = state.liquidity
                liquidity := mload(state)
                // sqrtPriceX96 = state.sqrtPriceX96
                sqrtPriceX96 := mload(add(state, 0x20))
                // sqrtRatioUpperX96 = state.sqrtRatioUpperX96
                sqrtRatioUpperX96 := mload(add(state, 0xc0))
                // feePips = state.feePips
                feePips := mload(add(state, 0xe0))
                // FEE_COMPLEMENT = MAX_FEE_PIPS - feePips
                FEE_COMPLEMENT := sub(MAX_FEE_PIPS, feePips)
            }
            {
                uint256 a0;
                assembly ("memory-safe") {
                    // amount0Desired = state.amount0Desired
                    let amount0Desired := mload(add(state, 0x60))
                    let liquidityX96 := shl(96, liquidity)
                    // a = amount0Desired + liquidity / ((1 - f) * sqrtPrice) - liquidity / sqrtRatioUpper
                    a0 := add(amount0Desired, div(mul(MAX_FEE_PIPS, liquidityX96), mul(FEE_COMPLEMENT, sqrtPriceX96)))
                    a := sub(a0, div(liquidityX96, sqrtRatioUpperX96))
                    // `a` is always positive and greater than `amount0Desired`.
                    if iszero(gt(a, amount0Desired)) {
                        // revert Math_Overflow()
                        mstore(0, 0x20236808)
                        revert(0x1c, 0x04)
                    }
                }
                b = a0.mulDivQ96(state.sqrtRatioLowerX96);
                assembly {
                    b := add(div(mul(feePips, liquidity), FEE_COMPLEMENT), b)
                }
            }
            {
                // c = amount1Desired + liquidity * sqrtPrice - liquidity * sqrtRatioLower / (1 - f)
                uint256 c0 = liquidity.mulDivQ96(sqrtPriceX96);
                assembly ("memory-safe") {
                    // c0 = amount1Desired + liquidity * sqrtPrice
                    c0 := add(mload(add(state, 0x80)), c0)
                }
                c = c0 - liquidity.mulDivQ96((MAX_FEE_PIPS * state.sqrtRatioLowerX96) / FEE_COMPLEMENT);
                b -= c0.mulDiv(FixedPoint96.Q96, sqrtRatioUpperX96);
            }
            assembly {
                a := shl(1, a)
                c := shl(1, c)
            }
        }
        // Given a root exists, the following calculations cannot realistically overflow/underflow.
        unchecked {
            uint256 numerator = FullMath.sqrt(b * b + a * c) + b;
            assembly {
                // `numerator` and `a` must be positive so use `div`.
                sqrtPriceFinalX96 := div(shl(96, numerator), a)
            }
        }
        // The final price must be less than or equal to the price at the last tick.
        // However the calculated price may increase if the ratio is close to optimal.
        assembly {
            // sqrtPriceFinalX96 = min(sqrtPriceFinalX96, sqrtPriceX96)
            sqrtPriceFinalX96 := xor(
                sqrtPriceX96,
                mul(xor(sqrtPriceX96, sqrtPriceFinalX96), lt(sqrtPriceFinalX96, sqrtPriceX96))
            )
        }
    }

    /// @dev Analytic solution for optimal swap between two nearest initialized ticks swapping token1 to token0
    /// @param state Pool state at the last tick of optimal swap
    /// @return sqrtPriceFinalX96 sqrt(price) after optimal swap
    function solveOptimalOneForZero(SwapState memory state) private pure returns (uint160 sqrtPriceFinalX96) {
        /**
         * root = (sqrt(b^2 + 4ac) + b) / 2a
         * `a` is in the order of `amount0Desired`. `b` is in the order of `liquidity`.
         * `c` is in the order of `amount1Desired`.
         * `a`, `b`, `c` are signed integers in two's complement but typed as unsigned to avoid unnecessary casting.
         */
        uint256 a;
        uint256 b;
        uint256 c;
        uint256 sqrtPriceX96;
        unchecked {
            uint256 liquidity;
            uint256 sqrtRatioUpperX96;
            uint256 feePips;
            uint256 FEE_COMPLEMENT;
            assembly ("memory-safe") {
                // liquidity = state.liquidity
                liquidity := mload(state)
                // sqrtPriceX96 = state.sqrtPriceX96
                sqrtPriceX96 := mload(add(state, 0x20))
                // sqrtRatioUpperX96 = state.sqrtRatioUpperX96
                sqrtRatioUpperX96 := mload(add(state, 0xc0))
                // feePips = state.feePips
                feePips := mload(add(state, 0xe0))
                // FEE_COMPLEMENT = MAX_FEE_PIPS - feePips
                FEE_COMPLEMENT := sub(MAX_FEE_PIPS, feePips)
            }
            {
                // a = state.amount0Desired + liquidity / sqrtPrice - liquidity / ((1 - f) * sqrtRatioUpper)
                uint256 a0;
                assembly ("memory-safe") {
                    let liquidityX96 := shl(96, liquidity)
                    // a0 = state.amount0Desired + liquidity / sqrtPrice
                    a0 := add(mload(add(state, 0x60)), div(liquidityX96, sqrtPriceX96))
                    a := sub(a0, div(mul(MAX_FEE_PIPS, liquidityX96), mul(FEE_COMPLEMENT, sqrtRatioUpperX96)))
                }
                b = a0.mulDivQ96(state.sqrtRatioLowerX96);
                assembly {
                    b := sub(b, div(mul(feePips, liquidity), FEE_COMPLEMENT))
                }
            }
            {
                // c = amount1Desired + liquidity * sqrtPrice / (1 - f) - liquidity * sqrtRatioLower
                uint256 c0 = liquidity.mulDivQ96((MAX_FEE_PIPS * sqrtPriceX96) / FEE_COMPLEMENT);
                uint256 amount1Desired;
                assembly ("memory-safe") {
                    // amount1Desired = state.amount1Desired
                    amount1Desired := mload(add(state, 0x80))
                    // c0 = amount1Desired + liquidity * sqrtPrice / (1 - f)
                    c0 := add(amount1Desired, c0)
                }
                c = c0 - liquidity.mulDivQ96(state.sqrtRatioLowerX96);
                assembly ("memory-safe") {
                    // `c` is always positive and greater than `amount1Desired`.
                    if iszero(gt(c, amount1Desired)) {
                        // revert Math_Overflow()
                        mstore(0, 0x20236808)
                        revert(0x1c, 0x04)
                    }
                }
                b -= c0.mulDiv(FixedPoint96.Q96, sqrtRatioUpperX96);
            }
            assembly {
                a := shl(1, a)
                c := shl(1, c)
            }
        }
        // Given a root exists, the following calculations cannot realistically overflow/underflow.
        unchecked {
            uint256 numerator = FullMath.sqrt(b * b + a * c) + b;
            assembly {
                // `numerator` and `a` may be negative so use `sdiv`.
                sqrtPriceFinalX96 := sdiv(shl(96, numerator), a)
            }
        }
        // The final price must be greater than or equal to the price at the last tick.
        // However the calculated price may decrease if the ratio is close to optimal.
        assembly {
            // sqrtPriceFinalX96 = max(sqrtPriceFinalX96, sqrtPriceX96)
            sqrtPriceFinalX96 := xor(
                sqrtPriceX96,
                mul(xor(sqrtPriceX96, sqrtPriceFinalX96), gt(sqrtPriceFinalX96, sqrtPriceX96))
            )
        }
    }

    /// @dev Swap direction to achieve optimal deposit when the current price is in range
    /// @param amount0Desired The desired amount of token0 to be spent
    /// @param amount1Desired The desired amount of token1 to be spent
    /// @param sqrtPriceX96 sqrt(price) at the last tick of optimal swap
    /// @param sqrtRatioLowerX96 The lower sqrt(price) of the position in which to add liquidity
    /// @param sqrtRatioUpperX96 The upper sqrt(price) of the position in which to add liquidity
    /// @return The direction of the swap, true for token0 to token1, false for token1 to token0
    function isZeroForOneInRange(
        uint256 amount0Desired,
        uint256 amount1Desired,
        uint256 sqrtPriceX96,
        uint256 sqrtRatioLowerX96,
        uint256 sqrtRatioUpperX96
    ) private pure returns (bool) {
        // amount0 = liquidity * (sqrt(upper) - sqrt(current)) / (sqrt(upper) * sqrt(current))
        // amount1 = liquidity * (sqrt(current) - sqrt(lower))
        // amount0 * amount1 = liquidity * (sqrt(upper) - sqrt(current)) / (sqrt(upper) * sqrt(current)) * amount1
        //     = liquidity * (sqrt(current) - sqrt(lower)) * amount0
        unchecked {
            return
                amount0Desired.mulDivQ96(sqrtPriceX96).mulDivQ96(sqrtPriceX96 - sqrtRatioLowerX96) >
                amount1Desired.mulDiv(sqrtRatioUpperX96 - sqrtPriceX96, sqrtRatioUpperX96);
        }
    }

    /// @dev Swap direction to achieve optimal deposit
    /// @param amount0Desired The desired amount of token0 to be spent
    /// @param amount1Desired The desired amount of token1 to be spent
    /// @param sqrtPriceX96 sqrt(price) at the last tick of optimal swap
    /// @param sqrtRatioLowerX96 The lower sqrt(price) of the position in which to add liquidity
    /// @param sqrtRatioUpperX96 The upper sqrt(price) of the position in which to add liquidity
    /// @return The direction of the swap, true for token0 to token1, false for token1 to token0
    function isZeroForOne(
        uint256 amount0Desired,
        uint256 amount1Desired,
        uint256 sqrtPriceX96,
        uint256 sqrtRatioLowerX96,
        uint256 sqrtRatioUpperX96
    ) internal pure returns (bool) {
        // If the current price is below `sqrtRatioLowerX96`, only token0 is required.
        if (sqrtPriceX96 <= sqrtRatioLowerX96) return false;
        // If the current tick is above `sqrtRatioUpperX96`, only token1 is required.
        else if (sqrtPriceX96 >= sqrtRatioUpperX96) return true;
        else
            return
                isZeroForOneInRange(amount0Desired, amount1Desired, sqrtPriceX96, sqrtRatioLowerX96, sqrtRatioUpperX96);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC4626.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC-721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC-721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0 >=0.5.0 ^0.8.24;

import {FixedPoint96} from "./OptimalSwap.sol";

// contracts/CL/core/libraries/FullMath.sol

/// @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++;
            }
        }
    }
}

// contracts/CL/periphery/libraries/LiquidityAmounts.sol

/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
    /// @notice Downcasts uint256 to uint128
    /// @param x The uint258 to be downcasted
    /// @return y The passed value, downcasted to uint128
    function toUint128(uint256 x) private pure returns (uint128 y) {
        require((y = uint128(x)) == x);
    }

    /// @notice Computes the amount of liquidity received for a given amount of token0 and price range
    /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param amount0 The amount0 being sent in
    /// @return liquidity The amount of returned liquidity
    function getLiquidityForAmount0(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount0
    ) internal pure returns (uint128 liquidity) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
        uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
        unchecked {
            return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
        }
    }

    /// @notice Computes the amount of liquidity received for a given amount of token1 and price range
    /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param amount1 The amount1 being sent in
    /// @return liquidity The amount of returned liquidity
    function getLiquidityForAmount1(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount1
    ) internal pure returns (uint128 liquidity) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
        unchecked {
            return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
        }
    }

    /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
    /// pool prices and the prices at the tick boundaries
    /// @param sqrtRatioX96 A sqrt price representing the current pool prices
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param amount0 The amount of token0 being sent in
    /// @param amount1 The amount of token1 being sent in
    /// @return liquidity The maximum amount of liquidity received
    function getLiquidityForAmounts(
        uint160 sqrtRatioX96,
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount0,
        uint256 amount1
    ) internal pure returns (uint128 liquidity) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        if (sqrtRatioX96 <= sqrtRatioAX96) {
            liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
        } else if (sqrtRatioX96 < sqrtRatioBX96) {
            uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
            uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);

            liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
        } else {
            liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
        }
    }

    /// @notice Computes the amount of token0 for a given amount of liquidity and a price range
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount0 The amount of token0
    function getAmount0ForLiquidity(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity
    ) internal pure returns (uint256 amount0) {
        unchecked {
            if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

            return
                FullMath.mulDiv(
                    uint256(liquidity) << FixedPoint96.RESOLUTION,
                    sqrtRatioBX96 - sqrtRatioAX96,
                    sqrtRatioBX96
                ) / sqrtRatioAX96;
        }
    }

    /// @notice Computes the amount of token1 for a given amount of liquidity and a price range
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount1 The amount of token1
    function getAmount1ForLiquidity(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity
    ) internal pure returns (uint256 amount1) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        unchecked {
            return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
        }
    }

    /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
    /// pool prices and the prices at the tick boundaries
    /// @param sqrtRatioX96 A sqrt price representing the current pool prices
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount0 The amount of token0
    /// @return amount1 The amount of token1
    function getAmountsForLiquidity(
        uint160 sqrtRatioX96,
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity
    ) internal pure returns (uint256 amount0, uint256 amount1) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        if (sqrtRatioX96 <= sqrtRatioAX96) {
            amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
        } else if (sqrtRatioX96 < sqrtRatioBX96) {
            amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
            amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
        } else {
            amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/IAccessControl.sol)

pragma solidity ^0.8.20;

/**
 * @dev External interface of AccessControl declared to support ERC-165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165Upgradeable is Initializable, IERC165 {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

// 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 IRamsesV3PoolState {
    /// @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
        );


    /// @notice get the period seconds in range of a specific position
    /// @param period the period number
    /// @param owner owner address
    /// @param index position index
    /// @param tickLower lower bound of range
    /// @param tickUpper upper bound of range
    /// @return periodSecondsInsideX96 seconds the position was not in range for the period
    function positionPeriodSecondsInRange(
        uint256 period,
        address owner,
        uint256 index,
        int24 tickLower,
        int24 tickUpper
    ) external view returns (uint256 periodSecondsInsideX96);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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);
}

File 26 of 27 : 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 27 of 27 : 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";

Settings
{
  "remappings": [
    "@uniswap/v3-core/=lib/v3-core/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "ds-test/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
    "shadow-core/=lib/shadow-core/",
    "solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/",
    "v3-core/=lib/v3-core/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": true,
  "libraries": {}
}

Contract Security Audit

Contract ABI

API
[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccessControlBadConfirmation","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"InvalidTickRange","type":"error"},{"inputs":[],"name":"Invalid_Tick_Range","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[],"name":"NotPositionManager","type":"error"},{"inputs":[],"name":"PositionAlreadyActive","type":"error"},{"inputs":[],"name":"PositionIsNotActive","type":"error"},{"inputs":[],"name":"PositionNotInRange","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"SlippageTooHigh","type":"error"},{"inputs":[],"name":"UnfavorableSwap","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"FeesCollected","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"FundsWithdrawn","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"LiquidityWithdrawn","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"int24","name":"minTick","type":"int24"},{"indexed":false,"internalType":"int24","name":"maxTick","type":"int24"}],"name":"MinAndMaxTickSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"int24","name":"tickLower","type":"int24"},{"indexed":false,"internalType":"int24","name":"tickUpper","type":"int24"},{"indexed":false,"internalType":"uint128","name":"liquidity","type":"uint128"}],"name":"PositionCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newTokenId","type":"uint256"},{"indexed":false,"internalType":"int24","name":"newTickLower","type":"int24"},{"indexed":false,"internalType":"int24","name":"newTickUpper","type":"int24"}],"name":"PositionRebalanced","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newSlippage","type":"uint256"}],"name":"SlippageUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"tokenIn","type":"address"},{"indexed":false,"internalType":"address","name":"tokenOut","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountIn","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountOut","type":"uint256"}],"name":"TokensSwapped","type":"event"},{"inputs":[],"name":"ADMIN_ADDRESS","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"EXECUTOR_ADDRESS","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"EXECUTOR_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"FEE_DISTRIBUTOR_ADDRESS","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"NFP_MANAGER_ADDRESS","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"RAMSES_V3_FACTORY","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ROUTER_ADDRESS","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VOTER_ADDRESS","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VOTE_MODULE_ADDRESS","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"X33_ADAPTER_ADDRESS","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"XSHADOW_ADDRESS","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"}],"name":"calculateMinAmountOut","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"calculateOptimalSwapForSlippageStaticCall","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bool","name":"","type":"bool"},{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"claimPastRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimingIncentivesFromVoter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"currentNftIds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currentPosition","outputs":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"bool","name":"isActive","type":"bool"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeDistributor","outputs":[{"internalType":"contract IFeeDistributor","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"gaugeV3","outputs":[{"internalType":"contract IGaugeV3","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCurrentNftIds","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPastNftIds","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getRewardsFromVoteModule","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token0","type":"address"},{"internalType":"address","name":"_token1","type":"address"},{"internalType":"int24","name":"_tickSpacing","type":"int24"},{"internalType":"int24","name":"_minTick","type":"int24"},{"internalType":"int24","name":"_maxTick","type":"int24"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isPositionOutOfRange","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxTick","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxTickMovement","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minTick","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"mintSlippage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"pastNftIds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pool","outputs":[{"internalType":"contract IRamsesV3PoolActions","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"positionManager","outputs":[{"internalType":"contract INonfungiblePositionManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOutMinimum","type":"uint256"}],"name":"rebalancePosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"callerConfirmation","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"router","outputs":[{"internalType":"contract ISwapRouter","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int24","name":"_maxTickMovement","type":"int24"}],"name":"setMaxTickMovement","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"int24","name":"_minTick","type":"int24"},{"internalType":"int24","name":"_maxTick","type":"int24"}],"name":"setMinAndMaxTick","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newSlippage","type":"uint256"}],"name":"setMintSlippage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newSlippage","type":"uint256"}],"name":"setSwapSlippage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"shadowV3Factory","outputs":[{"internalType":"contract IRamsesV3Factory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"swapSlippage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"swapXshadowTox33Tokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"tickSpacing","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"token0","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"token1","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"updateCurrentNftIds","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"voteModule","outputs":[{"internalType":"contract IVoteModule","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"voter","outputs":[{"internalType":"contract IVoter","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"withdrawAllLiquidityAndCollectFees","outputs":[{"internalType":"uint256","name":"collectedAmount0","type":"uint256"},{"internalType":"uint256","name":"collectedAmount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"withdrawFunds","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint128","name":"liquidity","type":"uint128"}],"name":"withdrawLiquidityAndCollectFees","outputs":[{"internalType":"uint256","name":"collectedAmount0","type":"uint256"},{"internalType":"uint256","name":"collectedAmount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"otherTokenRewards","type":"address[]"}],"name":"withdrawTokenRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"x33SharesAccumulated","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]

60808060405234620000bd577ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a009081549060ff8260401c16620000ae57506001600160401b036002600160401b03198282160162000068575b604051614a399081620000c28239f35b6001600160401b031990911681179091556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d290602090a15f808062000058565b63f92ee8a960e01b8152600490fd5b5f80fdfe6080604081815260049081361015610015575f80fd5b5f925f3560e01c90816301ffc9a714611c075750806307bd026514611be0578063085cc0ae14611bb85780630bf150f114611b955780630d43e8ad14611b675780630dfe168114611b40578063150b7a0214611ab157806316f0115b14611a8957806318bd7438146119d45780631aedeabe146119b65780631db3b6dd146119965780631de303dd146114bc5780631e160027146113635780631e213c8c146112fc57806324600fc3146110ae578063248a9ca314611077578063251b8b3d146110485780632e8e6f8d146110085780632f2ff15d14610fe057806336568abe14610f995780633866023214610cb457806346c96aac1461077e5780634c01677b14610f605780635fd7df2314610dc05780636898d48214610d9a57806372fcfbf814610d77578063791b98bc14610a805780637d00086b14610d235780637d09b43b14610d525780637de69b7614610d2357806382e7170014610d0457806384fd7b6514610ce357806385caf28b14610cb457806388faf2b714610c2c578381638d97171314610b715750806391d1485414610b21578063a217fddf14610b06578063b05100aa14610aaf578063b14a96a814610a80578063b547f4a614610851578063b63b57ce14610815578063b94a6dfe14610316578063bbfcd729146107e6578063bcdcd740146107ad578063cde48ea11461077e578063d0c93a7c1461075b57838163d1ec6727146106d857508063d21220a7146106af578063d534d63614610659578063d547741f1461060f578063d74b743f14610561578063e4b9b71714610542578063ea6011cb14610513578063ebe639b0146104c3578063f3c5a730146103a7578063f4fcb7c514610378578063f57ad98914610349578063f887ea40146103165763fa88dd15146102ae575f80fd5b34610312576020366003190112610312578135916102ca612a42565b606383116103045750816020917ff5a802650e0a86db227cc342f06327d2ca0ff5cf2b12e0084fc5d8a7db2c54fd9360015551908152a180f35b905163428637bb60e11b8152fd5b8280fd5b83823461034557816003193601126103455760209051735543c6176feb9b4b179078205d7c29eea2e2d6958152f35b5080fd5b83823461034557816003193601126103455760209051733402ebe2ad564ff3ca90513ff1a1935364179f6c8152f35b83823461034557816003193601126103455760209051739710e10a8f6fba8c391606fee18614885684548d8152f35b5090346103125782600319360112610312576103c1612a42565b600854825163133f757160e31b8152918201819052906101409081816024817312e66c8f215ddd5d48d150c8f46ad0c6fb0f44065afa9182156104b957859261041c575b846104108585612e25565b82519182526020820152f35b90809250813d83116104b2575b6104338183611d63565b810103126104ae5761041092935061044a81611dc6565b5061045760208201611dc6565b50610463848201611de7565b5061047060608201611de7565b5061047d60808201611de7565b506104a561012061049060a08401612a2e565b9261049e6101008201612a2e565b5001612a2e565b5083925f610405565b8380fd5b503d610429565b84513d87823e3d90fd5b5090346103125760203660031901126103125735600a548110156103125760209250600a5f527fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a801549051908152f35b838234610345578160031936011261034557602090517338569e5f28921537499da81ed14d32b5b4ce95ae8152f35b8382346103455781600319360112610345576020906003549051908152f35b5090346103125760209060206003193601126104ae578035906001600160401b03821161060b573660238301121561060b578101356105ab6105a282611d84565b94519485611d63565b8084526024602085019160051b8301019136831161060757602401905b8282106105e457856105e1866105dc612a95565b61284c565b80f35b81356001600160a01b03811681036106035781529083019083016105c8565b5f80fd5b8580fd5b8480fd5b503461031257806003193601126103125761065591356106506001610632611c6f565b938387525f805160206149a483398151915260205286200154612aeb565b613b35565b5080f35b83823461034557816003193601126103455760a09060075460ff600854918351938160020b85528160181c60020b60208601526001600160801b038260301c169085015260b01c16151560608301526080820152f35b83823461034557816003193601126103455760055490516001600160a01b039091168152602090f35b808484346107575782600319360112610757576106f3612a42565b73dcb5a24ec708cc13cee12bfe6799a78a79b666b491823b15610752578151631e8c5c8960e11b81529284918491829084905af190811561074957506107365750f35b61073f90611d06565b6107465780f35b80fd5b513d84823e3d90fd5b505050fd5b5050fd5b8382346103455781600319360112610345576020915460301c60020b9051908152f35b83823461034557816003193601126103455760209051739f59398d0a397b2eeb8a6123a6c7295cb0b0062d8152f35b509034610312576020366003190112610312573591600b5483101561074657506107d8602092611cd0565b91905490519160031b1c8152f35b8382346103455781600319360112610345576020905173392da14e4b78a634859b5655af7878d431fb350d8152f35b509190346103455760203660031901126103455735906001600160801b0382168203610746575061041090610848612a42565b60085490612e25565b50919034610345576003199282843601126103125761086e612a42565b805161087981611d2d565b826001956001835260208036818601378673392da14e4b78a634859b5655af7878d431fb350d806108a98761282b565b52865163c4f59f9b60e01b815294859182905afa928315610a76578793610a52575b508451926108d884611d2d565b6001845281885b818110610a425750508881519161090d6108f884611d84565b936109058a519586611d63565b808552611d84565b601f199390840136868301376109228761282b565b5261092c8661282b565b5089825b610a03575b505050739f59398d0a397b2eeb8a6123a6c7295cb0b0062d94853b156109ff5761098490879a95969a94939294519863183f9c7d60e11b8a5230908a0152606060248a015260648901906127ef565b9187830301604488015284519182815281810182808560051b8401019701948a925b8584106109ce575050508880898982828f8183818f03925af190811561074957506107365750f35b9091929394959685806109eb839f9b868682030188528b516127ef565b9a9e990197969591909101930191906109a6565b8880fd5b8151811015610a3d5782906001600160a01b03610a208285612838565b5116610a3582610a2f8b61282b565b51612838565b520182610930565b610935565b60608282880101520182906108df565b610a6f9193503d8089833e610a678183611d63565b81019061276e565b915f6108cb565b85513d89823e3d90fd5b838234610345578160031936011261034557602090517312e66c8f215ddd5d48d150c8f46ad0c6fb0f44068152f35b503461031257602036600319011261031257813591610acc612a42565b606383116103045750816020917ff5a802650e0a86db227cc342f06327d2ca0ff5cf2b12e0084fc5d8a7db2c54fd9360025551908152a180f35b83823461034557816003193601126103455751908152602090f35b50903461031257816003193601126103125781602093610b3f611c6f565b923581525f805160206149a48339815191528552209060018060a01b03165f52825260ff815f20541690519015158152f35b8084843461075757602036600319011261075757610b8d612a95565b600654815163c4f59f9b60e01b81526001600160a01b03909116929084818381875afa908115610c22578591610c08575b50833b1561060b57610bf593859283855180978195829463f5f8d36560e01b845280359084015288602484015260448301906127ef565b03925af190811561074957506107365750f35b610c1c91503d8087833e610a678183611d63565b86610bbe565b83513d87823e3d90fd5b5082346107465780600319360112610746578151918291600a54808552602080950194600a83527fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a892905b828210610c9d57610c998686610c8f828b0383611d63565b5191829182611c95565b0390f35b835487529586019560019384019390910190610c77565b8382346103455781600319360112610345576020905173dcb5a24ec708cc13cee12bfe6799a78a79b666b48152f35b8334610746578060031936011261074657610cfc612a42565b6105e161266e565b8382346103455781600319360112610345576020906002549051908152f35b8382346103455781600319360112610345576020905173cd2d0637c94fe77c2896bbcbb174ceffb08de6d78152f35b505034610345576020366003190112610345576105e190610d71612a42565b35612052565b8382346103455781600319360112610345576020915460181c60020b9051908152f35b838234610345578160031936011261034557602090610db7611fac565b90519015158152f35b509034610312578260031936011261031257610dda612a42565b600b54835b818110610eba57505081519060209260208301926001600160401b039181851083861117610ea7579084879252528411610e9457600160401b8411610e945750600b5483600b55808410610e67575b50600b8352825b838110610e4857836105e1600854611f76565b81515f8051602061498483398151915282015590820190600101610e35565b835f8051602061498483398151915291820191015b818110610e895750610e2e565b5f8155600101610e7c565b634e487b7160e01b845260419052602483fd5b604184634e487b7160e01b5f525260245ffd5b610ec381611cd0565b90549060039160085491831b1c14610f5757610ede82611cd0565b9054911b1c600a805490600160401b821015610f445760018201808255821015610f31575f527fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a801556001905b01610ddf565b603286634e487b7160e01b5f525260245ffd5b604186634e487b7160e01b5f525260245ffd5b50600190610f2b565b83823461034557606036600319011261034557602090610f92610f81611c59565b610f89611c6f565b60443591611eb3565b9051908152f35b50829034610345578060031936011261034557610fb4611c6f565b90336001600160a01b03831603610fd15750610655919235613b35565b5163334bd91960e11b81528390fd5b503461031257806003193601126103125761065591356110036001610632611c6f565b612d9f565b833461074657602036600319011261074657611022611c85565b61102a612a42565b5f549060481b62ffffff60481b169062ffffff60481b1916175f5580f35b83823461034557816003193601126103455760209051735050bc082ff4a74fb6b0b04385defddb114b24248152f35b50903461031257602036600319011261031257816020936001923581525f805160206149a483398151915285522001549051908152f35b50346103125782600319360112610312576110c7612a95565b60ff60075460b01c16611216575b815481516370a0823160e01b80825230828601526001600160a01b0392831694919290916020919082856024818a5afa94851561120c5788956111dd575b508290602483600554169588519687938492835230908301525afa928315610a7657879361118e575b508261117a9161116f867fd66662c0ded9e58fd31d5e44944bcfd07ffc15e6927ecc1382e7941cb7bd24c4993390613af5565b339060055416613af5565b856007555f6008558351928352820152a180f35b9092508181813d83116111d6575b6111a68183611d63565b810103126106035751917fd66662c0ded9e58fd31d5e44944bcfd07ffc15e6927ecc1382e7941cb7bd24c461113c565b503d61119c565b9094508281813d8311611205575b6111f58183611d63565b8101031261060357519382611113565b503d6111eb565b86513d8a823e3d90fd5b61121e612a42565b600854815163133f757160e31b81528381018290529061014080836024817312e66c8f215ddd5d48d150c8f46ad0c6fb0f44065afa9081156112f2578691611273575b5061126c9250612e25565b50506110d5565b905082813d83116112eb575b6112898183611d63565b8101031261060b578161129e61126c93611dc6565b506112ab60208201611dc6565b506112b7848201611de7565b506112c460608201611de7565b506112d160808201611de7565b506112e461012061049060a08401612a2e565b505f611261565b503d61127f565b84513d88823e3d90fd5b5082346107465780600319360112610746578151918291600b54808552602080950194600b83525f8051602061498483398151915292905b82821061134c57610c998686610c8f828b0383611d63565b835487529586019560019384019390910190611334565b5091903461034557816003193601126103455761137e612a42565b60075460ff8160b01c1661149e575b50611396613135565b909360018060a01b0393846009541685855416938351916370a0823160e01b808452308885015260209889856024818b5afa948515611494578695611465575b5060055416978651918252309082015288816024818b5afa94851561145a5794611426575b509060809861140b949392613218565b50905082959195519586521515908501528301526060820152f35b935091908784813d8311611453575b61143f8183611d63565b8101031261060357925192909160806113fb565b503d611435565b8651903d90823e3d90fd5b9094508981813d831161148d575b61147d8183611d63565b810103126106035751935f6113d6565b503d611473565b87513d88823e3d90fd5b6008546114b69160301c6001600160801b0316612e25565b5061138d565b5090346106035760a0366003190112610603576114d7611c59565b906114e0611c6f565b9060443560020b806044350361060357606435938460020b850361060357608435938460020b8503610603577ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a009586549560ff878a1c1615966001600160401b0381168015908161198e575b6001149081611984575b15908161197b575b5061196b5767ffffffffffffffff19811660011789558761194c575b5060ff88548a1c161561193c575f5460038602808060020b03611929579065ffffff00000062ffffff9260481b62ffffff60481b169460181b16906bffffffffffffffffffffffff19161791161768ffffff00000000000060443560301b1617175f5560018060a01b03906bffffffffffffffffffffffff60a01b92828116848754161786558282168460055416176005558851634a16fd0d60e11b81526020818061164c60443587878d8501919392604091606084019560018060a01b03809216855216602084015260020b910152565b0381739f59398d0a397b2eeb8a6123a6c7295cb0b0062d5afa90811561191f579084915f916118d8575b50600680549190921690861617905588516328af8d0b60e01b81526001600160a01b039182168782019081529290911660208084019190915260443560020b60408401529091829081906060015b038173cd2d0637c94fe77c2896bbcbb174ceffb08de6d75afa9081156118ce575f91611894575b5016906009541617600955600181145f146118705750600180555b60016002557312e66c8f215ddd5d48d150c8f46ad0c6fb0f4406803b15610603575f8091604487518094819363a22cb46560e01b83523388840152600160248401525af1801561186657611853575b5061175e612b19565b50611767612bc6565b50611770612c76565b5061177a33612d1f565b50739710e10a8f6fba8c391606fee18614885684548d84519163095ea7b360e01b83528201525f19602482015260208160448188735050bc082ff4a74fb6b0b04385defddb114b24245af180156104b95761181a575b506117d9578280f35b805468ff00000000000000001916905551600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d290602090a15f808280f35b6020813d60201161184b575b8161183360209383611d63565b8101031261060b5761184490611dda565b505f6117d0565b3d9150611826565b61185e919550611d06565b5f935f611755565b85513d5f823e3d90fd5b603281036118835750600a600155611706565b606403611706576014600155611706565b90506020813d6020116118c6575b816118af60209383611d63565b81010312610603576118c090611dc6565b5f6116eb565b3d91506118a2565b88513d5f823e3d90fd5b929150506020823d602011611917575b816118f560209383611d63565b81010312610603576116c4928461190d602094611dc6565b9194509192611676565b3d91506118e8565b8a513d5f823e3d90fd5b601188634e487b7160e01b5f525260245ffd5b8851631afcd79f60e31b81528690fd5b68ffffffffffffffffff1916680100000000000000011788555f61157a565b895163f92ee8a960e01b81528790fd5b9050155f61155e565b303b159150611556565b89915061154c565b5034610603575f366003190112610603576020905f5460020b9051908152f35b5034610603575f366003190112610603576020906001549051908152f35b50346106035780600319360112610603576119ed611c85565b602435908160020b9081830361060357611a05612a42565b8060020b92620d89ef1984128015611a7d575b611a6e577fd9388bd35364a0b59809b9dbe4393358ad02ba3f1a157294eae8a2aa9775da9a955065ffffff0000005f549162ffffff169260181b169065ffffffffffff191617175f5582519182526020820152a1005b84516264847d60e41b81528690fd5b50620d89f08313611a18565b5034610603575f3660031901126106035760095490516001600160a01b039091168152602090f35b503461060357608036600319011261060357611acb611c59565b50611ad4611c6f565b506064356001600160401b03808211610603573660238301121561060357818401359081116106035736910160240111610603577312e66c8f215ddd5d48d150c8f46ad0c6fb0f44063303611b335751630a85bd0160e11b8152602090f35b5163041fb8cb60e31b8152fd5b5034610603575f36600319011261060357905490516001600160a01b039091168152602090f35b5034610603575f366003190112610603576020905173392da14e4b78a634859b5655af7878d431fb350d8152f35b5034610603575f366003190112610603576020905f5460481c60020b9051908152f35b5034610603575f3660031901126106035760065490516001600160a01b039091168152602090f35b5034610603575f36600319011261060357602090515f805160206149c48339815191528152f35b833461060357602036600319011261060357359063ffffffff60e01b821680920361060357602091637965db0b60e01b8114908115611c48575b5015158152f35b6301ffc9a760e01b14905083611c41565b600435906001600160a01b038216820361060357565b602435906001600160a01b038216820361060357565b600435908160020b820361060357565b60209060206040818301928281528551809452019301915f5b828110611cbc575050505090565b835185529381019392810192600101611cae565b600b54811015611cf257600b5f525f8051602061498483398151915201905f90565b634e487b7160e01b5f52603260045260245ffd5b6001600160401b038111611d1957604052565b634e487b7160e01b5f52604160045260245ffd5b604081019081106001600160401b03821117611d1957604052565b608081019081106001600160401b03821117611d1957604052565b90601f801991011681019081106001600160401b03821117611d1957604052565b6001600160401b038111611d195760051b60200190565b9060020b9060020b02908160020b918203611db257565b634e487b7160e01b5f52601160045260245ffd5b51906001600160a01b038216820361060357565b5190811515820361060357565b51908160020b820361060357565b519061ffff8216820361060357565b908160e09103126106035780516001600160a01b03811681036106035791611e2e60208301611de7565b91611e3b60408201611df5565b91611e4860608301611df5565b91611e5560808201611df5565b9160a082015160ff811681036106035760c0611e72919301611dda565b90565b91908203918211611db257565b81810292918115918404141715611db257565b8115611e9f570490565b634e487b7160e01b5f52601260045260245ffd5b600954604051633850c7bd60e01b81526001600160a01b039160e0908290600490829086165afa8015611f6b5782611ef69181935f91611f36575b501680613bb4565b931691161015611f2857611f0991613bb4565b6001546064039060648211611db257606491611f2491611e82565b0490565b611f3191613bf8565b611f09565b611f58915060e03d60e011611f64575b611f508183611d63565b810190611e04565b5050505050505f611eee565b503d611f46565b6040513d5f823e3d90fd5b600b54600160401b811015611d1957806001611f959201600b55611cd0565b819291549060031b91821b915f19901b1916179055565b60075460ff8160b01c161561204c57600954604051633850c7bd60e01b81529060e090829060049082906001600160a01b03165afa908115611f6b575f91612026575b50611ff981613c7f565b156120205760020b8160020b811291821561201357505090565b60181c60020b1315919050565b50505f90565b61203f915060e03d60e011611f6457611f508183611d63565b505050505090505f611fef565b50600190565b61205a611fac565b1561265e5760075460ff8160b01c16612640575b50612077613135565b9160018060a01b0360045416604051916370a0823160e01b92838152306004820152602081602481865afa908115611f6b575f9161260e575b5060018060a01b036005541660405193858552306004860152602085602481855afa948515611f6b575f956125da575b506120f885848a8a60018060a01b0360095416613218565b509050819691612575575b5050505050505060018060a01b03600454169060405191818352306004840152602083602481845afa928315611f6b575f93612541575b50600554604051928352306004840152602090839060249082906001600160a01b03165afa918215611f6b575f9261250d575b5060ff60075460b01c166124fb57826121859161453c565b60055461219c9082906001600160a01b031661453c565b60018060a01b03600454169160018060a01b0360055416915f54916002546064039260648411611db25760646121de816121d68786611e82565b049585611e82565b049461012c42014211611db25760405196876101608101106001600160401b036101608a011117611d1957610160880160409081529088526020880191825260309290921c600290810b83890190815289820b60608a019081528b830b6080808c0191825260a08c0197885260c08c0198895260e08c01998a526101008c019a8b52306101208d019081524261012c016101408e019081529751636d70c41560e01b81529c516001600160a01b0390811660048f01529651871660248e01529351850b60448d01529151840b60648c01525190920b60848a0152935160a4890152935160c4880152935160e4870152935161010486015251909116610124840152905161014483015281610164815f7312e66c8f215ddd5d48d150c8f46ad0c6fb0f44065af18015611f6b575f915f9161248c575b50816001600160801b036080927f9314bc80d147aa8ca0b2957b6e387a64a6db9e2a210d2c1b9c8d77b11c4c4c7294600855600754600160b01b908860181b65ffffff000000169068ffffffffffffffffff60b81b1675ffffffffffffffffffffffffffffffff0000000000008460301b161762ffffff891617171760075561239b83611f76565b6040519283528560020b60208401528660020b6040840152166060820152a17fddeb651c3c5acecf292901bcf399e51d7a06a012e320facbc4bfab7c1055527060606008546040519081528360020b60208201528460020b6040820152a1600954604051633850c7bd60e01b81529060e090829060049082906001600160a01b03165afa908115611f6b575f91612466575b5060020b9060020b8112918215612459575b505061244757565b604051630a49cb5560e01b8152600490fd5b60020b1290505f8061243f565b61247f915060e03d60e011611f6457611f508183611d63565b505050505090505f61242d565b9150506080813d6080116124f3575b816124a860809383611d63565b81010312610603576080816001600160801b036124ea60207f9314bc80d147aa8ca0b2957b6e387a64a6db9e2a210d2c1b9c8d77b11c4c4c7295519301612a2e565b92505091612313565b3d915061249b565b6040516351becb2360e11b8152600490fd5b9091506020813d602011612539575b8161252960209383611d63565b810103126106035751905f61216d565b3d915061251c565b9092506020813d60201161256d575b8161255d60209383611d63565b810103126106035751915f61213a565b3d9150612550565b156125c05750505082116125ae576004546005546125a093916001600160a01b0391821691166141fc565b505b5f808080808080612103565b60405163133153a160e21b8152600490fd5b909194809350116125ae576125d4936141fc565b506125a2565b9094506020813d602011612606575b816125f660209383611d63565b810103126106035751935f6120e0565b3d91506125e9565b90506020813d602011612638575b8161262960209383611d63565b8101031261060357515f6120b0565b3d915061261c565b6008546126589160301c6001600160801b0316612e25565b5061206e565b50565b91908201809211611db257565b6040516370a0823160e01b815230600482015260208082602481735050bc082ff4a74fb6b0b04385defddb114b24245afa918215611f6b575f9261273f575b50811561273b5760405191636e553f6560e01b8352600483015230602483015280826044815f739710e10a8f6fba8c391606fee18614885684548d5af1908115611f6b575f9161270b575b506127069150600354612661565b600355565b905081813d8311612734575b6127218183611d63565b810103126106035761270690515f6126f8565b503d612717565b5050565b9080925081813d8311612767575b6127578183611d63565b810103126106035751905f6126ad565b503d61274d565b6020908181840312610603578051906001600160401b03821161060357019180601f840112156106035782516127a381611d84565b936127b16040519586611d63565b818552838086019260051b820101928311610603578301905b8282106127d8575050505090565b8380916127e484611dc6565b8152019101906127ca565b9081518082526020808093019301915f5b82811061280e575050505090565b83516001600160a01b031685529381019392810192600101612800565b805115611cf25760200190565b8051821015611cf25760209160051b010190565b6006546040805163c4f59f9b60e01b81526004926001600160a01b0391905f9082908690829086165afa908115612a24575f91612a0a575b5080515f5b81811061294b575050508351928315612944575f5b8481106128ad57505050505050565b826128b88288612838565b511690845180926370a0823160e01b8252308583015281602460209586935afa92831561293a575f93612907575b505061290160019233866128fa858c612838565b5116613af5565b0161289e565b90809350813d8311612933575b61291e8183611d63565b810103126106035761290160019251926128e6565b503d612914565b86513d5f823e3d90fd5b5050505050565b735050bc082ff4a74fb6b0b04385defddb114b24248461296b8386612838565b511614612a02578361297d8285612838565b511690855180926370a0823160e01b8252308983015281602460209586935afa9283156129f8575f936129c5575b50506129bf60019233876128fa8589612838565b01612889565b90809350813d83116129f1575b6129dc8183611d63565b81010312610603576129bf60019251926129ab565b503d6129d2565b87513d5f823e3d90fd5b6001906129bf565b612a1e91503d805f833e610a678183611d63565b5f612884565b83513d5f823e3d90fd5b51906001600160801b038216820361060357565b335f9081525f805160206149e483398151915260205260409020545f805160206149c48339815191529060ff1615612a775750565b6044906040519063e2517d3f60e01b82523360048301526024820152fd5b335f9081527fb7db2dd08fcb62d0c9e08c51941cae53c267786a0b75803fb7960902fc8ef97d602052604090205460ff1615612acd57565b60405163e2517d3f60e01b81523360048201525f6024820152604490fd5b805f525f805160206149a483398151915260205260405f20335f5260205260ff60405f20541615612a775750565b733402ebe2ad564ff3ca90513ff1a1935364179f6c5f8190527fb7db2dd08fcb62d0c9e08c51941cae53c267786a0b75803fb7960902fc8ef97d6020527fb311a8ef0b3c454754fc971be32932edce85d5c5f321d67b91e9027ab92faa79545f805160206149a48339815191529060ff16612020575f805260205260405f20815f5260205260405f20600160ff1982541617905533905f5f805160206149648339815191528180a4600190565b733402ebe2ad564ff3ca90513ff1a1935364179f6c5f8190525f805160206149e48339815191526020527f80e59f01c2d6a4515c62d34327860193ccb6e58244c720ab454bcdad18bf80b7545f805160206149c483398151915291905f805160206149a48339815191529060ff16612c6f57825f5260205260405f20815f5260205260405f20600160ff1982541617905533915f805160206149648339815191525f80a4600190565b5050505f90565b7338569e5f28921537499da81ed14d32b5b4ce95ae5f8190525f805160206149e48339815191526020527f163941dd190106e3d0258e77adfd8dfe425560a3c07faf20a19fd18ce9fb0b78545f805160206149c483398151915291905f805160206149a48339815191529060ff16612c6f57825f5260205260405f20815f5260205260405f20600160ff1982541617905533915f805160206149648339815191525f80a4600190565b6001600160a01b03165f8181525f805160206149e483398151915260205260409020545f805160206149c483398151915291905f805160206149a48339815191529060ff16612c6f57825f5260205260405f20815f5260205260405f20600160ff1982541617905533915f805160206149648339815191525f80a4600190565b90815f525f805160206149a48339815191528060205260405f209160018060a01b031691825f5260205260ff60405f205416155f14612c6f57825f5260205260405f20815f5260205260405f20600160ff1982541617905533915f805160206149648339815191525f80a4600190565b9190826040910312610603576020825192015190565b9160ff60075460b01c16156130e4575f915f906001600160801b0380951680612faf575b506040805195608087018781106001600160401b03821117611d19578252828752306020880190815287830182815260608901838152845163fc6f786560e01b8152995160048b015291516001600160a01b031660248a015251821660448901525116606487015280866084815f7312e66c8f215ddd5d48d150c8f46ad0c6fb0f44065af1928315612fa5575f965f94612f44575b50839291612f23612f3f92612f1d7fa54e6c2fc0861aa9c991b26891d71059d517983b9e84b91020f42609c452eb9d97998b5f6007555f600855611e75565b95611e75565b9051938493846040919493926060820195825260208201520152565b0390a1565b612f2397507fa54e6c2fc0861aa9c991b26891d71059d517983b9e84b91020f42609c452eb9d945091612f91612f3f929493823d8411612f9e575b612f898183611d63565b810190612e0f565b9098509450919290612ede565b503d612f7f565b50513d5f823e3d90fd5b9150925061012c420192834211611db25760409384519260a084018481106001600160401b03821117611d19578652828452602084019081528584015f81528760608601925f845260808701948552885196630624e65f60e11b885251600488015251166024860152516044850152516064840152516084830152838260a4815f7312e66c8f215ddd5d48d150c8f46ad0c6fb0f44065af180156130da575f925f91613099575b50935181815260208101839052604081018590529193917fbcdb14b9d37e7c5c183adc833dd59bf42815b5135e0cc94641f8929f943661c590606090a15f612e49565b7fbcdb14b9d37e7c5c183adc833dd59bf42815b5135e0cc94641f8929f943661c593506130d39150853d8711612f9e57612f898183611d63565b9092613056565b84513d5f823e3d90fd5b60405163ebb0360f60e01b8152600490fd5b60020b9060020b908115611e9f57627fffff1981145f19831416611db2570590565b600291820b910b0390627fffff198212627fffff831317611db257565b600954604051633850c7bd60e01b81529060e090829060049082906001600160a01b03165afa908115611f6b575f916131f2575b505f8160020b125f146131d6575f5460301c60020b5f19810191627fffff8313627fffff19841217611db257816131a66131b0946131ab93613118565b6130f6565b611d9b565b905b5f5460301c60020b8260020b0191627fffff198312627fffff841317611db2579190565b6131ec906131ab5f5460301c60020b80926130f6565b906131b2565b61320b915060e03d60e011611f6457611f508183611d63565b505050505090505f613169565b9493929190915f95811580613aed575b613adc578260020b8460020b9080821291821592613ace575b508115613ac1575b50613aaf57803b15613aa2576040519461012086018681106001600160401b03821117611d19576040525f86525f60208701525f60408701525f60608701525f60808701525f60a08701525f60c08701525f60e08701525f610100870152633850c7bd60e01b5f5260405f600481855afa15610603575f51956020519587966040830152630d34328160e11b5f5260205f600481875afa15610603575f519063ddca3f4360e01b5f5260205f600481885afa156106035762ffffff5f5116906334324e9f60e21b5f5260205f600481895afa15610603576133559261334f925f519186528b602087015288606087015286608087015260e0860152610100850152613cf9565b95613cf9565b60a0820186905260c08201819052926133806001600160a01b0380861690808916908b16868961401d565b9750617fff19905f905b604084015160020b8a61010086015160020b93815f146139d1575f858407128584050360081d95600187810b91900b036139b6575b8092600260ff5f1992885f81830712910503161b01165b8015613996577f07060605060205040602030205040301060502050303040105050304000000006f8421084210842108cc6318c6db6d54be826001600160801b031060071b83811c6001600160401b031060061b1783811c63ffffffff1060051b1783811c61ffff1060041b1783811c60ff1060031b1792831c1c601f161a17915b94809461346b81858460081b0102613cf9565b938361394b576020890151895160808b015160e08c01516134a29390926001600160801b03169089906001600160a01b031661466e565b94919590959460608c0151019560808c015103965b6001600160a01b039081169086160361393c5760a08b015160c08c0151911515916134ed916001600160a01b0388168a8a61401d565b1515146138e4575050505050505050505b8051926020820151926060830151966080840151928a155f1461370c57506001600160a01b038181169086161061365f575b6001600160a01b039081169085161015613559575b50505090613553918561412e565b91030192565b919650929198508551928660208101519460c08201519560e0830151620f424092818403908060601b8481046060880151019061359a60a08901518361488d565b9b6135b06135aa86898b02611e95565b8561488d565b956135c760a060808c01519889019b01518661488d565b8a0396871115613652576135539d86613607966135e7856136459e614850565b930204900303940290870204900360011b9260011b8302828002016148d7565b0160601b0581811190821802189860018d8b038060ff1d908101189260e061362f858a61488d565b9301519003928160601b908809151516016147ca565b9103019790915f80613545565b63202368085f526004601cfd5b9a975061367f61367860e0850151620f42400384614760565b868661415d565b976001600160a01b038c8116908a16101561369c5750809a613530565b9a939185856136e7926136df82879c969c038060ff1d908101186136c0818661488d565b60e08a0151620f42400391600190600160601b908809151516016147ca565b90039461412e565b6001600160a01b03851660208501520160608301819052608083018290529583613530565b929791969290506001600160a01b038082169086161161384a575b6001600160a01b039081169085161115613754575b505050906135539185038060ff1d908101189061488d565b91965091929850855195602081015160c082015160e0830151620f424099818b03908b606087015191828160601b9287840490848a880291020482010311156136525785948e8589938b8260a0820151878202898702048a01906137b79161488d565b946137c2888561488d565b6080840151019260a0015102906137d891611e95565b6137e2908361488d565b81039a6137ee91614850565b93020401039482049302908d0204010360011b9160011b820281800201613814906148d7565b0160601b0481811090821802189661382d8b868a6140ed565b9160e00151900361383d916147ca565b91030196905f808061373c565b9a975061386a61386360e0850151620f42400383614760565b8686614068565b976001600160a01b038c8116908a16106138865750819a613727565b9a9396906138bf906138ac61389c888b896140ed565b60e0870151620f424003906147ca565b90039785038060ff1d908101188661488d565b6001600160a01b03851660208501526060840188905201608083018190529583613727565b63f30dba9360e01b5f5282828260081b010260020b60045260405f6024818a5afa15610603578f93602051855f031885018b51018b5260208b015260081b01020360408701526060860152608085015291909161338a565b505050505050505050506134fe565b6020890151895160608b015160e08c015195969561397f9390926001600160801b03169089906001600160a01b031661466e565b9591949060608c0151039560808c015101966134b7565b50505090915f190160010b906139ac82826148b3565b9192918a816133d6565b506139cc5f858407128584050360081d846148b3565b6133bf565b60015f86850712868505030160020b60081d9560010b8660010b145f14613a92575b6001808294875f818307129105030160ff161b5f03165b8015613a7257805f03167e1f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405601f826001600160801b031060071b83811c6001600160401b031060061b1783811c63ffffffff1060051b1792831c63d76453e004161a1791613458565b505050909160010160010b90613a8882826148b3565b9192918a81613a0a565b50613a9d85846148b3565b6139f3565b6301ac05a55f526004601cfd5b6040516330673a1b60e01b8152600490fd5b620d89e89150135f613249565b620d89e7191391505f613241565b505050505090505f905f905f905f90565b508415613228565b60405163a9059cbb60e01b60208201526001600160a01b039092166024830152604480830193909352918152613b3391613b2e82611d48565b6141a2565b565b90815f525f805160206149a48339815191528060205260405f209160018060a01b031691825f5260205260ff60405f2054165f14612c6f57825f5260205260405f20815f5260205260405f2060ff19815416905533917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b5f80a4600190565b5f198282099082810292838084109303928084039314613bef57600160601b9183831115610603570990828211900360a01b910360601c1790565b50505060601c90565b90600160601b905f19828409928060601b92838086109503948086039514613c7157848311156106035782910981805f0316809204600280826003021880830282030280830282030280830282030280830282030280830282030280920290030293600183805f03040190848311900302920304170290565b505080925015610603570490565b5f5460029180830b908260181c840b82128015613cee575b613ce65760075460ff8160b01c1615613cdc57840b8092135f14613ccd5790613cbf91613118565b905b60481c820b910b131590565b613cd691613118565b90613cc1565b5050505050600190565b505050505f90565b5082840b8213613c97565b8060ff1d81810118620d89e881116140065763ffffffff91600160801b7001fffcb933bd6fad37aa2d162d1a5940016001841602189160028116613fea575b60048116613fce575b60088116613fb2575b60108116613f96575b60208116613f7a575b60408116613f5e575b608090818116613f43575b6101008116613f28575b6102008116613f0d575b6104008116613ef2575b6108008116613ed7575b6110008116613ebc575b6120008116613ea1575b6140008116613e86575b6180008116613e6b575b620100008116613e50575b620200008116613e36575b620400008116613e1c575b6208000016613e02575b505f12613dfa575b0160201c90565b5f1904613df3565b6b048a170391f7dc42444e8fa25f929302901c9190613deb565b6d2216e584f5fa1ea926041bedfe98909302811c92613de1565b926e5d6af8dedb81196699c329225ee60402811c92613dd6565b926f09aa508b5b7a84e1c677de54f3e99bc902811c92613dcb565b926f31be135f97d08fd981231505542fcfa602811c92613dc0565b926f70d869a156d2a1b890bb3df62baf32f702811c92613db6565b926fa9f746462d870fdf8a65dc1f90e061e502811c92613dac565b926fd097f3bdfd2022b8845ad8f792aa582502811c92613da2565b926fe7159475a2c29b7443b29c7fa6e889d902811c92613d98565b926ff3392b0822b70005940c7a398e4b70f302811c92613d8e565b926ff987a7253ac413176f2b074cf7815e5402811c92613d84565b926ffcbe86c7900a88aedcffc83b479aa3a402811c92613d7a565b926ffe5dee046a99a2a811c461f1969c305302811c92613d70565b916fff2ea16466c96a3843ec78b326b528610260801c91613d65565b916fff973b41fa98c081472e6896dfb254c00260801c91613d5c565b916fffcb9843d60f6159c9db58835c9266440260801c91613d53565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c91613d4a565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c91613d41565b916ffff97272373d413259a46990580e213a0260801c91613d38565b6308c379a05f52602080526101546041526045601cfd5b9193918385116140305750505050505f90565b828510614041575050505050600190565b614064936140528661405b9361488d565b9086039061488d565b93820390614872565b1090565b9082156140e75760601b9181810282828204146140a0575b5061408c918304612661565b80820491061515016001600160a01b031690565b830191838310156140b15791614080565b90506140be828285614872565b92096140d1575b6001600160a01b031690565b600101806140c5575b63ae47f7025f526004601cfd5b50905090565b918282108284180280808518931893146106035760601b9160019082810361411f6001600160a01b0383168287614872565b94098284061715151691040190565b8181188183100280821893928118911461060357611f24916001600160a01b038216918490039060601b614872565b9190614183918060a01c155f146141935760601b045b6001600160a01b03928316612661565b600160a01b811015610603571690565b9061419d91614850565b614173565b905f602091828151910182855af115611f6b575f513d6141f357506001600160a01b0381163b155b6141d15750565b604051635274afe760e01b81526001600160a01b039091166004820152602490fd5b600114156141ca565b91908115613ce6578315614529575b604051636eb1769f60e11b8152306004820152735543c6176feb9b4b179078205d7c29eea2e2d69560248201526020816044816001600160a01b0388165afa8015611f6b5783905f906144f3575b6142639250612661565b60405160205f81830163095ea7b360e01b94858252735543c6176feb9b4b179078205d7c29eea2e2d69560248601526044850152604484526142a484611d48565b835190826001600160a01b038a165af15f513d826144ce575b50501561446c575b50505f5460301c9361012c42014211611db2576040519461010086018681106001600160401b03821117611d195760405260018060a01b038516865260018060a01b038316602087015260020b604086015230606086015261012c420160808601528260a086015260c08501525f60e0850152604051936350131c1f60e11b855260018060a01b03815116600486015260018060a01b036020820151166024860152604081015160020b604486015260018060a01b0360608201511660648601526080810151608486015260a081015160a486015260c081015160c486015260e060018060a01b039101511660e4850152602084610104815f735543c6176feb9b4b179078205d7c29eea2e2d6955af1938415611f6b575f94614431575b50604080516001600160a01b039485168152939091166020840152820152606081018290527f25f1d03755df23c30e25db2dbd3891e31ce084bdfbfc46f9fe5e446ee5f9b2d490608090a190565b91929093506020823d602011614464575b8161444f60209383611d63565b810103126106035790519290919060806143e3565b3d9150614442565b6144b86144c792604051906020820152735543c6176feb9b4b179078205d7c29eea2e2d69560248201525f6044820152604481526144a981611d48565b6001600160a01b0387166141a2565b6001600160a01b0385166141a2565b5f806142c5565b9091506144eb57506001600160a01b0385163b15155b5f806142bd565b6001146144e4565b50506020813d602011614521575b8161450e60209383611d63565b8101031261060357826142639151614259565b3d9150614501565b9250614536818484611eb3565b9261420b565b604051636eb1769f60e11b81523060048201527312e66c8f215ddd5d48d150c8f46ad0c6fb0f440660248201819052926001600160a01b03831692916020918282604481885afa8015611f6b575f9061463f575b61459a9250612661565b9060405193815f81870163095ea7b360e01b958682528960248a01526044890152604488526145c888611d48565b87519082885af1903d5f519083614620575b505050156145e9575050505050565b61461694613b2e926040519283015260248201525f60448201526044815261461081611d48565b826141a2565b5f80808080612944565b9192509061463557503b15155b5f80806145da565b600191501461462d565b508282813d8311614667575b6146558183611d63565b810103126106035761459a9151614590565b503d61464b565b620f4240948503956001600160a01b0380841690831610159590949193929091906146998883614760565b8715614737576146aa8587846140ed565b925b8382106146ff5750509687926146c282846147ca565b92096146ed575b945b156146e45791611e7292038060ff1d908101189061488d565b611e729261412e565b600191500180156140da5785906146c9565b97985092505050821582151761060357851561472757614720908284614068565b80956146cb565b61473290828461415d565b614720565b8186038060ff1d90810118600161474e828861488d565b918160601b90880915151601926146ac565b81810291620f424091828282860414821517021561477f575050900490565b825f1983830985811086019003928392099211156140da57828211900360fa1b910360061c177fde8f6cefed634549b62c77574f722e1ac57e23f24d8fd5cb790fb65668c261390290565b90620f4240918281029282818386041483151702156147ea575050900490565b82905f1981840985811086019003920990825f03831692818111156140da578390046002816003028118808302820302808302820302808302820302808302820302808302820302809202900302936001848483030494805f0304019211900302170290565b606081901b9190600160601b81158285048214178302156147ea575050900490565b818102929181158285048214178302156147ea575050900490565b808202915f19910981811082019003600160601b8110156140da5760a01b9060601c1790565b60245f809260209463299ce14b60e11b835260010b6004525afa15610603575f5190565b8070ffffffffffffffffffffffffffffffffff1060071b81811c68ffffffffffffffffff1060061b1781811c64ffffffffff1060051b1781811c62ffffff1060041b1760019060b56201000084831c0191831c1b0260121c80830401811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c808092041090039056fe2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db902dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800d8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e6352fce5e8a5d0d9e8d1ea29f4525e512e9c27bf92cae50374d497f918ab48f382a26469706673582212203ea4a576af3a128e2895a9b542e0f8fe52169a59f3bcbd6a97205d44333b58d964736f6c63430008180033

Deployed Bytecode

0x6080604081815260049081361015610015575f80fd5b5f925f3560e01c90816301ffc9a714611c075750806307bd026514611be0578063085cc0ae14611bb85780630bf150f114611b955780630d43e8ad14611b675780630dfe168114611b40578063150b7a0214611ab157806316f0115b14611a8957806318bd7438146119d45780631aedeabe146119b65780631db3b6dd146119965780631de303dd146114bc5780631e160027146113635780631e213c8c146112fc57806324600fc3146110ae578063248a9ca314611077578063251b8b3d146110485780632e8e6f8d146110085780632f2ff15d14610fe057806336568abe14610f995780633866023214610cb457806346c96aac1461077e5780634c01677b14610f605780635fd7df2314610dc05780636898d48214610d9a57806372fcfbf814610d77578063791b98bc14610a805780637d00086b14610d235780637d09b43b14610d525780637de69b7614610d2357806382e7170014610d0457806384fd7b6514610ce357806385caf28b14610cb457806388faf2b714610c2c578381638d97171314610b715750806391d1485414610b21578063a217fddf14610b06578063b05100aa14610aaf578063b14a96a814610a80578063b547f4a614610851578063b63b57ce14610815578063b94a6dfe14610316578063bbfcd729146107e6578063bcdcd740146107ad578063cde48ea11461077e578063d0c93a7c1461075b57838163d1ec6727146106d857508063d21220a7146106af578063d534d63614610659578063d547741f1461060f578063d74b743f14610561578063e4b9b71714610542578063ea6011cb14610513578063ebe639b0146104c3578063f3c5a730146103a7578063f4fcb7c514610378578063f57ad98914610349578063f887ea40146103165763fa88dd15146102ae575f80fd5b34610312576020366003190112610312578135916102ca612a42565b606383116103045750816020917ff5a802650e0a86db227cc342f06327d2ca0ff5cf2b12e0084fc5d8a7db2c54fd9360015551908152a180f35b905163428637bb60e11b8152fd5b8280fd5b83823461034557816003193601126103455760209051735543c6176feb9b4b179078205d7c29eea2e2d6958152f35b5080fd5b83823461034557816003193601126103455760209051733402ebe2ad564ff3ca90513ff1a1935364179f6c8152f35b83823461034557816003193601126103455760209051739710e10a8f6fba8c391606fee18614885684548d8152f35b5090346103125782600319360112610312576103c1612a42565b600854825163133f757160e31b8152918201819052906101409081816024817312e66c8f215ddd5d48d150c8f46ad0c6fb0f44065afa9182156104b957859261041c575b846104108585612e25565b82519182526020820152f35b90809250813d83116104b2575b6104338183611d63565b810103126104ae5761041092935061044a81611dc6565b5061045760208201611dc6565b50610463848201611de7565b5061047060608201611de7565b5061047d60808201611de7565b506104a561012061049060a08401612a2e565b9261049e6101008201612a2e565b5001612a2e565b5083925f610405565b8380fd5b503d610429565b84513d87823e3d90fd5b5090346103125760203660031901126103125735600a548110156103125760209250600a5f527fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a801549051908152f35b838234610345578160031936011261034557602090517338569e5f28921537499da81ed14d32b5b4ce95ae8152f35b8382346103455781600319360112610345576020906003549051908152f35b5090346103125760209060206003193601126104ae578035906001600160401b03821161060b573660238301121561060b578101356105ab6105a282611d84565b94519485611d63565b8084526024602085019160051b8301019136831161060757602401905b8282106105e457856105e1866105dc612a95565b61284c565b80f35b81356001600160a01b03811681036106035781529083019083016105c8565b5f80fd5b8580fd5b8480fd5b503461031257806003193601126103125761065591356106506001610632611c6f565b938387525f805160206149a483398151915260205286200154612aeb565b613b35565b5080f35b83823461034557816003193601126103455760a09060075460ff600854918351938160020b85528160181c60020b60208601526001600160801b038260301c169085015260b01c16151560608301526080820152f35b83823461034557816003193601126103455760055490516001600160a01b039091168152602090f35b808484346107575782600319360112610757576106f3612a42565b73dcb5a24ec708cc13cee12bfe6799a78a79b666b491823b15610752578151631e8c5c8960e11b81529284918491829084905af190811561074957506107365750f35b61073f90611d06565b6107465780f35b80fd5b513d84823e3d90fd5b505050fd5b5050fd5b8382346103455781600319360112610345576020915460301c60020b9051908152f35b83823461034557816003193601126103455760209051739f59398d0a397b2eeb8a6123a6c7295cb0b0062d8152f35b509034610312576020366003190112610312573591600b5483101561074657506107d8602092611cd0565b91905490519160031b1c8152f35b8382346103455781600319360112610345576020905173392da14e4b78a634859b5655af7878d431fb350d8152f35b509190346103455760203660031901126103455735906001600160801b0382168203610746575061041090610848612a42565b60085490612e25565b50919034610345576003199282843601126103125761086e612a42565b805161087981611d2d565b826001956001835260208036818601378673392da14e4b78a634859b5655af7878d431fb350d806108a98761282b565b52865163c4f59f9b60e01b815294859182905afa928315610a76578793610a52575b508451926108d884611d2d565b6001845281885b818110610a425750508881519161090d6108f884611d84565b936109058a519586611d63565b808552611d84565b601f199390840136868301376109228761282b565b5261092c8661282b565b5089825b610a03575b505050739f59398d0a397b2eeb8a6123a6c7295cb0b0062d94853b156109ff5761098490879a95969a94939294519863183f9c7d60e11b8a5230908a0152606060248a015260648901906127ef565b9187830301604488015284519182815281810182808560051b8401019701948a925b8584106109ce575050508880898982828f8183818f03925af190811561074957506107365750f35b9091929394959685806109eb839f9b868682030188528b516127ef565b9a9e990197969591909101930191906109a6565b8880fd5b8151811015610a3d5782906001600160a01b03610a208285612838565b5116610a3582610a2f8b61282b565b51612838565b520182610930565b610935565b60608282880101520182906108df565b610a6f9193503d8089833e610a678183611d63565b81019061276e565b915f6108cb565b85513d89823e3d90fd5b838234610345578160031936011261034557602090517312e66c8f215ddd5d48d150c8f46ad0c6fb0f44068152f35b503461031257602036600319011261031257813591610acc612a42565b606383116103045750816020917ff5a802650e0a86db227cc342f06327d2ca0ff5cf2b12e0084fc5d8a7db2c54fd9360025551908152a180f35b83823461034557816003193601126103455751908152602090f35b50903461031257816003193601126103125781602093610b3f611c6f565b923581525f805160206149a48339815191528552209060018060a01b03165f52825260ff815f20541690519015158152f35b8084843461075757602036600319011261075757610b8d612a95565b600654815163c4f59f9b60e01b81526001600160a01b03909116929084818381875afa908115610c22578591610c08575b50833b1561060b57610bf593859283855180978195829463f5f8d36560e01b845280359084015288602484015260448301906127ef565b03925af190811561074957506107365750f35b610c1c91503d8087833e610a678183611d63565b86610bbe565b83513d87823e3d90fd5b5082346107465780600319360112610746578151918291600a54808552602080950194600a83527fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a892905b828210610c9d57610c998686610c8f828b0383611d63565b5191829182611c95565b0390f35b835487529586019560019384019390910190610c77565b8382346103455781600319360112610345576020905173dcb5a24ec708cc13cee12bfe6799a78a79b666b48152f35b8334610746578060031936011261074657610cfc612a42565b6105e161266e565b8382346103455781600319360112610345576020906002549051908152f35b8382346103455781600319360112610345576020905173cd2d0637c94fe77c2896bbcbb174ceffb08de6d78152f35b505034610345576020366003190112610345576105e190610d71612a42565b35612052565b8382346103455781600319360112610345576020915460181c60020b9051908152f35b838234610345578160031936011261034557602090610db7611fac565b90519015158152f35b509034610312578260031936011261031257610dda612a42565b600b54835b818110610eba57505081519060209260208301926001600160401b039181851083861117610ea7579084879252528411610e9457600160401b8411610e945750600b5483600b55808410610e67575b50600b8352825b838110610e4857836105e1600854611f76565b81515f8051602061498483398151915282015590820190600101610e35565b835f8051602061498483398151915291820191015b818110610e895750610e2e565b5f8155600101610e7c565b634e487b7160e01b845260419052602483fd5b604184634e487b7160e01b5f525260245ffd5b610ec381611cd0565b90549060039160085491831b1c14610f5757610ede82611cd0565b9054911b1c600a805490600160401b821015610f445760018201808255821015610f31575f527fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a801556001905b01610ddf565b603286634e487b7160e01b5f525260245ffd5b604186634e487b7160e01b5f525260245ffd5b50600190610f2b565b83823461034557606036600319011261034557602090610f92610f81611c59565b610f89611c6f565b60443591611eb3565b9051908152f35b50829034610345578060031936011261034557610fb4611c6f565b90336001600160a01b03831603610fd15750610655919235613b35565b5163334bd91960e11b81528390fd5b503461031257806003193601126103125761065591356110036001610632611c6f565b612d9f565b833461074657602036600319011261074657611022611c85565b61102a612a42565b5f549060481b62ffffff60481b169062ffffff60481b1916175f5580f35b83823461034557816003193601126103455760209051735050bc082ff4a74fb6b0b04385defddb114b24248152f35b50903461031257602036600319011261031257816020936001923581525f805160206149a483398151915285522001549051908152f35b50346103125782600319360112610312576110c7612a95565b60ff60075460b01c16611216575b815481516370a0823160e01b80825230828601526001600160a01b0392831694919290916020919082856024818a5afa94851561120c5788956111dd575b508290602483600554169588519687938492835230908301525afa928315610a7657879361118e575b508261117a9161116f867fd66662c0ded9e58fd31d5e44944bcfd07ffc15e6927ecc1382e7941cb7bd24c4993390613af5565b339060055416613af5565b856007555f6008558351928352820152a180f35b9092508181813d83116111d6575b6111a68183611d63565b810103126106035751917fd66662c0ded9e58fd31d5e44944bcfd07ffc15e6927ecc1382e7941cb7bd24c461113c565b503d61119c565b9094508281813d8311611205575b6111f58183611d63565b8101031261060357519382611113565b503d6111eb565b86513d8a823e3d90fd5b61121e612a42565b600854815163133f757160e31b81528381018290529061014080836024817312e66c8f215ddd5d48d150c8f46ad0c6fb0f44065afa9081156112f2578691611273575b5061126c9250612e25565b50506110d5565b905082813d83116112eb575b6112898183611d63565b8101031261060b578161129e61126c93611dc6565b506112ab60208201611dc6565b506112b7848201611de7565b506112c460608201611de7565b506112d160808201611de7565b506112e461012061049060a08401612a2e565b505f611261565b503d61127f565b84513d88823e3d90fd5b5082346107465780600319360112610746578151918291600b54808552602080950194600b83525f8051602061498483398151915292905b82821061134c57610c998686610c8f828b0383611d63565b835487529586019560019384019390910190611334565b5091903461034557816003193601126103455761137e612a42565b60075460ff8160b01c1661149e575b50611396613135565b909360018060a01b0393846009541685855416938351916370a0823160e01b808452308885015260209889856024818b5afa948515611494578695611465575b5060055416978651918252309082015288816024818b5afa94851561145a5794611426575b509060809861140b949392613218565b50905082959195519586521515908501528301526060820152f35b935091908784813d8311611453575b61143f8183611d63565b8101031261060357925192909160806113fb565b503d611435565b8651903d90823e3d90fd5b9094508981813d831161148d575b61147d8183611d63565b810103126106035751935f6113d6565b503d611473565b87513d88823e3d90fd5b6008546114b69160301c6001600160801b0316612e25565b5061138d565b5090346106035760a0366003190112610603576114d7611c59565b906114e0611c6f565b9060443560020b806044350361060357606435938460020b850361060357608435938460020b8503610603577ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a009586549560ff878a1c1615966001600160401b0381168015908161198e575b6001149081611984575b15908161197b575b5061196b5767ffffffffffffffff19811660011789558761194c575b5060ff88548a1c161561193c575f5460038602808060020b03611929579065ffffff00000062ffffff9260481b62ffffff60481b169460181b16906bffffffffffffffffffffffff19161791161768ffffff00000000000060443560301b1617175f5560018060a01b03906bffffffffffffffffffffffff60a01b92828116848754161786558282168460055416176005558851634a16fd0d60e11b81526020818061164c60443587878d8501919392604091606084019560018060a01b03809216855216602084015260020b910152565b0381739f59398d0a397b2eeb8a6123a6c7295cb0b0062d5afa90811561191f579084915f916118d8575b50600680549190921690861617905588516328af8d0b60e01b81526001600160a01b039182168782019081529290911660208084019190915260443560020b60408401529091829081906060015b038173cd2d0637c94fe77c2896bbcbb174ceffb08de6d75afa9081156118ce575f91611894575b5016906009541617600955600181145f146118705750600180555b60016002557312e66c8f215ddd5d48d150c8f46ad0c6fb0f4406803b15610603575f8091604487518094819363a22cb46560e01b83523388840152600160248401525af1801561186657611853575b5061175e612b19565b50611767612bc6565b50611770612c76565b5061177a33612d1f565b50739710e10a8f6fba8c391606fee18614885684548d84519163095ea7b360e01b83528201525f19602482015260208160448188735050bc082ff4a74fb6b0b04385defddb114b24245af180156104b95761181a575b506117d9578280f35b805468ff00000000000000001916905551600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d290602090a15f808280f35b6020813d60201161184b575b8161183360209383611d63565b8101031261060b5761184490611dda565b505f6117d0565b3d9150611826565b61185e919550611d06565b5f935f611755565b85513d5f823e3d90fd5b603281036118835750600a600155611706565b606403611706576014600155611706565b90506020813d6020116118c6575b816118af60209383611d63565b81010312610603576118c090611dc6565b5f6116eb565b3d91506118a2565b88513d5f823e3d90fd5b929150506020823d602011611917575b816118f560209383611d63565b81010312610603576116c4928461190d602094611dc6565b9194509192611676565b3d91506118e8565b8a513d5f823e3d90fd5b601188634e487b7160e01b5f525260245ffd5b8851631afcd79f60e31b81528690fd5b68ffffffffffffffffff1916680100000000000000011788555f61157a565b895163f92ee8a960e01b81528790fd5b9050155f61155e565b303b159150611556565b89915061154c565b5034610603575f366003190112610603576020905f5460020b9051908152f35b5034610603575f366003190112610603576020906001549051908152f35b50346106035780600319360112610603576119ed611c85565b602435908160020b9081830361060357611a05612a42565b8060020b92620d89ef1984128015611a7d575b611a6e577fd9388bd35364a0b59809b9dbe4393358ad02ba3f1a157294eae8a2aa9775da9a955065ffffff0000005f549162ffffff169260181b169065ffffffffffff191617175f5582519182526020820152a1005b84516264847d60e41b81528690fd5b50620d89f08313611a18565b5034610603575f3660031901126106035760095490516001600160a01b039091168152602090f35b503461060357608036600319011261060357611acb611c59565b50611ad4611c6f565b506064356001600160401b03808211610603573660238301121561060357818401359081116106035736910160240111610603577312e66c8f215ddd5d48d150c8f46ad0c6fb0f44063303611b335751630a85bd0160e11b8152602090f35b5163041fb8cb60e31b8152fd5b5034610603575f36600319011261060357905490516001600160a01b039091168152602090f35b5034610603575f366003190112610603576020905173392da14e4b78a634859b5655af7878d431fb350d8152f35b5034610603575f366003190112610603576020905f5460481c60020b9051908152f35b5034610603575f3660031901126106035760065490516001600160a01b039091168152602090f35b5034610603575f36600319011261060357602090515f805160206149c48339815191528152f35b833461060357602036600319011261060357359063ffffffff60e01b821680920361060357602091637965db0b60e01b8114908115611c48575b5015158152f35b6301ffc9a760e01b14905083611c41565b600435906001600160a01b038216820361060357565b602435906001600160a01b038216820361060357565b600435908160020b820361060357565b60209060206040818301928281528551809452019301915f5b828110611cbc575050505090565b835185529381019392810192600101611cae565b600b54811015611cf257600b5f525f8051602061498483398151915201905f90565b634e487b7160e01b5f52603260045260245ffd5b6001600160401b038111611d1957604052565b634e487b7160e01b5f52604160045260245ffd5b604081019081106001600160401b03821117611d1957604052565b608081019081106001600160401b03821117611d1957604052565b90601f801991011681019081106001600160401b03821117611d1957604052565b6001600160401b038111611d195760051b60200190565b9060020b9060020b02908160020b918203611db257565b634e487b7160e01b5f52601160045260245ffd5b51906001600160a01b038216820361060357565b5190811515820361060357565b51908160020b820361060357565b519061ffff8216820361060357565b908160e09103126106035780516001600160a01b03811681036106035791611e2e60208301611de7565b91611e3b60408201611df5565b91611e4860608301611df5565b91611e5560808201611df5565b9160a082015160ff811681036106035760c0611e72919301611dda565b90565b91908203918211611db257565b81810292918115918404141715611db257565b8115611e9f570490565b634e487b7160e01b5f52601260045260245ffd5b600954604051633850c7bd60e01b81526001600160a01b039160e0908290600490829086165afa8015611f6b5782611ef69181935f91611f36575b501680613bb4565b931691161015611f2857611f0991613bb4565b6001546064039060648211611db257606491611f2491611e82565b0490565b611f3191613bf8565b611f09565b611f58915060e03d60e011611f64575b611f508183611d63565b810190611e04565b5050505050505f611eee565b503d611f46565b6040513d5f823e3d90fd5b600b54600160401b811015611d1957806001611f959201600b55611cd0565b819291549060031b91821b915f19901b1916179055565b60075460ff8160b01c161561204c57600954604051633850c7bd60e01b81529060e090829060049082906001600160a01b03165afa908115611f6b575f91612026575b50611ff981613c7f565b156120205760020b8160020b811291821561201357505090565b60181c60020b1315919050565b50505f90565b61203f915060e03d60e011611f6457611f508183611d63565b505050505090505f611fef565b50600190565b61205a611fac565b1561265e5760075460ff8160b01c16612640575b50612077613135565b9160018060a01b0360045416604051916370a0823160e01b92838152306004820152602081602481865afa908115611f6b575f9161260e575b5060018060a01b036005541660405193858552306004860152602085602481855afa948515611f6b575f956125da575b506120f885848a8a60018060a01b0360095416613218565b509050819691612575575b5050505050505060018060a01b03600454169060405191818352306004840152602083602481845afa928315611f6b575f93612541575b50600554604051928352306004840152602090839060249082906001600160a01b03165afa918215611f6b575f9261250d575b5060ff60075460b01c166124fb57826121859161453c565b60055461219c9082906001600160a01b031661453c565b60018060a01b03600454169160018060a01b0360055416915f54916002546064039260648411611db25760646121de816121d68786611e82565b049585611e82565b049461012c42014211611db25760405196876101608101106001600160401b036101608a011117611d1957610160880160409081529088526020880191825260309290921c600290810b83890190815289820b60608a019081528b830b6080808c0191825260a08c0197885260c08c0198895260e08c01998a526101008c019a8b52306101208d019081524261012c016101408e019081529751636d70c41560e01b81529c516001600160a01b0390811660048f01529651871660248e01529351850b60448d01529151840b60648c01525190920b60848a0152935160a4890152935160c4880152935160e4870152935161010486015251909116610124840152905161014483015281610164815f7312e66c8f215ddd5d48d150c8f46ad0c6fb0f44065af18015611f6b575f915f9161248c575b50816001600160801b036080927f9314bc80d147aa8ca0b2957b6e387a64a6db9e2a210d2c1b9c8d77b11c4c4c7294600855600754600160b01b908860181b65ffffff000000169068ffffffffffffffffff60b81b1675ffffffffffffffffffffffffffffffff0000000000008460301b161762ffffff891617171760075561239b83611f76565b6040519283528560020b60208401528660020b6040840152166060820152a17fddeb651c3c5acecf292901bcf399e51d7a06a012e320facbc4bfab7c1055527060606008546040519081528360020b60208201528460020b6040820152a1600954604051633850c7bd60e01b81529060e090829060049082906001600160a01b03165afa908115611f6b575f91612466575b5060020b9060020b8112918215612459575b505061244757565b604051630a49cb5560e01b8152600490fd5b60020b1290505f8061243f565b61247f915060e03d60e011611f6457611f508183611d63565b505050505090505f61242d565b9150506080813d6080116124f3575b816124a860809383611d63565b81010312610603576080816001600160801b036124ea60207f9314bc80d147aa8ca0b2957b6e387a64a6db9e2a210d2c1b9c8d77b11c4c4c7295519301612a2e565b92505091612313565b3d915061249b565b6040516351becb2360e11b8152600490fd5b9091506020813d602011612539575b8161252960209383611d63565b810103126106035751905f61216d565b3d915061251c565b9092506020813d60201161256d575b8161255d60209383611d63565b810103126106035751915f61213a565b3d9150612550565b156125c05750505082116125ae576004546005546125a093916001600160a01b0391821691166141fc565b505b5f808080808080612103565b60405163133153a160e21b8152600490fd5b909194809350116125ae576125d4936141fc565b506125a2565b9094506020813d602011612606575b816125f660209383611d63565b810103126106035751935f6120e0565b3d91506125e9565b90506020813d602011612638575b8161262960209383611d63565b8101031261060357515f6120b0565b3d915061261c565b6008546126589160301c6001600160801b0316612e25565b5061206e565b50565b91908201809211611db257565b6040516370a0823160e01b815230600482015260208082602481735050bc082ff4a74fb6b0b04385defddb114b24245afa918215611f6b575f9261273f575b50811561273b5760405191636e553f6560e01b8352600483015230602483015280826044815f739710e10a8f6fba8c391606fee18614885684548d5af1908115611f6b575f9161270b575b506127069150600354612661565b600355565b905081813d8311612734575b6127218183611d63565b810103126106035761270690515f6126f8565b503d612717565b5050565b9080925081813d8311612767575b6127578183611d63565b810103126106035751905f6126ad565b503d61274d565b6020908181840312610603578051906001600160401b03821161060357019180601f840112156106035782516127a381611d84565b936127b16040519586611d63565b818552838086019260051b820101928311610603578301905b8282106127d8575050505090565b8380916127e484611dc6565b8152019101906127ca565b9081518082526020808093019301915f5b82811061280e575050505090565b83516001600160a01b031685529381019392810192600101612800565b805115611cf25760200190565b8051821015611cf25760209160051b010190565b6006546040805163c4f59f9b60e01b81526004926001600160a01b0391905f9082908690829086165afa908115612a24575f91612a0a575b5080515f5b81811061294b575050508351928315612944575f5b8481106128ad57505050505050565b826128b88288612838565b511690845180926370a0823160e01b8252308583015281602460209586935afa92831561293a575f93612907575b505061290160019233866128fa858c612838565b5116613af5565b0161289e565b90809350813d8311612933575b61291e8183611d63565b810103126106035761290160019251926128e6565b503d612914565b86513d5f823e3d90fd5b5050505050565b735050bc082ff4a74fb6b0b04385defddb114b24248461296b8386612838565b511614612a02578361297d8285612838565b511690855180926370a0823160e01b8252308983015281602460209586935afa9283156129f8575f936129c5575b50506129bf60019233876128fa8589612838565b01612889565b90809350813d83116129f1575b6129dc8183611d63565b81010312610603576129bf60019251926129ab565b503d6129d2565b87513d5f823e3d90fd5b6001906129bf565b612a1e91503d805f833e610a678183611d63565b5f612884565b83513d5f823e3d90fd5b51906001600160801b038216820361060357565b335f9081525f805160206149e483398151915260205260409020545f805160206149c48339815191529060ff1615612a775750565b6044906040519063e2517d3f60e01b82523360048301526024820152fd5b335f9081527fb7db2dd08fcb62d0c9e08c51941cae53c267786a0b75803fb7960902fc8ef97d602052604090205460ff1615612acd57565b60405163e2517d3f60e01b81523360048201525f6024820152604490fd5b805f525f805160206149a483398151915260205260405f20335f5260205260ff60405f20541615612a775750565b733402ebe2ad564ff3ca90513ff1a1935364179f6c5f8190527fb7db2dd08fcb62d0c9e08c51941cae53c267786a0b75803fb7960902fc8ef97d6020527fb311a8ef0b3c454754fc971be32932edce85d5c5f321d67b91e9027ab92faa79545f805160206149a48339815191529060ff16612020575f805260205260405f20815f5260205260405f20600160ff1982541617905533905f5f805160206149648339815191528180a4600190565b733402ebe2ad564ff3ca90513ff1a1935364179f6c5f8190525f805160206149e48339815191526020527f80e59f01c2d6a4515c62d34327860193ccb6e58244c720ab454bcdad18bf80b7545f805160206149c483398151915291905f805160206149a48339815191529060ff16612c6f57825f5260205260405f20815f5260205260405f20600160ff1982541617905533915f805160206149648339815191525f80a4600190565b5050505f90565b7338569e5f28921537499da81ed14d32b5b4ce95ae5f8190525f805160206149e48339815191526020527f163941dd190106e3d0258e77adfd8dfe425560a3c07faf20a19fd18ce9fb0b78545f805160206149c483398151915291905f805160206149a48339815191529060ff16612c6f57825f5260205260405f20815f5260205260405f20600160ff1982541617905533915f805160206149648339815191525f80a4600190565b6001600160a01b03165f8181525f805160206149e483398151915260205260409020545f805160206149c483398151915291905f805160206149a48339815191529060ff16612c6f57825f5260205260405f20815f5260205260405f20600160ff1982541617905533915f805160206149648339815191525f80a4600190565b90815f525f805160206149a48339815191528060205260405f209160018060a01b031691825f5260205260ff60405f205416155f14612c6f57825f5260205260405f20815f5260205260405f20600160ff1982541617905533915f805160206149648339815191525f80a4600190565b9190826040910312610603576020825192015190565b9160ff60075460b01c16156130e4575f915f906001600160801b0380951680612faf575b506040805195608087018781106001600160401b03821117611d19578252828752306020880190815287830182815260608901838152845163fc6f786560e01b8152995160048b015291516001600160a01b031660248a015251821660448901525116606487015280866084815f7312e66c8f215ddd5d48d150c8f46ad0c6fb0f44065af1928315612fa5575f965f94612f44575b50839291612f23612f3f92612f1d7fa54e6c2fc0861aa9c991b26891d71059d517983b9e84b91020f42609c452eb9d97998b5f6007555f600855611e75565b95611e75565b9051938493846040919493926060820195825260208201520152565b0390a1565b612f2397507fa54e6c2fc0861aa9c991b26891d71059d517983b9e84b91020f42609c452eb9d945091612f91612f3f929493823d8411612f9e575b612f898183611d63565b810190612e0f565b9098509450919290612ede565b503d612f7f565b50513d5f823e3d90fd5b9150925061012c420192834211611db25760409384519260a084018481106001600160401b03821117611d19578652828452602084019081528584015f81528760608601925f845260808701948552885196630624e65f60e11b885251600488015251166024860152516044850152516064840152516084830152838260a4815f7312e66c8f215ddd5d48d150c8f46ad0c6fb0f44065af180156130da575f925f91613099575b50935181815260208101839052604081018590529193917fbcdb14b9d37e7c5c183adc833dd59bf42815b5135e0cc94641f8929f943661c590606090a15f612e49565b7fbcdb14b9d37e7c5c183adc833dd59bf42815b5135e0cc94641f8929f943661c593506130d39150853d8711612f9e57612f898183611d63565b9092613056565b84513d5f823e3d90fd5b60405163ebb0360f60e01b8152600490fd5b60020b9060020b908115611e9f57627fffff1981145f19831416611db2570590565b600291820b910b0390627fffff198212627fffff831317611db257565b600954604051633850c7bd60e01b81529060e090829060049082906001600160a01b03165afa908115611f6b575f916131f2575b505f8160020b125f146131d6575f5460301c60020b5f19810191627fffff8313627fffff19841217611db257816131a66131b0946131ab93613118565b6130f6565b611d9b565b905b5f5460301c60020b8260020b0191627fffff198312627fffff841317611db2579190565b6131ec906131ab5f5460301c60020b80926130f6565b906131b2565b61320b915060e03d60e011611f6457611f508183611d63565b505050505090505f613169565b9493929190915f95811580613aed575b613adc578260020b8460020b9080821291821592613ace575b508115613ac1575b50613aaf57803b15613aa2576040519461012086018681106001600160401b03821117611d19576040525f86525f60208701525f60408701525f60608701525f60808701525f60a08701525f60c08701525f60e08701525f610100870152633850c7bd60e01b5f5260405f600481855afa15610603575f51956020519587966040830152630d34328160e11b5f5260205f600481875afa15610603575f519063ddca3f4360e01b5f5260205f600481885afa156106035762ffffff5f5116906334324e9f60e21b5f5260205f600481895afa15610603576133559261334f925f519186528b602087015288606087015286608087015260e0860152610100850152613cf9565b95613cf9565b60a0820186905260c08201819052926133806001600160a01b0380861690808916908b16868961401d565b9750617fff19905f905b604084015160020b8a61010086015160020b93815f146139d1575f858407128584050360081d95600187810b91900b036139b6575b8092600260ff5f1992885f81830712910503161b01165b8015613996577f07060605060205040602030205040301060502050303040105050304000000006f8421084210842108cc6318c6db6d54be826001600160801b031060071b83811c6001600160401b031060061b1783811c63ffffffff1060051b1783811c61ffff1060041b1783811c60ff1060031b1792831c1c601f161a17915b94809461346b81858460081b0102613cf9565b938361394b576020890151895160808b015160e08c01516134a29390926001600160801b03169089906001600160a01b031661466e565b94919590959460608c0151019560808c015103965b6001600160a01b039081169086160361393c5760a08b015160c08c0151911515916134ed916001600160a01b0388168a8a61401d565b1515146138e4575050505050505050505b8051926020820151926060830151966080840151928a155f1461370c57506001600160a01b038181169086161061365f575b6001600160a01b039081169085161015613559575b50505090613553918561412e565b91030192565b919650929198508551928660208101519460c08201519560e0830151620f424092818403908060601b8481046060880151019061359a60a08901518361488d565b9b6135b06135aa86898b02611e95565b8561488d565b956135c760a060808c01519889019b01518661488d565b8a0396871115613652576135539d86613607966135e7856136459e614850565b930204900303940290870204900360011b9260011b8302828002016148d7565b0160601b0581811190821802189860018d8b038060ff1d908101189260e061362f858a61488d565b9301519003928160601b908809151516016147ca565b9103019790915f80613545565b63202368085f526004601cfd5b9a975061367f61367860e0850151620f42400384614760565b868661415d565b976001600160a01b038c8116908a16101561369c5750809a613530565b9a939185856136e7926136df82879c969c038060ff1d908101186136c0818661488d565b60e08a0151620f42400391600190600160601b908809151516016147ca565b90039461412e565b6001600160a01b03851660208501520160608301819052608083018290529583613530565b929791969290506001600160a01b038082169086161161384a575b6001600160a01b039081169085161115613754575b505050906135539185038060ff1d908101189061488d565b91965091929850855195602081015160c082015160e0830151620f424099818b03908b606087015191828160601b9287840490848a880291020482010311156136525785948e8589938b8260a0820151878202898702048a01906137b79161488d565b946137c2888561488d565b6080840151019260a0015102906137d891611e95565b6137e2908361488d565b81039a6137ee91614850565b93020401039482049302908d0204010360011b9160011b820281800201613814906148d7565b0160601b0481811090821802189661382d8b868a6140ed565b9160e00151900361383d916147ca565b91030196905f808061373c565b9a975061386a61386360e0850151620f42400383614760565b8686614068565b976001600160a01b038c8116908a16106138865750819a613727565b9a9396906138bf906138ac61389c888b896140ed565b60e0870151620f424003906147ca565b90039785038060ff1d908101188661488d565b6001600160a01b03851660208501526060840188905201608083018190529583613727565b63f30dba9360e01b5f5282828260081b010260020b60045260405f6024818a5afa15610603578f93602051855f031885018b51018b5260208b015260081b01020360408701526060860152608085015291909161338a565b505050505050505050506134fe565b6020890151895160608b015160e08c015195969561397f9390926001600160801b03169089906001600160a01b031661466e565b9591949060608c0151039560808c015101966134b7565b50505090915f190160010b906139ac82826148b3565b9192918a816133d6565b506139cc5f858407128584050360081d846148b3565b6133bf565b60015f86850712868505030160020b60081d9560010b8660010b145f14613a92575b6001808294875f818307129105030160ff161b5f03165b8015613a7257805f03167e1f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405601f826001600160801b031060071b83811c6001600160401b031060061b1783811c63ffffffff1060051b1792831c63d76453e004161a1791613458565b505050909160010160010b90613a8882826148b3565b9192918a81613a0a565b50613a9d85846148b3565b6139f3565b6301ac05a55f526004601cfd5b6040516330673a1b60e01b8152600490fd5b620d89e89150135f613249565b620d89e7191391505f613241565b505050505090505f905f905f905f90565b508415613228565b60405163a9059cbb60e01b60208201526001600160a01b039092166024830152604480830193909352918152613b3391613b2e82611d48565b6141a2565b565b90815f525f805160206149a48339815191528060205260405f209160018060a01b031691825f5260205260ff60405f2054165f14612c6f57825f5260205260405f20815f5260205260405f2060ff19815416905533917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b5f80a4600190565b5f198282099082810292838084109303928084039314613bef57600160601b9183831115610603570990828211900360a01b910360601c1790565b50505060601c90565b90600160601b905f19828409928060601b92838086109503948086039514613c7157848311156106035782910981805f0316809204600280826003021880830282030280830282030280830282030280830282030280830282030280920290030293600183805f03040190848311900302920304170290565b505080925015610603570490565b5f5460029180830b908260181c840b82128015613cee575b613ce65760075460ff8160b01c1615613cdc57840b8092135f14613ccd5790613cbf91613118565b905b60481c820b910b131590565b613cd691613118565b90613cc1565b5050505050600190565b505050505f90565b5082840b8213613c97565b8060ff1d81810118620d89e881116140065763ffffffff91600160801b7001fffcb933bd6fad37aa2d162d1a5940016001841602189160028116613fea575b60048116613fce575b60088116613fb2575b60108116613f96575b60208116613f7a575b60408116613f5e575b608090818116613f43575b6101008116613f28575b6102008116613f0d575b6104008116613ef2575b6108008116613ed7575b6110008116613ebc575b6120008116613ea1575b6140008116613e86575b6180008116613e6b575b620100008116613e50575b620200008116613e36575b620400008116613e1c575b6208000016613e02575b505f12613dfa575b0160201c90565b5f1904613df3565b6b048a170391f7dc42444e8fa25f929302901c9190613deb565b6d2216e584f5fa1ea926041bedfe98909302811c92613de1565b926e5d6af8dedb81196699c329225ee60402811c92613dd6565b926f09aa508b5b7a84e1c677de54f3e99bc902811c92613dcb565b926f31be135f97d08fd981231505542fcfa602811c92613dc0565b926f70d869a156d2a1b890bb3df62baf32f702811c92613db6565b926fa9f746462d870fdf8a65dc1f90e061e502811c92613dac565b926fd097f3bdfd2022b8845ad8f792aa582502811c92613da2565b926fe7159475a2c29b7443b29c7fa6e889d902811c92613d98565b926ff3392b0822b70005940c7a398e4b70f302811c92613d8e565b926ff987a7253ac413176f2b074cf7815e5402811c92613d84565b926ffcbe86c7900a88aedcffc83b479aa3a402811c92613d7a565b926ffe5dee046a99a2a811c461f1969c305302811c92613d70565b916fff2ea16466c96a3843ec78b326b528610260801c91613d65565b916fff973b41fa98c081472e6896dfb254c00260801c91613d5c565b916fffcb9843d60f6159c9db58835c9266440260801c91613d53565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c91613d4a565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c91613d41565b916ffff97272373d413259a46990580e213a0260801c91613d38565b6308c379a05f52602080526101546041526045601cfd5b9193918385116140305750505050505f90565b828510614041575050505050600190565b614064936140528661405b9361488d565b9086039061488d565b93820390614872565b1090565b9082156140e75760601b9181810282828204146140a0575b5061408c918304612661565b80820491061515016001600160a01b031690565b830191838310156140b15791614080565b90506140be828285614872565b92096140d1575b6001600160a01b031690565b600101806140c5575b63ae47f7025f526004601cfd5b50905090565b918282108284180280808518931893146106035760601b9160019082810361411f6001600160a01b0383168287614872565b94098284061715151691040190565b8181188183100280821893928118911461060357611f24916001600160a01b038216918490039060601b614872565b9190614183918060a01c155f146141935760601b045b6001600160a01b03928316612661565b600160a01b811015610603571690565b9061419d91614850565b614173565b905f602091828151910182855af115611f6b575f513d6141f357506001600160a01b0381163b155b6141d15750565b604051635274afe760e01b81526001600160a01b039091166004820152602490fd5b600114156141ca565b91908115613ce6578315614529575b604051636eb1769f60e11b8152306004820152735543c6176feb9b4b179078205d7c29eea2e2d69560248201526020816044816001600160a01b0388165afa8015611f6b5783905f906144f3575b6142639250612661565b60405160205f81830163095ea7b360e01b94858252735543c6176feb9b4b179078205d7c29eea2e2d69560248601526044850152604484526142a484611d48565b835190826001600160a01b038a165af15f513d826144ce575b50501561446c575b50505f5460301c9361012c42014211611db2576040519461010086018681106001600160401b03821117611d195760405260018060a01b038516865260018060a01b038316602087015260020b604086015230606086015261012c420160808601528260a086015260c08501525f60e0850152604051936350131c1f60e11b855260018060a01b03815116600486015260018060a01b036020820151166024860152604081015160020b604486015260018060a01b0360608201511660648601526080810151608486015260a081015160a486015260c081015160c486015260e060018060a01b039101511660e4850152602084610104815f735543c6176feb9b4b179078205d7c29eea2e2d6955af1938415611f6b575f94614431575b50604080516001600160a01b039485168152939091166020840152820152606081018290527f25f1d03755df23c30e25db2dbd3891e31ce084bdfbfc46f9fe5e446ee5f9b2d490608090a190565b91929093506020823d602011614464575b8161444f60209383611d63565b810103126106035790519290919060806143e3565b3d9150614442565b6144b86144c792604051906020820152735543c6176feb9b4b179078205d7c29eea2e2d69560248201525f6044820152604481526144a981611d48565b6001600160a01b0387166141a2565b6001600160a01b0385166141a2565b5f806142c5565b9091506144eb57506001600160a01b0385163b15155b5f806142bd565b6001146144e4565b50506020813d602011614521575b8161450e60209383611d63565b8101031261060357826142639151614259565b3d9150614501565b9250614536818484611eb3565b9261420b565b604051636eb1769f60e11b81523060048201527312e66c8f215ddd5d48d150c8f46ad0c6fb0f440660248201819052926001600160a01b03831692916020918282604481885afa8015611f6b575f9061463f575b61459a9250612661565b9060405193815f81870163095ea7b360e01b958682528960248a01526044890152604488526145c888611d48565b87519082885af1903d5f519083614620575b505050156145e9575050505050565b61461694613b2e926040519283015260248201525f60448201526044815261461081611d48565b826141a2565b5f80808080612944565b9192509061463557503b15155b5f80806145da565b600191501461462d565b508282813d8311614667575b6146558183611d63565b810103126106035761459a9151614590565b503d61464b565b620f4240948503956001600160a01b0380841690831610159590949193929091906146998883614760565b8715614737576146aa8587846140ed565b925b8382106146ff5750509687926146c282846147ca565b92096146ed575b945b156146e45791611e7292038060ff1d908101189061488d565b611e729261412e565b600191500180156140da5785906146c9565b97985092505050821582151761060357851561472757614720908284614068565b80956146cb565b61473290828461415d565b614720565b8186038060ff1d90810118600161474e828861488d565b918160601b90880915151601926146ac565b81810291620f424091828282860414821517021561477f575050900490565b825f1983830985811086019003928392099211156140da57828211900360fa1b910360061c177fde8f6cefed634549b62c77574f722e1ac57e23f24d8fd5cb790fb65668c261390290565b90620f4240918281029282818386041483151702156147ea575050900490565b82905f1981840985811086019003920990825f03831692818111156140da578390046002816003028118808302820302808302820302808302820302808302820302808302820302809202900302936001848483030494805f0304019211900302170290565b606081901b9190600160601b81158285048214178302156147ea575050900490565b818102929181158285048214178302156147ea575050900490565b808202915f19910981811082019003600160601b8110156140da5760a01b9060601c1790565b60245f809260209463299ce14b60e11b835260010b6004525afa15610603575f5190565b8070ffffffffffffffffffffffffffffffffff1060071b81811c68ffffffffffffffffff1060061b1781811c64ffffffffff1060051b1781811c62ffffff1060041b1760019060b56201000084831c0191831c1b0260121c80830401811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c808092041090039056fe2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db902dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800d8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e6352fce5e8a5d0d9e8d1ea29f4525e512e9c27bf92cae50374d497f918ab48f382a26469706673582212203ea4a576af3a128e2895a9b542e0f8fe52169a59f3bcbd6a97205d44333b58d964736f6c63430008180033

Block Transaction Gas Used Reward
view all blocks ##produced##

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
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.