Unichain Sepolia Testnet

Contract

0xf043d11A5D4E520B68453B60eE314Fe1C6576acc
Source Code Source Code

Overview

ETH Balance

0 ETH

More Info

Multichain Info

N/A
Transaction Hash
Method
Block
From
To
Amount

There are no matching entries

1 Internal Transaction found.

Latest 1 internal transaction

Parent Transaction Hash Block From To Amount
239979462025-06-25 11:19:34233 days ago1750850374  Contract Creation0 ETH

Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
Levery

Compiler Version
v0.8.26+commit.8a97fa7a

Optimization Enabled:
Yes with 44444444 runs

Other Settings:
cancun EvmVersion

Contract Source Code (Solidity Standard Json-Input format)

File 1 of 36 : Levery.sol
// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2025, Wireshape, Inc.
pragma solidity 0.8.26;

import {ILevery} from "./interfaces/ILevery.sol";
import {BaseHook} from "v4-periphery/src/utils/BaseHook.sol";
import {Hooks} from "v4-core/src/libraries/Hooks.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {PoolId} from "v4-core/src/types/PoolId.sol";
import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary, toBeforeSwapDelta} from "v4-core/src/types/BeforeSwapDelta.sol";
import {TickMath} from "v4-core/src/libraries/TickMath.sol";
import {FullMath} from "v4-core/src/libraries/FullMath.sol";
import {StateLibrary} from "v4-core/src/libraries/StateLibrary.sol";
import {Currency} from "v4-core/src/types/Currency.sol";
import {Pausable} from "v4-core/lib/openzeppelin-contracts/contracts/utils/Pausable.sol";
import {IERC20} from "forge-std/interfaces/IERC20.sol";
import {IERC721} from "forge-std/interfaces/IERC721.sol";
import {AggregatorV3Interface} from "./interfaces/AggregatorV3Interface.sol";
import {IPermissionManager} from "./interfaces/IPermissionManager.sol";

/// @title Levery
/// @author Wireshape, Inc.
/// @notice Integrates dynamic fee management, price feed oracle deviation fees, service-fee collection and fine-grained
/// compliant permissioning into Uniswap V4 pools.
/// @dev Extends BaseHook to implement before/after hooks for initialization, liquidity and swaps.
///      Inherits OpenZeppelin’s Pausable to enable emergency shutdown at both contract and per-pool levels.
///      Uses IPermissionManager to enforce KYC/AML and role-based access to pool operations.
///      Supports global and per-pool base-fees, plus on-chain vs. market price deviation logic.
///      Emits events for all administrative and pool-level changes.
contract Levery is ILevery, BaseHook, Pausable {
    struct Permissions {
        bool swap;
        bool liquidity;
    }

    struct PoolOracle {
        address oracle;
        bool compareWithPrice0;
    }

    uint256 internal constant SQRT96 = 2 ** 96;
    uint256 internal constant MAX_PPM = 1_000_000;

    address public positionManager;
    address public swapRouter;
    address public quoter;
    address public serviceFeeVault;
    address public provider;
    address public institution;
    uint24 public baseFee;
    uint256 public serviceFee;
    uint256 public deviationFeeFactor;
    mapping(bytes32 => uint24) public poolBaseFees;
    mapping(bytes32 => PoolOracle) public poolOracles;
    mapping(bytes32 => bool) public poolPaused;
    IPermissionManager public permissionManager;

    mapping(bytes32 => bool) private rolesExists;
    mapping(bytes32 => mapping(address => Permissions)) private rolePermissions;
    mapping(bytes32 => bytes32) private poolRequiredRole;

    constructor(
        IPoolManager _poolManager,
        address _provider,
        address _institution,
        address _positionManager,
        address _swapRouter,
        address _quoter,
        address _serviceFeeVault,
        IPermissionManager _permissionManager
    ) BaseHook(_poolManager) {
        if (address(_poolManager) == address(0)) revert ZeroAddress();
        if (_provider == address(0)) revert ZeroAddress();
        if (_institution == address(0)) revert ZeroAddress();
        if (_positionManager == address(0)) revert ZeroAddress();
        if (_swapRouter == address(0)) revert ZeroAddress();
        if (_quoter == address(0)) revert ZeroAddress();
        if (_serviceFeeVault == address(0)) revert ZeroAddress();
        if (address(_permissionManager) == address(0)) revert ZeroAddress();

        provider = _provider;
        institution = _institution;
        positionManager = _positionManager;
        swapRouter = _swapRouter;
        quoter = _quoter;
        permissionManager = _permissionManager;
        serviceFeeVault = _serviceFeeVault;
        baseFee = 3_000; // 0.30%
        serviceFee = 1_000; // 0.10%
        deviationFeeFactor = 900_000; // 90%
    }

    /// @dev Restricts access to the designated "Provider" address, the protocol-level administrator.
    modifier onlyProvider() {
        if (msg.sender != provider) revert NotProvider(msg.sender);
        _;
    }

    /// @dev Restricts access to the designated "Institution" address creating and managing the pools.
    modifier onlyInstitution() {
        if (msg.sender != institution) revert NotInstitution(msg.sender);
        _;
    }

    /// @dev Fails if contract paused or pool paused.
    modifier whenPoolNotPaused(PoolKey calldata key) {
        if (paused()) revert ContractPaused();
        bytes32 id = PoolId.unwrap(key.toId());
        if (poolPaused[id]) revert PoolIsPaused(id);
        _;
    }

    /// @inheritdoc ILevery
    function pause() external onlyProvider {
        _pause();
    }

    /// @inheritdoc ILevery
    function unpause() external onlyProvider {
        _unpause();
    }

    /// @inheritdoc ILevery
    function pausePool(PoolKey calldata key) external onlyInstitution {
        bytes32 pid = _poolId(key);
        poolPaused[pid] = true;
        emit PoolPaused(pid);
    }

    /// @inheritdoc ILevery
    function unpausePool(PoolKey calldata key) external onlyInstitution {
        bytes32 pid = _poolId(key);
        poolPaused[pid] = false;
        emit PoolUnpaused(pid);
    }

    /// @inheritdoc ILevery
    function updateProvider(address _provider) external onlyProvider {
        if (_provider == address(0)) revert ZeroAddress();
        address old = provider;
        provider = _provider;
        emit ProviderUpdated(old, _provider);
    }

    /// @inheritdoc ILevery
    function updateInstitution(address _institution) external onlyInstitution {
        if (_institution == address(0)) revert ZeroAddress();
        address old = institution;
        institution = _institution;
        emit InstitutionUpdated(old, _institution);
    }

    /// @inheritdoc ILevery
    function updatePositionManager(address _positionManager) external onlyProvider {
        if (_positionManager == address(0)) revert ZeroAddress();
        address old = positionManager;
        positionManager = _positionManager;
        emit PositionManagerUpdated(old, _positionManager);
    }

    /// @inheritdoc ILevery
    function updateSwapRouter(address _swapRouter) external onlyProvider {
        if (_swapRouter == address(0)) revert ZeroAddress();
        address old = swapRouter;
        swapRouter = _swapRouter;
        emit SwapRouterUpdated(old, _swapRouter);
    }

    /// @inheritdoc ILevery
    function updateQuoter(address _quoter) external onlyProvider {
        if (_quoter == address(0)) revert ZeroAddress();
        address old = quoter;
        quoter = _quoter;
        emit QuoterUpdated(old, _quoter);
    }

    /// @inheritdoc ILevery
    function updateServiceFeeVault(address _serviceFeeVault) external onlyProvider {
        if (_serviceFeeVault == address(0)) revert ZeroAddress();
        address old = serviceFeeVault;
        serviceFeeVault = _serviceFeeVault;
        emit ServiceFeeVaultUpdated(old, _serviceFeeVault);
    }

    /// @inheritdoc ILevery
    function updatePermissionManager(IPermissionManager _permissionManager) external onlyProvider {
        if (address(_permissionManager) == address(0)) revert ZeroAddress();
        address old = address(permissionManager);
        permissionManager = _permissionManager;
        emit PermissionManagerUpdated(old, address(_permissionManager));
    }

    /// @inheritdoc ILevery
    function updateServiceFee(uint256 _serviceFee) external onlyProvider {
        if (_serviceFee > MAX_PPM) revert ServiceFeeTooLarge(_serviceFee);
        uint256 old = serviceFee;
        serviceFee = _serviceFee;
        emit ServiceFeeUpdated(old, _serviceFee);
    }

    /// @inheritdoc ILevery
    function updateBaseFee(uint24 _baseFee) external onlyInstitution {
        if (_baseFee > MAX_PPM) revert BaseFeeTooLarge(_baseFee);
        uint24 old = baseFee;
        baseFee = _baseFee;
        emit BaseFeeUpdated(old, _baseFee);
    }

    /// @inheritdoc ILevery
    function setDeviationFeeFactor(uint256 _deviationFeeFactor) external onlyInstitution {
        if (_deviationFeeFactor > MAX_PPM) revert DeviationFeeFactorTooLarge(_deviationFeeFactor);
        uint256 old = deviationFeeFactor;
        deviationFeeFactor = _deviationFeeFactor;
        emit DeviationFeeFactorUpdated(old, _deviationFeeFactor);
    }

    /// @inheritdoc ILevery
    function setPoolBaseFee(PoolKey calldata key, uint24 _baseFee) external onlyInstitution {
        if (_baseFee > MAX_PPM) revert BaseFeeTooLarge(_baseFee);
        bytes32 id = PoolId.unwrap(key.toId());
        poolBaseFees[id] = _baseFee;
        emit PoolBaseFeeSet(id, _baseFee);
    }

    /// @inheritdoc ILevery
    function createRole(bytes32 roleId) external onlyInstitution {
        if (rolesExists[roleId]) revert RoleAlreadyExists(roleId);
        rolesExists[roleId] = true;
        emit RoleCreated(roleId);
    }

    /// @inheritdoc ILevery
    function setRoleForUser(bytes32 roleId, address account, bool swap, bool liquidity) external onlyInstitution {
        if (!rolesExists[roleId]) revert RoleDoesNotExist(roleId);
        rolePermissions[roleId][account] = Permissions({swap: swap, liquidity: liquidity});
        emit UserRoleAssigned(roleId, account, swap, liquidity);
    }

    /// @inheritdoc ILevery
    function revokeUserRole(bytes32 roleId, address account) external onlyInstitution {
        if (!rolesExists[roleId]) revert RoleDoesNotExist(roleId);
        delete rolePermissions[roleId][account];
        emit UserRoleRevoked(roleId, account);
    }

    /// @inheritdoc ILevery
    function setPoolRequiredRole(PoolKey calldata key, bytes32 roleId) external onlyInstitution {
        if (!rolesExists[roleId]) revert RoleDoesNotExist(roleId);
        bytes32 pid = _poolId(key);
        poolRequiredRole[pid] = roleId;
        emit PoolRequiredRoleSet(pid, roleId);
    }

    /// @inheritdoc ILevery
    function clearPoolRequiredRole(PoolKey calldata key) external onlyInstitution {
        bytes32 pid = _poolId(key);
        bytes32 old = poolRequiredRole[pid];
        delete poolRequiredRole[pid];
        emit PoolRequiredRoleCleared(pid, old);
    }

    /// @inheritdoc ILevery
    function setPoolOracle(PoolKey calldata key, address _oracle, bool _compareWithPrice0) external onlyInstitution {
        if (_oracle == address(0)) revert ZeroAddress();
        bytes32 id = PoolId.unwrap(key.toId());
        poolOracles[id] = PoolOracle({oracle: _oracle, compareWithPrice0: _compareWithPrice0});
        emit PoolOracleSet(id, _oracle, _compareWithPrice0);
    }

    /// @inheritdoc ILevery
    function removePoolOracle(PoolKey calldata key) external onlyInstitution {
        bytes32 id = PoolId.unwrap(key.toId());
        if (poolOracles[id].oracle == address(0)) revert OracleNotSet(id);
        delete poolOracles[id];
        emit PoolOracleRemoved(id);
    }

    /// @inheritdoc ILevery
    function getPoolBaseFee(PoolKey calldata key) public view override returns (uint24) {
        return poolBaseFees[PoolId.unwrap(key.toId())];
    }

    /// @inheritdoc ILevery
    function getPoolRequiredRole(PoolKey calldata key) external view override returns (bytes32) {
        return poolRequiredRole[PoolId.unwrap(key.toId())];
    }

    /// @inheritdoc ILevery
    function getUserPoolPermissions(PoolKey calldata key, address account)
        external
        view
        override
        returns (bool hasRole, bool swapPerm, bool liquidityPerm)
    {
        bytes32 pid = _poolId(key);
        bytes32 rid = poolRequiredRole[pid];
        if (rid == bytes32(0)) return (true, true, true);
        Permissions memory p = rolePermissions[rid][account];
        return (p.swap || p.liquidity, p.swap, p.liquidity);
    }

    /// @inheritdoc ILevery
    function getPoolOracle(PoolKey calldata key)
        public
        view
        override
        returns (address oracle, bool compareWithPrice0)
    {
        PoolOracle storage po = poolOracles[PoolId.unwrap(key.toId())];
        return (po.oracle, po.compareWithPrice0);
    }

    /// @inheritdoc ILevery
    function getLastOraclePrice(address _oracle, PoolKey calldata key) public view override returns (int256) {
        AggregatorV3Interface priceFeed = AggregatorV3Interface(_oracle);
        uint8 feedDecimals = priceFeed.decimals();
        (, int256 answer,,,) = priceFeed.latestRoundData();
        bytes32 pid = _poolId(key);
        PoolOracle storage po = poolOracles[pid];
        bool cmp0 = po.compareWithPrice0;
        uint8 currencyDecimals = cmp0
            ? (Currency.unwrap(key.currency1) == address(0) ? 18 : IERC20(Currency.unwrap(key.currency1)).decimals())
            : (Currency.unwrap(key.currency0) == address(0) ? 18 : IERC20(Currency.unwrap(key.currency0)).decimals());

        if (feedDecimals > currencyDecimals) {
            answer = answer / int256(10 ** (feedDecimals - currencyDecimals));
        } else if (feedDecimals < currencyDecimals) {
            answer = answer * int256(10 ** (currencyDecimals - feedDecimals));
        }

        return answer;
    }

    /// @inheritdoc ILevery
    function getCurrentPrices(PoolKey calldata key) public view override returns (uint256 price0, uint256 price1) {
        (uint160 sp,,,) = StateLibrary.getSlot0(poolManager, key.toId());
        if (sp < TickMath.MIN_SQRT_PRICE || sp > TickMath.MAX_SQRT_PRICE) revert SqrtPriceOutOfBounds(sp);
        uint256 sq = FullMath.mulDiv(uint256(sp), uint256(sp), SQRT96);
        price0 = FullMath.mulDivRoundingUp(sq, 1e18, SQRT96);
        price1 = FullMath.mulDivRoundingUp(SQRT96, 1e18, sq);
        if (price0 == 0) revert Price0CalculationError(price0);
        if (price1 == 0) revert Price1CalculationError(price1);
    }

    /// @inheritdoc ILevery
    function getHookPermissions() public pure override(BaseHook, ILevery) returns (Hooks.Permissions memory) {
        return Hooks.Permissions({
            beforeInitialize: true,
            afterInitialize: false,
            beforeAddLiquidity: true,
            afterAddLiquidity: false,
            beforeRemoveLiquidity: true,
            afterRemoveLiquidity: false,
            beforeSwap: true,
            afterSwap: true,
            beforeDonate: false,
            afterDonate: false,
            beforeSwapReturnDelta: true,
            afterSwapReturnDelta: true,
            afterAddLiquidityReturnDelta: false,
            afterRemoveLiquidityReturnDelta: false
        });
    }
    // ─────────────── Internal Helpers & Hooks ───────────────

    /// @dev Returns the canonical pool identifier for a given PoolKey.
    /// @param key The PoolKey struct identifying the pool.
    /// @return pid The 32-byte pool identifier.
    function _poolId(PoolKey calldata key) private pure returns (bytes32 pid) {
        pid = PoolId.unwrap(key.toId());
    }

    /// @dev Calculates LP fee by applying a deviation multiplier when pool price diverges from the oracle market price.
    /// Uses pool base fee if set, else global fee.
    /// Fee adjustment is direction-sensitive based on swap side (`zeroForOne`).
    /// Reverts if the oracle price is zero.
    /// @param key PoolKey identifying the pool.
    /// @param price0 On‑chain price of token0.
    /// @param price1 On‑chain price of token1.
    /// @param zeroForOne Direction of the swap.
    /// @param currentFee Baseline fee in basis points.
    /// @return newSwapFee Adjusted fee in basis points.
    function _adjustSwapFee(PoolKey calldata key, uint256 price0, uint256 price1, bool zeroForOne, uint24 currentFee)
        internal
        view
        returns (uint24 newSwapFee)
    {
        newSwapFee = getPoolBaseFee(key) != 0 ? getPoolBaseFee(key) : currentFee;
        PoolOracle memory po = poolOracles[PoolId.unwrap(key.toId())];
        if (po.oracle != address(0)) {
            uint256 mp = uint256(getLastOraclePrice(po.oracle, key));
            if (mp == 0) revert OraclePriceZero();
            if (po.compareWithPrice0) {
                if (price0 > mp && zeroForOne) {
                    newSwapFee += uint24(((price0 - mp) * deviationFeeFactor) / mp);
                } else if (price0 < mp && !zeroForOne) {
                    newSwapFee += uint24(((mp - price0) * deviationFeeFactor) / mp);
                }
            } else {
                if (price1 < mp && zeroForOne) {
                    newSwapFee += uint24(((mp - price1) * deviationFeeFactor) / mp);
                } else if (price1 > mp && !zeroForOne) {
                    newSwapFee += uint24(((price1 - mp) * deviationFeeFactor) / mp);
                }
            }
        }
    }

    /// @dev Calculates and deducts the service fee for exact-input swaps.
    /// The fee is taken directly from the input amount and transferred to the service fee vault.
    /// Assumes `params.amountSpecified` is negative.
    /// @param key PoolKey identifying the pool.
    /// @param params Swap parameters.
    /// @return selector Hook selector to return.
    /// @return delta Fee delta encoded as BeforeSwapDelta.
    /// @return feeOverride Always zero (no LP fee override).
    function _handleExactInputServiceFee(PoolKey calldata key, IPoolManager.SwapParams calldata params)
        private
        returns (bytes4 selector, BeforeSwapDelta delta, uint24 feeOverride)
    {
        int256 fee256 = (-params.amountSpecified * int256(serviceFee)) / int256(MAX_PPM);
        require(fee256 <= type(int128).max && fee256 >= type(int128).min, "Fee overflow");
        int128 fee = int128(fee256);
        delta = toBeforeSwapDelta(fee, 0);
        Currency token = params.zeroForOne ? key.currency0 : key.currency1;
        poolManager.take(token, serviceFeeVault, uint256(fee256));
        return (this.beforeSwap.selector, delta, 0);
    }

    /// @dev Calculates dynamic LP fee for a given swap direction based on the pool price and oracle deviation logic.
    /// Starts from the global base fee and adjusts it if needed based on pool-specific settings and price deviation.
    /// @param key PoolKey identifying the pool.
    /// @param zeroForOne Direction of the swap.
    /// @return adjustedFee Adjusted LP fee in basis points.
    function _computeDynamicFee(PoolKey calldata key, bool zeroForOne) private view returns (uint24 adjustedFee) {
        (uint256 p0, uint256 p1) = getCurrentPrices(key);
        return _adjustSwapFee(key, p0, p1, zeroForOne, baseFee);
    }

    /// @dev Verifies that sender is swapRouter or quoter and that user has swap permission.
    /// @param sender Caller address.
    /// @param hookData ABI‑encoded user address.
    /// @return user Decoded user address.
    function _checkSwapPermissions(address sender, bytes calldata hookData) private view returns (address user) {
        if (sender != swapRouter && sender != quoter) revert UnapprovedSwapRouterOrQuoter(sender);
        user = abi.decode(hookData, (address));
        if (!permissionManager.isSwapAllowed(user)) revert SwapNotAllowed(user);
    }

    /// @dev Ensures the caller and position owner meet liquidity permissions before modifying positions.
    /// @param sender The address invoking the hook (should be the PositionManager).
    /// @param key    The PoolKey identifying the target pool.
    /// @param salt   The position identifier salt (as bytes32) used to derive the NFT token ID.
    function _ensureLiquidityPermission(address sender, PoolKey calldata key, bytes32 salt) internal view {
        if (sender != positionManager) revert UnapprovedPositionManager(sender);
        address owner = IERC721(positionManager).ownerOf(uint256(salt));
        if (!permissionManager.isLiquidityAllowed(owner)) revert LiquidityNotAllowed(owner);
        bytes32 pid = _poolId(key);
        bytes32 rid = poolRequiredRole[pid];
        if (rid != bytes32(0) && !rolePermissions[rid][owner].liquidity) {
            revert RoleRequired(pid, rid);
        }
    }

    /// @dev Hook triggered before a pool is initialized in the PoolManager.
    /// Ensures that only the designated institution address can initialize new pools.
    /// Function will revert if called while the contract is paused.
    /// @param sender Caller address.
    /// unused param key PoolKey identifying the pool.
    /// unused param sqrtPriceX96 Initial sqrtPriceX96 value.
    /// @return selector Selector for beforeInitialize hook.
    function _beforeInitialize(address sender, PoolKey calldata, uint160)
        internal
        view
        override
        whenNotPaused
        returns (bytes4 selector)
    {
        if (sender != institution) revert NotInstitution(sender);
        return BaseHook.beforeInitialize.selector;
    }

    /// @dev Hook before adding liquidity; verifies position ownership and liquidity permission.
    /// @param sender Caller address.
    /// @param key PoolKey identifying the pool.
    /// @param params Parameters for modifying liquidity.
    /// unused param hookData.
    /// @return selector Selector for beforeAddLiquidity hook.
    function _beforeAddLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        bytes calldata
    ) internal view override whenPoolNotPaused(key) returns (bytes4 selector) {
        _ensureLiquidityPermission(sender, key, params.salt);
        return BaseHook.beforeAddLiquidity.selector;
    }

    /// @dev Hook before removing liquidity; verifies position ownership and liquidity permission.
    /// @param sender Caller address.
    /// @param key PoolKey identifying the pool.
    /// @param params Parameters for modifying liquidity.
    /// unused param hookData.
    /// @return selector Selector for beforeRemoveLiquidity hook.
    function _beforeRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        bytes calldata
    ) internal view override whenPoolNotPaused(key) returns (bytes4 selector) {
        _ensureLiquidityPermission(sender, key, params.salt);
        return BaseHook.beforeRemoveLiquidity.selector;
    }

    /// @dev Hook executed before a swap; authorizes caller, enforces roles, updates LP fee, and handles service fee.
    /// @param sender Caller address (swapRouter or quoter).
    /// @param key PoolKey identifying the pool.
    /// @param params Swap parameters.
    /// @param hookData ABI‑encoded user address.
    /// @return selector Selector for beforeSwap hook.
    /// @return delta Fee delta to apply before swap.
    /// @return newFee LP fee override (zero if none).
    function _beforeSwap(
        address sender,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        bytes calldata hookData
    ) internal override whenPoolNotPaused(key) returns (bytes4 selector, BeforeSwapDelta delta, uint24 newFee) {
        address user = _checkSwapPermissions(sender, hookData);
        bytes32 pid = _poolId(key);
        bytes32 rid = poolRequiredRole[pid];
        if (rid != bytes32(0) && !rolePermissions[rid][user].swap) {
            revert RoleRequired(pid, rid);
        }
        poolManager.updateDynamicLPFee(key, _computeDynamicFee(key, params.zeroForOne));
        if (params.amountSpecified < 0) {
            return _handleExactInputServiceFee(key, params);
        }
        return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
    }

    /// @dev Hook after swap; deducts service fee on exact‑output swaps.
    /// unused param sender Caller address.
    /// @param key PoolKey identifying the pool.
    /// @param params Swap parameters.
    /// @param delta Balance change from swap.
    /// unused param hookData.
    /// @return selector Selector for afterSwap hook.
    /// @return collect Amount of service fee to collect.
    function _afterSwap(
        address,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata
    ) internal override returns (bytes4 selector, int128 collect) {
        if (params.amountSpecified > 0) {
            int128 inputDelta = params.zeroForOne ? delta.amount0() : delta.amount1();
            int256 fee256 = (-inputDelta * int256(serviceFee)) / int256(MAX_PPM);
            require(fee256 <= type(int128).max && fee256 >= type(int128).min, "Fee overflow");
            Currency token = params.zeroForOne ? key.currency0 : key.currency1;
            poolManager.take(token, serviceFeeVault, uint256(fee256));
            return (BaseHook.afterSwap.selector, int128(fee256));
        }
        return (BaseHook.afterSwap.selector, 0);
    }
}

