S Price: $0.689363 (-5.25%)

Contract Diff Checker

Contract Name:
Voter

Contract Source Code:

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

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {VoterRewardClaimers} from "./libraries/VoterRewardClaimers.sol";

import {IGaugeV3} from "./CL/gauge/interfaces/IGaugeV3.sol";

import {IMarbleMinter} from "./interfaces/IMarbleMinter.sol";
import {IMinter} from "./interfaces/IMinter.sol";
import {IPair} from "./interfaces/IPair.sol";
import {IPairFactory} from "./interfaces/IPairFactory.sol";
import {IFeeRecipient} from "./interfaces/IFeeRecipient.sol";
import {IFeeRecipientFactory} from "./interfaces/IFeeRecipientFactory.sol";

import {IShadowV3Factory} from "./CL/core/interfaces/IShadowV3Factory.sol";
import {IShadowV3Pool} from "./CL/core/interfaces/IShadowV3Pool.sol";
import {IClGaugeFactory} from "./CL/gauge/interfaces/IClGaugeFactory.sol";
import {IPoolUpdater} from "./CL/gauge/interfaces/IPoolUpdater.sol";
import {IFeeCollector} from "./CL/gauge/interfaces/IFeeCollector.sol";

import {IVoteModule} from "./interfaces/IVoteModule.sol";
import {IVoter} from "./interfaces/IVoter.sol";
import {Errors} from "contracts/libraries/Errors.sol";
import {IFeeDistributor} from "./interfaces/IFeeDistributor.sol";
import {IFeeDistributorFactory} from "./interfaces/IFeeDistributorFactory.sol";
import {IGauge} from "./interfaces/IGauge.sol";
import {IGaugeFactory} from "./interfaces/IGaugeFactory.sol";
import {IXShadow} from "./interfaces/IXShadow.sol";

import {VoterStorage} from "./libraries/VoterStorage.sol";
import {VoterGovernanceActions} from "./libraries/VoterGovernanceActions.sol";

