HYPE Price: $40.03 (-3.83%)
 

Overview

HYPE Balance

HyperEVM LogoHyperEVM LogoHyperEVM Logo0 HYPE

HYPE Value

$0.00

Token Holdings

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Rebalance162628342025-10-12 6:04:0030 days ago1760249040IN
0x89A8f48B...01090AbF4
0 HYPE0.000377820.2
Rebalance160381712025-10-09 16:41:0032 days ago1760028060IN
0x89A8f48B...01090AbF4
0 HYPE0.000360630.2
Rebalance129005322025-09-03 23:19:0068 days ago1756941540IN
0x89A8f48B...01090AbF4
0 HYPE0.000344730.20339602
Rebalance111291352025-08-14 19:05:0088 days ago1755198300IN
0x89A8f48B...01090AbF4
0 HYPE0.000388710.2
Rebalance101447562025-08-03 14:05:0099 days ago1754229900IN
0x89A8f48B...01090AbF4
0 HYPE0.000333660.2
Rebalance100380722025-08-02 8:53:00101 days ago1754124780IN
0x89A8f48B...01090AbF4
0 HYPE0.000373190.2089455
Rebalance94602122025-07-26 18:17:00107 days ago1753553820IN
0x89A8f48B...01090AbF4
0 HYPE0.00042170.2
Rebalance75936782025-07-05 11:46:00129 days ago1751715960IN
0x89A8f48B...01090AbF4
0 HYPE0.000362960.2
Rebalance75932512025-07-05 11:39:00129 days ago1751715540IN
0x89A8f48B...01090AbF4
0 HYPE0.000408460.2
Rebalance74021102025-07-03 7:23:00131 days ago1751527380IN
0x89A8f48B...01090AbF4
0 HYPE0.000483230.24108622
Rebalance70283652025-06-29 1:16:00135 days ago1751159760IN
0x89A8f48B...01090AbF4
0 HYPE0.000450010.2
Rebalance66070912025-06-24 6:00:00140 days ago1750744800IN
0x89A8f48B...01090AbF4
0 HYPE0.00060960.33480169
Withdraw65739072025-06-23 20:56:00140 days ago1750712160IN
0x89A8f48B...01090AbF4
0 HYPE0.000115580.11694502
Rebalance64165922025-06-22 1:57:00142 days ago1750557420IN
0x89A8f48B...01090AbF4
0 HYPE0.000422350.21589214
Rebalance64153722025-06-22 1:37:00142 days ago1750556220IN
0x89A8f48B...01090AbF4
0 HYPE0.000380860.2
Rebalance63843922025-06-21 17:09:00142 days ago1750525740IN
0x89A8f48B...01090AbF4
0 HYPE0.00034880.2
Rebalance63833552025-06-21 16:52:00142 days ago1750524720IN
0x89A8f48B...01090AbF4
0 HYPE0.000385040.2
Rebalance62693902025-06-20 9:40:00144 days ago1750412400IN
0x89A8f48B...01090AbF4
0 HYPE0.000325130.2
Rebalance62693292025-06-20 9:39:00144 days ago1750412340IN
0x89A8f48B...01090AbF4
0 HYPE0.000357050.2
Rebalance62692682025-06-20 9:38:00144 days ago1750412280IN
0x89A8f48B...01090AbF4
0 HYPE0.000396750.2
Rebalance62692072025-06-20 9:37:00144 days ago1750412220IN
0x89A8f48B...01090AbF4
0 HYPE0.000366560.2
Rebalance62691462025-06-20 9:36:00144 days ago1750412160IN
0x89A8f48B...01090AbF4
0 HYPE0.000402050.2
Rebalance62690852025-06-20 9:35:00144 days ago1750412100IN
0x89A8f48B...01090AbF4
0 HYPE0.000447180.2
Rebalance62681702025-06-20 9:20:00144 days ago1750411200IN
0x89A8f48B...01090AbF4
0 HYPE0.000371560.21448225
Rebalance62676822025-06-20 9:12:00144 days ago1750410720IN
0x89A8f48B...01090AbF4
0 HYPE0.000377050.2
View all transactions

Parent Transaction Hash Block From To
View All Internal Transactions
Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
HypervisorNFPM

Compiler Version
v0.8.20+commit.a1b79de6

Optimization Enabled:
Yes with 200 runs

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

pragma solidity =0.8.20;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";

import "@cryptoalgebra/integral-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
import "@cryptoalgebra/integral-farming/contracts/interfaces/IFarmingCenter.sol";
import "./interfaces/IIncentiveMaker.sol";
import "./interfaces/IHypervisorState.sol";
import "./interfaces/IMultiFeeDistribution.sol";

import "./libraries/PositionManagementLibrary.sol";
import "./libraries/PositionValue.sol";

import "@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol";
import "@cryptoalgebra/integral-core/contracts/libraries/TickMath.sol";

/// @title Hypervisor 1.3.1
/// @notice A Uniswap V2-like interface with fungible liquidity 
/// which allows for arbitrary liquidity provision: one-sided, lop-sided, and balanced
contract HypervisorNFPM is IHypervisorState, Ownable, Pausable, ERC20Permit, ReentrancyGuard {
    using SafeERC20 for IERC20;
    using PositionManagementLibrary for INonfungiblePositionManager;

    IAlgebraPool public pool;
    INonfungiblePositionManager public nonfungiblePositionManager;
    IFarmingCenter public farmingCenter;
    IIncentiveMaker public incentiveMaker;
    IMultiFeeDistribution public receiver;
    IncentiveKey public currentIncentiveKey;

    IERC20 public token0;
    IERC20 public token1;
    IERC20 public rewardToken;
    IERC20 public bonusRewardToken;

    uint8 public fee = 1;
    int24 public tickSpacing;

    int24 public baseLower;
    int24 public baseUpper;
    int24 public limitLower;
    int24 public limitUpper;

    uint256 public baseNftId;
    uint256 public limitNftId;

    address public whitelistedAddress;
    address public feeRecipient;
    bool public directDeposit;

    uint256 public constant PRECISION = 1e36;

    constructor(
        address _pool,
        address _nonfungiblePositionManager,  
        address _incentiveMaker,  
        address _receiver, 
        string memory name,
        string memory symbol
    ) ERC20(name, symbol) ERC20Permit(name) {
        require(
            _pool != address(0) &&
            _nonfungiblePositionManager != address(0) &&
            _receiver != address(0)
        );

        // Initialize core contracts
        pool = IAlgebraPool(_pool);
        nonfungiblePositionManager = INonfungiblePositionManager(_nonfungiblePositionManager);
        farmingCenter = IFarmingCenter(nonfungiblePositionManager.farmingCenter());
        incentiveMaker = IIncentiveMaker(_incentiveMaker);
        receiver = IMultiFeeDistribution(_receiver);

        // Set initial incentive maker and reward tokens
        if (_incentiveMaker != address(0)) {
            incentiveMaker = IIncentiveMaker(_incentiveMaker);
            currentIncentiveKey = incentiveMaker.poolToKey(_pool);
            rewardToken = IERC20(address(currentIncentiveKey.rewardToken));
            bonusRewardToken = IERC20(address(currentIncentiveKey.bonusRewardToken));
        }

        // Cache pool values in single external calls
        address token0Addr = pool.token0();
        address token1Addr = pool.token1();
        tickSpacing = pool.tickSpacing();
        require(token0Addr != address(0) && token1Addr != address(0));

        token0 = IERC20(token0Addr);
        token1 = IERC20(token1Addr);

        // Set initial values
        fee = 1;

        // Approve token spending
        token0.safeApprove(address(nonfungiblePositionManager), type(uint256).max);
        token1.safeApprove(address(nonfungiblePositionManager), type(uint256).max);

    }

    /// @notice Deposit tokens
    /// @param deposit0 Amount of token0 transfered from sender to Hypervisor
    /// @param deposit1 Amount of token1 transfered from sender to Hypervisor
    /// @param to Address to which liquidity tokens are minted
    /// @param from Address from which asset tokens are transferred
    /// @param inMin min spend for directDeposit is true 
    /// @return shares Quantity of liquidity tokens minted as a result of deposit
    function deposit(
        uint256 deposit0,
        uint256 deposit1,
        address to,
        address from,
        uint256[4] memory inMin
    ) nonReentrant whenNotPaused external returns (uint256 shares) {
        return _deposit(deposit0, deposit1, to, from, inMin);
    }

    /// @notice Deposits tokens into the hypervisor and automatically stakes the resulting LP tokens
    /// @dev First calls _deposit to mint LP tokens, then approves and stakes them in the receiver contract
    /// @param deposit0 Amount of token0 to deposit
    /// @param deposit1 Amount of token1 to deposit  
    /// @param to Address that will receive the staked position
    /// @param from Address from which deposit tokens are transferred
    /// @param inMin Array of minimum amounts: [base0Min, base1Min, limit0Min, limit1Min]
    /// @return shares The quantity of liquidity tokens minted and staked
    function depositAndStake(
        uint256 deposit0,
        uint256 deposit1,
        address to,
        address from,
        uint256[4] memory inMin
    ) nonReentrant whenNotPaused external returns (uint256 shares) {
        // First deposit to get LP tokens
        shares = _deposit(deposit0, deposit1, address(this), from, inMin);
        
        // Approve only the exact amount needed
        IERC20(address(this)).safeApprove(address(receiver), 0);
        IERC20(address(this)).safeApprove(address(receiver), shares);       
        // Stake the shares in the receiver
        receiver.stake(shares, to);
        
        return shares;
    }
    
    function _deposit(
        uint256 deposit0,
        uint256 deposit1,
        address to,
        address from,
        uint256[4] memory inMin
    ) internal returns (uint256 shares) {
        require(deposit0 > 0 || deposit1 > 0);
        require(to != address(0));
        if (msg.sender != whitelistedAddress) revert NotWhitelisted();

        /// update fees
        _zeroBurn();

        /// update rewards
        if (baseNftId != 0) _collectAndClaim(baseNftId);
        if (limitNftId != 0) _collectAndClaim(limitNftId);


        (uint160 sqrtPrice, , , , , ,) = pool.safelyGetStateOfAMM();

        uint256 price = FullMath.mulDiv(uint256(sqrtPrice) * 1e18, uint256(sqrtPrice) * 1e18, 2**(96 * 2));

        (uint256 pool0, uint256 pool1) = getTotalAmounts();

        shares = deposit1 + FullMath.mulDiv(deposit0, price, PRECISION);

        if (deposit0 > 0) {
            token0.safeTransferFrom(from, address(this), deposit0);
        }
        if (deposit1 > 0) {
            token1.safeTransferFrom(from, address(this), deposit1);
        }

        uint256 total = totalSupply();
        if (total != 0) {
            uint256 pool0PricedInToken1 = FullMath.mulDiv(pool0, price, PRECISION);
            shares = FullMath.mulDiv(shares, total, (pool0PricedInToken1 + pool1));
            

            if (directDeposit) {
                PositionManagementLibrary.DirectDepositParams memory params = PositionManagementLibrary.DirectDepositParams({
                    pool: pool,
                    baseNftId: baseNftId,
                    limitNftId: limitNftId,
                    baseLower: baseLower,
                    baseUpper: baseUpper,
                    limitLower: limitLower,
                    limitUpper: limitUpper,
                    deposit0: deposit0,
                    deposit1: deposit1,
                    minAmounts: inMin
                });
                
                nonfungiblePositionManager.computeAndDirectDeposit(params);
            }          
        }
        _mint(to, shares);

        emit Deposit(from, to, shares, deposit0, deposit1);
    }
    
    /// @notice External function to collect and distribute fees from active NFT positions
    /// @dev Can only be called by whitelisted address
    /// @return owed0 Total amount of token0 fees collected from both positions
    /// @return owed1 Total amount of token1 fees collected from both positions  
    function zeroBurn() external returns(uint256 owed0, uint256 owed1) {
        require(msg.sender == whitelistedAddress);
        return _zeroBurn();
    }

    /// @notice Collects and distributes fees from active NFT positions
    /// @dev Called internally to collect fees
    /// @return owed0 Total amount of token0 fees collected from both positions
    /// @return owed1 Total amount of token1 fees collected from both positions
    function _zeroBurn() internal returns(uint256 owed0, uint256 owed1) {
        uint256 collected0Base = 0;
        uint256 collected1Base = 0;
        uint256 collected0Limit = 0; 
        uint256 collected1Limit = 0;
        
        if (baseNftId != 0) {
            (collected0Base, collected1Base) = nonfungiblePositionManager.collect(
                INonfungiblePositionManager.CollectParams({
                    tokenId: baseNftId,
                    recipient: address(this), 
                    amount0Max: type(uint128).max,
                    amount1Max: type(uint128).max
                })
            );
        }

        if (limitNftId != 0) {
            (collected0Limit, collected1Limit) = nonfungiblePositionManager.collect(
                INonfungiblePositionManager.CollectParams({
                    tokenId: limitNftId,
                    recipient: address(this),
                    amount0Max: type(uint128).max,
                    amount1Max: type(uint128).max
                })
            );
        }
        
        unchecked {
            owed0 = collected0Base + collected0Limit;
            owed1 = collected1Base + collected1Limit;
        }

        emit ZeroBurn(fee, owed0, owed1);

        if (owed0/fee > 0 && token0.balanceOf(address(this)) > 0) token0.safeTransfer(feeRecipient, owed0/fee);
        if (owed1/fee > 0 && token1.balanceOf(address(this)) > 0) token1.safeTransfer(feeRecipient, owed1/fee);

        return (owed0, owed1);
    }

    /// @param shares Number of liquidity tokens to redeem as pool assets
    /// @param to Address to which redeemed pool assets are sent
    /// @param from Address from which liquidity tokens are sent
    /// @param minAmounts min amount0,1 returned for shares of liq 
    /// @return amount0 Amount of token0 redeemed by the submitted liquidity tokens
    /// @return amount1 Amount of token1 redeemed by the submitted liquidity tokens
    function withdraw(
        uint256 shares,
        address to,
        address from,
        uint256[4] memory minAmounts
        ) nonReentrant whenNotPaused external returns (uint256 amount0, uint256 amount1) {
        require(shares > 0);
        require(to != address(0));
        if (from != msg.sender) revert NotOwner();

        /// update fees
        _zeroBurn();

        /// update rewards
        if (baseNftId != 0) _collectAndClaim(baseNftId);
        if (limitNftId != 0) _collectAndClaim(limitNftId);

        (uint256 base0, uint256 base1, uint256 limit0, uint256 limit1) = 
            nonfungiblePositionManager.withdrawPositions(
                baseNftId,
                limitNftId,
                shares,
                to,
                totalSupply(),
                minAmounts
            );

        // Push tokens proportional to unused balances
        uint256 unusedAmount0 = FullMath.mulDiv(token0.balanceOf(address(this)), shares, totalSupply());
        uint256 unusedAmount1 = FullMath.mulDiv(token1.balanceOf(address(this)), shares, totalSupply());
        if (unusedAmount0 > 0) token0.safeTransfer(to, unusedAmount0);
        if (unusedAmount1 > 0) token1.safeTransfer(to, unusedAmount1);

        amount0 = base0 + limit0 + unusedAmount0;
        amount1 = base1 + limit1 + unusedAmount1;

        _burn(from, shares);

        emit Withdraw(from, to, shares, amount0, amount1);
    }

    /// @param _baseLower The lower tick of the base position
    /// @param _baseUpper The upper tick of the base position
    /// @param _limitLower The lower tick of the limit position
    /// @param _limitUpper The upper tick of the limit position
    /// @param  inMin min spend 
    /// @param  outMin min amount0,1 returned for shares of liq 
    /// @param _feeRecipient Address of recipient of % of fees since last rebalance
    function rebalance(
        int24 _baseLower,
        int24 _baseUpper,
        int24 _limitLower,
        int24 _limitUpper,
        address _feeRecipient,
        uint256[4] memory inMin, 
        uint256[4] memory outMin
        ) nonReentrant external onlyOwner {
        require(
            _baseLower < _baseUpper &&
            _baseLower % tickSpacing == 0 &&
            _baseUpper % tickSpacing == 0 &&
            _limitLower < _limitUpper &&
            _limitLower % tickSpacing == 0 &&
            _limitUpper % tickSpacing == 0 &&
            (_limitUpper != _baseUpper || _limitLower != _baseLower) &&
            _feeRecipient != address(0)
        );
        feeRecipient = _feeRecipient;

        /// update fees
        (uint256 owed0, uint256 owed1) = _zeroBurn();

        /// update rewards
        if (baseNftId != 0) _collectAndClaim(baseNftId);
        if (limitNftId != 0) _collectAndClaim(limitNftId);

        /// Burn existing positions if they exist
        if (baseNftId != 0) {
            (uint128 baseLiquidity, , ) = PositionValue.position(nonfungiblePositionManager, baseNftId);
            nonfungiblePositionManager.decreaseLiquidity(baseNftId, address(this), baseLiquidity, outMin[0], outMin[1]);
        }
        
        if (limitNftId != 0) {
            (uint128 limitLiquidity, , ) = PositionValue.position(nonfungiblePositionManager, limitNftId);
            nonfungiblePositionManager.decreaseLiquidity(limitNftId, address(this), limitLiquidity, outMin[2], outMin[3]);
        }


        emit Rebalance(
            currentTick(),
            token0.balanceOf(address(this)),
            token1.balanceOf(address(this)),
            owed0,
            owed1,
            totalSupply()
        );

        baseLower = _baseLower;
        baseUpper = _baseUpper;

        baseNftId = nonfungiblePositionManager.computeAndMintLiquidity(
            pool,
            baseLower,
            baseUpper,
            token0.balanceOf(address(this)),
            token1.balanceOf(address(this)),
            inMin[0],
            inMin[1],
            address(this)
        );
        if (baseNftId != 0 && address(currentIncentiveKey.pool) != address(0)) {
            _approveAndEnterFarming(baseNftId);
        }

        limitLower = _limitLower;
        limitUpper = _limitUpper;

        limitNftId = nonfungiblePositionManager.computeAndMintLiquidity(
            pool,
            limitLower,
            limitUpper,
            token0.balanceOf(address(this)),
            token1.balanceOf(address(this)),
            inMin[2],
            inMin[3],
            address(this)
        );
        if (limitNftId != 0 && address(currentIncentiveKey.pool) != address(0)) {
            _approveAndEnterFarming(limitNftId);
        }
    }

    /// @notice Compound pending fees and unused deposits
    /// @param inMin min spend 
    function compound(uint256[4] memory inMin) external nonReentrant onlyOwner {
        // update fees for compounding
        _zeroBurn();

        /// update rewards
        if (baseNftId != 0) _collectAndClaim(baseNftId);
        if (limitNftId != 0) _collectAndClaim(limitNftId);

        // Check baseNft and potential liquidity
        if (baseNftId != 0) {
            nonfungiblePositionManager.computeAndIncreaseLiquidity(
                pool,
                baseNftId,
                baseLower,
                baseUpper,
                token0.balanceOf(address(this)),
                token1.balanceOf(address(this)),
                inMin[0],
                inMin[1]
            );
        }

        // Check limitNft and potential liquidity only if limitNft exists
        if (limitNftId != 0) {
            nonfungiblePositionManager.computeAndIncreaseLiquidity(
                pool,
                limitNftId,
                limitLower,
                limitUpper,
                token0.balanceOf(address(this)),
                token1.balanceOf(address(this)),    
                inMin[2],
                inMin[3]
            );
        }
    }

    /// @return total0 Quantity of token0 in both positions and unused in the Hypervisor
    /// @return total1 Quantity of token1 in both positions and unused in the Hypervisor
    function getTotalAmounts() public view returns (uint256 total0, uint256 total1) {
        (, uint256 base0, uint256 base1) = getBasePosition();
        (, uint256 limit0, uint256 limit1) = getLimitPosition();
        
        total0 = token0.balanceOf(address(this)) + base0 + limit0;
        total1 = token1.balanceOf(address(this)) + base1 + limit1;
    }

    /// @return total0 Quantity of token0 in both positions and unused in the Hypervisor including unclaimed fees
    /// @return total1 Quantity of token1 in both positions and unused in the Hypervisor including unclaimed fees
    function getTotalAmountsPlusFees() public view returns (uint256 total0, uint256 total1) {
        // Get base amounts first
        (total0, total1) = getTotalAmounts();
        
        // Calculate unclaimed fees
        uint256 baseFee0 = 0;
        uint256 baseFee1 = 0;
        uint256 limitFee0 = 0;
        uint256 limitFee1 = 0;

        if (baseNftId != 0) {
            (baseFee0, baseFee1) = PositionValue.calculatePositionFee(
                nonfungiblePositionManager, 
                pool, 
                baseNftId
            );
        }

        if (limitNftId != 0) {
            (limitFee0, limitFee1) = PositionValue.calculatePositionFee(
                nonfungiblePositionManager, 
                pool, 
                limitNftId
            );
        }
        
        uint256 fees0 = baseFee0 + limitFee0;
        uint256 fees1 = baseFee1 + limitFee1;

        // Subtract the portion that would be taken by _zeroBurn
        // In _zeroBurn, the fee portion is calculated as owed/fee
        fees0 = fees0 - (fees0 / fee);
        fees1 = fees1 - (fees1 / fee);
        
        // Add fees to total amounts
        total0 = total0 + fees0;
        total1 = total1 + fees1;
    }
    
    /// @return liquidity Amount of total liquidity in the base position
    /// @return amount0 Estimated amount of token0 that could be collected by
    /// burning the base position
    /// @return amount1 Estimated amount of token1 that could be collected by
    function getBasePosition() public view returns (uint128 liquidity, uint256 amount0, uint256 amount1) {
        if (baseNftId == 0) {
            return (0, 0, 0);
        }
        
        (liquidity, , ) = PositionValue.position(nonfungiblePositionManager, baseNftId);
        (amount0, amount1) = PositionValue.amountsForLiquidity(pool, baseLower, baseUpper, liquidity);
    }

    function getLimitPosition() public view returns (uint128 liquidity, uint256 amount0, uint256 amount1) {
        if (limitNftId == 0) {
            return (0, 0, 0);
        }
        
        (liquidity, , ) = PositionValue.position(nonfungiblePositionManager, limitNftId);
        (amount0, amount1) = PositionValue.amountsForLiquidity(pool, limitLower, limitUpper, liquidity);
    }


    /// @notice Internal function to approve NFT for farming and enter farming position
    /// @param tokenId The ID of the NFT position to enter into farming
    function _approveAndEnterFarming(uint256 tokenId) internal {

        // Early return if pool address is zero
        if (address(currentIncentiveKey.pool) == address(0)) {
            return;
        }

        // Get the key from incentive maker
        IncentiveKey memory key = incentiveMaker.poolToKey(address(pool));

        // Check if there's an existing deposit and if its incentive is deactivated
        bytes32 incentiveId = keccak256(abi.encode(key));

        if (incentiveId != bytes32(0) && farmingCenter.eternalFarming().isIncentiveDeactivated(incentiveId)) {
            return;
        }
        if (
            address(key.rewardToken) != address(currentIncentiveKey.rewardToken) ||
            address(key.bonusRewardToken) != address(currentIncentiveKey.bonusRewardToken) ||
            address(key.pool) != address(currentIncentiveKey.pool) ||
            key.nonce != currentIncentiveKey.nonce) {
                currentIncentiveKey = key;
            }

        // Get position information to check width
        (,,,,int24 tickLower,int24 tickUpper,,,,,) = nonfungiblePositionManager.positions(tokenId);
        
        // Get incentive parameters
        (,,, uint24 minimalPositionWidth,,) = farmingCenter.eternalFarming().incentives(incentiveId);
        
        // Check if position width is sufficient
        if (int256(tickUpper) - int256(tickLower) < int256(uint256(minimalPositionWidth))) {
            return;
        }

        nonfungiblePositionManager.approveForFarming(
            tokenId, 
            true, 
            address(farmingCenter)
        );
        
        farmingCenter.enterFarming(key, tokenId);
    }

    modifier onlyReceiver() {
        require(msg.sender == address(receiver));
        _;
    }

    /// @notice Collects farming rewards from both base and limit positions
    /// @dev Can only be called by the receiver contract. Processes rewards from both NFT positions if they exist
    /// @dev Internally calls _collectAndClaim which handles reward collection and transfer to the receiver
    function getReward() external onlyReceiver {
        if (baseNftId != 0) _collectAndClaim(baseNftId);
        if (limitNftId != 0) _collectAndClaim(limitNftId);
    }

    /// @notice Collects and claims farming rewards for a specific NFT position
    /// @dev Using 0 as amount in claimReward means claim maximum available
    /// @param tokenId The ID of the NFT position to collect rewards from
    function _collectAndClaim(uint256 tokenId) internal {
        if (tokenId == 0) return;

        // Collect rewards
        IncentiveKey memory key = _getKeyForToken(tokenId);

        // Check if we have a valid key first
        if (address(key.pool) == address(0)) {
            return;
        }

        bytes32 incentiveId = keccak256(abi.encode(key));

        (uint128 totalReward,,,,,) = farmingCenter.eternalFarming().incentives(incentiveId);
        if (totalReward == 0) return;

        (uint256 reward, uint256 bonusReward) = farmingCenter.collectRewards(key, tokenId);

        // Claim and send to MultiFeeDistribution.  0 amount is max amount.
        if (reward > 0) {
            farmingCenter.claimReward(key.rewardToken, address(receiver), 0);
        }
        
        if (bonusReward > 0) {
            farmingCenter.claimReward(key.bonusRewardToken, address(receiver), 0);

        }
        
        emit RewardsCollected(
            tokenId,
            reward,
            bonusReward
        );
    }

    /// @notice Retrieves farming incentive key for a given NFT position
    /// @dev Internal function to fetch incentive parameters from farming center 
    /// @dev First gets the incentiveId from deposits mapping, then retrieves full incentive details
    /// @param tokenId The ID of the NFT position to get the incentive key for
    /// @return IncentiveKey struct containing reward tokens, pool address and nonce for the position
    function _getKeyForToken(uint256 tokenId) internal view returns (IncentiveKey memory) {
        bytes32 incentiveId = farmingCenter.deposits(tokenId);
        
        (
            IERC20Minimal rewardToken,
            IERC20Minimal bonusRewardToken,
            IAlgebraPool pool,
            uint256 nonce
        ) = farmingCenter.incentiveKeys(incentiveId);
        
        return IncentiveKey({
            rewardToken: rewardToken,
            bonusRewardToken: bonusRewardToken,
            pool: pool,
            nonce: nonce
        });
    }
    

    /// @return tick  pool's current price tick
    function currentTick() public view returns (int24 tick) {
        (, tick, , , , ,) = pool.safelyGetStateOfAMM();
    }

    /// @param _address Array of addresses to be appended
    function setWhitelist(address _address) external onlyOwner {
        whitelistedAddress = _address;
    }

    /// @notice set fee 
    function setFee(uint8 newFee) external onlyOwner {
        require(newFee > 0);
        fee = newFee;
        emit SetFee(fee);
    }

    /// @notice set tickSpacing if updated by FactoryOwner 
    function setTickSpacing(int24 newTickSpacing) external onlyOwner {
        tickSpacing = newTickSpacing;
    } 
    /// @notice Toggle Direct Deposit
    function toggleDirectDeposit() external onlyOwner {
        directDeposit = !directDeposit;
    }

    /// @notice Update protocol addresses
    /// @param _pool New pool address
    /// @param _nonfungiblePositionManager New nonfungible position manager address
    /// @param _farmingCenter New farming center address
    function setProtocolAddresses(
        address _pool,
        address _nonfungiblePositionManager,
        address _farmingCenter
    ) external onlyOwner {
        require(
            _pool != address(0) && 
            _nonfungiblePositionManager != address(0) && 
            _farmingCenter != address(0)
        );
        
        pool = IAlgebraPool(_pool);
        nonfungiblePositionManager = INonfungiblePositionManager(_nonfungiblePositionManager);
        farmingCenter = IFarmingCenter(_farmingCenter);
    }

    /// @notice Update incentive maker and handle reward token changes
    /// @param _incentiveMaker New incentive maker address
    function updateIncentiveMaker(address _incentiveMaker) external onlyOwner {
        require(_incentiveMaker != address(0));
        

        // Update incentive maker and get new key
        incentiveMaker = IIncentiveMaker(_incentiveMaker);
        IncentiveKey memory newKey = incentiveMaker.poolToKey(address(pool));
        
        // Update tokens and key
        rewardToken = IERC20(address(newKey.rewardToken));
        bonusRewardToken = IERC20(address(newKey.bonusRewardToken));
        currentIncentiveKey = newKey;

        emit IncentiveKeyUpdated(
            address(newKey.rewardToken),
            address(newKey.bonusRewardToken),
            address(newKey.pool),
            newKey.nonce
        );
    }

    // Instead of separate functions for each NFT ID
    function setNftIds(uint256 _baseNftId, uint256 _limitNftId) external onlyOwner {
        baseNftId = _baseNftId;
        limitNftId = _limitNftId;
    }  
    
    /// @notice External function to decrease liquidity for a given position, only callable by owner. Normally never called.
    /// @param tokenId The ID of the token for which liquidity is being decreased
    /// @param liquidity The amount of liquidity to decrease
    /// @param amount0Min The minimum amount of token0 that should be received
    /// @param amount1Min The minimum amount of token1 that should be received
    /// @return amount0 The amount of token0 removed
    /// @return amount1 The amount of token1 removed
    function decreaseLiquidity(
        uint256 tokenId,
        uint128 liquidity,
        uint256 amount0Min,
        uint256 amount1Min
    ) external nonReentrant onlyOwner returns (uint256 amount0, uint256 amount1) {
        return nonfungiblePositionManager.decreaseLiquidity(
            tokenId,
            address(this),
            liquidity,
            amount0Min,
            amount1Min
        );
    }

    /// @notice External function to add liquidity for a given position, only callable by owner.  Normally never called.
    /// @param tickLower The lower tick of the position in which to add liquidity
    /// @param tickUpper The upper tick of the position in which to add liquidity
    /// @param amount0Desired The desired amount of token0 to add as liquidity
    /// @param amount1Desired The desired amount of token1 to add as liquidity
    /// @param recipient Recipient address for the position
    /// @param amount0Min Minimum amount of token0 that should be paid
    /// @param amount1Min Minimum amount of token1 that should be paid
    /// @return tokenId The ID of the newly minted position
    function mintLiquidity(
        int24 tickLower,
        int24 tickUpper,
        uint256 amount0Desired,
        uint256 amount1Desired,
        address recipient,
        uint256 amount0Min,
        uint256 amount1Min
    ) external nonReentrant onlyOwner returns (uint256 tokenId) {
        tokenId = nonfungiblePositionManager.mintLiquidity(
            address(token0),
            address(token1),
            tickLower,
            tickUpper,
            amount0Desired,
            amount1Desired,
            recipient,
            amount0Min,
            amount1Min
        );
        
        if (tokenId != 0 && address(currentIncentiveKey.pool) != address(0)) {
            _approveAndEnterFarming(tokenId);
        }
        
        return tokenId;
    }

    function transferReceiver(address newReceiver) external onlyOwner {
        receiver = IMultiFeeDistribution(newReceiver);
        emit TransferReceiver(newReceiver);
    }

    /// @notice Emergency pause of critical contract functions
    function pause() external onlyOwner {
        _pause();
    }

    /// @notice Unpause the contract
    function unpause() external onlyOwner {
        _unpause();
    }



}

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