File 2 of 36 : ILevery.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;

import {Hooks} from "v4-core/src/libraries/Hooks.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {IPermissionManager} from "./IPermissionManager.sol";

/// @title ILevery
/// @notice Interface for the Levery dynamic‑fee & oracle hook contract on Uniswap V4.
interface ILevery {
    // ─────────────── Errors ───────────────

    /// @notice Thrown when a caller is not the configured provider.
    /// @param sender Address of the caller.
    error NotProvider(address sender);

    /// @notice Thrown when a caller is not the configured institution.
    /// @param sender Address of the caller.
    error NotInstitution(address sender);

    /// @notice Thrown when attempting to interact with a paused pool.
    /// @param poolId Identifier of the pool.
    error PoolIsPaused(bytes32 poolId);

    /// @notice Thrown when the entire contract is paused.
    error ContractPaused();

    /// @notice Thrown when attempting to create a role that already exists.
    /// @param roleId Identifier of the role.
    error RoleAlreadyExists(bytes32 roleId);

    /// @notice Thrown when referencing a role that does not exist.
    /// @param roleId Identifier of the role.
    error RoleDoesNotExist(bytes32 roleId);

    /// @notice Thrown when a user without liquidity permission tries to add or remove liquidity.
    /// @param user Address of the user.
    error LiquidityNotAllowed(address user);

    /// @notice Thrown when a user without swap permission tries to execute a swap.
    /// @param user Address of the user.
    error SwapNotAllowed(address user);

    /// @notice Thrown when an unapproved contract calls a liquidity hook.
    /// @param sender Address of the caller.
    error UnapprovedPositionManager(address sender);

    /// @notice Thrown when an unapproved contract calls a swap hook.
    /// @param sender Address of the caller.
    error UnapprovedSwapRouterOrQuoter(address sender);

    /// @notice Thrown when the user lacks a specific role required by the pool.
    /// @param poolId Identifier of the pool.
    /// @param roleId Identifier of the required role.
    error RoleRequired(bytes32 poolId, bytes32 roleId);

    /// @notice Thrown when attempting to remove a pool oracle that doesn't exist.
    /// @param poolId Identifier of the pool.
    error OracleNotSet(bytes32 poolId);

    /// @notice Thrown when the deviation fee factor exceeds the maximum allowed.
    /// @param multiplier The provided multiplier.
    error DeviationFeeFactorTooLarge(uint256 multiplier);

    /// @notice Thrown when the on‑chain sqrt price is outside acceptable bounds.
    /// @param sqrtPriceX96 The raw sqrt price.
    error SqrtPriceOutOfBounds(uint160 sqrtPriceX96);

    /// @notice Thrown when computed token0 price is zero.
    /// @param price0 The computed price.
    error Price0CalculationError(uint256 price0);

    /// @notice Thrown when computed token1 price is zero.
    /// @param price1 The computed price.
    error Price1CalculationError(uint256 price1);

    /// @notice Thrown when the oracle reports a zero market price.
    error OraclePriceZero();

    /// @notice Thrown when a zero address is passed to a setter function.
    error ZeroAddress();

    /// @notice Thrown when the new base fee exceeds the maximum allowed.
    /// @param fee base fee value that was attempted to be set.
    error BaseFeeTooLarge(uint24 fee);

    /// @notice Thrown when the new service fee exceeds the maximum allowed.
    /// @param serviceFee the service fee value that was attempted to be set.
    error ServiceFeeTooLarge(uint256 serviceFee);

    // ─────────────── Events ───────────────

    /// @notice Emitted when the provider address is updated.
    /// @param oldProvider Previous provider.
    /// @param newProvider New provider.
    event ProviderUpdated(address indexed oldProvider, address indexed newProvider);

    /// @notice Emitted when the institution address is updated.
    /// @param oldInstitution Previous institution.
    /// @param newInstitution New institution.
    event InstitutionUpdated(address indexed oldInstitution, address indexed newInstitution);

    /// @notice Emitted when the PositionManager address is updated.
    /// @param oldManager Previous PositionManager.
    /// @param newManager New PositionManager.
    event PositionManagerUpdated(address indexed oldManager, address indexed newManager);

    /// @notice Emitted when the SwapRouter address is updated.
    /// @param oldRouter Previous SwapRouter.
    /// @param newRouter New SwapRouter.
    event SwapRouterUpdated(address indexed oldRouter, address indexed newRouter);

    /// @notice Emitted when the Quoter address is updated.
    /// @param oldQuoter Previous Quoter.
    /// @param newQuoter New Quoter.
    event QuoterUpdated(address indexed oldQuoter, address indexed newQuoter);

    /// @notice Emitted when the service fee vault address is updated.
    /// @param oldVault Previous vault.
    /// @param newVault New vault.
    event ServiceFeeVaultUpdated(address indexed oldVault, address indexed newVault);

    /// @notice Emitted when the global base fee is updated.
    /// @param oldFee Previous base fee (bps).
    /// @param newFee New base fee (bps).
    event BaseFeeUpdated(uint24 indexed oldFee, uint24 indexed newFee);

    /// @notice Emitted when the deviation fee factor is updated.
    /// @param oldMultiplier Previous multiplier.
    /// @param newMultiplier New multiplier.
    event DeviationFeeFactorUpdated(uint256 indexed oldMultiplier, uint256 indexed newMultiplier);

    /// @notice Emitted when a specific pool’s base fee is set.
    /// @param poolId Identifier of the pool.
    /// @param newBaseFee New base fee (bps).
    event PoolBaseFeeSet(bytes32 indexed poolId, uint24 newBaseFee);

    /// @notice Emitted when a pool’s oracle configuration is set.
    /// @param poolId Identifier of the pool.
    /// @param oracle Address of the aggregator.
    /// @param compareWithPrice0 Flag to compare with token0 price.
    event PoolOracleSet(bytes32 indexed poolId, address oracle, bool compareWithPrice0);

    /// @notice Emitted when a pool is paused.
    /// @param poolId Identifier of the pool.
    event PoolPaused(bytes32 indexed poolId);

    /// @notice Emitted when a pool is unpaused.
    /// @param poolId Identifier of the pool.
    event PoolUnpaused(bytes32 indexed poolId);

    /// @notice Emitted when a pool’s oracle is removed.
    /// @param poolId Identifier of the pool.
    event PoolOracleRemoved(bytes32 indexed poolId);

    /// @notice Emitted when a new role is created.
    /// @param roleId Identifier of the role.
    event RoleCreated(bytes32 indexed roleId);

    /// @notice Emitted when a user’s role permissions are assigned.
    /// @param roleId Identifier of the role.
    /// @param account Address of the user.
    /// @param swap Whether swaps are allowed.
    /// @param liquidity Whether liquidity is allowed.
    event UserRoleAssigned(bytes32 indexed roleId, address indexed account, bool swap, bool liquidity);

    /// @notice Emitted when a pool’s required role is set.
    /// @param poolId Identifier of the pool.
    /// @param roleId Identifier of the role.
    event PoolRequiredRoleSet(bytes32 indexed poolId, bytes32 indexed roleId);

    /// @notice Emitted when a pool’s required role is cleared.
    /// @param poolId Identifier of the pool.
    /// @param roleId Previous role.
    event PoolRequiredRoleCleared(bytes32 indexed poolId, bytes32 indexed roleId);

    /// @notice Emitted when the service fee percentage is updated.
    /// @param oldFee Previous service fee (bps).
    /// @param newFee New service fee (bps).
    event ServiceFeeUpdated(uint256 indexed oldFee, uint256 indexed newFee);

    /// @notice Emitted when the PermissionManager address is updated.
    /// @param oldManager Previous manager.
    /// @param newManager New manager.
    event PermissionManagerUpdated(address indexed oldManager, address indexed newManager);

    /// @notice Emitted when a user’s role is revoked.
    /// @param roleId Identifier of the role.
    /// @param account Address of the user.
    event UserRoleRevoked(bytes32 indexed roleId, address indexed account);

    // ─────────────── Circuit‑breaker ───────────────

    /// @notice Pauses all contract operations.
    function pause() external;

    /// @notice Unpauses all contract operations.
    function unpause() external;

    /// @notice Pauses a single pool.
    /// @param key PoolKey identifying the pool.
    function pausePool(PoolKey calldata key) external;

    /// @notice Unpauses a single pool.
    /// @param key PoolKey identifying the pool.
    function unpausePool(PoolKey calldata key) external;

    // ─────────────── Admin Updaters ───────────────

    /// @notice Updates the provider address.
    /// @param _provider New provider address.
    function updateProvider(address _provider) external;

    /// @notice Updates the institution address.
    /// @param _institution New institution address.
    function updateInstitution(address _institution) external;

    /// @notice Updates the PositionManager contract address.
    /// @param _positionManager New PositionManager address.
    function updatePositionManager(address _positionManager) external;

    /// @notice Updates the SwapRouter contract address.
    /// @param _swapRouter New swap router address.
    function updateSwapRouter(address _swapRouter) external;

    /// @notice Updates the Quoter contract address.
    /// @param _quoter New Quoter address.
    function updateQuoter(address _quoter) external;

    /// @notice Updates the service fee vault address.
    /// @param _serviceFeeVault New vault address.
    function updateServiceFeeVault(address _serviceFeeVault) external;

    /// @notice Updates the PermissionManager contract address.
    /// @param _permissionManager New PermissionManager address.
    function updatePermissionManager(IPermissionManager _permissionManager) external;

    // ─────────────── Fee Setters ───────────────

    /// @notice Updates the service fee for all pools.
    /// @param _serviceFee New service fee in basis points (e.g., 1000 = 0.1%).
    function updateServiceFee(uint256 _serviceFee) external;

    /// @notice Updates the global base swap fee.
    /// @param _baseFee New base fee in basis points.
    function updateBaseFee(uint24 _baseFee) external;

    /// @notice Updates the deviation multiplier for dynamic fees.
    /// @param _deviationFeeFactor New multiplier (max 1,000,000).
    function setDeviationFeeFactor(uint256 _deviationFeeFactor) external;

    /// @notice Sets a custom base fee for a pool.
    /// @param key PoolKey identifying the pool.
    /// @param _baseFee New base fee in basis points.
    function setPoolBaseFee(PoolKey calldata key, uint24 _baseFee) external;

    // ─────────────── Role Management ───────────────

    /// @notice Creates a new role identifier.
    /// @param roleId Identifier of the new role.
    function createRole(bytes32 roleId) external;

    /// @notice Assigns swap and liquidity permissions under a role.
    /// @param roleId Identifier of the role.
    /// @param account Address to grant permissions.
    /// @param swap Whether swaps are allowed.
    /// @param liquidity Whether liquidity changes are allowed.
    function setRoleForUser(bytes32 roleId, address account, bool swap, bool liquidity) external;

    /// @notice Revokes a user’s role permissions.
    /// @param roleId Identifier of the role.
    /// @param account Address whose permissions are revoked.
    function revokeUserRole(bytes32 roleId, address account) external;

    /// @notice Sets the required role for a pool.
    /// @param key PoolKey identifying the pool.
    /// @param roleId Role identifier to require.
    function setPoolRequiredRole(PoolKey calldata key, bytes32 roleId) external;

    /// @notice Clears the required role for a pool.
    /// @param key PoolKey identifying the pool.
    function clearPoolRequiredRole(PoolKey calldata key) external;

    // ─────────────── Oracle Management ───────────────

    /// @notice Sets the oracle and comparison flag for a pool.
    /// @param key PoolKey identifying the pool.
    /// @param _oracle Address of the aggregator.
    /// @param _compareWithPrice0 Whether to compare with token0 price.
    function setPoolOracle(PoolKey calldata key, address _oracle, bool _compareWithPrice0) external;

    /// @notice Removes the oracle configuration for a pool.
    /// @param key PoolKey identifying the pool.
    function removePoolOracle(PoolKey calldata key) external;

    // ─────────────── View / Query ───────────────

    /// @notice Returns the base fee for a pool, if the pool has no custom base fee set, this function returns zero.
    /// @param key PoolKey identifying the pool.
    /// @return Base fee in basis points.
    function getPoolBaseFee(PoolKey calldata key) external view returns (uint24);

    /// @notice Returns the required role for a pool. If no role is required for the pool, this function returns zero.
    /// @param key PoolKey identifying the pool.
    /// @return roleId Role identifier or zero.
    function getPoolRequiredRole(PoolKey calldata key) external view returns (bytes32 roleId);

    /// @notice Returns a user’s swap and liquidity permissions for a pool.
    /// If the pool does not require any role, all users are allowed and the function returns (true, true, true).
    /// If the pool requires a role, returns whether the user has that role and their swap and liquidity permissions.
    /// @param key PoolKey identifying the pool.
    /// @param account User address.
    /// @return hasRole True if user meets role requirement.
    /// @return swapPerm True if swaps allowed.
    /// @return liquidityPerm True if liquidity allowed.
    function getUserPoolPermissions(PoolKey calldata key, address account)
        external
        view
        returns (bool hasRole, bool swapPerm, bool liquidityPerm);

    /// @notice Returns the oracle and comparison flag for a pool.
    /// @dev If no oracle is configured for the pool, returns `(address(0), false)`.
    /// @param key PoolKey identifying the pool.
    /// @return oracle Address of the aggregator.
    /// @return compareWithPrice0 Comparison flag.
    function getPoolOracle(PoolKey calldata key) external view returns (address oracle, bool compareWithPrice0);

    /// @notice Fetches the latest price from a Chainlink aggregator and scales it.
    /// @param _oracle Address of the aggregator.
    /// @param key PoolKey identifying the pool.
    /// @return answer Adjusted price in token units.
    function getLastOraclePrice(address _oracle, PoolKey calldata key) external view returns (int256 answer);

    /// @notice Computes current on‑chain token prices for a pool.
    /// @param key PoolKey identifying the pool.
    /// @return price0 Price of token0 (wei).
    /// @return price1 Price of token1 (wei).
    function getCurrentPrices(PoolKey calldata key) external view returns (uint256 price0, uint256 price1);

    /// @notice Returns which hooks are enabled by this contract.
    /// This informs the PoolManager which hook callbacks are implemented.
    /// @return Permissions struct indicating enabled hooks.
    function getHookPermissions() external pure returns (Hooks.Permissions memory);

    // ─────────────── Public Contract References ───────────────

    /// @notice Address of the PositionManager used by this hook.
    /// @return The PositionManager contract address.
    function positionManager() external view returns (address);

    /// @notice Address of the SwapRouter used by this hook.
    /// @return The SwapRouter contract address.
    function swapRouter() external view returns (address);

    /// @notice Address of the Quoter used by this hook.
    /// @return The Quoter contract address.
    function quoter() external view returns (address);

    /// @notice Address of the vault where all service‑fees are collected.
    /// @return The service fee vault address.
    function serviceFeeVault() external view returns (address);

    /// @notice Address with “provider” privileges (can pause/unpause contract).
    /// @return The provider address.
    function provider() external view returns (address);

    /// @notice Address with “institution” privileges (can configure pools).
    /// @return The institution address.
    function institution() external view returns (address);

    /// @notice Returns the contract responsible for swap and liquidity permission checks.
    /// @return The IPermissionManager implementation used by this hook.
    function permissionManager() external view returns (IPermissionManager);

    // ─────────────── Fee Parameters ───────────────

    /// @notice Global base swap fee, in basis points.
    /// @return The base fee (bps).
    function baseFee() external view returns (uint24);

    /// @notice Global service fee, in parts‑per‑million.
    /// @return The service fee (ppm).
    function serviceFee() external view returns (uint256);

    /// @notice Deviation multiplier for dynamic LP‑fees.
    /// @return The deviation fee factor.
    function deviationFeeFactor() external view returns (uint256);

    // ─────────────── Pool‑Specific Mappings ───────────────

    /// @notice Custom base fee for a specific pool.
    /// @param poolId The pool identifier.
    /// @return The pool‑specific base fee (bps).
    function poolBaseFees(bytes32 poolId) external view returns (uint24);

    /// @notice Oracle configuration for a specific pool.
    /// @param poolId The pool identifier.
    /// @return oracle Address of the price feed.
    /// @return compareWithPrice0 Whether to compare on‑chain price0 with the feed.
    function poolOracles(bytes32 poolId) external view returns (address oracle, bool compareWithPrice0);

    /// @notice Pause status of a specific pool.
    /// @param poolId The pool identifier.
    /// @return True if the pool is paused, false otherwise.
    function poolPaused(bytes32 poolId) external view returns (bool);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {BeforeSwapDelta} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {ImmutableState} from "../base/ImmutableState.sol";

/// @title Base Hook
/// @notice abstract contract for hook implementations
abstract contract BaseHook is IHooks, ImmutableState {
    error HookNotImplemented();

    constructor(IPoolManager _manager) ImmutableState(_manager) {
        validateHookAddress(this);
    }

    /// @notice Returns a struct of permissions to signal which hook functions are to be implemented
    /// @dev Used at deployment to validate the address correctly represents the expected permissions
    function getHookPermissions() public pure virtual returns (Hooks.Permissions memory);

    /// @notice Validates the deployed hook address agrees with the expected permissions of the hook
    /// @dev this function is virtual so that we can override it during testing,
    /// which allows us to deploy an implementation to any address
    /// and then etch the bytecode into the correct address
    function validateHookAddress(BaseHook _this) internal pure virtual {
        Hooks.validateHookPermissions(_this, getHookPermissions());
    }

    /// @inheritdoc IHooks
    function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96)
        external
        onlyPoolManager
        returns (bytes4)
    {
        return _beforeInitialize(sender, key, sqrtPriceX96);
    }