contract Voter is IVoter, ReentrancyGuard, Initializable {
    using EnumerableSet for EnumerableSet.AddressSet;

    /// @dev internal duration constant
    uint256 internal constant DURATION = 7 days;
    /// @inheritdoc IVoter
    uint256 public constant BASIS = 1_000_000;
    uint256 public constant OLD_LEGACY_FEE_SPLIT_BASIS = 10_000;

    modifier onlyGovernance() {
        _onlyGovernance();
        _;
    }

    function _onlyGovernance() internal view {
        require(msg.sender == VoterStorage.getStorage().accessHub, Errors.NOT_AUTHORIZED(msg.sender));
    }

    constructor() {
        _disableInitializers();
    }

    /// @dev should be called with upgradeToAndInitialize
    function initializeAccessHub(address _accessHub) external initializer {
        VoterStorage.getStorage().accessHub = _accessHub;
    }

    /// @dev separated from initializeAccessHub to minimize changes to deployment scripts
    function initialize(InitializationParams memory inputs) external reinitializer(2) {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev ensure only accessHub can initialize
        require($.accessHub == msg.sender, Errors.NOT_AUTHORIZED(msg.sender));
        $.legacyFactory = inputs.legacyFactory;
        $.shadow = inputs.shadow;
        $.gaugeFactory = inputs.gauges;
        $.feeDistributorFactory = inputs.feeDistributorFactory;
        $.minter = inputs.minter;
        $.xShadow = inputs.xShadow;
        $.governor = inputs.msig;
        $.feeRecipientFactory = inputs.feeRecipientFactory;
        $.voteModule = inputs.voteModule;
        $.launcherPlugin = inputs.launcherPlugin;
        $.poolUpdater = inputs.poolUpdater;

        $.clFactory = inputs.clFactory;
        $.clGaugeFactory = inputs.clGaugeFactory;
        $.nfpManager = inputs.nfpManager;

        /// @dev default at 100% xRatio
        $.xRatio = 1_000_000;
        /// @dev emits from the zero address since it's the first time
        emit EmissionsRatio(address(0), 0, 1_000_000);
        /// @dev perma approval
        IERC20(inputs.shadow).approve(inputs.xShadow, type(uint256).max);

        /// @dev whitelist shadow and xshadow
        $.isWhitelisted[inputs.shadow] = true;
        emit Whitelisted(msg.sender, inputs.shadow);
        $.isWhitelisted[inputs.xShadow] = true;
        emit Whitelisted(msg.sender, inputs.xShadow);
    }

    function transferOwnership(address _newAccessHub) external onlyGovernance {
        VoterStorage.getStorage().accessHub = _newAccessHub;
    }

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

    /// @inheritdoc IVoter
    function getVotes(address user, uint256 period)
        external
        view
        returns (address[] memory votes, uint256[] memory weights)
    {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev fetch the user's voted pools for the period
        votes = $.userVotedPoolsPerPeriod[user][period];
        /// @dev set weights array length equal to the votes length
        weights = new uint256[](votes.length);
        /// @dev loop through the votes and populate the weights
        for (uint256 i; i < votes.length; ++i) {
            weights[i] = $.userVotesForPoolPerPeriod[user][period][votes[i]];
        }
    }

    /// @inheritdoc IVoter
    function legacyFactory() external view returns (address) {
        return VoterStorage.getStorage().legacyFactory;
    }

    /// @inheritdoc IVoter
    function shadow() external view returns (address) {
        return VoterStorage.getStorage().shadow;
    }

    /// @inheritdoc IVoter
    function gaugeFactory() external view returns (address) {
        return VoterStorage.getStorage().gaugeFactory;
    }

    /// @inheritdoc IVoter
    function feeDistributorFactory() external view returns (address) {
        return VoterStorage.getStorage().feeDistributorFactory;
    }

    /// @inheritdoc IVoter
    function minter() external view returns (address) {
        return VoterStorage.getStorage().minter;
    }

    /// @inheritdoc IVoter
    function accessHub() external view returns (address) {
        return VoterStorage.getStorage().accessHub;
    }

    /// @inheritdoc IVoter
    function governor() external view returns (address) {
        return VoterStorage.getStorage().governor;
    }

    /// @inheritdoc IVoter
    function clFactory() external view returns (address) {
        return VoterStorage.getStorage().clFactory;
    }

    /// @inheritdoc IVoter
    function clGaugeFactory() external view returns (address) {
        return VoterStorage.getStorage().clGaugeFactory;
    }

    /// @inheritdoc IVoter
    function poolUpdater() external view returns (address) {
        return VoterStorage.getStorage().poolUpdater;
    }

    /// @inheritdoc IVoter
    function nfpManager() external view returns (address) {
        return VoterStorage.getStorage().nfpManager;
    }

    /// @inheritdoc IVoter
    function feeRecipientFactory() external view returns (address) {
        return VoterStorage.getStorage().feeRecipientFactory;
    }

    /// @inheritdoc IVoter
    function xShadow() external view returns (address) {
        return VoterStorage.getStorage().xShadow;
    }

    /// @inheritdoc IVoter
    function voteModule() external view returns (address) {
        return VoterStorage.getStorage().voteModule;
    }

    /// @inheritdoc IVoter
    function launcherPlugin() external view returns (address) {
        return VoterStorage.getStorage().launcherPlugin;
    }

    /// @inheritdoc IVoter
    function xRatio() external view returns (uint256) {
        return VoterStorage.getStorage().xRatio;
    }

    function gaugeForPool(address pool) external view returns (address) {
        return VoterStorage.getStorage().gaugeForPool[pool];
    }

    function poolForGauge(address gauge) external view returns (address) {
        return VoterStorage.getStorage().poolForGauge[gauge];
    }

    function feeDistributorForGauge(address gauge) external view returns (address) {
        return VoterStorage.getStorage().feeDistributorForGauge[gauge];
    }

    function poolTotalVotesPerPeriod(address pool, uint256 period) external view returns (uint256) {
        return VoterStorage.getStorage().poolTotalVotesPerPeriod[pool][period];
    }

    function userVotesForPoolPerPeriod(address user, uint256 period, address pool) external view returns (uint256) {
        return VoterStorage.getStorage().userVotesForPoolPerPeriod[user][period][pool];
    }

    function userVotedPoolsPerPeriod(address user, uint256 period, uint256 index) external view returns (address) {
        return VoterStorage.getStorage().userVotedPoolsPerPeriod[user][period][index];
    }

    function userVotedPoolsPerPeriodLength(address user, uint256 period) external view returns (uint256) {
        return VoterStorage.getStorage().userVotedPoolsPerPeriod[user][period].length;
    }

    function getAllUserVotedPoolsPerPeriod(address user, uint256 period) external view returns (address[] memory) {
        return VoterStorage.getStorage().userVotedPoolsPerPeriod[user][period];
    }

    function userVotingPowerPerPeriod(address user, uint256 period) external view returns (uint256) {
        return VoterStorage.getStorage().userVotingPowerPerPeriod[user][period];
    }

    function lastVoted(address user) external view returns (uint256) {
        return VoterStorage.getStorage().lastVoted[user];
    }

    function totalRewardPerPeriod(uint256 period) external view returns (uint256) {
        return VoterStorage.getStorage().totalRewardPerPeriod[period];
    }

    function totalVotesPerPeriod(uint256 period) external view returns (uint256) {
        return VoterStorage.getStorage().totalVotesPerPeriod[period];
    }

    function gaugeRewardsPerPeriod(address gauge, uint256 period) external view returns (uint256) {
        return VoterStorage.getStorage().gaugeRewardsPerPeriod[gauge][period];
    }

    function gaugePeriodDistributed(address gauge, uint256 period) external view returns (bool) {
        return VoterStorage.getStorage().gaugePeriodDistributed[gauge][period];
    }

    function lastDistro(address gauge) external view returns (uint256) {
        return VoterStorage.getStorage().lastDistro[gauge];
    }

    function isLegacyGauge(address gauge) external view returns (bool) {
        return VoterStorage.getStorage().isLegacyGauge[gauge];
    }

    function isClGauge(address gauge) external view returns (bool) {
        return VoterStorage.getStorage().isClGauge[gauge];
    }

    function isWhitelisted(address token) external view returns (bool) {
        return VoterStorage.getStorage().isWhitelisted[token];
    }

    function isAlive(address gauge) external view returns (bool) {
        return VoterStorage.getStorage().isAlive[gauge];
    }

    function poolForFeeDistributor(address feeDist) external view returns (address) {
        return VoterStorage.getStorage().poolForFeeDistributor[feeDist];
    }

    /// @inheritdoc IVoter
    function getPeriod() public view returns (uint256 period) {
        return (block.timestamp / 1 weeks);
    }

    ////////////
    // Voting //
    ////////////

    /// @inheritdoc IVoter
    function reset(address user) external {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev if the caller isn't the user
        if (msg.sender != user) {
            /// @dev check for delegation
            require(IVoteModule($.voteModule).isDelegateFor(msg.sender, user), Errors.NOT_AUTHORIZED(msg.sender));
        }
        _reset(user);

        $.lastVoted[user] = getPeriod();
    }

    function _reset(address user) internal {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev voting for the next period
        uint256 nextPeriod = getPeriod() + 1;
        /// @dev fetch the previously voted pools
        address[] memory votedPools = $.userVotedPoolsPerPeriod[user][nextPeriod];
        /// @dev fetch the user's stored voting power for the voting period
        uint256 votingPower = $.userVotingPowerPerPeriod[user][nextPeriod];
        /// @dev if an existing vote is cast
        if (votingPower > 0) {
            /// @dev loop through the pools
            for (uint256 i; i < votedPools.length; ++i) {
                /// @dev fetch the individual casted for the pool for the next period
                uint256 userVote = $.userVotesForPoolPerPeriod[user][nextPeriod][votedPools[i]];
                /// @dev decrement the total vote by the existing vote
                $.poolTotalVotesPerPeriod[votedPools[i]][nextPeriod] -= userVote;
                /// @dev wipe the mapping
                delete $.userVotesForPoolPerPeriod[user][nextPeriod][votedPools[i]];
                /// @dev call _withdraw on the FeeDistributor
                IFeeDistributor($.originalFeeDistributorForGauge[$.gaugeForPool[votedPools[i]]])._withdraw(
                    userVote, user
                );
                emit Abstained(address(0), userVote);
            }
            /// @dev reduce the overall vote power casted
            $.totalVotesPerPeriod[nextPeriod] -= votingPower;
            /// @dev wipe the mappings
            delete $.userVotingPowerPerPeriod[user][nextPeriod];
            delete $.userVotedPoolsPerPeriod[user][nextPeriod];
        }
    }

    /// @inheritdoc IVoter
    function poke(address user) external {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev ensure the caller is either the user or the vote module
        if (msg.sender != user) {
            /// @dev ...require they are authorized to be a delegate
            require(
                IVoteModule($.voteModule).isDelegateFor(msg.sender, user) || msg.sender == $.voteModule,
                Errors.NOT_AUTHORIZED(msg.sender)
            );
        }
        uint256 _lastVoted = $.lastVoted[user];
        /// @dev has no prior vote, terminate early
        if (_lastVoted == 0) return;
        /// @dev fetch the last voted pools since votes are casted into the next week's mapping
        address[] memory votedPools = $.userVotedPoolsPerPeriod[user][_lastVoted + 1];
        /// @dev fetch the voting power of the user in that period after
        uint256 userVotePower = $.userVotingPowerPerPeriod[user][_lastVoted + 1];
        /// @dev if nothing, terminate
        if (userVotePower == 0) return;

        uint256[] memory voteWeights = new uint256[](votedPools.length);
        /// @dev loop and fetch weights
        for (uint256 i; i < votedPools.length; i++) {
            voteWeights[i] = $.userVotesForPoolPerPeriod[user][_lastVoted + 1][votedPools[i]];
        }
        /// @dev recast with new voting power and same weights/pools as prior
        _vote(user, votedPools, voteWeights);
        emit Poke(user);
    }
    /// @inheritdoc IVoter
    /**
     * important information on the mappings (since it is quite confusing):
     * - userVotedPoolsPerPeriod is stored in the NEXT period when triggered
     * - userVotingPowerPerPeriod  is stored in the NEXT period
     * - userVotesForPoolPerPeriod is stored in the NEXT period
     * - poolTotalVotesPerPeriod is stored in the NEXT period
     * - lastVoted is stored in the CURRENT period
     */

    function vote(address user, address[] calldata _pools, uint256[] calldata _weights) external {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev ensure that the arrays length matches and that the length is > 0
        require(_pools.length > 0 && _pools.length == _weights.length, Errors.LENGTH_MISMATCH());
        /// @dev if the caller isn't the user...
        if (msg.sender != user) {
            /// @dev ...require they are authorized to be a delegate
            require(IVoteModule($.voteModule).isDelegateFor(msg.sender, user), Errors.NOT_AUTHORIZED(msg.sender));
        }
        /// @dev make a memory array of votedPools
        address[] memory votedPools = new address[](_pools.length);
        /// @dev loop through and populate the array
        for (uint256 i = 0; i < _pools.length; ++i) {
            votedPools[i] = _pools[i];
        }

        /// @dev cast new votes
        _vote(user, votedPools, _weights);
    }

    function _vote(address user, address[] memory _pools, uint256[] memory _weights) internal {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev wipe all votes if needed, the checks are in _reset()
        /// @dev keep this here, DO NOT REMOVE THIS. The gas saving isn't worth it
        /// @dev Prevents footguns where _vote() is called without resetting
        _reset(user);

        /// @dev grab the nextPeriod
        uint256 nextPeriod = getPeriod() + 1;
        /// @dev fetch the user's votingPower
        uint256 votingPower = IVoteModule($.voteModule).balanceOf(user);

        /// @dev loop through and add up the amounts, we do this because weights are proportions and not directly the vote power values
        uint256 totalVoteWeight;
        for (uint256 i; i < _pools.length; i++) {
            totalVoteWeight += _weights[i];
        }
        /// @dev if totalVoteWeight is 0, make it a 1 instead and let the rest of the tx go through
        /// incase anything else needs to be written
        /// early returns can be a footgun here if some data are written to storage and others not
        if (totalVoteWeight == 0) {
            totalVoteWeight = 1;
        }

        /// @dev assign variables for validation
        address[] memory validPools = new address[](_pools.length);
        uint256 validTotalWeight;
        uint256 validPoolLength;

        /// @dev loop through all pools
        for (uint256 i; i < _pools.length; i++) {
            /// @dev fetch the gauge for the pool
            address _gauge = $.gaugeForPool[_pools[i]];
            /// @dev skip if dead gauge
            if (!$.isAlive[_gauge]) {
                continue;
            }
            /// @dev scale the weight of the pool
            uint256 _poolWeight = (_weights[i] * votingPower) / totalVoteWeight;
            /// @dev skip if 0 weight
            if (_poolWeight == 0) {
                continue;
            }
            /// @dev skip if repeat vote
            if ($.userVotesForPoolPerPeriod[user][nextPeriod][_pools[i]] != 0) {
                continue;
            }
            /// @dev add to valid pools and valid total weights
            validPools[validPoolLength] = _pools[i];
            validTotalWeight += _poolWeight;
            validPoolLength++;

            /// @dev increment to the votes for this pool
            $.poolTotalVotesPerPeriod[_pools[i]][nextPeriod] += _poolWeight;
            /// @dev increment the user's votes for this pool
            $.userVotesForPoolPerPeriod[user][nextPeriod][_pools[i]] += _poolWeight;
            /// @dev deposit the votes to the FeeDistributor
            IFeeDistributor($.originalFeeDistributorForGauge[_gauge])._deposit(_poolWeight, user);
            /// @dev emit the voted event, passing the user and the raw vote weight given to the pool
            emit Voted(user, _poolWeight, _pools[i]);
        }

        /// @dev trim length if needed
        if (validPoolLength != validPools.length) {
            assembly ("memory-safe") {
                mstore(validPools, validPoolLength)
            }
        }

        /// @dev set the voting power for the user for the period
        $.userVotingPowerPerPeriod[user][nextPeriod] = validTotalWeight;
        /// @dev update the pools voted for
        $.userVotedPoolsPerPeriod[user][nextPeriod] = validPools;

        /// @dev increment to the total
        $.totalVotesPerPeriod[nextPeriod] += validTotalWeight;
        /// @dev last vote as current epoch
        $.lastVoted[user] = nextPeriod - 1;
    }

    ///////////////////////////
    // Emission Distribution //
    ///////////////////////////

    function _distribute(address _gauge, uint256 _claimable, uint256 _period) internal {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev check if the gauge is even alive
        if ($.isAlive[_gauge]) {
            /// @dev if there is 0 claimable terminate
            if (_claimable == 0) return;
            /// @dev if the gauge is already distributed for the period, terminate
            if ($.gaugePeriodDistributed[_gauge][_period]) return;

            /// @dev fetch shadow address
            address _xShadow = address($.xShadow);
            /// @dev fetch the current ratio and multiply by the claimable
            uint256 _xShadowClaimable = (_claimable * $.xRatio) / BASIS;
            /// @dev remove from the regular claimable tokens (SHADOW)
            _claimable -= _xShadowClaimable;

            /// @dev can only distribute if the distributed amount / week > 0 and is > left()
            bool canDistribute = true;

            /// @dev _claimable could be 0 if emission is 100% xShadow
            if (_claimable > 0) {
                if (
                    _claimable / DURATION == 0
                        || (_claimable < IGauge(_gauge).left($.shadow) && $.isLegacyGauge[_gauge])
                ) {
                    canDistribute = false;
                }
            }
            /// @dev _xShadowClaimable could be 0 if ratio is 100% emissions
            if (_xShadowClaimable > 0) {
                if (
                    _xShadowClaimable / DURATION == 0
                        || (_xShadowClaimable < IGauge(_gauge).left(_xShadow) && $.isLegacyGauge[_gauge])
                ) {
                    canDistribute = false;
                }
            }

            /// @dev if the checks pass and the gauge can be distributed
            if (canDistribute) {
                /// @dev set it to true firstly
                $.gaugePeriodDistributed[_gauge][_period] = true;

                /// @dev fetch destination gauge if there is an override
                address destinationGauge = $.gaugeRedirect[_gauge];
                if (destinationGauge == address(0)) {
                    destinationGauge = _gauge;
                }

                /// @dev check SHADOW "claimable"
                if (_claimable > 0) {
                    /// @dev notify emissions
                    IGauge(destinationGauge).notifyRewardAmount($.shadow, _claimable);
                }
                /// @dev check xSHADOW "claimable"
                if (_xShadowClaimable > 0) {
                    /// @dev convert, then notify the xShadow
                    IXShadow(_xShadow).convertEmissionsToken(_xShadowClaimable);
                    IGauge(destinationGauge).notifyRewardAmount(_xShadow, _xShadowClaimable);
                }

                emit DistributeReward(msg.sender, _gauge, _claimable + _xShadowClaimable);
            }
        }
    }

    ////////////////////////////////
    // Governance Gated Functions //
    ////////////////////////////////

    /// @inheritdoc IVoter
    /// @notice sets the default xShadowRatio
    function setGlobalRatio(uint256 _xRatio) external onlyGovernance {
        VoterGovernanceActions.setGlobalRatio(_xRatio);
    }

    /// @inheritdoc IVoter
    function setGovernor(address _governor) external onlyGovernance {
        VoterGovernanceActions.setGovernor(_governor);
    }

    /// @inheritdoc IVoter
    function whitelist(address _token) public onlyGovernance {
        VoterGovernanceActions.whitelist(_token);
    }

    /// @inheritdoc IVoter
    function revokeWhitelist(address _token) public onlyGovernance {
        VoterGovernanceActions.revokeWhitelist(_token);
    }

    /// @inheritdoc IVoter
    function killGauge(address _gauge) public onlyGovernance {
        VoterGovernanceActions.killGauge(_gauge);
    }

    /// @inheritdoc IVoter
    function reviveGauge(address _gauge) public onlyGovernance {
        VoterGovernanceActions.reviveGauge(_gauge);
    }

    /// @inheritdoc IVoter
    /// @dev in case of emission stuck due to killed gauges and unsupported operations
    function stuckEmissionsRecovery(address _gauge, uint256 _period) external onlyGovernance {
        VoterGovernanceActions.stuckEmissionsRecovery(_gauge, _period);
    }

    /// @inheritdoc IVoter
    function removeFeeDistributorReward(address _feeDistributor, address reward) external onlyGovernance {
        VoterGovernanceActions.removeFeeDistributorReward(_feeDistributor, reward);
    }

    /// @inheritdoc IVoter
    function setNfpManager(address _nfpManager) external onlyGovernance {
        VoterGovernanceActions.setNfpManager(_nfpManager);
    }

    ////////////////////
    // Gauge Creation //
    ////////////////////

    /// @inheritdoc IVoter
    function createGauge(address _pool) external onlyGovernance returns (address) {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev ensure there is no gauge for the pool
        require($.gaugeForPool[_pool] == address(0), Errors.ACTIVE_GAUGE($.gaugeForPool[_pool]));
        /// @dev check if it's a legacy pair
        bool isPair = IPairFactory($.legacyFactory).isPair(_pool);
        require(isPair, Errors.NOT_POOL(_pool));
        /// @dev fetch token0 and token1 from the pool's metadata
        (,,,,, address token0, address token1) = IPair(_pool).metadata();
        /// @dev ensure that both tokens are whitelisted
        require($.isWhitelisted[token0] && $.isWhitelisted[token1], Errors.BOTH_NOT_WHITELISTED());

        /// @dev create the feeRecipient via the factory
        address feeRecipient = IFeeRecipientFactory($.feeRecipientFactory).createFeeRecipient(_pool);
        /// @dev create the feeDist via factory from the feeRecipient
        address _feeDistributor = IFeeDistributorFactory($.feeDistributorFactory).createFeeDistributor(feeRecipient);
        /// @dev init feeRecipient with the feeDist
        IFeeRecipient(feeRecipient).initialize(_feeDistributor);
        if ($.voterOwnsLegacyFactory) {
            /// @dev set the feeRecipient in the factory
            IPairFactory($.legacyFactory).setFeeRecipient(_pool, feeRecipient);
        }
        /// @dev create a legacy gauge from the factory
        address _gauge = IGaugeFactory($.gaugeFactory).createGauge(_pool);
        /// @dev give infinite approvals in advance
        IERC20($.shadow).approve(_gauge, type(uint256).max);
        IERC20($.xShadow).approve(_gauge, type(uint256).max);
        /// @dev update voter mappings
        $.feeDistributorForGauge[_gauge] = _feeDistributor;
        $.originalFeeDistributorForGauge[_gauge] = _feeDistributor;
        $.gaugeForPool[_pool] = _gauge;
        $.poolForGauge[_gauge] = _pool;
        $.poolForFeeDistributor[_feeDistributor] = _pool;
        /// @dev set gauge to alive
        $.isAlive[_gauge] = true;
        /// @dev add to the sets
        $.pools.add(_pool);
        $.gauges.add(_gauge);
        $.feeDistributors.add(_feeDistributor);
        /// @dev set true that it is a legacy gauge
        $.isLegacyGauge[_gauge] = true;
        /// @dev set the last distribution as the current period
        $.lastDistro[_gauge] = getPeriod();
        /// @dev emit the gauge creation event
        emit GaugeCreated(_gauge, msg.sender, _feeDistributor, _pool);

        /// @dev set up fee redirection
        IMarbleMinter($.minter).postCreateLegacyGaugeHook(_pool);

        /// @dev return the new created gauge address
        return _gauge;
    }

    /// @inheritdoc IVoter
    function createCLGauge(address tokenA, address tokenB, int24 tickSpacing)
        external
        onlyGovernance
        returns (address)
    {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        IShadowV3Factory _factory = IShadowV3Factory($.clFactory);
        /// @dev fetch the V3 pool's address
        address _pool = _factory.getPool(tokenA, tokenB, tickSpacing);
        /// @dev require the pool exists
        require(_pool != address(0), Errors.NOT_POOL(_pool));
        /// @dev require the pool is seeded
        require(IPoolUpdater($.poolUpdater).isSeeded(_pool), Errors.NOT_SEEDED(_pool));
        /// @dev check the reentrancy lock
        (,,,,,, bool unlocked) = IShadowV3Pool(_pool).slot0();
        /// @dev require it is unlocked, else it is considered not initialized
        require(unlocked, Errors.NOT_INIT());
        /// @dev ensure a gauge does not already exist for the pool
        require($.gaugeForPool[_pool] == address(0), Errors.ACTIVE_GAUGE($.gaugeForPool[_pool]));
        /// @dev ensure both tokens are whitelisted
        require($.isWhitelisted[tokenA] && $.isWhitelisted[tokenB], Errors.BOTH_NOT_WHITELISTED());
        /// @dev fetch the feeCollector
        address _feeCollector = _factory.feeCollector();

        /// @dev sort tokens
        (address token0, address token1) = _sortTokens(tokenA, tokenB);

        /// @dev create a FeeDistributor if needed
        address _feeDistributor = $.feeDistributorForClPair[token0][token1];
        if (_feeDistributor == address(0)) {
            _feeDistributor = IFeeDistributorFactory($.feeDistributorFactory).createFeeDistributor(_feeCollector);
            $.feeDistributorForClPair[token0][token1] = _feeDistributor;
        }

        /// @dev create the gauge
        address _gauge = IClGaugeFactory($.clGaugeFactory).createGauge(_pool);
        /// @dev unlimited approve shadow and xShadow to the gauge
        IERC20($.shadow).approve(_gauge, type(uint256).max);
        IERC20($.xShadow).approve(_gauge, type(uint256).max);
        /// @dev update mappings
        $.feeDistributorForGauge[_gauge] = _feeDistributor;
        $.originalFeeDistributorForGauge[_gauge] = _feeDistributor;
        $.gaugeForPool[_pool] = _gauge;
        $.poolForGauge[_gauge] = _pool;
        $.poolForFeeDistributor[_feeDistributor] = _pool;
        $.lastDistro[_gauge] = getPeriod();
        $.pools.add(_pool);
        $.gauges.add(_gauge);
        $.feeDistributors.add(_feeDistributor);
        $.isClGauge[_gauge] = true;
        $._tickSpacingsForPair[token0][token1].push(tickSpacing);
        $._gaugeForClPool[token0][token1][tickSpacing] = _gauge;
        $.isAlive[_gauge] = true;

        /// @dev add this new gauge to the enumerable set
        $.gaugesForClPair[token0][token1].add(_gauge);

        /// @dev redirect gauges for the same cl pair to the new gauge
        /// governance most likely made this new gauge to replace others
        redirectEmissions(token0, token1, _gauge);

        emit GaugeCreated(_gauge, msg.sender, _feeDistributor, _pool);

        return _gauge;
    }

    /// @inheritdoc IVoter
    function redirectEmissions(address tokenA, address tokenB, address destinationGauge) public onlyGovernance {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev sort tokens
        (address token0, address token1) = _sortTokens(tokenA, tokenB);

        EnumerableSet.AddressSet storage _gaugesForClPair = $.gaugesForClPair[token0][token1];

        /// @dev require the destination gauge to be of the same token0/token1 pair
        require(_gaugesForClPair.contains(destinationGauge), Errors.NO_GAUGE(destinationGauge));

        /// @dev redirect the gauges
        uint256 length = _gaugesForClPair.length();
        for (uint256 i; i < length; i++) {
            address sourceGauge = _gaugesForClPair.at(i);
            $.gaugeRedirect[sourceGauge] = destinationGauge;

            emit EmissionsRedirected(sourceGauge, destinationGauge);
        }
    }

    /////////////////////////////
    // One-stop Reward Claimer //
    /////////////////////////////

    /// @inheritdoc IVoter
    function claimClGaugeRewards(
        address[] calldata _gauges,
        address[][] calldata _tokens,
        uint256[][] calldata _nfpTokenIds
    ) external {
        VoterRewardClaimers.claimClGaugeRewards(_gauges, _tokens, _nfpTokenIds);
    }

    /// @inheritdoc IVoter
    function claimIncentives(address owner, address[] calldata _feeDistributors, address[][] calldata _tokens)
        external
    {
        VoterRewardClaimers.claimIncentives(owner, _feeDistributors, _tokens);
    }

    /// @inheritdoc IVoter
    function claimLegacyIncentives(address owner, address[] calldata _feeDistributors, address[][] calldata _tokens)
        external
    {
        VoterRewardClaimers.claimLegacyIncentives(owner, _feeDistributors, _tokens);
    }

    /// @inheritdoc IVoter
    function claimRewards(address[] calldata _gauges, address[][] calldata _tokens) external {
        VoterRewardClaimers.claimRewards(_gauges, _tokens);
    }

    /// @inheritdoc IVoter
    function claimLegacyRewardsAndExit(address[] calldata _gauges, address[][] calldata _tokens) external {
        VoterRewardClaimers.claimLegacyRewardsAndExit(_gauges, _tokens);
    }

    /// @inheritdoc IVoter
    function claimClGaugeRewardsAndExit(
        address[] memory _gauges,
        address[][] memory _tokens,
        uint256[][] memory _nfpTokenIds
    ) external {
        VoterRewardClaimers.claimClGaugeRewardsAndExit(_gauges, _tokens, _nfpTokenIds);
    }

    //////////////////////////
    // Emission Calculation //
    //////////////////////////

    /// @inheritdoc IVoter
    function notifyRewardAmount(uint256 amount) external {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev gate to minter which prevents bricking distribution
        require(msg.sender == $.minter, Errors.NOT_AUTHORIZED(msg.sender));
        /// @dev transfer the tokens to the voter
        IERC20($.shadow).transferFrom(msg.sender, address(this), amount);
        /// @dev fetch the current period
        uint256 period = getPeriod();
        /// @dev add to the totalReward for the period
        $.totalRewardPerPeriod[period] += amount;
        /// @dev emit an event
        emit NotifyReward(msg.sender, $.shadow, amount);
    }

    ///////////////////////////
    // Emission Distribution //
    ///////////////////////////
    /// @inheritdoc IVoter
    function distribute(address _gauge) public nonReentrant {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev update the period if not already done
        IMinter($.minter).updatePeriod();
        /// @dev fetch the last distribution
        uint256 _lastDistro = $.lastDistro[_gauge];
        /// @dev fetch the current period
        uint256 currentPeriod = getPeriod();
        /// @dev fetch the pool address from the gauge
        address pool = $.poolForGauge[_gauge];
        /// @dev loop through _lastDistro + 1 up to and including the currentPeriod
        for (uint256 period = _lastDistro + 1; period <= currentPeriod; ++period) {
            /// @dev fetch the claimable amount
            uint256 claimable = _claimablePerPeriod(pool, period);
            /// @dev distribute for the period
            _distribute(_gauge, claimable, period);
        }
        /// @dev if the last distribution wasn't the current period
        if (_lastDistro != currentPeriod) {
            /// @dev check if a CL gauge
            if ($.isClGauge[_gauge]) {
                /// @dev set the feeProtocol to 100
                IShadowV3Factory($.clFactory).gaugeFeeSplitEnable(pool);
                address poolV3 = pool;
                /// @dev attempt period advancing
                IPoolUpdater($.poolUpdater).updatePool(pool);
                /// @dev collect fees by calling from the FeeCollector
                IFeeCollector(IShadowV3Factory($.clFactory).feeCollector()).collectProtocolFees(poolV3);
            }
            /// @dev if it's a legacy gauge, fees are handled as LP tokens and thus need to be treated diff
            else if ($.isLegacyGauge[_gauge]) {
                if ($.isAlive[_gauge] && $.voterOwnsLegacyFactory) {
                    /// @dev set the feeSplit to be 100% going to the feeDistributor
                    IPairFactory($.legacyFactory).setPairFeeSplit(pool, OLD_LEGACY_FEE_SPLIT_BASIS);
                }
                /// @dev mint the fees
                IPair(pool).mintFee();
                /// @dev notify the fees to the FeeDistributor
                IFeeRecipient(IFeeRecipientFactory($.feeRecipientFactory).feeRecipientForPair(pool)).notifyFees();
            }
            /// @dev no actions needed for custom gauge
        }
        /// @dev set the last distribution for the gauge as the currentPeriod
        $.lastDistro[_gauge] = currentPeriod;
    }

    /// @inheritdoc IVoter
    function distributeForPeriod(address _gauge, uint256 _period) public nonReentrant {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev attempt to update the period
        IMinter($.minter).updatePeriod();
        /// @dev fetch the pool address from the gauge
        address pool = $.poolForGauge[_gauge];
        /// @dev fetch the claimable amount for the period
        uint256 claimable = _claimablePerPeriod(pool, _period);

        /// @dev we dont update lastDistro here
        _distribute(_gauge, claimable, _period);
    }

    /// @inheritdoc IVoter
    function distributeAll() external {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev grab the length of all gauges in the set
        uint256 gaugesLength = $.gauges.length();
        /// @dev loop through and call distribute for every index
        for (uint256 i; i < gaugesLength; ++i) {
            distribute($.gauges.at(i));
        }
    }

    /// @inheritdoc IVoter
    function batchDistributeByIndex(uint256 startIndex, uint256 endIndex) external {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev grab the length of all gauges in the set
        uint256 gaugesLength = $.gauges.length();
        /// @dev if the end value is too high, set to end
        if (endIndex > gaugesLength) {
            endIndex = gaugesLength;
        }
        /// @dev loop through and distribute
        for (uint256 i = startIndex; i < endIndex; ++i) {
            distribute($.gauges.at(i));
        }
    }

    function updateLastDistro(address _gauge, uint256 period) external onlyGovernance {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        require(period <= getPeriod());
        $.lastDistro[_gauge] = period;
    }

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

    /// @inheritdoc IVoter
    function getAllPools() external view returns (address[] memory _pools) {
        _pools = VoterStorage.getStorage().pools.values();
    }

    /// @inheritdoc IVoter
    function getPoolsLength() external view returns (uint256) {
        return VoterStorage.getStorage().pools.length();
    }

    /// @inheritdoc IVoter
    function getPool(uint256 index) external view returns (address) {
        return VoterStorage.getStorage().pools.at(index);
    }

    /// @inheritdoc IVoter
    function getAllGauges() external view returns (address[] memory _gauges) {
        _gauges = VoterStorage.getStorage().gauges.values();
    }

    /// @inheritdoc IVoter
    function getGaugesLength() external view returns (uint256) {
        return VoterStorage.getStorage().gauges.length();
    }

    /// @inheritdoc IVoter
    function getGauge(uint256 index) external view returns (address) {
        return VoterStorage.getStorage().gauges.at(index);
    }

    /// @inheritdoc IVoter
    function getAllFeeDistributors() external view returns (address[] memory _feeDistributors) {
        return VoterStorage.getStorage().feeDistributors.values();
    }

    /// @inheritdoc IVoter
    function isGauge(address _gauge) external view returns (bool) {
        return VoterStorage.getStorage().gauges.contains(_gauge);
    }

    /// @inheritdoc IVoter
    function isFeeDistributor(address _feeDistributor) external view returns (bool) {
        return VoterStorage.getStorage().feeDistributors.contains(_feeDistributor);
    }

    /// @inheritdoc IVoter
    function tickSpacingsForPair(address tokenA, address tokenB) public view returns (int24[] memory) {
        (address token0, address token1) = _sortTokens(tokenA, tokenB);

        return VoterStorage.getStorage()._tickSpacingsForPair[token0][token1];
    }

    /// @inheritdoc IVoter
    function gaugeRedirect(address gauge) external view returns (address) {
        return VoterStorage.getStorage().gaugeRedirect[gauge];
    }

    /// @inheritdoc IVoter
    function gaugeForClPool(address tokenA, address tokenB, int24 tickSpacing) public view returns (address) {
        (address token0, address token1) = _sortTokens(tokenA, tokenB);

        return VoterStorage.getStorage()._gaugeForClPool[token0][token1][tickSpacing];
    }

    /// @dev shows how much is claimable per period
    function _claimablePerPeriod(address pool, uint256 period) internal view returns (uint256) {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        uint256 numerator = ($.totalRewardPerPeriod[period] * $.poolTotalVotesPerPeriod[pool][period]) * 1e18;

        /// @dev return 0 if this happens, or else there could be a divide by zero next
        return (numerator == 0 ? 0 : (numerator / $.totalVotesPerPeriod[period] / 1e18));
    }

    /// @dev sorts the two tokens
    function _sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
        token0 = tokenA < tokenB ? tokenA : tokenB;
        token1 = token0 == tokenA ? tokenB : tokenA;
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

// 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
// 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
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import {INonfungiblePositionManager} from "../CL/periphery/interfaces/INonfungiblePositionManager.sol";
import {IGauge} from "../interfaces/IGauge.sol";
import {IGaugeV3} from "../CL/gauge/interfaces/IGaugeV3.sol";
import {IVoteModule} from "../interfaces/IVoteModule.sol";
import {IFeeDistributor} from "../interfaces/IFeeDistributor.sol";
import {IXShadow} from "contracts/interfaces/IXShadow.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Errors} from "contracts/libraries/Errors.sol";
import {IPair} from "contracts/interfaces/IPair.sol";
import {IPairFactory} from "contracts/interfaces/IPairFactory.sol";
import {IRouter} from "contracts/interfaces/IRouter.sol";

import {VoterStorage} from "contracts/libraries/VoterStorage.sol";

/// @title VoterRewardClaimers
/// @notice Reward claimers logic for Voter
/// @dev Used to reduce Voter contract size by moving all reward claiming logic to a library
library VoterRewardClaimers {
    /// @dev function for claiming CL rewards with multiple ownership/access checks
    function claimClGaugeRewards(
        address[] calldata _gauges,
        address[][] calldata _tokens,
        uint256[][] calldata _nfpTokenIds
    ) external {
        INonfungiblePositionManager nfpManagerContract =
            INonfungiblePositionManager(VoterStorage.getStorage().nfpManager);
        for (uint256 i; i < _gauges.length; ++i) {
            for (uint256 j; j < _nfpTokenIds[i].length; ++j) {
                require(
                    msg.sender == nfpManagerContract.ownerOf(_nfpTokenIds[i][j])
                        || msg.sender == nfpManagerContract.getApproved(_nfpTokenIds[i][j])
                        || nfpManagerContract.isApprovedForAll(nfpManagerContract.ownerOf(_nfpTokenIds[i][j]), msg.sender),
                    Errors.NOT_AUTHORIZED(msg.sender)
                );

                IGaugeV3(_gauges[i]).getRewardForOwner(_nfpTokenIds[i][j], _tokens[i]);
            }
        }
    }

    function claimClGaugeRewardsAndExit(
        address[] memory _gauges,
        address[][] memory _tokens,
        uint256[][] memory _nfpTokenIds
    ) external {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();
        INonfungiblePositionManager nfpManagerContract = INonfungiblePositionManager($.nfpManager);

        /// @dev loop claim from all nfpIds
        for (uint256 i = 0; i < _gauges.length; i++) {
            for (uint256 j; j < _nfpTokenIds[i].length; ++j) {
                address owner = nfpManagerContract.ownerOf(_nfpTokenIds[i][j]);
                require(
                    msg.sender == owner || msg.sender == nfpManagerContract.getApproved(_nfpTokenIds[i][j])
                        || nfpManagerContract.isApprovedForAll(nfpManagerContract.ownerOf(_nfpTokenIds[i][j]), msg.sender),
                    Errors.NOT_AUTHORIZED(msg.sender)
                );

                uint256 xShadowBalanceBefore = IXShadow($.xShadow).balanceOf(address(this));

                /// @dev claim xShadow to this address
                IGaugeV3(_gauges[i]).getXShadowRewardForOwner(_nfpTokenIds[i][j]);
                /// @dev claim all other rewards (sent directly to the caller)
                IGaugeV3(_gauges[i]).getRewardForOwner(_nfpTokenIds[i][j], _tokens[i]);

                /// @dev exit and send xShadow in each loop, since the NFPs' owners can be different
                uint256 xShadowBalanceAfter = IXShadow($.xShadow).balanceOf(address(this));
                uint256 diff = xShadowBalanceAfter - xShadowBalanceBefore;

                /// @dev fetch only the difference (in case contract already had xshadow balance)
                /// @dev exit and transfer underlying to the NFP's owner
                if (diff > 0) {
                    IERC20($.shadow).transfer(owner, IXShadow($.xShadow).exit(diff));
                }
            }
        }
    }

    /// @dev claims voting incentives batched
    function claimIncentives(address owner, address[] calldata _feeDistributors, address[][] calldata _tokens)
        external
    {
        /// @dev restrict to authorized callers/admins
        require(
            IVoteModule(VoterStorage.getStorage().voteModule).isAdminFor(msg.sender, owner),
            Errors.NOT_AUTHORIZED(msg.sender)
        );

        for (uint256 i; i < _feeDistributors.length; ++i) {
            IFeeDistributor(_feeDistributors[i]).getRewardForOwner(owner, _tokens[i]);
        }
    }

    /// @dev for claiming a batch of legacy gauge rewards
    function claimRewards(address[] calldata _gauges, address[][] calldata _tokens) external {
        for (uint256 i; i < _gauges.length; ++i) {
            IGauge(_gauges[i]).getReward(msg.sender, _tokens[i]);
        }
    }

    /// @dev for users to exit legacy rewarded xshadow into shadow directly
    function claimLegacyRewardsAndExit(address[] calldata _gauges, address[][] calldata _tokens) external {
        for (uint256 i; i < _gauges.length; ++i) {
            IGauge(_gauges[i]).getRewardAndExit(msg.sender, _tokens[i]);
        }
    }

    /// @dev claim CL and legacy gauge rewards together
    function batchGetRewards(address[] calldata _gauges, address[][] calldata _tokens, uint256[][] calldata _nfpId)
        external
    {
        require(_gauges.length == _tokens.length && _gauges.length == _nfpId.length, "Invalid array length");

        INonfungiblePositionManager nfpManagerContract =
            INonfungiblePositionManager(VoterStorage.getStorage().nfpManager);

        for (uint256 i; i < _gauges.length; ++i) {
            /// @dev If no NFP IDs for this gauge, it's a legacy gauge
            if (_nfpId[i].length == 0) {
                IGauge(_gauges[i]).getReward(msg.sender, _tokens[i]);
            } else {
                /// @dev This is a v3 gauge - check ownership and claim for each NFP
                for (uint256 j; j < _nfpId[i].length; ++j) {
                    uint256 tokenId = _nfpId[i][j];
                    address tokenOwner = nfpManagerContract.ownerOf(tokenId);

                    require(
                        msg.sender == tokenOwner || msg.sender == nfpManagerContract.getApproved(tokenId)
                            || nfpManagerContract.isApprovedForAll(tokenOwner, msg.sender),
                        Errors.NOT_AUTHORIZED(msg.sender)
                    );

                    IGaugeV3(_gauges[i]).getRewardForOwner(tokenId, _tokens[i]);
                }
            }
        }
    }

    /// @notice try to unwrap LP token to token0/1
    /// @param pair LP token address
    /// @return isLP bool if its a LP token
    /// @return tokenA token0 address
    /// @return tokenB token1 address
    function _tryUnwrapLP(address legacyFactory, address pair)
        internal
        returns (bool isLP, address tokenA, address tokenB)
    {
        /// @dev early return with false, address(0), address(0) if it's not a pair
        /// only pairs with gauges/feeDists will have incentives so we only need to check VoterStorage
        /// and not legacyFactory
        if (!IPairFactory(legacyFactory).isPair(pair)) {
            return (false, address(0), address(0));
        }

        address token0 = IPair(pair).token0();
        address token1 = IPair(pair).token1();
        uint256 lpBalance = IERC20(pair).balanceOf(address(this));

        if (lpBalance > 0) {
            /// @dev transfering to the contract address and burn to remove liquidity
            IERC20(pair).transfer(pair, lpBalance);
            /// @dev putting msg.sender as the input for burn() automatically sends to tokens to the msg.sender
            IPair(pair).burn(msg.sender);

            return (true, token0, token1);
        }
    }

    /// @notice claim legacy incentives and unwrap LP token to token0/1
    /// @param _feeDistributors fee distributor addresses
    /// @param _rewardTokens reward token addresses
    function claimLegacyIncentives(address owner, address[] memory _feeDistributors, address[][] memory _rewardTokens)
        public
    {
        address legacyFactory = VoterStorage.getStorage().legacyFactory;

        /// @dev restrict to authorized callers/admins
        require(
            IVoteModule(VoterStorage.getStorage().voteModule).isAdminFor(msg.sender, owner),
            Errors.NOT_AUTHORIZED(msg.sender)
        );

        for (uint256 i = 0; i < _feeDistributors.length; i++) {
            // claim all tokens for this distributor
            IFeeDistributor(_feeDistributors[i]).getRewardForOwnerTo(owner, _rewardTokens[i], address(this));
            // process each reward token
            for (uint256 j = 0; j < _rewardTokens[i].length; j++) {
                address rewardToken = _rewardTokens[i][j];
                // try to unwrap if it's a LP token
                (bool isLP, address tokenA, address tokenB) = _tryUnwrapLP(legacyFactory, rewardToken);
                if (isLP) {
                    // transfer unwrapped tokens to caller
                    uint256 balanceA = IERC20(tokenA).balanceOf(address(this));
                    uint256 balanceB = IERC20(tokenB).balanceOf(address(this));

                    if (balanceA > 0) IERC20(tokenA).transfer(owner, balanceA);
                    if (balanceB > 0) IERC20(tokenB).transfer(owner, balanceB);
                } else {
                    // transfer regular token to caller
                    uint256 balance = IERC20(rewardToken).balanceOf(address(this));
                    if (balance > 0) IERC20(rewardToken).transfer(owner, balance);
                }
            }
        }
    }
}

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

interface IGaugeV3 {
    /// @notice Emitted when the NFP Manager is changed
    /// @param newNfpManager The address of the new NFP Manager
    /// @param oldNfpManager The address of the old NFP Manager
    event NfpManagerChanged(address indexed newNfpManager, address indexed oldNfpManager);

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

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

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

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

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

    /// @notice Returns the NFP Manager
    function nfpManager() external view returns (address);

    /// @notice updates pool data after period flip
    function updatePool() external;

    /// @notice Syncs NFP Manager from the voter
    function syncNfpManager() external;

    /// @notice returns an array of all nfpManagers in this gauge
    function getNfpManagers() external view returns (address[] memory);

    /// @notice returns the pool of this gauge
    function pool() external view returns (address);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

interface IMarbleMinter is IMinter {
    /// @notice migrate gauges for Marble Zone Migration
    function migration(address[] calldata gauges) external;

    /// @notice sets up fee redirection for new legacy gauges
    function postCreateLegacyGaugeHook(address pool) external;

    /// @notice redirects legacy pair fees to new feeRecipients
    function redirectFees(uint256 start, uint256 batchSize) external;

    /// @notice allows governance to rescue tokens (pair fees without gauges)
    function rescueTokens(address token, uint256 amount) external;

    /// @notice allows governance to change Access Hub
    function setAccessHub(address _accessHub) external;

    /// @notice allows governance to change Operator
    function setOperator(address _operator) external;
}

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

interface IMinter {
    event SetVeDist(address _value);
    event SetVoter(address _value);
    event Mint(address indexed sender, uint256 weekly);
    event RebaseUnsuccessful(uint256 _current, uint256 _currentPeriod);
    event EmissionsMultiplierUpdated(uint256 _emissionsMultiplier);

    /// @notice decay or inflation scaled to 1_000_000 = 100%
    /// @return _multiplier the emissions multiplier
    function emissionsMultiplier() external view returns (uint256 _multiplier);

    /// @notice unix timestamp of current epoch's start
    /// @return _activePeriod the active period
    function activePeriod() external view returns (uint256 _activePeriod);

    /// @notice update the epoch (period) -- callable once a week at >= Thursday 0 UTC
    /// @return period the new period
    function updatePeriod() external returns (uint256 period);

    /// @notice start emissions for epoch 0
    function startEmissions() external;

    /// @notice updates the decay or inflation scaled to 1_000_000 = 100%
    /// @param _emissionsMultiplier multiplier for emissions each week
    function updateEmissionsMultiplier(uint256 _emissionsMultiplier) external;

    /// @notice calculates the emissions to be sent to the voter
    /// @return _weeklyEmissions the amount of emissions for the week
    function calculateWeeklyEmissions() external view returns (uint256 _weeklyEmissions);

    /// @notice kicks off the initial minting and variable declarations
    function kickoff(
        address _shadow,
        address _voter,
        uint256 _initialWeeklyEmissions,
        uint256 _initialMultiplier,
        address _xShadow
    ) external;

    /// @notice returns (block.timestamp / 1 week) for gauge use
    /// @return period period number
    function getPeriod() external view returns (uint256 period);

    /// @notice returns the numerical value of the current epoch
    /// @return _epoch epoch number
    function getEpoch() external view returns (uint256 _epoch);

    /// @notice emissions value
    function weeklyEmissions() external view returns (uint256);

    /// @notice unix timestamp of the first period
    function firstPeriod() external view returns (uint256);

    /// @notice the last period the emissions multiplier was updated
    function lastMultiplierUpdate() external view returns (uint256);

    /// @notice current operator
    function operator() external view returns (address);

    /// @notice the access control center
    function accessHub() external view returns (address);

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

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

    /// @notice the IERC20 version of shadow
    function shadow() external view returns (address);
}

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

interface IPair {
    event Mint(address indexed sender, uint256 amount0, uint256 amount1);
    event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
    event Swap(
        address indexed sender,
        uint256 amount0In,
        uint256 amount1In,
        uint256 amount0Out,
        uint256 amount1Out,
        address indexed to
    );
    event Sync(uint112 reserve0, uint112 reserve1);

    /// @notice initialize the pool, called only once programatically
    function initialize(address _token0, address _token1, bool _stable) external;

    /// @notice calculate the current reserves of the pool and their last 'seen' timestamp
    /// @return _reserve0 amount of token0 in reserves
    /// @return _reserve1 amount of token1 in reserves
    /// @return _blockTimestampLast the timestamp when the pool was last updated
    function getReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast);

    /// @notice mint the pair tokens (LPs)
    /// @param to where to mint the LP tokens to
    /// @return liquidity amount of LP tokens to mint
    function mint(address to) external returns (uint256 liquidity);

    /// @notice burn the pair tokens (LPs)
    /// @param to where to send the underlying
    /// @return amount0 amount of amount0
    /// @return amount1 amount of amount1
    function burn(address to) external returns (uint256 amount0, uint256 amount1);

    /// @notice direct swap through the pool
    function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;

    /// @notice force balances to match reserves, can be used to harvest rebases from rebasing tokens or other external factors
    /// @param to where to send the excess tokens to
    function skim(address to) external;

    /// @notice force reserves to match balances, prevents skim excess if skim is enabled
    function sync() external;

    /// @notice set the pair fees contract address
    function setFeeRecipient(address _pairFees) external;

    /// @notice set the feesplit variable
    function setFeeSplit(uint256 _feeSplit) external;

    /// @notice sets the swap fee of the pair
    /// @dev scaled to a max of 50% (500_000/1_000_000)
    /// @param _fee the fee
    function setFee(uint256 _fee) external;

    /// @notice 'mint' the fees as LP tokens
    /// @dev this is used for protocol/voter fees
    function mintFee() external;

    /// @notice calculates the amount of tokens to receive post swap
    /// @param amountIn the token amount
    /// @param tokenIn the address of the token
    function getAmountOut(uint256 amountIn, address tokenIn) external view returns (uint256 amountOut);

    /// @notice returns various metadata about the pair
    function metadata()
        external
        view
        returns (
            uint256 _decimals0,
            uint256 _decimals1,
            uint256 _reserve0,
            uint256 _reserve1,
            bool _stable,
            address _token0,
            address _token1
        );

    /// @notice returns the feeSplit of the pair
    function feeSplit() external view returns (uint256);

    /// @notice returns the fee of the pair
    function fee() external view returns (uint256);

    /// @notice returns the feeRecipient of the pair
    function feeRecipient() external view returns (address);

    /// @notice returns the token0 of the pair
    function token0() external view returns (address);

    /// @notice returns the token1 of the pair
    function token1() external view returns (address);

    /// @notice returns if pair is stable
    function stable() external view returns (bool);

    /// @notice returns kLast
    function kLast() external view returns (uint256);
}

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

interface IPairFactory {
    event PairCreated(address indexed token0, address indexed token1, address pair, uint256);

    event SetFee(uint256 indexed fee);

    event SetPairFee(address indexed pair, uint256 indexed fee);

    event SetFeeSplit(uint256 indexed _feeSplit);

    event SetPairFeeSplit(address indexed pair, uint256 indexed _feeSplit);

    event SkimStatus(address indexed _pair, bool indexed _status);

    event NewTreasury(address indexed _caller, address indexed _newTreasury);

    event FeeSplitWhenNoGauge(address indexed _caller, bool indexed _status);

    event SetFeeRecipient(address indexed pair, address indexed feeRecipient);

    /// @notice returns the total length of legacy pairs
    /// @return _length the length
    function allPairsLength() external view returns (uint256 _length);

    /// @notice calculates if the address is a legacy pair
    /// @param pair the address to check
    /// @return _boolean the bool return
    function isPair(address pair) external view returns (bool _boolean);

    /// @notice calculates the pairCodeHash
    /// @return _hash the pair code hash
    function pairCodeHash() external view returns (bytes32 _hash);

    /// @param tokenA address of tokenA
    /// @param tokenB address of tokenB
    /// @param stable whether it uses the stable curve
    /// @return _pair the address of the pair
    function getPair(address tokenA, address tokenB, bool stable) external view returns (address _pair);

    /// @notice creates a new legacy pair
    /// @param tokenA address of tokenA
    /// @param tokenB address of tokenB
    /// @param stable whether it uses the stable curve
    /// @return pair the address of the created pair
    function createPair(address tokenA, address tokenB, bool stable) external returns (address pair);

    /// @notice the address of the voter
    /// @return _voter the address of the voter
    function voter() external view returns (address _voter);

    /// @notice returns the address of a pair based on the index
    /// @param _index the index to check for a pair
    /// @return _pair the address of the pair at the index
    function allPairs(uint256 _index) external view returns (address _pair);

    /// @notice the swap fee of a pair
    /// @param _pair the address of the pair
    /// @return _fee the fee
    function pairFee(address _pair) external view returns (uint256 _fee);

    /// @notice the split of fees
    /// @return _split the feeSplit
    function feeSplit() external view returns (uint256 _split);

    /// @notice sets the swap fee for a pair
    /// @param _pair the address of the pair
    /// @param _fee the fee for the pair
    function setPairFee(address _pair, uint256 _fee) external;

    /// @notice set the swap fees of the pair
    /// @param _fee the fee, scaled to MAX 500_000 = 50%
    function setFee(uint256 _fee) external;

    /// @notice the address for the treasury
    /// @return _treasury address of the treasury
    function treasury() external view returns (address _treasury);

    /// @notice sets the pairFees contract
    /// @param _pair the address of the pair
    /// @param _pairFees the address of the new Pair Fees
    function setFeeRecipient(address _pair, address _pairFees) external;

    /// @notice sets the feeSplit for a pair
    /// @param _pair the address of the pair
    /// @param _feeSplit the feeSplit
    function setPairFeeSplit(address _pair, uint256 _feeSplit) external;

    /// @notice whether there is feeSplit when there's no gauge
    /// @return _boolean whether there is a feesplit when no gauge
    function feeSplitWhenNoGauge() external view returns (bool _boolean);

    /// @notice whether a pair can be skimmed
    /// @param _pair the pair address
    /// @return _boolean whether skim is enabled
    function skimEnabled(address _pair) external view returns (bool _boolean);

    /// @notice set whether skim is enabled for a specific pair
    function setSkimEnabled(address _pair, bool _status) external;

    /// @notice sets a new treasury address
    /// @param _treasury the new treasury address
    function setTreasury(address _treasury) external;

    /// @notice set whether there should be a feesplit without gauges
    /// @param status whether enabled or not
    function setFeeSplitWhenNoGauge(bool status) external;

    /// @notice sets the feesSplit globally
    /// @param _feeSplit the fee split
    function setFeeSplit(uint256 _feeSplit) external;
}

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

interface IFeeRecipient {
    function initialize(address _feeDistributor) external;
    function notifyFees() external;
}

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

interface IFeeRecipientFactory {
    /// @notice the pair fees for a specific pair
    /// @param pair the pair to check
    /// @return feeRecipient the feeRecipient contract address for the pair
    function feeRecipientForPair(address pair) external view returns (address feeRecipient);

    /// @notice the last feeRecipient address created
    /// @return _feeRecipient the address of the last pair fees contract
    function lastFeeRecipient() external view returns (address _feeRecipient);
    /// @notice create the pair fees for a pair
    /// @param pair the address of the pair
    /// @return _feeRecipient the address of the newly created feeRecipient
    function createFeeRecipient(address pair) external returns (address _feeRecipient);

    /// @notice the fee % going to the treasury
    /// @return _feeToTreasury the fee %
    function feeToTreasury() external view returns (uint256 _feeToTreasury);

    /// @notice get the treasury address
    /// @return _treasury address of the treasury
    function treasury() external view returns (address _treasury);

    /// @notice set the fee % to be sent to the treasury
    /// @param _feeToTreasury the fee % to be sent to the treasury
    function setFeeToTreasury(uint256 _feeToTreasury) external;

    /// @notice set a new treasury address
    /// @param _treasury the new address
    function setTreasury(address _treasury) external;
}

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

/// @title The interface for the Shadow V3 Factory
/// @notice The Shadow V3 Factory facilitates creation of Shadow V3 pools and control over the protocol fees
interface IShadowV3Factory {
    /// @notice Emitted when a pool is created
    /// @param token0 The first token of the pool by address sort order
    /// @param token1 The second token of the pool by address sort order
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks
    /// @param pool The address of the created pool
    event PoolCreated(
        address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool
    );

    /// @notice Emitted when a new tickspacing amount is enabled for pool creation via the factory
    /// @dev unlike UniswapV3, we map via the tickSpacing rather than the fee tier
    /// @param tickSpacing The minimum number of ticks between initialized ticks
    /// @param fee The fee, denominated in hundredths of a bip
    event TickSpacingEnabled(int24 indexed tickSpacing, uint24 indexed fee);

    /// @notice Emitted when the protocol fee is changed
    /// @param feeProtocolOld The previous value of the protocol fee
    /// @param feeProtocolNew The updated value of the protocol fee
    event SetFeeProtocol(uint24 feeProtocolOld, uint24 feeProtocolNew);

    /// @notice Emitted when the protocol fee is changed
    /// @param pool The pool address
    /// @param feeProtocolOld The previous value of the protocol fee
    /// @param feeProtocolNew The updated value of the protocol fee
    event SetPoolFeeProtocol(address pool, uint24 feeProtocolOld, uint24 feeProtocolNew);

    /// @notice Emitted when a pool's fee is changed
    /// @param pool The pool address
    /// @param newFee The updated value of the protocol fee
    event FeeAdjustment(address pool, uint24 newFee);

    /// @notice Emitted when the fee collector is changed
    /// @param oldFeeCollector The previous implementation
    /// @param newFeeCollector The new implementation
    event FeeCollectorChanged(address indexed oldFeeCollector, address indexed newFeeCollector);

    /// @notice Returns the PoolDeployer address
    /// @return The address of the PoolDeployer contract
    function shadowV3PoolDeployer() external returns (address);

    /// @notice Returns the fee amount for a given tickSpacing, if enabled, or 0 if not enabled
    /// @dev A tickSpacing can never be removed, so this value should be hard coded or cached in the calling context
    /// @dev unlike UniswapV3, we map via the tickSpacing rather than the fee tier
    /// @param tickSpacing The enabled tickSpacing. Returns 0 in case of unenabled tickSpacing
    /// @return initialFee The initial fee
    function tickSpacingInitialFee(int24 tickSpacing) external view returns (uint24 initialFee);

    /// @notice Returns the pool address for a given pair of tokens and a tickSpacing, or address 0 if it does not exist
    /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
    /// @dev unlike UniswapV3, we map via the tickSpacing rather than the fee tier
    /// @param tokenA The contract address of either token0 or token1
    /// @param tokenB The contract address of the other token
    /// @param tickSpacing The tickSpacing of the pool
    /// @return pool The pool address
    function getPool(address tokenA, address tokenB, int24 tickSpacing) external view returns (address pool);

    /// @notice Creates a pool for the given two tokens and fee
    /// @dev unlike UniswapV3, we map via the tickSpacing rather than the fee tier
    /// @param tokenA One of the two tokens in the desired pool
    /// @param tokenB The other of the two tokens in the desired pool
    /// @param tickSpacing The desired tickSpacing for the pool
    /// @param sqrtPriceX96 initial sqrtPriceX96 of the pool
    /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0.
    /// @dev The call will revert if the pool already exists, the tickSpacing is invalid, or the token arguments are invalid.
    /// @return pool The address of the newly created pool
    function createPool(address tokenA, address tokenB, int24 tickSpacing, uint160 sqrtPriceX96)
        external
        returns (address pool);

    /// @notice Enables a tickSpacing with the given initialFee amount
    /// @dev unlike UniswapV3, we map via the tickSpacing rather than the fee tier
    /// @dev tickSpacings may never be removed once enabled
    /// @param tickSpacing The spacing between ticks to be enforced for all pools created
    /// @param initialFee The initial fee amount, denominated in hundredths of a bip (i.e. 1e-6)
    function enableTickSpacing(int24 tickSpacing, uint24 initialFee) external;

    /// @notice Returns the default protocol fee value
    /// @return _feeProtocol The default protocol fee percentage
    function feeProtocol() external view returns (uint24 _feeProtocol);

    /// @notice Returns the protocol fee percentage for a specific pool
    /// @dev If the fee is 0 or the pool is uninitialized, returns the Factory's default feeProtocol
    /// @param pool The address of the pool
    /// @return _feeProtocol The protocol fee percentage for the specified pool
    function poolFeeProtocol(address pool) external view returns (uint24 _feeProtocol);

    /// @notice Sets the default protocol fee percentage
    /// @param _feeProtocol New default protocol fee percentage for token0 and token1
    function setFeeProtocol(uint24 _feeProtocol) external;

    /// @notice Retrieves the parameters used in constructing a pool
    /// @dev Called by the pool constructor to fetch the pool's parameters
    /// @return factory The factory address
    /// @return token0 The first token of the pool by address sort order
    /// @return token1 The second token of the pool by address sort order
    /// @return fee The initialized fee tier of the pool, denominated in hundredths of a bip
    /// @return tickSpacing The minimum number of ticks between initialized ticks
    function parameters()
        external
        view
        returns (address factory, address token0, address token1, uint24 fee, int24 tickSpacing);

    /// @notice Updates the fee collector address
    /// @param _feeCollector The new fee collector address
    function setFeeCollector(address _feeCollector) external;

    /// @notice Updates the swap fee for a specific pool
    /// @param _pool The address of the pool to modify
    /// @param _fee The new fee value, scaled where 1_000_000 = 100%
    function setFee(address _pool, uint24 _fee) external;

    /// @notice Returns the current fee collector address
    /// @dev The fee collector contract determines the distribution of protocol fees
    /// @return The address of the fee collector contract
    function feeCollector() external view returns (address);

    /// @notice Flag for getting a pool to use the default feeProcotol
    /// @dev type(uint24).max denotes using default feeProcotol
    function DEFAULT_FEE_FLAG() external view returns (uint24);

    /// @notice Updates the protocol fee percentage for a specific pool
    /// @dev type(uint24).max denotes using default feeProcotol
    /// @param pool The address of the pool to modify
    /// @param _feeProtocol The new protocol fee percentage to assign
    function setPoolFeeProtocol(address pool, uint24 _feeProtocol) external;

    /// @notice Enables fee protocol splitting upon gauge creation
    /// @param pool The address of the pool to enable fee splitting for
    function gaugeFeeSplitEnable(address pool) external;

    /// @notice Updates the voter contract address
    /// @param _voter The new voter contract address
    function setVoter(address _voter) external;

    /// @notice Checks if a given address is a V3 pool
    /// @param _pool The address to check
    /// @return isV3 True if the address is a V3 pool, false otherwise
    function isPairV3(address _pool) external view returns (bool isV3);

    /// @notice Initializes the factory with a pool deployer
    /// @param poolDeployer The address of the pool deployer contract
    function initialize(address poolDeployer) 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.8.0;

/// @title The interface for the CL gauge Factory
/// @notice Deploys CL gauges
interface IClGaugeFactory {
    /// @dev Emitted when the implementation returned by the beacon is changed.
    event Upgraded(address indexed implementation);

    /// @notice Emitted when a gauge is created
    /// @param pool The address of the pool
    /// @param pool The address of the created gauge
    event GaugeCreated(address indexed pool, address gauge);

    /// @notice Emitted when the NFP Manager is changed
    /// @param newNfpManager The address of the new NFP Manager
    /// @param oldNfpManager The address of the old NFP Manager
    event NfpManagerChanged(address indexed newNfpManager, address indexed oldNfpManager);

    /// @notice Emitted when the Fee Collector is changed
    /// @param newFeeCollector The address of the new NFP Manager
    /// @param oldFeeCollector The address of the old NFP Manager
    event FeeCollectorChanged(address indexed newFeeCollector, address indexed oldFeeCollector);

    /// @notice Emitted when the Voter is changed
    /// @param newVoter The address of the new NFP Manager
    /// @param oldVoter The address of the old NFP Manager
    event VoterChanged(address indexed newVoter, address indexed oldVoter);

    /// @notice Returns the NFP Manager address
    function nfpManager() external view returns (address);

    /// @notice Set new NFP Manager
    function setNfpManager(address _nfpManager) external;

    /// @notice Returns Voter
    function voter() external view returns (address);

    /// @notice Returns the gauge address for a given pool, or address 0 if it does not exist
    /// @param pool The pool address
    /// @return gauge The gauge address
    function getGauge(address pool) external view returns (address gauge);

    /// @notice Returns the address of the fee collector contract
    /// @dev Fee collector decides where the protocol fees go (fee distributor, treasury, etc.)
    function feeCollector() external view returns (address);

    /// @notice Creates a gauge for the given pool
    /// @param pool One of the desired gauge
    /// @return gauge The address of the newly created gauge
    function createGauge(address pool) external returns (address gauge);
}

// 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: GPL-2.0-or-later
pragma solidity ^0.8.0;

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

interface IFeeCollector {
    /// @notice Emitted when the treasury address is changed.
    /// @param oldTreasury The previous treasury address.
    /// @param newTreasury The new treasury address.
    event TreasuryChanged(address oldTreasury, address newTreasury);

    /// @notice Emitted when the treasury fees value is changed.
    /// @param oldTreasuryFees The previous value of the treasury fees.
    /// @param newTreasuryFees The new value of the treasury fees.
    event TreasuryFeesChanged(uint256 oldTreasuryFees, uint256 newTreasuryFees);

    /// @notice Emitted when protocol fees are collected from a pool and distributed to the fee distributor and treasury.
    /// @param pool The address of the pool from which the fees were collected.
    /// @param feeDistAmount0 The amount of fee tokens (token 0) distributed to the fee distributor.
    /// @param feeDistAmount1 The amount of fee tokens (token 1) distributed to the fee distributor.
    /// @param treasuryAmount0 The amount of fee tokens (token 0) allocated to the treasury.
    /// @param treasuryAmount1 The amount of fee tokens (token 1) allocated to the treasury.
    event FeesCollected(
        address pool, uint256 feeDistAmount0, uint256 feeDistAmount1, uint256 treasuryAmount0, uint256 treasuryAmount1
    );

    /// @notice Returns the treasury address.
    function treasury() external returns (address);

    /// @notice Returns the treasury fees ratio.
    function treasuryFees() external returns (uint256);

    /// @notice Sets the treasury address to a new value.
    /// @param newTreasury The new address to set as the treasury.
    function setTreasury(address newTreasury) external;

    /// @notice Sets the value of treasury fees to a new amount.
    /// @param _treasuryFees The new amount of treasury fees to be set.
    function setTreasuryFees(uint256 _treasuryFees) external;

    /// @notice Collects protocol fees from a specified pool and distributes them to the fee distributor and treasury.
    /// @param pool The pool from which to collect the protocol fees.
    function collectProtocolFees(address pool) external;
}

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

interface IVoteModule {
    /**
     * Events
     */
    event Deposit(address indexed from, uint256 amount);

    event Withdraw(address indexed from, uint256 amount);

    event NotifyReward(address indexed from, uint256 amount);

    event ClaimRewards(address indexed from, uint256 amount);

    event ExemptedFromCooldown(address indexed candidate, bool status);

    event NewDuration(uint256 oldDuration, uint256 newDuration);

    event NewCooldown(uint256 oldCooldown, uint256 newCooldown);

    event Delegate(address indexed delegator, address indexed delegatee, bool indexed isAdded);

    event SetAdmin(address indexed owner, address indexed operator, bool indexed isAdded);

    /**
     * Functions
     */
    function delegates(address) external view returns (address);
    /// @notice mapping for admins for a specific address
    /// @param owner the owner to check against
    /// @return operator the address that is designated as an admin/operator
    function admins(address owner) external view returns (address operator);

    function accessHub() external view returns (address);

    /// @notice reward supply for a period
    function rewardSupply(uint256 period) external view returns (uint256);

    /// @notice user claimed reward amount for a period
    /// @dev same mapping order as FeeDistributor so the name is a bit odd
    function userClaimed(uint256 period, address owner) external view returns (uint256);

    /// @notice last claimed period for a user
    function userLastClaimPeriod(address owner) external view returns (uint256);

    /// @notice returns the current period
    function getPeriod() external view returns (uint256);

    /// @notice returns the amount of unclaimed rebase earned by the user
    function earned(address account) external view returns (uint256 _reward);

    /// @notice returns the amount of unclaimed rebase earned by the user for a period
    function periodEarned(uint256 period, address user) external view returns (uint256 amount);

    /// @notice the time which users can deposit and withdraw
    function unlockTime() external view returns (uint256 _timestamp);

    /// @notice claims pending rebase rewards
    function getReward() external;

    /// @notice claims pending rebase rewards for a period
    function getPeriodReward(uint256 period) external;

    /// @notice allows users to set their own last claimed period in case they haven't claimed in a while
    /// @param period the new period to start loops from
    function setUserLastClaimPeriod(uint256 period) external;

    /// @notice deposits all xShadow in the caller's wallet
    function depositAll() external;

    /// @notice deposit a specified amount of xShadow
    function deposit(uint256 amount) external;

    /// @notice withdraw all xShadow
    function withdrawAll() external;

    /// @notice withdraw a specified amount of xShadow
    function withdraw(uint256 amount) external;

    /// @notice check for admin perms
    /// @param operator the address to check
    /// @param owner the owner to check against for permissions
    function isAdminFor(address operator, address owner) external view returns (bool approved);

    /// @notice check for delegations
    /// @param delegate the address to check
    /// @param owner the owner to check against for permissions
    function isDelegateFor(address delegate, address owner) external view returns (bool approved);

    /// @notice used by the xShadow contract to notify pending rebases
    /// @param amount the amount of Shadow to be notified from exit penalties
    function notifyRewardAmount(uint256 amount) external;

    /// @notice the address of the xShadow token (staking/voting token)
    /// @return _xShadow the address
    function xShadow() external view returns (address _xShadow);

    /// @notice address of the voter contract
    /// @return _voter the voter contract address
    function voter() external view returns (address _voter);

    /// @notice returns the total voting power (equal to total supply in the VoteModule)
    /// @return _totalSupply the total voting power
    function totalSupply() external view returns (uint256 _totalSupply);

    /// @notice voting power
    /// @param user the address to check
    /// @return amount the staked balance
    function balanceOf(address user) external view returns (uint256 amount);

    /// @notice delegate voting perms to another address
    /// @param delegatee who you delegate to
    /// @dev set address(0) to revoke
    function delegate(address delegatee) external;

    /// @notice give admin permissions to a another address
    /// @param operator the address to give administrative perms to
    /// @dev set address(0) to revoke
    function setAdmin(address operator) external;

    function cooldownExempt(address) external view returns (bool);

    function setCooldownExemption(address, bool) external;

    /// @notice lock period after rebase starts accruing
    function cooldown() external returns (uint256);

    function setNewCooldown(uint256) external;
}

// 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: 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: BUSL-1.1
pragma solidity ^0.8.0;

import {IVoter} from "../interfaces/IVoter.sol";
import {IVoteModule} from "../interfaces/IVoteModule.sol";

interface IFeeDistributor {
    event Deposit(address owner, uint256 amount);

    event Withdraw(address owner, uint256 amount);

    event NotifyReward(address indexed from, address indexed reward, uint256 amount, uint256 period);

    event VotesIncentivized(address indexed from, address indexed reward, uint256 amount, uint256 period);

    event ClaimRewards(uint256 period, address owner, address receiver, address reward, uint256 amount);

    event RewardsRedirected(address indexed destination, address indexed _reward, uint256 _amount);

    event RewardsRemoved(address _reward);

    /// @notice the address of the voter contract
    function voter() external view returns (IVoter);
    /// @notice the address of the voting module
    function voteModule() external view returns (IVoteModule);
    /// @notice the address of the feeRecipient contract
    function feeRecipient() external view returns (address);

    /// @notice the first period (epoch) that this contract was deployed
    function firstPeriod() external view returns (uint256);

    /// @notice balance of the voting power for a user
    /// @param owner the owner
    /// @return amount the amount of voting share
    function balanceOf(address owner) external view returns (uint256 amount);

    /// @notice total cumulative amount of voting power per epoch
    /// @param period the period to check
    /// @return weight the amount of total voting power
    function votes(uint256 period) external view returns (uint256 weight);

    /// @notice "internal" function gated to voter to add votes
    /// @dev internal notation inherited from original solidly, kept for continuity
    function _deposit(uint256 amount, address owner) external;
    /// @notice "internal" function gated to voter to remove votes
    /// @dev internal notation inherited from original solidly, kept for continuity
    function _withdraw(uint256 amount, address owner) external;

    /// @notice function to claim rewards on behalf of another
    /// @param owner owner's address
    /// @param tokens an array of the tokens
    function getRewardForOwner(address owner, address[] memory tokens) external;

    /// @notice function to claim rewards on behalf of another
    /// @param owner owner's address
    /// @param tokens an array of the tokens
    /// @param destination destination of the rewards
    function getRewardForOwnerTo(address owner, address[] memory tokens, address destination) external;

    /// @notice function for sending fees directly to be claimable (in system where fees are distro'd through the week)
    /// @dev for lumpsum - this would operate similarly to incentivize
    /// @param token the address of the token to send for notifying
    /// @param amount the amount of token to send
    function notifyRewardAmount(address token, uint256 amount) external;

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

    /// @notice shows the earned incentives in the feedist
    /// @param token the token address to check
    /// @param owner owner's address
    /// @return reward the amount earned/claimable
    function earned(address token, address owner) external view returns (uint256 reward);

    /// @notice function to submit incentives to voters for the upcoming flip
    /// @param token the address of the token to send for incentivization
    /// @param amount the amount of token to send
    function incentivize(address token, uint256 amount) external;

    /// @notice get the rewards for a specific period
    /// @param owner owner's address
    function getPeriodReward(uint256 period, address owner, address token) external;
    /// @notice get the fees and incentives
    function getReward(address owner, address[] memory tokens) external;

    /// @notice remove a reward from the set
    function removeReward(address _token) external;

    /// @notice claws back rewards
    function clawbackRewards(address token, address destination) external;
}

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

interface IFeeDistributorFactory {
    function createFeeDistributor(address pairFees) external returns (address);
}

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

interface IGauge {
    event Deposit(address indexed from, uint256 amount);

    event Withdraw(address indexed from, uint256 amount);

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

    event ClaimRewards(address indexed from, address indexed reward, uint256 amount);

    event RewardWhitelisted(address indexed reward, bool whitelisted);

    /// @notice returns an array with all the addresses of the rewards
    /// @return _rewards array of addresses for rewards
    function rewardsList() external view returns (address[] memory _rewards);

    /// @notice number of different rewards the gauge has facilitated that are 'active'
    /// @return _length the number of individual rewards
    function rewardsListLength() external view returns (uint256 _length);

    /// @notice returns the last time the reward was modified or periodFinish if the reward has ended
    /// @param token address of the token
    /// @return ltra last time reward applicable
    function lastTimeRewardApplicable(address token) external view returns (uint256 ltra);

    /// @notice displays the data struct of rewards for a token
    /// @param token the address of the token
    /// @return data rewards struct
    function rewardData(address token) external view returns (Reward memory data);

    /// @notice calculates the amount of tokens earned for an address
    /// @param token address of the token to check
    /// @param account address to check
    /// @return _reward amount of token claimable
    function earned(address token, address account) external view returns (uint256 _reward);
    /// @notice claims rewards (shadow + any external LP Incentives)
    /// @param account the address to claim for
    /// @param tokens an array of the tokens to claim
    function getReward(address account, address[] calldata tokens) external;

    /// @notice claims all rewards and instant exits xshadow into shadow
    function getRewardAndExit(address account, address[] calldata tokens) external;

    /// @notice calculates the token amounts earned per lp token
    /// @param token address of the token to check
    /// @return rpt reward per token
    function rewardPerToken(address token) external view returns (uint256 rpt);

    /// @notice deposit all LP tokens from msg.sender's wallet to the gauge
    function depositAll() external;
    /// @param recipient the address of who to deposit on behalf of
    /// @param amount the amount of LP tokens to withdraw
    function depositFor(address recipient, uint256 amount) external;

    /// @notice deposit LP tokens to the gauge
    /// @param amount the amount of LP tokens to withdraw
    function deposit(uint256 amount) external;

    /// @notice withdraws all fungible LP tokens from legacy gauges
    function withdrawAll() external;

    /// @notice withdraws fungible LP tokens from legacy gauges
    /// @param amount the amount of LP tokens to withdraw
    function withdraw(uint256 amount) external;

    function unstakeAndClaimAll(address[] calldata tokens) external;

    /// @notice calculates how many tokens are left to be distributed
    /// @dev reduces per second
    /// @param token the address of the token
    function left(address token) external view returns (uint256);

    /**
     * @notice amount must be greater than left() for the token, this is to prevent griefing attacks
     * @notice notifying rewards is completely permissionless
     * @notice if nobody registers for a newly added reward for the period it will remain in the contract indefinitely
     */
    function notifyRewardAmount(address token, uint256 amount) external;

    struct Reward {
        /// @dev tokens per second
        uint256 rewardRate;
        /// @dev 7 days after start
        uint256 periodFinish;
        uint256 lastUpdateTime;
        uint256 rewardPerTokenStored;
    }

    /// @notice checks if a reward is whitelisted
    /// @param reward the address of the reward
    /// @return true if the reward is whitelisted, false otherwise
    function isWhitelisted(address reward) external view returns (bool);
}

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

interface IGaugeFactory {
    /// @notice create a legacy gauge for a specific pool
    /// @param pool the address of the pool
    /// @return newGauge is the address of the created gauge
    function createGauge(address pool) external returns (address newGauge);
}

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IVoter} from "./IVoter.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";

interface IXShadow is IERC20 {
    struct VestPosition {
        /// @dev amount of xShadow
        uint256 amount;
        /// @dev start unix timestamp
        uint256 start;
        /// @dev start + MAX_VEST (end timestamp)
        uint256 maxEnd;
        /// @dev vest identifier (starting from 0)
        uint256 vestID;
    }

    event CancelVesting(address indexed user, uint256 indexed vestId, uint256 amount);
    event ExitVesting(address indexed user, uint256 indexed vestId, uint256 amount);
    event InstantExit(address indexed user, uint256);

    event NewSlashingPenalty(uint256 penalty);

    event NewVest(address indexed user, uint256 indexed vestId, uint256 indexed amount);
    event NewVestingTimes(uint256 min, uint256 max);

    event Converted(address indexed user, uint256);

    event Exemption(address indexed candidate, bool status, bool success);

    event XShadowRedeemed(address indexed user, uint256);

    event NewOperator(address indexed o, address indexed n);

    event Rebase(address indexed caller, uint256 amount);

    event NewRebaseThreshold(uint256 threshold);

    /// @notice returns info on a user's vests
    function vestInfo(address user, uint256)
        external
        view
        returns (uint256 amount, uint256 start, uint256 maxEnd, uint256 vestID);

    /// @notice address of the shadow token
    function SHADOW() external view returns (IERC20);

    /// @notice address of the voter
    function VOTER() external view returns (IVoter);

    function MINTER() external view returns (address);

    function ACCESS_HUB() external view returns (address);

    /// @notice address of the operator
    function operator() external view returns (address);

    /// @notice address of the VoteModule
    function VOTE_MODULE() external view returns (address);

    /// @notice max slashing amount
    function SLASHING_PENALTY() external view returns (uint256);

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

    /// @notice the minimum vesting length
    function MIN_VEST() external view returns (uint256);

    /// @notice the maximum vesting length
    function MAX_VEST() external view returns (uint256);

    function shadow() external view returns (address);

    /// @notice the last period rebases were distributed
    function lastDistributedPeriod() external view returns (uint256);

    /// @notice amount of pvp rebase penalties accumulated pending to be distributed
    function pendingRebase() external view returns (uint256);

    /// @notice dust threshold before a rebase can happen
    function rebaseThreshold() external view returns (uint256);

    /// @notice pauses the contract
    function pause() external;

    /// @notice unpauses the contract
    function unpause() external;

    /**
     *
     */
    // General use functions
    /**
     *
     */

    /// @dev mints xShadows for each shadow.
    function convertEmissionsToken(uint256 _amount) external;

    /// @notice function called by the minter to send the rebases once a week
    function rebase() external;
    /**
     * @dev exit instantly with a penalty
     * @param _amount amount of xShadows to exit
     */
    function exit(uint256 _amount) external returns (uint256 _exitedAmount);

    /// @dev vesting xShadows --> emissionToken functionality
    function createVest(uint256 _amount) external;

    /// @dev handles all situations regarding exiting vests
    function exitVest(uint256 _vestID) external;

    /**
     *
     */
    // Permissioned functions, timelock/operator gated
    /**
     *
     */

    /// @dev allows the operator to redeem collected xShadows
    function operatorRedeem(uint256 _amount) external;

    /// @dev allows rescue of any non-stake token
    function rescueTrappedTokens(address[] calldata _tokens, uint256[] calldata _amounts) external;

    /// @notice migrates the operator to another contract
    function migrateOperator(address _operator) external;

    /// @notice set exemption status for an address
    function setExemption(address[] calldata _exemptee, bool[] calldata _exempt) external;

    function setExemptionTo(address[] calldata _exemptee, bool[] calldata _exempt) external;

    /// @notice set dust threshold before a rebase can happen
    function setRebaseThreshold(uint256 _newThreshold) external;

    /**
     *
     */
    // Getter functions
    /**
     *
     */

    /// @notice returns the amount of SHADOW within the contract
    function getBalanceResiding() external view returns (uint256);
    /// @notice returns the total number of individual vests the user has
    function usersTotalVests(address _who) external view returns (uint256 _numOfVests);

    /// @notice whether the address is exempt
    /// @param _who who to check
    /// @return _exempt whether it's exempt
    function isExempt(address _who) external view returns (bool _exempt);

    /// @notice returns the vest info for a user
    /// @param _who who to check
    /// @param _vestID vest ID to check
    /// @return VestPosition vest info
    function getVestInfo(address _who, uint256 _vestID) external view returns (VestPosition memory);
}

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

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

library VoterStorage {
    using EnumerableSet for EnumerableSet.AddressSet;

    /// @dev keccak256(abi.encode(uint256(keccak256("voter.storage")) - 1)) & ~bytes32(uint256(0xff));
    bytes32 public constant VOTER_STORAGE_LOCATION = 0x1756ff67afd71ca1c6aec4fe909f6cf0de32bed30949be9d2e1860a94e6e9500;

    /// @custom꞉storage‑location erc7201꞉voter.storage
    struct VoterState {
        /// @inheritdoc IVoter
        address legacyFactory;
        /// @inheritdoc IVoter
        address shadow;
        /// @inheritdoc IVoter
        address gaugeFactory;
        /// @inheritdoc IVoter
        address feeDistributorFactory;
        /// @inheritdoc IVoter
        address minter;
        /// @inheritdoc IVoter
        address accessHub;
        /// @inheritdoc IVoter
        address governor;
        /// @inheritdoc IVoter
        address clFactory;
        /// @inheritdoc IVoter
        address clGaugeFactory;
        /// @inheritdoc IVoter
        address poolUpdater;
        /// @inheritdoc IVoter
        address nfpManager;
        /// @inheritdoc IVoter
        address feeRecipientFactory;
        /// @inheritdoc IVoter
        address xShadow;
        /// @inheritdoc IVoter
        address voteModule;
        /// @inheritdoc IVoter
        address launcherPlugin;
        /// @inheritdoc IVoter
        uint256 xRatio;
        bool voterOwnsLegacyFactory;
        EnumerableSet.AddressSet pools;
        EnumerableSet.AddressSet gauges;
        EnumerableSet.AddressSet feeDistributors;
        mapping(address pool => address gauge) gaugeForPool;
        mapping(address gauge => address pool) poolForGauge;
        mapping(address gauge => address feeDistributor) feeDistributorForGauge;
        mapping(address token0 => mapping(address token1 => address feeDistributor)) feeDistributorForClPair;
        mapping(address token0 => mapping(address token1 => EnumerableSet.AddressSet gauges)) gaugesForClPair;
        mapping(address sourceGauge => address destinationGauge) gaugeRedirect;
        mapping(address pool => mapping(uint256 period => uint256 totalVotes)) poolTotalVotesPerPeriod;
        mapping(address user => mapping(uint256 period => mapping(address pool => uint256 totalVote)))
            userVotesForPoolPerPeriod;
        mapping(address user => mapping(uint256 period => address[] pools)) userVotedPoolsPerPeriod;
        mapping(address user => mapping(uint256 period => uint256 votingPower)) userVotingPowerPerPeriod;
        mapping(address user => uint256 period) lastVoted;
        mapping(uint256 period => uint256 rewards) totalRewardPerPeriod;
        mapping(uint256 period => uint256 weight) totalVotesPerPeriod;
        mapping(address gauge => mapping(uint256 period => uint256 reward)) gaugeRewardsPerPeriod;
        mapping(address gauge => mapping(uint256 period => bool distributed)) gaugePeriodDistributed;
        mapping(address gauge => uint256 period) lastDistro;
        mapping(address gauge => bool legacyGauge) isLegacyGauge;
        mapping(address gauge => bool clGauge) isClGauge;
        mapping(address => bool) isWhitelisted;
        mapping(address => bool) isAlive;
        /// @dev How many different CL pools there are for the same token pair
        mapping(address token0 => mapping(address token1 => int24[])) _tickSpacingsForPair;
        /// @dev specific gauge based on tickspacing
        mapping(address token0 => mapping(address token1 => mapping(int24 tickSpacing => address gauge)))
            _gaugeForClPool;
        mapping(address clGauge => address feeDist) originalFeeDistributorForGauge;
        mapping(address feeDist => address pool) poolForFeeDistributor;
    }

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

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

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

import {INonfungiblePositionManager} from "../CL/periphery/interfaces/INonfungiblePositionManager.sol";
import {IGauge} from "../interfaces/IGauge.sol";
import {IGaugeV3} from "../CL/gauge/interfaces/IGaugeV3.sol";
import {IClGaugeFactory} from "../CL/gauge/interfaces/IClGaugeFactory.sol";
import {IVoteModule} from "../interfaces/IVoteModule.sol";
import {IFeeDistributor} from "../interfaces/IFeeDistributor.sol";
import {IXShadow} from "contracts/interfaces/IXShadow.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Errors} from "contracts/libraries/Errors.sol";
import {IPair} from "contracts/interfaces/IPair.sol";
import {IPairFactory} from "contracts/interfaces/IPairFactory.sol";
import {IRouter} from "contracts/interfaces/IRouter.sol";
import {IVoter} from "contracts/interfaces/IVoter.sol";
import {IFeeRecipientFactory} from "contracts/interfaces/IFeeRecipientFactory.sol";

import {VoterStorage} from "contracts/libraries/VoterStorage.sol";

/// @title VoterGovernanceActions
/// @notice Governance logic for Voter
/// @dev Used to reduce Voter contract size by moving all governance related logic to a library
library VoterGovernanceActions {
    using EnumerableSet for EnumerableSet.AddressSet;

    uint256 internal constant DURATION = 7 days;
    uint256 public constant BASIS = 1_000_000;

    function setGlobalRatio(uint256 _xRatio) external {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        require(_xRatio <= BASIS, Errors.RATIO_TOO_HIGH(_xRatio));

        emit IVoter.EmissionsRatio(msg.sender, $.xRatio, _xRatio);
        $.xRatio = _xRatio;
    }

    function setGovernor(address _governor) external {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        if ($.governor != _governor) {
            $.governor = _governor;
            emit IVoter.NewGovernor(msg.sender, _governor);
        }
    }

    function whitelist(address _token) public {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        require(!$.isWhitelisted[_token], Errors.ALREADY_WHITELISTED(_token));
        $.isWhitelisted[_token] = true;
        emit IVoter.Whitelisted(msg.sender, _token);
    }

    function revokeWhitelist(address _token) public {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        require($.isWhitelisted[_token], Errors.NOT_WHITELISTED(_token));
        $.isWhitelisted[_token] = false;
        emit IVoter.WhitelistRevoked(msg.sender, _token, true);
    }

    function killGauge(address _gauge) public {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev ensure the gauge is alive already, and exists
        require($.isAlive[_gauge] && $.gauges.contains(_gauge), Errors.GAUGE_INACTIVE(_gauge));
        /// @dev set the gauge to dead
        $.isAlive[_gauge] = false;
        address pool = $.poolForGauge[_gauge];
        /// @dev check if it's a legacy gauge
        if ($.isLegacyGauge[_gauge]) {
            /// @dev revert back to the default feeSplit
            uint256 feeSplit = IPairFactory($.legacyFactory).feeSplit();
            IPairFactory($.legacyFactory).setPairFeeSplit(pool, feeSplit);

            /// @dev killed legacy gauges behave the same whether it has a main gauge or not
            bool feeSplitWhenNoGauge = IPairFactory($.legacyFactory).feeSplitWhenNoGauge();
            if (feeSplitWhenNoGauge) {
                /// @dev What used to go to FeeRecipient will go to treasury
                /// @dev we are assuming voter.governor is the intended receiver (== factory.treasury)
                IPairFactory($.legacyFactory).setFeeRecipient(pool, $.governor);
            } else {
                /// @dev the fees are handed to LPs instead of FeeRecipient
                IPairFactory($.legacyFactory).setFeeRecipient(pool, address(0));
            }
        }
        /// @dev fetch the last distribution
        uint256 _lastDistro = $.lastDistro[_gauge];
        /// @dev fetch the current period
        uint256 currentPeriod = getPeriod();
        /// @dev placeholder
        uint256 _claimable;
        /// @dev loop through the last distribution period up to and including the current period
        for (uint256 period = _lastDistro; period <= currentPeriod; ++period) {
            /// @dev if the gauge isn't distributed for the period
            if (!$.gaugePeriodDistributed[_gauge][period]) {
                uint256 additionalClaimable = _claimablePerPeriod(pool, period);
                _claimable += additionalClaimable;

                /// @dev prevent gaugePeriodDistributed being marked true when the minter hasn't updated yet
                if (additionalClaimable > 0) {
                    $.gaugePeriodDistributed[_gauge][period] = true;
                }
            }
        }
        /// @dev if there is anything claimable left
        if (_claimable > 0) {
            /// @dev send to the governor contract
            IERC20($.shadow).transfer($.governor, _claimable);
        }

        /// @dev we dont update lastDistro here so distribute can still be called to pass if revived

        emit IVoter.GaugeKilled(_gauge);
    }

    function reviveGauge(address _gauge) public {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev ensure the gauge is dead and exists
        require(!$.isAlive[_gauge] && $.gauges.contains(_gauge), Errors.ACTIVE_GAUGE(_gauge));
        /// @dev set the gauge to alive
        $.isAlive[_gauge] = true;
        /// @dev check if it's a legacy gauge
        if ($.isLegacyGauge[_gauge]) {
            address pool = $.poolForGauge[_gauge];
            address feeRecipient = IFeeRecipientFactory($.feeRecipientFactory).feeRecipientForPair(pool);
            IPairFactory($.legacyFactory).setFeeRecipient(pool, feeRecipient);

            /// @dev revert back to the 100% feeSplit going to feeRecipient
            IPairFactory($.legacyFactory).setPairFeeSplit(pool, BASIS);
        }

        /// @dev we dont update lastDistro here so distribute can still be called to pass fees

        emit IVoter.GaugeRevived(_gauge);
    }

    /// @dev in case of emission stuck due to killed gauges and unsupported operations
    function stuckEmissionsRecovery(address _gauge, uint256 _period) external {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev require gauge is dead
        require(!$.isAlive[_gauge], Errors.ACTIVE_GAUGE(_gauge));

        /// @dev ensure the gauge exists
        require($.gauges.contains(_gauge), Errors.GAUGE_INACTIVE(_gauge));

        /// @dev check if the period has been distributed already
        if (!$.gaugePeriodDistributed[_gauge][_period]) {
            address pool = $.poolForGauge[_gauge];
            uint256 _claimable = _claimablePerPeriod(pool, _period);
            /// @dev if there is gt 0 emissions, send to governor
            if (_claimable > 0) {
                IERC20($.shadow).transfer($.governor, _claimable);
                /// @dev mark period as distributed
                $.gaugePeriodDistributed[_gauge][_period] = true;
            }
        }
    }

    function removeFeeDistributorReward(address _feeDistributor, address reward) external {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        /// @dev ensure the feeDist exists
        require($.feeDistributors.contains(_feeDistributor));
        IFeeDistributor(_feeDistributor).removeReward(reward);
    }

    function setNfpManager(address _newNfpManager) external {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        $.nfpManager = _newNfpManager;
        IClGaugeFactory($.clGaugeFactory).setNfpManager(_newNfpManager);
    }

    function getPeriod() private view returns (uint256 period) {
        return (block.timestamp / 1 weeks);
    }

    /// @dev shows how much is claimable per period
    function _claimablePerPeriod(address pool, uint256 period) private view returns (uint256) {
        VoterStorage.VoterState storage $ = VoterStorage.getStorage();

        uint256 numerator = ($.totalRewardPerPeriod[period] * $.poolTotalVotesPerPeriod[pool][period]) * 1e18;

        /// @dev return 0 if this happens, or else there could be a divide by zero next
        return (numerator == 0 ? 0 : (numerator / $.totalVotesPerPeriod[period] / 1e18));
    }
}

// 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: GPL-2.0-or-later
pragma solidity ^0.8.0;

interface IRouter {
    struct route {
        /// @dev token from
        address from;
        /// @dev token to
        address to;
        /// @dev is stable route
        bool stable;
    }

    /// @notice sorts the tokens to see what the expected LP output would be for token0 and token1 (A/B)
    /// @param tokenA the address of tokenA
    /// @param tokenB the address of tokenB
    /// @return token0 address of which becomes token0
    /// @return token1 address of which becomes token1
    function sortTokens(address tokenA, address tokenB) external pure returns (address token0, address token1);

    /// @notice calculates the CREATE2 address for a pair without making any external calls
    /// @param tokenA the address of tokenA
    /// @param tokenB the address of tokenB
    /// @param stable if the pair is using the stable curve
    /// @return pair address of the pair
    function pairFor(address tokenA, address tokenB, bool stable) external view returns (address pair);

    /// @notice fetches and sorts the reserves for a pair
    /// @param tokenA the address of tokenA
    /// @param tokenB the address of tokenB
    /// @param stable if the pair is using the stable curve
    /// @return reserveA get the reserves for tokenA
    /// @return reserveB get the reserves for tokenB
    function getReserves(address tokenA, address tokenB, bool stable)
        external
        view
        returns (uint256 reserveA, uint256 reserveB);

    /// @notice performs chained getAmountOut calculations on any number of pairs
    /// @param amountIn the amount of tokens of routes[0] to swap
    /// @param routes the struct of the hops the swap should take
    /// @return amounts uint array of the amounts out
    function getAmountsOut(uint256 amountIn, route[] memory routes) external view returns (uint256[] memory amounts);

    /// @notice performs chained getAmountOut calculations on any number of pairs
    /// @param amountIn amount of tokenIn
    /// @param tokenIn address of the token going in
    /// @param tokenOut address of the token coming out
    /// @return amount uint amount out
    /// @return stable if the curve used is stable or not
    function getAmountOut(uint256 amountIn, address tokenIn, address tokenOut)
        external
        view
        returns (uint256 amount, bool stable);

    /// @notice performs calculations to determine the expected state when adding liquidity
    /// @param tokenA the address of tokenA
    /// @param tokenB the address of tokenB
    /// @param stable if the pair is using the stable curve
    /// @param amountADesired amount of tokenA desired to be added
    /// @param amountBDesired amount of tokenB desired to be added
    /// @return amountA amount of tokenA added
    /// @return amountB amount of tokenB added
    /// @return liquidity liquidity value added
    function quoteAddLiquidity(
        address tokenA,
        address tokenB,
        bool stable,
        uint256 amountADesired,
        uint256 amountBDesired
    ) external view returns (uint256 amountA, uint256 amountB, uint256 liquidity);

    /// @param tokenA the address of tokenA
    /// @param tokenB the address of tokenB
    /// @param stable if the pair is using the stable curve
    /// @param liquidity liquidity value to remove
    /// @return amountA amount of tokenA removed
    /// @return amountB amount of tokenB removed
    function quoteRemoveLiquidity(address tokenA, address tokenB, bool stable, uint256 liquidity)
        external
        view
        returns (uint256 amountA, uint256 amountB);

    /// @param tokenA the address of tokenA
    /// @param tokenB the address of tokenB
    /// @param stable if the pair is using the stable curve
    /// @param amountADesired amount of tokenA desired to be added
    /// @param amountBDesired amount of tokenB desired to be added
    /// @param amountAMin slippage for tokenA calculated from this param
    /// @param amountBMin slippage for tokenB calculated from this param
    /// @param to the address the liquidity tokens should be minted to
    /// @param deadline timestamp deadline
    /// @return amountA amount of tokenA used
    /// @return amountB amount of tokenB used
    /// @return liquidity amount of liquidity minted
    function addLiquidity(
        address tokenA,
        address tokenB,
        bool stable,
        uint256 amountADesired,
        uint256 amountBDesired,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);

    /// @param token the address of token
    /// @param stable if the pair is using the stable curve
    /// @param amountTokenDesired desired amount for token
    /// @param amountTokenMin slippage for token
    /// @param amountETHMin minimum amount of ETH added (slippage)
    /// @param to the address the liquidity tokens should be minted to
    /// @param deadline timestamp deadline
    /// @return amountToken amount of the token used
    /// @return amountETH amount of ETH used
    /// @return liquidity amount of liquidity minted
    function addLiquidityETH(
        address token,
        bool stable,
        uint256 amountTokenDesired,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
    ) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);
    /// @param tokenA the address of tokenA
    /// @param tokenB the address of tokenB
    /// @param stable if the pair is using the stable curve
    /// @param amountADesired amount of tokenA desired to be added
    /// @param amountBDesired amount of tokenB desired to be added
    /// @param amountAMin slippage for tokenA calculated from this param
    /// @param amountBMin slippage for tokenB calculated from this param
    /// @param to the address the liquidity tokens should be minted to
    /// @param deadline timestamp deadline
    /// @return amountA amount of tokenA used
    /// @return amountB amount of tokenB used
    /// @return liquidity amount of liquidity minted
    function addLiquidityAndStake(
        address tokenA,
        address tokenB,
        bool stable,
        uint256 amountADesired,
        uint256 amountBDesired,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);

    /// @notice adds liquidity to a legacy pair using ETH, and stakes it into a gauge on "to's" behalf
    /// @param token the address of token
    /// @param stable if the pair is using the stable curve
    /// @param amountTokenDesired amount of token to be used
    /// @param amountTokenMin slippage of token
    /// @param amountETHMin slippage of ETH
    /// @param to the address the liquidity tokens should be minted to
    /// @param deadline timestamp deadline
    /// @return amountA amount of tokenA used
    /// @return amountB amount of tokenB used
    /// @return liquidity amount of liquidity minted
    function addLiquidityETHAndStake(
        address token,
        bool stable,
        uint256 amountTokenDesired,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
    ) external payable returns (uint256 amountA, uint256 amountB, uint256 liquidity);
    /// @param tokenA the address of tokenA
    /// @param tokenB the address of tokenB
    /// @param stable if the pair is using the stable curve
    /// @param liquidity amount of LP tokens to remove
    /// @param amountAMin slippage of tokenA
    /// @param amountBMin slippage of tokenB
    /// @param to the address the liquidity tokens should be minted to
    /// @param deadline timestamp deadline
    /// @return amountA amount of tokenA used
    /// @return amountB amount of tokenB used
    function removeLiquidity(
        address tokenA,
        address tokenB,
        bool stable,
        uint256 liquidity,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountA, uint256 amountB);
    /// @param token address of the token
    /// @param stable if the pair is using the stable curve
    /// @param liquidity liquidity tokens to remove
    /// @param amountTokenMin slippage of token
    /// @param amountETHMin slippage of ETH
    /// @param to the address the liquidity tokens should be minted to
    /// @param deadline timestamp deadline
    /// @return amountToken amount of token used
    /// @return amountETH amount of ETH used
    function removeLiquidityETH(
        address token,
        bool stable,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountToken, uint256 amountETH);
    /// @param amountIn amount to send ideally
    /// @param amountOutMin slippage of amount out
    /// @param routes the hops the swap should take
    /// @param to the address the liquidity tokens should be minted to
    /// @param deadline timestamp deadline
    /// @return amounts amounts returned
    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        route[] calldata routes,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
    /// @param routes the hops the swap should take
    /// @param to the address the liquidity tokens should be minted to
    /// @param deadline timestamp deadline
    /// @return amounts amounts returned
    function swapTokensForExactTokens(
        uint256 amountOut,
        uint256 amountInMax,
        route[] memory routes,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
    /// @param amountOutMin slippage of token
    /// @param routes the hops the swap should take
    /// @param to the address the liquidity tokens should be minted to
    /// @param deadline timestamp deadline
    /// @return amounts amounts returned
    function swapExactETHForTokens(uint256 amountOutMin, route[] calldata routes, address to, uint256 deadline)
        external
        payable
        returns (uint256[] memory amounts);
    /// @param amountOut amount of tokens to get out
    /// @param amountInMax max amount of tokens to put in to achieve amountOut (slippage)
    /// @param routes the hops the swap should take
    /// @param to the address the liquidity tokens should be minted to
    /// @param deadline timestamp deadline
    /// @return amounts amounts returned
    function swapTokensForExactETH(
        uint256 amountOut,
        uint256 amountInMax,
        route[] calldata routes,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
    /// @param amountIn amount of tokens to swap
    /// @param amountOutMin slippage of token
    /// @param routes the hops the swap should take
    /// @param to the address the liquidity tokens should be minted to
    /// @param deadline timestamp deadline
    /// @return amounts amounts returned
    function swapExactTokensForETH(
        uint256 amountIn,
        uint256 amountOutMin,
        route[] calldata routes,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
    /// @param amountOut exact amount out or revert
    /// @param routes the hops the swap should take
    /// @param to the address the liquidity tokens should be minted to
    /// @param deadline timestamp deadline
    /// @return amounts amounts returned
    function swapETHForExactTokens(uint256 amountOut, route[] calldata routes, address to, uint256 deadline)
        external
        payable
        returns (uint256[] memory amounts);

    /// @param amountIn token amount to swap
    /// @param amountOutMin slippage of token
    /// @param routes the hops the swap should take
    /// @param to the address the liquidity tokens should be minted to
    /// @param deadline timestamp deadline
    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        route[] calldata routes,
        address to,
        uint256 deadline
    ) external;

    /// @param amountOutMin slippage of token
    /// @param routes the hops the swap should take
    /// @param to the address the liquidity tokens should be minted to
    /// @param deadline timestamp deadline
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint256 amountOutMin,
        route[] calldata routes,
        address to,
        uint256 deadline
    ) external payable;

    /// @param amountIn token amount to swap
    /// @param amountOutMin slippage of token
    /// @param routes the hops the swap should take
    /// @param to the address the liquidity tokens should be minted to
    /// @param deadline timestamp deadline
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        route[] calldata routes,
        address to,
        uint256 deadline
    ) external;

    /// @notice **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens)****
    /// @param token address of the token
    /// @param stable if the swap curve is stable
    /// @param liquidity liquidity value (lp tokens)
    /// @param amountTokenMin slippage of token
    /// @param amountETHMin slippage of ETH
    /// @param to address to send to
    /// @param deadline timestamp deadline
    /// @return amountToken amount of token received
    /// @return amountETH amount of ETH received
    function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        bool stable,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountToken, uint256 amountETH);
}

// 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: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// SPDX-License-Identifier: 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.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

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

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

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

// SPDX-License-Identifier: MIT
// 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):