/// @title Permissionless pool actions
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolActions {
  /// @notice Sets the initial price for the pool
  /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
  /// @dev Initialization should be done in one transaction with pool creation to avoid front-running
  /// @param initialPrice The initial sqrt price of the pool as a Q64.96
  function initialize(uint160 initialPrice) external;

  /// @notice Adds liquidity for the given recipient/bottomTick/topTick position
  /// @dev The caller of this method receives a callback in the form of IAlgebraMintCallback#algebraMintCallback
  /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
  /// on bottomTick, topTick, the amount of liquidity, and the current price.
  /// @param leftoversRecipient The address which will receive potential surplus of paid tokens
  /// @param recipient The address for which the liquidity will be created
  /// @param bottomTick The lower tick of the position in which to add liquidity
  /// @param topTick The upper tick of the position in which to add liquidity
  /// @param liquidityDesired The desired 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
  /// @return liquidityActual The actual minted amount of liquidity
  function mint(
    address leftoversRecipient,
    address recipient,
    int24 bottomTick,
    int24 topTick,
    uint128 liquidityDesired,
    bytes calldata data
  ) external returns (uint256 amount0, uint256 amount1, uint128 liquidityActual);

  /// @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 bottomTick The lower tick of the position for which to collect fees
  /// @param topTick The upper tick of the position for which to collect fees
  /// @param amount0Requested How much token0 should be withdrawn from the fees owed
  /// @param amount1Requested How much token1 should be withdrawn from the fees owed
  /// @return amount0 The amount of fees collected in token0
  /// @return amount1 The amount of fees collected in token1
  function collect(
    address recipient,
    int24 bottomTick,
    int24 topTick,
    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 bottomTick The lower tick of the position for which to burn liquidity
  /// @param topTick The upper tick of the position for which to burn liquidity
  /// @param amount How much liquidity to burn
  /// @param data Any data that should be passed through to the plugin
  /// @return amount0 The amount of token0 sent to the recipient
  /// @return amount1 The amount of token1 sent to the recipient
  function burn(int24 bottomTick, int24 topTick, uint128 amount, bytes calldata data) 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 IAlgebraSwapCallback#algebraSwapCallback
  /// @param recipient The address to receive the output of the swap
  /// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
  /// @param amountRequired The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
  /// @param limitSqrtPrice 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. If using the Router it should contain SwapRouter#SwapCallbackData
  /// @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 zeroToOne,
    int256 amountRequired,
    uint160 limitSqrtPrice,
    bytes calldata data
  ) external returns (int256 amount0, int256 amount1);

  /// @notice Swap token0 for token1, or token1 for token0 with prepayment
  /// @dev The caller of this method receives a callback in the form of IAlgebraSwapCallback#algebraSwapCallback
  /// caller must send tokens in callback before swap calculation
  /// the actually sent amount of tokens is used for further calculations
  /// @param leftoversRecipient The address which will receive potential surplus of paid tokens
  /// @param recipient The address to receive the output of the swap
  /// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
  /// @param amountToSell The amount of the swap, only positive (exact input) amount allowed
  /// @param limitSqrtPrice 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. If using the Router it should contain SwapRouter#SwapCallbackData
  /// @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 swapWithPaymentInAdvance(
    address leftoversRecipient,
    address recipient,
    bool zeroToOne,
    int256 amountToSell,
    uint160 limitSqrtPrice,
    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 IAlgebraFlashCallback#algebraFlashCallback
  /// @dev All excess tokens paid in the callback are distributed to currently in-range liquidity providers as an additional fee.
  /// If there are no in-range liquidity providers, the fee will be transferred to the first active provider in the future
  /// @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;
}

File 3 of 52 : IAlgebraPoolErrors.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;

/// @title Errors emitted by a pool
/// @notice Contains custom errors emitted by the pool
/// @dev Custom errors are separated from the common pool interface for compatibility with older versions of Solidity
interface IAlgebraPoolErrors {
  // ####  pool errors  ####

  /// @notice Emitted by the reentrancy guard
  error locked();

  /// @notice Emitted if arithmetic error occurred
  error arithmeticError();

  /// @notice Emitted if an attempt is made to initialize the pool twice
  error alreadyInitialized();

  /// @notice Emitted if an attempt is made to mint or swap in uninitialized pool
  error notInitialized();

  /// @notice Emitted if 0 is passed as amountRequired to swap function
  error zeroAmountRequired();

  /// @notice Emitted if invalid amount is passed as amountRequired to swap function
  error invalidAmountRequired();

  /// @notice Emitted if the pool received fewer tokens than it should have
  error insufficientInputAmount();

  /// @notice Emitted if there was an attempt to mint zero liquidity
  error zeroLiquidityDesired();
  /// @notice Emitted if actual amount of liquidity is zero (due to insufficient amount of tokens received)
  error zeroLiquidityActual();

  /// @notice Emitted if the pool received fewer tokens0 after flash than it should have
  error flashInsufficientPaid0();
  /// @notice Emitted if the pool received fewer tokens1 after flash than it should have
  error flashInsufficientPaid1();

  /// @notice Emitted if limitSqrtPrice param is incorrect
  error invalidLimitSqrtPrice();

  /// @notice Tick must be divisible by tickspacing
  error tickIsNotSpaced();

  /// @notice Emitted if a method is called that is accessible only to the factory owner or dedicated role
  error notAllowed();

  /// @notice Emitted if new tick spacing exceeds max allowed value
  error invalidNewTickSpacing();
  /// @notice Emitted if new community fee exceeds max allowed value
  error invalidNewCommunityFee();

  /// @notice Emitted if an attempt is made to manually change the fee value, but dynamic fee is enabled
  error dynamicFeeActive();
  /// @notice Emitted if an attempt is made by plugin to change the fee value, but dynamic fee is disabled
  error dynamicFeeDisabled();
  /// @notice Emitted if an attempt is made to change the plugin configuration, but the plugin is not connected
  error pluginIsNotConnected();
  /// @notice Emitted if a plugin returns invalid selector after hook call
  /// @param expectedSelector The expected selector
  error invalidHookResponse(bytes4 expectedSelector);

  // ####  LiquidityMath errors  ####

  /// @notice Emitted if liquidity underflows
  error liquiditySub();
  /// @notice Emitted if liquidity overflows
  error liquidityAdd();

  // ####  TickManagement errors  ####

  /// @notice Emitted if the topTick param not greater then the bottomTick param
  error topTickLowerOrEqBottomTick();
  /// @notice Emitted if the bottomTick param is lower than min allowed value
  error bottomTickLowerThanMIN();
  /// @notice Emitted if the topTick param is greater than max allowed value
  error topTickAboveMAX();
  /// @notice Emitted if the liquidity value associated with the tick exceeds MAX_LIQUIDITY_PER_TICK
  error liquidityOverflow();
  /// @notice Emitted if an attempt is made to interact with an uninitialized tick
  error tickIsNotInitialized();
  /// @notice Emitted if there is an attempt to insert a new tick into the list of ticks with incorrect indexes of the previous and next ticks
  error tickInvalidLinks();

  // ####  SafeTransfer errors  ####

  /// @notice Emitted if token transfer failed internally
  error transferFailed();

  // ####  TickMath errors  ####

  /// @notice Emitted if tick is greater than the maximum or less than the minimum allowed value
  error tickOutOfRange();
  /// @notice Emitted if price is greater than the maximum or less than the minimum allowed value
  error priceOutOfRange();
}

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

/// @title Multicall interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
    /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
    /// @dev The `msg.value` should not be trusted for any method callable from multicall.
    /// @param data The encoded function data for each of the calls to make to this contract
    /// @return results The results from each of the calls passed in via data
    function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}

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

/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of NativeToken
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
interface IPeripheryPayments {
    /// @notice Unwraps the contract's WNativeToken balance and sends it to recipient as NativeToken.
    /// @dev The amountMinimum parameter prevents malicious contracts from stealing WNativeToken from users.
    /// @param amountMinimum The minimum amount of WNativeToken to unwrap
    /// @param recipient The address receiving NativeToken
    function unwrapWNativeToken(uint256 amountMinimum, address recipient) external payable;

    /// @notice Refunds any NativeToken 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 refundNativeToken() 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.7.5;
pragma abicoder v2;

import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';

import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryPayments.sol';
import './IPeripheryImmutableState.sol';

/// @title Non-fungible token for positions
/// @notice Wraps Algebra positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
interface INonfungiblePositionManager is
    IPoolInitializer,
    IPeripheryPayments,
    IPeripheryImmutableState,
    IERC721Metadata,
    IERC721Enumerable,
    IERC721Permit
{
    /// @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 liquidityDesired The amount by which liquidity for the NFT position was increased
    /// @param actualLiquidity the actual liquidity that was added into a pool. Could differ from
    /// _liquidity_ when using FeeOnTransfer tokens
    /// @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 liquidityDesired,
        uint128 actualLiquidity,
        uint256 amount0,
        uint256 amount1,
        address pool
    );

    /// @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 Emitted if farming failed in call from NonfungiblePositionManager.
    /// @dev Should never be emitted
    /// @param tokenId The ID of corresponding token
    event FarmingFailed(uint256 indexed tokenId);

    /// @notice Emitted after farming center address change
    /// @param farmingCenterAddress The new address of connected farming center
    event FarmingCenter(address farmingCenterAddress);

    /// @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 nonce The nonce for permits
    /// @return operator The address that is approved for spending
    /// @return token0 The address of the token0 for a specific pool
    /// @return token1 The address of the token1 for a specific 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 (
            uint88 nonce,
            address operator,
            address token0,
            address token1,
            int24 tickLower,
            int24 tickUpper,
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    struct MintParams {
        address token0;
        address token1;
        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.
    /// @dev If native token is used as input, this function should be accompanied by a `refundNativeToken` in multicall to avoid potential loss of native tokens
    /// @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 liquidity delta amount as a result of the increase
    /// @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
    /// @dev If native token is used as input, this function should be accompanied by a `refundNativeToken` in multicall to avoid potential loss of native tokens
    /// @return liquidity The liquidity delta amount as a result of the increase
    /// @return amount0 The amount of token0 to achieve resulting liquidity
    /// @return amount1 The amount of token1 to achieve 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 Changes approval of token ID for farming.
    /// @param tokenId The ID of the token that is being approved / unapproved
    /// @param approve New status of approval
    /// @param farmingAddress The address of farming: used to prevent tx frontrun
    function approveForFarming(uint256 tokenId, bool approve, address farmingAddress) external payable;

    /// @notice Changes farming status of token to 'farmed' or 'not farmed'
    /// @dev can be called only by farmingCenter
    /// @param tokenId The ID of the token
    /// @param toActive The new status
    function switchFarmingStatus(uint256 tokenId, bool toActive) external;

    /// @notice Changes address of farmingCenter
    /// @dev can be called only by factory owner or NONFUNGIBLE_POSITION_MANAGER_ADMINISTRATOR_ROLE
    /// @param newFarmingCenter The new address of farmingCenter
    function setFarmingCenter(address newFarmingCenter) external;

    /// @notice Returns whether `spender` is allowed to manage `tokenId`
    /// @dev Requirement: `tokenId` must exist
    function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);

    /// @notice Returns the address of currently connected farming, if any
    /// @return The address of the farming center contract, which handles farmings logic
    function farmingCenter() external view returns (address);

    /// @notice Returns the address of farming that is approved for this token, if any
    function farmingApprovals(uint256 tokenId) external view returns (address);

    /// @notice Returns the address of farming in which this token is farmed, if any
    function tokenFarmedIn(uint256 tokenId) external view returns (address);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.0;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
 * _Available since v4.9 for `string`, `bytes`._
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

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

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

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

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}

File 9 of 52 : Constants.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.9.0;