    function _beforeInitialize(address, PoolKey calldata, uint160) internal virtual returns (bytes4) {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
        external
        onlyPoolManager
        returns (bytes4)
    {
        return _afterInitialize(sender, key, sqrtPriceX96, tick);
    }

    function _afterInitialize(address, PoolKey calldata, uint160, int24) internal virtual returns (bytes4) {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function beforeAddLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4) {
        return _beforeAddLiquidity(sender, key, params, hookData);
    }

    function _beforeAddLiquidity(address, PoolKey calldata, IPoolManager.ModifyLiquidityParams calldata, bytes calldata)
        internal
        virtual
        returns (bytes4)
    {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function beforeRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4) {
        return _beforeRemoveLiquidity(sender, key, params, hookData);
    }

    function _beforeRemoveLiquidity(
        address,
        PoolKey calldata,
        IPoolManager.ModifyLiquidityParams calldata,
        bytes calldata
    ) internal virtual returns (bytes4) {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function afterAddLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4, BalanceDelta) {
        return _afterAddLiquidity(sender, key, params, delta, feesAccrued, hookData);
    }

    function _afterAddLiquidity(
        address,
        PoolKey calldata,
        IPoolManager.ModifyLiquidityParams calldata,
        BalanceDelta,
        BalanceDelta,
        bytes calldata
    ) internal virtual returns (bytes4, BalanceDelta) {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function afterRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4, BalanceDelta) {
        return _afterRemoveLiquidity(sender, key, params, delta, feesAccrued, hookData);
    }

    function _afterRemoveLiquidity(
        address,
        PoolKey calldata,
        IPoolManager.ModifyLiquidityParams calldata,
        BalanceDelta,
        BalanceDelta,
        bytes calldata
    ) internal virtual returns (bytes4, BalanceDelta) {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function beforeSwap(
        address sender,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4, BeforeSwapDelta, uint24) {
        return _beforeSwap(sender, key, params, hookData);
    }

    function _beforeSwap(address, PoolKey calldata, IPoolManager.SwapParams calldata, bytes calldata)
        internal
        virtual
        returns (bytes4, BeforeSwapDelta, uint24)
    {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function afterSwap(
        address sender,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4, int128) {
        return _afterSwap(sender, key, params, delta, hookData);
    }

    function _afterSwap(address, PoolKey calldata, IPoolManager.SwapParams calldata, BalanceDelta, bytes calldata)
        internal
        virtual
        returns (bytes4, int128)
    {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function beforeDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4) {
        return _beforeDonate(sender, key, amount0, amount1, hookData);
    }

    function _beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
        internal
        virtual
        returns (bytes4)
    {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function afterDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4) {
        return _afterDonate(sender, key, amount0, amount1, hookData);
    }

    function _afterDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
        internal
        virtual
        returns (bytes4)
    {
        revert HookNotImplemented();
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {SafeCast} from "./SafeCast.sol";
import {LPFeeLibrary} from "./LPFeeLibrary.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {ParseBytes} from "./ParseBytes.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
library Hooks {
    using LPFeeLibrary for uint24;
    using Hooks for IHooks;
    using SafeCast for int256;
    using BeforeSwapDeltaLibrary for BeforeSwapDelta;
    using ParseBytes for bytes;
    using CustomRevert for bytes4;

    uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1);

    uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13;
    uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12;

    uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11;
    uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10;

    uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9;
    uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8;

    uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7;
    uint160 internal constant AFTER_SWAP_FLAG = 1 << 6;

    uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5;
    uint160 internal constant AFTER_DONATE_FLAG = 1 << 4;

    uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3;
    uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2;
    uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1;
    uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0;

    struct Permissions {
        bool beforeInitialize;
        bool afterInitialize;
        bool beforeAddLiquidity;
        bool afterAddLiquidity;
        bool beforeRemoveLiquidity;
        bool afterRemoveLiquidity;
        bool beforeSwap;
        bool afterSwap;
        bool beforeDonate;
        bool afterDonate;
        bool beforeSwapReturnDelta;
        bool afterSwapReturnDelta;
        bool afterAddLiquidityReturnDelta;
        bool afterRemoveLiquidityReturnDelta;
    }

    /// @notice Thrown if the address will not lead to the specified hook calls being called
    /// @param hooks The address of the hooks contract
    error HookAddressNotValid(address hooks);

    /// @notice Hook did not return its selector
    error InvalidHookResponse();

    /// @notice Additional context for ERC-7751 wrapped error when a hook call fails
    error HookCallFailed();

    /// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa
    error HookDeltaExceedsSwapAmount();

    /// @notice Utility function intended to be used in hook constructors to ensure
    /// the deployed hooks address causes the intended hooks to be called
    /// @param permissions The hooks that are intended to be called
    /// @dev permissions param is memory as the function will be called from constructors
    function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure {
        if (
            permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG)
                || permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG)
                || permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)
                || permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)
                || permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)
                || permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
                || permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG)
                || permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG)
                || permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG)
                || permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG)
                || permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)
                || permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
                || permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
                || permissions.afterRemoveLiquidityReturnDelta
                    != self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
        ) {
            HookAddressNotValid.selector.revertWith(address(self));
        }
    }

    /// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address
    /// @param self The hook to verify
    /// @param fee The fee of the pool the hook is used with
    /// @return bool True if the hook address is valid
    function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) {
        // The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag
        if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false;
        if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false;
        if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG))
        {
            return false;
        }
        if (
            !self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
                && self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
        ) return false;

        // If there is no hook contract set, then fee cannot be dynamic
        // If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee
        return address(self) == address(0)
            ? !fee.isDynamicFee()
            : (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee());
    }

    /// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta
    /// @return result The complete data returned by the hook
    function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {
        bool success;
        assembly ("memory-safe") {
            success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)
        }
        // Revert with FailedHookCall, containing any error message to bubble up
        if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);

        // The call was successful, fetch the returned data
        assembly ("memory-safe") {
            // allocate result byte array from the free memory pointer
            result := mload(0x40)
            // store new free memory pointer at the end of the array padded to 32 bytes
            mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))
            // store length in memory
            mstore(result, returndatasize())
            // copy return data to result
            returndatacopy(add(result, 0x20), 0, returndatasize())
        }

        // Length must be at least 32 to contain the selector. Check expected selector and returned selector match.
        if (result.length < 32 || result.parseSelector() != data.parseSelector()) {
            InvalidHookResponse.selector.revertWith();
        }
    }

    /// @notice performs a hook call using the given calldata on the given hook
    /// @return int256 The delta returned by the hook
    function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) {
        bytes memory result = callHook(self, data);

        // If this hook wasn't meant to return something, default to 0 delta
        if (!parseReturn) return 0;

        // A length of 64 bytes is required to return a bytes4, and a 32 byte delta
        if (result.length != 64) InvalidHookResponse.selector.revertWith();
        return result.parseReturnDelta();
    }

    /// @notice modifier to prevent calling a hook if they initiated the action
    modifier noSelfCall(IHooks self) {
        if (msg.sender != address(self)) {
            _;
        }
    }

    /// @notice calls beforeInitialize hook if permissioned and validates return value
    function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) {
        if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96)));
        }
    }

    /// @notice calls afterInitialize hook if permissioned and validates return value
    function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(AFTER_INITIALIZE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick)));
        }
    }

    /// @notice calls beforeModifyLiquidity hook if permissioned and validates return value
    function beforeModifyLiquidity(
        IHooks self,
        PoolKey memory key,
        IPoolManager.ModifyLiquidityParams memory params,
        bytes calldata hookData
    ) internal noSelfCall(self) {
        if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData)));
        } else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData)));
        }
    }

    /// @notice calls afterModifyLiquidity hook if permissioned and validates return value
    function afterModifyLiquidity(
        IHooks self,
        PoolKey memory key,
        IPoolManager.ModifyLiquidityParams memory params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {
        if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA);

        callerDelta = delta;
        if (params.liquidityDelta > 0) {
            if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) {
                hookDelta = BalanceDelta.wrap(
                    self.callHookWithReturnDelta(
                        abi.encodeCall(
                            IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
                        ),
                        self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
                    )
                );
                callerDelta = callerDelta - hookDelta;
            }
        } else {
            if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) {
                hookDelta = BalanceDelta.wrap(
                    self.callHookWithReturnDelta(
                        abi.encodeCall(
                            IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
                        ),
                        self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
                    )
                );
                callerDelta = callerDelta - hookDelta;
            }
        }
    }

    /// @notice calls beforeSwap hook if permissioned and validates return value
    function beforeSwap(IHooks self, PoolKey memory key, IPoolManager.SwapParams memory params, bytes calldata hookData)
        internal
        returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride)
    {
        amountToSwap = params.amountSpecified;
        if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride);

        if (self.hasPermission(BEFORE_SWAP_FLAG)) {
            bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData)));

            // A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee
            if (result.length != 96) InvalidHookResponse.selector.revertWith();

            // dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag
            // is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used
            if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee();

            // skip this logic for the case where the hook return is 0
            if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {
                hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());

                // any return in unspecified is passed to the afterSwap hook for handling
                int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();

                // Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)
                if (hookDeltaSpecified != 0) {
                    bool exactInput = amountToSwap < 0;
                    amountToSwap += hookDeltaSpecified;
                    if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {
                        HookDeltaExceedsSwapAmount.selector.revertWith();
                    }
                }
            }
        }
    }

    /// @notice calls afterSwap hook if permissioned and validates return value
    function afterSwap(
        IHooks self,
        PoolKey memory key,
        IPoolManager.SwapParams memory params,
        BalanceDelta swapDelta,
        bytes calldata hookData,
        BeforeSwapDelta beforeSwapHookReturn
    ) internal returns (BalanceDelta, BalanceDelta) {
        if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA);

        int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta();
        int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta();

        if (self.hasPermission(AFTER_SWAP_FLAG)) {
            hookDeltaUnspecified += self.callHookWithReturnDelta(
                abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)),
                self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
            ).toInt128();
        }

        BalanceDelta hookDelta;
        if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {
            hookDelta = (params.amountSpecified < 0 == params.zeroForOne)
                ? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)
                : toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);

            // the caller has to pay for (or receive) the hook's delta
            swapDelta = swapDelta - hookDelta;
        }
        return (swapDelta, hookDelta);
    }

    /// @notice calls beforeDonate hook if permissioned and validates return value
    function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(BEFORE_DONATE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData)));
        }
    }

    /// @notice calls afterDonate hook if permissioned and validates return value
    function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(AFTER_DONATE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData)));
        }
    }

    function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) {
        return uint160(address(self)) & flag != 0;
    }
}

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

import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";

/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
    /// @notice Thrown when a currency is not netted out after the contract is unlocked
    error CurrencyNotSettled();

    /// @notice Thrown when trying to interact with a non-initialized pool
    error PoolNotInitialized();

    /// @notice Thrown when unlock is called, but the contract is already unlocked
    error AlreadyUnlocked();

    /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
    error ManagerLocked();

    /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
    error TickSpacingTooLarge(int24 tickSpacing);

    /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
    error TickSpacingTooSmall(int24 tickSpacing);

    /// @notice PoolKey must have currencies where address(currency0) < address(currency1)
    error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);

    /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
    /// or on a pool that does not have a dynamic swap fee.
    error UnauthorizedDynamicLPFeeUpdate();

    /// @notice Thrown when trying to swap amount of 0
    error SwapAmountCannotBeZero();

    ///@notice Thrown when native currency is passed to a non native settlement
    error NonzeroNativeValue();

    /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
    error MustClearExactPositiveDelta();

    /// @notice Emitted when a new pool is initialized
    /// @param id The abi encoded hash of the pool key struct for the new pool
    /// @param currency0 The first currency of the pool by address sort order
    /// @param currency1 The second currency of the pool by address sort order
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks
    /// @param hooks The hooks contract address for the pool, or address(0) if none
    /// @param sqrtPriceX96 The price of the pool on initialization
    /// @param tick The initial tick of the pool corresponding to the initialized price
    event Initialize(
        PoolId indexed id,
        Currency indexed currency0,
        Currency indexed currency1,
        uint24 fee,
        int24 tickSpacing,
        IHooks hooks,
        uint160 sqrtPriceX96,
        int24 tick
    );

    /// @notice Emitted when a liquidity position is modified
    /// @param id The abi encoded hash of the pool key struct for the pool that was modified
    /// @param sender The address that modified the pool
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param liquidityDelta The amount of liquidity that was added or removed
    /// @param salt The extra data to make positions unique
    event ModifyLiquidity(
        PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
    );

    /// @notice Emitted for swaps between currency0 and currency1
    /// @param id The abi encoded hash of the pool key struct for the pool that was modified
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param amount0 The delta of the currency0 balance of the pool
    /// @param amount1 The delta of the currency1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of the price of the pool after the swap
    /// @param fee The swap fee in hundredths of a bip
    event Swap(
        PoolId indexed id,
        address indexed sender,
        int128 amount0,
        int128 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick,
        uint24 fee
    );

    /// @notice Emitted for donations
    /// @param id The abi encoded hash of the pool key struct for the pool that was donated to
    /// @param sender The address that initiated the donate call
    /// @param amount0 The amount donated in currency0
    /// @param amount1 The amount donated in currency1
    event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);

    /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
    /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
    /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
    /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
    /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
    function unlock(bytes calldata data) external returns (bytes memory);

    /// @notice Initialize the state for a given pool ID
    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
    /// @param key The pool key for the pool to initialize
    /// @param sqrtPriceX96 The initial square root price
    /// @return tick The initial tick of the pool
    function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);

    struct ModifyLiquidityParams {
        // the lower and upper tick of the position
        int24 tickLower;
        int24 tickUpper;
        // how to modify the liquidity
        int256 liquidityDelta;
        // a value to set if you want unique liquidity positions at the same range
        bytes32 salt;
    }

    /// @notice Modify the liquidity for the given pool
    /// @dev Poke by calling with a zero liquidityDelta
    /// @param key The pool to modify liquidity in
    /// @param params The parameters for modifying the liquidity
    /// @param hookData The data to pass through to the add/removeLiquidity hooks
    /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
    /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
    /// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
    /// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
    /// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
    function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);

    struct SwapParams {
        /// Whether to swap token0 for token1 or vice versa
        bool zeroForOne;
        /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
        int256 amountSpecified;
        /// The sqrt price at which, if reached, the swap will stop executing
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swap against the given pool
    /// @param key The pool to swap in
    /// @param params The parameters for swapping
    /// @param hookData The data to pass through to the swap hooks
    /// @return swapDelta The balance delta of the address swapping
    /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
    /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
    /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
    function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta swapDelta);

    /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
    /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
    /// Donors should keep this in mind when designing donation mechanisms.
    /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
    /// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
    /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
    /// Read the comments in `Pool.swap()` for more information about this.
    /// @param key The key of the pool to donate to
    /// @param amount0 The amount of currency0 to donate
    /// @param amount1 The amount of currency1 to donate
    /// @param hookData The data to pass through to the donate hooks
    /// @return BalanceDelta The delta of the caller after the donate
    function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        external
        returns (BalanceDelta);

    /// @notice Writes the current ERC20 balance of the specified currency to transient storage
    /// This is used to checkpoint balances for the manager and derive deltas for the caller.
    /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
    /// for native tokens because the amount to settle is determined by the sent value.
    /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
    /// native funds, this function can be called with the native currency to then be able to settle the native currency
    function sync(Currency currency) external;

    /// @notice Called by the user to net out some value owed to the user
    /// @dev Will revert if the requested amount is not available, consider using `mint` instead
    /// @dev Can also be used as a mechanism for free flash loans
    /// @param currency The currency to withdraw from the pool manager
    /// @param to The address to withdraw to
    /// @param amount The amount of currency to withdraw
    function take(Currency currency, address to, uint256 amount) external;

    /// @notice Called by the user to pay what is owed
    /// @return paid The amount of currency settled
    function settle() external payable returns (uint256 paid);

    /// @notice Called by the user to pay on behalf of another address
    /// @param recipient The address to credit for the payment
    /// @return paid The amount of currency settled
    function settleFor(address recipient) external payable returns (uint256 paid);

    /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
    /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
    /// @dev This could be used to clear a balance that is considered dust.
    /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
    function clear(Currency currency, uint256 amount) external;

    /// @notice Called by the user to move value into ERC6909 balance
    /// @param to The address to mint the tokens to
    /// @param id The currency address to mint to ERC6909s, as a uint256
    /// @param amount The amount of currency to mint
    /// @dev The id is converted to a uint160 to correspond to a currency address
    /// If the upper 12 bytes are not 0, they will be 0-ed out
    function mint(address to, uint256 id, uint256 amount) external;

    /// @notice Called by the user to move value from ERC6909 balance
    /// @param from The address to burn the tokens from
    /// @param id The currency address to burn from ERC6909s, as a uint256
    /// @param amount The amount of currency to burn
    /// @dev The id is converted to a uint160 to correspond to a currency address
    /// If the upper 12 bytes are not 0, they will be 0-ed out
    function burn(address from, uint256 id, uint256 amount) external;

    /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
    /// @param key The key of the pool to update dynamic LP fees for
    /// @param newDynamicLPFee The new dynamic pool LP fee
    function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}

File 6 of 36 : PoolKey.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";

using PoolIdLibrary for PoolKey global;

/// @notice Returns the key for identifying a pool
struct PoolKey {
    /// @notice The lower currency of the pool, sorted numerically
    Currency currency0;
    /// @notice The higher currency of the pool, sorted numerically
    Currency currency1;
    /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
    uint24 fee;
    /// @notice Ticks that involve positions must be a multiple of tick spacing
    int24 tickSpacing;
    /// @notice The hooks of the pool
    IHooks hooks;
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

type PoolId is bytes32;

/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
    /// @notice Returns value equal to keccak256(abi.encode(poolKey))
    function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
        assembly ("memory-safe") {
            // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
            poolId := keccak256(poolKey, 0xa0)
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {SafeCast} from "../libraries/SafeCast.sol";

/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;

using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;

function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
    assembly ("memory-safe") {
        balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
    }
}

function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
    int256 res0;
    int256 res1;
    assembly ("memory-safe") {
        let a0 := sar(128, a)
        let a1 := signextend(15, a)
        let b0 := sar(128, b)
        let b1 := signextend(15, b)
        res0 := add(a0, b0)
        res1 := add(a1, b1)
    }
    return toBalanceDelta(res0.toInt128(), res1.toInt128());
}

function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
    int256 res0;
    int256 res1;
    assembly ("memory-safe") {
        let a0 := sar(128, a)
        let a1 := signextend(15, a)
        let b0 := sar(128, b)
        let b1 := signextend(15, b)
        res0 := sub(a0, b0)
        res1 := sub(a1, b1)
    }
    return toBalanceDelta(res0.toInt128(), res1.toInt128());
}

function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
    return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}

function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
    return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}

/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
    /// @notice A BalanceDelta of 0
    BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);

    function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
        assembly ("memory-safe") {
            _amount0 := sar(128, balanceDelta)
        }
    }

    function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
        assembly ("memory-safe") {
            _amount1 := signextend(15, balanceDelta)
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;

// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
    pure
    returns (BeforeSwapDelta beforeSwapDelta)
{
    assembly ("memory-safe") {
        beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
    }
}

/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
    /// @notice A BeforeSwapDelta of 0
    BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);

    /// extracts int128 from the upper 128 bits of the BeforeSwapDelta
    /// returned by beforeSwap
    function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
        assembly ("memory-safe") {
            deltaSpecified := sar(128, delta)
        }
    }

    /// extracts int128 from the lower 128 bits of the BeforeSwapDelta
    /// returned by beforeSwap and afterSwap
    function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
        assembly ("memory-safe") {
            deltaUnspecified := signextend(15, delta)
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
    using CustomRevert for bytes4;

    /// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
    error InvalidTick(int24 tick);
    /// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
    error InvalidSqrtPrice(uint160 sqrtPriceX96);

    /// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
    int24 internal constant MAX_TICK = 887272;

    /// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
    int24 internal constant MIN_TICK_SPACING = 1;
    /// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
    int24 internal constant MAX_TICK_SPACING = type(int16).max;

    /// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_PRICE = 4295128739;
    /// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
    /// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
    uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
        1461446703485210103287273052203988822378723970342 - 4295128739 - 1;

    /// @notice Given a tickSpacing, compute the maximum usable tick
    function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
        unchecked {
            return (MAX_TICK / tickSpacing) * tickSpacing;
        }
    }

    /// @notice Given a tickSpacing, compute the minimum usable tick
    function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
        unchecked {
            return (MIN_TICK / tickSpacing) * tickSpacing;
        }
    }

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
    /// at the given tick
    function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        unchecked {
            uint256 absTick;
            assembly ("memory-safe") {
                tick := signextend(2, tick)
                // mask = 0 if tick >= 0 else -1 (all 1s)
                let mask := sar(255, tick)
                // if tick >= 0, |tick| = tick = 0 ^ tick
                // if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
                // either way, |tick| = mask ^ (tick + mask)
                absTick := xor(mask, add(mask, tick))
            }

            if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);

            // The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
            // is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer

            // Equivalent to:
            //     price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
            //     or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
            uint256 price;
            assembly ("memory-safe") {
                price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
            }
            if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
            if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
            if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
            if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
            if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
            if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
            if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
            if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
            if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
            if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
            if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
            if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
            if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
            if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
            if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
            if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
            if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
            if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
            if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;

            assembly ("memory-safe") {
                // if (tick > 0) price = type(uint256).max / price;
                if sgt(tick, 0) { price := div(not(0), price) }

                // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
                // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
                // we round up in the division so getTickAtSqrtPrice of the output price is always consistent
                // `sub(shl(32, 1), 1)` is `type(uint32).max`
                // `price + type(uint32).max` will not overflow because `price` fits in 192 bits
                sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
            }
        }
    }

    /// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
    /// ever return.
    /// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
    /// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
    function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
        unchecked {
            // Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
            // second inequality must be >= because the price can never reach the price at the max tick
            // if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
            // if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
            if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
                InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
            }

            uint256 price = uint256(sqrtPriceX96) << 32;

            uint256 r = price;
            uint256 msb = BitMath.mostSignificantBit(r);

            if (msb >= 128) r = price >> (msb - 127);
            else r = price << (127 - msb);

            int256 log_2 = (int256(msb) - 128) << 64;

            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(63, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(62, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(61, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(60, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(59, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(58, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(57, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(56, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(55, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(54, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(53, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(52, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(51, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(50, f))
            }

            int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number

            // Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
            int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);

            // Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
            // sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
            // is changed, this may need to be changed too
            int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);

            tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = a * b
            // Compute the product mod 2**256 and mod 2**256 - 1
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2**256 + prod0
            uint256 prod0 = a * b; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly ("memory-safe") {
                let mm := mulmod(a, b, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Make sure the result is less than 2**256.
            // Also prevents denominator == 0
            require(denominator > prod1);

            // Handle non-overflow cases, 256 by 256 division
            if (prod1 == 0) {
                assembly ("memory-safe") {
                    result := div(prod0, denominator)
                }
                return result;
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0]
            // Compute remainder using mulmod
            uint256 remainder;
            assembly ("memory-safe") {
                remainder := mulmod(a, b, denominator)
            }
            // Subtract 256 bit number from 512 bit number
            assembly ("memory-safe") {
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator
            // Compute largest power of two divisor of denominator.
            // Always >= 1.
            uint256 twos = (0 - denominator) & denominator;
            // Divide denominator by power of two
            assembly ("memory-safe") {
                denominator := div(denominator, twos)
            }

            // Divide [prod1 prod0] by the factors of two
            assembly ("memory-safe") {
                prod0 := div(prod0, twos)
            }
            // Shift in bits from prod1 into prod0. For this we need
            // to flip `twos` such that it is 2**256 / twos.
            // If twos is zero, then it becomes one
            assembly ("memory-safe") {
                twos := add(div(sub(0, twos), twos), 1)
            }
            prod0 |= prod1 * twos;

            // Invert denominator mod 2**256
            // Now that denominator is an odd number, it has an inverse
            // modulo 2**256 such that denominator * inv = 1 mod 2**256.
            // Compute the inverse by starting with a seed that is correct
            // correct for four bits. That is, denominator * inv = 1 mod 2**4
            uint256 inv = (3 * denominator) ^ 2;
            // Now use Newton-Raphson iteration to improve the precision.
            // Thanks to Hensel's lifting lemma, this also works in modular
            // arithmetic, doubling the correct bits in each step.
            inv *= 2 - denominator * inv; // inverse mod 2**8
            inv *= 2 - denominator * inv; // inverse mod 2**16
            inv *= 2 - denominator * inv; // inverse mod 2**32
            inv *= 2 - denominator * inv; // inverse mod 2**64
            inv *= 2 - denominator * inv; // inverse mod 2**128
            inv *= 2 - denominator * inv; // inverse mod 2**256

            // Because the division is now exact we can divide by multiplying
            // with the modular inverse of denominator. This will give us the
            // correct result modulo 2**256. Since the preconditions guarantee
            // that the outcome is less than 2**256, this is the final result.
            // We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inv;
            return result;
        }
    }

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            result = mulDiv(a, b, denominator);
            if (mulmod(a, b, denominator) != 0) {
                require(++result > 0);
            }
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {PoolId} from "../types/PoolId.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Position} from "./Position.sol";

/// @notice A helper library to provide state getters that use extsload
library StateLibrary {
    /// @notice index of pools mapping in the PoolManager
    bytes32 public constant POOLS_SLOT = bytes32(uint256(6));

    /// @notice index of feeGrowthGlobal0X128 in Pool.State
    uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;

    // feeGrowthGlobal1X128 offset in Pool.State = 2

    /// @notice index of liquidity in Pool.State
    uint256 public constant LIQUIDITY_OFFSET = 3;

    /// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;
    uint256 public constant TICKS_OFFSET = 4;

    /// @notice index of tickBitmap mapping in Pool.State
    uint256 public constant TICK_BITMAP_OFFSET = 5;

    /// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;
    uint256 public constant POSITIONS_OFFSET = 6;

    /**
     * @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee
     * @dev Corresponds to pools[poolId].slot0
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.
     * @return tick The current tick of the pool.
     * @return protocolFee The protocol fee of the pool.
     * @return lpFee The swap fee of the pool.
     */
    function getSlot0(IPoolManager manager, PoolId poolId)
        internal
        view
        returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        bytes32 data = manager.extsload(stateSlot);

        //   24 bits  |24bits|24bits      |24 bits|160 bits
        // 0x000000   |000bb8|000000      |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7
        // ---------- | fee  |protocolfee | tick  | sqrtPriceX96
        assembly ("memory-safe") {
            // bottom 160 bits of data
            sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
            // next 24 bits of data
            tick := signextend(2, shr(160, data))
            // next 24 bits of data
            protocolFee := and(shr(184, data), 0xFFFFFF)
            // last 24 bits of data
            lpFee := and(shr(208, data), 0xFFFFFF)
        }
    }

    /**
     * @notice Retrieves the tick information of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].ticks[tick]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve information for.
     * @return liquidityGross The total position liquidity that references this tick
     * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
     * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     */
    function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128
        )
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        // read all 3 words of the TickInfo struct
        bytes32[] memory data = manager.extsload(slot, 3);
        assembly ("memory-safe") {
            let firstWord := mload(add(data, 32))
            liquidityNet := sar(128, firstWord)
            liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
            feeGrowthOutside0X128 := mload(add(data, 64))
            feeGrowthOutside1X128 := mload(add(data, 96))
        }
    }

    /**
     * @notice Retrieves the liquidity information of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve liquidity for.
     * @return liquidityGross The total position liquidity that references this tick
     * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
     */
    function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (uint128 liquidityGross, int128 liquidityNet)
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        bytes32 value = manager.extsload(slot);
        assembly ("memory-safe") {
            liquidityNet := sar(128, value)
            liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
        }
    }

    /**
     * @notice Retrieves the fee growth outside a tick range of a pool
     * @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve fee growth for.
     * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     */
    function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        // offset by 1 word, since the first word is liquidityGross + liquidityNet
        bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);
        assembly ("memory-safe") {
            feeGrowthOutside0X128 := mload(add(data, 32))
            feeGrowthOutside1X128 := mload(add(data, 64))
        }
    }

    /**
     * @notice Retrieves the global fee growth of a pool.
     * @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return feeGrowthGlobal0 The global fee growth for token0.
     * @return feeGrowthGlobal1 The global fee growth for token1.
     * @dev Note that feeGrowthGlobal can be artificially inflated
     * For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal
     * atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
     */
    function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)
        internal
        view
        returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State, `uint256 feeGrowthGlobal0X128`
        bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);

        // read the 2 words of feeGrowthGlobal
        bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);
        assembly ("memory-safe") {
            feeGrowthGlobal0 := mload(add(data, 32))
            feeGrowthGlobal1 := mload(add(data, 64))
        }
    }

    /**
     * @notice Retrieves total the liquidity of a pool.
     * @dev Corresponds to pools[poolId].liquidity
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return liquidity The liquidity of the pool.
     */
    function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `uint128 liquidity`
        bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);

        liquidity = uint128(uint256(manager.extsload(slot)));
    }

    /**
     * @notice Retrieves the tick bitmap of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].tickBitmap[tick]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve the bitmap for.
     * @return tickBitmap The bitmap of the tick.
     */
    function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)
        internal
        view
        returns (uint256 tickBitmap)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(int16 => uint256) tickBitmap;`
        bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);

        // slot id of the mapping key: `pools[poolId].tickBitmap[tick]
        bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));

        tickBitmap = uint256(manager.extsload(slot));
    }

    /**
     * @notice Retrieves the position information of a pool without needing to calculate the `positionId`.
     * @dev Corresponds to pools[poolId].positions[positionId]
     * @param poolId The ID of the pool.
     * @param owner The owner of the liquidity position.
     * @param tickLower The lower tick of the liquidity range.
     * @param tickUpper The upper tick of the liquidity range.
     * @param salt The bytes32 randomness to further distinguish position state.
     * @return liquidity The liquidity of the position.
     * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
     * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
     */
    function getPositionInfo(
        IPoolManager manager,
        PoolId poolId,
        address owner,
        int24 tickLower,
        int24 tickUpper,
        bytes32 salt
    ) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {
        // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
        bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);

        (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);
    }

    /**
     * @notice Retrieves the position information of a pool at a specific position ID.
     * @dev Corresponds to pools[poolId].positions[positionId]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param positionId The ID of the position.
     * @return liquidity The liquidity of the position.
     * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
     * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
     */
    function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)
        internal
        view
        returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)
    {
        bytes32 slot = _getPositionInfoSlot(poolId, positionId);

        // read all 3 words of the Position.State struct
        bytes32[] memory data = manager.extsload(slot, 3);

        assembly ("memory-safe") {
            liquidity := mload(add(data, 32))
            feeGrowthInside0LastX128 := mload(add(data, 64))
            feeGrowthInside1LastX128 := mload(add(data, 96))
        }
    }

    /**
     * @notice Retrieves the liquidity of a position.
     * @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param positionId The ID of the position.
     * @return liquidity The liquidity of the position.
     */
    function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)
        internal
        view
        returns (uint128 liquidity)
    {
        bytes32 slot = _getPositionInfoSlot(poolId, positionId);
        liquidity = uint128(uint256(manager.extsload(slot)));
    }

    /**
     * @notice Calculate the fee growth inside a tick range of a pool
     * @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tickLower The lower tick of the range.
     * @param tickUpper The upper tick of the range.
     * @return feeGrowthInside0X128 The fee growth inside the tick range for token0.
     * @return feeGrowthInside1X128 The fee growth inside the tick range for token1.
     */
    function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)
        internal
        view
        returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)
    {
        (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);

        (uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =
            getTickFeeGrowthOutside(manager, poolId, tickLower);
        (uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =
            getTickFeeGrowthOutside(manager, poolId, tickUpper);
        (, int24 tickCurrent,,) = getSlot0(manager, poolId);
        unchecked {
            if (tickCurrent < tickLower) {
                feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
                feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
            } else if (tickCurrent >= tickUpper) {
                feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;
                feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;
            } else {
                feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
                feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
            }
        }
    }

    function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));
    }

    function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(int24 => TickInfo) ticks`
        bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);

        // slot key of the tick key: `pools[poolId].ticks[tick]
        return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));
    }

    function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(bytes32 => Position.State) positions;`
        bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);

        // slot of the mapping key: `pools[poolId].positions[positionId]
        return keccak256(abi.encodePacked(positionId, positionMapping));
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";

