S Price: $0.698888 (-3.94%)

Contract Diff Checker

Contract Name:
PoolUpdater

Contract Source Code:

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

import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";

import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";

import {Errors} from "contracts/libraries/Errors.sol";
import {PoolUpdaterStorage} from "contracts/CL/gauge/libraries/PoolUpdaterStorage.sol";
import {LiquidityAmounts} from "contracts/CL/periphery/libraries/LiquidityAmounts.sol";

import {IVoter} from "contracts/interfaces/IVoter.sol";
import {IShadowV3Pool, IShadowV3PoolActions} from "contracts/CL/core/interfaces/IShadowV3Pool.sol";
import {INonfungiblePositionManager} from "contracts/CL/periphery/interfaces/INonfungiblePositionManager.sol";
import {IPoolUpdater} from "contracts/CL/gauge/interfaces/IPoolUpdater.sol";

contract PoolUpdater is IPoolUpdater {
    using EnumerableSet for EnumerableSet.AddressSet;

    IVoter public immutable voter;
    INonfungiblePositionManager public immutable nfpManager;

    int24 internal constant MIN_TICK = -887272;
    int24 internal constant MAX_TICK = -MIN_TICK;

    uint160 internal constant MIN_SQRT_RATIO = 4295128739;
    uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;

    modifier running() {
        PoolUpdaterStorage.PoolUpdaterState storage $ = PoolUpdaterStorage.getStorage();

        $.isRunning = true;
        _;
        $.isRunning = false;
    }

    modifier onlyRunning() {
        require(PoolUpdaterStorage.getStorage().isRunning, Errors.NOT_RUNNING());
        _;
    }

    modifier onlyAccessHub() {
        require(msg.sender == IVoter(voter).accessHub(), Errors.NOT_ACCESSHUB());
        _;
    }

    constructor(address _voter, address _nfpManager) {
        voter = IVoter(_voter);
        nfpManager = INonfungiblePositionManager(payable(_nfpManager));
    }

    ////////////////////
    // View Functions //
    ////////////////////

    function amountForSeed(address pool) public view returns (uint256 amount0, uint256 amount1) {
        (uint160 sqrtRatioX96,,,,,,) = IShadowV3Pool(pool).slot0();

        (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(sqrtRatioX96, MIN_SQRT_RATIO, MAX_SQRT_RATIO, 1000);

        // round up one wei
        amount0++;
        amount1++;

        // add 500 wei for at least 500 runs (~9.5yrs) of operation
        amount0 += 500;
        amount1 += 500;
    }

    function isSeeded(address pool) public view returns (bool) {
        try nfpManager.ownerOf(PoolUpdaterStorage.getStorage().poolToNfp[pool]) returns (address _owner) {
            // return success if nfp already exists and is owned by this contract
            if (_owner == address(this)) {
                return true;
            }
        } catch (bytes memory) {}

        return false;
    }

    function findMissing() external view returns (address[] memory _missingTokens) {
        PoolUpdaterStorage.PoolUpdaterState storage $ = PoolUpdaterStorage.getStorage();

        _missingTokens = new address[]($.clPools.length() * 2);

        uint256 missingLength;

        uint256 index;
        for (index = 0; index < $.clPools.length(); index++) {
            IShadowV3Pool pool = IShadowV3Pool($.clPools.at(index));
            address token0 = pool.token0();
            address token1 = pool.token1();

            if (IERC20(token0).balanceOf(address(this)) == 0) {
                _missingTokens[missingLength] = token0;
                missingLength++;
            }
            if (IERC20(token1).balanceOf(address(this)) == 0) {
                _missingTokens[missingLength] = token1;
                missingLength++;
            }
        }

        // trim _missingTokens length if needed
        if (missingLength != _missingTokens.length) {
            assembly ("memory-safe") {
                mstore(_missingTokens, missingLength)
            }
        }
    }

    function findNotUpdated() public view returns (address[] memory pools) {
        PoolUpdaterStorage.PoolUpdaterState storage $ = PoolUpdaterStorage.getStorage();

        uint256 end = $.clPools.length();
        pools = new address[](end);

        uint256 notUpdatedLength = 0;
        uint256 index;
        uint256 period = block.timestamp / (86400 * 7);
        for (index = 0; index < end; index++) {
            IShadowV3Pool pool = IShadowV3Pool($.clPools.at(index));
            if (pool.lastPeriod() != period) {
                pools[notUpdatedLength] = address(pool);
                notUpdatedLength++;
            }
        }

        // trim length if needed
        if (notUpdatedLength != pools.length) {
            assembly ("memory-safe") {
                mstore(pools, notUpdatedLength)
            }
        }
    }

    function poolToNfp(address clPool) external view returns (uint256) {
        return PoolUpdaterStorage.getStorage().poolToNfp[clPool];
    }

    function getAllGauges() external view returns (address[] memory) {
        return PoolUpdaterStorage.getStorage().gauges.values();
    }

    function getGauge(uint256 index) external view returns (address) {
        return PoolUpdaterStorage.getStorage().gauges.at(index);
    }

    function getGaugeLength() external view returns (uint256) {
        return PoolUpdaterStorage.getStorage().gauges.length();
    }

    function getAllClPools() external view returns (address[] memory) {
        return PoolUpdaterStorage.getStorage().clPools.values();
    }

    function getClPool(uint256 index) external view returns (address) {
        return PoolUpdaterStorage.getStorage().clPools.at(index);
    }

    function getClPoolsLength() external view returns (uint256) {
        return PoolUpdaterStorage.getStorage().clPools.length();
    }

    //////////////////////
    // Seed and Updates //
    //////////////////////

    function updateRecords() public {
        PoolUpdaterStorage.PoolUpdaterState storage $ = PoolUpdaterStorage.getStorage();

        address[] memory _gauges = voter.getAllGauges();

        // Check if there are more gauges than currently recorded
        uint256 oldLength = $.gauges.length();
        if (oldLength != _gauges.length) {
            uint256 index;
            for (index = oldLength; index < _gauges.length; index++) {
                // add to recorded gauges
                $.gauges.add(_gauges[index]);

                // add to clPools if CL
                if (voter.isClGauge(_gauges[index])) {
                    $.clPools.add(voter.poolForGauge(_gauges[index]));
                }
            }
        }
    }

    function seed(uint256 start, uint256 end) external returns (SeedData[] memory failedSeeds) {
        PoolUpdaterStorage.PoolUpdaterState storage $ = PoolUpdaterStorage.getStorage();

        if (end > $.clPools.length()) {
            end = $.clPools.length();
        }

        failedSeeds = new SeedData[](end);
        uint256 failedLength;

        for (uint256 index = start; index < end; index++) {
            address pool = $.clPools.at(index);
            (bool success, SeedData memory seedData) = seed(pool, false);

            if (!success) {
                failedSeeds[failedLength] = seedData;
                failedLength++;
            }
        }

        // trim length if needed
        if (failedLength != failedSeeds.length) {
            assembly ("memory-safe") {
                mstore(failedSeeds, failedLength)
            }
        }

        return failedSeeds;
    }

    function seed(address pool) external {
        seed(pool, true);
    }

    function seed(address pool, bool revertOnFailure) public returns (bool success, SeedData memory seedData) {
        if (isSeeded(pool)) {
            success = true;
            return (success, seedData);
        }

        PoolUpdaterStorage.PoolUpdaterState storage $ = PoolUpdaterStorage.getStorage();

        address token0 = IShadowV3Pool(pool).token0();
        address token1 = IShadowV3Pool(pool).token1();

        (uint160 sqrtRatioX96,,,,,,) = IShadowV3Pool(pool).slot0();

        // make sure there is at least some cardinality
        IShadowV3Pool(pool).increaseObservationCardinalityNext(100);

        (uint256 mintAmount0, uint256 mintAmount1) =
            LiquidityAmounts.getAmountsForLiquidity(sqrtRatioX96, MIN_SQRT_RATIO, MAX_SQRT_RATIO, 1000);
        mintAmount0++; // round up one wei
        mintAmount1++; // round up one wei

        seedData.pool = address(pool);
        seedData.token0 = token0;
        seedData.token1 = token1;
        seedData.amount0 = mintAmount0 + 500; // add 500 wei for at least 500 runs (~9.5yrs) of operation
        seedData.amount1 = mintAmount1 + 500; // add 500 wei for at least 500 runs (~9.5yrs) of operation

        try IERC20(token0).transferFrom(msg.sender, address(this), seedData.amount0) returns (bool) {}
        catch (bytes memory) {
            if (revertOnFailure) {
                revert Errors.TRANSFER_FROM_FOR_SEEDING_FAILED(token0, seedData.amount0);
            } else {
                return (false, seedData);
            }
        }

        try IERC20(token1).transferFrom(msg.sender, address(this), seedData.amount1) returns (bool) {}
        catch (bytes memory) {
            if (revertOnFailure) {
                revert Errors.TRANSFER_FROM_FOR_SEEDING_FAILED(token1, seedData.amount1);
            } else {
                return (false, seedData);
            }
        }

        IERC20(token0).approve(address(nfpManager), mintAmount0);
        IERC20(token1).approve(address(nfpManager), mintAmount1);

        int24 tickSpacing = IShadowV3Pool(pool).tickSpacing();

        // mint and update nfp tokenId for pool
        try nfpManager.mint(
            INonfungiblePositionManager.MintParams({
                token0: token0,
                token1: token1,
                tickSpacing: tickSpacing,
                tickLower: MIN_TICK - (MIN_TICK % tickSpacing),
                tickUpper: MAX_TICK - (MAX_TICK % tickSpacing),
                amount0Desired: mintAmount0,
                amount1Desired: mintAmount1,
                amount0Min: 0,
                amount1Min: 0,
                recipient: address(this),
                deadline: block.timestamp + 1
            })
        ) returns (uint256 _tokenId, uint128 _liquidity, uint256, uint256) {
            if (_liquidity > 0) {
                $.poolToNfp[seedData.pool] = _tokenId;
                success = true;
            }
        } catch (bytes memory) {}

        if (!success && revertOnFailure) {
            revert Errors.SEEDING_FAILED();
        }

        return (success, seedData);
    }

    function updatePools(uint256 start, uint256 end, bool _updateRecords, bool force)
        public
        running
        returns (uint256[] memory, address[] memory)
    {
        PoolUpdaterStorage.PoolUpdaterState storage $ = PoolUpdaterStorage.getStorage();

        if (block.timestamp > ((block.timestamp / 1 weeks) + 1) * 1 weeks - 1 hours && !force) {
            revert Errors.TOO_EARLY();
        }

        if (_updateRecords) {
            updateRecords();
        }

        if (end > $.clPools.length()) {
            end = $.clPools.length();
        }

        uint256 index;
        uint256 period = block.timestamp / 1 weeks;
        uint256[] memory failedIndex = new uint256[](end - start);
        address[] memory failedPools = new address[](end - start);
        uint256 failedLength;
        bool didUpdate;
        for (index = start; index < end; index++) {
            IShadowV3Pool pool = IShadowV3Pool($.clPools.at(index));
            if (pool.lastPeriod() == period && !force) {
                continue;
            }
            address token0 = pool.token0();
            $._tempToken0 = token0;
            $._tempToken1 = pool.token1();

            bool zeroForOne = IERC20(token0).balanceOf(address(this)) > 1;

            // try update
            bool success = _update(pool, zeroForOne);

            // if first update fails, flip zeroForOne and try again
            if (!success) {
                success = _update(pool, !zeroForOne);

                // if it still fails, record it as a failed pair and report in the return data, don't revert
                if (!success) {
                    failedIndex[failedLength] = index;
                    failedPools[failedLength] = address(pool);
                    failedLength++;
                }
            }

            // records if any swaps were a success
            if (success) {
                didUpdate = true;
            }
        }

        if (!didUpdate && !force) {
            revert Errors.NO_UPDATES();
        }

        // trim length if needed
        if (failedLength != failedIndex.length) {
            assembly ("memory-safe") {
                mstore(failedIndex, failedLength)
                mstore(failedPools, failedLength)
            }
        }

        return (failedIndex, failedPools);
    }

    function updatePool(address _pool) public running {
        PoolUpdaterStorage.PoolUpdaterState storage $ = PoolUpdaterStorage.getStorage();

        uint256 period = block.timestamp / 1 weeks;

        IShadowV3Pool pool = IShadowV3Pool(_pool);
        if (pool.lastPeriod() == period) {
            return;
        }

        address token0 = pool.token0();
        $._tempToken0 = token0;
        $._tempToken1 = pool.token1();

        bool zeroForOne = IERC20(token0).balanceOf(address(this)) > 1;

        // try update
        bool success = _update(pool, zeroForOne);

        // if first update fails, flip zeroForOne and try again
        if (!success) {
            success = _update(pool, !zeroForOne);

            // if it still fails, revert
            if (!success) {
                assembly ("memory-safe") {
                    returndatacopy(0, 0, returndatasize())
                    revert(0, returndatasize())
                }
            }
        }
    }

    function _update(IShadowV3Pool pool, bool zeroForOne) internal returns (bool _success) {
        (uint160 priceLimit,,,,,,) = pool.slot0();
        priceLimit = zeroForOne ? priceLimit - 1 : priceLimit + 1;

        (_success,) = address(pool).call(
            abi.encodeCall(IShadowV3PoolActions.swap, (address(this), zeroForOne, 1, priceLimit, ""))
        );
    }

    ///////////////
    // Callbacks //
    ///////////////

    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata //data
    ) external onlyRunning {
        PoolUpdaterStorage.PoolUpdaterState storage $ = PoolUpdaterStorage.getStorage();

        if (amount0Delta > 0) {
            IERC20($._tempToken0).transfer(msg.sender, uint256(amount0Delta));
        }

        if (amount1Delta > 0) {
            IERC20($._tempToken1).transfer(msg.sender, uint256(amount1Delta));
        }
    }

    function onERC721Received(
        address, // operator
        address, // from
        uint256, // tokenId
        bytes calldata // data
    ) external pure returns (bytes4 retval) {
        return this.onERC721Received.selector;
    }

    ///////////////////////
    // AccessHub Actions //
    ///////////////////////

    function sweep(address _token) external onlyAccessHub {
        IERC20(_token).transfer(msg.sender, IERC20(_token).balanceOf(address(this)));
    }

    function execute(address _target, bytes calldata _payload)
        external
        onlyAccessHub
        returns (bytes memory _returndata)
    {
        bool _success;
        (_success, _returndata) = _target.call(_payload);

        if (!_success) {
            assembly {
                returndatacopy(0, 0, returndatasize())
                revert(0, returndatasize())
            }
        }
    }
}

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