/// @title Contains common constants for Algebra contracts
/// @dev Constants moved to the library, not the base contract, to further emphasize their constant nature
library Constants {
  uint8 internal constant RESOLUTION = 96;
  uint256 internal constant Q96 = 1 << 96;
  uint256 internal constant Q128 = 1 << 128;

  uint24 internal constant FEE_DENOMINATOR = 1e6;
  uint16 internal constant FLASH_FEE = 0.01e4; // fee for flash loan in hundredths of a bip (0.01%)
  uint16 internal constant INIT_DEFAULT_FEE = 0.05e4; // init default fee value in hundredths of a bip (0.05%)
  uint16 internal constant MAX_DEFAULT_FEE = 5e4; // max default fee value in hundredths of a bip (5%)

  int24 internal constant INIT_DEFAULT_TICK_SPACING = 60;
  int24 internal constant MAX_TICK_SPACING = 500;
  int24 internal constant MIN_TICK_SPACING = 1;

  // the frequency with which the accumulated community fees are sent to the vault
  uint32 internal constant COMMUNITY_FEE_TRANSFER_FREQUENCY = 8 hours;

  // max(uint128) / (MAX_TICK - MIN_TICK)
  uint128 internal constant MAX_LIQUIDITY_PER_TICK = 191757638537527648490752896198553;

  uint16 internal constant MAX_COMMUNITY_FEE = 1e3; // 100%
  uint256 internal constant COMMUNITY_FEE_DENOMINATOR = 1e3;
  // role that can change settings in pools
  bytes32 internal constant POOLS_ADMINISTRATOR_ROLE = keccak256('POOLS_ADMINISTRATOR');
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../Strings.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV // Deprecated in v4.8
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        uint8 v = uint8((uint256(vs) >> 255) + 27);
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\n32")
            mstore(0x1c, hash)
            message := keccak256(0x00, 0x3c)
        }
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, "\x19\x01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            data := keccak256(ptr, 0x42)
        }
    }

    /**
     * @dev Returns an Ethereum Signed Data with intended validator, created from a
     * `validator` and `data` according to the version 0 of EIP-191.
     *
     * See {recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x00", validator, data));
    }
}

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

/// @title Creates and initializes Algebra Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
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 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,
        uint160 sqrtPriceX96
    ) external payable returns (address pool);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(address from, address to, uint256 amount) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";
import "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@cryptoalgebra/integral-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
import "@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol";
import "./PositionValue.sol";

library PositionManagementLibrary {
    function mintLiquidity(
        INonfungiblePositionManager self,
        address token0,
        address token1,
        int24 tickLower,
        int24 tickUpper,
        uint256 amount0Desired,
        uint256 amount1Desired,
        address recipient,
        uint256 amount0Min,
        uint256 amount1Min
    ) internal returns (uint256 tokenId) {
        if (amount0Desired == 0 && amount1Desired == 0) return 0;
        
        (tokenId, , , ) = self.mint(INonfungiblePositionManager.MintParams({
            token0: token0,
            token1: token1,
            tickLower: tickLower,
            tickUpper: tickUpper,
            amount0Desired: amount0Desired,
            amount1Desired: amount1Desired,
            amount0Min: amount0Min,
            amount1Min: amount1Min,
            recipient: recipient,
            deadline: block.timestamp
        }));
    }

    function increaseLiquidity(
        INonfungiblePositionManager self,
        uint256 tokenId,
        uint256 amount0Desired,
        uint256 amount1Desired,
        uint256 amount0Min,
        uint256 amount1Min
    ) internal returns (uint128 liquidity) {
        if (amount0Desired == 0 && amount1Desired == 0) return 0;
        
        (liquidity, , ) = self.increaseLiquidity(INonfungiblePositionManager.IncreaseLiquidityParams({
            tokenId: tokenId,
            amount0Desired: amount0Desired,
            amount1Desired: amount1Desired,
            amount0Min: amount0Min,
            amount1Min: amount1Min,
            deadline: block.timestamp
        }));
    }

    function decreaseLiquidity(
        INonfungiblePositionManager self,
        uint256 tokenId,
        address to,
        uint128 liquidity,
        uint256 amount0Min,
        uint256 amount1Min
    ) internal returns (uint256 amount0, uint256 amount1) {
        if (liquidity == 0) return (0, 0);
        
        // First decrease the liquidity - this burns the position and records tokens owed
        (amount0, amount1) = self.decreaseLiquidity(
            INonfungiblePositionManager.DecreaseLiquidityParams({
                tokenId: tokenId,
                liquidity: liquidity,
                amount0Min: amount0Min,
                amount1Min: amount1Min,
                deadline: block.timestamp
            })
        );

        // Then collect all owed tokens (both from burned liquidity and accumulated fees)
        (uint256 collected0, uint256 collected1) = self.collect(
            INonfungiblePositionManager.CollectParams({
                tokenId: tokenId,
                recipient: to,
                amount0Max: type(uint128).max,
                amount1Max: type(uint128).max
            })
        );

        // Return total amounts (burned liquidity + collected fees)
        amount0 = collected0;
        amount1 = collected1;
    }

    function computeAndMintLiquidity(
        INonfungiblePositionManager self,
        IAlgebraPool pool,
        int24 tickLower,
        int24 tickUpper,
        uint256 token0Balance,
        uint256 token1Balance,
        uint256 amount0Min,
        uint256 amount1Min,
        address recipient
    ) internal returns (uint256 tokenId) {
        uint128 newLiquidity = PositionValue.liquidityForAmounts(
            pool,
            tickLower,
            tickUpper,
            token0Balance,
            token1Balance
        );
        
        if (newLiquidity > 0) {
            tokenId = mintLiquidity(
                self,
                address(pool.token0()),
                address(pool.token1()),
                tickLower,
                tickUpper,
                token0Balance,
                token1Balance,
                recipient,
                amount0Min,
                amount1Min
            );
        }
    }

    function computeAndIncreaseLiquidity(
        INonfungiblePositionManager self,
        IAlgebraPool pool,
        uint256 tokenId,
        int24 tickLower,
        int24 tickUpper,
        uint256 token0Balance,
        uint256 token1Balance,
        uint256 amount0Min,
        uint256 amount1Min
    ) internal returns (uint128 addedLiquidity) {
        uint128 newLiquidity = PositionValue.liquidityForAmounts(
            pool,
            tickLower,
            tickUpper,
            token0Balance,
            token1Balance
        );
        
        if (newLiquidity > 0) {
            addedLiquidity = increaseLiquidity(
                self,
                tokenId,
                token0Balance,
                token1Balance,
                amount0Min,
                amount1Min
            );
        }
    }


    struct DirectDepositParams {
        IAlgebraPool pool;
        uint256 baseNftId;
        uint256 limitNftId;
        int24 baseLower;
        int24 baseUpper;
        int24 limitLower;
        int24 limitUpper;
        uint256 deposit0;
        uint256 deposit1;
        uint256[4] minAmounts;
    }

    function computeAndDirectDeposit(
        INonfungiblePositionManager self,
        DirectDepositParams memory params
    ) internal returns (uint256 used0, uint256 used1) {
        // Calculate amounts for base position
        if (params.baseNftId != 0) {
            // Get actual amounts that can be used in the base position
            (uint256 base0, uint256 base1) = PositionValue.amountsForLiquidity(
                params.pool,
                params.baseLower,
                params.baseUpper,
                PositionValue.liquidityForAmounts(
                    params.pool,
                    params.baseLower,
                    params.baseUpper,
                    params.deposit0,
                    params.deposit1
                )
            );
            
            if (base0 > 0 || base1 > 0) {
                // Only use what the position can actually accept
                used0 = base0 > params.deposit0 ? params.deposit0 : base0;
                used1 = base1 > params.deposit1 ? params.deposit1 : base1;
                
                increaseLiquidity(
                    self,
                    params.baseNftId,
                    used0,
                    used1,
                    params.minAmounts[0],
                    params.minAmounts[1]
                );
            }
        }

        // Calculate remaining amounts for limit position
        uint256 remaining0 = params.deposit0 > used0 ? params.deposit0 - used0 : 0;
        uint256 remaining1 = params.deposit1 > used1 ? params.deposit1 - used1 : 0;

        if ((remaining0 > 0 || remaining1 > 0) && params.limitNftId != 0) {
            // Get actual amounts that can be used in the limit position
            (uint256 limit0, uint256 limit1) = PositionValue.amountsForLiquidity(
                params.pool,
                params.limitLower,
                params.limitUpper,
                PositionValue.liquidityForAmounts(
                    params.pool,
                    params.limitLower,
                    params.limitUpper,
                    remaining0,
                    remaining1
                )
            );
            
            if (limit0 > 0 || limit1 > 0) {
                // Only use what's available and what the position can accept
                uint256 toAdd0 = limit0 > remaining0 ? remaining0 : limit0;
                uint256 toAdd1 = limit1 > remaining1 ? remaining1 : limit1;
                
                uint128 addedLiquidity = increaseLiquidity(
                    self,
                    params.limitNftId,
                    toAdd0,
                    toAdd1,
                    params.minAmounts[2],
                    params.minAmounts[3]
                );
                
                if (addedLiquidity > 0) {
                    used0 += toAdd0;
                    used1 += toAdd1;
                }
            }
        }
    }

    function withdrawPositions(
        INonfungiblePositionManager self,
        uint256 baseNftId,
        uint256 limitNftId,
        uint256 shares,
        address to,
        uint256 totalSupply,
        uint256[4] memory minAmounts
    ) internal returns (uint256 base0, uint256 base1, uint256 limit0, uint256 limit1) {
        if (baseNftId != 0) {
            (base0, base1) = decreaseLiquidity(
                self,
                baseNftId,
                to,
                PositionValue.liquidityForShares(self, baseNftId, shares, totalSupply),
                minAmounts[0],
                minAmounts[1]
            );
        }

        if (limitNftId != 0) {
            (limit0, limit1) = decreaseLiquidity(
                self,
                limitNftId,
                to,
                PositionValue.liquidityForShares(self, limitNftId, shares, totalSupply),
                minAmounts[2],
                minAmounts[3]
            );
        }
    }

}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

// 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 permissioned addresses
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolPermissionedActions {
  /// @notice Set the community's % share of the fees. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
  /// @param newCommunityFee The new community fee percent in thousandths (1e-3)
  function setCommunityFee(uint16 newCommunityFee) external;

  /// @notice Set the new tick spacing values. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
  /// @param newTickSpacing The new tick spacing value
  function setTickSpacing(int24 newTickSpacing) external;

  /// @notice Set the new plugin address. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
  /// @param newPluginAddress The new plugin address
  function setPlugin(address newPluginAddress) external;

  /// @notice Set new plugin config. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
  /// @param newConfig In the new configuration of the plugin,
  /// each bit of which is responsible for a particular hook.
  function setPluginConfig(uint8 newConfig) external;

  /// @notice Set new community fee vault address. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
  /// @dev Community fee vault receives collected community fees.
  /// **accumulated but not yet sent to the vault community fees once will be sent to the `newCommunityVault` address**
  /// @param newCommunityVault The address of new community fee vault
  function setCommunityVault(address newCommunityVault) external;

  /// @notice Set new pool fee. Can be called by owner if dynamic fee is disabled.
  /// Called by the plugin if dynamic fee is enabled
  /// @param newFee The new fee value
  function setFee(uint16 newFee) external;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

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

pragma solidity ^0.8.0;

import "../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 The interface for the Algebra farming plugin
/// @dev This contract used for virtual pools in farms
interface IFarmingPlugin {
  /// @notice Emitted when new activeIncentive is set
  /// @param newIncentive The address of the new incentive
  event Incentive(address newIncentive);

  /// @notice Returns the address of the pool the plugin is created for
  /// @return address of the pool
  function pool() external view returns (address);

  /// @notice Connects or disconnects an incentive.
  /// @dev Only farming can connect incentives.
  /// The one who connected it and the current farming has the right to disconnect the incentive.
  /// @param newIncentive The address associated with the incentive or zero address
  function setIncentive(address newIncentive) external;

  /// @notice Checks if the incentive is connected to pool
  /// @dev Returns false if the plugin has a different incentive set, the plugin is not connected to the pool,
  /// or the plugin configuration is incorrect.
  /// @param targetIncentive The address of the incentive to be checked
  /// @return Indicates whether the target incentive is active
  function isIncentiveConnected(address targetIncentive) external view returns (bool);

  /// @notice Returns the address of active incentive
  /// @dev if there is no active incentive at the moment, incentiveAddress would be equal to address(0)
  /// @return  The address associated with the current active incentive
  function incentive() external view returns (address);
}

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

/// @title Pool state that can change
/// @dev Important security note: when using this data by external contracts, it is necessary to take into account the possibility
/// of manipulation (including read-only reentrancy).
/// This interface is based on the UniswapV3 interface, credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolState {
  /// @notice Safely get most important state values of Algebra Integral AMM
  /// @dev Several values exposed as a single method to save gas when accessed externally.
  /// **Important security note: this method checks reentrancy lock and should be preferred in most cases**.
  /// @return sqrtPrice The current price of the pool as a sqrt(dToken1/dToken0) Q64.96 value
  /// @return tick The current global tick of the pool. May not always be equal to SqrtTickMath.getTickAtSqrtRatio(price) if the price is on a tick boundary
  /// @return lastFee The current (last known) pool fee value in hundredths of a bip, i.e. 1e-6 (so '100' is '0.01%'). May be obsolete if using dynamic fee plugin
  /// @return pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic
  /// @return activeLiquidity  The currently in-range liquidity available to the pool
  /// @return nextTick The next initialized tick after current global tick
  /// @return previousTick The previous initialized tick before (or at) current global tick
  function safelyGetStateOfAMM()
    external
    view
    returns (uint160 sqrtPrice, int24 tick, uint16 lastFee, uint8 pluginConfig, uint128 activeLiquidity, int24 nextTick, int24 previousTick);

  /// @notice Allows to easily get current reentrancy lock status
  /// @dev can be used to prevent read-only reentrancy.
  /// This method just returns `globalState.unlocked` value
  /// @return unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false
  function isUnlocked() external view returns (bool unlocked);

  // ! IMPORTANT security note: the pool state can be manipulated.
  // ! The following methods do not check reentrancy lock themselves.

  /// @notice The globalState structure in the pool stores many values but requires only one slot
  /// and is exposed as a single method to save gas when accessed externally.
  /// @dev **important security note: caller should check `unlocked` flag to prevent read-only reentrancy**
  /// @return price The current price of the pool as a sqrt(dToken1/dToken0) 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(price) if the price is on a tick boundary
  /// @return lastFee The current (last known) pool fee value in hundredths of a bip, i.e. 1e-6 (so '100' is '0.01%'). May be obsolete if using dynamic fee plugin
  /// @return pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic
  /// @return communityFee The community fee represented as a percent of all collected fee in thousandths, i.e. 1e-3 (so 100 is 10%)
  /// @return unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false
  function globalState() external view returns (uint160 price, int24 tick, uint16 lastFee, uint8 pluginConfig, uint16 communityFee, bool unlocked);

  /// @notice Look up information about a specific tick in the pool
  /// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
  /// @param tick The tick to look up
  /// @return liquidityTotal The total amount of position liquidity that uses the pool either as tick lower or tick upper
  /// @return liquidityDelta How much liquidity changes when the pool price crosses the tick
  /// @return prevTick The previous tick in tick list
  /// @return nextTick The next tick in tick list
  /// @return outerFeeGrowth0Token The fee growth on the other side of the tick from the current tick in token0
  /// @return outerFeeGrowth1Token The fee growth on the other side of the tick from the current tick in token1
  /// 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 (
      uint256 liquidityTotal,
      int128 liquidityDelta,
      int24 prevTick,
      int24 nextTick,
      uint256 outerFeeGrowth0Token,
      uint256 outerFeeGrowth1Token
    );

  /// @notice The timestamp of the last sending of tokens to community vault
  /// @return The timestamp truncated to 32 bits
  function communityFeeLastTimestamp() external view returns (uint32);

  /// @notice The amounts of token0 and token1 that will be sent to the vault
  /// @dev Will be sent COMMUNITY_FEE_TRANSFER_FREQUENCY after communityFeeLastTimestamp
  /// @return communityFeePending0 The amount of token0 that will be sent to the vault
  /// @return communityFeePending1 The amount of token1 that will be sent to the vault
  function getCommunityFeePending() external view returns (uint128 communityFeePending0, uint128 communityFeePending1);

  /// @notice Returns the address of currently used plugin
  /// @dev The plugin is subject to change
  /// @return pluginAddress The address of currently used plugin
  function plugin() external view returns (address pluginAddress);

  /// @notice The contract to which community fees are transferred
  /// @return communityVaultAddress The communityVault address
  function communityVault() external view returns (address communityVaultAddress);

  /// @notice Returns 256 packed tick initialized boolean values. See TickTree for more information
  /// @param wordPosition Index of 256-bits word with ticks
  /// @return The 256-bits word with packed ticks info
  function tickTable(int16 wordPosition) external view returns (uint256);

  /// @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
  /// @return The fee growth accumulator for token0
  function totalFeeGrowth0Token() 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
  /// @return The fee growth accumulator for token1
  function totalFeeGrowth1Token() external view returns (uint256);

  /// @notice The current pool fee value
  /// @dev In case dynamic fee is enabled in the pool, this method will call the plugin to get the current fee.
  /// If the plugin implements complex fee logic, this method may return an incorrect value or revert.
  /// In this case, see the plugin implementation and related documentation.
  /// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
  /// @return currentFee The current pool fee value in hundredths of a bip, i.e. 1e-6
  function fee() external view returns (uint16 currentFee);

  /// @notice The tracked token0 and token1 reserves of pool
  /// @dev If at any time the real balance is larger, the excess will be transferred to liquidity providers as additional fee.
  /// If the balance exceeds uint128, the excess will be sent to the communityVault.
  /// @return reserve0 The last known reserve of token0
  /// @return reserve1 The last known reserve of token1
  function getReserves() external view returns (uint128 reserve0, uint128 reserve1);

  /// @notice Returns the information about a position by the position's key
  /// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
  /// @param key The position's key is a packed concatenation of the owner address, bottomTick and topTick indexes
  /// @return liquidity The amount of liquidity in the position
  /// @return innerFeeGrowth0Token Fee growth of token0 inside the tick range as of the last mint/burn/poke
  /// @return innerFeeGrowth1Token Fee growth of token1 inside the tick range as of the last mint/burn/poke
  /// @return fees0 The computed amount of token0 owed to the position as of the last mint/burn/poke
  /// @return fees1 The computed amount of token1 owed to the position as of the last mint/burn/poke
  function positions(
    bytes32 key
  ) external view returns (uint256 liquidity, uint256 innerFeeGrowth0Token, uint256 innerFeeGrowth1Token, uint128 fees0, uint128 fees1);

  /// @notice The currently in range liquidity available to the pool
  /// @dev This value has no relationship to the total liquidity across all ticks.
  /// Returned value cannot exceed type(uint128).max
  /// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
  /// @return The current in range liquidity
  function liquidity() external view returns (uint128);

  /// @notice The current tick spacing
  /// @dev Ticks can only be initialized by new mints at multiples of this value
  /// e.g.: a tickSpacing of 60 means ticks can be initialized every 60th tick, i.e., ..., -120, -60, 0, 60, 120, ...
  /// However, tickspacing can be changed after the ticks have been initialized.
  /// This value is an int24 to avoid casting even though it is always positive.
  /// @return The current tick spacing
  function tickSpacing() external view returns (int24);

  /// @notice The previous initialized tick before (or at) current global tick
  /// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
  /// @return The previous initialized tick
  function prevTickGlobal() external view returns (int24);

  /// @notice The next initialized tick after current global tick
  /// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
  /// @return The next initialized tick
  function nextTickGlobal() external view returns (int24);

  /// @notice The root of tick search tree
  /// @dev Each bit corresponds to one node in the second layer of tick tree: '1' if node has at least one active bit.
  /// **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
  /// @return The root of tick search tree as bitmap
  function tickTreeRoot() external view returns (uint32);

  /// @notice The second layer of tick search tree
  /// @dev Each bit in node corresponds to one node in the leafs layer (`tickTable`) of tick tree: '1' if leaf has at least one active bit.
  /// **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
  /// @return The node of tick search tree second layer
  function tickTreeSecondLayer(int16) external view returns (uint256);
}

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

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 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 ERC721 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 ERC721
     * 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 caller.
     *
     * 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 v4.9.0) (utils/cryptography/EIP712.sol)

pragma solidity ^0.8.8;

import "./ECDSA.sol";
import "../ShortStrings.sol";
import "../../interfaces/IERC5267.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
 * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
 * they need in their contracts using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
 * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
 * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
 *
 * _Available since v3.4._
 *
 * @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
 */
abstract contract EIP712 is IERC5267 {
    using ShortStrings for *;

    bytes32 private constant _TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _cachedDomainSeparator;
    uint256 private immutable _cachedChainId;
    address private immutable _cachedThis;

    bytes32 private immutable _hashedName;
    bytes32 private immutable _hashedVersion;

    ShortString private immutable _name;
    ShortString private immutable _version;
    string private _nameFallback;
    string private _versionFallback;

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        _name = name.toShortStringWithFallback(_nameFallback);
        _version = version.toShortStringWithFallback(_versionFallback);
        _hashedName = keccak256(bytes(name));
        _hashedVersion = keccak256(bytes(version));

        _cachedChainId = block.chainid;
        _cachedDomainSeparator = _buildDomainSeparator();
        _cachedThis = address(this);
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
            return _cachedDomainSeparator;
        } else {
            return _buildDomainSeparator();
        }
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(_TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
    }

    /**
     * @dev See {EIP-5267}.
     *
     * _Available since v4.9._
     */
    function eip712Domain()
        public
        view
        virtual
        override
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        )
    {
        return (
            hex"0f", // 01111
            _name.toStringWithFallback(_nameFallback),
            _version.toStringWithFallback(_versionFallback),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }
}

File 24 of 52 : IHypervisorState.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;

import "@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IIncentiveMaker.sol";

interface IHypervisorState {
    struct RewardData {
        uint256 rewardAmount; 
        uint256 bonusRewardAmount;
        uint256 lastTimeUpdated;
        uint256 rewardPerToken;
        uint256 bonusRewardPerToken;
    }

    struct UserData {
        uint256 tokenAmount;
        uint256 lastTimeUpdated;
        uint256 rewardTokenClaimable;
        uint256 bonusRewardTokenClaimable;
        uint256 rewardPerToken;
        uint256 bonusRewardPerToken;
    }

    event Deposit(
        address indexed sender,
        address indexed to,
        uint256 shares,
        uint256 amount0,
        uint256 amount1
    );

    event InitialMint(
        uint256 baseNftId,
        uint256 limitNftId
    );

    event Withdraw(
        address indexed sender,
        address indexed to,
        uint256 shares,
        uint256 amount0,
        uint256 amount1
    );

    event Rebalance(
        int24 tick,
        uint256 totalAmount0,
        uint256 totalAmount1,
        uint256 feeAmount0,
        uint256 feeAmount1,
        uint256 totalSupply
    );

    event RewardsCollected(
        uint256 indexed tokenId,
        uint256 reward,          // Just show claimed reward amount
        uint256 bonusReward      // Just show claimed bonus reward amount
    );

    event RewardPaid(
        address indexed user,
        IERC20 indexed rewardToken,
        uint256 amount
    );
    
    // Add new event for key mismatch
    event IncentiveKeyMismatch(uint256 tokenId, IncentiveKey foundKey, IncentiveKey currentKey);
    event IncentiveKeyUpdated(
        address rewardToken,
        address bonusRewardToken,
        address pool,
        uint256 nonce
    );
    event RewardsTransferredToOwner(
        address indexed rewardToken,
        address indexed bonusRewardToken,
        uint256 rewardAmount,
        uint256 bonusRewardAmount
    );
    event ClaimPauseStateChanged(bool isPaused);
    event RewardTokenTransferred(address token, uint256 amount);
    event BonusRewardTokenTransferred(address token, uint256 amount);

    event ZeroBurn(uint8 fee, uint256 fees0, uint256 fees1);
    
    event SetFee(uint8 newFee);

    event TransferReceiver(address newReceiver);

    error ZeroAddress();
    error ZeroDeposits();
    error ZeroFee();
    error NotOwner();
    error ZeroShares();
    error InvalidRecipient();
    error InvalidTokens();
    error NotWhitelisted();
    error OnlyReceiver();
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

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

    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
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // 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: GPL-2.0-or-later
pragma solidity >=0.8.4 <0.9.0;

import '../interfaces/pool/IAlgebraPoolErrors.sol';

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries
library TickMath {
  /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
  int24 internal constant MIN_TICK = -887272;
  /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
  int24 internal constant MAX_TICK = -MIN_TICK;

  /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
  uint160 internal constant MIN_SQRT_RATIO = 4295128739;
  /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
  uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;

  /// @notice Calculates sqrt(1.0001^tick) * 2^96
  /// @dev Throws if |tick| > max tick
  /// @param tick The input tick for the above formula
  /// @return price A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
  /// at the given tick
  function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 price) {
    unchecked {
      // get abs value
      int24 absTickMask = tick >> (24 - 1);
      uint256 absTick = uint24((tick + absTickMask) ^ absTickMask);
      if (absTick > uint24(MAX_TICK)) revert IAlgebraPoolErrors.tickOutOfRange();

      uint256 ratio = 0x100000000000000000000000000000000;
      if (absTick & 0x1 != 0) ratio = 0xfffcb933bd6fad37aa2d162d1a594001;
      if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
      if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
      if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
      if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
      if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
      if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
      if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
      if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
      if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
      if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
      if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
      if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
      if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
      if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
      if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
      if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
      if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
      if (absTick >= 0x40000) {
        if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
        if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
      }

      if (tick > 0) {
        assembly {
          ratio := div(not(0), ratio)
        }
      }

      // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
      // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
      // we round up in the division so getTickAtSqrtRatio of the output price is always consistent
      price = uint160((ratio + 0xFFFFFFFF) >> 32);
    }
  }

  /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
  /// @dev Throws in case price < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
  /// ever return.
  /// @param price The sqrt ratio for which to compute the tick as a Q64.96
  /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
  function getTickAtSqrtRatio(uint160 price) internal pure returns (int24 tick) {
    unchecked {
      // second inequality must be >= because the price can never reach the price at the max tick
      if (price < MIN_SQRT_RATIO || price >= MAX_SQRT_RATIO) revert IAlgebraPoolErrors.priceOutOfRange();
      uint256 ratio = uint256(price) << 32;

      uint256 r = ratio;
      uint256 msb;

      assembly {
        let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
        msb := or(msb, f)
        r := shr(f, r)
      }
      assembly {
        let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
        msb := or(msb, f)
        r := shr(f, r)
      }
      assembly {
        let f := shl(5, gt(r, 0xFFFFFFFF))
        msb := or(msb, f)
        r := shr(f, r)
      }
      assembly {
        let f := shl(4, gt(r, 0xFFFF))
        msb := or(msb, f)
        r := shr(f, r)
      }
      assembly {
        let f := shl(3, gt(r, 0xFF))
        msb := or(msb, f)
        r := shr(f, r)
      }
      assembly {
        let f := shl(2, gt(r, 0xF))
        msb := or(msb, f)
        r := shr(f, r)
      }
      assembly {
        let f := shl(1, gt(r, 0x3))
        msb := or(msb, f)
        r := shr(f, r)
      }
      assembly {
        let f := gt(r, 0x1)
        msb := or(msb, f)
      }

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

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

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

      int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number

      int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
      int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);

      tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= price ? tickHi : tickLow;
    }
  }
}

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

import '@cryptoalgebra/integral-core/contracts/libraries/FullMath.sol';
import '@cryptoalgebra/integral-core/contracts/libraries/Constants.sol';

/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
library LiquidityAmounts {
    /// @notice Downcasts uint256 to uint128
    /// @param x The uint258 to be downcasted
    /// @return y The passed value, downcasted to uint128
    function toUint128(uint256 x) private pure returns (uint128 y) {
        require((y = uint128(x)) == x);
    }

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

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

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

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

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

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

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

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

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

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

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

/// @title Pool state that never changes
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolImmutables {
  /// @notice The Algebra factory contract, which must adhere to the IAlgebraFactory 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 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: MIT

pragma solidity 0.8.20;
pragma abicoder v2;

import "@cryptoalgebra/integral-farming/contracts/base/IncentiveKey.sol";

interface IIncentiveMaker{

   function poolToKey(address pool) external view returns (IncentiveKey memory);
    
}

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

/// @title Minimal ERC20 interface for Algebra
/// @notice Contains a subset of the full ERC20 interface that is used in Algebra
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IERC20Minimal {
  /// @notice Returns the balance of a token
  /// @param account The account for which to look up the number of tokens it has, i.e. its balance
  /// @return The number of tokens held by the account
  function balanceOf(address account) external view returns (uint256);

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

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

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

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

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

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

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

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

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

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

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

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

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

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

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

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

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

  /// @notice Returns ceil(x / y)
  /// @dev division by 0 has unspecified behavior, and must be checked externally
  /// @param x The dividend
  /// @param y The divisor
  /// @return z The quotient, ceil(x / y)
  function unsafeDivRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
    assembly {
      z := add(div(x, y), gt(mod(x, y), 0))
    }
  }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol)

pragma solidity ^0.8.8;

import "./StorageSlot.sol";

// | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
// | length  | 0x                                                              BB |
type ShortString is bytes32;

/**
 * @dev This library provides functions to convert short memory strings
 * into a `ShortString` type that can be used as an immutable variable.
 *
 * Strings of arbitrary length can be optimized using this library if
 * they are short enough (up to 31 bytes) by packing them with their
 * length (1 byte) in a single EVM word (32 bytes). Additionally, a
 * fallback mechanism can be used for every other case.
 *
 * Usage example:
 *
 * ```solidity
 * contract Named {
 *     using ShortStrings for *;
 *
 *     ShortString private immutable _name;
 *     string private _nameFallback;
 *
 *     constructor(string memory contractName) {
 *         _name = contractName.toShortStringWithFallback(_nameFallback);
 *     }
 *
 *     function name() external view returns (string memory) {
 *         return _name.toStringWithFallback(_nameFallback);
 *     }
 * }
 * ```
 */
library ShortStrings {
    // Used as an identifier for strings longer than 31 bytes.
    bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;

    error StringTooLong(string str);
    error InvalidShortString();

    /**
     * @dev Encode a string of at most 31 chars into a `ShortString`.
     *
     * This will trigger a `StringTooLong` error is the input string is too long.
     */
    function toShortString(string memory str) internal pure returns (ShortString) {
        bytes memory bstr = bytes(str);
        if (bstr.length > 31) {
            revert StringTooLong(str);
        }
        return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
    }

    /**
     * @dev Decode a `ShortString` back to a "normal" string.
     */
    function toString(ShortString sstr) internal pure returns (string memory) {
        uint256 len = byteLength(sstr);
        // using `new string(len)` would work locally but is not memory safe.
        string memory str = new string(32);
        /// @solidity memory-safe-assembly
        assembly {
            mstore(str, len)
            mstore(add(str, 0x20), sstr)
        }
        return str;
    }

    /**
     * @dev Return the length of a `ShortString`.
     */
    function byteLength(ShortString sstr) internal pure returns (uint256) {
        uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
        if (result > 31) {
            revert InvalidShortString();
        }
        return result;
    }

    /**
     * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
     */
    function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
        if (bytes(value).length < 32) {
            return toShortString(value);
        } else {
            StorageSlot.getStringSlot(store).value = value;
            return ShortString.wrap(_FALLBACK_SENTINEL);
        }
    }

    /**
     * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
     */
    function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
        if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
            return toString(value);
        } else {
            return store;
        }
    }

    /**
     * @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
     *
     * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
     * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
     */
    function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
        if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
            return byteLength(value);
        } else {
            return bytes(store).length;
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)

pragma solidity ^0.8.0;

/**
 * @title Counters
 * @author Matt Condon (@shrugs)
 * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
 * of elements in a mapping, issuing ERC721 ids, or counting request ids.
 *
 * Include with `using Counters for Counters.Counter;`
 */