type Currency is address;

using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;

function equals(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) == Currency.unwrap(other);
}

function greaterThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) > Currency.unwrap(other);
}

function lessThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) < Currency.unwrap(other);
}

function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) >= Currency.unwrap(other);
}

/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
    /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
    error NativeTransferFailed();

    /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
    error ERC20TransferFailed();

    /// @notice A constant to represent the native currency
    Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));

    function transfer(Currency currency, address to, uint256 amount) internal {
        // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
        // modified custom error selectors

        bool success;
        if (currency.isAddressZero()) {
            assembly ("memory-safe") {
                // Transfer the ETH and revert if it fails.
                success := call(gas(), to, amount, 0, 0, 0, 0)
            }
            // revert with NativeTransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
            }
        } else {
            assembly ("memory-safe") {
                // Get a pointer to some free memory.
                let fmp := mload(0x40)

                // Write the abi-encoded calldata into memory, beginning with the function selector.
                mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

                success :=
                    and(
                        // Set success to whether the call reverted, if not we check it either
                        // returned exactly 1 (can't just be non-zero data), or had no return data.
                        or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                        // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                        // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                        // Counterintuitively, this call must be positioned second to the or() call in the
                        // surrounding and() call or else returndatasize() will be zero during the computation.
                        call(gas(), currency, 0, fmp, 68, 0, 32)
                    )

                // Now clean the memory we used
                mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
                mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
                mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
            }
            // revert with ERC20TransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(
                    Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
                );
            }
        }
    }

    function balanceOfSelf(Currency currency) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return address(this).balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
        }
    }

    function balanceOf(Currency currency, address owner) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return owner.balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
        }
    }

    function isAddressZero(Currency currency) internal pure returns (bool) {
        return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
    }

    function toId(Currency currency) internal pure returns (uint256) {
        return uint160(Currency.unwrap(currency));
    }

    // If the upper 12 bytes are non-zero, they will be zero-ed out
    // Therefore, fromId() and toId() are not inverses of each other
    function fromId(uint256 id) internal pure returns (Currency) {
        return Currency.wrap(address(uint160(id)));
    }
}

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

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2;

/// @dev Interface of the ERC20 standard as defined in the EIP.
/// @dev This includes the optional name, symbol, and decimals metadata.
interface IERC20 {
    /// @dev Emitted when `value` tokens are moved from one account (`from`) to another (`to`).
    event Transfer(address indexed from, address indexed to, uint256 value);

    /// @dev Emitted when the allowance of a `spender` for an `owner` is set, where `value`
    /// is the new allowance.
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /// @notice Returns the amount of tokens in existence.
    function totalSupply() external view returns (uint256);

    /// @notice Returns the amount of tokens owned by `account`.
    function balanceOf(address account) external view returns (uint256);

    /// @notice Moves `amount` tokens from the caller's account to `to`.
    function transfer(address to, uint256 amount) external returns (bool);

    /// @notice Returns the remaining number of tokens that `spender` is allowed
    /// to spend on behalf of `owner`
    function allowance(address owner, address spender) external view returns (uint256);

    /// @notice Sets `amount` as the allowance of `spender` over the caller's tokens.
    /// @dev Be aware of front-running risks: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
    function approve(address spender, uint256 amount) external returns (bool);

    /// @notice Moves `amount` tokens from `from` to `to` using the allowance mechanism.
    /// `amount` is then deducted from the caller's allowance.
    function transferFrom(address from, address to, uint256 amount) external returns (bool);

    /// @notice Returns the name of the token.
    function name() external view returns (string memory);

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

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

// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2;

import "./IERC165.sol";

/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
interface IERC721 is IERC165 {
    /// @dev This emits when ownership of any NFT changes by any mechanism.
    /// This event emits when NFTs are created (`from` == 0) and destroyed
    /// (`to` == 0). Exception: during contract creation, any number of NFTs
    /// may be created and assigned without emitting Transfer. At the time of
    /// any transfer, the approved address for that NFT (if any) is reset to none.
    event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);

    /// @dev This emits when the approved address for an NFT is changed or
    /// reaffirmed. The zero address indicates there is no approved address.
    /// When a Transfer event emits, this also indicates that the approved
    /// address for that NFT (if any) is reset to none.
    event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);

    /// @dev This emits when an operator is enabled or disabled for an owner.
    /// The operator can manage all NFTs of the owner.
    event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);

    /// @notice Count all NFTs assigned to an owner
    /// @dev NFTs assigned to the zero address are considered invalid, and this
    /// function throws for queries about the zero address.
    /// @param _owner An address for whom to query the balance
    /// @return The number of NFTs owned by `_owner`, possibly zero
    function balanceOf(address _owner) external view returns (uint256);

    /// @notice Find the owner of an NFT
    /// @dev NFTs assigned to zero address are considered invalid, and queries
    /// about them do throw.
    /// @param _tokenId The identifier for an NFT
    /// @return The address of the owner of the NFT
    function ownerOf(uint256 _tokenId) external view returns (address);

    /// @notice Transfers the ownership of an NFT from one address to another address
    /// @dev Throws unless `msg.sender` is the current owner, an authorized
    /// operator, or the approved address for this NFT. Throws if `_from` is
    /// not the current owner. Throws if `_to` is the zero address. Throws if
    /// `_tokenId` is not a valid NFT. When transfer is complete, this function
    /// checks if `_to` is a smart contract (code size > 0). If so, it calls
    /// `onERC721Received` on `_to` and throws if the return value is not
    /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
    /// @param _from The current owner of the NFT
    /// @param _to The new owner
    /// @param _tokenId The NFT to transfer
    /// @param data Additional data with no specified format, sent in call to `_to`
    function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata data) external payable;

    /// @notice Transfers the ownership of an NFT from one address to another address
    /// @dev This works identically to the other function with an extra data parameter,
    /// except this function just sets data to "".
    /// @param _from The current owner of the NFT
    /// @param _to The new owner
    /// @param _tokenId The NFT to transfer
    function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;

    /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
    /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
    /// THEY MAY BE PERMANENTLY LOST
    /// @dev Throws unless `msg.sender` is the current owner, an authorized
    /// operator, or the approved address for this NFT. Throws if `_from` is
    /// not the current owner. Throws if `_to` is the zero address. Throws if
    /// `_tokenId` is not a valid NFT.
    /// @param _from The current owner of the NFT
    /// @param _to The new owner
    /// @param _tokenId The NFT to transfer
    function transferFrom(address _from, address _to, uint256 _tokenId) external payable;

    /// @notice Change or reaffirm the approved address for an NFT
    /// @dev The zero address indicates there is no approved address.
    /// Throws unless `msg.sender` is the current NFT owner, or an authorized
    /// operator of the current owner.
    /// @param _approved The new approved NFT controller
    /// @param _tokenId The NFT to approve
    function approve(address _approved, uint256 _tokenId) external payable;

    /// @notice Enable or disable approval for a third party ("operator") to manage
    /// all of `msg.sender`'s assets
    /// @dev Emits the ApprovalForAll event. The contract MUST allow
    /// multiple operators per owner.
    /// @param _operator Address to add to the set of authorized operators
    /// @param _approved True if the operator is approved, false to revoke approval
    function setApprovalForAll(address _operator, bool _approved) external;

    /// @notice Get the approved address for a single NFT
    /// @dev Throws if `_tokenId` is not a valid NFT.
    /// @param _tokenId The NFT to find the approved address for
    /// @return The approved address for this NFT, or the zero address if there is none
    function getApproved(uint256 _tokenId) external view returns (address);

    /// @notice Query if an address is an authorized operator for another address
    /// @param _owner The address that owns the NFTs
    /// @param _operator The address that acts on behalf of the owner
    /// @return True if `_operator` is an approved operator for `_owner`, false otherwise
    function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}

/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface IERC721TokenReceiver {
    /// @notice Handle the receipt of an NFT
    /// @dev The ERC721 smart contract calls this function on the recipient
    /// after a `transfer`. This function MAY throw to revert and reject the
    /// transfer. Return of other than the magic value MUST result in the
    /// transaction being reverted.
    /// Note: the contract address is always the message sender.
    /// @param _operator The address which called `safeTransferFrom` function
    /// @param _from The address which previously owned the token
    /// @param _tokenId The NFT identifier which is being transferred
    /// @param _data Additional data with no specified format
    /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
    ///  unless throwing
    function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data)
        external
        returns (bytes4);
}

/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x5b5e139f.
interface IERC721Metadata is IERC721 {
    /// @notice A descriptive name for a collection of NFTs in this contract
    function name() external view returns (string memory _name);

    /// @notice An abbreviated name for NFTs in this contract
    function symbol() external view returns (string memory _symbol);

    /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
    /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
    /// 3986. The URI may point to a JSON file that conforms to the "ERC721
    /// Metadata JSON Schema".
    function tokenURI(uint256 _tokenId) external view returns (string memory);
}

/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x780e9d63.
interface IERC721Enumerable is IERC721 {
    /// @notice Count NFTs tracked by this contract
    /// @return A count of valid NFTs tracked by this contract, where each one of
    /// them has an assigned and queryable owner not equal to the zero address
    function totalSupply() external view returns (uint256);

    /// @notice Enumerate valid NFTs
    /// @dev Throws if `_index` >= `totalSupply()`.
    /// @param _index A counter less than `totalSupply()`
    /// @return The token identifier for the `_index`th NFT,
    /// (sort order not specified)
    function tokenByIndex(uint256 _index) external view returns (uint256);

    /// @notice Enumerate NFTs assigned to an owner
    /// @dev Throws if `_index` >= `balanceOf(_owner)` or if
    /// `_owner` is the zero address, representing invalid NFTs.
    /// @param _owner An address where we are interested in NFTs owned by them
    /// @param _index A counter less than `balanceOf(_owner)`
    /// @return The token identifier for the `_index`th NFT assigned to `_owner`,
    /// (sort order not specified)
    function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

// solhint-disable-next-line interface-starts-with-i
interface AggregatorV3Interface {
    function decimals() external view returns (uint8);

    function description() external view returns (string memory);

    function version() external view returns (uint256);

    function getRoundData(uint80 _roundId)
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);

    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;

/// @title IPermissionManager
/// @notice Interface for managing swap and liquidity permissions
/// @dev Mirrors the public API of the PermissionManager contract for modular integration and testing
interface IPermissionManager {
    error NotAdmin();
    error ZeroAddressAdmin();

    /// @dev Emitted when the admin is changed
    event AdminChanged(address indexed previousAdmin, address indexed newAdmin);

    /// @dev Emitted when swap permission is toggled
    event SwapPermissionSet(address indexed user, bool permission);

    /// @dev Emitted when liquidity permission is toggled
    event LiquidityPermissionSet(address indexed user, bool permission);

    /// @notice Returns the address of the current administrator
    /// @return The admin address
    function admin() external view returns (address);

    /// @notice Sets a new administrator
    /// @dev Can only be called by the current admin, emits AdminChanged
    /// @param newAdmin The address of the new administrator (cannot be zero address)
    function setAdmin(address newAdmin) external;

    /// @notice Grants or revokes swap permission for a user
    /// @dev Can only be called by the admin, emits SwapPermissionSet
    /// @param user The address of the user whose permission is being updated
    /// @param permission `true` to grant swap permission, `false` to revoke
    function setSwapPermission(address user, bool permission) external;

    /// @notice Grants or revokes liquidity permission for a user
    /// @dev Can only be called by the admin, emits LiquidityPermissionSet
    /// @param user The address of the user whose permission is being updated
    /// @param permission `true` to grant liquidity permission, `false` to revoke
    function setLiquidityPermission(address user, bool permission) external;

    /// @notice Checks if a user is allowed to perform swap operations
    /// @param user The address of the user to check
    /// @return `true` if swap is allowed, `false` otherwise
    function isSwapAllowed(address user) external view returns (bool);

    /// @notice Checks if a user is allowed to manage liquidity
    /// @param user The address of the user to check
    /// @return `true` if liquidity management is allowed, `false` otherwise
    function isLiquidityAllowed(address user) external view returns (bool);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {IPoolManager} from "./IPoolManager.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";

/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
    /// @notice The hook called before the state of a pool is initialized
    /// @param sender The initial msg.sender for the initialize call
    /// @param key The key for the pool being initialized
    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
    /// @return bytes4 The function selector for the hook
    function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);

    /// @notice The hook called after the state of a pool is initialized
    /// @param sender The initial msg.sender for the initialize call
    /// @param key The key for the pool being initialized
    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
    /// @param tick The current tick after the state of a pool is initialized
    /// @return bytes4 The function selector for the hook
    function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
        external
        returns (bytes4);

    /// @notice The hook called before liquidity is added
    /// @param sender The initial msg.sender for the add liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for adding liquidity
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeAddLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after liquidity is added
    /// @param sender The initial msg.sender for the add liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for adding liquidity
    /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
    /// @param feesAccrued The fees accrued since the last time fees were collected from this position
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterAddLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external returns (bytes4, BalanceDelta);

    /// @notice The hook called before liquidity is removed
    /// @param sender The initial msg.sender for the remove liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for removing liquidity
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after liquidity is removed
    /// @param sender The initial msg.sender for the remove liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for removing liquidity
    /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
    /// @param feesAccrued The fees accrued since the last time fees were collected from this position
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external returns (bytes4, BalanceDelta);

    /// @notice The hook called before a swap
    /// @param sender The initial msg.sender for the swap call
    /// @param key The key for the pool
    /// @param params The parameters for the swap
    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
    function beforeSwap(
        address sender,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4, BeforeSwapDelta, uint24);

    /// @notice The hook called after a swap
    /// @param sender The initial msg.sender for the swap call
    /// @param key The key for the pool
    /// @param params The parameters for the swap
    /// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterSwap(
        address sender,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata hookData
    ) external returns (bytes4, int128);

    /// @notice The hook called before donate
    /// @param sender The initial msg.sender for the donate call
    /// @param key The key for the pool
    /// @param amount0 The amount of token0 being donated
    /// @param amount1 The amount of token1 being donated
    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after donate
    /// @param sender The initial msg.sender for the donate call
    /// @param key The key for the pool
    /// @param amount0 The amount of token0 being donated
    /// @param amount1 The amount of token1 being donated
    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function afterDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external returns (bytes4);
}

File 20 of 36 : ImmutableState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IImmutableState} from "../interfaces/IImmutableState.sol";