pragma solidity ^0.8.20;

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }
}

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

/// @title Central Errors Library
/// @notice Contains all custom errors used across the protocol
/// @dev Centralized error definitions to prevent redundancy
library Errors {
    /*//////////////////////////////////////////////////////////////
                                VOTER ERRORS
    //////////////////////////////////////////////////////////////*/

    /// @notice Thrown when attempting to interact with an already active gauge
    /// @param gauge The address of the gauge
    error ACTIVE_GAUGE(address gauge);

    /// @notice Thrown when attempting to interact with an inactive gauge
    /// @param gauge The address of the gauge
    error GAUGE_INACTIVE(address gauge);

    /// @notice Thrown when attempting to whitelist an already whitelisted token
    /// @param token The address of the token
    error ALREADY_WHITELISTED(address token);

    /// @notice Thrown when caller is not authorized to perform an action
    /// @param caller The address of the unauthorized caller
    error NOT_AUTHORIZED(address caller);

    /// @notice Thrown when token is not whitelisted
    /// @param token The address of the non-whitelisted token
    error NOT_WHITELISTED(address token);

    /// @notice Thrown when both tokens in a pair are not whitelisted
    error BOTH_NOT_WHITELISTED();

    /// @notice Thrown when address is not a valid pool
    /// @param pool The invalid pool address
    error NOT_POOL(address pool);

    /// @notice Thrown when pool is not seeded in PoolUpdater
    /// @param pool The invalid pool address
    error NOT_SEEDED(address pool);

    /// @notice Thrown when contract is not initialized
    error NOT_INIT();

    /// @notice Thrown when array lengths don't match
    error LENGTH_MISMATCH();

    /// @notice Thrown when pool doesn't have an associated gauge
    /// @param pool The address of the pool
    error NO_GAUGE(address pool);

    /// @notice Thrown when rewards are already distributed for a period
    /// @param gauge The gauge address
    /// @param period The distribution period
    error ALREADY_DISTRIBUTED(address gauge, uint256 period);

    /// @notice Thrown when attempting to vote with zero amount
    /// @param pool The pool address
    error ZERO_VOTE(address pool);

    /// @notice Thrown when ratio exceeds maximum allowed
    /// @param _xRatio The excessive ratio value
    error RATIO_TOO_HIGH(uint256 _xRatio);

    /// @notice Thrown when vote operation fails
    error VOTE_UNSUCCESSFUL();

    /*//////////////////////////////////////////////////////////////
                            GAUGE V3 ERRORS
    //////////////////////////////////////////////////////////////*/

    /// @notice Thrown when the pool already has a gauge
    /// @param pool The address of the pool
    error GAUGE_EXISTS(address pool);

    /// @notice Thrown when caller is not the voter
    /// @param caller The address of the invalid caller
    error NOT_VOTER(address caller);

    /// @notice Thrown when amount is not greater than zero
    /// @param amt The invalid amount
    error NOT_GT_ZERO(uint256 amt);

    /// @notice Thrown when attempting to claim future rewards
    error CANT_CLAIM_FUTURE();

    /// @notice Throw when gauge can't determine if using secondsInRange from the pool is safe
    error NEED_TEAM_TO_UPDATE();

    /*//////////////////////////////////////////////////////////////
                            GAUGE ERRORS
    //////////////////////////////////////////////////////////////*/

    /// @notice Thrown when amount is zero
    error ZERO_AMOUNT();

    /// @notice Thrown when stake notification fails
    error CANT_NOTIFY_STAKE();

    /// @notice Thrown when reward amount is too high
    error REWARD_TOO_HIGH();

    /// @notice Thrown when amount exceeds remaining balance
    /// @param amount The requested amount
    /// @param remaining The remaining balance
    error NOT_GREATER_THAN_REMAINING(uint256 amount, uint256 remaining);

    /// @notice Thrown when token operation fails
    /// @param token The address of the problematic token
    error TOKEN_ERROR(address token);

    /// @notice Thrown when an address is not an NfpManager
    error NOT_NFP_MANAGER(address nfpManager);

    /*//////////////////////////////////////////////////////////////
                        FEE DISTRIBUTOR ERRORS
    //////////////////////////////////////////////////////////////*/

    /// @notice Thrown when period is not finalized
    /// @param period The unfinalized period
    error NOT_FINALIZED(uint256 period);

    /// @notice Thrown when the destination of a redirect is not a feeDistributor
    /// @param destination Destination of the redirect
    error NOT_FEE_DISTRIBUTOR(address destination);

    /// @notice Thrown when the destination of a redirect's pool/pair has completely different tokens
    error DIFFERENT_DESTINATION_TOKENS();

    /*//////////////////////////////////////////////////////////////
                            PAIR ERRORS
    //////////////////////////////////////////////////////////////*/

    /// @notice Thrown when ratio is unstable
    error UNSTABLE_RATIO();

    /// @notice Thrown when safe transfer fails
    error SAFE_TRANSFER_FAILED();

    /// @notice Thrown on arithmetic overflow
    error OVERFLOW();

    /// @notice Thrown when skim operation is disabled
    error SKIM_DISABLED();

    /// @notice Thrown when insufficient liquidity is minted
    error INSUFFICIENT_LIQUIDITY_MINTED();

    /// @notice Thrown when insufficient liquidity is burned
    error INSUFFICIENT_LIQUIDITY_BURNED();

    /// @notice Thrown when output amount is insufficient
    error INSUFFICIENT_OUTPUT_AMOUNT();

    /// @notice Thrown when input amount is insufficient
    error INSUFFICIENT_INPUT_AMOUNT();

    /// @notice Generic insufficient liquidity error
    error INSUFFICIENT_LIQUIDITY();

    /// @notice Invalid transfer error
    error INVALID_TRANSFER();

    /// @notice K value error in AMM
    error K();

    /*//////////////////////////////////////////////////////////////
                        PAIR FACTORY ERRORS
    //////////////////////////////////////////////////////////////*/

    /// @notice Thrown when fee is too high
    error FEE_TOO_HIGH();

    /// @notice Thrown when fee is zero
    error ZERO_FEE();

    /// @notice Thrown when token assortment is invalid
    error INVALID_ASSORTMENT();

    /// @notice Thrown when address is zero
    error ZERO_ADDRESS();

    /// @notice Thrown when pair already exists
    error PAIR_EXISTS();

    /// @notice Thrown when fee split is invalid
    error INVALID_FEE_SPLIT();

    /*//////////////////////////////////////////////////////////////
                    FEE RECIPIENT FACTORY ERRORS
    //////////////////////////////////////////////////////////////*/

    /// @notice Thrown when treasury fee is invalid
    error INVALID_TREASURY_FEE();

    /*//////////////////////////////////////////////////////////////
                            ROUTER ERRORS
    //////////////////////////////////////////////////////////////*/

    /// @notice Thrown when deadline has expired
    error EXPIRED();

    /// @notice Thrown when tokens are identical
    error IDENTICAL();

    /// @notice Thrown when amount is insufficient
    error INSUFFICIENT_AMOUNT();

    /// @notice Thrown when path is invalid
    error INVALID_PATH();

    /// @notice Thrown when token B amount is insufficient
    error INSUFFICIENT_B_AMOUNT();

    /// @notice Thrown when token A amount is insufficient
    error INSUFFICIENT_A_AMOUNT();

    /// @notice Thrown when input amount is excessive
    error EXCESSIVE_INPUT_AMOUNT();

    /// @notice Thrown when ETH transfer fails
    error ETH_TRANSFER_FAILED();

    /// @notice Thrown when reserves are invalid
    error INVALID_RESERVES();

    /*//////////////////////////////////////////////////////////////
                            MINTER ERRORS
    //////////////////////////////////////////////////////////////*/

    /// @notice Thrown when epoch 0 has already started
    error STARTED();

    /// @notice Thrown when emissions haven't started
    error EMISSIONS_NOT_STARTED();

    /// @notice Thrown when deviation is too high
    error TOO_HIGH();

    /// @notice Thrown when no value change detected
    error NO_CHANGE();

    /// @notice Thrown when updating emissions in same period
    error SAME_PERIOD();

    /// @notice Thrown when contract setup is invalid
    error INVALID_CONTRACT();

    /// @notice Thrown when legacy factory doesn't have feeSplitWhenNoGauge on
    error FEE_SPLIT_WHEN_NO_GAUGE_IS_OFF();

    /*//////////////////////////////////////////////////////////////
                        ACCESS HUB ERRORS
    //////////////////////////////////////////////////////////////*/

    /// @notice Thrown when addresses are identical
    error SAME_ADDRESS();

    /// @notice Thrown when caller is not timelock
    /// @param caller The invalid caller address
    error NOT_TIMELOCK(address caller);

    /// @notice Thrown when manual execution fails
    /// @param reason The failure reason
    error MANUAL_EXECUTION_FAILURE(bytes reason);

    /// @notice Thrown when kick operation is forbidden
    /// @param target The target address
    error KICK_FORBIDDEN(address target);

    /*//////////////////////////////////////////////////////////////
                        VOTE MODULE ERRORS
    //////////////////////////////////////////////////////////////*/

    /// @notice Thrown when caller is not xShadow
    error NOT_XSHADOW();

    /// @notice Thrown when cooldown period is still active
    error COOLDOWN_ACTIVE();

    /// @notice Thrown when caller is not vote module
    error NOT_VOTEMODULE();

    /// @notice Thrown when caller is unauthorized
    error UNAUTHORIZED();

    /// @notice Thrown when caller is not access hub
    error NOT_ACCESSHUB();

    /// @notice Thrown when address is invalid
    error INVALID_ADDRESS();

    /*//////////////////////////////////////////////////////////////
                        LAUNCHER PLUGIN ERRORS
    //////////////////////////////////////////////////////////////*/

    /// @notice Thrown when caller is not authority
    error NOT_AUTHORITY();

    /// @notice Thrown when already an authority
    error ALREADY_AUTHORITY();

    /// @notice Thrown when caller is not operator
    error NOT_OPERATOR();

    /// @notice Thrown when already an operator
    error ALREADY_OPERATOR();

    /// @notice Thrown when pool is not enabled
    /// @param pool The disabled pool address
    error NOT_ENABLED(address pool);

    /// @notice Thrown when fee distributor is missing
    error NO_FEEDIST();

    /// @notice Thrown when already enabled
    error ENABLED();

    /// @notice Thrown when take value is invalid
    error INVALID_TAKE();

    /*//////////////////////////////////////////////////////////////
                            X33 ERRORS
    //////////////////////////////////////////////////////////////*/

    /// @notice Thrown when value is zero
    error ZERO();

    /// @notice Thrown when amount is insufficient
    error NOT_ENOUGH();

    /// @notice Thrown when value doesn't conform to scale
    /// @param value The non-conforming value
    error NOT_CONFORMED_TO_SCALE(uint256 value);

    /// @notice Thrown when contract is locked
    error LOCKED();

    /// @notice Thrown when rebase is in progress
    error REBASE_IN_PROGRESS();

    /// @notice Thrown when aggregator reverts
    /// @param reason The revert reason
    error AGGREGATOR_REVERTED(bytes reason);

    /// @notice Thrown when output amount is too low
    /// @param amount The insufficient amount
    error AMOUNT_OUT_TOO_LOW(uint256 amount);

    /// @notice Thrown when aggregator is not whitelisted
    /// @param aggregator The non-whitelisted aggregator address
    error AGGREGATOR_NOT_WHITELISTED(address aggregator);

    /// @notice Thrown when token is forbidden
    /// @param token The forbidden token address
    error FORBIDDEN_TOKEN(address token);

    /*//////////////////////////////////////////////////////////////
                            XSHADOW ERRORS
    //////////////////////////////////////////////////////////////*/

    /// @notice Thrown when caller is not minter
    error NOT_MINTER();

    /// @notice Thrown when no vest exists
    error NO_VEST();

    /// @notice Thrown when already exempt
    error ALREADY_EXEMPT();

    /// @notice Thrown when not exempt
    error NOT_EXEMPT();

    /// @notice Thrown when rescue operation is not allowed
    error CANT_RESCUE();

    /// @notice Thrown when array lengths mismatch
    error ARRAY_LENGTHS();

    /// @notice Thrown when vesting periods overlap
    error VEST_OVERLAP();

    /*//////////////////////////////////////////////////////////////
                            V3 FACTORY ERRORS
    //////////////////////////////////////////////////////////////*/

    /// @notice Thrown when tokens are identical
    error IDENTICAL_TOKENS();

    /// @notice Thrown when fee is too large
    error FEE_TOO_LARGE();

    /// @notice Address zero error
    error ADDRESS_ZERO();

    /// @notice Fee zero error
    error F0();

    /// @notice Thrown when value is out of bounds
    /// @param value The out of bounds value
    error OOB(uint8 value);

    /*//////////////////////////////////////////////////////////////
                            POOL UPDATER ERRORS
    //////////////////////////////////////////////////////////////*/
    /// @notice Thrown when seeding for a pool fails
    error TRANSFER_FROM_FOR_SEEDING_FAILED(address token, uint256 amount);

    /// @notice Thrown when seeding for a pool fails
    error SEEDING_FAILED();

    /// @notice Thrown when updatePools is called too early
    error TOO_EARLY();

    /// @notice Thrown when a callback is called when an update isn't running
    error NOT_RUNNING();

    /// @notice Thrown when updatePools didn't perform any updates
    error NO_UPDATES();
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";

import {IShadowV3Pool} from "contracts/CL/core/interfaces/IShadowV3Pool.sol";

library PoolUpdaterStorage {
    using EnumerableSet for EnumerableSet.AddressSet;

    /// @dev keccak256(abi.encode(uint256(keccak256("poolUpdater.storage")) - 1)) & ~bytes32(uint256(0xff));
    bytes32 public constant POOL_UPDATER_STORAGE_LOCATION =
        0x8350060c97380d4a9b441acc4769b870f3b1aad9bcd71ebf7300a85af9f9f900;

    /// @custom꞉storage‑location erc7201꞉poolUpdater.storage
    struct PoolUpdaterState {
        EnumerableSet.AddressSet gauges;
        EnumerableSet.AddressSet clPools;
        mapping(address clPool => uint256 tokenId) poolToNfp;
        bool isRunning;
        address _tempToken0;
        address _tempToken1;
    }

    /// @dev Return state storage struct for reading and writing
    function getStorage() internal pure returns (PoolUpdaterState storage $) {
        assembly {
            $.slot := POOL_UPDATER_STORAGE_LOCATION
        }
    }
}

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

import '../../core/libraries/FullMath.sol';
import '../../core/libraries/FixedPoint96.sol';

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

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

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

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

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

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

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

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

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

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

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

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

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

interface IVoter {
    event GaugeCreated(address indexed gauge, address creator, address feeDistributor, address indexed pool);

    event GaugeKilled(address indexed gauge);

    event GaugeRevived(address indexed gauge);

    event Voted(address indexed owner, uint256 weight, address indexed pool);

    event Abstained(address indexed owner, uint256 weight);

    event Deposit(address indexed lp, address indexed gauge, address indexed owner, uint256 amount);

    event Withdraw(address indexed lp, address indexed gauge, address indexed owner, uint256 amount);

    event NotifyReward(address indexed sender, address indexed reward, uint256 amount);

    event DistributeReward(address indexed sender, address indexed gauge, uint256 amount);

    event EmissionsRatio(address indexed caller, uint256 oldRatio, uint256 newRatio);

    event NewGovernor(address indexed sender, address indexed governor);

    event Whitelisted(address indexed whitelister, address indexed token);

    event WhitelistRevoked(address indexed forbidder, address indexed token, bool status);

    event MainTickSpacingChanged(address indexed token0, address indexed token1, int24 indexed newMainTickSpacing);

    event Poke(address indexed user);

    event EmissionsRedirected(address indexed sourceGauge, address indexed destinationGauge);

    struct InitializationParams {
        address shadow;
        address legacyFactory;
        address gauges;
        address feeDistributorFactory;
        address minter;
        address msig;
        address xShadow;
        address clFactory;
        address clGaugeFactory;
        address nfpManager;
        address feeRecipientFactory;
        address voteModule;
        address launcherPlugin;
        address poolUpdater;
    }

    function initialize(InitializationParams memory inputs) external;

    /// @notice denominator basis
    function BASIS() external view returns (uint256);

    /// @notice ratio of xShadow emissions globally
    function xRatio() external view returns (uint256);

    /// @notice xShadow contract address
    function xShadow() external view returns (address);

    /// @notice legacy factory address (uni-v2/stableswap)
    function legacyFactory() external view returns (address);

    /// @notice concentrated liquidity factory
    function clFactory() external view returns (address);

    /// @notice gauge factory for CL
    function clGaugeFactory() external view returns (address);

    /// @notice pool updater for CL
    function poolUpdater() external view returns (address);

    /// @notice legacy fee recipient factory
    function feeRecipientFactory() external view returns (address);

    /// @notice peripheral NFPManager contract
    function nfpManager() external view returns (address);

    /// @notice returns the address of the current governor
    /// @return _governor address of the governor
    function governor() external view returns (address _governor);

    /// @notice the address of the vote module
    /// @return _voteModule the vote module contract address
    function voteModule() external view returns (address _voteModule);

    /// @notice address of the central access Hub
    function accessHub() external view returns (address);

    /// @notice the address of the shadow launcher plugin to enable third party launchers
    /// @return _launcherPlugin the address of the plugin
    function launcherPlugin() external view returns (address _launcherPlugin);

    /// @notice distributes emissions from the minter to the voter
    /// @param amount the amount of tokens to notify
    function notifyRewardAmount(uint256 amount) external;

    /// @notice distributes the emissions for a specific gauge
    /// @param _gauge the gauge address
    function distribute(address _gauge) external;

    /// @notice returns the address of the gauge factory
    /// @param _gaugeFactory gauge factory address
    function gaugeFactory() external view returns (address _gaugeFactory);

    /// @notice returns the address of the feeDistributor factory
    /// @return _feeDistributorFactory feeDist factory address
    function feeDistributorFactory() external view returns (address _feeDistributorFactory);

    /// @notice returns the address of the minter contract
    /// @return _minter address of the minter
    function minter() external view returns (address _minter);

    /// @notice check if the gauge is active for governance use
    /// @param _gauge address of the gauge
    /// @return _trueOrFalse if the gauge is alive
    function isAlive(address _gauge) external view returns (bool _trueOrFalse);

    /// @notice allows the token to be paired with other whitelisted assets to participate in governance
    /// @param _token the address of the token
    function whitelist(address _token) external;

    /// @notice effectively disqualifies a token from governance
    /// @param _token the address of the token
    function revokeWhitelist(address _token) external;

    /// @notice returns if the address is a gauge
    /// @param gauge address of the gauge
    /// @return _trueOrFalse boolean if the address is a gauge
    function isGauge(address gauge) external view returns (bool _trueOrFalse);

    /// @notice disable a gauge from governance
    /// @param _gauge address of the gauge
    function killGauge(address _gauge) external;

    /// @notice re-activate a dead gauge
    /// @param _gauge address of the gauge
    function reviveGauge(address _gauge) external;

    /// @notice re-cast a tokenID's votes
    /// @param owner address of the owner
    function poke(address owner) external;

    /// @notice sets the main destinationGauge of a token pairing
    /// @param tokenA address of tokenA
    /// @param tokenB address of tokenB
    /// @param destinationGauge the main gauge to set to
    function redirectEmissions(address tokenA, address tokenB, address destinationGauge) external;

    /// @notice returns if the address is a fee distributor
    /// @param _feeDistributor address of the feeDist
    /// @return _trueOrFalse if the address is a fee distributor
    function isFeeDistributor(address _feeDistributor) external view returns (bool _trueOrFalse);

    /// @notice returns the address of the emission's token
    /// @return _shadow emissions token contract address
    function shadow() external view returns (address _shadow);

    /// @notice returns the address of the pool's gauge, if any
    /// @param _pool pool address
    /// @return _gauge gauge address
    function gaugeForPool(address _pool) external view returns (address _gauge);

    /// @notice returns the address of the pool's feeDistributor, if any
    /// @param _gauge address of the gauge
    /// @return _feeDistributor address of the pool's feedist
    function feeDistributorForGauge(address _gauge) external view returns (address _feeDistributor);

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

    /// @notice returns the array of all tickspacings for the tokenA/tokenB combination
    /// @param tokenA address of token A in the pair
    /// @param tokenB address of token B in the pair
    /// @return _ts array of all the tickspacings
    function tickSpacingsForPair(address tokenA, address tokenB) external view returns (int24[] memory _ts);

    /// @notice returns the destination of a gauge redirect
    /// @param gauge address of gauge
    function gaugeRedirect(address gauge) external view returns (address);

    /// @notice returns the block.timestamp divided by 1 week in seconds
    /// @return period the period used for gauges
    function getPeriod() external view returns (uint256 period);

    /// @notice cast a vote to direct emissions to gauges and earn incentives
    /// @param owner address of the owner
    /// @param _pools the list of pools to vote on
    /// @param _weights an arbitrary weight per pool which will be normalized to 100% regardless of numerical inputs
    function vote(address owner, address[] calldata _pools, uint256[] calldata _weights) external;

    /// @notice reset the vote of an address
    /// @param owner address of the owner
    function reset(address owner) external;

    /// @notice set the governor address
    /// @param _governor the new governor address
    function setGovernor(address _governor) external;

    /// @notice recover stuck emissions
    /// @param _gauge the gauge address
    /// @param _period the period
    function stuckEmissionsRecovery(address _gauge, uint256 _period) external;

    /// @notice creates a legacy gauge for the pool
    /// @param _pool pool's address
    /// @return _gauge address of the new gauge
    function createGauge(address _pool) external returns (address _gauge);

    /// @notice create a concentrated liquidity gauge
    /// @param tokenA the address of tokenA
    /// @param tokenB the address of tokenB
    /// @param tickSpacing the tickspacing of the pool
    /// @return _clGauge address of the new gauge
    function createCLGauge(address tokenA, address tokenB, int24 tickSpacing) external returns (address _clGauge);

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

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

    /// @notice claim arbitrary rewards from specific feeDists and break up legacy pairs
    /// @param owner address of the owner
    /// @param _feeDistributors address of the feeDists
    /// @param _tokens two dimensional array for the tokens to claim
    function claimLegacyIncentives(address owner, address[] calldata _feeDistributors, address[][] calldata _tokens)
        external;

    /// @notice claim arbitrary rewards from specific gauges
    /// @param _gauges address of the gauges
    /// @param _tokens two dimensional array for the tokens to claim
    function claimRewards(address[] calldata _gauges, address[][] calldata _tokens) external;

    /// @notice claim arbitrary rewards from specific legacy gauges, and exit to shadow
    /// @param _gauges address of the gauges
    /// @param _tokens two dimensional array for the tokens to claim
    function claimLegacyRewardsAndExit(address[] calldata _gauges, address[][] calldata _tokens) external;

    /// @notice claim arbitrary rewards from specific cl gauges, and exit to shadow
    /// @param _gauges address of the gauges
    /// @param _tokens two dimensional array for the tokens to claim
    /// @param _nfpTokenIds two dimensional array for the nfp to claim
    function claimClGaugeRewardsAndExit(
        address[] memory _gauges,
        address[][] memory _tokens,
        uint256[][] memory _nfpTokenIds
    ) external;

    /// @notice distribute emissions to a gauge for a specific period
    /// @param _gauge address of the gauge
    /// @param _period value of the period
    function distributeForPeriod(address _gauge, uint256 _period) external;

    /// @notice attempt distribution of emissions to all gauges
    function distributeAll() external;

    /// @notice distribute emissions to gauges by index
    /// @param startIndex start of the loop
    /// @param endIndex end of the loop
    function batchDistributeByIndex(uint256 startIndex, uint256 endIndex) external;

    /// @notice lets governance update lastDistro period for a gauge
    /// @dev should only be used if distribute() is running out of gas
    /// @dev gaugePeriodDistributed will stop double claiming
    /// @param _gauge gauge to update
    /// @param _period period to update to
    function updateLastDistro(address _gauge, uint256 _period) external;

    /// @notice returns the votes cast for a tokenID
    /// @param owner address of the owner
    /// @return votes an array of votes casted
    /// @return weights an array of the weights casted per pool
    function getVotes(address owner, uint256 period)
        external
        view
        returns (address[] memory votes, uint256[] memory weights);

    /// @notice returns an array of all the pools
    /// @return _pools the array of pools
    function getAllPools() external view returns (address[] memory _pools);

    /// @notice returns the length of pools
    function getPoolsLength() external view returns (uint256);

    /// @notice returns the pool at index
    function getPool(uint256 index) external view returns (address);

    /// @notice returns an array of all the gauges
    /// @return _gauges the array of gauges
    function getAllGauges() external view returns (address[] memory _gauges);

    /// @notice returns the length of gauges
    function getGaugesLength() external view returns (uint256);

    /// @notice returns the gauge at index
    function getGauge(uint256 index) external view returns (address);

    /// @notice returns an array of all the feeDists
    /// @return _feeDistributors the array of feeDists
    function getAllFeeDistributors() external view returns (address[] memory _feeDistributors);

    /// @notice sets the xShadowRatio default
    function setGlobalRatio(uint256 _xRatio) external;

    /// @notice whether the token is whitelisted in governance
    function isWhitelisted(address _token) external view returns (bool _tf);

    /// @notice function for removing malicious or stuffed tokens
    function removeFeeDistributorReward(address _feeDist, address _token) external;

    /// @notice returns the total votes for a pool in a specific period
    /// @param pool the pool address to check
    /// @param period the period to check
    /// @return votes the total votes for the pool in that period
    function poolTotalVotesPerPeriod(address pool, uint256 period) external view returns (uint256 votes);

    /// @notice returns the pool address for a given gauge
    /// @param gauge address of the gauge
    /// @return pool address of the pool
    function poolForGauge(address gauge) external view returns (address pool);

    /// @notice returns the pool address for a given feeDistributor
    /// @param feeDistributor address of the feeDistributor
    /// @return pool address of the pool
    function poolForFeeDistributor(address feeDistributor) external view returns (address pool);

    /// @notice returns the voting power used by a voter for a period
    /// @param user address of the user
    /// @param period the period to check
    function userVotingPowerPerPeriod(address user, uint256 period) external view returns (uint256 votingPower);

    /// @notice returns the total votes for a specific period
    /// @param period the period to check
    /// @return weight the total votes for that period
    function totalVotesPerPeriod(uint256 period) external view returns (uint256 weight);

    /// @notice returns the total rewards allocated for a specific period
    /// @param period the period to check
    /// @return amount the total rewards for that period
    function totalRewardPerPeriod(uint256 period) external view returns (uint256 amount);

    /// @notice returns the last distribution period for a gauge
    /// @param _gauge address of the gauge
    /// @return period the last period distributions occurred
    function lastDistro(address _gauge) external view returns (uint256 period);

    /// @notice returns if the gauge is a Cl gauge
    /// @param gauge the gauge to check
    function isClGauge(address gauge) external view returns (bool);

    /// @notice returns if the gauge is a legacy gauge
    /// @param gauge the gauge to check
    function isLegacyGauge(address gauge) external view returns (bool);

    /// @notice sets a new NFP manager
    function setNfpManager(address _nfpManager) external;
}

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

import {IShadowV3PoolImmutables} from "./pool/IShadowV3PoolImmutables.sol";
import {IShadowV3PoolState} from "./pool/IShadowV3PoolState.sol";
import {IShadowV3PoolDerivedState} from "./pool/IShadowV3PoolDerivedState.sol";
import {IShadowV3PoolActions} from "./pool/IShadowV3PoolActions.sol";
import {IShadowV3PoolOwnerActions} from "./pool/IShadowV3PoolOwnerActions.sol";
import {IShadowV3PoolErrors} from "./pool/IShadowV3PoolErrors.sol";
import {IShadowV3PoolEvents} from "./pool/IShadowV3PoolEvents.sol";

/// @title The interface for a Shadow V3 Pool
/// @notice A Shadow pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IShadowV3Pool is
    IShadowV3PoolImmutables,
    IShadowV3PoolState,
    IShadowV3PoolDerivedState,
    IShadowV3PoolActions,
    IShadowV3PoolOwnerActions,
    IShadowV3PoolErrors,
    IShadowV3PoolEvents
{
    /// @notice if a new period, advance on interaction
    function _advancePeriod() external;

    /// @notice Get the index of the last period in the pool
    /// @return The index of the last period
    function lastPeriod() external view returns (uint256);

    /// @notice allows reading arbitrary storage slots
    function readStorage(bytes32[] calldata slots) external view returns (bytes32[] memory returnData);
}

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

import {IPoolInitializer} from './IPoolInitializer.sol';
import {IPeripheryPayments} from './IPeripheryPayments.sol';
import {IPeripheryImmutableState} from './IPeripheryImmutableState.sol';
import {PoolAddress} from '../libraries/PoolAddress.sol';

import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import {IERC721Metadata} from '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import {IERC721Enumerable} from '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';

import {IPeripheryErrors} from './IPeripheryErrors.sol';

/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
    IPeripheryErrors,
    IPoolInitializer,
    IPeripheryPayments,
    IPeripheryImmutableState,
    IERC721,
    IERC721Metadata,
    IERC721Enumerable
{
    /// @notice Emitted when liquidity is increased for a position NFT
    /// @dev Also emitted when a token is minted
    /// @param tokenId The ID of the token for which liquidity was increased
    /// @param liquidity The amount by which liquidity for the NFT position was increased
    /// @param amount0 The amount of token0 that was paid for the increase in liquidity
    /// @param amount1 The amount of token1 that was paid for the increase in liquidity
    event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
    /// @notice Emitted when liquidity is decreased for a position NFT
    /// @param tokenId The ID of the token for which liquidity was decreased
    /// @param liquidity The amount by which liquidity for the NFT position was decreased
    /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
    /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
    event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
    /// @notice Emitted when tokens are collected for a position NFT
    /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
    /// @param tokenId The ID of the token for which underlying tokens were collected
    /// @param recipient The address of the account that received the collected tokens
    /// @param amount0 The amount of token0 owed to the position that was collected
    /// @param amount1 The amount of token1 owed to the position that was collected
    event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);

    /// @notice Returns the position information associated with a given token ID.
    /// @dev Throws if the token ID is not valid.
    /// @param tokenId The ID of the token that represents the position
    /// @return token0 The address of the token0 for a specific pool
    /// @return token1 The address of the token1 for a specific pool
    /// @return tickSpacing The tickSpacing the pool
    /// @return tickLower The lower end of the tick range for the position
    /// @return tickUpper The higher end of the tick range for the position
    /// @return liquidity The liquidity of the position
    /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
    /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
    /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
    /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
    function positions(
        uint256 tokenId
    )
        external
        view
        returns (
            address token0,
            address token1,
            int24 tickSpacing,
            int24 tickLower,
            int24 tickUpper,
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

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

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

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

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

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

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

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

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

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

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

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

import {IVoter} from "contracts/interfaces/IVoter.sol";
import {INonfungiblePositionManager} from "contracts/CL/periphery/interfaces/INonfungiblePositionManager.sol";

interface IPoolUpdater {
    struct SeedData {
        address pool;
        address token0;
        address token1;
        uint256 amount0;
        uint256 amount1;
    }

    ////////////////////
    // View Functions //
    ////////////////////

    function voter() external view returns (IVoter);

    function nfpManager() external view returns (INonfungiblePositionManager);

    function isSeeded(address pool) external view returns (bool);

    function findMissing() external view returns (address[] memory _missingTokens);

    function findNotUpdated() external view returns (address[] memory pools);

    function poolToNfp(address clPool) external view returns (uint256);

    function getAllGauges() external view returns (address[] memory);

    function getGauge(uint256 index) external view returns (address);

    function getGaugeLength() external view returns (uint256);

    function getAllClPools() external view returns (address[] memory);

    function getClPool(uint256 index) external view returns (address);

    function getClPoolsLength() external view returns (uint256);

    //////////////////////
    // Seed and Updates //
    //////////////////////

    function updateRecords() external;

    function seed(uint256 start, uint256 end) external returns (SeedData[] memory failedSeeds);
    function seed(address pool) external;

    function seed(address pool, bool revertOnFailure) external returns (bool success, SeedData memory seedData);

    function updatePools(uint256 start, uint256 end, bool _updateRecords, bool force)
        external
        returns (uint256[] memory, address[] memory);

    function updatePool(address _pool) external;

    ///////////////
    // Callbacks //
    ///////////////

    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata //data
    ) external;

    function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
        external
        pure
        returns (bytes4 retval);

    ///////////////////////
    // AccessHub Actions //
    ///////////////////////

    function sweep(address _token) external;

    function execute(address _target, bytes calldata _payload) external returns (bytes memory _returndata);
}

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

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

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

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

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

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

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

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

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

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

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

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

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

/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
    uint8 internal constant RESOLUTION = 96;
    uint256 internal constant Q96 = 0x1000000000000000000000000;
}

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