library Counters {
    struct Counter {
        // This variable should never be directly accessed by users of the library: interactions must be restricted to
        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
        // this feature: see https://github.com/ethereum/solidity/issues/4637
        uint256 _value; // default: 0
    }

    function current(Counter storage counter) internal view returns (uint256) {
        return counter._value;
    }

    function increment(Counter storage counter) internal {
        unchecked {
            counter._value += 1;
        }
    }

    function decrement(Counter storage counter) internal {
        uint256 value = counter._value;
        require(value > 0, "Counter: decrement overflow");
        unchecked {
            counter._value = value - 1;
        }
    }

    function reset(Counter storage counter) internal {
        counter._value = 0;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * 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[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

File 36 of 52 : IAlgebraPool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;

import './pool/IAlgebraPoolImmutables.sol';
import './pool/IAlgebraPoolState.sol';
import './pool/IAlgebraPoolActions.sol';
import './pool/IAlgebraPoolPermissionedActions.sol';
import './pool/IAlgebraPoolEvents.sol';
import './pool/IAlgebraPoolErrors.sol';

/// @title The interface for a Algebra Pool
/// @dev The pool interface is broken up into many smaller pieces.
/// This interface includes custom error definitions and cannot be used in older versions of Solidity.
/// For older versions of Solidity use #IAlgebraPoolLegacy
/// Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPool is
  IAlgebraPoolImmutables,
  IAlgebraPoolState,
  IAlgebraPoolActions,
  IAlgebraPoolPermissionedActions,
  IAlgebraPoolEvents,
  IAlgebraPoolErrors
{
  // used only for combining interfaces
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;

import "@cryptoalgebra/integral-core/contracts/libraries/TickMath.sol";
import "@cryptoalgebra/integral-periphery/contracts/libraries/LiquidityAmounts.sol";
import "@cryptoalgebra/integral-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
import "@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol";

library PositionValue {
    uint256 internal constant Q128 = 1 << 128;
    function amountsForLiquidity(
        IAlgebraPool pool,
        int24 tickLower,
        int24 tickUpper,
        uint128 liquidity
    ) internal view returns (uint256, uint256) {
        (uint160 sqrtRatioX96, , , , , ,) = pool.safelyGetStateOfAMM();
        return
            LiquidityAmounts.getAmountsForLiquidity(
                sqrtRatioX96,
                TickMath.getSqrtRatioAtTick(tickLower),
                TickMath.getSqrtRatioAtTick(tickUpper),
                liquidity
            );
    }

    function liquidityForAmounts(
        IAlgebraPool pool,
        int24 tickLower,
        int24 tickUpper,
        uint256 amount0,
        uint256 amount1
    ) internal view returns (uint128) {
        (uint160 sqrtRatioX96, , , , , ,) = pool.safelyGetStateOfAMM();
        return
            LiquidityAmounts.getLiquidityForAmounts(
                sqrtRatioX96,
                TickMath.getSqrtRatioAtTick(tickLower),
                TickMath.getSqrtRatioAtTick(tickUpper),
                amount0,
                amount1
            );
    }

    function position(
        INonfungiblePositionManager positionManager,
        uint256 tokenId
    ) internal view returns (
        uint128 liquidity,
        uint128 tokensOwed0,
        uint128 tokensOwed1
    ) {
        if (tokenId == 0) {
            return (0, 0, 0);
        }

        ( , , , , , , liquidity, , , tokensOwed0, tokensOwed1) = positionManager.positions(tokenId);
    }
    
    function liquidityForShares(
        INonfungiblePositionManager positionManager,
        uint256 tokenId, 
        uint256 shares,
        uint256 totalSupply
    ) internal view returns (uint128 liquidity) {
        ( , , , , , , uint128 positionLiquidity, , , , ) = positionManager.positions(tokenId);
        // x <= type(uint128).max check
        uint256 result = FullMath.mulDiv(uint256(positionLiquidity), shares, totalSupply);
        require(result <= type(uint128).max);
        return uint128(result);
    }

    function calculatePositionFee(
        INonfungiblePositionManager positionManager,
        IAlgebraPool pool,    
        uint256 tokenId
    ) internal view returns (uint256 fee0, uint256 fee1) {
        ( , , , , int24 tickLower, int24 tickUpper, uint128 liquidityBefore, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1) = positionManager.positions(tokenId);

        // Early return if no liquidity
        if (liquidityBefore == 0) return (uint256(tokensOwed0), uint256(tokensOwed1));

        // Initial fee assignments outside unchecked
        fee0 = uint256(tokensOwed0);
        fee1 = uint256(tokensOwed1);

        (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = getFeeGrowthInside(pool, tickLower, tickUpper);

        unchecked {
            if (feeGrowthInside0X128 != feeGrowthInside0LastX128) {
                fee0 += FullMath.mulDiv(feeGrowthInside0X128 - feeGrowthInside0LastX128,liquidityBefore,Q128);
            }
            if (feeGrowthInside1X128 != feeGrowthInside1LastX128) {
                fee1 += FullMath.mulDiv(feeGrowthInside1X128 - feeGrowthInside1LastX128,liquidityBefore,Q128);
            }
        }
    }

    function getFeeGrowthInside(
        IAlgebraPool pool,
        int24 bottomTick,
        int24 topTick
    ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) {
        (, int24 currentTick, , , , ,) = pool.safelyGetStateOfAMM(); 
        
        (,,,, uint256 outerFeeGrowth0TokenLower, uint256 outerFeeGrowth1TokenLower) = pool.ticks(bottomTick);
        (,,,, uint256 outerFeeGrowth0TokenUpper, uint256 outerFeeGrowth1TokenUpper) = pool.ticks(topTick);
        
        uint256 feeGrowthGlobal0X128 = pool.totalFeeGrowth0Token();
        uint256 feeGrowthGlobal1X128 = pool.totalFeeGrowth1Token();

        unchecked {
            if (currentTick < bottomTick) {
                feeGrowthInside0X128 = outerFeeGrowth0TokenLower - outerFeeGrowth0TokenUpper;
                feeGrowthInside1X128 = outerFeeGrowth1TokenLower - outerFeeGrowth1TokenUpper;
            } else if (currentTick < topTick) {
                feeGrowthInside0X128 = feeGrowthGlobal0X128 - outerFeeGrowth0TokenLower - outerFeeGrowth0TokenUpper;
                feeGrowthInside1X128 = feeGrowthGlobal1X128 - outerFeeGrowth1TokenLower - outerFeeGrowth1TokenUpper;
            } else {
                feeGrowthInside0X128 = outerFeeGrowth0TokenUpper - outerFeeGrowth0TokenLower;
                feeGrowthInside1X128 = outerFeeGrowth1TokenUpper - outerFeeGrowth1TokenLower;
            }
        }
    }


}

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

import '@cryptoalgebra/integral-core/contracts/interfaces/IERC20Minimal.sol';

import '@cryptoalgebra/integral-periphery/contracts/interfaces/IMulticall.sol';
import '@cryptoalgebra/integral-periphery/contracts/interfaces/INonfungiblePositionManager.sol';

import '@cryptoalgebra/integral-base-plugin/contracts/interfaces/plugins/IFarmingPlugin.sol';

import '../base/IncentiveKey.sol';
import '../interfaces/IAlgebraEternalFarming.sol';

/// @title Algebra main farming contract interface
/// @dev Manages users deposits and performs entry, exit and other actions.
interface IFarmingCenter is IMulticall {
  /// @notice Returns current virtual pool address for Algebra pool
  function virtualPoolAddresses(address poolAddress) external view returns (address virtualPoolAddresses);

  /// @notice The nonfungible position manager with which this farming contract is compatible
  function nonfungiblePositionManager() external view returns (INonfungiblePositionManager);

  /// @notice The eternal farming contract
  function eternalFarming() external view returns (IAlgebraEternalFarming);

  /// @notice The Algebra poolDeployer contract
  function algebraPoolDeployer() external view returns (address);

  /// @notice Returns information about a deposited NFT
  /// @param tokenId The ID of the deposit (and token) that is being transferred
  /// @return eternalIncentiveId The id of eternal incentive that is active for this NFT
  function deposits(uint256 tokenId) external view returns (bytes32 eternalIncentiveId);

  /// @notice Returns incentive key for specific incentiveId
  /// @param incentiveId The hash of incentive key
  function incentiveKeys(
    bytes32 incentiveId
  ) external view returns (IERC20Minimal rewardToken, IERC20Minimal bonusRewardToken, IAlgebraPool pool, uint256 nonce);

  /// @notice Used to connect incentive to compatible AlgebraPool plugin
  /// @dev only farming can do it
  /// Will revert if something is already connected to the plugin
  /// @param virtualPool The virtual pool to be connected, must not be zero address
  /// @param plugin The Algebra farming plugin
  function connectVirtualPoolToPlugin(address virtualPool, IFarmingPlugin plugin) external;

  /// @notice Used to disconnect incentive from compatible AlgebraPool plugin
  /// @dev only farming can do it.
  /// If the specified virtual pool is not connected to the plugin, nothing will happen
  /// @param virtualPool The virtual pool to be disconnected, must not be zero address
  /// @param plugin The Algebra farming plugin
  function disconnectVirtualPoolFromPlugin(address virtualPool, IFarmingPlugin plugin) external;

  /// @notice Enters in incentive (eternal farming) with NFT-position token
  /// @dev msg.sender must be the owner of NFT
  /// @param key The incentive key
  /// @param tokenId The id of position NFT
  function enterFarming(IncentiveKey memory key, uint256 tokenId) external;

  /// @notice Exits from incentive (eternal farming) with NFT-position token
  /// @dev msg.sender must be the owner of NFT
  /// @param key The incentive key
  /// @param tokenId The id of position NFT
  function exitFarming(IncentiveKey memory key, uint256 tokenId) external;

  /// @notice Used to collect reward from eternal farming. Then reward can be claimed.
  /// @param key The incentive key
  /// @param tokenId The id of position NFT
  /// @return reward The amount of collected reward
  /// @return bonusReward The amount of collected  bonus reward
  function collectRewards(IncentiveKey memory key, uint256 tokenId) external returns (uint256 reward, uint256 bonusReward);

  /// @notice Used to claim and send rewards from farming(s)
  /// @dev can be used via static call to get current rewards for user
  /// @param rewardToken The token that is a reward
  /// @param to The address to be rewarded
  /// @param amountRequested Amount to claim in eternal farming
  /// @return rewardBalanceBefore The total amount of unclaimed reward *before* claim
  function claimReward(IERC20Minimal rewardToken, address to, uint256 amountRequested) external returns (uint256 rewardBalanceBefore);
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.20;
pragma abicoder v2;

interface IMultiFeeDistribution {
    /**
     * @notice Stake tokens to receive rewards
     * @param amount to stake
     * @param onBehalfOf address for staking
     */
    function stake(uint256 amount, address onBehalfOf) external;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

File 41 of 52 : IERC5267.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)

pragma solidity ^0.8.0;

interface IERC5267 {
    /**
     * @dev MAY be emitted to signal that the domain could have changed.
     */
    event EIP712DomainChanged();

    /**
     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
     * signature.
     */
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../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 {
    /**
     * @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);

    bool private _paused;

    /**
     * @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 {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

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

import '@openzeppelin/contracts/token/ERC721/IERC721.sol';

/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
    /// @notice The permit typehash used in the permit signature
    /// @return The typehash for the permit
    function PERMIT_TYPEHASH() external pure returns (bytes32);

    /// @notice The domain separator used in the permit signature
    /// @return The domain separator used in encoding of permit signature
    function DOMAIN_SEPARATOR() external view returns (bytes32);

    /// @notice Approve of a specific token ID for spending by spender via signature
    /// @param spender The account that is being approved
    /// @param tokenId The ID of the token that is being approved for spending
    /// @param deadline The deadline timestamp by which the call must be mined for the approve to work
    /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
    /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
    /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
    function permit(
        address spender,
        uint256 tokenId,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable;
}

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

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

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

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC20Permit.sol)

pragma solidity ^0.8.0;

import "./IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/cryptography/EIP712.sol";
import "../../../utils/Counters.sol";

/**
 * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * _Available since v3.4._
 */
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
    using Counters for Counters.Counter;

    mapping(address => Counters.Counter) private _nonces;

    // solhint-disable-next-line var-name-mixedcase
    bytes32 private constant _PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
    /**
     * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`.
     * However, to ensure consistency with the upgradeable transpiler, we will continue
     * to reserve a slot.
     * @custom:oz-renamed-from _PERMIT_TYPEHASH
     */
    // solhint-disable-next-line var-name-mixedcase
    bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT;

    /**
     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
     *
     * It's a good idea to use the same `name` that is defined as the ERC20 token name.
     */
    constructor(string memory name) EIP712(name, "1") {}

    /**
     * @dev See {IERC20Permit-permit}.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual override {
        require(block.timestamp <= deadline, "ERC20Permit: expired deadline");

        bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));

        bytes32 hash = _hashTypedDataV4(structHash);

        address signer = ECDSA.recover(hash, v, r, s);
        require(signer == owner, "ERC20Permit: invalid signature");

        _approve(owner, spender, value);
    }

    /**
     * @dev See {IERC20Permit-nonces}.
     */
    function nonces(address owner) public view virtual override returns (uint256) {
        return _nonces[owner].current();
    }

    /**
     * @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view override returns (bytes32) {
        return _domainSeparatorV4();
    }

    /**
     * @dev "Consume a nonce": return the current value and increment.
     *
     * _Available since v4.1._
     */
    function _useNonce(address owner) internal virtual returns (uint256 current) {
        Counters.Counter storage nonce = _nonces[owner];
        current = nonce.current();
        nonce.increment();
    }
}

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

import '@cryptoalgebra/integral-periphery/contracts/interfaces/INonfungiblePositionManager.sol';
import '../base/IncentiveKey.sol';

/// @title Algebra Eternal Farming Interface
/// @notice Allows farming nonfungible liquidity tokens in exchange for reward tokens without locking NFT for incentive time
interface IAlgebraEternalFarming {
  /// @notice Details of the incentive to create
  struct IncentiveParams {
    uint128 reward; // The amount of reward tokens to be distributed
    uint128 bonusReward; // The amount of bonus reward tokens to be distributed
    uint128 rewardRate; // The rate of reward distribution per second
    uint128 bonusRewardRate; // The rate of bonus reward distribution per second
    uint24 minimalPositionWidth; // The minimal allowed width of position (tickUpper - tickLower)
  }

  error farmDoesNotExist();
  error tokenAlreadyFarmed();
  error incentiveNotExist();
  error incentiveStopped();
  error anotherFarmingIsActive();
  error pluginNotConnected();

  error minimalPositionWidthTooWide();
  error zeroRewardAmount();

  error positionIsTooNarrow();
  error zeroLiquidity();
  error invalidPool();
  error claimToZeroAddress();

  error invalidTokenAmount();

  error emergencyActivated();

  error reentrancyLock();
  error poolReentrancyLock();

  /// @notice Returns hash of 'INCENTIVE_MAKER_ROLE', used as role for incentive creation
  function INCENTIVE_MAKER_ROLE() external view returns (bytes32);

  /// @notice Returns hash of 'FARMINGS_ADMINISTRATOR_ROLE', used as role for permissioned actions in farming
  function FARMINGS_ADMINISTRATOR_ROLE() external view returns (bytes32);

  /// @notice The nonfungible position manager with which this farming contract is compatible
  function nonfungiblePositionManager() external view returns (INonfungiblePositionManager);

  /// @notice Represents a farming incentive
  /// @param incentiveId The ID of the incentive computed from its parameters
  function incentives(
    bytes32 incentiveId
  )
    external
    view
    returns (
      uint128 totalReward,
      uint128 bonusReward,
      address virtualPoolAddress,
      uint24 minimalPositionWidth,
      bool deactivated,
      address pluginAddress
    );

  /// @notice Check if incentive is deactivated (manually or automatically)
  /// @dev Does not check if the incentive is indeed currently connected to the Algebra pool or not
  /// @param incentiveId The ID of the incentive computed from its parameters
  /// @return True if incentive is deactivated (manually or automatically)
  function isIncentiveDeactivated(bytes32 incentiveId) external view returns (bool);

  /// @notice Returns address of current farmingCenter
  function farmingCenter() external view returns (address);

  /// @notice Users can withdraw liquidity without any checks if active.
  function isEmergencyWithdrawActivated() external view returns (bool);

  /// @notice Detach incentive from the pool and deactivate it
  /// @param key The key of the incentive
  function deactivateIncentive(IncentiveKey memory key) external;

  /// @notice Add rewards for incentive
  /// @param key The key of the incentive
  /// @param rewardAmount The amount of token0
  /// @param bonusRewardAmount The amount of token1
  function addRewards(IncentiveKey memory key, uint128 rewardAmount, uint128 bonusRewardAmount) external;

  /// @notice Decrease rewards for incentive and withdraw
  /// @param key The key of the incentive
  /// @param rewardAmount The amount of token0
  /// @param bonusRewardAmount The amount of token1
  function decreaseRewardsAmount(IncentiveKey memory key, uint128 rewardAmount, uint128 bonusRewardAmount) external;

  /// @notice Changes `isEmergencyWithdrawActivated`. Users can withdraw liquidity without any checks if activated.
  /// User cannot enter to farmings if activated.
  /// _Must_ only be used in emergency situations. Farmings may be unusable after activation.
  /// @dev only farmings administrator
  /// @param newStatus The new status of `isEmergencyWithdrawActivated`.
  function setEmergencyWithdrawStatus(bool newStatus) external;

  /// @notice Returns amount of created incentives
  function numOfIncentives() external view returns (uint256);

  /// @notice Returns amounts of reward tokens owed to a given address according to the last time all farms were updated
  /// @param owner The owner for which the rewards owed are checked
  /// @param rewardToken The token for which to check rewards
  /// @return rewardsOwed The amount of the reward token claimable by the owner
  function rewards(address owner, IERC20Minimal rewardToken) external view returns (uint256 rewardsOwed);

  /// @notice Updates farming center address
  /// @param _farmingCenter The new farming center contract address
  function setFarmingCenterAddress(address _farmingCenter) external;

  /// @notice enter farming for Algebra LP token
  /// @param key The key of the incentive for which to enter farming
  /// @param tokenId The ID of the token to enter farming
  function enterFarming(IncentiveKey memory key, uint256 tokenId) external;

  /// @notice exitFarmings for Algebra LP token
  /// @param key The key of the incentive for which to exit farming
  /// @param tokenId The ID of the token to exit farming
  /// @param _owner Owner of the token
  function exitFarming(IncentiveKey memory key, uint256 tokenId, address _owner) external;

  /// @notice Transfers `amountRequested` of accrued `rewardToken` (if possible) rewards from the contract to the recipient `to`
  /// @param rewardToken The token being distributed as a reward
  /// @param to The address where claimed rewards will be sent to
  /// @param amountRequested The amount of reward tokens to claim. Claims entire reward amount if set to 0.
  /// @return rewardBalanceBefore The total amount of unclaimed reward *before* claim
  function claimReward(IERC20Minimal rewardToken, address to, uint256 amountRequested) external returns (uint256 rewardBalanceBefore);

  /// @notice Transfers `amountRequested` of accrued `rewardToken` (if possible) rewards from the contract to the recipient `to`
  /// @notice only for FarmingCenter
  /// @param rewardToken The token being distributed as a reward
  /// @param from The address of position owner
  /// @param to The address where claimed rewards will be sent to
  /// @param amountRequested The amount of reward tokens to claim. Claims entire reward amount if set to 0.
  /// @return rewardBalanceBefore The total amount of unclaimed reward *before* claim
  function claimRewardFrom(
    IERC20Minimal rewardToken,
    address from,
    address to,
    uint256 amountRequested
  ) external returns (uint256 rewardBalanceBefore);

  /// @notice Calculates the reward amount that will be received for the given farm
  /// @param key The key of the incentive
  /// @param tokenId The ID of the token
  /// @return reward The reward accrued to the NFT for the given incentive thus far
  /// @return bonusReward The bonus reward accrued to the NFT for the given incentive thus far
  function getRewardInfo(IncentiveKey memory key, uint256 tokenId) external returns (uint256 reward, uint256 bonusReward);

  /// @notice Returns information about a farmed liquidity NFT
  /// @param tokenId The ID of the farmed token
  /// @param incentiveId The ID of the incentive for which the token is farmed
  /// @return liquidity The amount of liquidity in the NFT as of the last time the rewards were computed,
  /// @return tickLower The lower tick of position,
  /// @return tickUpper The upper tick of position,
  /// @return innerRewardGrowth0 The last saved reward0 growth inside position,
  /// @return innerRewardGrowth1 The last saved reward1 growth inside position
  function farms(
    uint256 tokenId,
    bytes32 incentiveId
  ) external view returns (uint128 liquidity, int24 tickLower, int24 tickUpper, uint256 innerRewardGrowth0, uint256 innerRewardGrowth1);

  /// @notice Creates a new liquidity farming incentive program
  /// @param key Details of the incentive to create
  /// @param params Params of incentive
  /// @param plugin The address of corresponding plugin
  /// @return virtualPool The created virtual pool
  function createEternalFarming(IncentiveKey memory key, IncentiveParams memory params, address plugin) external returns (address virtualPool);

  /// @notice Change reward rates for incentive
  /// @param key The key of incentive
  /// @param rewardRate The new rate of main token (token0) distribution per sec
  /// @param bonusRewardRate The new rate of bonus token (token1) distribution per sec
  function setRates(IncentiveKey memory key, uint128 rewardRate, uint128 bonusRewardRate) external;

  /// @notice Collect rewards for tokenId
  /// @dev only FarmingCenter
  /// @param key The key of incentive
  /// @param tokenId The ID of the token to exit farming
  /// @param _owner Owner of the token
  /// @return reward The amount of main token (token0) collected
  /// @param bonusReward The amount of bonus token (token1) collected
  function collectRewards(IncentiveKey memory key, uint256 tokenId, address _owner) external returns (uint256 reward, uint256 bonusReward);

  /// @notice Event emitted when a liquidity mining incentive has been stopped from the outside
  /// @param incentiveId The stopped incentive
  event IncentiveDeactivated(bytes32 indexed incentiveId);

  /// @notice Event emitted when a Algebra LP token has been farmed
  /// @param tokenId The unique identifier of an Algebra LP token
  /// @param incentiveId The incentive in which the token is farming
  /// @param liquidity The amount of liquidity farmed
  event FarmEntered(uint256 indexed tokenId, bytes32 indexed incentiveId, uint128 liquidity);

  /// @notice Event emitted when a Algebra LP token exited from farming
  /// @param tokenId The unique identifier of an Algebra LP token
  /// @param incentiveId The incentive in which the token is farming
  /// @param rewardAddress The token being distributed as a reward
  /// @param bonusRewardToken The token being distributed as a bonus reward
  /// @param owner The address where claimed rewards were sent to
  /// @param reward The amount of reward tokens to be claimed
  /// @param bonusReward The amount of bonus reward tokens to be claimed
  event FarmEnded(
    uint256 indexed tokenId,
    bytes32 indexed incentiveId,
    address indexed rewardAddress,
    address bonusRewardToken,
    address owner,
    uint256 reward,
    uint256 bonusReward
  );

  /// @notice Emitted when the farming center is changed
  /// @param farmingCenter The farming center after the address was changed
  event FarmingCenter(address indexed farmingCenter);

  /// @notice Event emitted when rewards were added
  /// @param rewardAmount The additional amount of main token
  /// @param bonusRewardAmount The additional amount of bonus token
  /// @param incentiveId The ID of the incentive for which rewards were added
  event RewardsAdded(uint256 rewardAmount, uint256 bonusRewardAmount, bytes32 incentiveId);

  /// @notice Event emitted when rewards were decreased
  /// @param rewardAmount The withdrawn amount of main token
  /// @param bonusRewardAmount The withdrawn amount of bonus token
  /// @param incentiveId The ID of the incentive for which rewards were decreased
  event RewardAmountsDecreased(uint256 rewardAmount, uint256 bonusRewardAmount, bytes32 incentiveId);

  /// @notice Event emitted when a reward token has been claimed
  /// @param to The address where claimed rewards were sent to
  /// @param reward The amount of reward tokens claimed
  /// @param rewardAddress The token reward address
  /// @param owner The address where claimed rewards were claimed from
  event RewardClaimed(address indexed to, uint256 reward, address indexed rewardAddress, address indexed owner);

  /// @notice Event emitted when reward rates were changed
  /// @param rewardRate The new rate of main token (token0) distribution per sec
  /// @param bonusRewardRate The new rate of bonus token (token1) distribution per sec
  /// @param incentiveId The ID of the incentive for which rates were changed
  event RewardsRatesChanged(uint128 rewardRate, uint128 bonusRewardRate, bytes32 incentiveId);

  /// @notice Event emitted when rewards were collected
  /// @param tokenId The ID of the token for which rewards were collected
  /// @param incentiveId The ID of the incentive for which rewards were collected
  /// @param rewardAmount Collected amount of reward
  /// @param bonusRewardAmount Collected amount of bonus reward
  event RewardsCollected(uint256 tokenId, bytes32 incentiveId, uint256 rewardAmount, uint256 bonusRewardAmount);

  /// @notice Event emitted when a liquidity mining incentive has been created
  /// @param rewardToken The token being distributed as a reward
  /// @param bonusRewardToken The token being distributed as a bonus reward
  /// @param pool The Algebra pool
  /// @param virtualPool The virtual pool address
  /// @param nonce The nonce of new farming
  /// @param reward The amount of reward tokens to be distributed
  /// @param bonusReward The amount of bonus reward tokens to be distributed
  /// @param minimalAllowedPositionWidth The minimal allowed position width (tickUpper - tickLower)
  event EternalFarmingCreated(
    IERC20Minimal indexed rewardToken,
    IERC20Minimal indexed bonusRewardToken,
    IAlgebraPool indexed pool,
    address virtualPool,
    uint256 nonce,
    uint256 reward,
    uint256 bonusReward,
    uint24 minimalAllowedPositionWidth
  );

  /// @notice Emitted when status of `isEmergencyWithdrawActivated` changes
  /// @param newStatus New value of `isEmergencyWithdrawActivated`. Users can withdraw liquidity without any checks if active.
  event EmergencyWithdraw(bool newStatus);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "../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 v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

// 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
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
interface IPeripheryImmutableState {
    /// @return Returns the address of the Algebra factory
    function factory() external view returns (address);

    /// @return Returns the address of the pool Deployer
    function poolDeployer() external view returns (address);

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

File 51 of 52 : IAlgebraPoolEvents.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Events emitted by a pool
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolEvents {
  /// @notice Emitted exactly once by a pool when #initialize is first called on the pool
  /// @dev Mint/Burn/Swaps cannot be emitted by the pool before Initialize
  /// @param price 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 price, 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 bottomTick The lower tick of the position
  /// @param topTick The upper tick of the position
  /// @param liquidityAmount 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 bottomTick,
    int24 indexed topTick,
    uint128 liquidityAmount,
    uint256 amount0,
    uint256 amount1
  );

  /// @notice Emitted when fees are collected by the owner of a position
  /// @param owner The owner of the position for which fees are collected
  /// @param recipient The address that received fees
  /// @param bottomTick The lower tick of the position
  /// @param topTick 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 bottomTick, int24 indexed topTick, 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 bottomTick The lower tick of the position
  /// @param topTick The upper tick of the position
  /// @param liquidityAmount 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 bottomTick, int24 indexed topTick, uint128 liquidityAmount, 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 price 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 price, 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 when the community fee is changed by the pool
  /// @param communityFeeNew The updated value of the community fee in thousandths (1e-3)
  event CommunityFee(uint16 communityFeeNew);

  /// @notice Emitted when the tick spacing changes
  /// @param newTickSpacing The updated value of the new tick spacing
  event TickSpacing(int24 newTickSpacing);

  /// @notice Emitted when the plugin address changes
  /// @param newPluginAddress New plugin address
  event Plugin(address newPluginAddress);

  /// @notice Emitted when the plugin config changes
  /// @param newPluginConfig New plugin config
  event PluginConfig(uint8 newPluginConfig);

  /// @notice Emitted when the fee changes inside the pool
  /// @param fee The current fee in hundredths of a bip, i.e. 1e-6
  event Fee(uint16 fee);

  event CommunityVault(address newCommunityVault);
}

File 52 of 52 : IncentiveKey.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.6;
pragma abicoder v2;

import '@cryptoalgebra/integral-core/contracts/interfaces/IERC20Minimal.sol';
import '@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol';

/// @param rewardToken The token being distributed as a reward (token0)
/// @param bonusRewardToken The bonus token being distributed as a reward (token1)
/// @param pool The Algebra pool
/// @param nonce The nonce of incentive
struct IncentiveKey {
  IERC20Minimal rewardToken;
  IERC20Minimal bonusRewardToken;
  IAlgebraPool pool;
  uint256 nonce;
}

Settings
{
  "evmVersion": "shanghai",
  "libraries": {},
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "remappings": [
    "@chainlink/=node_modules/@chainlink/",
    "@cryptoalgebra/=node_modules/@cryptoalgebra/",
    "@ensdomains/=node_modules/@ensdomains/",
    "@openzeppelin/=node_modules/@openzeppelin/",
    "@uniswap/=node_modules/@uniswap/",
    "base64-sol/=node_modules/base64-sol/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "eth-gas-reporter/=node_modules/eth-gas-reporter/",
    "forge-std/=lib/forge-std/src/",
    "hardhat/=node_modules/hardhat/"
  ],
  "viaIR": false
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_pool","type":"address"},{"internalType":"address","name":"_nonfungiblePositionManager","type":"address"},{"internalType":"address","name":"_incentiveMaker","type":"address"},{"internalType":"address","name":"_receiver","type":"address"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"InvalidRecipient","type":"error"},{"inputs":[],"name":"InvalidShortString","type":"error"},{"inputs":[],"name":"InvalidTokens","type":"error"},{"inputs":[],"name":"NotOwner","type":"error"},{"inputs":[],"name":"NotWhitelisted","type":"error"},{"inputs":[],"name":"OnlyReceiver","type":"error"},{"inputs":[{"internalType":"string","name":"str","type":"string"}],"name":"StringTooLong","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"inputs":[],"name":"ZeroDeposits","type":"error"},{"inputs":[],"name":"ZeroFee","type":"error"},{"inputs":[],"name":"ZeroShares","type":"error"},{"inputs":[],"name":"tickOutOfRange","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"BonusRewardTokenTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"isPaused","type":"bool"}],"name":"ClaimPauseStateChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[],"name":"EIP712DomainChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"tokenId","type":"uint256"},{"components":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"contract IERC20Minimal","name":"bonusRewardToken","type":"address"},{"internalType":"contract IAlgebraPool","name":"pool","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"}],"indexed":false,"internalType":"struct IncentiveKey","name":"foundKey","type":"tuple"},{"components":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"contract IERC20Minimal","name":"bonusRewardToken","type":"address"},{"internalType":"contract IAlgebraPool","name":"pool","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"}],"indexed":false,"internalType":"struct IncentiveKey","name":"currentKey","type":"tuple"}],"name":"IncentiveKeyMismatch","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"rewardToken","type":"address"},{"indexed":false,"internalType":"address","name":"bonusRewardToken","type":"address"},{"indexed":false,"internalType":"address","name":"pool","type":"address"},{"indexed":false,"internalType":"uint256","name":"nonce","type":"uint256"}],"name":"IncentiveKeyUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"baseNftId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"limitNftId","type":"uint256"}],"name":"InitialMint","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"int24","name":"tick","type":"int24"},{"indexed":false,"internalType":"uint256","name":"totalAmount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalAmount1","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"feeAmount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"feeAmount1","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalSupply","type":"uint256"}],"name":"Rebalance","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"contract IERC20","name":"rewardToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"RewardPaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"RewardTokenTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"bonusReward","type":"uint256"}],"name":"RewardsCollected","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"rewardToken","type":"address"},{"indexed":true,"internalType":"address","name":"bonusRewardToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"rewardAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"bonusRewardAmount","type":"uint256"}],"name":"RewardsTransferredToOwner","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"newFee","type":"uint8"}],"name":"SetFee","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newReceiver","type":"address"}],"name":"TransferReceiver","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"Withdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"fee","type":"uint8"},{"indexed":false,"internalType":"uint256","name":"fees0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"fees1","type":"uint256"}],"name":"ZeroBurn","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PRECISION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"baseLower","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"baseNftId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"baseUpper","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"bonusRewardToken","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256[4]","name":"inMin","type":"uint256[4]"}],"name":"compound","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"currentIncentiveKey","outputs":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"contract IERC20Minimal","name":"bonusRewardToken","type":"address"},{"internalType":"contract IAlgebraPool","name":"pool","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currentTick","outputs":[{"internalType":"int24","name":"tick","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"amount0Min","type":"uint256"},{"internalType":"uint256","name":"amount1Min","type":"uint256"}],"name":"decreaseLiquidity","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"deposit0","type":"uint256"},{"internalType":"uint256","name":"deposit1","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"address","name":"from","type":"address"},{"internalType":"uint256[4]","name":"inMin","type":"uint256[4]"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"deposit0","type":"uint256"},{"internalType":"uint256","name":"deposit1","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"address","name":"from","type":"address"},{"internalType":"uint256[4]","name":"inMin","type":"uint256[4]"}],"name":"depositAndStake","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"directDeposit","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"eip712Domain","outputs":[{"internalType":"bytes1","name":"fields","type":"bytes1"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"version","type":"string"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"verifyingContract","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256[]","name":"extensions","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"farmingCenter","outputs":[{"internalType":"contract IFarmingCenter","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"fee","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getBasePosition","outputs":[{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLimitPosition","outputs":[{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getReward","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getTotalAmounts","outputs":[{"internalType":"uint256","name":"total0","type":"uint256"},{"internalType":"uint256","name":"total1","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTotalAmountsPlusFees","outputs":[{"internalType":"uint256","name":"total0","type":"uint256"},{"internalType":"uint256","name":"total1","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"incentiveMaker","outputs":[{"internalType":"contract IIncentiveMaker","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"limitLower","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"limitNftId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"limitUpper","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint256","name":"amount0Desired","type":"uint256"},{"internalType":"uint256","name":"amount1Desired","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount0Min","type":"uint256"},{"internalType":"uint256","name":"amount1Min","type":"uint256"}],"name":"mintLiquidity","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nonfungiblePositionManager","outputs":[{"internalType":"contract INonfungiblePositionManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"pool","outputs":[{"internalType":"contract IAlgebraPool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int24","name":"_baseLower","type":"int24"},{"internalType":"int24","name":"_baseUpper","type":"int24"},{"internalType":"int24","name":"_limitLower","type":"int24"},{"internalType":"int24","name":"_limitUpper","type":"int24"},{"internalType":"address","name":"_feeRecipient","type":"address"},{"internalType":"uint256[4]","name":"inMin","type":"uint256[4]"},{"internalType":"uint256[4]","name":"outMin","type":"uint256[4]"}],"name":"rebalance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"receiver","outputs":[{"internalType":"contract IMultiFeeDistribution","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rewardToken","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"newFee","type":"uint8"}],"name":"setFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_baseNftId","type":"uint256"},{"internalType":"uint256","name":"_limitNftId","type":"uint256"}],"name":"setNftIds","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_pool","type":"address"},{"internalType":"address","name":"_nonfungiblePositionManager","type":"address"},{"internalType":"address","name":"_farmingCenter","type":"address"}],"name":"setProtocolAddresses","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"int24","name":"newTickSpacing","type":"int24"}],"name":"setTickSpacing","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_address","type":"address"}],"name":"setWhitelist","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tickSpacing","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"toggleDirectDeposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"token0","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"token1","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newReceiver","type":"address"}],"name":"transferReceiver","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_incentiveMaker","type":"address"}],"name":"updateIncentiveMaker","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"whitelistedAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"address","name":"from","type":"address"},{"internalType":"uint256[4]","name":"minAmounts","type":"uint256[4]"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"zeroBurn","outputs":[{"internalType":"uint256","name":"owed0","type":"uint256"},{"internalType":"uint256","name":"owed1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]

6101606040526017805460ff60a01b1916600160a01b17905534801562000024575f80fd5b5060405162006e9138038062006e91833981016040819052620000479162000b00565b8180604051806040016040528060018152602001603160f81b81525084846200007f620000796200059460201b60201c565b62000598565b5f805460ff60a01b19169055600462000099838262000c44565b506005620000a8828262000c44565b50620000ba91508390506006620005e7565b61012052620000cb816007620005e7565b61014052815160208084019190912060e052815190820120610100524660a0526200015860e05161010051604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201529081019290925260608201524660808201523060a08201525f9060c00160405160208183030381529060405280519060200120905090565b60805250503060c052506001600a556001600160a01b038616158015906200018857506001600160a01b03851615155b80156200019d57506001600160a01b03831615155b620001a6575f80fd5b600b80546001600160a01b038089166001600160a01b031992831617909255600c8054928816929091168217905560408051631baadcbb60e31b8152905163dd56e5d8916004808201926020929091908290030181865afa1580156200020e573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000234919062000d0c565b600d80546001600160a01b03199081166001600160a01b0393841617909155600e80548216878416908117909155600f8054909216928616929092179055156200036357600e80546001600160a01b0319166001600160a01b03868116918217909255604051600162964af760e01b0319815291881660048301529063ff69b50990602401608060405180830381865afa158015620002d5573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620002fb919062000d31565b8051601080546001600160a01b039283166001600160a01b031991821681179092556020840151601180549185169183168217905560408501516012805491909516908316179093556060909301516013556016805484169091179055601780549092161790555b600b5460408051630dfe168160e01b815290515f926001600160a01b031691630dfe16819160048083019260209291908290030181865afa158015620003ab573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620003d1919062000d0c565b90505f600b5f9054906101000a90046001600160a01b03166001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000425573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200044b919062000d0c565b9050600b5f9054906101000a90046001600160a01b03166001600160a01b031663d0c93a7c6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156200049e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620004c4919062000db6565b6017805462ffffff92909216600160a81b0262ffffff60a81b199092169190911790556001600160a01b038216158015906200050857506001600160a01b03811615155b62000511575f80fd5b601480546001600160a01b038085166001600160a01b03199283168117909355601580548583169316929092179091556017805460ff60a01b1916600160a01b179055600c54620005669291165f196200061f565b600c5460155462000586916001600160a01b0391821691165f196200061f565b505050505050505062000e86565b3390565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b5f6020835110156200060657620005fe8362000770565b905062000619565b8162000613848262000c44565b5060ff90505b92915050565b8015806200069b5750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa15801562000673573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000699919062000dd8565b155b620007135760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527f20746f206e6f6e2d7a65726f20616c6c6f77616e63650000000000000000000060648201526084015b60405180910390fd5b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b0390811663095ea7b360e01b179091526200076b918591620007b216565b505050565b5f80829050601f815111156200079d578260405163305a27a960e01b81526004016200070a919062000df0565b8051620007aa8262000e24565b179392505050565b6040805180820190915260208082527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564908201525f9062000800906001600160a01b03851690849062000884565b905080515f14806200082357508080602001905181019062000823919062000e48565b6200076b5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016200070a565b60606200089484845f856200089c565b949350505050565b606082471015620008ff5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016200070a565b5f80866001600160a01b031685876040516200091c919062000e69565b5f6040518083038185875af1925050503d805f811462000958576040519150601f19603f3d011682016040523d82523d5f602084013e6200095d565b606091505b50909250905062000971878383876200097c565b979650505050505050565b60608315620009ef5782515f03620009e7576001600160a01b0385163b620009e75760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016200070a565b508162000894565b62000894838381511562000a065781518083602001fd5b8060405162461bcd60e51b81526004016200070a919062000df0565b6001600160a01b038116811462000a37575f80fd5b50565b634e487b7160e01b5f52604160045260245ffd5b5f5b8381101562000a6a57818101518382015260200162000a50565b50505f910152565b5f82601f83011262000a82575f80fd5b81516001600160401b038082111562000a9f5762000a9f62000a3a565b604051601f8301601f19908116603f0116810190828211818310171562000aca5762000aca62000a3a565b8160405283815286602085880101111562000ae3575f80fd5b62000af684602083016020890162000a4e565b9695505050505050565b5f805f805f8060c0878903121562000b16575f80fd5b865162000b238162000a22565b602088015190965062000b368162000a22565b604088015190955062000b498162000a22565b606088015190945062000b5c8162000a22565b60808801519093506001600160401b038082111562000b79575f80fd5b62000b878a838b0162000a72565b935060a089015191508082111562000b9d575f80fd5b5062000bac89828a0162000a72565b9150509295509295509295565b600181811c9082168062000bce57607f821691505b60208210810362000bed57634e487b7160e01b5f52602260045260245ffd5b50919050565b601f8211156200076b575f81815260208120601f850160051c8101602086101562000c1b5750805b601f850160051c820191505b8181101562000c3c5782815560010162000c27565b505050505050565b81516001600160401b0381111562000c605762000c6062000a3a565b62000c788162000c71845462000bb9565b8462000bf3565b602080601f83116001811462000cae575f841562000c965750858301515b5f19600386901b1c1916600185901b17855562000c3c565b5f85815260208120601f198616915b8281101562000cde5788860151825594840194600190910190840162000cbd565b508582101562000cfc57878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b5f6020828403121562000d1d575f80fd5b815162000d2a8162000a22565b9392505050565b5f6080828403121562000d42575f80fd5b604051608081016001600160401b038111828210171562000d675762000d6762000a3a565b604052825162000d778162000a22565b8152602083015162000d898162000a22565b6020820152604083015162000d9e8162000a22565b60408201526060928301519281019290925250919050565b5f6020828403121562000dc7575f80fd5b81518060020b811462000d2a575f80fd5b5f6020828403121562000de9575f80fd5b5051919050565b602081525f825180602084015262000e1081604085016020870162000a4e565b601f01601f19169190910160400192915050565b8051602080830151919081101562000bed575f1960209190910360031b1b16919050565b5f6020828403121562000e59575f80fd5b8151801515811462000d2a575f80fd5b5f825162000e7c81846020870162000a4e565b9190910192915050565b60805160a05160c05160e051610100516101205161014051615fb962000ed85f395f610fcd01525f610fa201525f61258d01525f61256501525f6124c001525f6124ea01525f6125140152615fb95ff3fe608060405234801561000f575f80fd5b50600436106103ca575f3560e01c8063888a913411610200578063d0c93a7c1161011f578063e1cace88116100b4578063f2fde38b11610084578063f2fde38b1461087e578063f7260d3e14610891578063f7c618c1146108a4578063f9d5111c146108b7578063fa082743146108ca575f80fd5b8063e1cace8814610832578063e43bff5814610845578063ef405caf14610858578063f085a6101461086b575f80fd5b8063dd56e5d8116100ef578063dd56e5d8146107e5578063dd62ed3e146107f8578063ddca3f431461080b578063e0525da91461081f575f80fd5b8063d0c93a7c146107a3578063d21220a7146107b7578063d2eabcfc146107ca578063d505accf146107d2575f80fd5b8063a855987211610195578063b44a272211610165578063b44a27221461076d578063c4a7761e14610780578063cb122a0914610788578063cce6776e1461079b575f80fd5b8063a855987214610729578063a9059cbb1461073c578063aaf5eb681461074f578063b1a3d53314610765575f80fd5b806395d89b41116101d057806395d89b41146106d9578063a049de6b146106e1578063a457c2d71461070e578063a4823eb414610721575f80fd5b8063888a91341461067a5780638da5cb5b1461068e5780638e3c92e41461069e5780638e5f5977146106b1575f80fd5b80633f4ba83a116102ec578063715018a61161028157806384b0196e1161025157806384b0196e14610626578063854cff2f1461064157806385919c5d1461065457806386a2908114610667575f80fd5b8063715018a6146105fa57806374cc0d1a146106025780637ecebe001461060b5780638456cb591461061e575f80fd5b80635c975abb116102bc5780635c975abb146105a45780636bb1972d146105b55780636d90a39c146105be57806370a08231146105d2575f80fd5b80633f4ba83a146105695780634690484014610571578063513ea8841461058457806351e87af714610597575f80fd5b806318160ddd11610362578063313ce56711610332578063313ce567146105315780633644e51514610546578063395093511461054e5780633d18b91214610561575f80fd5b806318160ddd146104a05780631a7d2f48146104b25780631e59ded31461050b57806323b872dd1461051e575f80fd5b80630dfe16811161039d5780630dfe16811461043b5780630f35bcac146104665780631056305e1461047a57806316f0115b1461048d575f80fd5b8063065e5360146103ce57806306fdde03146103ee578063095ea7b3146104035780630b40aaa114610426575b5f80fd5b6103d66108de565b60405160029190910b81526020015b60405180910390f35b6103f6610955565b6040516103e591906153fd565b610416610411366004615423565b6109e5565b60405190151581526020016103e5565b61043961043436600461544d565b6109fe565b005b60145461044e906001600160a01b031681565b6040516001600160a01b0390911681526020016103e5565b6018546103d6906301000000900460020b81565b610439610488366004615468565b610b50565b600b5461044e906001600160a01b031681565b6003545b6040519081526020016103e5565b6010546011546012546013546104d6936001600160a01b0390811693811692169084565b6040516103e594939291906001600160a01b039485168152928416602084015292166040820152606081019190915260800190565b61043961051936600461544d565b610bd3565b61041661052c3660046154b0565b610c30565b60125b60405160ff90911681526020016103e5565b6104a4610c55565b61041661055c366004615423565b610c63565b610439610c84565b610439610cc2565b601c5461044e906001600160a01b031681565b610439610592366004615570565b610cd2565b6018546103d69060020b81565b5f54600160a01b900460ff16610416565b6104a4601a5481565b601c5461041690600160a01b900460ff1681565b6104a46105e036600461544d565b6001600160a01b03165f9081526001602052604090205490565b610439610f57565b6104a460195481565b6104a461061936600461544d565b610f68565b610439610f85565b61062e610f95565b6040516103e5979695949392919061558a565b61043961064f36600461544d565b61101c565b61043961066236600461562c565b611046565b601b5461044e906001600160a01b031681565b6017546103d690600160d81b900460020b81565b5f546001600160a01b031661044e565b6104a46106ac3660046156bb565b611644565b6106c46106bf366004615728565b611677565b604080519283526020830191909152016103e5565b6103f66116ba565b6106e96116c9565b604080516001600160801b0390941684526020840192909252908201526060016103e5565b61041661071c366004615423565b611733565b6106c46117bd565b6106c4610737366004615762565b6118b4565b61041661074a366004615423565b611b43565b6104a46ec097ce7bc90715b34b9f100000000081565b610439611b50565b600c5461044e906001600160a01b031681565b6106c4611b79565b6104396107963660046157bf565b611caa565b6106c4611d11565b6017546103d690600160a81b900460020b81565b60155461044e906001600160a01b031681565b6106e9611d3b565b6104396107e03660046157da565b611da2565b600d5461044e906001600160a01b031681565b6104a4610806366004615846565b611f03565b60175461053490600160a01b900460ff1681565b6104a461082d3660046156bb565b611f2d565b6104a461084036600461587d565b611fe9565b6104396108533660046158cc565b612062565b60175461044e906001600160a01b031681565b6104396108793660046158ec565b612075565b61043961088c36600461544d565b6120a1565b600f5461044e906001600160a01b031681565b60165461044e906001600160a01b031681565b600e5461044e906001600160a01b031681565b6017546103d690600160c01b900460020b81565b600b54604080516397ce1c5160e01b815290515f926001600160a01b0316916397ce1c519160048083019260e09291908290030181865afa158015610925573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610949919061591d565b50939695505050505050565b606060048054610964906159ba565b80601f0160208091040260200160405190810160405280929190818152602001828054610990906159ba565b80156109db5780601f106109b2576101008083540402835291602001916109db565b820191905f5260205f20905b8154815290600101906020018083116109be57829003601f168201915b5050505050905090565b5f336109f2818585612117565b60019150505b92915050565b610a0661223a565b6001600160a01b038116610a18575f80fd5b600e80546001600160a01b0319166001600160a01b03838116918217909255600b54604051600162964af760e01b03198152921660048301525f9163ff69b50990602401608060405180830381865afa158015610a77573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a9b91906159ec565b8051601680546001600160a01b039283166001600160a01b03199182168117909255602080850151601780549186169184168217905560108054841685179055601180548416821790556040808701516012805491909716941684179095556060808701516013819055865195865292850191909152838501929092529082015290519192507fc23197554eb2c0fabeb181b2a679122e4621981948d957035228e0925104d67c919081900360800190a15050565b610b5861223a565b6001600160a01b03831615801590610b7857506001600160a01b03821615155b8015610b8c57506001600160a01b03811615155b610b94575f80fd5b600b80546001600160a01b039485166001600160a01b031991821617909155600c805493851693821693909317909255600d8054919093169116179055565b610bdb61223a565b600f80546001600160a01b0319166001600160a01b0383169081179091556040519081527f4a558665c36272d3508d1143a280d81be952c3abd93ffd377aed6b0b996205ad906020015b60405180910390a150565b5f33610c3d858285612293565b610c4885858561230b565b60019150505b9392505050565b5f610c5e6124b4565b905090565b5f336109f2818585610c758383611f03565b610c7f9190615a5e565b612117565b600f546001600160a01b03163314610c9a575f80fd5b60195415610cad57610cad6019546125dd565b601a5415610cc057610cc0601a546125dd565b565b610cca61223a565b610cc06128f4565b610cda612948565b610ce261223a565b610cea6129a1565b505060195415610cff57610cff6019546125dd565b601a5415610d1257610d12601a546125dd565b60195415610e3d57600b546019546017546014546040516370a0823160e01b8152306004820152610e3b946001600160a01b039081169493600160c01b8104600290810b94600160d81b909204900b929116906370a0823190602401602060405180830381865afa158015610d89573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610dad9190615a71565b6015546040516370a0823160e01b81523060048201526001600160a01b03909116906370a0823190602401602060405180830381865afa158015610df3573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e179190615a71565b87518860015b6020020151600c546001600160a01b03169796959493929190612ce6565b505b601a5415610f4a57600b54601a546018546014546040516370a0823160e01b8152306004820152610f48946001600160a01b039081169493600281810b946301000000909204900b929116906370a0823190602401602060405180830381865afa158015610ead573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ed19190615a71565b6015546040516370a0823160e01b81523060048201526001600160a01b03909116906370a0823190602401602060405180830381865afa158015610f17573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f3b9190615a71565b6040880151886003610e1d565b505b610f546001600a55565b50565b610f5f61223a565b610cc05f612d25565b6001600160a01b0381165f908152600860205260408120546109f8565b610f8d61223a565b610cc0612d74565b5f60608082808083610fc87f00000000000000000000000000000000000000000000000000000000000000006006612db6565b610ff37f00000000000000000000000000000000000000000000000000000000000000006007612db6565b604080515f80825260208201909252600f60f81b9b939a50919850469750309650945092509050565b61102461223a565b601b80546001600160a01b0319166001600160a01b0392909216919091179055565b61104e612948565b61105661223a565b8560020b8760020b128015611082575060175461107d90600160a81b900460020b88615ab0565b60020b155b80156110a557506017546110a090600160a81b900460020b87615ab0565b60020b155b80156110b657508360020b8560020b125b80156110d957506017546110d490600160a81b900460020b86615ab0565b60020b155b80156110fc57506017546110f790600160a81b900460020b85615ab0565b60020b155b801561111e57508560020b8460020b14158061111e57508660020b8560020b14155b801561113257506001600160a01b03831615155b61113a575f80fd5b601c80546001600160a01b0319166001600160a01b0385161790555f8061115f6129a1565b915091506019545f14611177576111776019546125dd565b601a541561118a5761118a601a546125dd565b601954156111e457600c546019545f916111af916001600160a01b0390911690612e5f565b505060195485519192506111e091309084908860015b6020020151600c546001600160a01b03169493929190612ef6565b5050505b601a541561122b57600c54601a545f91611209916001600160a01b0390911690612e5f565b5050601a5490915061122790308387600260200201518860036111c5565b5050505b7fbc4c20ad04f161d631d9ce94d27659391196415aa3c42f6a71c62e905ece782d6112546108de565b6014546040516370a0823160e01b81523060048201526001600160a01b03909116906370a0823190602401602060405180830381865afa15801561129a573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112be9190615a71565b6015546040516370a0823160e01b81523060048201526001600160a01b03909116906370a0823190602401602060405180830381865afa158015611304573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113289190615a71565b858561133360035490565b6040805160029790970b87526020870195909552938501929092526060840152608083015260a082015260c00160405180910390a16017805465ffffffffffff60c01b1916600160c01b62ffffff8c8116820262ffffff60d81b191692909217600160d81b928c1683021792839055600b546014546040516370a0823160e01b81523060048201526114b4956001600160a01b0393841695948104600290810b95909104900b92909116906370a0823190602401602060405180830381865afa158015611402573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114269190615a71565b6015546040516370a0823160e01b81523060048201526001600160a01b03909116906370a0823190602401602060405180830381865afa15801561146c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114909190615a71565b89518a60015b6020020151600c546001600160a01b03169695949392919030613079565b6019819055158015906114d157506012546001600160a01b031615155b156114e1576114e1601954613169565b6018805462ffffff89811665ffffffffffff1990921691909117630100000091891682021791829055600b546014546040516370a0823160e01b8152306004820152611602946001600160a01b0393841694600282810b959190920490910b9216906370a0823190602401602060405180830381865afa158015611567573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061158b9190615a71565b6015546040516370a0823160e01b81523060048201526001600160a01b03909116906370a0823190602401602060405180830381865afa1580156115d1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115f59190615a71565b60408a01518a6003611496565b601a8190551580159061161f57506012546001600160a01b031615155b1561162f5761162f601a54613169565b505061163b6001600a55565b50505050505050565b5f61164d612948565b61165561361a565b6116628686868686613666565b905061166e6001600a55565b95945050505050565b5f80611681612948565b61168961223a565b600c546116a3906001600160a01b03168730888888612ef6565b915091506116b16001600a55565b94509492505050565b606060058054610964906159ba565b5f805f601a545f036116e057505f92839250829150565b600c54601a546116f9916001600160a01b031690612e5f565b5050600b54601854919450611729916001600160a01b0390911690600281810b9163010000009004900b86613966565b9394909392509050565b5f33816117408286611f03565b9050838110156117a55760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b60648201526084015b60405180910390fd5b6117b28286868403612117565b506001949350505050565b5f806117c7611b79565b80925081935050505f805f806019545f1461180257600c54600b546019546117fc926001600160a01b039081169216906139fb565b90945092505b601a541561183057600c54600b54601a5461182a926001600160a01b039081169216906139fb565b90925090505b5f61183b8386615a5e565b90505f6118488386615a5e565b60175490915061186290600160a01b900460ff1683615ad1565b61186c9083615ae4565b60175490925061188690600160a01b900460ff1682615ad1565b6118909082615ae4565b905061189c8289615a5e565b97506118a88188615a5e565b96505050505050509091565b5f806118be612948565b6118c661361a565b5f86116118d1575f80fd5b6001600160a01b0385166118e3575f80fd5b6001600160a01b038416331461190c576040516330cd747160e01b815260040160405180910390fd5b6119146129a1565b505060195415611929576119296019546125dd565b601a541561193c5761193c601a546125dd565b5f805f8061196b601954601a548c8c61195460035490565b600c546001600160a01b031694939291908d613b36565b6014546040516370a0823160e01b815230600482015294985092965090945092505f916119f3916001600160a01b0316906370a0823190602401602060405180830381865afa1580156119c0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906119e49190615a71565b8c6119ee60035490565b613ba1565b6015546040516370a0823160e01b81523060048201529192505f91611a6e916001600160a01b0316906370a0823190602401602060405180830381865afa158015611a40573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a649190615a71565b8d6119ee60035490565b90508115611a8d57601454611a8d906001600160a01b03168c84613c35565b8015611aaa57601554611aaa906001600160a01b03168c83613c35565b81611ab58588615a5e565b611abf9190615a5e565b975080611acc8487615a5e565b611ad69190615a5e565b9650611ae28a8d613c9d565b604080518d8152602081018a90529081018890526001600160a01b03808d1691908c16907febff2602b3f468259e1e99f613fed6691f3a6526effe6ef3e768ba7ae7a36c4f9060600160405180910390a35050505050506116b16001600a55565b5f336109f281858561230b565b611b5861223a565b601c805460ff60a01b198116600160a01b9182900460ff1615909102179055565b5f805f80611b85611d3b565b92509250505f80611b946116c9565b6014546040516370a0823160e01b815230600482015292955090935084925086916001600160a01b03909116906370a0823190602401602060405180830381865afa158015611be5573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c099190615a71565b611c139190615a5e565b611c1d9190615a5e565b6015546040516370a0823160e01b8152306004820152919750829185916001600160a01b0316906370a0823190602401602060405180830381865afa158015611c68573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c8c9190615a71565b611c969190615a5e565b611ca09190615a5e565b9450505050509091565b611cb261223a565b5f8160ff1611611cc0575f80fd5b6017805460ff60a01b1916600160a01b60ff8481168202929092179283905560405192041681527f91f2ade82ab0e77bb6823899e6daddc07e3da0e3ad998577e7c09c2f38943c4390602001610c25565b601b545f9081906001600160a01b03163314611d2b575f80fd5b611d336129a1565b915091509091565b5f805f6019545f03611d5257505f92839250829150565b600c54601954611d6b916001600160a01b031690612e5f565b5050600b54601754919450611729916001600160a01b0390911690600160c01b8104600290810b91600160d81b9004900b86613966565b83421115611df25760405162461bcd60e51b815260206004820152601d60248201527f45524332305065726d69743a206578706972656420646561646c696e65000000604482015260640161179c565b5f7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9888888611e208c613dcf565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e0016040516020818303038152906040528051906020012090505f611e7a82613df6565b90505f611e8982878787613e22565b9050896001600160a01b0316816001600160a01b031614611eec5760405162461bcd60e51b815260206004820152601e60248201527f45524332305065726d69743a20696e76616c6964207369676e61747572650000604482015260640161179c565b611ef78a8a8a612117565b50505050505050505050565b6001600160a01b039182165f90815260026020908152604080832093909416825291909152205490565b5f611f36612948565b611f3e61361a565b611f4b8686308686613666565b600f54909150611f669030906001600160a01b03165f613e4a565b600f54611f7e9030906001600160a01b031683613e4a565b600f54604051637acb775760e01b8152600481018390526001600160a01b03868116602483015290911690637acb7757906044015f604051808303815f87803b158015611fc9575f80fd5b505af1158015611fdb573d5f803e3d5ffd5b5050505061166e6001600a55565b5f611ff2612948565b611ffa61223a565b601454601554600c54612024926001600160a01b039182169290821691168b8b8b8b8b8b8b613f5d565b9050801580159061203f57506012546001600160a01b031615155b1561204d5761204d81613169565b6120576001600a55565b979650505050505050565b61206a61223a565b601991909155601a55565b61207d61223a565b6017805462ffffff909216600160a81b0262ffffff60a81b19909216919091179055565b6120a961223a565b6001600160a01b03811661210e5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b606482015260840161179c565b610f5481612d25565b6001600160a01b0383166121795760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b606482015260840161179c565b6001600160a01b0382166121da5760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b606482015260840161179c565b6001600160a01b038381165f8181526002602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b5f546001600160a01b03163314610cc05760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161179c565b5f61229e8484611f03565b90505f19811461230557818110156122f85760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e6365000000604482015260640161179c565b6123058484848403612117565b50505050565b6001600160a01b03831661236f5760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b606482015260840161179c565b6001600160a01b0382166123d15760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b606482015260840161179c565b6001600160a01b0383165f90815260016020526040902054818110156124485760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b606482015260840161179c565b6001600160a01b038085165f8181526001602052604080822086860390559286168082529083902080548601905591517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906124a79086815260200190565b60405180910390a3612305565b5f306001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614801561250c57507f000000000000000000000000000000000000000000000000000000000000000046145b1561253657507f000000000000000000000000000000000000000000000000000000000000000090565b610c5e604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527f0000000000000000000000000000000000000000000000000000000000000000918101919091527f000000000000000000000000000000000000000000000000000000000000000060608201524660808201523060a08201525f9060c00160405160208183030381529060405280519060200120905090565b805f036125e75750565b5f6125f18261405d565b60408101519091506001600160a01b031661260a575050565b5f8160405160200161261c9190615af7565b60408051601f198184030181528282528051602091820120600d5463de2356d160e01b855292519094505f936001600160a01b039093169263de2356d19260048083019391928290030181865afa158015612679573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061269d9190615b32565b6001600160a01b03166360777795836040518263ffffffff1660e01b81526004016126ca91815260200190565b60c060405180830381865afa1580156126e5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127099190615b67565b50505050509050806001600160801b03165f036127265750505050565b600d54604051633578057760e11b81525f9182916001600160a01b0390911690636af00aee9061275c9088908a90600401615bed565b60408051808303815f875af1158015612777573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061279b9190615c2d565b9092509050811561282757600d548551600f54604051632f2d783d60e01b81526001600160a01b03928316600482015290821660248201525f6044820152911690632f2d783d906064016020604051808303815f875af1158015612801573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128259190615a71565b505b80156128b157600d546020860151600f54604051632f2d783d60e01b81526001600160a01b03928316600482015290821660248201525f6044820152911690632f2d783d906064016020604051808303815f875af115801561288b573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128af9190615a71565b505b604080518381526020810183905287917f3dddd974134793c524aaece0b9af4dd610a213cd4317cf0cb12c3613eafea8cd910160405180910390a2505050505050565b6128fc614199565b5f805460ff60a01b191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b6002600a540361299a5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604482015260640161179c565b6002600a55565b5f805f805f806019545f14612a4a57600c546040805160808101825260195481523060208201526001600160801b038183018190526060820152905163fc6f786560e01b81526001600160a01b039092169163fc6f786591612a0591600401615c4f565b60408051808303815f875af1158015612a20573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612a449190615c2d565b90945092505b601a5415612aec57600c5460408051608081018252601a5481523060208201526001600160801b038183018190526060820152905163fc6f786560e01b81526001600160a01b039092169163fc6f786591612aa791600401615c4f565b60408051808303815f875af1158015612ac2573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ae69190615c2d565b90925090505b60175460408051600160a01b90920460ff16825283860160208301819052838601918301829052975095507f4606b8a47eb284e8e80929101ece6ab5fe8d4f8735acc56bd0c92ca872f2cfe79060600160405180910390a16017545f90612b5d90600160a01b900460ff1688615ad1565b118015612bd157506014546040516370a0823160e01b81523060048201525f916001600160a01b0316906370a0823190602401602060405180830381865afa158015612bab573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612bcf9190615a71565b115b15612c1157601c54601754612c11916001600160a01b031690612bfe90600160a01b900460ff1689615ad1565b6014546001600160a01b03169190613c35565b6017545f90612c2a90600160a01b900460ff1687615ad1565b118015612c9e57506015546040516370a0823160e01b81523060048201525f916001600160a01b0316906370a0823190602401602060405180830381865afa158015612c78573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c9c9190615a71565b115b15612cde57601c54601754612cde916001600160a01b031690612ccb90600160a01b900460ff1688615ad1565b6015546001600160a01b03169190613c35565b505050509091565b5f80612cf58a898989896141e8565b90506001600160801b03811615612d1757612d148b8a8888888861426f565b91505b509998505050505050505050565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b612d7c61361a565b5f805460ff60a01b1916600160a01b1790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25861292b3390565b606060ff8314612dd057612dc983614350565b90506109f8565b818054612ddc906159ba565b80601f0160208091040260200160405190810160405280929190818152602001828054612e08906159ba565b8015612e535780601f10612e2a57610100808354040283529160200191612e53565b820191905f5260205f20905b815481529060010190602001808311612e3657829003601f168201915b505050505090506109f8565b5f805f835f03612e7657505f915081905080612eef565b60405163133f757160e31b8152600481018590526001600160a01b038616906399fbab889060240161016060405180830381865afa158015612eba573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ede9190615c92565b939c509a5091985050505050505050505b9250925092565b5f80846001600160801b03165f03612f1257505f90508061306e565b6040805160a0810182528881526001600160801b03878116602083019081528284018881526060840188815242608086019081529551630624e65f60e11b8152945160048601529151909216602484015290516044830152516064820152905160848201526001600160a01b03891690630c49ccbe9060a40160408051808303815f875af1158015612fa6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612fca9190615c2d565b604080516080810182528a81526001600160a01b038a811660208301526001600160801b038284018190526060830152915163fc6f786560e01b81529395509193505f928392918c169163fc6f7865916130279190600401615c4f565b60408051808303815f875af1158015613042573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130669190615c2d565b909450925050505b965096945050505050565b5f806130888a8a8a8a8a6141e8565b90506001600160801b03811615612d1757612d148b8b6001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa1580156130d9573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130fd9190615b32565b8c6001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa158015613139573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061315d9190615b32565b8c8c8c8c8a8d8d613f5d565b6012546001600160a01b031661317c5750565b600e54600b54604051600162964af760e01b031981526001600160a01b0391821660048201525f92919091169063ff69b50990602401608060405180830381865afa1580156131cd573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906131f191906159ec565b90505f816040516020016132059190615af7565b60408051601f198184030181529190528051602090910120905080158015906133095750600d5f9054906101000a90046001600160a01b03166001600160a01b031663de2356d16040518163ffffffff1660e01b8152600401602060405180830381865afa158015613279573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061329d9190615b32565b6001600160a01b031663b5bae00a826040518263ffffffff1660e01b81526004016132ca91815260200190565b602060405180830381865afa1580156132e5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906133099190615d60565b1561331357505050565b60105482516001600160a01b039081169116141580613345575060115460208301516001600160a01b03908116911614155b80613363575060125460408301516001600160a01b03908116911614155b806133745750601354606083015114155b156133ca578151601080546001600160a01b039283166001600160a01b03199182161790915560208401516011805491841691831691909117905560408401516012805491909316911617905560608201516013555b600c5460405163133f757160e31b8152600481018590525f9182916001600160a01b03909116906399fbab889060240161016060405180830381865afa158015613416573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061343a9190615c92565b505050505095509550505050505f600d5f9054906101000a90046001600160a01b03166001600160a01b031663de2356d16040518163ffffffff1660e01b8152600401602060405180830381865afa158015613498573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906134bc9190615b32565b6001600160a01b03166360777795856040518263ffffffff1660e01b81526004016134e991815260200190565b60c060405180830381865afa158015613504573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906135289190615b67565b505093505050508062ffffff168360020b8360020b6135479190615d79565b121561355557505050505050565b600c54600d54604051634197b18560e11b815260048101899052600160248201526001600160a01b03918216604482015291169063832f630a906064015f604051808303815f87803b1580156135a9575f80fd5b505af11580156135bb573d5f803e3d5ffd5b5050600d54604051635739f0b960e01b81526001600160a01b039091169250635739f0b991506135f19088908a90600401615bed565b5f604051808303815f87803b158015613608575f80fd5b505af1158015611ef7573d5f803e3d5ffd5b5f54600160a01b900460ff1615610cc05760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b604482015260640161179c565b5f8086118061367457505f85115b61367c575f80fd5b6001600160a01b03841661368e575f80fd5b601b546001600160a01b031633146136b957604051630b094f2760e31b815260040160405180910390fd5b6136c16129a1565b5050601954156136d6576136d66019546125dd565b601a54156136e9576136e9601a546125dd565b600b54604080516397ce1c5160e01b815290515f926001600160a01b0316916397ce1c519160048083019260e09291908290030181865afa158015613730573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613754919061591d565b50505050505090505f6137a2826001600160a01b0316670de0b6b3a764000061377d9190615d9f565b6137986001600160a01b038516670de0b6b3a7640000615d9f565b600160c01b613ba1565b90505f806137ae611b79565b915091506137cc8a846ec097ce7bc90715b34b9f1000000000613ba1565b6137d6908a615a5e565b945089156137f6576014546137f6906001600160a01b031688308d61438d565b881561381457601554613814906001600160a01b031688308c61438d565b5f61381e60035490565b905080156138fd575f61384184866ec097ce7bc90715b34b9f1000000000613ba1565b905061385287836119ee8685615a5e565b601c54909750600160a01b900460ff16156138fb576040805161014081018252600b546001600160a01b0390811682526019546020830152601a5492820192909252601754600160c01b8104600290810b6060840152600160d81b909104810b608083015260185480820b60a084015263010000009004900b60c082015260e081018e905261010081018d905261012081018a9052600c5490916138f79116826143c5565b5050505b505b61390789876145d5565b60408051878152602081018d90529081018b90526001600160a01b03808b1691908a16907f4e2ca0515ed1aef1395f66b5303bb5d6f1bf9d61a353fa53f73f8ac9973fa9f69060600160405180910390a3505050505095945050505050565b5f805f866001600160a01b03166397ce1c516040518163ffffffff1660e01b815260040160e060405180830381865afa1580156139a5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906139c9919061591d565b50505050505090506139ed816139de88614694565b6139e788614694565b8761496c565b925092505094509492505050565b5f805f805f805f805f8b6001600160a01b03166399fbab888b6040518263ffffffff1660e01b8152600401613a3291815260200190565b61016060405180830381865afa158015613a4e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613a729190615c92565b9a509a509a509a509a509a509a5050505050846001600160801b03165f03613aaf576001600160801b039182169850169550613b2e945050505050565b816001600160801b03169850806001600160801b031697505f80613ad48d8a8a614a06565b91509150858214613afe57613af9868303886001600160801b0316600160801b613ba1565b8b019a505b848114613b2457613b1f858203886001600160801b0316600160801b613ba1565b8a0199505b5050505050505050505b935093915050565b5f8080808915613b6857613b628b8b89613b528f8f8e8d614c7e565b89518a60015b6020020151612ef6565b90945092505b8815613b9357613b8d8b8a89613b808f8e8e8d614c7e565b60408a01518a6003613b58565b90925090505b975097509750979350505050565b5f838302815f1985870982811083820303915050808411613bc0575f80fd5b805f03613bd257508290049050610c4e565b838587095f8581038616958690049560026003880281188089028203028089028203028089028203028089028203028089028203028089029091030291819003819004600101858411909403939093029190930391909104170290509392505050565b6040516001600160a01b038316602482015260448101829052613c9890849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152614d20565b505050565b6001600160a01b038216613cfd5760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b606482015260840161179c565b6001600160a01b0382165f9081526001602052604090205481811015613d705760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b606482015260840161179c565b6001600160a01b0383165f8181526001602090815260408083208686039055600380548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3505050565b6001600160a01b0381165f9081526008602052604090208054600181018255905b50919050565b5f6109f8613e026124b4565b8360405161190160f01b8152600281019290925260228201526042902090565b5f805f613e3187878787614df3565b91509150613e3e81614ead565b5090505b949350505050565b801580613ec25750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa158015613e9c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ec09190615a71565b155b613f2d5760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527520746f206e6f6e2d7a65726f20616c6c6f77616e636560501b606482015260840161179c565b6040516001600160a01b038316602482015260448101829052613c9890849063095ea7b360e01b90606401613c61565b5f85158015613f6a575084155b15613f7657505f61404f565b8a6001600160a01b0316639cc1a2836040518061014001604052808d6001600160a01b031681526020018c6001600160a01b031681526020018b60020b81526020018a60020b8152602001898152602001888152602001868152602001858152602001876001600160a01b03168152602001428152506040518263ffffffff1660e01b81526004016140089190615db6565b6080604051808303815f875af1158015614024573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906140489190615e61565b5091925050505b9a9950505050505050505050565b604080516080810182525f808252602082018190529181018290526060810191909152600d54604051630b02c43d60e41b8152600481018490525f916001600160a01b03169063b02c43d090602401602060405180830381865afa1580156140c7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906140eb9190615a71565b600d54604051634613f8fb60e11b8152600481018390529192505f918291829182916001600160a01b031690638c27f1f690602401608060405180830381865afa15801561413b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061415f9190615e9c565b604080516080810182526001600160a01b039586168152938516602085015291909316908201526060810191909152979650505050505050565b5f54600160a01b900460ff16610cc05760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b604482015260640161179c565b5f80866001600160a01b03166397ce1c516040518163ffffffff1660e01b815260040160e060405180830381865afa158015614226573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061424a919061591d565b50505050505090506120578161425f88614694565b61426888614694565b8787614ff6565b5f8415801561427c575083155b1561428857505f614346565b6040805160c0810182528781526020810187815281830187815260608301878152608084018781524260a08601908152955163219f5d1760e01b8152945160048601529251602485015290516044840152516064830152516084820152905160a48201526001600160a01b0388169063219f5d179060c4016060604051808303815f875af115801561431c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906143409190615eec565b50909150505b9695505050505050565b60605f61435c836150ab565b6040805160208082528183019092529192505f91906020820181803683375050509182525060208101929092525090565b6040516001600160a01b03808516602483015283166044820152606481018290526123059085906323b872dd60e01b90608401613c61565b5f8082602001515f14614494575f8061440b855f015186606001518760800151614406895f01518a606001518b608001518c60e001518d61010001516141e8565b613966565b915091505f82118061441c57505f81115b15614491578460e0015182116144325781614438565b8460e001515b9350846101000151811161444c5780614453565b8461010001515b925061448f86866020015186868961012001515f6004811061447757614477615a88565b60200201516101208b015160015b602002015161426f565b505b50505b5f828460e00151116144a6575f6144b6565b828460e001516144b69190615ae4565b90505f82856101000151116144cb575f6144dc565b828561010001516144dc9190615ae4565b90505f8211806144eb57505f81115b80156144fa5750604085015115155b156145cc57845160a086015160c08701515f928392614520926144068383838b8b6141e8565b915091505f82118061453157505f81115b156145c9575f8483116145445782614546565b845b90505f8483116145565782614558565b845b90505f61459b8b8b6040015185858e610120015160026004811061457e5761457e615a88565b60200201518f610120015160036004811061448557614485615a88565b90506001600160801b038116156145c5576145b6838a615a5e565b98506145c28289615a5e565b97505b5050505b50505b50509250929050565b6001600160a01b03821661462b5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015260640161179c565b8060035f82825461463c9190615a5e565b90915550506001600160a01b0382165f818152600160209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b5f600282900b60171d62ffffff818401821816620d89e88111156146cb57604051633c10250f60e01b815260040160405180910390fd5b600160801b60018216156146ec57506ffffcb933bd6fad37aa2d162d1a5940015b600282161561470b576ffff97272373d413259a46990580e213a0260801c5b600482161561472a576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615614749576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615614768576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615614787576fff973b41fa98c081472e6896dfb254c00260801c5b60408216156147a6576fff2ea16466c96a3843ec78b326b528610260801c5b60808216156147c5576ffe5dee046a99a2a811c461f1969c30530260801c5b6101008216156147e5576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615614805576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615614825576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615614845576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615614865576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615614885576fa9f746462d870fdf8a65dc1f90e061e50260801c5b6140008216156148a5576f70d869a156d2a1b890bb3df62baf32f70260801c5b6180008216156148c5576f31be135f97d08fd981231505542fcfa60260801c5b620100008216156148e6576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615614906576e5d6af8dedb81196699c329225ee6040260801c5b62040000821061494c576204000082161561492f576d2216e584f5fa1ea926041bedfe980260801c5b6208000082161561494c576b048a170391f7dc42444e8fa20260801c5b5f8560020b131561495b575f19045b63ffffffff0160201c949350505050565b5f80836001600160a01b0316856001600160a01b0316111561498c579293925b846001600160a01b0316866001600160a01b0316116149b7576149b08585856150d2565b91506116b1565b836001600160a01b0316866001600160a01b031610156149f0576149dc8685856150d2565b91506149e9858785615140565b90506116b1565b6149fb858585615140565b905094509492505050565b5f805f856001600160a01b03166397ce1c516040518163ffffffff1660e01b815260040160e060405180830381865afa158015614a45573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614a69919061591d565b505060405163f30dba9360e01b815260028b900b60048201529395505f945084936001600160a01b038c16935063f30dba939250602401905060c060405180830381865afa158015614abd573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614ae19190615f20565b60405163f30dba9360e01b815260028d900b600482015291975095505f94508493506001600160a01b038d16925063f30dba93915060240160c060405180830381865afa158015614b34573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614b589190615f20565b95509550505050505f8a6001600160a01b0316636378ae446040518163ffffffff1660e01b8152600401602060405180830381865afa158015614b9d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614bc19190615a71565b90505f8b6001600160a01b031663ecdecf426040518163ffffffff1660e01b8152600401602060405180830381865afa158015614c00573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614c249190615a71565b90508a60020b8760020b1215614c435783860398508285039750614c6f565b8960020b8760020b1215614c64578386830303985082858203039750614c6f565b858403985084830397505b50505050505050935093915050565b60405163133f757160e31b8152600481018490525f9081906001600160a01b038716906399fbab889060240161016060405180830381865afa158015614cc6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614cea9190615c92565b5050505096505050505050505f614d0b826001600160801b03168686613ba1565b90506001600160801b03811115614346575f80fd5b5f614d74826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166151829092919063ffffffff16565b905080515f1480614d94575080806020019051810190614d949190615d60565b613c985760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840161179c565b5f807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0831115614e2857505f905060036116b1565b604080515f8082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa158015614e79573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b038116614ea1575f600192509250506116b1565b965f9650945050505050565b5f816004811115614ec057614ec0615f8a565b03614ec85750565b6001816004811115614edc57614edc615f8a565b03614f295760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e61747572650000000000000000604482015260640161179c565b6002816004811115614f3d57614f3d615f8a565b03614f8a5760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e67746800604482015260640161179c565b6003816004811115614f9e57614f9e615f8a565b03610f545760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b606482015260840161179c565b5f836001600160a01b0316856001600160a01b03161115615015579293925b846001600160a01b0316866001600160a01b03161161504057615039858585615190565b905061166e565b836001600160a01b0316866001600160a01b031610156150a0575f615066878686615190565b90505f6150748789866151f1565b9050806001600160801b0316826001600160801b0316106150955780615097565b815b9250505061166e565b6143468585846151f1565b5f60ff8216601f8111156109f857604051632cd44ac360e21b815260040160405180910390fd5b5f826001600160a01b0316846001600160a01b031611156150f1579192915b836001600160a01b031661512a606060ff16846001600160801b0316901b8686036001600160a01b0316866001600160a01b0316613ba1565b8161513757615137615a9c565b04949350505050565b5f826001600160a01b0316846001600160a01b0316111561515f579192915b613e42826001600160801b03168585036001600160a01b0316600160601b613ba1565b6060613e4284845f8561522d565b5f826001600160a01b0316846001600160a01b031611156151af579192915b5f6151d1856001600160a01b0316856001600160a01b0316600160601b613ba1565b905061166e6151ec84838888036001600160a01b0316613ba1565b6152f9565b5f826001600160a01b0316846001600160a01b03161115615210579192915b613e426151ec83600160601b8787036001600160a01b0316613ba1565b60608247101561528e5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b606482015260840161179c565b5f80866001600160a01b031685876040516152a99190615f9e565b5f6040518083038185875af1925050503d805f81146152e3576040519150601f19603f3d011682016040523d82523d5f602084013e6152e8565b606091505b509150915061205787838387615313565b806001600160801b038116811461530e575f80fd5b919050565b606083156153815782515f0361537a576001600160a01b0385163b61537a5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161179c565b5081613e42565b613e4283838151156153965781518083602001fd5b8060405162461bcd60e51b815260040161179c91906153fd565b5f5b838110156153ca5781810151838201526020016153b2565b50505f910152565b5f81518084526153e98160208601602086016153b0565b601f01601f19169290920160200192915050565b602081525f610c4e60208301846153d2565b6001600160a01b0381168114610f54575f80fd5b5f8060408385031215615434575f80fd5b823561543f8161540f565b946020939093013593505050565b5f6020828403121561545d575f80fd5b8135610c4e8161540f565b5f805f6060848603121561547a575f80fd5b83356154858161540f565b925060208401356154958161540f565b915060408401356154a58161540f565b809150509250925092565b5f805f606084860312156154c2575f80fd5b83356154cd8161540f565b925060208401356154dd8161540f565b929592945050506040919091013590565b6040516080810167ffffffffffffffff8111828210171561551d57634e487b7160e01b5f52604160045260245ffd5b60405290565b5f82601f830112615532575f80fd5b61553a6154ee565b80608084018581111561554b575f80fd5b845b8181101561556557803584526020938401930161554d565b509095945050505050565b5f60808284031215615580575f80fd5b610c4e8383615523565b60ff60f81b881681525f602060e0818401526155a960e084018a6153d2565b83810360408501526155bb818a6153d2565b606085018990526001600160a01b038816608086015260a0850187905284810360c086015285518082528387019250908301905f5b8181101561560c578351835292840192918401916001016155f0565b50909c9b505050505050505050505050565b8060020b8114610f54575f80fd5b5f805f805f805f6101a0888a031215615643575f80fd5b873561564e8161561e565b9650602088013561565e8161561e565b9550604088013561566e8161561e565b9450606088013561567e8161561e565b9350608088013561568e8161540f565b925061569d8960a08a01615523565b91506156ad896101208a01615523565b905092959891949750929550565b5f805f805f61010086880312156156d0575f80fd5b853594506020860135935060408601356156e98161540f565b925060608601356156f98161540f565b91506157088760808801615523565b90509295509295909350565b6001600160801b0381168114610f54575f80fd5b5f805f806080858703121561573b575f80fd5b84359350602085013561574d81615714565b93969395505050506040820135916060013590565b5f805f8060e08587031215615775575f80fd5b8435935060208501356157878161540f565b925060408501356157978161540f565b91506157a68660608701615523565b905092959194509250565b60ff81168114610f54575f80fd5b5f602082840312156157cf575f80fd5b8135610c4e816157b1565b5f805f805f805f60e0888a0312156157f0575f80fd5b87356157fb8161540f565b9650602088013561580b8161540f565b955060408801359450606088013593506080880135615829816157b1565b9699959850939692959460a0840135945060c09093013592915050565b5f8060408385031215615857575f80fd5b82356158628161540f565b915060208301356158728161540f565b809150509250929050565b5f805f805f805f60e0888a031215615893575f80fd5b873561589e8161561e565b965060208801356158ae8161561e565b9550604088013594506060880135935060808801356158298161540f565b5f80604083850312156158dd575f80fd5b50508035926020909101359150565b5f602082840312156158fc575f80fd5b8135610c4e8161561e565b805161530e8161561e565b805161530e81615714565b5f805f805f805f60e0888a031215615933575f80fd5b875161593e8161540f565b602089015190975061594f8161561e565b604089015190965061ffff81168114615966575f80fd5b6060890151909550615977816157b1565b608089015190945061598881615714565b60a08901519093506159998161561e565b60c08901519092506159aa8161561e565b8091505092959891949750929550565b600181811c908216806159ce57607f821691505b602082108103613df057634e487b7160e01b5f52602260045260245ffd5b5f608082840312156159fc575f80fd5b615a046154ee565b8251615a0f8161540f565b81526020830151615a1f8161540f565b60208201526040830151615a328161540f565b60408201526060928301519281019290925250919050565b634e487b7160e01b5f52601160045260245ffd5b808201808211156109f8576109f8615a4a565b5f60208284031215615a81575f80fd5b5051919050565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601260045260245ffd5b5f8260020b80615ac257615ac2615a9c565b808360020b0791505092915050565b5f82615adf57615adf615a9c565b500490565b818103818111156109f8576109f8615a4a565b81516001600160a01b0390811682526020808401518216908301526040808401519091169082015260608083015190820152608081016109f8565b5f60208284031215615b42575f80fd5b8151610c4e8161540f565b805161530e8161540f565b8051801515811461530e575f80fd5b5f805f805f8060c08789031215615b7c575f80fd5b8651615b8781615714565b6020880151909650615b9881615714565b6040880151909550615ba98161540f565b606088015190945062ffffff81168114615bc1575f80fd5b9250615bcf60808801615b58565b915060a0870151615bdf8161540f565b809150509295509295509295565b82516001600160a01b0390811682526020808501518216908301526040808501519091169082015260609283015192810192909252608082015260a00190565b5f8060408385031215615c3e575f80fd5b505080516020909101519092909150565b815181526020808301516001600160a01b0316908201526040808301516001600160801b0390811691830191909152606092830151169181019190915260800190565b5f805f805f805f805f805f6101608c8e031215615cad575f80fd5b8b516affffffffffffffffffffff81168114615cc7575f80fd5b60208d0151909b50615cd88161540f565b60408d0151909a50615ce98161540f565b9850615cf760608d01615b4d565b9750615d0560808d01615907565b9650615d1360a08d01615907565b9550615d2160c08d01615912565b945060e08c015193506101008c01519250615d3f6101208d01615912565b9150615d4e6101408d01615912565b90509295989b509295989b9093969950565b5f60208284031215615d70575f80fd5b610c4e82615b58565b8181035f831280158383131683831282161715615d9857615d98615a4a565b5092915050565b80820281158282048414176109f8576109f8615a4a565b81516001600160a01b0316815261014081016020830151615de260208401826001600160a01b03169052565b506040830151615df7604084018260020b9052565b506060830151615e0c606084018260020b9052565b506080830151608083015260a083015160a083015260c083015160c083015260e083015160e083015261010080840151615e50828501826001600160a01b03169052565b505061012092830151919092015290565b5f805f8060808587031215615e74575f80fd5b845193506020850151615e8681615714565b6040860151606090960151949790965092505050565b5f805f8060808587031215615eaf575f80fd5b8451615eba8161540f565b6020860151909450615ecb8161540f565b6040860151909350615edc8161540f565b6060959095015193969295505050565b5f805f60608486031215615efe575f80fd5b8351615f0981615714565b602085015160409095015190969495509392505050565b5f805f805f8060c08789031215615f35575f80fd5b86519550602087015180600f0b8114615f4c575f80fd5b6040880151909550615f5d8161561e565b6060880151909450615f6e8161561e565b809350506080870151915060a087015190509295509295509295565b634e487b7160e01b5f52602160045260245ffd5b5f8251615faf8184602087016153b0565b91909101929150505600000000000000000000000024ecf7d3881256ccb518389a4f2716ac9bedd0e7000000000000000000000000c657e530019e91e267d97660e80c1f66e7d1afea000000000000000000000000a41bcca08dd84c0753ca1819369d078a4a44522c000000000000000000000000a8e22aac49b573581510e07ac5d07175518d57fb00000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000d615350484552452d574859504500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d615350484552452d574859504500000000000000000000000000000000000000

Deployed Bytecode

0x608060405234801561000f575f80fd5b50600436106103ca575f3560e01c8063888a913411610200578063d0c93a7c1161011f578063e1cace88116100b4578063f2fde38b11610084578063f2fde38b1461087e578063f7260d3e14610891578063f7c618c1146108a4578063f9d5111c146108b7578063fa082743146108ca575f80fd5b8063e1cace8814610832578063e43bff5814610845578063ef405caf14610858578063f085a6101461086b575f80fd5b8063dd56e5d8116100ef578063dd56e5d8146107e5578063dd62ed3e146107f8578063ddca3f431461080b578063e0525da91461081f575f80fd5b8063d0c93a7c146107a3578063d21220a7146107b7578063d2eabcfc146107ca578063d505accf146107d2575f80fd5b8063a855987211610195578063b44a272211610165578063b44a27221461076d578063c4a7761e14610780578063cb122a0914610788578063cce6776e1461079b575f80fd5b8063a855987214610729578063a9059cbb1461073c578063aaf5eb681461074f578063b1a3d53314610765575f80fd5b806395d89b41116101d057806395d89b41146106d9578063a049de6b146106e1578063a457c2d71461070e578063a4823eb414610721575f80fd5b8063888a91341461067a5780638da5cb5b1461068e5780638e3c92e41461069e5780638e5f5977146106b1575f80fd5b80633f4ba83a116102ec578063715018a61161028157806384b0196e1161025157806384b0196e14610626578063854cff2f1461064157806385919c5d1461065457806386a2908114610667575f80fd5b8063715018a6146105fa57806374cc0d1a146106025780637ecebe001461060b5780638456cb591461061e575f80fd5b80635c975abb116102bc5780635c975abb146105a45780636bb1972d146105b55780636d90a39c146105be57806370a08231146105d2575f80fd5b80633f4ba83a146105695780634690484014610571578063513ea8841461058457806351e87af714610597575f80fd5b806318160ddd11610362578063313ce56711610332578063313ce567146105315780633644e51514610546578063395093511461054e5780633d18b91214610561575f80fd5b806318160ddd146104a05780631a7d2f48146104b25780631e59ded31461050b57806323b872dd1461051e575f80fd5b80630dfe16811161039d5780630dfe16811461043b5780630f35bcac146104665780631056305e1461047a57806316f0115b1461048d575f80fd5b8063065e5360146103ce57806306fdde03146103ee578063095ea7b3146104035780630b40aaa114610426575b5f80fd5b6103d66108de565b60405160029190910b81526020015b60405180910390f35b6103f6610955565b6040516103e591906153fd565b610416610411366004615423565b6109e5565b60405190151581526020016103e5565b61043961043436600461544d565b6109fe565b005b60145461044e906001600160a01b031681565b6040516001600160a01b0390911681526020016103e5565b6018546103d6906301000000900460020b81565b610439610488366004615468565b610b50565b600b5461044e906001600160a01b031681565b6003545b6040519081526020016103e5565b6010546011546012546013546104d6936001600160a01b0390811693811692169084565b6040516103e594939291906001600160a01b039485168152928416602084015292166040820152606081019190915260800190565b61043961051936600461544d565b610bd3565b61041661052c3660046154b0565b610c30565b60125b60405160ff90911681526020016103e5565b6104a4610c55565b61041661055c366004615423565b610c63565b610439610c84565b610439610cc2565b601c5461044e906001600160a01b031681565b610439610592366004615570565b610cd2565b6018546103d69060020b81565b5f54600160a01b900460ff16610416565b6104a4601a5481565b601c5461041690600160a01b900460ff1681565b6104a46105e036600461544d565b6001600160a01b03165f9081526001602052604090205490565b610439610f57565b6104a460195481565b6104a461061936600461544d565b610f68565b610439610f85565b61062e610f95565b6040516103e5979695949392919061558a565b61043961064f36600461544d565b61101c565b61043961066236600461562c565b611046565b601b5461044e906001600160a01b031681565b6017546103d690600160d81b900460020b81565b5f546001600160a01b031661044e565b6104a46106ac3660046156bb565b611644565b6106c46106bf366004615728565b611677565b604080519283526020830191909152016103e5565b6103f66116ba565b6106e96116c9565b604080516001600160801b0390941684526020840192909252908201526060016103e5565b61041661071c366004615423565b611733565b6106c46117bd565b6106c4610737366004615762565b6118b4565b61041661074a366004615423565b611b43565b6104a46ec097ce7bc90715b34b9f100000000081565b610439611b50565b600c5461044e906001600160a01b031681565b6106c4611b79565b6104396107963660046157bf565b611caa565b6106c4611d11565b6017546103d690600160a81b900460020b81565b60155461044e906001600160a01b031681565b6106e9611d3b565b6104396107e03660046157da565b611da2565b600d5461044e906001600160a01b031681565b6104a4610806366004615846565b611f03565b60175461053490600160a01b900460ff1681565b6104a461082d3660046156bb565b611f2d565b6104a461084036600461587d565b611fe9565b6104396108533660046158cc565b612062565b60175461044e906001600160a01b031681565b6104396108793660046158ec565b612075565b61043961088c36600461544d565b6120a1565b600f5461044e906001600160a01b031681565b60165461044e906001600160a01b031681565b600e5461044e906001600160a01b031681565b6017546103d690600160c01b900460020b81565b600b54604080516397ce1c5160e01b815290515f926001600160a01b0316916397ce1c519160048083019260e09291908290030181865afa158015610925573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610949919061591d565b50939695505050505050565b606060048054610964906159ba565b80601f0160208091040260200160405190810160405280929190818152602001828054610990906159ba565b80156109db5780601f106109b2576101008083540402835291602001916109db565b820191905f5260205f20905b8154815290600101906020018083116109be57829003601f168201915b5050505050905090565b5f336109f2818585612117565b60019150505b92915050565b610a0661223a565b6001600160a01b038116610a18575f80fd5b600e80546001600160a01b0319166001600160a01b03838116918217909255600b54604051600162964af760e01b03198152921660048301525f9163ff69b50990602401608060405180830381865afa158015610a77573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a9b91906159ec565b8051601680546001600160a01b039283166001600160a01b03199182168117909255602080850151601780549186169184168217905560108054841685179055601180548416821790556040808701516012805491909716941684179095556060808701516013819055865195865292850191909152838501929092529082015290519192507fc23197554eb2c0fabeb181b2a679122e4621981948d957035228e0925104d67c919081900360800190a15050565b610b5861223a565b6001600160a01b03831615801590610b7857506001600160a01b03821615155b8015610b8c57506001600160a01b03811615155b610b94575f80fd5b600b80546001600160a01b039485166001600160a01b031991821617909155600c805493851693821693909317909255600d8054919093169116179055565b610bdb61223a565b600f80546001600160a01b0319166001600160a01b0383169081179091556040519081527f4a558665c36272d3508d1143a280d81be952c3abd93ffd377aed6b0b996205ad906020015b60405180910390a150565b5f33610c3d858285612293565b610c4885858561230b565b60019150505b9392505050565b5f610c5e6124b4565b905090565b5f336109f2818585610c758383611f03565b610c7f9190615a5e565b612117565b600f546001600160a01b03163314610c9a575f80fd5b60195415610cad57610cad6019546125dd565b601a5415610cc057610cc0601a546125dd565b565b610cca61223a565b610cc06128f4565b610cda612948565b610ce261223a565b610cea6129a1565b505060195415610cff57610cff6019546125dd565b601a5415610d1257610d12601a546125dd565b60195415610e3d57600b546019546017546014546040516370a0823160e01b8152306004820152610e3b946001600160a01b039081169493600160c01b8104600290810b94600160d81b909204900b929116906370a0823190602401602060405180830381865afa158015610d89573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610dad9190615a71565b6015546040516370a0823160e01b81523060048201526001600160a01b03909116906370a0823190602401602060405180830381865afa158015610df3573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e179190615a71565b87518860015b6020020151600c546001600160a01b03169796959493929190612ce6565b505b601a5415610f4a57600b54601a546018546014546040516370a0823160e01b8152306004820152610f48946001600160a01b039081169493600281810b946301000000909204900b929116906370a0823190602401602060405180830381865afa158015610ead573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ed19190615a71565b6015546040516370a0823160e01b81523060048201526001600160a01b03909116906370a0823190602401602060405180830381865afa158015610f17573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f3b9190615a71565b6040880151886003610e1d565b505b610f546001600a55565b50565b610f5f61223a565b610cc05f612d25565b6001600160a01b0381165f908152600860205260408120546109f8565b610f8d61223a565b610cc0612d74565b5f60608082808083610fc87f615350484552452d57485950450000000000000000000000000000000000000d6006612db6565b610ff37f31000000000000000000000000000000000000000000000000000000000000016007612db6565b604080515f80825260208201909252600f60f81b9b939a50919850469750309650945092509050565b61102461223a565b601b80546001600160a01b0319166001600160a01b0392909216919091179055565b61104e612948565b61105661223a565b8560020b8760020b128015611082575060175461107d90600160a81b900460020b88615ab0565b60020b155b80156110a557506017546110a090600160a81b900460020b87615ab0565b60020b155b80156110b657508360020b8560020b125b80156110d957506017546110d490600160a81b900460020b86615ab0565b60020b155b80156110fc57506017546110f790600160a81b900460020b85615ab0565b60020b155b801561111e57508560020b8460020b14158061111e57508660020b8560020b14155b801561113257506001600160a01b03831615155b61113a575f80fd5b601c80546001600160a01b0319166001600160a01b0385161790555f8061115f6129a1565b915091506019545f14611177576111776019546125dd565b601a541561118a5761118a601a546125dd565b601954156111e457600c546019545f916111af916001600160a01b0390911690612e5f565b505060195485519192506111e091309084908860015b6020020151600c546001600160a01b03169493929190612ef6565b5050505b601a541561122b57600c54601a545f91611209916001600160a01b0390911690612e5f565b5050601a5490915061122790308387600260200201518860036111c5565b5050505b7fbc4c20ad04f161d631d9ce94d27659391196415aa3c42f6a71c62e905ece782d6112546108de565b6014546040516370a0823160e01b81523060048201526001600160a01b03909116906370a0823190602401602060405180830381865afa15801561129a573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112be9190615a71565b6015546040516370a0823160e01b81523060048201526001600160a01b03909116906370a0823190602401602060405180830381865afa158015611304573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113289190615a71565b858561133360035490565b6040805160029790970b87526020870195909552938501929092526060840152608083015260a082015260c00160405180910390a16017805465ffffffffffff60c01b1916600160c01b62ffffff8c8116820262ffffff60d81b191692909217600160d81b928c1683021792839055600b546014546040516370a0823160e01b81523060048201526114b4956001600160a01b0393841695948104600290810b95909104900b92909116906370a0823190602401602060405180830381865afa158015611402573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114269190615a71565b6015546040516370a0823160e01b81523060048201526001600160a01b03909116906370a0823190602401602060405180830381865afa15801561146c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114909190615a71565b89518a60015b6020020151600c546001600160a01b03169695949392919030613079565b6019819055158015906114d157506012546001600160a01b031615155b156114e1576114e1601954613169565b6018805462ffffff89811665ffffffffffff1990921691909117630100000091891682021791829055600b546014546040516370a0823160e01b8152306004820152611602946001600160a01b0393841694600282810b959190920490910b9216906370a0823190602401602060405180830381865afa158015611567573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061158b9190615a71565b6015546040516370a0823160e01b81523060048201526001600160a01b03909116906370a0823190602401602060405180830381865afa1580156115d1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115f59190615a71565b60408a01518a6003611496565b601a8190551580159061161f57506012546001600160a01b031615155b1561162f5761162f601a54613169565b505061163b6001600a55565b50505050505050565b5f61164d612948565b61165561361a565b6116628686868686613666565b905061166e6001600a55565b95945050505050565b5f80611681612948565b61168961223a565b600c546116a3906001600160a01b03168730888888612ef6565b915091506116b16001600a55565b94509492505050565b606060058054610964906159ba565b5f805f601a545f036116e057505f92839250829150565b600c54601a546116f9916001600160a01b031690612e5f565b5050600b54601854919450611729916001600160a01b0390911690600281810b9163010000009004900b86613966565b9394909392509050565b5f33816117408286611f03565b9050838110156117a55760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b60648201526084015b60405180910390fd5b6117b28286868403612117565b506001949350505050565b5f806117c7611b79565b80925081935050505f805f806019545f1461180257600c54600b546019546117fc926001600160a01b039081169216906139fb565b90945092505b601a541561183057600c54600b54601a5461182a926001600160a01b039081169216906139fb565b90925090505b5f61183b8386615a5e565b90505f6118488386615a5e565b60175490915061186290600160a01b900460ff1683615ad1565b61186c9083615ae4565b60175490925061188690600160a01b900460ff1682615ad1565b6118909082615ae4565b905061189c8289615a5e565b97506118a88188615a5e565b96505050505050509091565b5f806118be612948565b6118c661361a565b5f86116118d1575f80fd5b6001600160a01b0385166118e3575f80fd5b6001600160a01b038416331461190c576040516330cd747160e01b815260040160405180910390fd5b6119146129a1565b505060195415611929576119296019546125dd565b601a541561193c5761193c601a546125dd565b5f805f8061196b601954601a548c8c61195460035490565b600c546001600160a01b031694939291908d613b36565b6014546040516370a0823160e01b815230600482015294985092965090945092505f916119f3916001600160a01b0316906370a0823190602401602060405180830381865afa1580156119c0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906119e49190615a71565b8c6119ee60035490565b613ba1565b6015546040516370a0823160e01b81523060048201529192505f91611a6e916001600160a01b0316906370a0823190602401602060405180830381865afa158015611a40573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a649190615a71565b8d6119ee60035490565b90508115611a8d57601454611a8d906001600160a01b03168c84613c35565b8015611aaa57601554611aaa906001600160a01b03168c83613c35565b81611ab58588615a5e565b611abf9190615a5e565b975080611acc8487615a5e565b611ad69190615a5e565b9650611ae28a8d613c9d565b604080518d8152602081018a90529081018890526001600160a01b03808d1691908c16907febff2602b3f468259e1e99f613fed6691f3a6526effe6ef3e768ba7ae7a36c4f9060600160405180910390a35050505050506116b16001600a55565b5f336109f281858561230b565b611b5861223a565b601c805460ff60a01b198116600160a01b9182900460ff1615909102179055565b5f805f80611b85611d3b565b92509250505f80611b946116c9565b6014546040516370a0823160e01b815230600482015292955090935084925086916001600160a01b03909116906370a0823190602401602060405180830381865afa158015611be5573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c099190615a71565b611c139190615a5e565b611c1d9190615a5e565b6015546040516370a0823160e01b8152306004820152919750829185916001600160a01b0316906370a0823190602401602060405180830381865afa158015611c68573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c8c9190615a71565b611c969190615a5e565b611ca09190615a5e565b9450505050509091565b611cb261223a565b5f8160ff1611611cc0575f80fd5b6017805460ff60a01b1916600160a01b60ff8481168202929092179283905560405192041681527f91f2ade82ab0e77bb6823899e6daddc07e3da0e3ad998577e7c09c2f38943c4390602001610c25565b601b545f9081906001600160a01b03163314611d2b575f80fd5b611d336129a1565b915091509091565b5f805f6019545f03611d5257505f92839250829150565b600c54601954611d6b916001600160a01b031690612e5f565b5050600b54601754919450611729916001600160a01b0390911690600160c01b8104600290810b91600160d81b9004900b86613966565b83421115611df25760405162461bcd60e51b815260206004820152601d60248201527f45524332305065726d69743a206578706972656420646561646c696e65000000604482015260640161179c565b5f7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9888888611e208c613dcf565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e0016040516020818303038152906040528051906020012090505f611e7a82613df6565b90505f611e8982878787613e22565b9050896001600160a01b0316816001600160a01b031614611eec5760405162461bcd60e51b815260206004820152601e60248201527f45524332305065726d69743a20696e76616c6964207369676e61747572650000604482015260640161179c565b611ef78a8a8a612117565b50505050505050505050565b6001600160a01b039182165f90815260026020908152604080832093909416825291909152205490565b5f611f36612948565b611f3e61361a565b611f4b8686308686613666565b600f54909150611f669030906001600160a01b03165f613e4a565b600f54611f7e9030906001600160a01b031683613e4a565b600f54604051637acb775760e01b8152600481018390526001600160a01b03868116602483015290911690637acb7757906044015f604051808303815f87803b158015611fc9575f80fd5b505af1158015611fdb573d5f803e3d5ffd5b5050505061166e6001600a55565b5f611ff2612948565b611ffa61223a565b601454601554600c54612024926001600160a01b039182169290821691168b8b8b8b8b8b8b613f5d565b9050801580159061203f57506012546001600160a01b031615155b1561204d5761204d81613169565b6120576001600a55565b979650505050505050565b61206a61223a565b601991909155601a55565b61207d61223a565b6017805462ffffff909216600160a81b0262ffffff60a81b19909216919091179055565b6120a961223a565b6001600160a01b03811661210e5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b606482015260840161179c565b610f5481612d25565b6001600160a01b0383166121795760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b606482015260840161179c565b6001600160a01b0382166121da5760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b606482015260840161179c565b6001600160a01b038381165f8181526002602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b5f546001600160a01b03163314610cc05760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161179c565b5f61229e8484611f03565b90505f19811461230557818110156122f85760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e6365000000604482015260640161179c565b6123058484848403612117565b50505050565b6001600160a01b03831661236f5760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b606482015260840161179c565b6001600160a01b0382166123d15760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b606482015260840161179c565b6001600160a01b0383165f90815260016020526040902054818110156124485760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b606482015260840161179c565b6001600160a01b038085165f8181526001602052604080822086860390559286168082529083902080548601905591517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906124a79086815260200190565b60405180910390a3612305565b5f306001600160a01b037f00000000000000000000000089a8f48b2a2d93910184c861077815c01090abf41614801561250c57507f00000000000000000000000000000000000000000000000000000000000003e746145b1561253657507f2f32f146a02b4edb42e7445f41f3e707d51bb0f0f7c7cf366ae1aa42f86e6d7990565b610c5e604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527fba4efd55f69b70de2e05e40e91c5bd5e3f9e84c41b040cd417640a34b049ffab918101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a08201525f9060c00160405160208183030381529060405280519060200120905090565b805f036125e75750565b5f6125f18261405d565b60408101519091506001600160a01b031661260a575050565b5f8160405160200161261c9190615af7565b60408051601f198184030181528282528051602091820120600d5463de2356d160e01b855292519094505f936001600160a01b039093169263de2356d19260048083019391928290030181865afa158015612679573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061269d9190615b32565b6001600160a01b03166360777795836040518263ffffffff1660e01b81526004016126ca91815260200190565b60c060405180830381865afa1580156126e5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127099190615b67565b50505050509050806001600160801b03165f036127265750505050565b600d54604051633578057760e11b81525f9182916001600160a01b0390911690636af00aee9061275c9088908a90600401615bed565b60408051808303815f875af1158015612777573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061279b9190615c2d565b9092509050811561282757600d548551600f54604051632f2d783d60e01b81526001600160a01b03928316600482015290821660248201525f6044820152911690632f2d783d906064016020604051808303815f875af1158015612801573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128259190615a71565b505b80156128b157600d546020860151600f54604051632f2d783d60e01b81526001600160a01b03928316600482015290821660248201525f6044820152911690632f2d783d906064016020604051808303815f875af115801561288b573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128af9190615a71565b505b604080518381526020810183905287917f3dddd974134793c524aaece0b9af4dd610a213cd4317cf0cb12c3613eafea8cd910160405180910390a2505050505050565b6128fc614199565b5f805460ff60a01b191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b6002600a540361299a5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604482015260640161179c565b6002600a55565b5f805f805f806019545f14612a4a57600c546040805160808101825260195481523060208201526001600160801b038183018190526060820152905163fc6f786560e01b81526001600160a01b039092169163fc6f786591612a0591600401615c4f565b60408051808303815f875af1158015612a20573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612a449190615c2d565b90945092505b601a5415612aec57600c5460408051608081018252601a5481523060208201526001600160801b038183018190526060820152905163fc6f786560e01b81526001600160a01b039092169163fc6f786591612aa791600401615c4f565b60408051808303815f875af1158015612ac2573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ae69190615c2d565b90925090505b60175460408051600160a01b90920460ff16825283860160208301819052838601918301829052975095507f4606b8a47eb284e8e80929101ece6ab5fe8d4f8735acc56bd0c92ca872f2cfe79060600160405180910390a16017545f90612b5d90600160a01b900460ff1688615ad1565b118015612bd157506014546040516370a0823160e01b81523060048201525f916001600160a01b0316906370a0823190602401602060405180830381865afa158015612bab573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612bcf9190615a71565b115b15612c1157601c54601754612c11916001600160a01b031690612bfe90600160a01b900460ff1689615ad1565b6014546001600160a01b03169190613c35565b6017545f90612c2a90600160a01b900460ff1687615ad1565b118015612c9e57506015546040516370a0823160e01b81523060048201525f916001600160a01b0316906370a0823190602401602060405180830381865afa158015612c78573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c9c9190615a71565b115b15612cde57601c54601754612cde916001600160a01b031690612ccb90600160a01b900460ff1688615ad1565b6015546001600160a01b03169190613c35565b505050509091565b5f80612cf58a898989896141e8565b90506001600160801b03811615612d1757612d148b8a8888888861426f565b91505b509998505050505050505050565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b612d7c61361a565b5f805460ff60a01b1916600160a01b1790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25861292b3390565b606060ff8314612dd057612dc983614350565b90506109f8565b818054612ddc906159ba565b80601f0160208091040260200160405190810160405280929190818152602001828054612e08906159ba565b8015612e535780601f10612e2a57610100808354040283529160200191612e53565b820191905f5260205f20905b815481529060010190602001808311612e3657829003601f168201915b505050505090506109f8565b5f805f835f03612e7657505f915081905080612eef565b60405163133f757160e31b8152600481018590526001600160a01b038616906399fbab889060240161016060405180830381865afa158015612eba573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ede9190615c92565b939c509a5091985050505050505050505b9250925092565b5f80846001600160801b03165f03612f1257505f90508061306e565b6040805160a0810182528881526001600160801b03878116602083019081528284018881526060840188815242608086019081529551630624e65f60e11b8152945160048601529151909216602484015290516044830152516064820152905160848201526001600160a01b03891690630c49ccbe9060a40160408051808303815f875af1158015612fa6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612fca9190615c2d565b604080516080810182528a81526001600160a01b038a811660208301526001600160801b038284018190526060830152915163fc6f786560e01b81529395509193505f928392918c169163fc6f7865916130279190600401615c4f565b60408051808303815f875af1158015613042573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130669190615c2d565b909450925050505b965096945050505050565b5f806130888a8a8a8a8a6141e8565b90506001600160801b03811615612d1757612d148b8b6001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa1580156130d9573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130fd9190615b32565b8c6001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa158015613139573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061315d9190615b32565b8c8c8c8c8a8d8d613f5d565b6012546001600160a01b031661317c5750565b600e54600b54604051600162964af760e01b031981526001600160a01b0391821660048201525f92919091169063ff69b50990602401608060405180830381865afa1580156131cd573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906131f191906159ec565b90505f816040516020016132059190615af7565b60408051601f198184030181529190528051602090910120905080158015906133095750600d5f9054906101000a90046001600160a01b03166001600160a01b031663de2356d16040518163ffffffff1660e01b8152600401602060405180830381865afa158015613279573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061329d9190615b32565b6001600160a01b031663b5bae00a826040518263ffffffff1660e01b81526004016132ca91815260200190565b602060405180830381865afa1580156132e5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906133099190615d60565b1561331357505050565b60105482516001600160a01b039081169116141580613345575060115460208301516001600160a01b03908116911614155b80613363575060125460408301516001600160a01b03908116911614155b806133745750601354606083015114155b156133ca578151601080546001600160a01b039283166001600160a01b03199182161790915560208401516011805491841691831691909117905560408401516012805491909316911617905560608201516013555b600c5460405163133f757160e31b8152600481018590525f9182916001600160a01b03909116906399fbab889060240161016060405180830381865afa158015613416573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061343a9190615c92565b505050505095509550505050505f600d5f9054906101000a90046001600160a01b03166001600160a01b031663de2356d16040518163ffffffff1660e01b8152600401602060405180830381865afa158015613498573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906134bc9190615b32565b6001600160a01b03166360777795856040518263ffffffff1660e01b81526004016134e991815260200190565b60c060405180830381865afa158015613504573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906135289190615b67565b505093505050508062ffffff168360020b8360020b6135479190615d79565b121561355557505050505050565b600c54600d54604051634197b18560e11b815260048101899052600160248201526001600160a01b03918216604482015291169063832f630a906064015f604051808303815f87803b1580156135a9575f80fd5b505af11580156135bb573d5f803e3d5ffd5b5050600d54604051635739f0b960e01b81526001600160a01b039091169250635739f0b991506135f19088908a90600401615bed565b5f604051808303815f87803b158015613608575f80fd5b505af1158015611ef7573d5f803e3d5ffd5b5f54600160a01b900460ff1615610cc05760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b604482015260640161179c565b5f8086118061367457505f85115b61367c575f80fd5b6001600160a01b03841661368e575f80fd5b601b546001600160a01b031633146136b957604051630b094f2760e31b815260040160405180910390fd5b6136c16129a1565b5050601954156136d6576136d66019546125dd565b601a54156136e9576136e9601a546125dd565b600b54604080516397ce1c5160e01b815290515f926001600160a01b0316916397ce1c519160048083019260e09291908290030181865afa158015613730573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613754919061591d565b50505050505090505f6137a2826001600160a01b0316670de0b6b3a764000061377d9190615d9f565b6137986001600160a01b038516670de0b6b3a7640000615d9f565b600160c01b613ba1565b90505f806137ae611b79565b915091506137cc8a846ec097ce7bc90715b34b9f1000000000613ba1565b6137d6908a615a5e565b945089156137f6576014546137f6906001600160a01b031688308d61438d565b881561381457601554613814906001600160a01b031688308c61438d565b5f61381e60035490565b905080156138fd575f61384184866ec097ce7bc90715b34b9f1000000000613ba1565b905061385287836119ee8685615a5e565b601c54909750600160a01b900460ff16156138fb576040805161014081018252600b546001600160a01b0390811682526019546020830152601a5492820192909252601754600160c01b8104600290810b6060840152600160d81b909104810b608083015260185480820b60a084015263010000009004900b60c082015260e081018e905261010081018d905261012081018a9052600c5490916138f79116826143c5565b5050505b505b61390789876145d5565b60408051878152602081018d90529081018b90526001600160a01b03808b1691908a16907f4e2ca0515ed1aef1395f66b5303bb5d6f1bf9d61a353fa53f73f8ac9973fa9f69060600160405180910390a3505050505095945050505050565b5f805f866001600160a01b03166397ce1c516040518163ffffffff1660e01b815260040160e060405180830381865afa1580156139a5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906139c9919061591d565b50505050505090506139ed816139de88614694565b6139e788614694565b8761496c565b925092505094509492505050565b5f805f805f805f805f8b6001600160a01b03166399fbab888b6040518263ffffffff1660e01b8152600401613a3291815260200190565b61016060405180830381865afa158015613a4e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613a729190615c92565b9a509a509a509a509a509a509a5050505050846001600160801b03165f03613aaf576001600160801b039182169850169550613b2e945050505050565b816001600160801b03169850806001600160801b031697505f80613ad48d8a8a614a06565b91509150858214613afe57613af9868303886001600160801b0316600160801b613ba1565b8b019a505b848114613b2457613b1f858203886001600160801b0316600160801b613ba1565b8a0199505b5050505050505050505b935093915050565b5f8080808915613b6857613b628b8b89613b528f8f8e8d614c7e565b89518a60015b6020020151612ef6565b90945092505b8815613b9357613b8d8b8a89613b808f8e8e8d614c7e565b60408a01518a6003613b58565b90925090505b975097509750979350505050565b5f838302815f1985870982811083820303915050808411613bc0575f80fd5b805f03613bd257508290049050610c4e565b838587095f8581038616958690049560026003880281188089028203028089028203028089028203028089028203028089028203028089029091030291819003819004600101858411909403939093029190930391909104170290509392505050565b6040516001600160a01b038316602482015260448101829052613c9890849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152614d20565b505050565b6001600160a01b038216613cfd5760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b606482015260840161179c565b6001600160a01b0382165f9081526001602052604090205481811015613d705760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b606482015260840161179c565b6001600160a01b0383165f8181526001602090815260408083208686039055600380548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3505050565b6001600160a01b0381165f9081526008602052604090208054600181018255905b50919050565b5f6109f8613e026124b4565b8360405161190160f01b8152600281019290925260228201526042902090565b5f805f613e3187878787614df3565b91509150613e3e81614ead565b5090505b949350505050565b801580613ec25750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa158015613e9c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ec09190615a71565b155b613f2d5760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527520746f206e6f6e2d7a65726f20616c6c6f77616e636560501b606482015260840161179c565b6040516001600160a01b038316602482015260448101829052613c9890849063095ea7b360e01b90606401613c61565b5f85158015613f6a575084155b15613f7657505f61404f565b8a6001600160a01b0316639cc1a2836040518061014001604052808d6001600160a01b031681526020018c6001600160a01b031681526020018b60020b81526020018a60020b8152602001898152602001888152602001868152602001858152602001876001600160a01b03168152602001428152506040518263ffffffff1660e01b81526004016140089190615db6565b6080604051808303815f875af1158015614024573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906140489190615e61565b5091925050505b9a9950505050505050505050565b604080516080810182525f808252602082018190529181018290526060810191909152600d54604051630b02c43d60e41b8152600481018490525f916001600160a01b03169063b02c43d090602401602060405180830381865afa1580156140c7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906140eb9190615a71565b600d54604051634613f8fb60e11b8152600481018390529192505f918291829182916001600160a01b031690638c27f1f690602401608060405180830381865afa15801561413b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061415f9190615e9c565b604080516080810182526001600160a01b039586168152938516602085015291909316908201526060810191909152979650505050505050565b5f54600160a01b900460ff16610cc05760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b604482015260640161179c565b5f80866001600160a01b03166397ce1c516040518163ffffffff1660e01b815260040160e060405180830381865afa158015614226573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061424a919061591d565b50505050505090506120578161425f88614694565b61426888614694565b8787614ff6565b5f8415801561427c575083155b1561428857505f614346565b6040805160c0810182528781526020810187815281830187815260608301878152608084018781524260a08601908152955163219f5d1760e01b8152945160048601529251602485015290516044840152516064830152516084820152905160a48201526001600160a01b0388169063219f5d179060c4016060604051808303815f875af115801561431c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906143409190615eec565b50909150505b9695505050505050565b60605f61435c836150ab565b6040805160208082528183019092529192505f91906020820181803683375050509182525060208101929092525090565b6040516001600160a01b03808516602483015283166044820152606481018290526123059085906323b872dd60e01b90608401613c61565b5f8082602001515f14614494575f8061440b855f015186606001518760800151614406895f01518a606001518b608001518c60e001518d61010001516141e8565b613966565b915091505f82118061441c57505f81115b15614491578460e0015182116144325781614438565b8460e001515b9350846101000151811161444c5780614453565b8461010001515b925061448f86866020015186868961012001515f6004811061447757614477615a88565b60200201516101208b015160015b602002015161426f565b505b50505b5f828460e00151116144a6575f6144b6565b828460e001516144b69190615ae4565b90505f82856101000151116144cb575f6144dc565b828561010001516144dc9190615ae4565b90505f8211806144eb57505f81115b80156144fa5750604085015115155b156145cc57845160a086015160c08701515f928392614520926144068383838b8b6141e8565b915091505f82118061453157505f81115b156145c9575f8483116145445782614546565b845b90505f8483116145565782614558565b845b90505f61459b8b8b6040015185858e610120015160026004811061457e5761457e615a88565b60200201518f610120015160036004811061448557614485615a88565b90506001600160801b038116156145c5576145b6838a615a5e565b98506145c28289615a5e565b97505b5050505b50505b50509250929050565b6001600160a01b03821661462b5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015260640161179c565b8060035f82825461463c9190615a5e565b90915550506001600160a01b0382165f818152600160209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b5f600282900b60171d62ffffff818401821816620d89e88111156146cb57604051633c10250f60e01b815260040160405180910390fd5b600160801b60018216156146ec57506ffffcb933bd6fad37aa2d162d1a5940015b600282161561470b576ffff97272373d413259a46990580e213a0260801c5b600482161561472a576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615614749576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615614768576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615614787576fff973b41fa98c081472e6896dfb254c00260801c5b60408216156147a6576fff2ea16466c96a3843ec78b326b528610260801c5b60808216156147c5576ffe5dee046a99a2a811c461f1969c30530260801c5b6101008216156147e5576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615614805576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615614825576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615614845576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615614865576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615614885576fa9f746462d870fdf8a65dc1f90e061e50260801c5b6140008216156148a5576f70d869a156d2a1b890bb3df62baf32f70260801c5b6180008216156148c5576f31be135f97d08fd981231505542fcfa60260801c5b620100008216156148e6576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615614906576e5d6af8dedb81196699c329225ee6040260801c5b62040000821061494c576204000082161561492f576d2216e584f5fa1ea926041bedfe980260801c5b6208000082161561494c576b048a170391f7dc42444e8fa20260801c5b5f8560020b131561495b575f19045b63ffffffff0160201c949350505050565b5f80836001600160a01b0316856001600160a01b0316111561498c579293925b846001600160a01b0316866001600160a01b0316116149b7576149b08585856150d2565b91506116b1565b836001600160a01b0316866001600160a01b031610156149f0576149dc8685856150d2565b91506149e9858785615140565b90506116b1565b6149fb858585615140565b905094509492505050565b5f805f856001600160a01b03166397ce1c516040518163ffffffff1660e01b815260040160e060405180830381865afa158015614a45573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614a69919061591d565b505060405163f30dba9360e01b815260028b900b60048201529395505f945084936001600160a01b038c16935063f30dba939250602401905060c060405180830381865afa158015614abd573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614ae19190615f20565b60405163f30dba9360e01b815260028d900b600482015291975095505f94508493506001600160a01b038d16925063f30dba93915060240160c060405180830381865afa158015614b34573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614b589190615f20565b95509550505050505f8a6001600160a01b0316636378ae446040518163ffffffff1660e01b8152600401602060405180830381865afa158015614b9d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614bc19190615a71565b90505f8b6001600160a01b031663ecdecf426040518163ffffffff1660e01b8152600401602060405180830381865afa158015614c00573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614c249190615a71565b90508a60020b8760020b1215614c435783860398508285039750614c6f565b8960020b8760020b1215614c64578386830303985082858203039750614c6f565b858403985084830397505b50505050505050935093915050565b60405163133f757160e31b8152600481018490525f9081906001600160a01b038716906399fbab889060240161016060405180830381865afa158015614cc6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614cea9190615c92565b5050505096505050505050505f614d0b826001600160801b03168686613ba1565b90506001600160801b03811115614346575f80fd5b5f614d74826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166151829092919063ffffffff16565b905080515f1480614d94575080806020019051810190614d949190615d60565b613c985760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840161179c565b5f807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0831115614e2857505f905060036116b1565b604080515f8082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa158015614e79573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b038116614ea1575f600192509250506116b1565b965f9650945050505050565b5f816004811115614ec057614ec0615f8a565b03614ec85750565b6001816004811115614edc57614edc615f8a565b03614f295760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e61747572650000000000000000604482015260640161179c565b6002816004811115614f3d57614f3d615f8a565b03614f8a5760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e67746800604482015260640161179c565b6003816004811115614f9e57614f9e615f8a565b03610f545760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b606482015260840161179c565b5f836001600160a01b0316856001600160a01b03161115615015579293925b846001600160a01b0316866001600160a01b03161161504057615039858585615190565b905061166e565b836001600160a01b0316866001600160a01b031610156150a0575f615066878686615190565b90505f6150748789866151f1565b9050806001600160801b0316826001600160801b0316106150955780615097565b815b9250505061166e565b6143468585846151f1565b5f60ff8216601f8111156109f857604051632cd44ac360e21b815260040160405180910390fd5b5f826001600160a01b0316846001600160a01b031611156150f1579192915b836001600160a01b031661512a606060ff16846001600160801b0316901b8686036001600160a01b0316866001600160a01b0316613ba1565b8161513757615137615a9c565b04949350505050565b5f826001600160a01b0316846001600160a01b0316111561515f579192915b613e42826001600160801b03168585036001600160a01b0316600160601b613ba1565b6060613e4284845f8561522d565b5f826001600160a01b0316846001600160a01b031611156151af579192915b5f6151d1856001600160a01b0316856001600160a01b0316600160601b613ba1565b905061166e6151ec84838888036001600160a01b0316613ba1565b6152f9565b5f826001600160a01b0316846001600160a01b03161115615210579192915b613e426151ec83600160601b8787036001600160a01b0316613ba1565b60608247101561528e5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b606482015260840161179c565b5f80866001600160a01b031685876040516152a99190615f9e565b5f6040518083038185875af1925050503d805f81146152e3576040519150601f19603f3d011682016040523d82523d5f602084013e6152e8565b606091505b509150915061205787838387615313565b806001600160801b038116811461530e575f80fd5b919050565b606083156153815782515f0361537a576001600160a01b0385163b61537a5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161179c565b5081613e42565b613e4283838151156153965781518083602001fd5b8060405162461bcd60e51b815260040161179c91906153fd565b5f5b838110156153ca5781810151838201526020016153b2565b50505f910152565b5f81518084526153e98160208601602086016153b0565b601f01601f19169290920160200192915050565b602081525f610c4e60208301846153d2565b6001600160a01b0381168114610f54575f80fd5b5f8060408385031215615434575f80fd5b823561543f8161540f565b946020939093013593505050565b5f6020828403121561545d575f80fd5b8135610c4e8161540f565b5f805f6060848603121561547a575f80fd5b83356154858161540f565b925060208401356154958161540f565b915060408401356154a58161540f565b809150509250925092565b5f805f606084860312156154c2575f80fd5b83356154cd8161540f565b925060208401356154dd8161540f565b929592945050506040919091013590565b6040516080810167ffffffffffffffff8111828210171561551d57634e487b7160e01b5f52604160045260245ffd5b60405290565b5f82601f830112615532575f80fd5b61553a6154ee565b80608084018581111561554b575f80fd5b845b8181101561556557803584526020938401930161554d565b509095945050505050565b5f60808284031215615580575f80fd5b610c4e8383615523565b60ff60f81b881681525f602060e0818401526155a960e084018a6153d2565b83810360408501526155bb818a6153d2565b606085018990526001600160a01b038816608086015260a0850187905284810360c086015285518082528387019250908301905f5b8181101561560c578351835292840192918401916001016155f0565b50909c9b505050505050505050505050565b8060020b8114610f54575f80fd5b5f805f805f805f6101a0888a031215615643575f80fd5b873561564e8161561e565b9650602088013561565e8161561e565b9550604088013561566e8161561e565b9450606088013561567e8161561e565b9350608088013561568e8161540f565b925061569d8960a08a01615523565b91506156ad896101208a01615523565b905092959891949750929550565b5f805f805f61010086880312156156d0575f80fd5b853594506020860135935060408601356156e98161540f565b925060608601356156f98161540f565b91506157088760808801615523565b90509295509295909350565b6001600160801b0381168114610f54575f80fd5b5f805f806080858703121561573b575f80fd5b84359350602085013561574d81615714565b93969395505050506040820135916060013590565b5f805f8060e08587031215615775575f80fd5b8435935060208501356157878161540f565b925060408501356157978161540f565b91506157a68660608701615523565b905092959194509250565b60ff81168114610f54575f80fd5b5f602082840312156157cf575f80fd5b8135610c4e816157b1565b5f805f805f805f60e0888a0312156157f0575f80fd5b87356157fb8161540f565b9650602088013561580b8161540f565b955060408801359450606088013593506080880135615829816157b1565b9699959850939692959460a0840135945060c09093013592915050565b5f8060408385031215615857575f80fd5b82356158628161540f565b915060208301356158728161540f565b809150509250929050565b5f805f805f805f60e0888a031215615893575f80fd5b873561589e8161561e565b965060208801356158ae8161561e565b9550604088013594506060880135935060808801356158298161540f565b5f80604083850312156158dd575f80fd5b50508035926020909101359150565b5f602082840312156158fc575f80fd5b8135610c4e8161561e565b805161530e8161561e565b805161530e81615714565b5f805f805f805f60e0888a031215615933575f80fd5b875161593e8161540f565b602089015190975061594f8161561e565b604089015190965061ffff81168114615966575f80fd5b6060890151909550615977816157b1565b608089015190945061598881615714565b60a08901519093506159998161561e565b60c08901519092506159aa8161561e565b8091505092959891949750929550565b600181811c908216806159ce57607f821691505b602082108103613df057634e487b7160e01b5f52602260045260245ffd5b5f608082840312156159fc575f80fd5b615a046154ee565b8251615a0f8161540f565b81526020830151615a1f8161540f565b60208201526040830151615a328161540f565b60408201526060928301519281019290925250919050565b634e487b7160e01b5f52601160045260245ffd5b808201808211156109f8576109f8615a4a565b5f60208284031215615a81575f80fd5b5051919050565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601260045260245ffd5b5f8260020b80615ac257615ac2615a9c565b808360020b0791505092915050565b5f82615adf57615adf615a9c565b500490565b818103818111156109f8576109f8615a4a565b81516001600160a01b0390811682526020808401518216908301526040808401519091169082015260608083015190820152608081016109f8565b5f60208284031215615b42575f80fd5b8151610c4e8161540f565b805161530e8161540f565b8051801515811461530e575f80fd5b5f805f805f8060c08789031215615b7c575f80fd5b8651615b8781615714565b6020880151909650615b9881615714565b6040880151909550615ba98161540f565b606088015190945062ffffff81168114615bc1575f80fd5b9250615bcf60808801615b58565b915060a0870151615bdf8161540f565b809150509295509295509295565b82516001600160a01b0390811682526020808501518216908301526040808501519091169082015260609283015192810192909252608082015260a00190565b5f8060408385031215615c3e575f80fd5b505080516020909101519092909150565b815181526020808301516001600160a01b0316908201526040808301516001600160801b0390811691830191909152606092830151169181019190915260800190565b5f805f805f805f805f805f6101608c8e031215615cad575f80fd5b8b516affffffffffffffffffffff81168114615cc7575f80fd5b60208d0151909b50615cd88161540f565b60408d0151909a50615ce98161540f565b9850615cf760608d01615b4d565b9750615d0560808d01615907565b9650615d1360a08d01615907565b9550615d2160c08d01615912565b945060e08c015193506101008c01519250615d3f6101208d01615912565b9150615d4e6101408d01615912565b90509295989b509295989b9093969950565b5f60208284031215615d70575f80fd5b610c4e82615b58565b8181035f831280158383131683831282161715615d9857615d98615a4a565b5092915050565b80820281158282048414176109f8576109f8615a4a565b81516001600160a01b0316815261014081016020830151615de260208401826001600160a01b03169052565b506040830151615df7604084018260020b9052565b506060830151615e0c606084018260020b9052565b506080830151608083015260a083015160a083015260c083015160c083015260e083015160e083015261010080840151615e50828501826001600160a01b03169052565b505061012092830151919092015290565b5f805f8060808587031215615e74575f80fd5b845193506020850151615e8681615714565b6040860151606090960151949790965092505050565b5f805f8060808587031215615eaf575f80fd5b8451615eba8161540f565b6020860151909450615ecb8161540f565b6040860151909350615edc8161540f565b6060959095015193969295505050565b5f805f60608486031215615efe575f80fd5b8351615f0981615714565b602085015160409095015190969495509392505050565b5f805f805f8060c08789031215615f35575f80fd5b86519550602087015180600f0b8114615f4c575f80fd5b6040880151909550615f5d8161561e565b6060880151909450615f6e8161561e565b809350506080870151915060a087015190509295509295509295565b634e487b7160e01b5f52602160045260245ffd5b5f8251615faf8184602087016153b0565b919091019291505056

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

00000000000000000000000024ecf7d3881256ccb518389a4f2716ac9bedd0e7000000000000000000000000c657e530019e91e267d97660e80c1f66e7d1afea000000000000000000000000a41bcca08dd84c0753ca1819369d078a4a44522c000000000000000000000000a8e22aac49b573581510e07ac5d07175518d57fb00000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000d615350484552452d574859504500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d615350484552452d574859504500000000000000000000000000000000000000

-----Decoded View---------------
Arg [0] : _pool (address): 0x24ecF7D3881256CCB518389A4f2716ac9BedD0E7
Arg [1] : _nonfungiblePositionManager (address): 0xc657e530019E91E267D97660E80C1F66e7D1AFeA
Arg [2] : _incentiveMaker (address): 0xA41bCca08dD84c0753ca1819369D078a4a44522c
Arg [3] : _receiver (address): 0xA8E22aac49b573581510E07ac5D07175518d57fB
Arg [4] : name (string): aSPHERE-WHYPE
Arg [5] : symbol (string): aSPHERE-WHYPE

-----Encoded View---------------
10 Constructor Arguments found :
Arg [0] : 00000000000000000000000024ecf7d3881256ccb518389a4f2716ac9bedd0e7
Arg [1] : 000000000000000000000000c657e530019e91e267d97660e80c1f66e7d1afea
Arg [2] : 000000000000000000000000a41bcca08dd84c0753ca1819369d078a4a44522c
Arg [3] : 000000000000000000000000a8e22aac49b573581510e07ac5d07175518d57fb
Arg [4] : 00000000000000000000000000000000000000000000000000000000000000c0
Arg [5] : 0000000000000000000000000000000000000000000000000000000000000100
Arg [6] : 000000000000000000000000000000000000000000000000000000000000000d
Arg [7] : 615350484552452d574859504500000000000000000000000000000000000000
Arg [8] : 000000000000000000000000000000000000000000000000000000000000000d
Arg [9] : 615350484552452d574859504500000000000000000000000000000000000000


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

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

Validator Index Block Amount
View All Withdrawals

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

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