/// @title Immutable State
/// @notice A collection of immutable state variables, commonly used across multiple contracts
contract ImmutableState is IImmutableState {
    /// @inheritdoc IImmutableState
    IPoolManager public immutable poolManager;

    /// @notice Thrown when the caller is not PoolManager
    error NotPoolManager();

    /// @notice Only allow calls from the PoolManager contract
    modifier onlyPoolManager() {
        if (msg.sender != address(poolManager)) revert NotPoolManager();
        _;
    }

    constructor(IPoolManager _poolManager) {
        poolManager = _poolManager;
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
    using CustomRevert for bytes4;

    error SafeCastOverflow();

    /// @notice Cast a uint256 to a uint160, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return y The downcasted integer, now type uint160
    function toUint160(uint256 x) internal pure returns (uint160 y) {
        y = uint160(x);
        if (y != x) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a uint128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return y The downcasted integer, now type uint128
    function toUint128(uint256 x) internal pure returns (uint128 y) {
        y = uint128(x);
        if (x != y) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a int128 to a uint128, revert on overflow or underflow
    /// @param x The int128 to be casted
    /// @return y The casted integer, now type uint128
    function toUint128(int128 x) internal pure returns (uint128 y) {
        if (x < 0) SafeCastOverflow.selector.revertWith();
        y = uint128(x);
    }

    /// @notice Cast a int256 to a int128, revert on overflow or underflow
    /// @param x The int256 to be downcasted
    /// @return y The downcasted integer, now type int128
    function toInt128(int256 x) internal pure returns (int128 y) {
        y = int128(x);
        if (y != x) SafeCastOverflow.selector.revertWith();
    }

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

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

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

/// @notice Library of helper functions for a pools LP fee
library LPFeeLibrary {
    using LPFeeLibrary for uint24;
    using CustomRevert for bytes4;

    /// @notice Thrown when the static or dynamic fee on a pool exceeds 100%.
    error LPFeeTooLarge(uint24 fee);

    /// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE
    uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;

    /// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap
    // only dynamic-fee pools can return a fee via the beforeSwap hook
    uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;

    /// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook
    uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;

    /// @notice the lp fee is represented in hundredths of a bip, so the max is 100%
    uint24 public constant MAX_LP_FEE = 1000000;

    /// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee
    /// @param self The fee to check
    /// @return bool True of the fee is dynamic
    function isDynamicFee(uint24 self) internal pure returns (bool) {
        return self == DYNAMIC_FEE_FLAG;
    }

    /// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee
    /// @param self The fee to check
    /// @return bool True of the fee is valid
    function isValid(uint24 self) internal pure returns (bool) {
        return self <= MAX_LP_FEE;
    }

    /// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
    /// @param self The fee to validate
    function validate(uint24 self) internal pure {
        if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self);
    }

    /// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.
    /// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook
    /// @param self The fee to get the initial LP from
    /// @return initialFee 0 if the fee is dynamic, otherwise the fee (if valid)
    function getInitialLPFee(uint24 self) internal pure returns (uint24) {
        // the initial fee for a dynamic fee pool is 0
        if (self.isDynamicFee()) return 0;
        self.validate();
        return self;
    }

    /// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)
    /// @param self The fee to check
    /// @return bool True of the fee has the override flag set
    function isOverride(uint24 self) internal pure returns (bool) {
        return self & OVERRIDE_FEE_FLAG != 0;
    }

    /// @notice returns a fee with the override flag removed
    /// @param self The fee to remove the override flag from
    /// @return fee The fee without the override flag set
    function removeOverrideFlag(uint24 self) internal pure returns (uint24) {
        return self & REMOVE_OVERRIDE_MASK;
    }

    /// @notice Removes the override flag and validates the fee (reverts if the fee is too large)
    /// @param self The fee to remove the override flag from, and then validate
    /// @return fee The fee without the override flag set (if valid)
    function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {
        fee = self.removeOverrideFlag();
        fee.validate();
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks.
/// @dev parseSelector also is used to parse the expected selector
/// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24).
library ParseBytes {
    function parseSelector(bytes memory result) internal pure returns (bytes4 selector) {
        // equivalent: (selector,) = abi.decode(result, (bytes4, int256));
        assembly ("memory-safe") {
            selector := mload(add(result, 0x20))
        }
    }

    function parseFee(bytes memory result) internal pure returns (uint24 lpFee) {
        // equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24));
        assembly ("memory-safe") {
            lpFee := mload(add(result, 0x60))
        }
    }

    function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {
        // equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));
        assembly ("memory-safe") {
            hookReturn := mload(add(result, 0x40))
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
    /// @dev ERC-7751 error for wrapping bubbled up reverts
    error WrappedError(address target, bytes4 selector, bytes reason, bytes details);

    /// @dev Reverts with the selector of a custom error in the scratch space
    function revertWith(bytes4 selector) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            revert(0, 0x04)
        }
    }

    /// @dev Reverts with a custom error with an address argument in the scratch space
    function revertWith(bytes4 selector, address addr) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with an int24 argument in the scratch space
    function revertWith(bytes4 selector, int24 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, signextend(2, value))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with a uint160 argument in the scratch space
    function revertWith(bytes4 selector, uint160 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with two int24 arguments
    function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), signextend(2, value1))
            mstore(add(fmp, 0x24), signextend(2, value2))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two uint160 arguments
    function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two address arguments
    function revertWith(bytes4 selector, address value1, address value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
    /// @dev this method can be vulnerable to revert data bombs
    function bubbleUpAndRevertWith(
        address revertingContract,
        bytes4 revertingFunctionSelector,
        bytes4 additionalContext
    ) internal pure {
        bytes4 wrappedErrorSelector = WrappedError.selector;
        assembly ("memory-safe") {
            // Ensure the size of the revert data is a multiple of 32 bytes
            let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)

            let fmp := mload(0x40)

            // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
            mstore(fmp, wrappedErrorSelector)
            mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(
                add(fmp, 0x24),
                and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            // offset revert reason
            mstore(add(fmp, 0x44), 0x80)
            // offset additional context
            mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
            // size revert reason
            mstore(add(fmp, 0x84), returndatasize())
            // revert reason
            returndatacopy(add(fmp, 0xa4), 0, returndatasize())
            // size additional context
            mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
            // additional context
            mstore(
                add(fmp, add(0xc4, encodedDataSize)),
                and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            revert(fmp, add(0xe4, encodedDataSize))
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event OperatorSet(address indexed owner, address indexed operator, bool approved);

    event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);

    event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                                 FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /// @notice Owner balance of an id.
    /// @param owner The address of the owner.
    /// @param id The id of the token.
    /// @return amount The balance of the token.
    function balanceOf(address owner, uint256 id) external view returns (uint256 amount);

    /// @notice Spender allowance of an id.
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @param id The id of the token.
    /// @return amount The allowance of the token.
    function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);

    /// @notice Checks if a spender is approved by an owner as an operator
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @return approved The approval status.
    function isOperator(address owner, address spender) external view returns (bool approved);

    /// @notice Transfers an amount of an id from the caller to a receiver.
    /// @param receiver The address of the receiver.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always, unless the function reverts
    function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);

    /// @notice Transfers an amount of an id from a sender to a receiver.
    /// @param sender The address of the sender.
    /// @param receiver The address of the receiver.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always, unless the function reverts
    function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);

    /// @notice Approves an amount of an id to a spender.
    /// @param spender The address of the spender.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always
    function approve(address spender, uint256 id, uint256 amount) external returns (bool);

    /// @notice Sets or removes an operator for the caller.
    /// @param operator The address of the operator.
    /// @param approved The approval status.
    /// @return bool True, always
    function setOperator(address operator, bool approved) external returns (bool);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";

/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
    /// @notice Thrown when protocol fee is set too high
    error ProtocolFeeTooLarge(uint24 fee);

    /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
    error InvalidCaller();

    /// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
    error ProtocolFeeCurrencySynced();

    /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
    event ProtocolFeeControllerUpdated(address indexed protocolFeeController);

    /// @notice Emitted when the protocol fee is updated for a pool.
    event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);

    /// @notice Given a currency address, returns the protocol fees accrued in that currency
    /// @param currency The currency to check
    /// @return amount The amount of protocol fees accrued in the currency
    function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);

    /// @notice Sets the protocol fee for the given pool
    /// @param key The key of the pool to set a protocol fee for
    /// @param newProtocolFee The fee to set
    function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;

    /// @notice Sets the protocol fee controller
    /// @param controller The new protocol fee controller
    function setProtocolFeeController(address controller) external;

    /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
    /// @dev This will revert if the contract is unlocked
    /// @param recipient The address to receive the protocol fees
    /// @param currency The currency to withdraw
    /// @param amount The amount of currency to withdraw
    /// @return amountCollected The amount of currency successfully withdrawn
    function collectProtocolFees(address recipient, Currency currency, uint256 amount)
        external
        returns (uint256 amountCollected);

    /// @notice Returns the current protocol fee controller address
    /// @return address The current protocol fee controller address
    function protocolFeeController() external view returns (address);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
    /// @notice Called by external contracts to access granular pool state
    /// @param slot Key of slot to sload
    /// @return value The value of the slot as bytes32
    function extsload(bytes32 slot) external view returns (bytes32 value);

    /// @notice Called by external contracts to access granular pool state
    /// @param startSlot Key of slot to start sloading from
    /// @param nSlots Number of slots to load into return value
    /// @return values List of loaded values.
    function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);

    /// @notice Called by external contracts to access sparse pool state
    /// @param slots List of slots to SLOAD from.
    /// @return values List of loaded values.
    function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}

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

/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
    /// @notice Called by external contracts to access transient storage of the contract
    /// @param slot Key of slot to tload
    /// @return value The value of the slot as bytes32
    function exttload(bytes32 slot) external view returns (bytes32 value);

    /// @notice Called by external contracts to access sparse transient pool state
    /// @param slots List of slots to tload
    /// @return values List of loaded values
    function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
    /// @notice Returns the index of the most significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @param x the value for which to compute the most significant bit, must be greater than 0
    /// @return r the index of the most significant bit
    function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        assembly ("memory-safe") {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0x0706060506020500060203020504000106050205030304010505030400000000))
        }
    }

    /// @notice Returns the index of the least significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @param x the value for which to compute the least significant bit, must be greater than 0
    /// @return r the index of the least significant bit
    function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        assembly ("memory-safe") {
            // Isolate the least significant bit.
            x := and(x, sub(0, x))
            // For the upper 3 bits of the result, use a De Bruijn-like lookup.
            // Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
            // forgefmt: disable-next-item
            r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
                0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
                0x8040405543005266443200005020610674053026020000107506200176117077)))
            // For the lower 5 bits of the result, use a De Bruijn lookup.
            // forgefmt: disable-next-item
            r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
                0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
        }
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

import {FullMath} from "./FullMath.sol";
import {FixedPoint128} from "./FixedPoint128.sol";
import {LiquidityMath} from "./LiquidityMath.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @title Position
/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary
/// @dev Positions store additional state for tracking fees owed to the position
library Position {
    using CustomRevert for bytes4;

    /// @notice Cannot update a position with no liquidity
    error CannotUpdateEmptyPosition();

    // info stored for each user's position
    struct State {
        // 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;
    }

    /// @notice Returns the State struct of a position, given an owner and position boundaries
    /// @param self The mapping containing all user positions
    /// @param owner The address of the position owner
    /// @param tickLower The lower tick boundary of the position
    /// @param tickUpper The upper tick boundary of the position
    /// @param salt A unique value to differentiate between multiple positions in the same range
    /// @return position The position info struct of the given owners' position
    function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
        internal
        view
        returns (State storage position)
    {
        bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);
        position = self[positionKey];
    }

    /// @notice A helper function to calculate the position key
    /// @param owner The address of the position owner
    /// @param tickLower the lower tick boundary of the position
    /// @param tickUpper the upper tick boundary of the position
    /// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.
    function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
        internal
        pure
        returns (bytes32 positionKey)
    {
        // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(add(fmp, 0x26), salt) // [0x26, 0x46)
            mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)
            mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)
            mstore(fmp, owner) // [0x0c, 0x20)
            positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes

            // now clean the memory we used
            mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt
            mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt
            mstore(fmp, 0) // fmp held owner
        }
    }

    /// @notice Credits accumulated fees to a user's position
    /// @param self The individual position to update
    /// @param liquidityDelta The change in pool liquidity as a result of the position update
    /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries
    /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries
    /// @return feesOwed0 The amount of currency0 owed to the position owner
    /// @return feesOwed1 The amount of currency1 owed to the position owner
    function update(
        State storage self,
        int128 liquidityDelta,
        uint256 feeGrowthInside0X128,
        uint256 feeGrowthInside1X128
    ) internal returns (uint256 feesOwed0, uint256 feesOwed1) {
        uint128 liquidity = self.liquidity;

        if (liquidityDelta == 0) {
            // disallow pokes for 0 liquidity positions
            if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();
        } else {
            self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);
        }

        // calculate accumulated fees. overflow in the subtraction of fee growth is expected
        unchecked {
            feesOwed0 =
                FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);
            feesOwed1 =
                FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);
        }

        // update the position
        self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
        self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
    /// @notice Returns an account's balance in the token
    /// @param account The account for which to look up the number of tokens it has, i.e. its balance
    /// @return The number of tokens held by the account
    function balanceOf(address account) external view returns (uint256);

    /// @notice Transfers the amount of token from the `msg.sender` to the recipient
    /// @param recipient The account that will receive the amount transferred
    /// @param amount The number of tokens to send from the sender to the recipient
    /// @return Returns true for a successful transfer, false for an unsuccessful transfer
    function transfer(address recipient, uint256 amount) external returns (bool);

    /// @notice Returns the current allowance given to a spender by an owner
    /// @param owner The account of the token owner
    /// @param spender The account of the token spender
    /// @return The current allowance granted by `owner` to `spender`
    function allowance(address owner, address spender) external view returns (uint256);

    /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
    /// @param spender The account which will be allowed to spend a given amount of the owners tokens
    /// @param amount The amount of tokens allowed to be used by `spender`
    /// @return Returns true for a successful approval, false for unsuccessful
    function approve(address spender, uint256 amount) external returns (bool);

    /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
    /// @param sender The account from which the transfer will be initiated
    /// @param recipient The recipient of the transfer
    /// @param amount The amount of the transfer
    /// @return Returns true for a successful transfer, false for unsuccessful
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
    /// @param from The account from which the tokens were sent, i.e. the balance decreased
    /// @param to The account to which the tokens were sent, i.e. the balance increased
    /// @param value The amount of tokens that were transferred
    event Transfer(address indexed from, address indexed to, uint256 value);

    /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
    /// @param owner The account that approved spending of its tokens
    /// @param spender The account for which the spending allowance was modified
    /// @param value The new allowance from the owner to the spender
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

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

pragma solidity ^0.8.20;