/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IShadowV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the IShadowV3Factory interface
    /// @return The contract address
    function factory() external view returns (address);

    /// @notice The first of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token0() external view returns (address);

    /// @notice The second of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token1() external view returns (address);

    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
    /// @return The fee
    function fee() external view returns (uint24);

    /// @notice The pool tick spacing
    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
    /// This value is an int24 to avoid casting even though it is always positive.
    /// @return The tick spacing
    function tickSpacing() external view returns (int24);

    /// @notice The maximum amount of position liquidity that can use any tick in the range
    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
    /// @return The max amount of liquidity per tick
    function maxLiquidityPerTick() external view returns (uint128);
}

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

/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IShadowV3PoolState {
    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
    /// when accessed externally.
    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
    /// @return tick The current tick of the pool, i.e. according to the last tick transition that was run.
    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
    /// boundary.
    /// @return observationIndex The index of the last oracle observation that was written,
    /// @return observationCardinality The current maximum number of observations stored in the pool,
    /// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation.
    /// @return feeProtocol The protocol fee for both tokens of the pool.
    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
    /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
    /// unlocked Whether the pool is currently locked to reentrancy
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint24 feeProtocol,
            bool unlocked
        );

    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal0X128() external view returns (uint256);

    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal1X128() external view returns (uint256);

    /// @notice Get the accumulated fee growth for the first token in the pool before protocol fees
    /// @dev This value can overflow the uint256
    function grossFeeGrowthGlobal0X128() external view returns (uint256);

    /// @notice Get the accumulated fee growth for the second token in the pool before protocol fees
    /// @dev This value can overflow the uint256
    function grossFeeGrowthGlobal1X128() external view returns (uint256);

    /// @notice The amounts of token0 and token1 that are owed to the protocol
    /// @dev Protocol fees will never exceed uint128 max in either token
    function protocolFees() external view returns (uint128 token0, uint128 token1);

    /// @notice The currently in range liquidity available to the pool
    /// @dev This value has no relationship to the total liquidity across all ticks
    /// @return The liquidity at the current price of the pool
    function liquidity() external view returns (uint128);

    /// @notice Look up information about a specific tick in the pool
    /// @param tick The tick to look up
    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
    /// tick upper
    /// @return liquidityNet how much liquidity changes when the pool price crosses the tick,
    /// @return feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
    /// @return feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
    /// @return tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
    /// @return secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
    /// @return secondsOutside the seconds spent on the other side of the tick from the current tick,
    /// @return initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for
    /// a specific position.
    function ticks(
        int24 tick
    )
        external
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
    function tickBitmap(int16 wordPosition) external view returns (uint256);

    /// @notice Returns the information about a position by the position's key
    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
    /// @return liquidity The amount of liquidity in the position,
    /// @return feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
    /// @return feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
    /// @return tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
    /// @return tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
    function positions(
        bytes32 key
    )
        external
        view
        returns (
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    /// @notice Returns data about a specific observation index
    /// @param index The element of the observations array to fetch
    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
    /// ago, rather than at a specific index in the array.
    /// @return blockTimestamp The timestamp of the observation,
    /// @return tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
    /// @return secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
    /// @return initialized whether the observation has been initialized and the values are safe to use
    function observations(
        uint256 index
    )
        external
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        );

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

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

/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IShadowV3PoolDerivedState {
    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
    /// you must call it with secondsAgos = [3600, 0].
    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
    /// timestamp
    function observe(
        uint32[] calldata secondsAgos
    ) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
    /// snapshot is taken and the second snapshot is taken.
    /// @param tickLower The lower tick of the range
    /// @param tickUpper The upper tick of the range
    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range
    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
    /// @return secondsInside The snapshot of seconds per liquidity for the range
    function snapshotCumulativesInside(
        int24 tickLower,
        int24 tickUpper
    ) external view returns (int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside);
}

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

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IShadowV3PoolActions {
    /// @notice Sets the initial price for the pool
    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initialize(uint160 sqrtPriceX96) external;

    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
    /// on tickLower, tickUpper, the amount of liquidity, and the current price.
    /// @param recipient The address for which the liquidity will be created
    /// @param index The index for which the liquidity will be created
    /// @param tickLower The lower tick of the position in which to add liquidity
    /// @param tickUpper The upper tick of the position in which to add liquidity
    /// @param amount The amount of liquidity to mint
    /// @param data Any data that should be passed through to the callback
    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
    function mint(
        address recipient,
        uint256 index,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Collects tokens owed to a position
    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
    /// @param recipient The address which should receive the fees collected
    /// @param index The index of the position to be collected
    /// @param tickLower The lower tick of the position for which to collect fees
    /// @param tickUpper The upper tick of the position for which to collect fees
    /// @param amount0Requested How much token0 should be withdrawn from the fees owed
    /// @param amount1Requested How much token1 should be withdrawn from the fees owed
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(
        address recipient,
        uint256 index,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
    /// @dev Fees must be collected separately via a call to #collect
    /// @param index The index for which the liquidity will be burned
    /// @param tickLower The lower tick of the position for which to burn liquidity
    /// @param tickUpper The upper tick of the position for which to burn liquidity
    /// @param amount How much liquidity to burn
    /// @return amount0 The amount of token0 sent to the recipient
    /// @return amount1 The amount of token1 sent to the recipient
    function burn(
        uint256 index,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

    
    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
    /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
    /// with 0 amount{0,1} and sending the donation amount(s) from the callback
    /// @param recipient The address which will receive the token0 and token1 amounts
    /// @param amount0 The amount of token0 to send
    /// @param amount1 The amount of token1 to send
    /// @param data Any data to be passed through to the callback
    function flash(
        address recipient,
        uint256 amount0,
        uint256 amount1,
        bytes calldata data
    ) external;
    

    /// @notice Increase the maximum number of price and liquidity observations that this pool will store
    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
    /// the input observationCardinalityNext.
    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store
    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}

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

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IShadowV3PoolOwnerActions {
    /// @notice Set the denominator of the protocol's % share of the fees
    function setFeeProtocol() external;

    /// @notice Collect the protocol fee accrued to the pool
    /// @param recipient The address to which collected protocol fees should be sent
    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
    /// @return amount0 The protocol fee collected in token0
    /// @return amount1 The protocol fee collected in token1
    function collectProtocol(
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    function setFee(uint24 _fee) external;
}

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

/// @title Errors emitted by a pool
/// @notice Contains all custom errors that can be emitted by the pool
interface IShadowV3PoolErrors {
    /*//////////////////////////////////////////////////////////////
                            POOL ERRORS
    //////////////////////////////////////////////////////////////*/

    /// @notice Thrown when the pool is locked during a swap or mint/burn operation
    error LOK(); // Locked

    /// @notice Thrown when tick lower is greater than upper in position management
    error TLU(); // Tick Lower > Upper

    /// @notice Thrown when tick lower is less than minimum allowed
    error TLM(); // Tick Lower < Min

    /// @notice Thrown when tick upper is greater than maximum allowed
    error TUM(); // Tick Upper > Max

    /// @notice Thrown when the pool is already initialized
    error AI(); // Already Initialized

    /// @notice Thrown when the first margin value is zero
    error M0(); // Mint token 0 error

    /// @notice Thrown when the second margin value is zero
    error M1(); // Mint token1 error

    /// @notice Thrown when amount specified is invalid
    error AS(); // Amount Specified Invalid

    /// @notice Thrown when input amount is insufficient
    error IIA(); // Insufficient Input Amount

    /// @notice Thrown when pool lacks sufficient liquidity for operation
    error L(); // Insufficient Liquidity

    /// @notice Thrown when the first fee value is zero
    error F0(); // Fee0 issue or Fee = 0

    /// @notice Thrown when the second fee value is zero
    error F1(); // Fee1 issue

    /// @notice Thrown when square price limit is invalid
    error SPL(); // Square Price Limit Invalid
}

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

/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IShadowV3PoolEvents {
    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool
    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
    event Initialize(uint160 sqrtPriceX96, int24 tick);

    /// @notice Emitted when liquidity is minted for a given position
    /// @param sender The address that minted the liquidity
    /// @param owner The owner of the position and recipient of any minted liquidity
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity minted to the position range
    /// @param amount0 How much token0 was required for the minted liquidity
    /// @param amount1 How much token1 was required for the minted liquidity
    event Mint(
        address sender,
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted when fees are collected by the owner of a position
    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
    /// @param owner The owner of the position for which fees are collected
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount0 The amount of token0 fees collected
    /// @param amount1 The amount of token1 fees collected
    event Collect(
        address indexed owner,
        address recipient,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount0,
        uint128 amount1
    );

    /// @notice Emitted when a position's liquidity is removed
    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
    /// @param owner The owner of the position for which liquidity is removed
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity to remove
    /// @param amount0 The amount of token0 withdrawn
    /// @param amount1 The amount of token1 withdrawn
    event Burn(
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted by the pool for any swaps between token0 and token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the output of the swap
    /// @param amount0 The delta of the token0 balance of the pool
    /// @param amount1 The delta of the token1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of price of the pool after the swap
    event Swap(
        address indexed sender,
        address indexed recipient,
        int256 amount0,
        int256 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick
    );

    /// @notice Emitted by the pool for any flashes of token0/token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the tokens from flash
    /// @param amount0 The amount of token0 that was flashed
    /// @param amount1 The amount of token1 that was flashed
    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
    event Flash(
        address indexed sender,
        address indexed recipient,
        uint256 amount0,
        uint256 amount1,
        uint256 paid0,
        uint256 paid1
    );

    /// @notice Emitted by the pool for increases to the number of observations that can be stored
    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
    /// just before a mint/swap/burn.
    /// @param observationCardinalityNextOld The previous value of the next observation cardinality
    /// @param observationCardinalityNextNew The updated value of the next observation cardinality
    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew
    );

    /// @notice Emitted when the protocol fee is changed by the pool
    /// @param feeProtocol0Old The previous value of the token0 protocol fee
    /// @param feeProtocol1Old The previous value of the token1 protocol fee
    /// @param feeProtocol0New The updated value of the token0 protocol fee
    /// @param feeProtocol1New The updated value of the token1 protocol fee
    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);

    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
    /// @param sender The address that collects the protocol fees
    /// @param recipient The address that receives the collected protocol fees
    /// @param amount0 The amount of token0 protocol fees that is withdrawn
    /// @param amount0 The amount of token1 protocol fees that is withdrawn
    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}

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

/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
    /// @notice Creates a new pool if it does not exist, then initializes if not initialized
    /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
    /// @param token0 The contract address of token0 of the pool
    /// @param token1 The contract address of token1 of the pool
    /// @param tickSpacing The tickSpacing of the v3 pool for the specified token pair
    /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
    /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
    function createAndInitializePoolIfNecessary(
        address token0,
        address token1,
        int24 tickSpacing,
        uint160 sqrtPriceX96
    ) external payable returns (address pool);
}

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

/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
    /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
    /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
    /// @param amountMinimum The minimum amount of WETH9 to unwrap
    /// @param recipient The address receiving ETH
    function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;

    /// @notice Refunds any ETH balance held by this contract to the `msg.sender`
    /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
    /// that use ether for the input amount
    function refundETH() external payable;

    /// @notice Transfers the full amount of a token held by this contract to recipient
    /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
    /// @param token The contract address of the token which will be transferred to `recipient`
    /// @param amountMinimum The minimum amount of token required for a transfer
    /// @param recipient The destination address of the token
    function sweepToken(
        address token,
        uint256 amountMinimum,
        address recipient
    ) external payable;
}

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

/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
    /// @return Returns the address of the Uniswap V3 deployer
    function deployer() external view returns (address);

    /// @return Returns the address of WETH9
    function WETH9() external view returns (address);
}

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

/// @title Provides functions for deriving a pool address from the deployer, tokens, and the fee
library PoolAddress {
    bytes32 internal constant POOL_INIT_CODE_HASH = 0x892f127ed4b26ca352056c8fb54585a3268f76f97fdd84d5836ef4bda8d8c685;

    /// @notice The identifying key of the pool
    struct PoolKey {
        address token0;
        address token1;
        int24 tickSpacing;
    }

    /// @notice Returns PoolKey: the ordered tokens with the matched fee levels
    /// @param tokenA The first token of a pool, unsorted
    /// @param tokenB The second token of a pool, unsorted
    /// @param tickSpacing The tickSpacing of the pool
    /// @return Poolkey The pool details with ordered token0 and token1 assignments
    function getPoolKey(address tokenA, address tokenB, int24 tickSpacing) internal pure returns (PoolKey memory) {
        if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
        return PoolKey({token0: tokenA, token1: tokenB, tickSpacing: tickSpacing});
    }

    /// @notice Deterministically computes the pool address given the deployer and PoolKey
    /// @param deployer The Uniswap V3 deployer contract address
    /// @param key The PoolKey
    /// @return pool The contract address of the V3 pool
    function computeAddress(address deployer, PoolKey memory key) internal pure returns (address pool) {
        require(key.token0 < key.token1, "!TokenOrder");
        pool = address(
            uint160(
                uint256(
                    keccak256(
                        abi.encodePacked(
                            hex'ff',
                            deployer,
                            keccak256(abi.encode(key.token0, key.token1, key.tickSpacing)),
                            POOL_INIT_CODE_HASH
                        )
                    )
                )
            )
        );
    }
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Enumerable.sol)

pragma solidity ^0.8.20;

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

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}

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

/// @title Errors emitted by the NonFungiblePositionManager
/// @notice Contains all events emitted by the NfpManager
interface IPeripheryErrors {
    error InvalidTokenId(uint256 tokenId);
    error CheckSlippage();
    error NotCleared();
}

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

Please enter a contract address above to load the contract details and source code.

Context size (optional):