/**
 * @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 Context {
    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
pragma solidity >=0.6.2;

interface IERC165 {
    /// @notice Query if a contract implements an interface
    /// @param interfaceID The interface identifier, as specified in ERC-165
    /// @dev Interface identification is specified in ERC-165. This function
    /// uses less than 30,000 gas.
    /// @return `true` if the contract implements `interfaceID` and
    /// `interfaceID` is not 0xffffffff, `false` otherwise
    function supportsInterface(bytes4 interfaceID) external view returns (bool);
}

File 34 of 36 : IImmutableState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";

/// @title IImmutableState
/// @notice Interface for the ImmutableState contract
interface IImmutableState {
    /// @notice The Uniswap v4 PoolManager contract
    function poolManager() external view returns (IPoolManager);
}

File 35 of 36 : FixedPoint128.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
    uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title Math library for liquidity
library LiquidityMath {
    /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
    /// @param x The liquidity before change
    /// @param y The delta by which liquidity should be changed
    /// @return z The liquidity delta
    function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
        assembly ("memory-safe") {
            z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))
            if shr(128, z) {
                // revert SafeCastOverflow()
                mstore(0, 0x93dafdf1)
                revert(0x1c, 0x04)
            }
        }
    }
}

Settings
{
  "remappings": [
    "@uniswap/v4-core/=lib/v4-core/",
    "forge-gas-snapshot/=lib/v4-core/lib/forge-gas-snapshot/src/",
    "forge-std/=lib/v4-core/lib/forge-std/src/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "solmate/=lib/v4-core/lib/solmate/",
    "v4-core/=lib/v4-core/",
    "v4-router/=lib/v4-router/",
    "v4-periphery/=lib/v4-periphery/",
    "@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
    "@openzeppelin/uniswap-hooks/=lib/uniswap-hooks/",
    "@oz496/=lib/openzeppelin-contracts/",
    "solady/=lib/v4-router/lib/solady/",
    "lib/v4-router:@v4/=lib/v4-core/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@forge/=lib/v4-router/lib/forge-std/src/",
    "@permit2/=lib/v4-router/lib/permit2/src/",
    "@solady/=lib/v4-router/lib/solady/",
    "@uniswap/v2-core/=lib/v4-router/lib/universal-router/node_modules/@uniswap/v2-core/",
    "@uniswap/v3-core/=lib/v4-router/lib/universal-router/node_modules/@uniswap/v3-core/",
    "@uniswap/v3-periphery/=lib/v4-router/lib/universal-router/lib/v3-periphery/",
    "@uniswap/v4-periphery/=lib/v4-router/lib/universal-router/lib/v4-periphery/",
    "@universal-router/=lib/v4-router/lib/universal-router/contracts/",
    "@v4-periphery/=lib/v4-router/lib/v4-periphery/",
    "@v4-template/=lib/v4-router/lib/v4-template/",
    "@v4/=lib/v4-router/lib/v4-core/",
    "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin/=lib/openzeppelin-contracts/contracts/",
    "uniswap-hooks/=lib/uniswap-hooks/src/",
    "universal-router/=lib/v4-router/lib/universal-router/",
    "v3-periphery/=lib/v4-router/lib/universal-router/lib/v3-periphery/contracts/",
    "v4-template/=lib/v4-router/lib/v4-template/",
    "lib/permit2/test:openzeppelin-contracts/contracts/=lib/v4-router/lib/permit2/lib/openzeppelin-contracts/contracts/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 44444444
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "none",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": true,
  "libraries": {}
}

Contract ABI

API
[{"inputs":[{"internalType":"contract IPoolManager","name":"_poolManager","type":"address"},{"internalType":"address","name":"_provider","type":"address"},{"internalType":"address","name":"_institution","type":"address"},{"internalType":"address","name":"_positionManager","type":"address"},{"internalType":"address","name":"_swapRouter","type":"address"},{"internalType":"address","name":"_quoter","type":"address"},{"internalType":"address","name":"_serviceFeeVault","type":"address"},{"internalType":"contract IPermissionManager","name":"_permissionManager","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint24","name":"fee","type":"uint24"}],"name":"BaseFeeTooLarge","type":"error"},{"inputs":[],"name":"ContractPaused","type":"error"},{"inputs":[{"internalType":"uint256","name":"multiplier","type":"uint256"}],"name":"DeviationFeeFactorTooLarge","type":"error"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[],"name":"HookNotImplemented","type":"error"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"LiquidityNotAllowed","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"NotInstitution","type":"error"},{"inputs":[],"name":"NotPoolManager","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"NotProvider","type":"error"},{"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"}],"name":"OracleNotSet","type":"error"},{"inputs":[],"name":"OraclePriceZero","type":"error"},{"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"}],"name":"PoolIsPaused","type":"error"},{"inputs":[{"internalType":"uint256","name":"price0","type":"uint256"}],"name":"Price0CalculationError","type":"error"},{"inputs":[{"internalType":"uint256","name":"price1","type":"uint256"}],"name":"Price1CalculationError","type":"error"},{"inputs":[{"internalType":"bytes32","name":"roleId","type":"bytes32"}],"name":"RoleAlreadyExists","type":"error"},{"inputs":[{"internalType":"bytes32","name":"roleId","type":"bytes32"}],"name":"RoleDoesNotExist","type":"error"},{"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"bytes32","name":"roleId","type":"bytes32"}],"name":"RoleRequired","type":"error"},{"inputs":[{"internalType":"uint256","name":"serviceFee","type":"uint256"}],"name":"ServiceFeeTooLarge","type":"error"},{"inputs":[{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"}],"name":"SqrtPriceOutOfBounds","type":"error"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"SwapNotAllowed","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"UnapprovedPositionManager","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"UnapprovedSwapRouterOrQuoter","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint24","name":"oldFee","type":"uint24"},{"indexed":true,"internalType":"uint24","name":"newFee","type":"uint24"}],"name":"BaseFeeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"oldMultiplier","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"newMultiplier","type":"uint256"}],"name":"DeviationFeeFactorUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldInstitution","type":"address"},{"indexed":true,"internalType":"address","name":"newInstitution","type":"address"}],"name":"InstitutionUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldManager","type":"address"},{"indexed":true,"internalType":"address","name":"newManager","type":"address"}],"name":"PermissionManagerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"uint24","name":"newBaseFee","type":"uint24"}],"name":"PoolBaseFeeSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"}],"name":"PoolOracleRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"address","name":"oracle","type":"address"},{"indexed":false,"internalType":"bool","name":"compareWithPrice0","type":"bool"}],"name":"PoolOracleSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"}],"name":"PoolPaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"roleId","type":"bytes32"}],"name":"PoolRequiredRoleCleared","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"roleId","type":"bytes32"}],"name":"PoolRequiredRoleSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"}],"name":"PoolUnpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldManager","type":"address"},{"indexed":true,"internalType":"address","name":"newManager","type":"address"}],"name":"PositionManagerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldProvider","type":"address"},{"indexed":true,"internalType":"address","name":"newProvider","type":"address"}],"name":"ProviderUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldQuoter","type":"address"},{"indexed":true,"internalType":"address","name":"newQuoter","type":"address"}],"name":"QuoterUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"roleId","type":"bytes32"}],"name":"RoleCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"oldFee","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"newFee","type":"uint256"}],"name":"ServiceFeeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldVault","type":"address"},{"indexed":true,"internalType":"address","name":"newVault","type":"address"}],"name":"ServiceFeeVaultUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldRouter","type":"address"},{"indexed":true,"internalType":"address","name":"newRouter","type":"address"}],"name":"SwapRouterUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"roleId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"bool","name":"swap","type":"bool"},{"indexed":false,"internalType":"bool","name":"liquidity","type":"bool"}],"name":"UserRoleAssigned","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"roleId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"}],"name":"UserRoleRevoked","type":"event"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"int256","name":"liquidityDelta","type":"int256"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"internalType":"struct IPoolManager.ModifyLiquidityParams","name":"params","type":"tuple"},{"internalType":"BalanceDelta","name":"delta","type":"int256"},{"internalType":"BalanceDelta","name":"feesAccrued","type":"int256"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"afterAddLiquidity","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"},{"internalType":"BalanceDelta","name":"","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"afterDonate","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"internalType":"int24","name":"tick","type":"int24"}],"name":"afterInitialize","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"int256","name":"liquidityDelta","type":"int256"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"internalType":"struct IPoolManager.ModifyLiquidityParams","name":"params","type":"tuple"},{"internalType":"BalanceDelta","name":"delta","type":"int256"},{"internalType":"BalanceDelta","name":"feesAccrued","type":"int256"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"afterRemoveLiquidity","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"},{"internalType":"BalanceDelta","name":"","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"int256","name":"amountSpecified","type":"int256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct IPoolManager.SwapParams","name":"params","type":"tuple"},{"internalType":"BalanceDelta","name":"delta","type":"int256"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"afterSwap","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"},{"internalType":"int128","name":"","type":"int128"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"baseFee","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"int256","name":"liquidityDelta","type":"int256"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"internalType":"struct IPoolManager.ModifyLiquidityParams","name":"params","type":"tuple"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"beforeAddLiquidity","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"beforeDonate","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"}],"name":"beforeInitialize","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"int256","name":"liquidityDelta","type":"int256"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"internalType":"struct IPoolManager.ModifyLiquidityParams","name":"params","type":"tuple"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"beforeRemoveLiquidity","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"int256","name":"amountSpecified","type":"int256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct IPoolManager.SwapParams","name":"params","type":"tuple"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"beforeSwap","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"},{"internalType":"BeforeSwapDelta","name":"","type":"int256"},{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"}],"name":"clearPoolRequiredRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"roleId","type":"bytes32"}],"name":"createRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"deviationFeeFactor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"}],"name":"getCurrentPrices","outputs":[{"internalType":"uint256","name":"price0","type":"uint256"},{"internalType":"uint256","name":"price1","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getHookPermissions","outputs":[{"components":[{"internalType":"bool","name":"beforeInitialize","type":"bool"},{"internalType":"bool","name":"afterInitialize","type":"bool"},{"internalType":"bool","name":"beforeAddLiquidity","type":"bool"},{"internalType":"bool","name":"afterAddLiquidity","type":"bool"},{"internalType":"bool","name":"beforeRemoveLiquidity","type":"bool"},{"internalType":"bool","name":"afterRemoveLiquidity","type":"bool"},{"internalType":"bool","name":"beforeSwap","type":"bool"},{"internalType":"bool","name":"afterSwap","type":"bool"},{"internalType":"bool","name":"beforeDonate","type":"bool"},{"internalType":"bool","name":"afterDonate","type":"bool"},{"internalType":"bool","name":"beforeSwapReturnDelta","type":"bool"},{"internalType":"bool","name":"afterSwapReturnDelta","type":"bool"},{"internalType":"bool","name":"afterAddLiquidityReturnDelta","type":"bool"},{"internalType":"bool","name":"afterRemoveLiquidityReturnDelta","type":"bool"}],"internalType":"struct Hooks.Permissions","name":"","type":"tuple"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"_oracle","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"}],"name":"getLastOraclePrice","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"}],"name":"getPoolBaseFee","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"}],"name":"getPoolOracle","outputs":[{"internalType":"address","name":"oracle","type":"address"},{"internalType":"bool","name":"compareWithPrice0","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"}],"name":"getPoolRequiredRole","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"address","name":"account","type":"address"}],"name":"getUserPoolPermissions","outputs":[{"internalType":"bool","name":"hasRole","type":"bool"},{"internalType":"bool","name":"swapPerm","type":"bool"},{"internalType":"bool","name":"liquidityPerm","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"institution","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"}],"name":"pausePool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"permissionManager","outputs":[{"internalType":"contract IPermissionManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"poolBaseFees","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolManager","outputs":[{"internalType":"contract IPoolManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"poolOracles","outputs":[{"internalType":"address","name":"oracle","type":"address"},{"internalType":"bool","name":"compareWithPrice0","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"poolPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"positionManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"provider","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"quoter","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"}],"name":"removePoolOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"roleId","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeUserRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"serviceFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"serviceFeeVault","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_deviationFeeFactor","type":"uint256"}],"name":"setDeviationFeeFactor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint24","name":"_baseFee","type":"uint24"}],"name":"setPoolBaseFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"address","name":"_oracle","type":"address"},{"internalType":"bool","name":"_compareWithPrice0","type":"bool"}],"name":"setPoolOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"bytes32","name":"roleId","type":"bytes32"}],"name":"setPoolRequiredRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"roleId","type":"bytes32"},{"internalType":"address","name":"account","type":"address"},{"internalType":"bool","name":"swap","type":"bool"},{"internalType":"bool","name":"liquidity","type":"bool"}],"name":"setRoleForUser","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"swapRouter","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"}],"name":"unpausePool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint24","name":"_baseFee","type":"uint24"}],"name":"updateBaseFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_institution","type":"address"}],"name":"updateInstitution","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IPermissionManager","name":"_permissionManager","type":"address"}],"name":"updatePermissionManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_positionManager","type":"address"}],"name":"updatePositionManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_provider","type":"address"}],"name":"updateProvider","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_quoter","type":"address"}],"name":"updateQuoter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_serviceFee","type":"uint256"}],"name":"updateServiceFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_serviceFeeVault","type":"address"}],"name":"updateServiceFeeVault","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_swapRouter","type":"address"}],"name":"updateSwapRouter","outputs":[],"stateMutability":"nonpayable","type":"function"}]

60a06040523461042d57604051601f61499038819003918201601f19168301916001600160401b03831184841017610431578084926101009460405283398101031261042d578051906001600160a01b0382169081830361042d5761006660208201610465565b9261007360408301610465565b9161008060608201610465565b9461008d60808301610465565b9461009a60a08401610465565b9160e06100a960c08601610465565b9401516001600160a01b038116959086900361042d576080525f6101a06100ce610445565b8281528260208201528260408201528260608201528260808201528260a08201528260c08201528260e0820152826101008201528261012082015282610140820152826101608201528261018082015201525f6101a061012c610445565b6001815282602082015260016040820152826060820152600160808201528260a0820152600160c0820152600160e082015282610100820152826101208201526001610140820152600161016082015282610180820152015261200030161515600114801590610420575b801561040f575b8015610402575b80156103f1575b80156103e4575b80156103d4575b80156103c4575b80156103b8575b80156103ac575b801561039c575b801561038c575b8015610380575b8015610374575b610361575f549115610352576001600160a01b0316948515610352576001600160a01b0316958615610352576001600160a01b03881615610352576001600160a01b0316918215610352576001600160a01b0316928315610352576001600160a01b031694851561035257841561035257600480546001600160a01b0319908116929092179055600580546001600160a81b031990931660089990991b610100600160a81b0316989098175f556001805482169390931790925560028054831693909317909255600b8054821693909317909255600380549092169290921790556001600160b81b0319161761017760a31b1790556103e8600655620dbba0600755604051614516908161047a823960805181818161040901528181610500015281816105f0015281816110a30152818161166101528181611bcc01528181611ea9015281816122cb015281816126d3015281816127850152818161355a01526141520152f35b63d92e233d60e01b5f5260045ffd5b630732d7b560e51b5f523060045260245ffd5b506001301615156101eb565b506002301615156101e4565b50600430161515600114156101dd565b50600830161515600114156101d6565b506010301615156101cf565b506020301615156101c8565b50604030161515600114156101c1565b50608030161515600114156101ba565b50610100301615156101b3565b5061020030161515600114156101ac565b50610400301615156101a5565b50610800301615156001141561019e565b5061100030161515610197565b5f80fd5b634e487b7160e01b5f52604160045260245ffd5b604051906101c082016001600160401b0381118382101761043157604052565b51906001600160a01b038216820361042d5756fe60806040526004361015610011575f80fd5b5f3560e01c80624f07f514612afa578063085d488314612aa957806309846580146129a25780630c450bcd146128ef5780631e2cbb7d1461280e57806321d0ee701461275c578063259982e5146126aa5780632e027230146125ce578063341d7eec1461244257806339747b33146122225780633f4ba83a14612152578063426172d6146120795780634327623d1461202c578063575e24b414611de45780635c975abb14611da55780636881d8cb14611cae5780636c2bbe7e146116355780636c52f9ae14611c5d5780636ef25c3a14611c1a5780636fe7e6eb14611b40578063758af29d14611af3578063791b98bc14611aa05780637d6913c414611a105780637e6bd2011461195b5780638456cb59146118b15780638abdf5aa146118765780638f0ff5e0146117c45780639ba34035146117735780639c4d8430146116af5780639f063efc14611635578063a30e865c146112ec578063aa33141114611257578063ae4b7c26146111a5578063b327f3c614611108578063b47b2fb114610fdc578063b6a8b0fa146103de578063b98b677f14610f03578063bc7d2e7814610e11578063c0c0f4cd14610c77578063c1c7a1ab14610c15578063c31c9c0714610bc4578063c42994a214610ad9578063c4941e1614610a9e578063c4e833ce14610914578063c6bbd5a7146108c3578063cc7a204914610872578063cce1e4bc14610799578063d1384eb614610748578063d8505b3c14610614578063dc4c90d3146105a6578063dc98354e1461047f578063e1b4af69146103de578063e64927ca146103865763ef70768a1461026a575f80fd5b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576102a1612bf6565b6004549073ffffffffffffffffffffffffffffffffffffffff8216908133036103565773ffffffffffffffffffffffffffffffffffffffff1691821561032e577fffffffffffffffffffffffff00000000000000000000000000000000000000001682176004557fa4652513510d8a8ef70d7c10761c2fd3d3f582d2e903ac7f7a74c3075331f53f5f80a3005b7fd92e233d000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f1bd2224f000000000000000000000000000000000000000000000000000000005f523360045260245ffd5b5f80fd5b346103825760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760a06103c236600461308a565b205f526008602052602062ffffff60405f205416604051908152f35b34610382576103ec36612e5a565b50505050505073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000163303610457577f0a85dc29000000000000000000000000000000000000000000000000000000005f5260045ffd5b7fae18210a000000000000000000000000000000000000000000000000000000005f5260045ffd5b346103825760e07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576104b6612bf6565b60a07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc360112610382576104e8612e27565b5073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000001633036104575761052e614494565b73ffffffffffffffffffffffffffffffffffffffff8060055416911690810361057b5760206040517fdc98354e000000000000000000000000000000000000000000000000000000008152f35b7fbdc4ce88000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602060405173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760043562ffffff8116908181036103825760055473ffffffffffffffffffffffffffffffffffffffff8116330361071c57620f424083116106f05776ffffff000000000000000000000000000000000000000062ffffff9260a01b167fffffffffffffffffff000000ffffffffffffffffffffffffffffffffffffffff82161760055560a01c167f434d1e61af6b7d470d22269977887cd1da10bd474fd3e4a0a693abd991b371465f80a3005b827f1c068a62000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b7fbdc4ce88000000000000000000000000000000000000000000000000000000005f523360045260245ffd5b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602073ffffffffffffffffffffffffffffffffffffffff60055416604051908152f35b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576107d0612bf6565b73ffffffffffffffffffffffffffffffffffffffff6004541633036103565773ffffffffffffffffffffffffffffffffffffffff16801561032e5773ffffffffffffffffffffffffffffffffffffffff600354827fffffffffffffffffffffffff0000000000000000000000000000000000000000821617600355167ff9e093782db3a0fed57e2066a601109931c0b3471fc88692e39625498b6202fb5f80a3005b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602073ffffffffffffffffffffffffffffffffffffffff600b5416604051908152f35b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602073ffffffffffffffffffffffffffffffffffffffff60025416604051908152f35b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382575f6101a060405161095281612f44565b8281528260208201528260408201528260608201528260808201528260a08201528260c08201528260e0820152826101008201528261012082015282610140820152826101608201528261018082015201526101c060206040516109b581612f44565b60018152818101905f82526040810160018152606082015f8152608083016001815260a084015f815260c085016001815260e0860190600182526101008701925f84526101208801945f8652610140890196600188526101608a019860018a526101a06101808c019b5f8d52019b5f8d526040519d8e916001835251151591015251151560408d015251151560608c015251151560808b015251151560a08a015251151560c089015251151560e08801525115156101008701525115156101208601525115156101408501525115156101608401525115156101808301525115156101a0820152f35b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576020600754604051908152f35b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760043573ffffffffffffffffffffffffffffffffffffffff60055416330361071c57805f52600c60205260ff60405f205416610b9957805f52600c60205260405f2060017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff008254161790557f41ae852bd4986bdb048f0e9fe3e32c8d368d22693a4853f4bb5d6eb35f563f7a5f80a2005b7f6bedb188000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602073ffffffffffffffffffffffffffffffffffffffff60015416604051908152f35b34610382577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360160c081126103825760a013610382576060610c5e610c59612c19565b613240565b9060405192151583521515602083015215156040820152f35b34610382577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360160e081126103825760a01361038257610cb6612c19565b60c43590811515918281036103825773ffffffffffffffffffffffffffffffffffffffff60055416330361071c5773ffffffffffffffffffffffffffffffffffffffff821691821561032e577f784cae19d63e2e54635d5faa8f12dfcd2b72dd8f81bc1536d45357e441a51ef89260a0610d2f36612fbe565b209460405191610d3e83612efb565b825260208201908152855f52600960205273ffffffffffffffffffffffffffffffffffffffff60405f209251167fffffffffffffffffffffffff00000000000000000000000000000000000000008354161782555115157fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff74ff000000000000000000000000000000000000000083549260a01b169116179055610e0c6040519283928390929160209073ffffffffffffffffffffffffffffffffffffffff60408401951683521515910152565b0390a2005b346103825760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257600435610e4b612bd3565b73ffffffffffffffffffffffffffffffffffffffff60055416330361071c57815f52600c60205260ff60405f20541615610ed75773ffffffffffffffffffffffffffffffffffffffff90825f52600d60205260405f208282165f526020525f604081205516907f1b657c620098024c31a71bd93ec7ab15587b2cb33d293dc18e899b7d6b8312275f80a3005b507fb5804118000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257610f3a612bf6565b73ffffffffffffffffffffffffffffffffffffffff6004541633036103565773ffffffffffffffffffffffffffffffffffffffff16801561032e5773ffffffffffffffffffffffffffffffffffffffff600154827fffffffffffffffffffffffff0000000000000000000000000000000000000000821617600155167fca394f95d8dbf1e8b2e76b9a8da90cacce1da85181a65508dab13212dc1df53b5f80a3005b34610382576101607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257611014612bf6565b5060a07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc3601126103825760607fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff3c360112610382576101443567ffffffffffffffff81116103825761108a903690600401612c5d565b505073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000001633036104575760406110d761012435614066565b7fffffffff00000000000000000000000000000000000000000000000000000000835192168252600f0b6020820152f35b346103825760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760a061114236612fbe565b205f5260096020526111a160405f2054604051918173ffffffffffffffffffffffffffffffffffffffff60ff859460a01c1691168390929160209073ffffffffffffffffffffffffffffffffffffffff60408401951683521515910152565b0390f35b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760043573ffffffffffffffffffffffffffffffffffffffff60045416330361035657620f4240811161122c57600654816006557e3b413cf14a67407425bd0b5c065b2de08876554d8489ad7dd4aa95604d280c5f80a3005b7f4a856718000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b346103825760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825773ffffffffffffffffffffffffffffffffffffffff60055416330361071c5760a06112b036612fbe565b205f818152600e6020526040812080549082905591907f8eefd920ae5764b15adf66795346bd0d627327b2af2e698ff9050486667f30549080a3005b346103825760c07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257611323612bf6565b60a07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc3601126103825773ffffffffffffffffffffffffffffffffffffffff16604051907f313ce567000000000000000000000000000000000000000000000000000000008252602082600481845afa91821561151a575f9261160e575b5060a0600491604051928380927ffeaf968c0000000000000000000000000000000000000000000000000000000082525afa90811561151a575f916115c1575b508060a06113f036602461308a565b205f52600960205260ff60405f205460a01c165f14611525576044359273ffffffffffffffffffffffffffffffffffffffff84169384810361038257846114a457506020935060125b915b60ff831660ff83168181115f146114735750505061146061146b93926114659261312e565b61316f565b906131be565b604051908152f35b93919310611484575b50505061146b565b61149c9350611496916114609161312e565b90613180565b82808061147c565b60049460209150604051958680927f313ce5670000000000000000000000000000000000000000000000000000000082525afa801561151a576020945f916114ed575b50611439565b61150d9150853d8711611513575b6115058183612f7d565b8101906130fe565b856114e7565b503d6114fb565b6040513d5f823e3d90fd5b6024359273ffffffffffffffffffffffffffffffffffffffff841693848103610382578461155b57506020935060125b9161143b565b60049460209150604051958680927f313ce5670000000000000000000000000000000000000000000000000000000082525afa801561151a576020945f916115a4575b50611555565b6115bb9150853d8711611513576115058183612f7d565b8561159e565b905060a0813d60a011611606575b816115dc60a09383612f7d565b81010312610382576115ed81613117565b506115ff608060208301519201613117565b50826113e1565b3d91506115cf565b600491925061162d60a09160203d602011611513576115058183612f7d565b9291506113a1565b346103825761164336612d56565b5050505050505073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000163303610457577f0a85dc29000000000000000000000000000000000000000000000000000000005f5260045ffd5b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576116e6612bf6565b6005549073ffffffffffffffffffffffffffffffffffffffff82169081330361071c5773ffffffffffffffffffffffffffffffffffffffff1691821561032e577fffffffffffffffffffffffff00000000000000000000000000000000000000001682176005557f45365411c3e9129f7be193ff6605177702fb3e87561f579dc9c9b7618d6366605f80a3005b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602073ffffffffffffffffffffffffffffffffffffffff60035416604051908152f35b346103825760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825773ffffffffffffffffffffffffffffffffffffffff60055416330361071c5760a061181d36612fbe565b20805f52600a60205260405f207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0081541690557f5426ee8913abe0348f9b1853fe58185c5bba29d9f453932d82c2f398656cdcf15f80a2005b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576020600654604051908152f35b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825773ffffffffffffffffffffffffffffffffffffffff60045416330361035657611906614494565b60017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff005f5416175f557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586020604051338152a1005b346103825760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825773ffffffffffffffffffffffffffffffffffffffff60055416330361071c5760a06119b436612fbe565b20805f52600a60205260405f2060017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff008254161790557f320d1812dbf67ff1b70fe61860ed3dea465c55622f697ddae51a3c95e6d501135f80a2005b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576004355f5260096020526111a160405f2054604051918173ffffffffffffffffffffffffffffffffffffffff60ff859460a01c1691168390929160209073ffffffffffffffffffffffffffffffffffffffff60408401951683521515910152565b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602073ffffffffffffffffffffffffffffffffffffffff5f5460081c16604051908152f35b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576004355f526008602052602062ffffff60405f205416604051908152f35b34610382576101007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257611b78612bf6565b5060a07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc36011261038257611bab612e27565b50611bb4612e4a565b5073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000163303610457577f0a85dc29000000000000000000000000000000000000000000000000000000005f5260045ffd5b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602062ffffff60055460a01c16604051908152f35b346103825760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760a0611c9736612fbe565b205f52600e602052602060405f2054604051908152f35b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257611ce5612bf6565b73ffffffffffffffffffffffffffffffffffffffff6004541633036103565773ffffffffffffffffffffffffffffffffffffffff811690811561032e5773ffffffffffffffffffffffffffffffffffffffff9074ffffffffffffffffffffffffffffffffffffffff005f549160081b167fffffffffffffffffffffff0000000000000000000000000000000000000000ff8216175f5560081c167f9ee681927833c2398c73d0f5b2a218383929087bada1b839781887af24e6bb025f80a3005b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602060ff5f54166040519015158152f35b34610382576101407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257611e1c612bf6565b60a07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc3601126103825760607fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff3c360112610382576101243567ffffffffffffffff811161038257611e91903690600401612c5d565b9173ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000001633036104575760ff5f541661200457604051611ee481612f61565b60243573ffffffffffffffffffffffffffffffffffffffff8116810361038257815260443573ffffffffffffffffffffffffffffffffffffffff8116810361038257602082015260643562ffffff811681036103825760408201526084358060020b810361038257606082015260a4359073ffffffffffffffffffffffffffffffffffffffff821682036103825760a091608082015220805f52600a60205260ff60405f205416611fd957606062ffffff611fa086868661346c565b907fffffffff00000000000000000000000000000000000000000000000000000000604094939451941684526020840152166040820152f35b7ff6eb2251000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b7fab35696f000000000000000000000000000000000000000000000000000000005f5260045ffd5b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576004355f52600a602052602060ff60405f2054166040519015158152f35b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576120b0612bf6565b73ffffffffffffffffffffffffffffffffffffffff6004541633036103565773ffffffffffffffffffffffffffffffffffffffff16801561032e5773ffffffffffffffffffffffffffffffffffffffff600254827fffffffffffffffffffffffff0000000000000000000000000000000000000000821617600255167ff7248061c47e1cf157db85f3c9bac5cb0007cbb8867be0807f6dcdb7eb8f52685f80a3005b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825773ffffffffffffffffffffffffffffffffffffffff600454163303610356575f5460ff8116156121fa577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00165f557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa6020604051338152a1005b7f8dfc202b000000000000000000000000000000000000000000000000000000005f5260045ffd5b346103825760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760a061225e36600461308a565b2060405160208101918252600660408201526040815261227f606082612f7d565b519020604051907f1e2eaeaf000000000000000000000000000000000000000000000000000000008252600482015260208160248173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000165afa801561151a575f906123fc575b73ffffffffffffffffffffffffffffffffffffffff9150166401000276a3811080156123df575b6123b4578061232f916132d5565b61234161233b826133ee565b91613426565b90801561238957811561235d5760409182519182526020820152f35b507fc881dfc1000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b7ffe022ea6000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b7f6b321609000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b5073fffd8963efd1fc6a506488495d951d5263988d268111612321565b506020813d60201161243a575b8161241660209383612f7d565b810103126103825773ffffffffffffffffffffffffffffffffffffffff90516122fa565b3d9150612409565b346103825760807ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760043561247c612bd3565b9060443591821515809303610382576064358015158091036103825773ffffffffffffffffffffffffffffffffffffffff60055416330361071c57825f52600c60205260ff60405f205416156125a25773ffffffffffffffffffffffffffffffffffffffff7f85ca9edad330f6dc1008725309246b3fdc3769c13e2434fb9770991f44abeb2492604092835161251181612efb565b87815260208101828152875f52600d602052855f208585165f52602052855f209151151560ff7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0084541691161782555115157fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff61ff0083549260081b169116179055835196875260208701521693a3005b827fb5804118000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760043573ffffffffffffffffffffffffffffffffffffffff81168091036103825773ffffffffffffffffffffffffffffffffffffffff60045416330361035657801561032e5773ffffffffffffffffffffffffffffffffffffffff600b54827fffffffffffffffffffffffff0000000000000000000000000000000000000000821617600b55167f92606658741484a06da44fb0916b7e3bd10d7123a3f8385fc3b540671591a31e5f80a3005b34610382576126b836612c8b565b5050919073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000001633036104575760ff5f54166120045760a061270e368361308a565b20805f52600a60205260ff60405f205416611fd957506060612732930135916142a5565b60206040517f259982e5000000000000000000000000000000000000000000000000000000008152f35b346103825761276a36612c8b565b5050919073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000001633036104575760ff5f54166120045760a06127c0368361308a565b20805f52600a60205260ff60405f205416611fd9575060606127e4930135916142a5565b60206040517f21d0ee70000000000000000000000000000000000000000000000000000000008152f35b346103825760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825773ffffffffffffffffffffffffffffffffffffffff60055416330361071c5760a061286736612fbe565b20805f52600960205273ffffffffffffffffffffffffffffffffffffffff60405f205416156128c457805f5260096020525f60408120557f1fa7adc33dd794fa7af3591a807ea327491700ae41f9a3e1eb8cbf9171865d2f5f80a2005b7f76e06d74000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760043573ffffffffffffffffffffffffffffffffffffffff60055416330361071c57620f4240811161297757600754816007557fd6c414670dee6af93dc1053ea827d2cd46d232651726ea67447c141e977b303c5f80a3005b7f56855fcb000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b34610382577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360160c081126103825760a0136103825760a43562ffffff81168091036103825773ffffffffffffffffffffffffffffffffffffffff60055416330361071c57620f42408111612a7e577f5b753eaf7438ed5e05c956935e54328fc2a0a61497bd9cc7383e4de3881fd2da602060a0612a4036612fbe565b2092835f526008825260405f20817fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000825416179055604051908152a2005b7f1c068a62000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602073ffffffffffffffffffffffffffffffffffffffff60045416604051908152f35b34610382577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360160c081126103825760a0136103825760a43573ffffffffffffffffffffffffffffffffffffffff60055416330361071c57805f52600c60205260ff60405f20541615612ba85760a0612b7336612fbe565b20805f52600e6020528160405f20557f427f407d4af5bf85493cc041cd295af87c2e645ded8f1450133b2d2fc6a8e4695f80a3005b7fb5804118000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b6024359073ffffffffffffffffffffffffffffffffffffffff8216820361038257565b6004359073ffffffffffffffffffffffffffffffffffffffff8216820361038257565b60a4359073ffffffffffffffffffffffffffffffffffffffff8216820361038257565b359073ffffffffffffffffffffffffffffffffffffffff8216820361038257565b9181601f840112156103825782359167ffffffffffffffff8311610382576020838186019501011161038257565b906101607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc8301126103825760043573ffffffffffffffffffffffffffffffffffffffff81168103610382579160a07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc8201126103825760249160807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff3c8301126103825760c491610144359067ffffffffffffffff821161038257612d5291600401612c5d565b9091565b906101a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc8301126103825760043573ffffffffffffffffffffffffffffffffffffffff81168103610382579160a07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc8201126103825760249160807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff3c8301126103825760c49161014435916101643591610184359067ffffffffffffffff821161038257612d5291600401612c5d565b60c4359073ffffffffffffffffffffffffffffffffffffffff8216820361038257565b60e435908160020b820361038257565b6101207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc8201126103825760043573ffffffffffffffffffffffffffffffffffffffff81168103610382579160a07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc8301126103825760249160c4359160e43591610104359067ffffffffffffffff821161038257612d5291600401612c5d565b6040810190811067ffffffffffffffff821117612f1757604052565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b6101c0810190811067ffffffffffffffff821117612f1757604052565b60a0810190811067ffffffffffffffff821117612f1757604052565b90601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0910116810190811067ffffffffffffffff821117612f1757604052565b7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc60a09101126103825760405190612ff582612f61565b8160043573ffffffffffffffffffffffffffffffffffffffff8116810361038257815260243573ffffffffffffffffffffffffffffffffffffffff8116810361038257602082015260443562ffffff811681036103825760408201526064358060020b81036103825760608201526084359073ffffffffffffffffffffffffffffffffffffffff821682036103825760800152565b91908260a0910312610382576040516130a281612f61565b80926130ad81612c3c565b82526130bb60208201612c3c565b6020830152604081013562ffffff811681036103825760408301526060810135908160020b82036103825760806130f9918193606086015201612c3c565b910152565b90816020910312610382575160ff811681036103825790565b519069ffffffffffffffffffff8216820361038257565b9060ff8091169116039060ff821161314257565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b60ff16604d811161314257600a0a90565b81810292915f82127f800000000000000000000000000000000000000000000000000000000000000082141661314257818405149015171561314257565b8115613213577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82147f8000000000000000000000000000000000000000000000000000000000000000821416613142570590565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b60a061324d36600461308a565b205f52600e60205260405f205480156132c8575f52600d60205273ffffffffffffffffffffffffffffffffffffffff60405f2091165f52602052602060405f20916040519261329b84612efb565b549260ff8416159060ff82159586835260081c161515938491015283906132c157929190565b5081929190565b5050600190600190600190565b90808202917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff828209918380841093039280840393846c0100000000000000000000000011156103825714613346576c01000000000000000000000000910990828211900360a01b910360601c1790565b50505060601c90565b91818302917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8185099383808610950394808603958685111561038257146133e6579082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b505091500490565b906c01000000000000000000000000670de0b6b3a764000061341182828661334f565b930961341957565b9060010190811561038257565b9061344782670de0b6b3a76400006c0100000000000000000000000061334f565b91801561321357670de0b6b3a76400006c010000000000000000000000000961341957565b915f9273ffffffffffffffffffffffffffffffffffffffff806001541691169081141580613fdf575b613fb457508160209181010312610382573573ffffffffffffffffffffffffffffffffffffffff8116809103610382576024602073ffffffffffffffffffffffffffffffffffffffff600b5416604051928380927f97f8e2ab0000000000000000000000000000000000000000000000000000000082528660048301525afa90811561151a575f91613f85575b5015613f5a5760a061353536602461308a565b20805f52600e60205260405f2054918215159081613f21575b50613ef357505060c4357f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff168115801583036103825760a06135a636602461308a565b206040516020810191825260066040820152604081526135c7606082612f7d565b519020604051907f1e2eaeaf0000000000000000000000000000000000000000000000000000000082526004820152602081602481865afa801561151a575f90613ead575b73ffffffffffffffffffffffffffffffffffffffff9150166401000276a381108015613e90575b6123b45780613641916132d5565b9061365461364e836133ee565b92613426565b918015612389578215613e645762ffffff60055460a01c1660a061367936602461308a565b205f9081526008602052604090205462ffffff1615613e5e575060a06136a036602461308a565b205f52600860205262ffffff60405f205416915b829360a06136c336602461308a565b205f52600960205260405f2093604051946136dd86612efb565b549460ff602073ffffffffffffffffffffffffffffffffffffffff881692838152019660a01c1615158652806139f1575b505050505050813b1561038257604051907f527596510000000000000000000000000000000000000000000000000000000082526024359173ffffffffffffffffffffffffffffffffffffffff83168084036103825760048201526044359173ffffffffffffffffffffffffffffffffffffffff831680840361038257602483015260643562ffffff81168091036103825760448301526084358060020b80910361038257606483015260a4359073ffffffffffffffffffffffffffffffffffffffff82168092036103825762ffffff9160848401521660a48201525f8160c48183885af1801561151a576139dc575b5060e4358581126138345750505050507f575e24b400000000000000000000000000000000000000000000000000000000918190565b7f800000000000000000000000000000000000000000000000000000000000000081979597146139af57613871620f424091600654908803613180565b05956f7fffffffffffffffffffffffffffffff87131580613985575b61389690614001565b1561397e57505b73ffffffffffffffffffffffffffffffffffffffff6003541690823b1561397a576040517f0b0d9c0900000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff918216600482015291166024820152604481018590529083908290606490829084905af1801561396f57908391613956575b50507f575e24b4000000000000000000000000000000000000000000000000000000009260801b9190565b8161396091612f7d565b61396b57815f61392b565b5080fd5b6040513d85823e3d90fd5b8480fd5b905061389d565b507fffffffffffffffffffffffffffffffff8000000000000000000000000000000087121561388d565b6024867f4e487b710000000000000000000000000000000000000000000000000000000081526011600452fd5b6139e99195505f90612f7d565b5f935f6137fe565b604051907f313ce567000000000000000000000000000000000000000000000000000000008252602082600481845afa91821561151a575f92613e37575b5060a0600491604051928380927ffeaf968c0000000000000000000000000000000000000000000000000000000082525afa90811561151a575f91613dea575b50809160a0613a7f36602461308a565b205f52600960205260ff60405f205460a01c165f14613d0c5760443573ffffffffffffffffffffffffffffffffffffffff811681036103825773ffffffffffffffffffffffffffffffffffffffff8116613c73575060125b915b60ff831660ff83168181115f14613c4357505050611460613afe93926114659261312e565b945b8515613c1b575115613b9c57505082821180613b95575b15613b565750613b4482613b3f613b36613b4b969562ffffff956144c7565b600754906144d4565b6144e7565b16906144f1565b5f808080808061370e565b8282109081613b8d575b50613b6d575b5050613b4b565b613b4482613b3f613b3662ffffff94613b8697966144c7565b5f80613b66565b90505f613b60565b5085613b17565b90919493809350821080613c14575b15613bd05750613bcb935081613b3f613b36613b449362ffffff956144c7565b613b4b565b92938282119081613c0c575b50613bea575b505050613b4b565b613c04935081613b3f613b3662ffffff94613b44946144c7565b5f8080613be2565b90505f613bdc565b5086613bab565b7f579595ac000000000000000000000000000000000000000000000000000000005f5260045ffd5b99949993919310613c57575b505050613b00565b613c6a939850611496916114609161312e565b945f8080613c4f565b73ffffffffffffffffffffffffffffffffffffffff811681036103825760208173ffffffffffffffffffffffffffffffffffffffff92506004604051809481937f313ce567000000000000000000000000000000000000000000000000000000008352165afa90811561151a575f91613ced575b50613ad7565b613d06915060203d602011611513576115058183612f7d565b5f613ce7565b60243573ffffffffffffffffffffffffffffffffffffffff811681036103825773ffffffffffffffffffffffffffffffffffffffff8116613d51575060125b91613ad9565b73ffffffffffffffffffffffffffffffffffffffff811681036103825760208173ffffffffffffffffffffffffffffffffffffffff92506004604051809481937f313ce567000000000000000000000000000000000000000000000000000000008352165afa90811561151a575f91613dcb575b50613d4b565b613de4915060203d602011611513576115058183612f7d565b5f613dc5565b905060a0813d60a011613e2f575b81613e0560a09383612f7d565b8101031261038257613e1681613117565b50613e28608060208301519201613117565b505f613a6f565b3d9150613df8565b6004919250613e5660a09160203d602011611513576115058183612f7d565b929150613a2f565b916136b4565b827fc881dfc1000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b5073fffd8963efd1fc6a506488495d951d5263988d268111613633565b506020813d602011613eeb575b81613ec760209383612f7d565b810103126103825773ffffffffffffffffffffffffffffffffffffffff905161360c565b3d9150613eba565b7f22a8be08000000000000000000000000000000000000000000000000000000005f5260045260245260445ffd5b9050825f52600d60205273ffffffffffffffffffffffffffffffffffffffff60405f2091165f5260205260ff60405f205416155f61354e565b7f4036ba6b000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b613fa7915060203d602011613fad575b613f9f8183612f7d565b81019061428d565b5f613522565b503d613f95565b7f42d0e2e1000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b5073ffffffffffffffffffffffffffffffffffffffff60025416811415613495565b1561400857565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600c60248201527f466565206f766572666c6f7700000000000000000000000000000000000000006044820152fd5b905f915f60e4351361409857507fb47b2fb1000000000000000000000000000000000000000000000000000000009190565b60c435925082151583036103825782156142855760801d5b600f0b7fffffffffffffffffffffffffffffffff800000000000000000000000000000008114613142576140f0620f424091600654905f03600f0b613180565b05916f7fffffffffffffffffffffffffffffff8313158061425b575b61411590614001565b156142375760243573ffffffffffffffffffffffffffffffffffffffff81168103610382575b73ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000169073ffffffffffffffffffffffffffffffffffffffff6003541690823b15610382576040517f0b0d9c0900000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff91821660048201529116602482015260448101849052905f908290606490829084905af1801561151a57614227575b507fb47b2fb10000000000000000000000000000000000000000000000000000000091600f0b90565b5f61423191612f7d565b5f6141fe565b60443573ffffffffffffffffffffffffffffffffffffffff8116811461413b575f80fd5b507fffffffffffffffffffffffffffffffff8000000000000000000000000000000083121561410c565b600f0b6140b0565b90816020910312610382575180151581036103825790565b9173ffffffffffffffffffffffffffffffffffffffff805f5460081c16931683810361446957506020906024604051809581937f6352211e00000000000000000000000000000000000000000000000000000000835260048301525afa91821561151a575f92614418575b5073ffffffffffffffffffffffffffffffffffffffff602081600b5416936024604051809481937f9746656200000000000000000000000000000000000000000000000000000000835216968760048301525afa90811561151a575f916143f9575b50156143cd5761438560a091369061308a565b20805f52600e60205260405f20549182151590816143a7575b50613ef3575050565b9050825f52600d60205260405f20905f5260205260ff60405f205460081c16155f61439e565b507f353b811a000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b614412915060203d602011613fad57613f9f8183612f7d565b5f614372565b9091506020813d602011614461575b8161443460209383612f7d565b81010312610382575173ffffffffffffffffffffffffffffffffffffffff8116810361038257905f614310565b3d9150614427565b7f3afe49ea000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b60ff5f541661449f57565b7fd93c0665000000000000000000000000000000000000000000000000000000005f5260045ffd5b9190820391821161314257565b8181029291811591840414171561314257565b8115613213570490565b9062ffffff8091169116019062ffffff82116131425756fea164736f6c634300081a000a00000000000000000000000000b036b58a818b1bc34d502d3fe730db729e62ac0000000000000000000000005d7df7b73a0d67b4a11297475184dc645be56cc400000000000000000000000048bbb8f2836b9797a5682f80b6ad5fb999b35430000000000000000000000000bb8f2f659ecbd0ce8fe3ec4e9001f1e8167b3a5a000000000000000000000000a5ab51e02b65994a269dcd8dc4b9f7df6a63906300000000000000000000000056dcd40a3f2d466f48e7f48bdbe5cc9b92ae4472000000000000000000000000dfcd46794357af78994c813a378eca96293524d40000000000000000000000004cf2adfa1a53f4d53fcd0d7851512ebe581e7509

Deployed Bytecode

0x60806040526004361015610011575f80fd5b5f3560e01c80624f07f514612afa578063085d488314612aa957806309846580146129a25780630c450bcd146128ef5780631e2cbb7d1461280e57806321d0ee701461275c578063259982e5146126aa5780632e027230146125ce578063341d7eec1461244257806339747b33146122225780633f4ba83a14612152578063426172d6146120795780634327623d1461202c578063575e24b414611de45780635c975abb14611da55780636881d8cb14611cae5780636c2bbe7e146116355780636c52f9ae14611c5d5780636ef25c3a14611c1a5780636fe7e6eb14611b40578063758af29d14611af3578063791b98bc14611aa05780637d6913c414611a105780637e6bd2011461195b5780638456cb59146118b15780638abdf5aa146118765780638f0ff5e0146117c45780639ba34035146117735780639c4d8430146116af5780639f063efc14611635578063a30e865c146112ec578063aa33141114611257578063ae4b7c26146111a5578063b327f3c614611108578063b47b2fb114610fdc578063b6a8b0fa146103de578063b98b677f14610f03578063bc7d2e7814610e11578063c0c0f4cd14610c77578063c1c7a1ab14610c15578063c31c9c0714610bc4578063c42994a214610ad9578063c4941e1614610a9e578063c4e833ce14610914578063c6bbd5a7146108c3578063cc7a204914610872578063cce1e4bc14610799578063d1384eb614610748578063d8505b3c14610614578063dc4c90d3146105a6578063dc98354e1461047f578063e1b4af69146103de578063e64927ca146103865763ef70768a1461026a575f80fd5b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576102a1612bf6565b6004549073ffffffffffffffffffffffffffffffffffffffff8216908133036103565773ffffffffffffffffffffffffffffffffffffffff1691821561032e577fffffffffffffffffffffffff00000000000000000000000000000000000000001682176004557fa4652513510d8a8ef70d7c10761c2fd3d3f582d2e903ac7f7a74c3075331f53f5f80a3005b7fd92e233d000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f1bd2224f000000000000000000000000000000000000000000000000000000005f523360045260245ffd5b5f80fd5b346103825760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760a06103c236600461308a565b205f526008602052602062ffffff60405f205416604051908152f35b34610382576103ec36612e5a565b50505050505073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000b036b58a818b1bc34d502d3fe730db729e62ac163303610457577f0a85dc29000000000000000000000000000000000000000000000000000000005f5260045ffd5b7fae18210a000000000000000000000000000000000000000000000000000000005f5260045ffd5b346103825760e07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576104b6612bf6565b60a07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc360112610382576104e8612e27565b5073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000b036b58a818b1bc34d502d3fe730db729e62ac1633036104575761052e614494565b73ffffffffffffffffffffffffffffffffffffffff8060055416911690810361057b5760206040517fdc98354e000000000000000000000000000000000000000000000000000000008152f35b7fbdc4ce88000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602060405173ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000b036b58a818b1bc34d502d3fe730db729e62ac168152f35b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760043562ffffff8116908181036103825760055473ffffffffffffffffffffffffffffffffffffffff8116330361071c57620f424083116106f05776ffffff000000000000000000000000000000000000000062ffffff9260a01b167fffffffffffffffffff000000ffffffffffffffffffffffffffffffffffffffff82161760055560a01c167f434d1e61af6b7d470d22269977887cd1da10bd474fd3e4a0a693abd991b371465f80a3005b827f1c068a62000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b7fbdc4ce88000000000000000000000000000000000000000000000000000000005f523360045260245ffd5b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602073ffffffffffffffffffffffffffffffffffffffff60055416604051908152f35b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576107d0612bf6565b73ffffffffffffffffffffffffffffffffffffffff6004541633036103565773ffffffffffffffffffffffffffffffffffffffff16801561032e5773ffffffffffffffffffffffffffffffffffffffff600354827fffffffffffffffffffffffff0000000000000000000000000000000000000000821617600355167ff9e093782db3a0fed57e2066a601109931c0b3471fc88692e39625498b6202fb5f80a3005b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602073ffffffffffffffffffffffffffffffffffffffff600b5416604051908152f35b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602073ffffffffffffffffffffffffffffffffffffffff60025416604051908152f35b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382575f6101a060405161095281612f44565b8281528260208201528260408201528260608201528260808201528260a08201528260c08201528260e0820152826101008201528261012082015282610140820152826101608201528261018082015201526101c060206040516109b581612f44565b60018152818101905f82526040810160018152606082015f8152608083016001815260a084015f815260c085016001815260e0860190600182526101008701925f84526101208801945f8652610140890196600188526101608a019860018a526101a06101808c019b5f8d52019b5f8d526040519d8e916001835251151591015251151560408d015251151560608c015251151560808b015251151560a08a015251151560c089015251151560e08801525115156101008701525115156101208601525115156101408501525115156101608401525115156101808301525115156101a0820152f35b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576020600754604051908152f35b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760043573ffffffffffffffffffffffffffffffffffffffff60055416330361071c57805f52600c60205260ff60405f205416610b9957805f52600c60205260405f2060017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff008254161790557f41ae852bd4986bdb048f0e9fe3e32c8d368d22693a4853f4bb5d6eb35f563f7a5f80a2005b7f6bedb188000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602073ffffffffffffffffffffffffffffffffffffffff60015416604051908152f35b34610382577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360160c081126103825760a013610382576060610c5e610c59612c19565b613240565b9060405192151583521515602083015215156040820152f35b34610382577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360160e081126103825760a01361038257610cb6612c19565b60c43590811515918281036103825773ffffffffffffffffffffffffffffffffffffffff60055416330361071c5773ffffffffffffffffffffffffffffffffffffffff821691821561032e577f784cae19d63e2e54635d5faa8f12dfcd2b72dd8f81bc1536d45357e441a51ef89260a0610d2f36612fbe565b209460405191610d3e83612efb565b825260208201908152855f52600960205273ffffffffffffffffffffffffffffffffffffffff60405f209251167fffffffffffffffffffffffff00000000000000000000000000000000000000008354161782555115157fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff74ff000000000000000000000000000000000000000083549260a01b169116179055610e0c6040519283928390929160209073ffffffffffffffffffffffffffffffffffffffff60408401951683521515910152565b0390a2005b346103825760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257600435610e4b612bd3565b73ffffffffffffffffffffffffffffffffffffffff60055416330361071c57815f52600c60205260ff60405f20541615610ed75773ffffffffffffffffffffffffffffffffffffffff90825f52600d60205260405f208282165f526020525f604081205516907f1b657c620098024c31a71bd93ec7ab15587b2cb33d293dc18e899b7d6b8312275f80a3005b507fb5804118000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257610f3a612bf6565b73ffffffffffffffffffffffffffffffffffffffff6004541633036103565773ffffffffffffffffffffffffffffffffffffffff16801561032e5773ffffffffffffffffffffffffffffffffffffffff600154827fffffffffffffffffffffffff0000000000000000000000000000000000000000821617600155167fca394f95d8dbf1e8b2e76b9a8da90cacce1da85181a65508dab13212dc1df53b5f80a3005b34610382576101607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257611014612bf6565b5060a07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc3601126103825760607fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff3c360112610382576101443567ffffffffffffffff81116103825761108a903690600401612c5d565b505073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000b036b58a818b1bc34d502d3fe730db729e62ac1633036104575760406110d761012435614066565b7fffffffff00000000000000000000000000000000000000000000000000000000835192168252600f0b6020820152f35b346103825760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760a061114236612fbe565b205f5260096020526111a160405f2054604051918173ffffffffffffffffffffffffffffffffffffffff60ff859460a01c1691168390929160209073ffffffffffffffffffffffffffffffffffffffff60408401951683521515910152565b0390f35b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760043573ffffffffffffffffffffffffffffffffffffffff60045416330361035657620f4240811161122c57600654816006557e3b413cf14a67407425bd0b5c065b2de08876554d8489ad7dd4aa95604d280c5f80a3005b7f4a856718000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b346103825760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825773ffffffffffffffffffffffffffffffffffffffff60055416330361071c5760a06112b036612fbe565b205f818152600e6020526040812080549082905591907f8eefd920ae5764b15adf66795346bd0d627327b2af2e698ff9050486667f30549080a3005b346103825760c07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257611323612bf6565b60a07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc3601126103825773ffffffffffffffffffffffffffffffffffffffff16604051907f313ce567000000000000000000000000000000000000000000000000000000008252602082600481845afa91821561151a575f9261160e575b5060a0600491604051928380927ffeaf968c0000000000000000000000000000000000000000000000000000000082525afa90811561151a575f916115c1575b508060a06113f036602461308a565b205f52600960205260ff60405f205460a01c165f14611525576044359273ffffffffffffffffffffffffffffffffffffffff84169384810361038257846114a457506020935060125b915b60ff831660ff83168181115f146114735750505061146061146b93926114659261312e565b61316f565b906131be565b604051908152f35b93919310611484575b50505061146b565b61149c9350611496916114609161312e565b90613180565b82808061147c565b60049460209150604051958680927f313ce5670000000000000000000000000000000000000000000000000000000082525afa801561151a576020945f916114ed575b50611439565b61150d9150853d8711611513575b6115058183612f7d565b8101906130fe565b856114e7565b503d6114fb565b6040513d5f823e3d90fd5b6024359273ffffffffffffffffffffffffffffffffffffffff841693848103610382578461155b57506020935060125b9161143b565b60049460209150604051958680927f313ce5670000000000000000000000000000000000000000000000000000000082525afa801561151a576020945f916115a4575b50611555565b6115bb9150853d8711611513576115058183612f7d565b8561159e565b905060a0813d60a011611606575b816115dc60a09383612f7d565b81010312610382576115ed81613117565b506115ff608060208301519201613117565b50826113e1565b3d91506115cf565b600491925061162d60a09160203d602011611513576115058183612f7d565b9291506113a1565b346103825761164336612d56565b5050505050505073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000b036b58a818b1bc34d502d3fe730db729e62ac163303610457577f0a85dc29000000000000000000000000000000000000000000000000000000005f5260045ffd5b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576116e6612bf6565b6005549073ffffffffffffffffffffffffffffffffffffffff82169081330361071c5773ffffffffffffffffffffffffffffffffffffffff1691821561032e577fffffffffffffffffffffffff00000000000000000000000000000000000000001682176005557f45365411c3e9129f7be193ff6605177702fb3e87561f579dc9c9b7618d6366605f80a3005b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602073ffffffffffffffffffffffffffffffffffffffff60035416604051908152f35b346103825760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825773ffffffffffffffffffffffffffffffffffffffff60055416330361071c5760a061181d36612fbe565b20805f52600a60205260405f207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0081541690557f5426ee8913abe0348f9b1853fe58185c5bba29d9f453932d82c2f398656cdcf15f80a2005b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576020600654604051908152f35b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825773ffffffffffffffffffffffffffffffffffffffff60045416330361035657611906614494565b60017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff005f5416175f557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586020604051338152a1005b346103825760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825773ffffffffffffffffffffffffffffffffffffffff60055416330361071c5760a06119b436612fbe565b20805f52600a60205260405f2060017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff008254161790557f320d1812dbf67ff1b70fe61860ed3dea465c55622f697ddae51a3c95e6d501135f80a2005b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576004355f5260096020526111a160405f2054604051918173ffffffffffffffffffffffffffffffffffffffff60ff859460a01c1691168390929160209073ffffffffffffffffffffffffffffffffffffffff60408401951683521515910152565b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602073ffffffffffffffffffffffffffffffffffffffff5f5460081c16604051908152f35b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576004355f526008602052602062ffffff60405f205416604051908152f35b34610382576101007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257611b78612bf6565b5060a07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc36011261038257611bab612e27565b50611bb4612e4a565b5073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000b036b58a818b1bc34d502d3fe730db729e62ac163303610457577f0a85dc29000000000000000000000000000000000000000000000000000000005f5260045ffd5b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602062ffffff60055460a01c16604051908152f35b346103825760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760a0611c9736612fbe565b205f52600e602052602060405f2054604051908152f35b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257611ce5612bf6565b73ffffffffffffffffffffffffffffffffffffffff6004541633036103565773ffffffffffffffffffffffffffffffffffffffff811690811561032e5773ffffffffffffffffffffffffffffffffffffffff9074ffffffffffffffffffffffffffffffffffffffff005f549160081b167fffffffffffffffffffffff0000000000000000000000000000000000000000ff8216175f5560081c167f9ee681927833c2398c73d0f5b2a218383929087bada1b839781887af24e6bb025f80a3005b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602060ff5f54166040519015158152f35b34610382576101407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257611e1c612bf6565b60a07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc3601126103825760607fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff3c360112610382576101243567ffffffffffffffff811161038257611e91903690600401612c5d565b9173ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000b036b58a818b1bc34d502d3fe730db729e62ac1633036104575760ff5f541661200457604051611ee481612f61565b60243573ffffffffffffffffffffffffffffffffffffffff8116810361038257815260443573ffffffffffffffffffffffffffffffffffffffff8116810361038257602082015260643562ffffff811681036103825760408201526084358060020b810361038257606082015260a4359073ffffffffffffffffffffffffffffffffffffffff821682036103825760a091608082015220805f52600a60205260ff60405f205416611fd957606062ffffff611fa086868661346c565b907fffffffff00000000000000000000000000000000000000000000000000000000604094939451941684526020840152166040820152f35b7ff6eb2251000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b7fab35696f000000000000000000000000000000000000000000000000000000005f5260045ffd5b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576004355f52600a602052602060ff60405f2054166040519015158152f35b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610382576120b0612bf6565b73ffffffffffffffffffffffffffffffffffffffff6004541633036103565773ffffffffffffffffffffffffffffffffffffffff16801561032e5773ffffffffffffffffffffffffffffffffffffffff600254827fffffffffffffffffffffffff0000000000000000000000000000000000000000821617600255167ff7248061c47e1cf157db85f3c9bac5cb0007cbb8867be0807f6dcdb7eb8f52685f80a3005b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825773ffffffffffffffffffffffffffffffffffffffff600454163303610356575f5460ff8116156121fa577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00165f557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa6020604051338152a1005b7f8dfc202b000000000000000000000000000000000000000000000000000000005f5260045ffd5b346103825760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760a061225e36600461308a565b2060405160208101918252600660408201526040815261227f606082612f7d565b519020604051907f1e2eaeaf000000000000000000000000000000000000000000000000000000008252600482015260208160248173ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000b036b58a818b1bc34d502d3fe730db729e62ac165afa801561151a575f906123fc575b73ffffffffffffffffffffffffffffffffffffffff9150166401000276a3811080156123df575b6123b4578061232f916132d5565b61234161233b826133ee565b91613426565b90801561238957811561235d5760409182519182526020820152f35b507fc881dfc1000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b7ffe022ea6000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b7f6b321609000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b5073fffd8963efd1fc6a506488495d951d5263988d268111612321565b506020813d60201161243a575b8161241660209383612f7d565b810103126103825773ffffffffffffffffffffffffffffffffffffffff90516122fa565b3d9150612409565b346103825760807ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760043561247c612bd3565b9060443591821515809303610382576064358015158091036103825773ffffffffffffffffffffffffffffffffffffffff60055416330361071c57825f52600c60205260ff60405f205416156125a25773ffffffffffffffffffffffffffffffffffffffff7f85ca9edad330f6dc1008725309246b3fdc3769c13e2434fb9770991f44abeb2492604092835161251181612efb565b87815260208101828152875f52600d602052855f208585165f52602052855f209151151560ff7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0084541691161782555115157fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff61ff0083549260081b169116179055835196875260208701521693a3005b827fb5804118000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760043573ffffffffffffffffffffffffffffffffffffffff81168091036103825773ffffffffffffffffffffffffffffffffffffffff60045416330361035657801561032e5773ffffffffffffffffffffffffffffffffffffffff600b54827fffffffffffffffffffffffff0000000000000000000000000000000000000000821617600b55167f92606658741484a06da44fb0916b7e3bd10d7123a3f8385fc3b540671591a31e5f80a3005b34610382576126b836612c8b565b5050919073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000b036b58a818b1bc34d502d3fe730db729e62ac1633036104575760ff5f54166120045760a061270e368361308a565b20805f52600a60205260ff60405f205416611fd957506060612732930135916142a5565b60206040517f259982e5000000000000000000000000000000000000000000000000000000008152f35b346103825761276a36612c8b565b5050919073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000b036b58a818b1bc34d502d3fe730db729e62ac1633036104575760ff5f54166120045760a06127c0368361308a565b20805f52600a60205260ff60405f205416611fd9575060606127e4930135916142a5565b60206040517f21d0ee70000000000000000000000000000000000000000000000000000000008152f35b346103825760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825773ffffffffffffffffffffffffffffffffffffffff60055416330361071c5760a061286736612fbe565b20805f52600960205273ffffffffffffffffffffffffffffffffffffffff60405f205416156128c457805f5260096020525f60408120557f1fa7adc33dd794fa7af3591a807ea327491700ae41f9a3e1eb8cbf9171865d2f5f80a2005b7f76e06d74000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b346103825760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103825760043573ffffffffffffffffffffffffffffffffffffffff60055416330361071c57620f4240811161297757600754816007557fd6c414670dee6af93dc1053ea827d2cd46d232651726ea67447c141e977b303c5f80a3005b7f56855fcb000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b34610382577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360160c081126103825760a0136103825760a43562ffffff81168091036103825773ffffffffffffffffffffffffffffffffffffffff60055416330361071c57620f42408111612a7e577f5b753eaf7438ed5e05c956935e54328fc2a0a61497bd9cc7383e4de3881fd2da602060a0612a4036612fbe565b2092835f526008825260405f20817fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000825416179055604051908152a2005b7f1c068a62000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b34610382575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261038257602073ffffffffffffffffffffffffffffffffffffffff60045416604051908152f35b34610382577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360160c081126103825760a0136103825760a43573ffffffffffffffffffffffffffffffffffffffff60055416330361071c57805f52600c60205260ff60405f20541615612ba85760a0612b7336612fbe565b20805f52600e6020528160405f20557f427f407d4af5bf85493cc041cd295af87c2e645ded8f1450133b2d2fc6a8e4695f80a3005b7fb5804118000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b6024359073ffffffffffffffffffffffffffffffffffffffff8216820361038257565b6004359073ffffffffffffffffffffffffffffffffffffffff8216820361038257565b60a4359073ffffffffffffffffffffffffffffffffffffffff8216820361038257565b359073ffffffffffffffffffffffffffffffffffffffff8216820361038257565b9181601f840112156103825782359167ffffffffffffffff8311610382576020838186019501011161038257565b906101607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc8301126103825760043573ffffffffffffffffffffffffffffffffffffffff81168103610382579160a07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc8201126103825760249160807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff3c8301126103825760c491610144359067ffffffffffffffff821161038257612d5291600401612c5d565b9091565b906101a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc8301126103825760043573ffffffffffffffffffffffffffffffffffffffff81168103610382579160a07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc8201126103825760249160807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff3c8301126103825760c49161014435916101643591610184359067ffffffffffffffff821161038257612d5291600401612c5d565b60c4359073ffffffffffffffffffffffffffffffffffffffff8216820361038257565b60e435908160020b820361038257565b6101207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc8201126103825760043573ffffffffffffffffffffffffffffffffffffffff81168103610382579160a07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc8301126103825760249160c4359160e43591610104359067ffffffffffffffff821161038257612d5291600401612c5d565b6040810190811067ffffffffffffffff821117612f1757604052565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b6101c0810190811067ffffffffffffffff821117612f1757604052565b60a0810190811067ffffffffffffffff821117612f1757604052565b90601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0910116810190811067ffffffffffffffff821117612f1757604052565b7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc60a09101126103825760405190612ff582612f61565b8160043573ffffffffffffffffffffffffffffffffffffffff8116810361038257815260243573ffffffffffffffffffffffffffffffffffffffff8116810361038257602082015260443562ffffff811681036103825760408201526064358060020b81036103825760608201526084359073ffffffffffffffffffffffffffffffffffffffff821682036103825760800152565b91908260a0910312610382576040516130a281612f61565b80926130ad81612c3c565b82526130bb60208201612c3c565b6020830152604081013562ffffff811681036103825760408301526060810135908160020b82036103825760806130f9918193606086015201612c3c565b910152565b90816020910312610382575160ff811681036103825790565b519069ffffffffffffffffffff8216820361038257565b9060ff8091169116039060ff821161314257565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b60ff16604d811161314257600a0a90565b81810292915f82127f800000000000000000000000000000000000000000000000000000000000000082141661314257818405149015171561314257565b8115613213577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82147f8000000000000000000000000000000000000000000000000000000000000000821416613142570590565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b60a061324d36600461308a565b205f52600e60205260405f205480156132c8575f52600d60205273ffffffffffffffffffffffffffffffffffffffff60405f2091165f52602052602060405f20916040519261329b84612efb565b549260ff8416159060ff82159586835260081c161515938491015283906132c157929190565b5081929190565b5050600190600190600190565b90808202917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff828209918380841093039280840393846c0100000000000000000000000011156103825714613346576c01000000000000000000000000910990828211900360a01b910360601c1790565b50505060601c90565b91818302917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8185099383808610950394808603958685111561038257146133e6579082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b505091500490565b906c01000000000000000000000000670de0b6b3a764000061341182828661334f565b930961341957565b9060010190811561038257565b9061344782670de0b6b3a76400006c0100000000000000000000000061334f565b91801561321357670de0b6b3a76400006c010000000000000000000000000961341957565b915f9273ffffffffffffffffffffffffffffffffffffffff806001541691169081141580613fdf575b613fb457508160209181010312610382573573ffffffffffffffffffffffffffffffffffffffff8116809103610382576024602073ffffffffffffffffffffffffffffffffffffffff600b5416604051928380927f97f8e2ab0000000000000000000000000000000000000000000000000000000082528660048301525afa90811561151a575f91613f85575b5015613f5a5760a061353536602461308a565b20805f52600e60205260405f2054918215159081613f21575b50613ef357505060c4357f00000000000000000000000000b036b58a818b1bc34d502d3fe730db729e62ac73ffffffffffffffffffffffffffffffffffffffff168115801583036103825760a06135a636602461308a565b206040516020810191825260066040820152604081526135c7606082612f7d565b519020604051907f1e2eaeaf0000000000000000000000000000000000000000000000000000000082526004820152602081602481865afa801561151a575f90613ead575b73ffffffffffffffffffffffffffffffffffffffff9150166401000276a381108015613e90575b6123b45780613641916132d5565b9061365461364e836133ee565b92613426565b918015612389578215613e645762ffffff60055460a01c1660a061367936602461308a565b205f9081526008602052604090205462ffffff1615613e5e575060a06136a036602461308a565b205f52600860205262ffffff60405f205416915b829360a06136c336602461308a565b205f52600960205260405f2093604051946136dd86612efb565b549460ff602073ffffffffffffffffffffffffffffffffffffffff881692838152019660a01c1615158652806139f1575b505050505050813b1561038257604051907f527596510000000000000000000000000000000000000000000000000000000082526024359173ffffffffffffffffffffffffffffffffffffffff83168084036103825760048201526044359173ffffffffffffffffffffffffffffffffffffffff831680840361038257602483015260643562ffffff81168091036103825760448301526084358060020b80910361038257606483015260a4359073ffffffffffffffffffffffffffffffffffffffff82168092036103825762ffffff9160848401521660a48201525f8160c48183885af1801561151a576139dc575b5060e4358581126138345750505050507f575e24b400000000000000000000000000000000000000000000000000000000918190565b7f800000000000000000000000000000000000000000000000000000000000000081979597146139af57613871620f424091600654908803613180565b05956f7fffffffffffffffffffffffffffffff87131580613985575b61389690614001565b1561397e57505b73ffffffffffffffffffffffffffffffffffffffff6003541690823b1561397a576040517f0b0d9c0900000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff918216600482015291166024820152604481018590529083908290606490829084905af1801561396f57908391613956575b50507f575e24b4000000000000000000000000000000000000000000000000000000009260801b9190565b8161396091612f7d565b61396b57815f61392b565b5080fd5b6040513d85823e3d90fd5b8480fd5b905061389d565b507fffffffffffffffffffffffffffffffff8000000000000000000000000000000087121561388d565b6024867f4e487b710000000000000000000000000000000000000000000000000000000081526011600452fd5b6139e99195505f90612f7d565b5f935f6137fe565b604051907f313ce567000000000000000000000000000000000000000000000000000000008252602082600481845afa91821561151a575f92613e37575b5060a0600491604051928380927ffeaf968c0000000000000000000000000000000000000000000000000000000082525afa90811561151a575f91613dea575b50809160a0613a7f36602461308a565b205f52600960205260ff60405f205460a01c165f14613d0c5760443573ffffffffffffffffffffffffffffffffffffffff811681036103825773ffffffffffffffffffffffffffffffffffffffff8116613c73575060125b915b60ff831660ff83168181115f14613c4357505050611460613afe93926114659261312e565b945b8515613c1b575115613b9c57505082821180613b95575b15613b565750613b4482613b3f613b36613b4b969562ffffff956144c7565b600754906144d4565b6144e7565b16906144f1565b5f808080808061370e565b8282109081613b8d575b50613b6d575b5050613b4b565b613b4482613b3f613b3662ffffff94613b8697966144c7565b5f80613b66565b90505f613b60565b5085613b17565b90919493809350821080613c14575b15613bd05750613bcb935081613b3f613b36613b449362ffffff956144c7565b613b4b565b92938282119081613c0c575b50613bea575b505050613b4b565b613c04935081613b3f613b3662ffffff94613b44946144c7565b5f8080613be2565b90505f613bdc565b5086613bab565b7f579595ac000000000000000000000000000000000000000000000000000000005f5260045ffd5b99949993919310613c57575b505050613b00565b613c6a939850611496916114609161312e565b945f8080613c4f565b73ffffffffffffffffffffffffffffffffffffffff811681036103825760208173ffffffffffffffffffffffffffffffffffffffff92506004604051809481937f313ce567000000000000000000000000000000000000000000000000000000008352165afa90811561151a575f91613ced575b50613ad7565b613d06915060203d602011611513576115058183612f7d565b5f613ce7565b60243573ffffffffffffffffffffffffffffffffffffffff811681036103825773ffffffffffffffffffffffffffffffffffffffff8116613d51575060125b91613ad9565b73ffffffffffffffffffffffffffffffffffffffff811681036103825760208173ffffffffffffffffffffffffffffffffffffffff92506004604051809481937f313ce567000000000000000000000000000000000000000000000000000000008352165afa90811561151a575f91613dcb575b50613d4b565b613de4915060203d602011611513576115058183612f7d565b5f613dc5565b905060a0813d60a011613e2f575b81613e0560a09383612f7d565b8101031261038257613e1681613117565b50613e28608060208301519201613117565b505f613a6f565b3d9150613df8565b6004919250613e5660a09160203d602011611513576115058183612f7d565b929150613a2f565b916136b4565b827fc881dfc1000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b5073fffd8963efd1fc6a506488495d951d5263988d268111613633565b506020813d602011613eeb575b81613ec760209383612f7d565b810103126103825773ffffffffffffffffffffffffffffffffffffffff905161360c565b3d9150613eba565b7f22a8be08000000000000000000000000000000000000000000000000000000005f5260045260245260445ffd5b9050825f52600d60205273ffffffffffffffffffffffffffffffffffffffff60405f2091165f5260205260ff60405f205416155f61354e565b7f4036ba6b000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b613fa7915060203d602011613fad575b613f9f8183612f7d565b81019061428d565b5f613522565b503d613f95565b7f42d0e2e1000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b5073ffffffffffffffffffffffffffffffffffffffff60025416811415613495565b1561400857565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600c60248201527f466565206f766572666c6f7700000000000000000000000000000000000000006044820152fd5b905f915f60e4351361409857507fb47b2fb1000000000000000000000000000000000000000000000000000000009190565b60c435925082151583036103825782156142855760801d5b600f0b7fffffffffffffffffffffffffffffffff800000000000000000000000000000008114613142576140f0620f424091600654905f03600f0b613180565b05916f7fffffffffffffffffffffffffffffff8313158061425b575b61411590614001565b156142375760243573ffffffffffffffffffffffffffffffffffffffff81168103610382575b73ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000b036b58a818b1bc34d502d3fe730db729e62ac169073ffffffffffffffffffffffffffffffffffffffff6003541690823b15610382576040517f0b0d9c0900000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff91821660048201529116602482015260448101849052905f908290606490829084905af1801561151a57614227575b507fb47b2fb10000000000000000000000000000000000000000000000000000000091600f0b90565b5f61423191612f7d565b5f6141fe565b60443573ffffffffffffffffffffffffffffffffffffffff8116811461413b575f80fd5b507fffffffffffffffffffffffffffffffff8000000000000000000000000000000083121561410c565b600f0b6140b0565b90816020910312610382575180151581036103825790565b9173ffffffffffffffffffffffffffffffffffffffff805f5460081c16931683810361446957506020906024604051809581937f6352211e00000000000000000000000000000000000000000000000000000000835260048301525afa91821561151a575f92614418575b5073ffffffffffffffffffffffffffffffffffffffff602081600b5416936024604051809481937f9746656200000000000000000000000000000000000000000000000000000000835216968760048301525afa90811561151a575f916143f9575b50156143cd5761438560a091369061308a565b20805f52600e60205260405f20549182151590816143a7575b50613ef3575050565b9050825f52600d60205260405f20905f5260205260ff60405f205460081c16155f61439e565b507f353b811a000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b614412915060203d602011613fad57613f9f8183612f7d565b5f614372565b9091506020813d602011614461575b8161443460209383612f7d565b81010312610382575173ffffffffffffffffffffffffffffffffffffffff8116810361038257905f614310565b3d9150614427565b7f3afe49ea000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b60ff5f541661449f57565b7fd93c0665000000000000000000000000000000000000000000000000000000005f5260045ffd5b9190820391821161314257565b8181029291811591840414171561314257565b8115613213570490565b9062ffffff8091169116019062ffffff82116131425756fea164736f6c634300081a000a

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

00000000000000000000000000b036b58a818b1bc34d502d3fe730db729e62ac0000000000000000000000005d7df7b73a0d67b4a11297475184dc645be56cc400000000000000000000000048bbb8f2836b9797a5682f80b6ad5fb999b35430000000000000000000000000bb8f2f659ecbd0ce8fe3ec4e9001f1e8167b3a5a000000000000000000000000a5ab51e02b65994a269dcd8dc4b9f7df6a63906300000000000000000000000056dcd40a3f2d466f48e7f48bdbe5cc9b92ae4472000000000000000000000000dfcd46794357af78994c813a378eca96293524d40000000000000000000000004cf2adfa1a53f4d53fcd0d7851512ebe581e7509

-----Decoded View---------------
Arg [0] : _poolManager (address): 0x00B036B58a818B1BC34d502D3fE730Db729e62AC
Arg [1] : _provider (address): 0x5d7dF7b73a0D67B4A11297475184Dc645bE56CC4
Arg [2] : _institution (address): 0x48bbB8f2836B9797A5682f80b6AD5fb999B35430
Arg [3] : _positionManager (address): 0xBB8f2F659EcBd0ce8fe3ec4E9001f1e8167B3A5a
Arg [4] : _swapRouter (address): 0xA5aB51E02b65994a269DCD8dC4B9F7DF6a639063
Arg [5] : _quoter (address): 0x56DCD40A3F2d466F48e7F48bDBE5Cc9B92Ae4472
Arg [6] : _serviceFeeVault (address): 0xDFcd46794357Af78994C813a378Eca96293524D4
Arg [7] : _permissionManager (address): 0x4CF2adFA1a53f4D53FCd0D7851512eBe581E7509

-----Encoded View---------------
8 Constructor Arguments found :
Arg [0] : 00000000000000000000000000b036b58a818b1bc34d502d3fe730db729e62ac
Arg [1] : 0000000000000000000000005d7df7b73a0d67b4a11297475184dc645be56cc4
Arg [2] : 00000000000000000000000048bbb8f2836b9797a5682f80b6ad5fb999b35430
Arg [3] : 000000000000000000000000bb8f2f659ecbd0ce8fe3ec4e9001f1e8167b3a5a
Arg [4] : 000000000000000000000000a5ab51e02b65994a269dcd8dc4b9f7df6a639063
Arg [5] : 00000000000000000000000056dcd40a3f2d466f48e7f48bdbe5cc9b92ae4472
Arg [6] : 000000000000000000000000dfcd46794357af78994c813a378eca96293524d4
Arg [7] : 0000000000000000000000004cf2adfa1a53f4d53fcd0d7851512ebe581e7509


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
0xf043d11A5D4E520B68453B60eE314Fe1C6576acc
Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.