MON Price: $0.018864 (+2.97%)

Contract

0xA93A5AE0C4ab23490af96a308a0E1DE0fd6E6dE3
Transaction Hash
Method
Block
From
To
Approve505724932026-01-23 10:39:0128 hrs ago1769164741IN
0xA93A5AE0...0fd6E6dE3
0 MON0.00539884101.94
Approve499773882026-01-20 16:25:323 days ago1768926332IN
0xA93A5AE0...0fd6E6dE3
0 MON0.00539161102
Approve491720102026-01-16 22:24:107 days ago1768602250IN
0xA93A5AE0...0fd6E6dE3
0 MON0.00810308102
Approve488575722026-01-15 11:14:469 days ago1768475686IN
0xA93A5AE0...0fd6E6dE3
0 MON0.00539884101.94
Approve477424762026-01-10 6:50:5014 days ago1768027850IN
0xA93A5AE0...0fd6E6dE3
0 MON0.00810308102
Withdraw470344202026-01-06 23:57:2417 days ago1767743844IN
0xA93A5AE0...0fd6E6dE3
0 MON0.13351881102
Transfer468126252026-01-05 23:10:1818 days ago1767654618IN
0xA93A5AE0...0fd6E6dE3
0 MON0.05295463107.1
Approve467339862026-01-05 14:18:4119 days ago1767622721IN
0xA93A5AE0...0fd6E6dE3
0 MON0.0079442100.0001
Approve454556642025-12-30 16:00:3524 days ago1767110435IN
0xA93A5AE0...0fd6E6dE3
0 MON0.00810298102
Approve451437612025-12-29 5:18:2526 days ago1766985505IN
0xA93A5AE0...0fd6E6dE3
0 MON0.00540141101.9885
Approve451270962025-12-29 3:27:1226 days ago1766978832IN
0xA93A5AE0...0fd6E6dE3
0 MON0.00361736102.09599087
Approve451270512025-12-29 3:26:5426 days ago1766978814IN
0xA93A5AE0...0fd6E6dE3
0 MON0.0217909100
Approve451269002025-12-29 3:25:5426 days ago1766978754IN
0xA93A5AE0...0fd6E6dE3
0 MON0.02102023101.9885
Approve451268162025-12-29 3:25:2026 days ago1766978720IN
0xA93A5AE0...0fd6E6dE3
0 MON0.03447231101.9885
Approve444618872025-12-26 0:57:2129 days ago1766710641IN
0xA93A5AE0...0fd6E6dE3
0 MON0.00359437102
Approve426489102025-12-17 15:01:0038 days ago1765983660IN
0xA93A5AE0...0fd6E6dE3
0 MON0.00594804102.10004247
Approve426333582025-12-17 13:17:0438 days ago1765977424IN
0xA93A5AE0...0fd6E6dE3
0 MON0.00539636101.89323341
Approve425075812025-12-16 23:17:0638 days ago1765927026IN
0xA93A5AE0...0fd6E6dE3
0 MON0.00594804102.10004247
Approve424700352025-12-16 19:06:2938 days ago1765911989IN
0xA93A5AE0...0fd6E6dE3
0 MON0.0120593227.70163659
Approve423369082025-12-16 4:15:1039 days ago1765858510IN
0xA93A5AE0...0fd6E6dE3
0 MON0.00552718104
Approve421738152025-12-15 10:03:3640 days ago1765793016IN
0xA93A5AE0...0fd6E6dE3
0 MON0.00594804102.10004247
Approve421019152025-12-15 2:02:2540 days ago1765764145IN
0xA93A5AE0...0fd6E6dE3
0 MON0.008262120
Approve420262682025-12-14 17:34:1440 days ago1765733654IN
0xA93A5AE0...0fd6E6dE3
0 MON0.00545498103
Approve417987252025-12-13 16:09:3741 days ago1765642177IN
0xA93A5AE0...0fd6E6dE3
0 MON0.00818252103
Approve415915522025-12-12 17:02:1342 days ago1765558933IN
0xA93A5AE0...0fd6E6dE3
0 MON0.00594221102
View all transactions

Latest 1 internal transaction

Advanced mode:
Parent Transaction Hash Block From To
379221772025-11-25 14:50:0060 days ago1764082200  Contract Creation0 MON
Loading...
Loading

Similar Match Source Code
This contract matches the deployed Bytecode of the Source Code for Contract 0x05a5a933...B9cfe41Ba
The constructor portion of the code might be different and could alter the actual behaviour of the contract

Contract Name:
ICHIVault

Compiler Version
v0.8.20+commit.a1b79de6

Optimization Enabled:
Yes with 200 runs

Other Settings:
paris EvmVersion

Contract Source Code (Solidity Standard Json-Input format)

File 1 of 49 : ICHIVault.sol
// SPDX-License-Identifier: BUSL-1.1

pragma solidity >=0.8.4;

import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { UV3Math } from "./lib/UV3Math.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";

import {
    IAlgebraSwapCallback
} from "@cryptoalgebra/integral-core/contracts/interfaces/callback/IAlgebraSwapCallback.sol";
import { IAlgebraPool } from "@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol";
import {
    INonfungiblePositionManager
} from "@cryptoalgebra/integral-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
import { IFarmingCenter } from "@cryptoalgebra/integral-farming/contracts/interfaces/IFarmingCenter.sol";
import { IIncentiveMaker } from "../interfaces/IIncentiveMaker.sol";
import { IncentiveKey } from  "@cryptoalgebra/integral-farming/contracts/base/IncentiveKey.sol";
import { IERC20Minimal } from "@cryptoalgebra/integral-core/contracts/interfaces/IERC20Minimal.sol";

import { IICHIVault } from "../interfaces/IICHIVault.sol";
import { IICHIVaultFactory } from "../interfaces/IICHIVaultFactory.sol";

/**
 @notice A Uniswap V2-like interface with fungible liquidity to Uniswap V3
 which allows for either one-sided or two-sided liquidity provision.
 ICHIVaults should be deployed by the ICHIVaultFactory.
 ICHIVaults should not be used with tokens that charge transaction fees.
 */

/// Error Codes:
///     ADP - Algebra disconnected plugin
///     BPI - Base position invalid
///     DTL - Deposit, try later
///     DNA - Deposit, token not allowed or amount is zero or amount is too large
///     IIP - Identical positions
///     LPI - Limit position invalid
///     MSS - Must be single sided
///     MPR - Missing period
///     NAT - No allowed tokens
///     ONO - Caller is not the owner
///     PIL - Pool is locked
///     RNA - Roles: not an admin
///     RRD - Roles: not a depositor
///     RRR - Roles: not a rebalancer
///     UBR - Unexpected burn
///     WMS - Withdraw, min shares
///     WTO - Withdraw, tokens owed
///     WZH - Withdraw zero shares
///     ZAD - Zero address

contract ICHIVault is IICHIVault, IAlgebraSwapCallback, ERC20, ReentrancyGuard, Ownable {
    using SafeERC20 for IERC20;
    using SafeMath for uint256;

    address public immutable override ichiVaultFactory;
    address public immutable override pool;
    address public immutable override token0;
    address public immutable override token1;
    bool public immutable override allowToken0;
    bool public immutable override allowToken1;

    address public override ammFeeRecipient;
    address public override affiliate;
    address public override farmingContract;

    // Position tracking
    uint256 public override basePositionId;
    uint256 public override limitPositionId;

    uint256 public override deposit0Max;
    uint256 public override deposit1Max;
    uint256 public override hysteresis;

    uint256 public constant PRECISION = 10 ** 18;
    //uint256 constant PERCENT = 100;
    address constant NULL_ADDRESS = address(0);
    uint256 constant MIN_SHARES = 1000;

    uint32 public override twapPeriod;
    uint32 public override auxTwapPeriod;

    /**
     @notice Creates an ICHIVault instance based on Uniswap V3 pool. Controls liquidity provision types.
     @param _pool Address of the Uniswap V3 pool for liquidity management.
     @param _allowToken0 Flag indicating if token0 deposits are allowed.
     @param _allowToken1 Flag indicating if token1 deposits are allowed.
     @param __owner Owner address of the ICHIVault.
     @param _twapPeriod TWAP period for hysteresis checks.
     @param _vaultIndex Index of the vault in the factory.
     */
    constructor(
        address _pool,
        bool _allowToken0,
        bool _allowToken1,
        address __owner,
        uint32 _twapPeriod,
        uint256 _vaultIndex
    ) ERC20("ICHI Vault Liquidity", UV3Math.computeIVsymbol(_vaultIndex, _pool, _allowToken0)) {
        require(_pool != NULL_ADDRESS, "ZAD");
        require((_allowToken0 && !_allowToken1) ||
                (_allowToken1 && !_allowToken0), "MSS");

        ichiVaultFactory = msg.sender;
        pool = _pool;
        token0 = IAlgebraPool(_pool).token0();
        token1 = IAlgebraPool(_pool).token1();
        allowToken0 = _allowToken0;
        allowToken1 = _allowToken1;
        twapPeriod = _twapPeriod;
        auxTwapPeriod = _twapPeriod / 4; // default value is a quarter of the TWAP period

        transferOwnership(__owner);

        hysteresis = PRECISION.div(200); // 0.5% threshold
        deposit0Max = type(uint256).max; // max uint256
        deposit1Max = type(uint256).max; // max uint256
        ammFeeRecipient = NULL_ADDRESS; // by default there is no amm fee recipient address;
        affiliate = NULL_ADDRESS; // by default there is no affiliate address
        farmingContract = NULL_ADDRESS; // by default there is no farming contract address

        // Approve NFT manager to spend tokens
        IERC20(token0).approve(IICHIVaultFactory(ichiVaultFactory).nftManager(), type(uint256).max);
        IERC20(token1).approve(IICHIVaultFactory(ichiVaultFactory).nftManager(), type(uint256).max);

        emit DeployICHIVault(msg.sender, _pool, _allowToken0, _allowToken1, __owner, _twapPeriod);
    }

    function _onlyOwner() private view {
        require(owner() == _msgSender(), "ONO");
    }

    /// @notice gets baseLower tick from the base position
    /// @return int24 baseLower tick
    function baseLower() external view override returns (int24) {
        if (basePositionId == 0) return 0;
        (,,,,,int24 tickLower,,,,,,) = _nftManager().positions(basePositionId);
        return tickLower;
    }

    /// @notice gets baseUpper tick from the base position
    /// @return int24 baseUpper tick
    function baseUpper() external view override returns (int24) {
        if (basePositionId == 0) return 0;
        (,,,,,,int24 tickUpper,,,,,) = _nftManager().positions(basePositionId);
        return tickUpper;
    }

    /// @notice gets limitLower tick from the limit position
    /// @return int24 limitLower tick
    function limitLower() external view override returns (int24) {
        if (limitPositionId == 0) return 0;
        (,,,,,int24 tickLower,,,,,,) = _nftManager().positions(limitPositionId);
        return tickLower;
    }

    /// @notice gets limitUpper tick from the limit position
    /// @return int24 limitUpper tick
    function limitUpper() external view override returns (int24) {
        if (limitPositionId == 0) return 0;
        (,,,,,,int24 tickUpper,,,,,) = _nftManager().positions(limitPositionId);
        return tickUpper;
    }

    /// @notice resets allowances for the NFT manager
    function resetAllowances() external override {
        _onlyOwner();
        address nftManager = address(_nftManager());
        IERC20(token0).approve(nftManager, type(uint256).max);
        IERC20(token1).approve(nftManager, type(uint256).max);
    }

    /// @notice sets TWAP period for hysteresis checks
    /// @dev onlyOwner
    /// @param newTwapPeriod new TWAP period
    function setTwapPeriod(uint32 newTwapPeriod) external override {
        _onlyOwner();
        require(newTwapPeriod > 0, "MPR");
        twapPeriod = newTwapPeriod;
        emit SetTwapPeriod(msg.sender, newTwapPeriod);
    }

    /// @notice sets auxiliary TWAP period for hysteresis checks
    /// @dev onlyOwner
    /// @dev aux TWAP could be set to 0 to avoid an additional check
    /// @param newAuxTwapPeriod new auxiliary TWAP period
    function setAuxTwapPeriod(uint32 newAuxTwapPeriod) external override {
        _onlyOwner();
        auxTwapPeriod = newAuxTwapPeriod;
        emit SetAuxTwapPeriod(msg.sender, newAuxTwapPeriod);
    }

    /// @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 {
        // Get the key from incentive maker
        IncentiveKey memory key = _incentiveMaker().poolToKey(address(pool));
        // if the pool is not in the incentive maker, return
        if (address(key.pool) == NULL_ADDRESS) return;

        _nftManager().approveForFarming(
            tokenId,
            true,
            address(_farmingCenter())
        );

        // Enter farming
        _farmingCenter().enterFarming(key, tokenId);
    }

    function _collectAndClaimRewards(uint256 tokenId) internal {
        if (tokenId == 0) return;

        // Collect rewards
        IncentiveKey memory key = _getKeyForToken(tokenId);
        // if the pool is not in the incentive maker, return
        if (address(key.pool) == NULL_ADDRESS) return;

        address recipient = farmingContract != NULL_ADDRESS ? farmingContract : affiliate;
        // not reverting, to avoid a hypothetical situation where withdraws are blocked because of missing recipient
        if (recipient == NULL_ADDRESS) return;

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

        // Claim
        if (reward > 0) {
            _farmingCenter().claimReward(key.rewardToken, recipient, reward);
        }

        if (bonusReward > 0) {
            _farmingCenter().claimReward(key.bonusRewardToken, recipient, bonusReward);
        }

        // assuming reward and bonusReward are known
        emit RewardsCollected(
            reward,
            bonusReward
        );
    }

    /**
     @notice Collect rewards and sends them to the farming contract.
     */
    function collectRewards() external override nonReentrant {
        if (basePositionId != 0) _collectAndClaimRewards(basePositionId);
        if (limitPositionId != 0) _collectAndClaimRewards(limitPositionId);
    }

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

    /// @notice collects fees and tokens from the positions and burns the NFTs
    /// @param positionId NFT position ID
    function _dismantlePosition(uint256 positionId) internal {
        if (positionId != 0) {
            uint128 positionLiquidity = _getPositionLiquidity(positionId);
            if (positionLiquidity > 0) {
                _nftManager().decreaseLiquidity(
                    INonfungiblePositionManager.DecreaseLiquidityParams({
                        tokenId: positionId,
                        liquidity: positionLiquidity,
                        amount0Min: 0,
                        amount1Min: 0,
                        deadline: block.timestamp
                    })
                );
            }

            _nftManager().collect(
                INonfungiblePositionManager.CollectParams({
                    tokenId: positionId,
                    recipient: address(this),
                    amount0Max: type(uint128).max,
                    amount1Max: type(uint128).max
                })
            );
            _nftManager().burn(positionId);
            // not setting positionId to 0, as it is done in the rebalance->mint functions
        }
    }

    /// @notice gets NFT manager
    /// @return INonfungiblePositionManager NFT manager
    function _nftManager() internal view returns (INonfungiblePositionManager) {
        return INonfungiblePositionManager(IICHIVaultFactory(ichiVaultFactory).nftManager());
    }

    /// @notice gets Farming center
    /// @return IFarmingCenter Farming center
    function _farmingCenter() internal view returns (IFarmingCenter) {
        return IFarmingCenter(IICHIVaultFactory(ichiVaultFactory).farmingCenter());
    }

    /// @notice gets Incentive maker
    /// @return IIncentiveMaker Incentive maker
    function _incentiveMaker() internal view returns (IIncentiveMaker) {
        return IIncentiveMaker(IICHIVaultFactory(ichiVaultFactory).incentiveMaker());
    }

    /// @notice collects fees from the position
    /// @param positionId NFT position ID
    function _collectFromPosition(uint256 positionId) internal returns (uint256 fees0, uint256 fees1) {
        if (positionId == 0) {
            return (0, 0);
        }
        (uint256 _fees0, uint256 _fees1) = _nftManager().collect(
            INonfungiblePositionManager.CollectParams({
                tokenId: positionId,
                recipient: address(this),
                amount0Max: type(uint128).max,
                amount1Max: type(uint128).max
            })
        );
        fees0 = _fees0;
        fees1 = _fees1;
    }

    /// @notice collects fees from both positions and distributes them
    /// @param withEvent flag to emit CollectFees event (false in rebalances, true otherwise)
    /// @return fees0 collected fees in token0
    /// @return fees1 collected fees in token1
    function _cleanPositions(bool withEvent) internal returns (uint256 fees0, uint256 fees1) {
        fees0 = 0;
        fees1 = 0;
        if (basePositionId != 0) {
            _collectAndClaimRewards(basePositionId);
            (uint256 feesBase0, uint256 feesBase1) = _collectFromPosition(basePositionId);
            fees0 = fees0.add(feesBase0);
            fees1 = fees1.add(feesBase1);
        }
        if (limitPositionId != 0) {
            _collectAndClaimRewards(limitPositionId);
            (uint256 feesLimit0, uint256 feesLimit1) = _collectFromPosition(limitPositionId);
            fees0 = fees0.add(feesLimit0);
            fees1 = fees1.add(feesLimit1);
        }
        if (fees0 > 0 || fees1 > 0) {
            _distributeFees(fees0, fees1);
            if (withEvent) {

                (uint160 sqrtPriceX96, int24 tick_, , , , ) = IAlgebraPool(pool).globalState();
                (uint256 totalAmount0, uint256 totalAmount1) = _getTotalAmountsWithPrice(sqrtPriceX96);
                
                emit CollectFees(
                    msg.sender,
                    fees0,
                    fees1,
                    pool,
                    totalSupply(),
                    tick_,
                    totalAmount0,
                    totalAmount1,
                    sqrtPriceX96
                );
            }
        }
    }

    /**
    @notice Internal function to mint an NFT position
    @param tickLower Lower tick of the position
    @param tickUpper Upper tick of the position
    @param amount0Desired Desired amount of token0
    @param amount1Desired Desired amount of token1
    @return positionId ID of the minted NFT position
    */
    function _mintPosition(
        int24 tickLower,
        int24 tickUpper,
        uint256 amount0Desired,
        uint256 amount1Desired
    ) internal returns (uint256 positionId) {
        // Don't try to mint if we don't have any tokens
        if (amount0Desired == 0 && amount1Desired == 0) {
            return 0;
        }

        // Get current tick to determine if position can be minted
        int24 currentTick = currentTick();

        // If current tick is within or on the boundaries of our range, we need both tokens
        if (currentTick >= tickLower && currentTick < tickUpper) {
            if (amount0Desired == 0 || amount1Desired == 0) {
                return 0;
            }
        }
        // If entirely above current tick (not including boundary), we only need token0
        else if (currentTick < tickLower) {
            if (amount0Desired == 0) {
                return 0;
            }
        }
        // If entirely below current tick (including boundary), we only need token1
        else if (currentTick >= tickUpper) {
            if (amount1Desired == 0) {
                return 0;
            }
        }

        (positionId, , , ) = _nftManager().mint(
            INonfungiblePositionManager.MintParams({
                token0: token0,
                token1: token1,
                deployer: address(0),
                tickLower: tickLower,
                tickUpper: tickUpper,
                amount0Desired: amount0Desired,
                amount1Desired: amount1Desired,
                amount0Min: 0,
                amount1Min: 0,
                recipient: address(this),
                deadline: block.timestamp
            })
        );

        // Approve and enter farming center
        _approveAndEnterFarming(positionId);
    }

    /// @notice mints base position
    /// @param _baseLower lower tick of the base position
    /// @param _baseUpper upper tick of the base position
    /// @param amount0Desired desired amount of token0
    /// @param amount1Desired desired amount of token1
    function _mintBasePosition(
        int24 _baseLower,
        int24 _baseUpper,
        uint256 amount0Desired,
        uint256 amount1Desired
    ) internal {
        basePositionId = _mintPosition(_baseLower, _baseUpper, amount0Desired, amount1Desired);
    }

    /// @notice mints limit position
    /// @param _limitLower lower tick of the limit position
    /// @param _limitUpper upper tick of the limit position
    /// @param amount0Desired desired amount of token0
    /// @param amount1Desired desired amount of token1
    function _mintLimitPosition(
        int24 _limitLower,
        int24 _limitUpper,
        uint256 amount0Desired,
        uint256 amount1Desired
    ) internal {
        limitPositionId = _mintPosition(_limitLower, _limitUpper, amount0Desired, amount1Desired);
    }

    /** @notice Helper function to get the most conservative price
     @param spot Current spot price
     @param twap TWAP price
     @param auxTwap Auxiliary TWAP price
     @param isPool Flag indicating if the valuation is for the pool or deposit
     @return price Most conservative price
    */
    function _getConservativePrice(
        uint256 spot,
        uint256 twap,
        uint256 auxTwap,
        bool isPool
    ) internal view returns (uint256 price) {
        if (isPool) {
            // For pool valuation, use highest price to be conservative
            price = max(spot, twap);
            if (auxTwapPeriod > 0) {
                price = max(price, auxTwap);
            }
        } else {
            // For deposit valuation, use lowest price to be conservative
            price = min(spot, twap);
            if (auxTwapPeriod > 0) {
                price = min(price, auxTwap);
            }
        }
    }

    /**
     @notice Distributes shares based on token1 value, adjusted by liquidity shares and pool's AUM in token1.
     @param deposit0 Token0 amount transferred from sender to ICHIVault.
     @param deposit1 Token1 amount transferred from sender to ICHIVault.
     @param to Recipient address for minted liquidity tokens.
     @return shares Number of liquidity tokens minted for deposit.
     */
    function deposit(
        uint256 deposit0,
        uint256 deposit1,
        address to
    ) external override nonReentrant returns (uint256 shares) {
        require((allowToken0 && deposit0 > 0 && deposit0 < deposit0Max && deposit1 == 0) ||
                (allowToken1 && deposit1 > 0 && deposit1 < deposit1Max && deposit0 == 0), "DNA");
        require(to != NULL_ADDRESS && to != address(this), "ZAD");

        // Get current pool state once (optimization: single globalState call)
        (uint160 sqrtPriceX96, int24 cachedTick, , , , ) = IAlgebraPool(pool).globalState();
        
        // Get spot price using cached tick
        uint256 price = _fetchSpot(token0, token1, cachedTick, PRECISION);

        // Get TWAP price
        uint256 twap = _fetchTwap(pool, token0, token1, twapPeriod, PRECISION);

        // Get aux TWAP price if aux period is set (otherwise set it equal to the TWAP price)
        uint256 auxTwap = auxTwapPeriod > 0
            ? _fetchTwap(pool, token0, token1, auxTwapPeriod, PRECISION)
            : twap;

        // Check price manipulation
        UV3Math._checkPriceManipulation(price, twap, auxTwap, auxTwapPeriod, hysteresis, _getBasePluginFromPool());

        // Clean positions and collect/distribute fees
        _cleanPositions(true);

        // Get total amounts including current positions with updated fees
        (uint256 pool0, uint256 pool1) = getTotalAmounts();

        // Transfer tokens from depositor
        if (deposit0 > 0) {
            IERC20(token0).safeTransferFrom(msg.sender, address(this), deposit0);
        }
        if (deposit1 > 0) {
            IERC20(token1).safeTransferFrom(msg.sender, address(this), deposit1);
        }

        // Calculate share value in token1
        uint256 priceForDeposit = _getConservativePrice(price, twap, auxTwap, false);
        uint256 deposit0PricedInToken1 = deposit0.mul(priceForDeposit).div(PRECISION);

        // Calculate shares to mint
        shares = deposit1.add(deposit0PricedInToken1);

        if (totalSupply() != 0) {
            uint256 priceForPool = _getConservativePrice(price, twap, auxTwap, true);
            uint256 pool0PricedInToken1 = pool0.mul(priceForPool).div(PRECISION);
            shares = shares.mul(totalSupply()).div(pool0PricedInToken1.add(pool1));
        } else {
            shares = shares.mul(MIN_SHARES);
        }

        _mint(to, shares);

        // Calculate total amounts after deposit (using cached values)
        uint256 total0 = pool0.add(deposit0);
        uint256 total1 = pool1.add(deposit1);

        emit Deposit(
            msg.sender, 
            to, 
            shares, 
            deposit0, 
            deposit1,
            pool,
            total0,
            total1,
            totalSupply(),
            cachedTick,  // use cached tick
            sqrtPriceX96   // use cached price
        );
    }

    /**
    @notice Decreases liquidity from NFT position proportional to shares
    @param positionId NFT position ID
    @param shares Amount of shares being withdrawn
    @param totalSupply Total supply of shares
    @param to Address to receive tokens
    @return amount0 Token0 amount withdrawn
    @return amount1 Token1 amount withdrawn
    */
    function _withdrawFromPosition(
        uint256 positionId,
        uint256 shares,
        uint256 totalSupply,
        address to
    ) internal returns (uint256 amount0, uint256 amount1) {
        // this function is always called after _cleanPositions is aleady called

        // Get position info
        (
            ,
            ,
            ,
            ,
            ,
            ,
            ,
            uint128 positionLiquidity,
            ,
            ,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        ) = _nftManager().positions(positionId);

        // should not be happening, safety check
        require(tokensOwed0 == 0 && tokensOwed1 == 0, "WTO");

        // Calculate proportional liquidity
        uint128 liquidityToDecrease = uint128(uint256(positionLiquidity).mul(shares).div(totalSupply));

        if (liquidityToDecrease > 0) {
            // Decrease liquidity
            (amount0, amount1) = _nftManager().decreaseLiquidity(
                INonfungiblePositionManager.DecreaseLiquidityParams({
                    tokenId: positionId,
                    liquidity: liquidityToDecrease,
                    amount0Min: 0,
                    amount1Min: 0,
                    deadline: block.timestamp
                })
            );

            // Collect tokens
            _nftManager().collect(
                INonfungiblePositionManager.CollectParams({
                    tokenId: positionId,
                    recipient: to,
                    amount0Max: uint128(amount0),
                    amount1Max: uint128(amount1)
                })
            );
        }
    }
    /**
     @notice Redeems shares for a proportion of ICHIVault's AUM, matching the share percentage of total issued.
     @param shares Quantity of liquidity tokens to redeem as pool assets.
     @param to Address receiving the redeemed pool assets.
     @return amount0 Token0 amount received from liquidity token redemption.
     @return amount1 Token1 amount received from liquidity token redemption.
     */
    function withdraw(
        uint256 shares,
        address to
    ) external override nonReentrant returns (uint256 amount0, uint256 amount1) {
        require(shares > 0, "WZH");
        require(to != NULL_ADDRESS, "ZAD");

        uint256 _totalSupply = totalSupply();
        require(shares == _totalSupply || _totalSupply >= shares.add(MIN_SHARES), "WMS");

        // Clean positions and collect/distribute fees
        _cleanPositions(true);

        // Withdraw from positions
        uint256 base0;
        uint256 base1;
        uint256 limit0;
        uint256 limit1;

        if (basePositionId != 0) {
            (base0, base1) = _withdrawFromPosition(basePositionId, shares, _totalSupply, to);
        }

        if (limitPositionId != 0) {
            (limit0, limit1) = _withdrawFromPosition(limitPositionId, shares, _totalSupply, to);
        }

        // Add proportional share of unused balances
        uint256 unusedAmount0 = IERC20(token0).balanceOf(address(this)).mul(shares).div(_totalSupply);
        uint256 unusedAmount1 = IERC20(token1).balanceOf(address(this)).mul(shares).div(_totalSupply);
        if (unusedAmount0 > 0) IERC20(token0).safeTransfer(to, unusedAmount0);
        if (unusedAmount1 > 0) IERC20(token1).safeTransfer(to, unusedAmount1);

        // Calculate total amounts returned
        amount0 = base0.add(limit0).add(unusedAmount0);
        amount1 = base1.add(limit1).add(unusedAmount1);

        _burn(msg.sender, shares);

        // Get pool state once (optimization: single globalState call)
        (uint160 sqrtPriceX96, int24 cachedTick, , , , ) = IAlgebraPool(pool).globalState();
        (uint256 total0, uint256 total1) = getTotalAmounts();

        emit Withdraw(
            msg.sender, 
            to, 
            shares, 
            amount0, 
            amount1,
            pool,
            total0,
            total1,
            _totalSupply,
            cachedTick,  // use cached tick
            sqrtPriceX96
        );    

    }

    /**
     @notice Updates LP positions in the ICHIVault.
     @dev First places a base position symmetrically around current price, using one token fully.
     Remaining token forms a single-sided order.
     @param _baseLower Lower tick of the base position.
     @param _baseUpper Upper tick of the base position.
     @param _limitLower Lower tick of the limit position.
     @param _limitUpper Upper tick of the limit position.
     @param swapQuantity Token swap quantity; positive for token0 to token1, negative for token1 to token0.
     */
    function rebalance(
        int24 _baseLower,
        int24 _baseUpper,
        int24 _limitLower,
        int24 _limitUpper,
        int256 swapQuantity
    ) external override nonReentrant {
        _onlyOwner();
        int24 tickSpacing_ = IAlgebraPool(pool).tickSpacing();
        require(
            _baseLower < _baseUpper && _baseLower % tickSpacing_ == 0 && _baseUpper % tickSpacing_ == 0,
            "BPI"
        );
        require(
            _limitLower < _limitUpper && _limitLower % tickSpacing_ == 0 && _limitUpper % tickSpacing_ == 0,
            "LPI"
        );
        require(_baseLower != _limitLower || _baseUpper != _limitUpper, "IIP");

        // Clean positions and collect/distribute fees
        (uint256 fees0, uint256 fees1) = _cleanPositions(false);

        // dismantle positions, collect all tokens (fees already collected)
        _dismantlePosition(basePositionId);
        _dismantlePosition(limitPositionId);

        // swap tokens if required
        if (swapQuantity != 0) {
            IAlgebraPool(pool).swap(
                address(this),
                swapQuantity > 0,
                swapQuantity > 0 ? swapQuantity : -swapQuantity,
                swapQuantity > 0 ? UV3Math.MIN_SQRT_RATIO + 1 : UV3Math.MAX_SQRT_RATIO - 1,
                abi.encode(address(this))
            );
        }

        uint256 balance0 = IERC20(token0).balanceOf(address(this));
        uint256 balance1 = IERC20(token1).balanceOf(address(this));

        // Get pool state once (optimization: single globalState call)
        (uint160 sqrtPriceX96, int24 cachedTick, , , , ) = IAlgebraPool(pool).globalState();

        emit Rebalance(
            cachedTick,  // use cached tick instead of calling currentTick()
            balance0,
            balance1,
            fees0,
            fees1,
            totalSupply(),
            pool,
            sqrtPriceX96
        );

        _mintBasePosition(_baseLower, _baseUpper,
            balance0, balance1);
        // balances had changed, so we need to recalculate them for the limit position
        _mintLimitPosition(_limitLower, _limitUpper,
            IERC20(token0).balanceOf(address(this)),
            IERC20(token1).balanceOf(address(this))
        );
    }

    /**
     @notice Collects and distributes fees from ICHIVault's LP positions. Transaction can be paid by anyone.
     @return fees0 Collected fees in token0.
     @return fees1 Collected fees in token1.
     */
    function collectFees() external override nonReentrant returns (uint256 fees0, uint256 fees1) {
        (uint256 _fees0, uint256 _fees1) = _cleanPositions(true);
        return (_fees0, _fees1);
    }

    /// @notice min function
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /// @notice max function
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? b : a;
    }

    /**
     @notice Sends portion of swap fees to ammFeeRecepient, feeRecipient and affiliate.
     @param fees0 fees for token0
     @param fees1 fees for token1
     */
    function _distributeFees(uint256 fees0, uint256 fees1) internal {
        uint256 ammFee = IICHIVaultFactory(ichiVaultFactory).ammFee();
        uint256 baseFee = IICHIVaultFactory(ichiVaultFactory).baseFee();

        // Make sure there are always enough fees to distribute
        fees0 = min(fees0, IERC20(token0).balanceOf(address(this)));
        fees1 = min(fees1, IERC20(token1).balanceOf(address(this)));

        // baseFeeRecipient cannot be NULL. This is checked and controlled in the factory
        // ammFeeRecipient could be NULL, in this case ammFees are not taken
        // ammFee + baseFee is always <= 100%. Also controlled in the factory

        if (ammFee > 0 && ammFeeRecipient != NULL_ADDRESS) {
            if (fees0 > 0) {
                IERC20(token0).safeTransfer(ammFeeRecipient, fees0.mul(ammFee).div(PRECISION));
            }
            if (fees1 > 0) {
                IERC20(token1).safeTransfer(ammFeeRecipient, fees1.mul(ammFee).div(PRECISION));
            }
        }

        if (baseFee > 0) {
            // if there is no affiliate 100% of the baseFee should go to feeRecipient
            uint256 baseFeeSplit = (affiliate == NULL_ADDRESS)
                ? PRECISION
                : IICHIVaultFactory(ichiVaultFactory).baseFeeSplit();
            address feeRecipient = IICHIVaultFactory(ichiVaultFactory).feeRecipient();

            if (fees0 > 0) {
                uint256 totalFee = fees0.mul(baseFee).div(PRECISION);
                uint256 toRecipient = totalFee.mul(baseFeeSplit).div(PRECISION);
                uint256 toAffiliate = totalFee.sub(toRecipient);
                IERC20(token0).safeTransfer(feeRecipient, toRecipient);
                if (toAffiliate > 0) {
                    IERC20(token0).safeTransfer(affiliate, toAffiliate);
                }
            }
            if (fees1 > 0) {
                uint256 totalFee = fees1.mul(baseFee).div(PRECISION);
                uint256 toRecipient = totalFee.mul(baseFeeSplit).div(PRECISION);
                uint256 toAffiliate = totalFee.sub(toRecipient);
                IERC20(token1).safeTransfer(feeRecipient, toRecipient);
                if (toAffiliate > 0) {
                    IERC20(token1).safeTransfer(affiliate, toAffiliate);
                }
            }
        }
    }

    /**
     @notice Returns the current fee in the pool
     @return fee_ current fee in the pool
     */
    function fee() external view override returns (uint24 fee_) {
        (, , fee_, , , ) = IAlgebraPool(pool).globalState();
    }

    /**
     @notice Sets the hysteresis threshold, in percentage points (10**16 = 1%). Triggers a flashloan attack
     check when the difference between spot price and TWAP exceeds this threshold.
     @dev Accessible only by the owner.
     @param _hysteresis Hysteresis threshold value.
     */
    function setHysteresis(uint256 _hysteresis) external override {
        _onlyOwner();
        hysteresis = _hysteresis;
        emit Hysteresis(msg.sender, _hysteresis);
    }

    /**
     @notice Sets the AMM fee recipient account address, where portion of the collected swap fees will be distributed
     @dev onlyOwner
     @param _ammFeeRecipient The AMM fee recipient account address
     */
    function setAmmFeeRecipient(address _ammFeeRecipient) external override {
        _onlyOwner();
        ammFeeRecipient = _ammFeeRecipient;
        // emit AmmFeeRecipient(msg.sender, _ammFeeRecipient);
    }

    /**
     @notice Sets the affiliate account address where portion of the collected swap fees will be distributed
     @dev onlyOwner
     @param _affiliate The affiliate account address
     */
    function setAffiliate(address _affiliate) external override {
        _onlyOwner();
        affiliate = _affiliate;
        emit Affiliate(msg.sender, _affiliate);
    }

    /**
     @notice Sets the farming contract address where rewards will be sent
     @dev onlyOwner
     @param _farmingContract The farming contract address
     */
    function setFarmingContract(address _farmingContract) external override {
        _onlyOwner();
        farmingContract = _farmingContract;
        emit FarmingContract(msg.sender, _farmingContract);
    }

    /**
     @notice Sets the maximum token0 and token1 amounts the contract allows in a deposit
     @dev onlyOwner
     @param _deposit0Max The maximum amount of token0 allowed in a deposit
     @param _deposit1Max The maximum amount of token1 allowed in a deposit
     */
    function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external override {
        _onlyOwner();
        deposit0Max = _deposit0Max;
        deposit1Max = _deposit1Max;
        emit DepositMax(msg.sender, _deposit0Max, _deposit1Max);
    }

    /**
     @notice Returns the current tickSpacing in the pool
     @return tickSpacing current tickSpacing in the pool
     */
    function tickSpacing() external view override returns (int24) {
        return IAlgebraPool(pool).tickSpacing();
    }

    /**
     @notice Calculates total quantity of token0 and token1 in both positions (and unused in the ICHIVault)
     @return total0 Quantity of token0 in both positions (and unused in the ICHIVault)
     @return total1 Quantity of token1 in both positions (and unused in the ICHIVault)
     */
    function getTotalAmounts() public view override returns (uint256 total0, uint256 total1) {
        (, uint256 base0, uint256 base1) = getBasePosition();
        (, uint256 limit0, uint256 limit1) = getLimitPosition();
        total0 = IERC20(token0).balanceOf(address(this)).add(base0).add(limit0);
        total1 = IERC20(token1).balanceOf(address(this)).add(base1).add(limit1);
    }

    /**
    * @notice Gets position info and calculates token amounts for a given NFT position
    * @param positionId NFT position ID to query
    * @return liquidity Amount of liquidity in the position
    * @return amount0 Amount of token0 in position (including fees)
    * @return amount1 Amount of token1 in position (including fees)
    */
    function _getPositionAmounts(
        uint256 positionId
    ) internal view returns (uint128 liquidity, uint256 amount0, uint256 amount1) {
        if (positionId == 0) {
            return (0, 0, 0);
        }

        // Get current position info from NFT manager
        (
            ,
            ,
            ,
            ,
            ,
            int24 tickLower,
            int24 tickUpper,
            uint128 positionLiquidity,
            ,
            ,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        ) = _nftManager().positions(positionId);

        // Get current price from pool for amount calculation
        (uint160 sqrtRatioX96, , , , , ) = IAlgebraPool(pool).globalState();

        // Calculate amounts for the current liquidity
        (amount0, amount1) = UV3Math.getAmountsForLiquidity(
            sqrtRatioX96,
            UV3Math.getSqrtRatioAtTick(tickLower),
            UV3Math.getSqrtRatioAtTick(tickUpper),
            positionLiquidity
        );

        // Add any uncollected fees
        amount0 = amount0.add(uint256(tokensOwed0));
        amount1 = amount1.add(uint256(tokensOwed1));
        liquidity = positionLiquidity;
    }

    /**
    * @notice Gets position info and calculates token amounts using cached price
    * @param positionId NFT position ID to query
    * @param sqrtRatioX96 Cached sqrt price to avoid additional globalState calls
    * @return liquidity Amount of liquidity in the position
    * @return amount0 Amount of token0 in position (including fees)
    * @return amount1 Amount of token1 in position (including fees)
    */
    function _getPositionAmountsWithPrice(
        uint256 positionId,
        uint160 sqrtRatioX96
    ) internal view returns (uint128 liquidity, uint256 amount0, uint256 amount1) {
        if (positionId == 0) {
            return (0, 0, 0);
        }

        // Get current position info from NFT manager
        (
            ,
            ,
            ,
            ,
            ,
            int24 tickLower,
            int24 tickUpper,
            uint128 positionLiquidity,
            ,
            ,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        ) = _nftManager().positions(positionId);

        // Calculate amounts for the current liquidity using cached price
        (amount0, amount1) = UV3Math.getAmountsForLiquidity(
            sqrtRatioX96,
            UV3Math.getSqrtRatioAtTick(tickLower),
            UV3Math.getSqrtRatioAtTick(tickUpper),
            positionLiquidity
        );

        // Add any uncollected fees
        amount0 = amount0.add(uint256(tokensOwed0));
        amount1 = amount1.add(uint256(tokensOwed1));
        liquidity = positionLiquidity;
    }

    /**
     @notice Calculates total quantity of token0 and token1 using cached price to minimize function calls
     @param sqrtRatioX96 Cached sqrt price from pool
     @return total0 Quantity of token0 in both positions (and unused in the ICHIVault)
     @return total1 Quantity of token1 in both positions (and unused in the ICHIVault)
     */
    function _getTotalAmountsWithPrice(uint160 sqrtRatioX96) internal view returns (uint256 total0, uint256 total1) {
        (, uint256 base0, uint256 base1) = _getPositionAmountsWithPrice(basePositionId, sqrtRatioX96);
        (, uint256 limit0, uint256 limit1) = _getPositionAmountsWithPrice(limitPositionId, sqrtRatioX96);
        total0 = IERC20(token0).balanceOf(address(this)).add(base0).add(limit0);
        total1 = IERC20(token1).balanceOf(address(this)).add(base1).add(limit1);
    }

    /**
    * @notice Gets position liquidity for a given NFT position
    * @param positionId NFT position ID to query
    * @return liquidity Amount of liquidity in the position
    */
    function _getPositionLiquidity(
        uint256 positionId
    ) internal view returns (uint128 liquidity) {
        if (positionId == 0) {
            return 0;
        }

        // Get current position info from NFT manager
        (
            ,
            ,
            ,
            ,
            ,
            ,
            ,
            uint128 positionLiquidity,
            ,
            ,
            ,
        ) = _nftManager().positions(positionId);
        liquidity = positionLiquidity;
    }

    /**
     @notice Calculates amount of total liquidity in the base position
     @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 burning the base position
     */
    function getBasePosition() public view override returns (uint128 liquidity, uint256 amount0, uint256 amount1) {
        return _getPositionAmounts(basePositionId);
    }

    /**
     @notice Calculates amount of total liquidity in the limit position
     @return liquidity Amount of total liquidity in the base position
     @return amount0 Estimated amount of token0 that could be collected by burning the limit position
     @return amount1 Estimated amount of token1 that could be collected by burning the limit position
     */
    function getLimitPosition() public view override returns (uint128 liquidity, uint256 amount0, uint256 amount1) {
        return _getPositionAmounts(limitPositionId);
    }

    /**
     @notice Returns current price tick
     @return tick Uniswap pool's current price tick
     */
    function currentTick() public view override returns (int24 tick) {
        (, int24 tick_, , , , bool unlocked_) = IAlgebraPool(pool).globalState();
        require(unlocked_, "PIL");
        tick = tick_;
    }

    /**
     @notice returns equivalent _tokenOut for _amountIn, _tokenIn using spot price
     @param _tokenIn token the input amount is in
     @param _tokenOut token for the output amount
     @param _tick tick for the spot price
     @param _amountIn amount in _tokenIn
     @return amountOut equivalent anount in _tokenOut
     */
    function _fetchSpot(
        address _tokenIn,
        address _tokenOut,
        int24 _tick,
        uint256 _amountIn
    ) internal pure returns (uint256 amountOut) {
        return UV3Math.getQuoteAtTick(_tick, UV3Math.toUint128(_amountIn), _tokenIn, _tokenOut);
    }

    /**
     @notice returns equivalent _tokenOut for _amountIn, _tokenIn using TWAP price
     @param _pool Uniswap V3 pool address to be used for price checking
     @param _tokenIn token the input amount is in
     @param _tokenOut token for the output amount
     @param _twapPeriod the averaging time period
     @param _amountIn amount in _tokenIn
     @return amountOut equivalent anount in _tokenOut
     */
    function _fetchTwap(
        address _pool,
        address _tokenIn,
        address _tokenOut,
        uint32 _twapPeriod,
        uint256 _amountIn
    ) internal view returns (uint256 amountOut) {
        address basePlugin = _getBasePluginFromPool();

        int256 twapTick = UV3Math.consult(basePlugin, _twapPeriod);
        return
            UV3Math.getQuoteAtTick(
                int24(twapTick), // can assume safe being result from consult()
                UV3Math.toUint128(_amountIn),
                _tokenIn,
                _tokenOut
            );
    }

    /**
     @notice Callback function for swap
     @dev this is where the payer transfers required token0 and token1 amounts
     @param amount0Delta required amount of token0
     @param amount1Delta required amount of token1
     @param data encoded payer's address
     */
    function algebraSwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external override {
        require(msg.sender == address(pool), "cb2");

        if (amount0Delta > 0) {
            IERC20(token0).safeTransfer(msg.sender, uint256(amount0Delta));
        } else if (amount1Delta > 0) {
            IERC20(token1).safeTransfer(msg.sender, uint256(amount1Delta));
        }
    }

    function _getBasePluginFromPool() private view returns (address basePlugin) {
        basePlugin = IAlgebraPool(pool).plugin();
        // make sure the base plugin is connected to the pool
        require(UV3Math.isOracleConnectedToPool(basePlugin, pool), "ADP");
    }

    /**
     @notice Enhanced transfer function with dual events for maximum compatibility
     @param from Address transferring tokens from
     @param to Address transferring tokens to
     @param value Amount of tokens being transferred
     */
    function _transfer(address from, address to, uint256 value) internal override {
        // Execute standard ERC20 transfer (emits standard Transfer event)
        super._transfer(from, to, value);
        
        // Get current pool state (optimization: single globalState call)
        address poolAddress = pool;
        uint256 currentTotalSupply = totalSupply();
        (uint160 sqrtPriceX96, int24 cachedTick, , , , ) = IAlgebraPool(poolAddress).globalState();
        (uint256 totalAmount0, uint256 totalAmount1) = _getTotalAmountsWithPrice(sqrtPriceX96);
        
        // Emit enhanced VaultTransfer with additional data
        emit VaultTransfer(
            from,
            to,
            value,
            poolAddress,
            currentTotalSupply,
            cachedTick,
            totalAmount0,
            totalAmount1,
            sqrtPriceX96
        );
    }

    /**
     @notice Enhanced mint function with VaultTransfer event emission
     @param to Address receiving the minted tokens
     @param amount Amount of tokens being minted
     */
    function _mint(address to, uint256 amount) internal override {
        super._mint(to, amount);
        
        // Get current pool state for VaultTransfer event
        address poolAddress = pool;
        uint256 currentTotalSupply = totalSupply();
        (uint160 sqrtPriceX96, int24 cachedTick, , , , ) = IAlgebraPool(poolAddress).globalState();
        (uint256 totalAmount0, uint256 totalAmount1) = _getTotalAmountsWithPrice(sqrtPriceX96);
        
        // Emit VaultTransfer for mint
        emit VaultTransfer(
            address(0),
            to,
            amount,
            poolAddress,
            currentTotalSupply,
            cachedTick,
            totalAmount0,
            totalAmount1,
            sqrtPriceX96
        );
    }

    /**
     @notice Enhanced burn function with VaultTransfer event emission
     @param from Address from which tokens are being burned
     @param amount Amount of tokens being burned
     */
    function _burn(address from, uint256 amount) internal override {
        super._burn(from, amount);
        
        // Get current pool state for VaultTransfer event
        address poolAddress = pool;
        uint256 currentTotalSupply = totalSupply();
        (uint160 sqrtPriceX96, int24 cachedTick, , , , ) = IAlgebraPool(poolAddress).globalState();
        (uint256 totalAmount0, uint256 totalAmount1) = _getTotalAmountsWithPrice(sqrtPriceX96);
        
        // Emit VaultTransfer for burn
        emit VaultTransfer(
            from,
            address(0),
            amount,
            poolAddress,
            currentTotalSupply,
            cachedTick,
            totalAmount0,
            totalAmount1,
            sqrtPriceX96
        );
    }
}

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

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

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

/// @title The interface for the Algebra volatility oracle
/// @dev This contract stores timepoints and calculates statistical averages
interface IVolatilityOracle {
  /// @notice Returns data belonging to a certain timepoint
  /// @param index The index of timepoint in the array
  /// @dev There is more convenient function to fetch a timepoint: getTimepoints(). Which requires not an index but seconds
  /// @return initialized Whether the timepoint has been initialized and the values are safe to use
  /// @return blockTimestamp The timestamp of the timepoint
  /// @return tickCumulative The tick multiplied by seconds elapsed for the life of the pool as of the timepoint timestamp
  /// @return volatilityCumulative Cumulative standard deviation for the life of the pool as of the timepoint timestamp
  /// @return tick The tick at blockTimestamp
  /// @return averageTick Time-weighted average tick
  /// @return windowStartIndex Index of closest timepoint >= WINDOW seconds ago
  function timepoints(
    uint256 index
  )
    external
    view
    returns (
      bool initialized,
      uint32 blockTimestamp,
      int56 tickCumulative,
      uint88 volatilityCumulative,
      int24 tick,
      int24 averageTick,
      uint16 windowStartIndex
    );

  /// @notice Returns the index of the last timepoint that was written.
  /// @return index of the last timepoint written
  function timepointIndex() external view returns (uint16);

  /// @notice Initialize the plugin externally
  /// @dev This function allows to initialize the plugin if it was created after the pool was created
  function initialize() external;

  /// @notice Returns the timestamp of the last timepoint that was written.
  /// @return timestamp of the last timepoint
  function lastTimepointTimestamp() external view returns (uint32);

  /// @notice Returns information about whether oracle is initialized
  /// @return true if oracle is initialized, otherwise false
  function isInitialized() external view returns (bool);

  /// @dev Reverts if a timepoint at or before the desired timepoint timestamp does not exist.
  /// 0 may be passed as `secondsAgo' to return the current cumulative values.
  /// If called with a timestamp falling between two timepoints, returns the counterfactual accumulator values
  /// at exactly the timestamp between the two timepoints.
  /// @dev `volatilityCumulative` values for timestamps after the last timepoint _should not_ be compared because they may differ due to interpolation errors
  /// @param secondsAgo The amount of time to look back, in seconds, at which point to return a timepoint
  /// @return tickCumulative The cumulative tick since the pool was first initialized, as of `secondsAgo`
  /// @return volatilityCumulative The cumulative volatility value since the pool was first initialized, as of `secondsAgo`
  function getSingleTimepoint(uint32 secondsAgo) external view returns (int56 tickCumulative, uint88 volatilityCumulative);

  /// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos`
  /// @dev Reverts if `secondsAgos` > oldest timepoint
  /// @dev `volatilityCumulative` values for timestamps after the last timepoint _should not_ be compared because they may differ due to interpolation errors
  /// @param secondsAgos Each amount of time to look back, in seconds, at which point to return a timepoint
  /// @return tickCumulatives The cumulative tick since the pool was first initialized, as of each `secondsAgo`
  /// @return volatilityCumulatives The cumulative volatility values since the pool was first initialized, as of each `secondsAgo`
  function getTimepoints(uint32[] memory secondsAgos) external view returns (int56[] memory tickCumulatives, uint88[] memory volatilityCumulatives);

  /// @notice Fills uninitialized timepoints with nonzero value
  /// @dev Can be used to reduce the gas cost of future swaps
  /// @param startIndex The start index, must be not initialized
  /// @param amount of slots to fill, startIndex + amount must be <= type(uint16).max
  function prepayTimepointsStorageSlots(uint16 startIndex, uint16 amount) external;
}

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

/// @title Callback for IAlgebraPoolActions#swap
/// @notice Any contract that calls IAlgebraPoolActions#swap must implement this interface
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraSwapCallback {
  /// @notice Called to `msg.sender` after executing a swap via IAlgebraPool#swap.
  /// @dev In the implementation you must pay the pool tokens owed for the swap.
  /// The caller of this method _must_ be checked to be a AlgebraPool deployed by the canonical AlgebraFactory.
  /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
  /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
  /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
  /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
  /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
  /// @param data Any data passed through by the caller via the IAlgebraPoolActions#swap call
  function algebraSwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external;
}

File 5 of 49 : 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: 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: 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 8 of 49 : 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 plugin fee param greater than fee/override fee
  error incorrectPluginFee();

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

File 9 of 49 : 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
  /// @param pluginFee The fee to be sent to the plugin
  event Burn(
    address indexed owner,
    int24 indexed bottomTick,
    int24 indexed topTick,
    uint128 liquidityAmount,
    uint256 amount0,
    uint256 amount1,
    uint24 pluginFee
  );

  /// @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
  /// @param overrideFee The fee to be applied to the trade
  /// @param pluginFee The fee to be sent to the plugin
  event Swap(
    address indexed sender,
    address indexed recipient,
    int256 amount0,
    int256 amount1,
    uint160 price,
    uint128 liquidity,
    int24 tick,
    uint24 overrideFee,
    uint24 pluginFee
  );

  /// @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 pool has higher balances than expected.
  /// Any excess of tokens will be distributed between liquidity providers as fee.
  /// @dev Fees after flash also will trigger this event due to mechanics of flash.
  /// @param amount0 The excess of token0
  /// @param amount1 The excess of token1
  event ExcessTokens(uint256 amount0, uint256 amount1);

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

  /// @notice Emitted when the community vault address changes
  /// @param newCommunityVault New community vault
  event CommunityVault(address newCommunityVault);

  /// @notice Emitted when the plugin does skim the excess of tokens
  /// @param to THe receiver of tokens (plugin)
  /// @param amount0 The amount of token0
  /// @param amount1 The amount of token1
  event Skim(address indexed to, uint256 amount0, uint256 amount1);
}

// 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: 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;

  /// @notice Forces balances to match reserves. Excessive tokens will be distributed between active LPs
  /// @dev Only plugin can call this function
  function sync() external;

  /// @notice Forces balances to match reserves. Excessive tokens will be sent to msg.sender
  /// @dev Only plugin can call this function
  function skim() external;
}

// 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 vault/plugin
  /// @return The timestamp truncated to 32 bits
  function lastFeeTransferTimestamp() external view returns (uint32);

  /// @notice The amounts of token0 and token1 that will be sent to the vault
  /// @dev Will be sent 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 The amounts of token0 and token1 that will be sent to the plugin
  /// @dev Will be sent FEE_TRANSFER_FREQUENCY after feeLastTransferTimestamp
  /// @return pluginFeePending0 The amount of token0 that will be sent to the plugin
  /// @return pluginFeePending1 The amount of token1 that will be sent to the plugin
  function getPluginFeePending() external view returns (uint128 pluginFeePending0, uint128 pluginFeePending1);

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

File 13 of 49 : 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 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
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: GPL-2.0-or-later
pragma solidity >=0.8.4 <0.9.0;

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

/// @title Contains logic and constants for interacting with the plugin through hooks
/// @dev Allows pool to check which hooks are enabled, as well as control the return selector
library Plugins {
  function hasFlag(uint8 pluginConfig, uint256 flag) internal pure returns (bool res) {
    assembly {
      res := gt(and(pluginConfig, flag), 0)
    }
  }

  function shouldReturn(bytes4 selector, bytes4 expectedSelector) internal pure {
    if (selector != expectedSelector) revert IAlgebraPoolErrors.invalidHookResponse(expectedSelector);
  }

  uint256 internal constant BEFORE_SWAP_FLAG = 1;
  uint256 internal constant AFTER_SWAP_FLAG = 1 << 1;
  uint256 internal constant BEFORE_POSITION_MODIFY_FLAG = 1 << 2;
  uint256 internal constant AFTER_POSITION_MODIFY_FLAG = 1 << 3;
  uint256 internal constant BEFORE_FLASH_FLAG = 1 << 4;
  uint256 internal constant AFTER_FLASH_FLAG = 1 << 5;
  uint256 internal constant AFTER_INIT_FLAG = 1 << 6;
  uint256 internal constant DYNAMIC_FEE = 1 << 7;
}

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

File 17 of 49 : 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;
}

// 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: 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: 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: 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;
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 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 deployer The address of the custom pool deployer
    /// @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,
            address deployer,
            int24 tickLower,
            int24 tickUpper,
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    struct MintParams {
        address token0;
        address token1;
        address deployer;
        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: 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);
}

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

/// @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
    /// @param data Data for plugin initialization
    /// @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,
        address deployer,
        uint160 sqrtPriceX96,
        bytes calldata data
    ) external payable returns (address pool);
}

// 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 Provides functions for deriving a pool address from the poolDeployer and tokens
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
library PoolAddress {
    bytes32 internal constant POOL_INIT_CODE_HASH = 0xb3fc09be5eb433d99b1ec89fd8435aaf5ffea75c1879e19028aa2414a14b3c85;

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

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

    /// @notice Deterministically computes the pool address given the poolDeployer and PoolKey
    /// @param poolDeployer The Algebra poolDeployer contract address
    /// @param key The PoolKey
    /// @return pool The contract address of the Algebra pool
    function computeAddress(address poolDeployer, PoolKey memory key) internal pure returns (address pool) {
        require(key.token0 < key.token1, 'Invalid order of tokens');
        pool = address(
            uint160(
                uint256(
                    keccak256(
                        abi.encodePacked(
                            hex'ff',
                            poolDeployer,
                            keccak256(
                                key.deployer == address(0)
                                    ? abi.encode(key.token0, key.token1)
                                    : abi.encode(key.deployer, key.token0, key.token1)
                            ),
                            POOL_INIT_CODE_HASH
                        )
                    )
                )
            )
        );
    }
}

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

// 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: 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 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
// 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: 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.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.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: 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 (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/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: 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 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);
}

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

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

pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}

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

import "@cryptoalgebra/integral-core/contracts/libraries/FullMath.sol";
import "@cryptoalgebra/integral-core/contracts/libraries/TickMath.sol";
import "@cryptoalgebra/integral-core/contracts/libraries/Plugins.sol";
import "@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol";
import "@cryptoalgebra/integral-periphery/contracts/libraries/PoolAddress.sol";
import "@cryptoalgebra/integral-base-plugin/contracts/interfaces/plugins/IVolatilityOracle.sol";

/// @title Oracle library
/// @notice Provides functions to integrate with Algebra pool TWAP VolatilityOracle
library OracleLibrary {
    /// @notice Fetches time-weighted average tick using Algebra VolatilityOracle
    /// @param oracleAddress The address of oracle
    /// @param period Number of seconds in the past to start calculating time-weighted average
    /// @return timeWeightedAverageTick The time-weighted average tick from (block.timestamp-period) to block.timestamp
    function consult(address oracleAddress, uint32 period) internal view returns (int24 timeWeightedAverageTick) {
        require(period != 0, "Period is zero");

        uint32[] memory secondAgos = new uint32[](2);
        secondAgos[0] = period;
        secondAgos[1] = 0;

        IVolatilityOracle oracle = IVolatilityOracle(oracleAddress);
        (int56[] memory tickCumulatives, ) = oracle.getTimepoints(secondAgos);
        int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];

        timeWeightedAverageTick = int24(tickCumulativesDelta / int56(uint56(period)));

        // Always round to negative infinity
        if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(period)) != 0)) timeWeightedAverageTick--;
    }

    /// @notice Given a tick and a token amount, calculates the amount of token received in exchange
    /// @param tick Tick value used to calculate the quote
    /// @param baseAmount Amount of token to be converted
    /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination
    /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
    /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken
    function getQuoteAtTick(
        int24 tick,
        uint128 baseAmount,
        address baseToken,
        address quoteToken
    ) internal pure returns (uint256 quoteAmount) {
        uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);

        // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
        if (sqrtRatioX96 <= type(uint128).max) {
            uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
            quoteAmount = baseToken < quoteToken
                ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
                : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
        } else {
            uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
            quoteAmount = baseToken < quoteToken
                ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)
                : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);
        }
    }

    /// @notice Fetches metadata of last available record (most recent) in oracle
    /// @param oracleAddress The address of oracle
    /// @return index The index of last available record (most recent) in oracle
    /// @return timestamp The timestamp of last available record (most recent) in oracle, truncated to uint32
    function lastTimepointMetadata(address oracleAddress) internal view returns (uint16 index, uint32 timestamp) {
        index = latestIndex(oracleAddress);
        timestamp = IVolatilityOracle(oracleAddress).lastTimepointTimestamp();
    }

    /// @notice Fetches metadata of oldest available record in oracle
    /// @param oracleAddress The address of oracle
    /// @return index The index of oldest available record in oracle
    /// @return timestamp The timestamp of oldest available record in oracle, truncated to uint32
    function oldestTimepointMetadata(address oracleAddress) internal view returns (uint16 index, uint32 timestamp) {
        uint16 lastIndex = latestIndex(oracleAddress);
        bool initialized;
        unchecked {
            // overflow is desired
            index = lastIndex + 1;
            (initialized, timestamp) = timepointMetadata(oracleAddress, index);
        }
        if (initialized) return (index, timestamp);

        (, timestamp) = timepointMetadata(oracleAddress, 0);
        return (0, timestamp);
    }

    /// @notice Gets information about whether the oracle has been initialized
    function isInitialized(address oracleAddress) internal view returns (bool result) {
        (result, ) = timepointMetadata(oracleAddress, 0);
        return result;
    }

    /// @notice Fetches the index of last available record (most recent) in oracle
    function latestIndex(address oracle) internal view returns (uint16) {
        return (IVolatilityOracle(oracle).timepointIndex());
    }

    /// @notice Fetches the metadata of record in oracle
    /// @param oracleAddress The address of oracle
    /// @param index The index of record in oracle
    /// @return initialized Whether or not the timepoint is initialized
    /// @return timestamp The timestamp of timepoint
    function timepointMetadata(
        address oracleAddress,
        uint16 index
    ) internal view returns (bool initialized, uint32 timestamp) {
        (initialized, timestamp, , , , , ) = IVolatilityOracle(oracleAddress).timepoints(index);
    }

    /// @notice Checks if the oracle is currently connected to the pool
    /// @param oracleAddress The address of oracle
    /// @param oracleAddress The address of the pool
    /// @return connected Whether or not the oracle is connected
    function isOracleConnectedToPool(
        address oracleAddress,
        address poolAddress
    ) internal view returns (bool connected) {
        IAlgebraPool pool = IAlgebraPool(poolAddress);
        if (oracleAddress == pool.plugin()) {
            (, , , uint8 pluginConfig, , ) = pool.globalState();
            connected = Plugins.hasFlag(pluginConfig, Plugins.BEFORE_SWAP_FLAG);
        }
    }
}

// SPDX-License-Identifier: BUSL-1.1

pragma solidity >=0.8.4;

import { TickMath } from "@cryptoalgebra/integral-core/contracts/libraries/TickMath.sol";
import { LiquidityAmounts } from "@cryptoalgebra/integral-periphery/contracts/libraries/LiquidityAmounts.sol";
import { IAlgebraPool } from "@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol";
import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol";

import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";

import { OracleLibrary } from "./OracleLibrary.sol";
import { IICHIVaultFactory } from "../../interfaces/IICHIVaultFactory.sol";

library UV3Math {
    using SafeMath for uint256;

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

    uint256 internal constant PRECISION = 10 ** 18;

    /*******************
     * Tick Math
     *******************/

    function getSqrtRatioAtTick(int24 currentTick) public pure returns (uint160 sqrtPriceX96) {
        sqrtPriceX96 = TickMath.getSqrtRatioAtTick(currentTick);
    }

    /*******************
     * LiquidityAmounts
     *******************/

    function getAmountsForLiquidity(
        uint160 sqrtRatioX96,
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity
    ) public pure returns (uint256 amount0, uint256 amount1) {
        (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
            sqrtRatioX96,
            sqrtRatioAX96,
            sqrtRatioBX96,
            liquidity
        );
    }

    function getLiquidityForAmounts(
        uint160 sqrtRatioX96,
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount0,
        uint256 amount1
    ) public pure returns (uint128 liquidity) {
        liquidity = LiquidityAmounts.getLiquidityForAmounts(
            sqrtRatioX96,
            sqrtRatioAX96,
            sqrtRatioBX96,
            amount0,
            amount1
        );
    }

    /*******************
     * OracleLibrary
     *******************/

    function consult(address _basePlugin, uint32 _twapPeriod) public view returns (int24 timeWeightedAverageTick) {
        timeWeightedAverageTick = OracleLibrary.consult(_basePlugin, _twapPeriod);
    }

    function getQuoteAtTick(
        int24 tick,
        uint128 baseAmount,
        address baseToken,
        address quoteToken
    ) public pure returns (uint256 quoteAmount) {
        quoteAmount = OracleLibrary.getQuoteAtTick(tick, baseAmount, baseToken, quoteToken);
    }

    function lastTimepointMetadata(address oracleAddress) public view returns (uint16 index, uint32 timestamp) {
        (index, timestamp) = OracleLibrary.lastTimepointMetadata(oracleAddress);
    }

    function isOracleConnectedToPool(address oracleAddress, address poolAddress) public view returns (bool connected) {
        if (oracleAddress == address(0))
            return false;
        connected = OracleLibrary.isOracleConnectedToPool(oracleAddress, poolAddress);
    }

    /*******************
     * SafeUnit128
     *******************/

    /// @notice Cast a uint256 to a uint128, revert on overflow
    /// @param y The uint256 to be downcasted
    /// @return z The downcasted integer, now type uint128
    function toUint128(uint256 y) public pure returns (uint128 z) {
        require((z = uint128(y)) == y, "SafeUint128: overflow");
    }


    function checkHysteresis(address basePlugin) public view returns (bool) {
        // get latest timestamp from the plugin
        (, uint32 blockTimestamp) = lastTimepointMetadata(basePlugin);
        return (block.timestamp != blockTimestamp);
    }

    function _checkPriceManipulation(
        uint256 price,
        uint256 twap,
        uint256 auxTwap,
        uint256 auxTwapPeriod,
        uint256 hysteresis,
        address basePlugin
    ) public view {
        uint256 delta = (price > twap)
            ? price.sub(twap).mul(PRECISION).div(price)
            : twap.sub(price).mul(PRECISION).div(twap);

        if (auxTwapPeriod > 0) {
            uint256 auxDelta = (price > auxTwap)
                ? price.sub(auxTwap).mul(PRECISION).div(price)
                : auxTwap.sub(price).mul(PRECISION).div(auxTwap);

            if (delta > hysteresis || auxDelta > hysteresis)
                require(checkHysteresis(basePlugin), "DTL");
        } else if (delta > hysteresis) {
            require(checkHysteresis(basePlugin), "DTL");
        }
    }

    /******************************
     * ICHIVault specific functions
     ******************************/

    /**
     @dev Computes a unique vault's symbol for vaults created through Ramses factory.
     @param value index of the vault to be created
     */
    function computeIVsymbol(uint256 value, address pool, bool allowToken0) public view returns (string memory) {
        IAlgebraPool algebraPool = IAlgebraPool(pool);
        string memory token0Symbol = ERC20(algebraPool.token0()).symbol();
        string memory token1Symbol = ERC20(algebraPool.token1()).symbol();
        // Format: IV-[ammName]-index-deposit-quote
        return string(abi.encodePacked(
            "IV-",
            IICHIVaultFactory(msg.sender).ammName(),
            "-",
            Strings.toString(value),
            "-",
            allowToken0 ? token0Symbol : token1Symbol,
            "-",
            allowToken0 ? token1Symbol : token0Symbol
        ));
    }
}

// SPDX-License-Identifier: Unlicense

pragma solidity >=0.8.4;

interface IICHIVault {
    function ichiVaultFactory() external view returns (address);

    function pool() external view returns (address);

    function token0() external view returns (address);

    function allowToken0() external view returns (bool);

    function token1() external view returns (address);

    function allowToken1() external view returns (bool);

    function fee() external view returns (uint24);

    function tickSpacing() external view returns (int24);

    function ammFeeRecipient() external view returns(address);

    function farmingContract() external view returns(address);

    function affiliate() external view returns (address);

    function baseLower() external view returns (int24);

    function baseUpper() external view returns (int24);

    function limitLower() external view returns (int24);

    function limitUpper() external view returns (int24);

    /// @notice NFT ID of the base position. If 0, the base position is not initialized.
    function basePositionId() external view returns (uint256);

    /// @notice NFT ID of the limit position. If 0, the limit position is not initialized.
    function limitPositionId() external view returns (uint256);

    function deposit0Max() external view returns (uint256);

    function deposit1Max() external view returns (uint256);

    function hysteresis() external view returns (uint256);

    function twapPeriod() external view returns (uint32);

    function auxTwapPeriod() external view returns (uint32);

    function getTotalAmounts() external view returns (uint256, uint256);

    function getBasePosition() external view returns (uint128, uint256, uint256);

    function getLimitPosition() external view returns (uint128, uint256, uint256);

    function deposit(uint256, uint256, address) external returns (uint256);

    function withdraw(uint256, address) external returns (uint256, uint256);

    function currentTick() external view returns (int24);

    function resetAllowances() external;

    function collectRewards() external;

    function rebalance(
        int24 _baseLower,
        int24 _baseUpper,
        int24 _limitLower,
        int24 _limitUpper,
        int256 swapQuantity
    ) external;

    function collectFees() external returns (uint256 fees0, uint256 fees1);

    function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external;

    function setHysteresis(uint256 _hysteresis) external;

    function setAmmFeeRecipient(address _ammFeeRecipient) external;

    function setAffiliate(address _affiliate) external;

    function setTwapPeriod(uint32 newTwapPeriod) external;

    function setAuxTwapPeriod(uint32 newAuxTwapPeriod) external;

    function setFarmingContract(address _farmingContract) external;

    event DeployICHIVault(
        address indexed sender,
        address indexed pool,
        bool allowToken0,
        bool allowToken1,
        address owner,
        uint256 twapPeriod
    );

    event SetTwapPeriod(address sender, uint32 newTwapPeriod);

    event SetAuxTwapPeriod(address sender, uint32 newAuxTwapPeriod);

    event Deposit(
        address indexed sender,
        address indexed to,
        uint256 shares,
        uint256 amount0,
        uint256 amount1,
        // --- Added state data ---
        address pool,                    // Pool address
        uint256 totalAmount0,           // Total vault amount0 after deposit
        uint256 totalAmount1,           // Total vault amount1 after deposit
        uint256 totalSupply,            // Total vault shares after deposit
        int24 currentTick,              // Current pool tick
        uint160 sqrtPriceX96           // Current pool sqrt price
    );
    event Withdraw(
        address indexed sender,
        address indexed to,
        uint256 shares,
        uint256 amount0,
        uint256 amount1,
        // --- Added state data ---
        address pool,                   // Pool address
        uint256 totalAmount0,          // Total vault amount0 after withdraw
        uint256 totalAmount1,          // Total vault amount1 after withdraw
        uint256 totalSupply,           // Total vault shares after withdraw
        int24 currentTick,             // Current pool tick
        uint160 sqrtPriceX96          // Current pool sqrt price
    );
    event Rebalance(
        int24 tick,
        uint256 totalAmount0,
        uint256 totalAmount1,
        uint256 feeAmount0,
        uint256 feeAmount1,
        uint256 totalSupply,
        // --- Added state data ---
        address pool,                   // Pool address  
        uint160 sqrtPriceX96          // Current pool sqrt price
    );

event CollectFees(
    address indexed sender,
    uint256 feeAmount0,
    uint256 feeAmount1,
    // --- Added state data ---
    address pool,           // Pool address
    uint256 totalSupply,    // Vault total supply
    int24 currentTick,      // Current tick from pool
    uint256 totalAmount0,   // Vault total amount0
    uint256 totalAmount1,   // Vault total amount1
    uint160 sqrtPriceX96    // Sqrt price from pool
);
    event RewardsCollected(uint256 reward, uint256 bonusReward);

    event Hysteresis(address indexed sender, uint256 hysteresis);

    event DepositMax(address indexed sender, uint256 deposit0Max, uint256 deposit1Max);

    // event AmmFeeRecipient(address indexed sender, address ammFeeRecipient);

    event Affiliate(address indexed sender, address affiliate);

    event FarmingContract(address indexed sender, address farmingContract);

    event VaultTransfer(
        address indexed from,
        address indexed to,
        uint256 value,
        address pool,           // Pool address
        uint256 totalSupply,    // Vault total supply
        int24 currentTick,      // Current tick from pool
        uint256 totalAmount0,   // Vault total amount0
        uint256 totalAmount1,   // Vault total amount1
        uint160 sqrtPriceX96    // Sqrt price from pool
    );
}

// SPDX-License-Identifier: BUSL-1.1

pragma solidity >=0.8.4;

interface IICHIVaultFactory {
    event FeeRecipient(address indexed sender, address feeRecipient);

    event AmmFee(address indexed sender, uint256 ammFee);

    event BaseFee(address indexed sender, uint256 baseFee);

    event BaseFeeSplit(address indexed sender, uint256 baseFeeSplit);

    event DeployICHIVaultFactory(address indexed sender, address algebraFactory);

    event ICHIVaultCreated(
        address indexed sender,
        address indexed ichiVault,
        address tokenA,
        address tokenB,
        bool allowTokenA,
        bool allowTokenB,
        uint256 count,
        uint24 fee,
        address token0,
        address token1,
        uint8 decimals0,
        uint8 decimals1
    );

    function getICHIVault(bytes32 vaultKey) external view returns(address);

    function algebraFactory() external view returns (address);

    function nftManager() external view returns (address);
    function farmingCenter() external view returns (address);
    function incentiveMaker() external view returns (address);

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

    function feeRecipient() external view returns (address);

    function ammFee() external view returns (uint256);

    function baseFee() external view returns (uint256);

    function baseFeeSplit() external view returns (uint256);

    function setFeeRecipient(address _feeRecipient) external;

    function setAmmFee(uint256 _ammFee) external;

    function setBaseFee(uint256 _baseFee) external;

    function setBaseFeeSplit(uint256 _baseFeeSplit) external;

    function createICHIVault(
        address tokenA,
        bool allowTokenA,
        address tokenB,
        bool allowTokenB
    ) external returns (address ichiVault);

    function genKey(
        address deployer,
        address token0,
        address token1,
        bool allowToken0,
        bool allowToken1
    ) external pure returns (bytes32 key);
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.20;
pragma abicoder v2;

import "@cryptoalgebra/integral-farming/contracts/base/IncentiveKey.sol";
import { IFarmingCenter } from "@cryptoalgebra/integral-farming/contracts/interfaces/IFarmingCenter.sol";

interface IIncentiveMaker{

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

}

Settings
{
  "metadata": {
    "bytecodeHash": "none"
  },
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "viaIR": true,
  "evmVersion": "paris",
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {
    "contracts/ICHIVault.sol": {
      "UV3Math": "0x62a7d1fa1e67000e70e2a7ed59a99e39d8265da1"
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_pool","type":"address"},{"internalType":"bool","name":"_allowToken0","type":"bool"},{"internalType":"bool","name":"_allowToken1","type":"bool"},{"internalType":"address","name":"__owner","type":"address"},{"internalType":"uint32","name":"_twapPeriod","type":"uint32"},{"internalType":"uint256","name":"_vaultIndex","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"address","name":"affiliate","type":"address"}],"name":"Affiliate","type":"event"},{"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":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"feeAmount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"feeAmount1","type":"uint256"},{"indexed":false,"internalType":"address","name":"pool","type":"address"},{"indexed":false,"internalType":"uint256","name":"totalSupply","type":"uint256"},{"indexed":false,"internalType":"int24","name":"currentTick","type":"int24"},{"indexed":false,"internalType":"uint256","name":"totalAmount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalAmount1","type":"uint256"},{"indexed":false,"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"}],"name":"CollectFees","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"pool","type":"address"},{"indexed":false,"internalType":"bool","name":"allowToken0","type":"bool"},{"indexed":false,"internalType":"bool","name":"allowToken1","type":"bool"},{"indexed":false,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"twapPeriod","type":"uint256"}],"name":"DeployICHIVault","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"},{"indexed":false,"internalType":"address","name":"pool","type":"address"},{"indexed":false,"internalType":"uint256","name":"totalAmount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalAmount1","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalSupply","type":"uint256"},{"indexed":false,"internalType":"int24","name":"currentTick","type":"int24"},{"indexed":false,"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"deposit0Max","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"deposit1Max","type":"uint256"}],"name":"DepositMax","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"address","name":"farmingContract","type":"address"}],"name":"FarmingContract","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"hysteresis","type":"uint256"}],"name":"Hysteresis","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":"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"},{"indexed":false,"internalType":"address","name":"pool","type":"address"},{"indexed":false,"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"}],"name":"Rebalance","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"bonusReward","type":"uint256"}],"name":"RewardsCollected","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint32","name":"newAuxTwapPeriod","type":"uint32"}],"name":"SetAuxTwapPeriod","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint32","name":"newTwapPeriod","type":"uint32"}],"name":"SetTwapPeriod","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":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":false,"internalType":"address","name":"pool","type":"address"},{"indexed":false,"internalType":"uint256","name":"totalSupply","type":"uint256"},{"indexed":false,"internalType":"int24","name":"currentTick","type":"int24"},{"indexed":false,"internalType":"uint256","name":"totalAmount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalAmount1","type":"uint256"},{"indexed":false,"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"}],"name":"VaultTransfer","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"},{"indexed":false,"internalType":"address","name":"pool","type":"address"},{"indexed":false,"internalType":"uint256","name":"totalAmount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalAmount1","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalSupply","type":"uint256"},{"indexed":false,"internalType":"int24","name":"currentTick","type":"int24"},{"indexed":false,"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"}],"name":"Withdraw","type":"event"},{"inputs":[],"name":"PRECISION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"affiliate","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int256","name":"amount0Delta","type":"int256"},{"internalType":"int256","name":"amount1Delta","type":"int256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"algebraSwapCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"allowToken0","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"allowToken1","outputs":[{"internalType":"bool","name":"","type":"bool"}],"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":[],"name":"ammFeeRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"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":[],"name":"auxTwapPeriod","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","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":"basePositionId","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":"collectFees","outputs":[{"internalType":"uint256","name":"fees0","type":"uint256"},{"internalType":"uint256","name":"fees1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"collectRewards","outputs":[],"stateMutability":"nonpayable","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":"deposit0","type":"uint256"},{"internalType":"uint256","name":"deposit1","type":"uint256"},{"internalType":"address","name":"to","type":"address"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"deposit0Max","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"deposit1Max","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"farmingContract","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"fee","outputs":[{"internalType":"uint24","name":"fee_","type":"uint24"}],"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":"getTotalAmounts","outputs":[{"internalType":"uint256","name":"total0","type":"uint256"},{"internalType":"uint256","name":"total1","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"hysteresis","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ichiVaultFactory","outputs":[{"internalType":"address","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":"limitPositionId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"limitUpper","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pool","outputs":[{"internalType":"address","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":"int256","name":"swapQuantity","type":"int256"}],"name":"rebalance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"resetAllowances","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_affiliate","type":"address"}],"name":"setAffiliate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_ammFeeRecipient","type":"address"}],"name":"setAmmFeeRecipient","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"newAuxTwapPeriod","type":"uint32"}],"name":"setAuxTwapPeriod","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_deposit0Max","type":"uint256"},{"internalType":"uint256","name":"_deposit1Max","type":"uint256"}],"name":"setDepositMax","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_farmingContract","type":"address"}],"name":"setFarmingContract","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_hysteresis","type":"uint256"}],"name":"setHysteresis","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"newTwapPeriod","type":"uint32"}],"name":"setTwapPeriod","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":"token0","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"token1","outputs":[{"internalType":"address","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":[],"name":"twapPeriod","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"to","type":"address"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]

0x6101408060405234620006c05760c08162006669803803809162000024828562000c50565b833981010312620006c0576200003a8162000c74565b620000486020830162000c89565b91620000576040820162000c89565b90620000666060820162000c74565b60808201519163ffffffff83168303620006c05760a00151604080519081016001600160401b0381118282101762000a71576040908152601482527f49434849205661756c74204c6971756964697479000000000000000000000000602083015251633afd2b7960e11b815260048101929092526001600160a01b038616602483015286151560448301526000826064817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af4918215620006ce5760009262000b9f575b508051906001600160401b03821162000a715760035490600182811c9216801562000b94575b602083101462000a505781601f84931162000b22575b50602090601f831160011462000a935760009262000a87575b50508160011b916000199060031b1c1916176003555b8051906001600160401b03821162000a715760045490600182811c9216801562000a66575b602083101462000a505781601f849311620009db575b50602090601f83116001146200094c5760009262000940575b50508160011b916000199060031b1c1916176004555b6001600555620002043362000c97565b6001600160a01b03841615620009155784806200090c575b8015620008fa575b15620008cf573360805260a0849052604051630dfe168160e01b81526020816004816001600160a01b0389165afa908115620006ce576000916200088d575b5060c05260405163d21220a760e01b81526020816004816001600160a01b0389165afa908115620006ce576000916200084b575b5060e052610100859052610120839052600f80546001600160401b03191663ffffffff841617601e84901b673fffffff0000000016179055600654336001600160a01b03919091160362000807576001600160a01b03811615620007b357620003008162000c97565b6611c37937e08000600e55600019600c819055600d55600780546001600160a01b0319908116909155600880548216905560098054909116905560c051608051604051637445c8f560e11b81526001600160a01b0392831692909160209183916004918391165afa908115620006ce5760009162000767575b5060405163095ea7b360e01b81526001600160a01b039091166004820152600019602482015290602090829060449082906000905af18015620006ce5762000726575b5060e051608051604051637445c8f560e11b81526001600160a01b039283169592909160209183916004918391165afa908115620006ce57600091620006da575b5060405163095ea7b360e01b81526001600160a01b039091166004820152600019602482015293602090859060449082906000905af18015620006ce5762000684575b63ffffffff935060405195151586521515602086015260018060a01b0316604085015216606083015260018060a01b0316907f3e708ccf7d0e6de8558e020ea36189511cb3435bbfec54e721a48ee4df0d4f8c60803392a3604051615988908162000ce1823960805181818161056c01528181610bf601528181610c4501528181610d9301528181610f9d01528181613b6601528181613bf101528181613fb60152614cc9015260a0518181816104d00152818161067d015281816107f40152818161088901528181610b33015281816113ee015281816117b301528181611d3901528181611de801528181611e3c015281816128f401528181612b3501528181612ec8015281816140e601528181614d170152818161539501528181615506015281816155ec01526157c0015260c051818181610750015281816108e501528181610c9a01528181610ec401528181610f14015281816110aa01528181611870015281816119bc01528181611b1201528181611fcb015281816127890152818161292c01528181612b9501528181612d720152818161402601528181614ae40152614f5b015260e0518181816107a50152818161093a01528181610cfb01528181610e1501528181610e6601528181611050015281816113980152818161184e0152818161199a01528181611af001528181611f8f015281816127d50152818161296a01528181612ddc0152818161406f01528181614b090152614fb101526101005181818161174601526123b901526101205181818161227b015261270b0152f35b6020843d602011620006c5575b81620006a06020938362000c50565b81010312620006c057620006b963ffffffff9462000c89565b5062000440565b600080fd5b3d915062000691565b6040513d6000823e3d90fd5b90506020813d6020116200071d575b81620006f86020938362000c50565b81010312620006c05760009460446200071360209362000c74565b92505094620003fd565b3d9150620006e9565b6020813d6020116200075e575b81620007426020938362000c50565b81010312620006c057620007569062000c89565b5038620003bc565b3d915062000733565b90506020813d602011620007aa575b81620007856020938362000c50565b81010312620006c0576000916044620007a060209362000c74565b9250509162000379565b3d915062000776565b60405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b6064820152608490fd5b606460405162461bcd60e51b815260206004820152602060248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152fd5b90506020813d60201162000884575b81620008696020938362000c50565b81010312620006c0576200087d9062000c74565b3862000297565b3d91506200085a565b90506020813d602011620008c6575b81620008ab6020938362000c50565b81010312620006c057620008bf9062000c74565b3862000263565b3d91506200089c565b60405162461bcd60e51b81526020600482015260036024820152624d535360e81b6044820152606490fd5b50828015620002245750841562000224565b5082156200021c565b60405162461bcd60e51b815260206004820152600360248201526216905160ea1b6044820152606490fd5b015190503880620001de565b6004600090815293507f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b91905b601f1984168510620009bf576001945083601f19811610620009a5575b505050811b01600455620001f4565b015160001960f88460031b161c1916905538808062000996565b8181015183556020948501946001909301929091019062000979565b60046000529091507f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b601f840160051c8101916020851062000a45575b90601f859493920160051c01905b81811062000a355750620001c5565b6000815584935060010162000a26565b909150819062000a18565b634e487b7160e01b600052602260045260246000fd5b91607f1691620001af565b634e487b7160e01b600052604160045260246000fd5b01519050388062000174565b6003600090815293507fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b91905b601f198416851062000b06576001945083601f1981161062000aec575b505050811b016003556200018a565b015160001960f88460031b161c1916905538808062000add565b8181015183556020948501946001909301929091019062000ac0565b60036000529091507fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b601f840160051c81016020851062000b8c575b90849392915b601f830160051c8201811062000b7c5750506200015b565b6000815585945060010162000b64565b508062000b5e565b91607f169162000145565b9091503d806000833e62000bb4818362000c50565b810190602081830312620006c0578051906001600160401b038211620006c0570181601f82011215620006c0578051906001600160401b03821162000a71576040519262000c0d601f8401601f19166020018562000c50565b82845260208383010111620006c05760005b82811062000c3a57505060206000918301015290386200011f565b8060208092840101518282870101520162000c1f565b601f909101601f19168101906001600160401b0382119082101762000a7157604052565b51906001600160a01b0382168203620006c057565b51908115158203620006c057565b600680546001600160a01b039283166001600160a01b0319821681179092559091167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a356fe6080604052600436101561001257600080fd5b6000803560e01c8062f714ce14612cf157806302eec56814612cc8578063065e536014612cad57806306fdde0314612beb578063095ea7b314612bc45780630dfe168114612b7f5780630f35bcac14612b6457806316f0115b14612b1f57806318160ddd14612b0157806322401d7c14612ae357806323b872dd14612a275780632bbb56d9146129ba5780632c8958f61461289c578063313ce567146128805780633505b09f1461273057806337e41b40146126f357806339509351146126a35780633e091ee914612647578063400f0ceb146125b457806345e05f431461258b5780634d461fbb1461256d57806351e87af7146125525780635ffc1ff714612502578063648cab85146124e457806370a08231146124ac57806370bb45b314612459578063715018a6146123fc5780637aea5309146123de5780637f7a1eec146123a157806381de128b14612361578063888a913414612346578063897f078c1461231d5780638da5cb5b146122f45780638dbdbe6d1461171757806391563d32146116f157806395d89b41146115e4578063a049de6b146115c5578063a457c2d714611520578063a9059cbb146114ee578063aaf5eb68146114cb578063c4a7761e146114a4578063c879657214611470578063d0c93a7c146113c7578063d21220a714611382578063d2eabcfc14611338578063d87346aa14610608578063d940d768146105ea578063dd62ed3e1461059b578063dd81fa6314610556578063ddca3f43146104aa578063e7bbf2b21461043d578063f2fde38b14610377578063f620732614610353578063f9c95d46146102a15763fa0827431461027957600080fd5b3461029e578060031936011261029e576020610293613587565b6040519060020b8152f35b80fd5b503461029e57602036600319011261029e5760043563ffffffff811680820361034f576102cc6136c2565b801561032457600f805463ffffffff191690911790556040805133815263ffffffff90921660208301527fe4c60f4984caeb7f45b0cfe6d4233c115601ab11d141bc2cbf68b48346cdef389190819081015b0390a180f35b60405162461bcd60e51b815260206004820152600360248201526226a82960e91b6044820152606490fd5b8280fd5b503461029e578060031936011261029e57602063ffffffff600f5416604051908152f35b503461029e57602036600319011261029e57610391613234565b61039961328a565b6001600160a01b039081169081156103e957600654826001600160601b0360a01b821617600655167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a380f35b60405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b6064820152608490fd5b503461029e57602036600319011261029e57610457613234565b61045f6136c2565b60018060a01b0316806001600160601b0360a01b60095416176009556040519081527f52879d117cfbdc2394606bb3ec87af61be311fea7f1fe0ad192d4058ed7d18fa60203392a280f35b503461029e578060031936011261029e576040516339db007960e21b815260c0816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa90811561054b5760209291610517575b5061ffff60405191168152f35b610538915060c03d8111610544575b6105308183613360565b810190613c68565b5050509150503861050a565b503d610526565b6040513d84823e3d90fd5b503461029e578060031936011261029e576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b503461029e57604036600319011261029e576105b5613234565b60406105bf61321e565b9260018060a01b03809316815260016020522091166000526020526020604060002054604051908152f35b503461029e578060031936011261029e576020600a54604051908152f35b503461029e5760a036600319011261029e5760043560020b80600435036109bb5760243560020b9081602435036109bb5760443560020b80604435036109bb5760643560020b9182606435036109bb57610660613701565b6106686136c2565b6040516334324e9f60e21b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610a2f5786916112fa575b50848212806112e4575b806112ce575b156112a357838312908161128b575b81611274575b501561124957149182159261123e575b50501561121357600080600a54806111f5575b50600b54806111cd575b5080158015906111c4575b610be1575b610722600a546148d4565b61072d600b546148d4565b608435610ab6575b6040516370a0823160e01b81523060048201526020816024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610aab578491610a79575b506040516370a0823160e01b8152306004820152916020836024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa928315610a6e578593610a3a575b506040516339db007960e21b81529360c0856004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa8015610a2f576108c7957f9681fa3ae1d0b9be922122be8d3a08c714fb9a23b5a9cdb2f53f2183e9c3080f936101009389928a94610a05575b50600254916040519460020b85528760208601528860408601526060850152608084015260a083015260018060a01b037f00000000000000000000000000000000000000000000000000000000000000001660c083015260018060a01b031660e0820152a1602435600435614a66565b600a556040516370a0823160e01b81523060048201526020816024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa90811561054b5782916109d3575b506040516370a0823160e01b8152306004820152906020826024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa9081156109c857839161098d575b6109829250606435604435614a66565b600b55600160055580f35b90506020823d6020116109c0575b816109a860209383613360565b810103126109bb57610982915190610972565b600080fd5b3d915061099b565b6040513d85823e3d90fd5b90506020813d6020116109fd575b816109ee60209383613360565b810103126109bb57513861091d565b3d91506109e1565b909350610a2191925060c03d8111610544576105308183613360565b505050509190919238610857565b6040513d88823e3d90fd5b9092506020813d602011610a66575b81610a5660209383613360565b810103126109bb575191386107dd565b3d9150610a49565b6040513d87823e3d90fd5b90506020813d602011610aa3575b81610a9460209383613360565b810103126109bb575138610788565b3d9150610a87565b6040513d86823e3d90fd5b826084351380600014610bb45760406084355b8215610b99576401000276a4925b610b2e835130602082015260208152610aef81613344565b84519586948594630251596160e31b86523060048701526024860152604485015260018060a01b0316606484015260a0608484015260a483019061324a565b0381877f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165af18015610aab57610b6e575b50610735565b604090813d8311610b92575b610b848183613360565b8101031261034f5738610b68565b503d610b7a565b73fffd8963efd1fc6a506488495d951d5263988d2592610ad7565b608435600160ff1b14610bcd5760406084358503610ac9565b634e487b7160e01b84526011600452602484fd5b60405163665a17c560e01b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610f7c57600091611192575b506040516337792e1d60e11b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610f7c57600091611160575b506040516370a0823160e01b81523060048201526020816024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610f7c5760009161112e575b5080841015611128575082915b6040516370a0823160e01b81523060048201526020816024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610f7c576000916110f6575b50808610156110f0575084905b801515806110dc575b61101e575b5081610d5e575b505050610717565b6008546000906001600160a01b0316610f885750670de0b6b3a7640000905b60405163011a412160e61b8152936020856004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa948515610f7c57600095610f3f575b50808491610e91575b505080610de3575b50610d56565b610e4292610e0a610e1292610e02670de0b6b3a7640000938492613f36565b049384613f36565b048092614f08565b927f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031661460e565b80610e50575b808080610ddd565b600854610e8b91906001600160a01b03908116907f00000000000000000000000000000000000000000000000000000000000000001661460e565b38610e48565b610ec0610ef191610eac670de0b6b3a7640000948592613f36565b0492610eb88685613f36565b048093614f08565b91867f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031661460e565b80610efe575b8390610dd5565b600854610f3991906001600160a01b03908116907f00000000000000000000000000000000000000000000000000000000000000001661460e565b38610ef7565b90946020823d602011610f74575b81610f5a60209383613360565b8101031261029e5750610f6d84916134a7565b9490610dcc565b3d9150610f4d565b6040513d6000823e3d90fd5b60405163acc8247d60e01b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa918215611012578092610fdd575b505090610d7d565b9091506020823d60201161100a575b81610ff960209383613360565b8101031261029e5750513880610fd5565b3d9150610fec565b604051903d90823e3d90fd5b83611083575b8115610d4f5761107d90670de0b6b3a764000061104c60018060a01b03600754169285613f36565b04907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031661460e565b38610d4f565b6007546110d7906001600160a01b0316670de0b6b3a76400006110a68488613f36565b04907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031661460e565b611024565b506007546001600160a01b03161515610d4a565b90610d41565b906020823d602011611120575b8161111060209383613360565b8101031261029e57505138610d34565b3d9150611103565b91610ce0565b906020823d602011611158575b8161114860209383613360565b8101031261029e57505138610cd3565b3d915061113b565b906020823d60201161118a575b8161117a60209383613360565b8101031261029e57505138610c7e565b3d915061116d565b906020823d6020116111bc575b816111ac60209383613360565b8101031261029e57505138610c2f565b3d915061119f565b50811515610712565b906111da6111ee9261376d565b6111e86111e8600b54614556565b92613382565b9038610707565b9050611201915061376d565b61120c600a54614556565b90386106fd565b60405162461bcd60e51b815260206004820152600360248201526204949560ec1b6044820152606490fd5b1415905038806106ea565b60405162461bcd60e51b81526020600482015260036024820152624c504960e81b6044820152606490fd5b61128191506064356148c2565b60020b15386106da565b9050611299816044356148c2565b60020b15906106d4565b60405162461bcd60e51b815260206004820152600360248201526242504960e81b6044820152606490fd5b506112db816024356148c2565b60020b156106c5565b506112f1816004356148c2565b60020b156106bf565b90506020813d602011611330575b8161131560209383613360565b8101031261132c57611326906134bb565b386106b5565b8580fd5b3d9150611308565b503461029e578060031936011261029e5761137e611357600a54615328565b604080516001600160801b0390941684526020840192909252908201529081906060820190565b0390f35b503461029e578060031936011261029e576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b503461029e578060031936011261029e576040516334324e9f60e21b8152906020826004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115611012578091611434575b6020826040519060020b8152f35b90506020823d8211611468575b8161144e60209383613360565b8101031261029e57506114626020916134bb565b38611426565b3d9150611441565b503461029e578060031936011261029e57611489613701565b6040611493613f69565b600160055582519182526020820152f35b503461029e578060031936011261029e5760406114bf614f15565b82519182526020820152f35b503461029e578060031936011261029e576020604051670de0b6b3a76400008152f35b503461029e57604036600319011261029e5761151561150b613234565b6024359033615747565b602060405160018152f35b503461029e57604036600319011261029e5761153a613234565b60406024359233815260016020522060018060a01b0382166000526020526040600020549180831061157257611515920390336133a5565b60405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608490fd5b503461029e578060031936011261029e5761137e611357600b54615328565b503461029e578060031936011261029e57604051908060045491600183811c928185169485156116e7575b60209586861081146116d3578588528794939291879082156116b1575050600114611657575b505061164392500383613360565b61137e60405192828493845283019061324a565b90859250600482527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b5b85831061169957505061164393508201013880611635565b80548389018501528794508693909201918101611681565b925093505061164394915060ff191682840152151560051b8201013880611635565b634e487b7160e01b83526022600452602483fd5b93607f169361160f565b503461029e578060031936011261029e576020600f5463ffffffff60405191831c168152f35b503461029e57606036600319011261029e576044356001600160a01b03811681036122f057611744613701565b7f0000000000000000000000000000000000000000000000000000000000000000806122e5575b806122d8575b806122ce575b8015612278575b1561224d576001600160a01b03811615158061223a575b61179e90613c27565b6040516339db007960e21b815260c0816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa80156109c85783918491612215575b5060405163809fdd3360e01b8152670de0b6b3a76400006004820152926020846024817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af4938415610a6e5785946121d5575b50602061189a94604051809681926343c57a2760e01b83527f0000000000000000000000000000000000000000000000000000000000000000907f000000000000000000000000000000000000000000000000000000000000000090886004860161559a565b03817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af4938415610a6e578594612199575b509061191091602063ffffffff600f54166118da6155d0565b604051638241348960e01b81526001600160a01b03909116600482015263ffffffff909116602482015293849081906044820190565b03817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af4928315610a2f57869361215d575b5060405163809fdd3360e01b8152670de0b6b3a764000060048201526020816024817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af490811561205557879161211b575b506040516343c57a2760e01b815293602091859182916119e8917f0000000000000000000000000000000000000000000000000000000000000000917f00000000000000000000000000000000000000000000000000000000000000009160020b6004860161559a565b03817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af4928315610a2f5786936120e7575b50600f5460201c63ffffffff1680156120e0576020611a6691611a306155d0565b604051638241348960e01b81526001600160a01b03909116600482015263ffffffff909116602482015291829081906044820190565b03817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af49081156120555787916120a6575b5060405163809fdd3360e01b8152670de0b6b3a764000060048201526020816024817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af4908115612010578891612060575b506040516343c57a2760e01b81529160209183918291611b3e917f0000000000000000000000000000000000000000000000000000000000000000917f00000000000000000000000000000000000000000000000000000000000000009160020b6004860161559a565b03817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af490811561205557879161201f575b505b63ffffffff600f5460201c16600e54611b7e6155d0565b907362a7d1fa1e67000e70e2a7ed59a99e39d8265da13b1561201b57604051630333977f60e51b8152600481018a90526024810188905260448101859052606481019390935260848301526001600160a01b031660a4820152878160c4817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af4801561201057611ffd575b50611c07613f69565b5050611c11614f15565b80959192600435611fc1575b602435611f85575b828910908115611f7e5789905b8163ffffffff600f5460201c1615159283611f45575b50670de0b6b3a7640000611c61611c6a92600435613f36565b04602435613382565b946002549b8c94851515600014611f1057611cbd9796946111e894611cb79794670de0b6b3a764000094611cb094600014611f0957505b8092611eee575b505089613f36565b0494613f36565b90613f49565b955b6001600160a01b03831615611ea95786611cd891613382565b6002556001600160a01b03821680885260208881526040808a2080548a0190555188815289917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a36002546040516339db007960e21b815260c0816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa8015611e9e578493898b7f3aba9fb77678760b537dcec639050ddd940cae3a850b34b8fc37f5c47d40d6ff611e69967f130b253b739caf04e8881d257635ce95d7231a9056540dac5ed79f3ffb1c22f19a9960209f611e2498611e1a98611e0e92918791611e79575b50611dd682615057565b9160405196879660018060a01b03169a7f0000000000000000000000000000000000000000000000000000000000000000908861570a565b0390a360043590613382565b9560243590613382565b956002549360405194859460018060a01b03169833987f00000000000000000000000000000000000000000000000000000000000000006024358d600435908a613cc0565b0390a36001600555604051908152f35b9050611e94915060c03d60c011610544576105308183613360565b5050505038611dcc565b6040513d8b823e3d90fd5b60405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606490fd5b90915081811015611f0257505b3880611ca8565b9050611efb565b9050611ca1565b505050505050506103e890818102918183041490151715611f315795611cbf565b634e487b7160e01b88526011600452602488fd5b905081811015611f6857670de0b6b3a7640000611c61611c6a925b925050611c48565b50611c6a670de0b6b3a7640000611c6183611f60565b8390611c32565b611fbc60243530337f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316613d0d565b611c25565b611ff860043530337f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316613d0d565b611c1d565b612009909791976132e2565b9538611bfe565b6040513d8a823e3d90fd5b8980fd5b90506020813d60201161204d575b8161203a60209383613360565b81010312612049575138611b65565b8680fd5b3d915061202d565b6040513d89823e3d90fd5b90506020813d60201161209e575b8161207b60209383613360565b8101031261209a57611b3e916120926020926134c9565b915091611ad4565b8780fd5b3d915061206e565b90506020813d6020116120d8575b816120c160209383613360565b81010312612049576120d2906134bb565b38611a8d565b3d91506120b4565b5082611b67565b9092506020813d602011612113575b8161210360209383613360565b8101031261132c57519138611a0f565b3d91506120f6565b90506020813d602011612155575b8161213660209383613360565b81010312612049576119e89361214d6020926134c9565b91509361197e565b3d9150612129565b9092506020813d602011612191575b8161217960209383613360565b8101031261132c5761218a906134bb565b9138611937565b3d915061216c565b919093506020823d6020116121cd575b816121b660209383613360565b810103126121c9579051926119106118c1565b8480fd5b3d91506121a9565b93506020843d60201161220d575b816121f060209383613360565b810103126121c957602061220661189a956134c9565b9450611834565b3d91506121e3565b9050612230915060c03d60c011610544576105308183613360565b50505050386117ec565b506001600160a01b038116301415611795565b60405162461bcd60e51b8152602060048201526003602482015262444e4160e81b6044820152606490fd5b507f0000000000000000000000000000000000000000000000000000000000000000806122c3575b806122b6575b801561177e57506004351561177e565b50600d54602435106122a6565b5060243515156122a0565b5060243515611777565b50600c5460043510611771565b50600435151561176b565b5080fd5b503461029e578060031936011261029e576006546040516001600160a01b039091168152602090f35b503461029e578060031936011261029e576007546040516001600160a01b039091168152602090f35b503461029e578060031936011261029e576020610293613610565b503461029e57602036600319011261029e5761237b613234565b6123836136c2565b60018060a01b03166001600160601b0360a01b600754161760075580f35b503461029e578060031936011261029e5760206040517f000000000000000000000000000000000000000000000000000000000000000015158152f35b503461029e578060031936011261029e576020600e54604051908152f35b503461029e578060031936011261029e5761241561328a565b600680546001600160a01b0319811690915581906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b503461029e578060031936011261029e57612472613701565b600a548061249d575b50600b548061248e575b50600160055580f35b6124979061376d565b38612485565b6124a69061376d565b3861247b565b503461029e57602036600319011261029e576020906040906001600160a01b036124d4613234565b1681528083522054604051908152f35b503461029e578060031936011261029e576020600c54604051908152f35b503461029e57602036600319011261029e5760043561251f6136c2565b80600e556040519081527f529698f34660760dcb172def5c99d62e1b5b74b444df322e8f7da31f2bd0a86b60203392a280f35b503461029e578060031936011261029e576020610293613683565b503461029e578060031936011261029e576020600d54604051908152f35b503461029e578060031936011261029e576008546040516001600160a01b039091168152602090f35b503461029e57602036600319011261029e5760043563ffffffff811681036122f05761031e7f39da19f5960a3f182ced1ff1853b7be54f37150799b3003a40bf4e0d4c740c85916126036136c2565b600f805467ffffffff000000001916602083811b67ffffffff0000000016919091179091556040805133815263ffffffff9093169183019190915290918291820190565b503461029e57604036600319011261029e576004356024356126676136c2565b81600c5580600d5560405191825260208201527fafd3b05a4086b378b6f291200a528d8aed8c5e0317af77436b001f1bec28821a60403392a280f35b503461029e57604036600319011261029e57611515906126ec6126c4613234565b9133815260016020526040812060018060a01b03841682526020526040602435912054613382565b90336133a5565b503461029e578060031936011261029e5760206040517f000000000000000000000000000000000000000000000000000000000000000015158152f35b503461029e578060031936011261029e576127496136c2565b6001600160a01b038061275a613b48565b16906040519063095ea7b360e01b918281528360048201526000199384602483015260209386858460448184897f0000000000000000000000000000000000000000000000000000000000000000165af1938415612873578694612838575b50604492939460405197889586948552600485015260248401527f0000000000000000000000000000000000000000000000000000000000000000165af180156109c857612805578280f35b81813d8311612831575b6128198183613360565b810103126122f05761282a906136b5565b5038808280f35b503d61280f565b929383813d831161286c575b61284e8183613360565b8101031261029e5785946128636044946136b5565b509493926127b9565b503d612844565b50604051903d90823e3d90fd5b503461029e578060031936011261029e57602060405160128152f35b503461029e57606036600319011261029e5760243560043560443567ffffffffffffffff8082116121c957366023830112156121c95781600401359081116121c9573691016024011161034f576001600160a01b03917f00000000000000000000000000000000000000000000000000000000000000008316330361298f578382131561295457506129519133907f00000000000000000000000000000000000000000000000000000000000000001661460e565b80f35b905082811361296257505080f35b6129519133907f00000000000000000000000000000000000000000000000000000000000000001661460e565b60405162461bcd60e51b815260206004820152600360248201526231b11960e91b6044820152606490fd5b503461029e57602036600319011261029e576129d4613234565b6129dc6136c2565b60018060a01b0316806001600160601b0360a01b60085416176008556040519081527f3066ef5dd340e8b2ea28d62f5a8391eb7a82d3ee87532724a1ca4386d34f752360203392a280f35b503461029e57606036600319011261029e57612a41613234565b90612a4a61321e565b6001600160a01b03831682526001602081815260408085203386529091529092205492604435928401612a82575b6115159350615747565b828410612a9e57612a9983611515950333836133a5565b612a78565b60405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606490fd5b503461029e578060031936011261029e576020600b54604051908152f35b503461029e578060031936011261029e576020600254604051908152f35b503461029e578060031936011261029e576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b503461029e578060031936011261029e57602061029361369c565b503461029e578060031936011261029e576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b503461029e57604036600319011261029e57611515612be1613234565b60243590336133a5565b503461029e578060031936011261029e57604051908060035491600183811c92818516948515612ca3575b60209586861081146116d3578588528794939291879082156116b1575050600114612c4957505061164392500383613360565b90859250600382527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b5b858310612c8b57505061164393508201013880611635565b80548389018501528794508693909201918101612c73565b93607f1693612c16565b503461029e578060031936011261029e5760206102936154f1565b503461029e578060031936011261029e576009546040516001600160a01b039091168152602090f35b503461029e57604036600319011261029e57600435612d0e61321e565b90612d17613701565b80156131f3576001600160a01b03612d328382161515613c27565b6002549182811480156131ca575b1561319f57612d4d613f69565b5050849185948687600a5480613184575b50828786600b548061316c575b50505050837f00000000000000000000000000000000000000000000000000000000000000001690604051966370a0823160e01b908189523060048a01526020988c8a82602481895afa8015612873578a928d9291613133575b50612dd892612dd391613f36565b613f49565b91877f000000000000000000000000000000000000000000000000000000000000000016906040519081523060048201528d8b82602481865afa8015612873578d928c92916130ee575b5093612e5e969593612e42612e5e94612dd3612e699c95612e6399613f36565b98858c816130dd575b90508a8092506130cc575b505050613382565b613382565b99613382565b94331561307d57338852878552604088205484811061302d578490338a5289875203604089205583600254039081600255886040518681527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef883392a37f0000000000000000000000000000000000000000000000000000000000000000848116604051936339db007960e21b8086528c60c0968781600481885afa801561054b57889487612f578e947f3aba9fb77678760b537dcec639050ddd940cae3a850b34b8fc37f5c47d40d6ff948791889161300a575b50612f4882615057565b91604051968796339a8861570a565b0390a360046040518094819382525afa938415612fff57937fb825c5045d957b2dd950081018da46e8ba5127fe05785c8099ecbd5cb0376e479593612fc2938d938d9a999760409f9594612fd4575b5050612fb0614f15565b918f8e9051998a99169c339c8a613cc0565b0390a360016005558351928352820152f35b612ff09395508091929450903d10610544576105308183613360565b50505050929092913880612fa6565b6040513d8d823e3d90fd5b90506130239150893d8b11610544576105308183613360565b5050505038612f3e565b60405162461bcd60e51b815260048101879052602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608490fd5b60405162461bcd60e51b815260048101869052602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608490fd5b6130d59261460e565b38888b612e56565b6130e69261460e565b38858c612e4b565b925050508a818196959394963d831161312c575b61310c8183613360565b810103126131285751929390929091908b908a90612e5e612e22565b8d80fd5b503d613102565b925050508981813d8311613165575b61314c8183613360565b81010312613161575188908b90612dd8612dc5565b8c80fd5b503d613142565b909192935061317b9450614684565b82878638612d6b565b61319692985083919650858891614684565b96909438612d5e565b60405162461bcd60e51b8152602060048201526003602482015262574d5360e81b6044820152606490fd5b506103e881018082116131df57831015612d40565b634e487b7160e01b86526011600452602486fd5b60405162461bcd60e51b81526020600482015260036024820152620aeb4960eb1b6044820152606490fd5b602435906001600160a01b03821682036109bb57565b600435906001600160a01b03821682036109bb57565b919082519283825260005b848110613276575050826000602080949584010152601f8019910116010190565b602081830181015184830182015201613255565b6006546001600160a01b0316330361329e57565b606460405162461bcd60e51b815260206004820152602060248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152fd5b67ffffffffffffffff81116132f657604052565b634e487b7160e01b600052604160045260246000fd5b6080810190811067ffffffffffffffff8211176132f657604052565b60a0810190811067ffffffffffffffff8211176132f657604052565b6040810190811067ffffffffffffffff8211176132f657604052565b90601f8019910116810190811067ffffffffffffffff8211176132f657604052565b9190820180921161338f57565b634e487b7160e01b600052601160045260246000fd5b6001600160a01b0390811691821561345657169182156134065760207f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925918360005260018252604060002085600052825280604060002055604051908152a3565b60405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608490fd5b60405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608490fd5b51906001600160a01b03821682036109bb57565b51908160020b82036109bb57565b51906001600160801b03821682036109bb57565b9190826101809103126109bb5781516affffffffffffffffffffff811681036109bb579161350d602082016134a7565b9161351a604083016134a7565b91613527606082016134a7565b91613534608083016134a7565b9161354160a082016134bb565b9161354e60c083016134bb565b9161355b60e082016134c9565b91610100820151916101208101519161358461016061357d61014085016134c9565b93016134c9565b90565b600a54801561360a576001600160a01b036135a0613b48565b169060405191829163133f757160e31b835260048301528160246101809485935afa918215610f7c576000926135d557505090565b6135f49250803d10613603575b6135ec8183613360565b8101906134dd565b50505050505094505050505090565b503d6135e2565b50600090565b600a54801561360a576001600160a01b03613629613b48565b169060405191829163133f757160e31b835260048301528160246101809485935afa918215610f7c5760009261365e57505090565b6136749250803d10613603576135ec8183613360565b50505050509550505050505090565b600b54801561360a576001600160a01b036135a0613b48565b600b54801561360a576001600160a01b03613629613b48565b519081151582036109bb57565b6006546001600160a01b031633036136d657565b60405162461bcd60e51b81526020600482015260036024820152624f4e4f60e81b6044820152606490fd5b600260055414613712576002600555565b60405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606490fd5b91908260409103126109bb576020825192015190565b908115613b44576040908151916137838361330c565b60009283815283606060209282848201528285820152015260018060a01b0390602481836137af613bd3565b16855192838092630b02c43d60e41b82528b60048301525afa908115613b0d578691613b17575b506080836137e2613bd3565b16916024865180948193634613f8fb60e11b835260048301525afa928315613b0d578693879288908992613aaf575b508290818851976138218961330c565b168752818688019516855216908187870152606086015215613aa55760095481168015613a9957905b80821615613a8e57856138c0899a836138659b999a9b613bd3565b8451633578057760e11b81528a516001600160a01b03908116600483015260208c01518116602483015260408c015116604482015260608b01516064820152608481019390935291998a9391909216918391829060a4820190565b03925af1948515613a845789968a96613a4f575b508487806139b1575b50505084613918575b5050507f86116443bd63d647e9aa2e093f847ef30ee2a359ffcba4bdf4bb7eb0929cce8b9495508351928352820152a1565b6139679284928a83889461392a613bd3565b169351168a5196879586948593632f2d783d60e01b85526004850160409194939294606082019560018060a01b0380921683521660208201520152565b03925af180156139a75761397d575b80806138e6565b8190813d83116139a0575b6139928183613360565b8101031261132c5785613976565b503d613988565b85513d89823e3d90fd5b6139fe92858d86806139c1613bd3565b169351168d5196879586948593632f2d783d60e01b85526004850160409194939294606082019560018060a01b0380921683521660208201520152565b03925af18015613a4557908591613a18575b5080876138dd565b813d8311613a3e575b613a2b8183613360565b81010312613a3a578338613a10565b8880fd5b503d613a21565b88513d8c823e3d90fd5b909550613a73919650873d8911613a7d575b613a6b8183613360565b810190613757565b95909594386138d4565b503d613a61565b87513d8b823e3d90fd5b505050505050915050565b5080600854169061384a565b5050505050915050565b9350505092506080813d8211613b05575b81613acd60809383613360565b8101031261132c57613ade816134a7565b92613aea8383016134a7565b93816060613af98886016134a7565b94015191959390613811565b3d9150613ac0565b84513d88823e3d90fd5b90508181813d8311613b3d575b613b2e8183613360565b8101031261132c5751386137d6565b503d613b24565b9050565b604051637445c8f560e11b81526001600160a01b03906020816004817f000000000000000000000000000000000000000000000000000000000000000086165afa908115610f7c57600091613b9c57501690565b906020823d8211613bcb575b81613bb560209383613360565b8101031261029e5750613bc7906134a7565b1690565b3d9150613ba8565b604051631baadcbb60e31b81526001600160a01b03906020816004817f000000000000000000000000000000000000000000000000000000000000000086165afa908115610f7c57600091613b9c57501690565b15613c2e57565b60405162461bcd60e51b815260206004820152600360248201526216905160ea1b6044820152606490fd5b519061ffff821682036109bb57565b91908260c09103126109bb57613c7d826134a7565b91613c8a602082016134bb565b91613c9760408301613c59565b91606081015160ff811681036109bb579161358460a0613cb960808501613c59565b93016136b5565b979395919261010097939a9995919a6101208a019b8a5260208a0152604089015260018060a01b038096166060890152608088015260a087015260c086015260020b60e085015216910152565b6040516323b872dd60e01b60208201526001600160a01b039283166024820152929091166044830152606480830193909352918152613d5491613d4f82613328565b613d56565b565b60018060a01b031690604051613d6b81613344565b6020928382527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564848301526000808486829651910182855af13d15613e8f573d9167ffffffffffffffff8311613e7b5790613de693929160405192613dd988601f19601f8401160185613360565b83523d868885013e613e99565b90815190838215928315613e59575b505050905015613e025750565b6084906040519062461bcd60e51b82526004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152fd5b84809293945001031261029e575081613e7291016136b5565b80388381613df5565b634e487b7160e01b85526041600452602485fd5b90613de692916060915b91929015613efb5750815115613ead575090565b3b15613eb65790565b60405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606490fd5b825190915015613f0e5750805190602001fd5b60405162461bcd60e51b815260206004820152908190613f3290602483019061324a565b0390fd5b8181029291811591840414171561338f57565b8115613f53570490565b634e487b7160e01b600052601260045260246000fd5b60009060009081600a54806144f5575b50600b54806144cb575b5083158015906144c2575b613f955750565b6040805163665a17c560e01b81526020926001600160a01b039290916004907f0000000000000000000000000000000000000000000000000000000000000000851686828481845afa9182156144b8578592614489575b5083516337792e1d60e11b81529087828581845afa91821561447f578692614450575b5084516370a0823160e01b808252308683015293907f00000000000000000000000000000000000000000000000000000000000000008916908a81602481855afa8015614446578e8a91614417575b8192501060001461441257508c5b897f00000000000000000000000000000000000000000000000000000000000000001695885190815230888201528b816024818a5afa9081156142e6578e899796959493928d928d916143d4575b50808210156143cc5750935b801515806143bf575b614361575b5050846141c2575b50505050505050837f0000000000000000000000000000000000000000000000000000000000000000169060c0835180926339db007960e21b825281855afa9081156141b557849161418d575b5061413384615057565b939092600254918a8151998d8b528a0152880152606087015260020b608086015260a085015260c08401521660e08201527fd60cb839fcc616abcef8f3fdb4081a15ede9d5e0c919cc0122169d74f65f00456101003392a2565b90506141a891935060c03d8111610544576105308183613360565b5050505092909238614129565b50505051903d90823e3d90fd5b6008548b166142f0578b670de0b6b3a7640000945b8a5163011a412160e61b815297889182905afa9586156142e6578a966142ae575b5080859161425c575b50505080614212575b8086946140dc565b61423892610e0a61423192610e02670de0b6b3a7640000938492613f36565b928461460e565b80614246575b80808061420a565b6142559186600854169061460e565b388061423e565b61428361428b91614277670de0b6b3a7640000948592613f36565b0492610eb88785613f36565b91878461460e565b80614298575b8490614201565b6142a7918b600854169061460e565b3880614291565b9095508b81813d83116142df575b6142c68183613360565b8101031261201b576142d885916134a7565b95906141f8565b503d6142bc565b89513d8c823e3d90fd5b909192939450875163acc8247d60e01b81528b818981885afa9081156142e657889695949392918d918c91614327575b50946141d7565b929394959697505081813d831161435a575b6143438183613360565b8101031261201b57908b8896959493925138614320565b503d614339565b82614397575b84156140d457670de0b6b3a764000061438861439093600754169287613f36565b04908961460e565b8a386140d4565b6143ba8260075416670de0b6b3a76400006143b28487613f36565b04908661460e565b614367565b50816007541615156140cf565b9050936140c6565b939495969798505050508b81813d831161440b575b6143f38183613360565b8101031261201b57908a8e89979695949351386140ba565b503d6143e9565b61406c565b50508a81813d831161443f575b61442e8183613360565b81010312613a3a578d90518161405e565b503d614424565b88513d8b823e3d90fd5b9091508781813d8311614478575b6144688183613360565b8101031261132c5751903861400f565b503d61445e565b85513d88823e3d90fd5b9091508681813d83116144b1575b6144a18183613360565b810103126121c957519038613fec565b503d614497565b84513d87823e3d90fd5b50821515613f8e565b936144da6144ee92949561376d565b6144e86111e8600b54614556565b94613382565b9138613f83565b90925061450391935061376d565b61450e600a54614556565b9290929138613f79565b919091606060808201938051835260018060a01b036020820151166020840152816001600160801b0391826040820151166040860152015116910152565b801561460557600091906001600160a01b03614570613b48565b16906145bb60409283928351906145868261330c565b81523060208201526001600160801b0380858301526060820152835196878094819363fc6f786560e01b835260048301614518565b03925af19283156145fa5760009182946145d6575b50509190565b6145f193945080919250903d10613a7d57613a6b8183613360565b919038806145d0565b50513d6000823e3d90fd5b50600090600090565b60405163a9059cbb60e01b60208201526001600160a01b039092166024830152604480830193909352918152613d5491613d4f8261330c565b91909160808060a0830194805184526001600160801b03602082015116602085015260408101516040850152606081015160608501520151910152565b600094859490936001600160a01b03938693909291856146a2613b48565b16906040948551809363133f757160e31b82528560048301528160246101809687935afa80156148b857889189958a92614887575b50506001600160801b038080961615918261487c575b5050156148525791612dd36147059285809516613f36565b1680614715575b50505050505050565b86995085985061477090859761472e9693949596613b48565b169083519061473c82613328565b8682526020820152878482015287606082015242608082015283519a8b80948193630624e65f60e11b835260048301614647565b03925af180156148485784978591614818575b5092859282856147d79488979b809d8061479b613b48565b16968951966147a98861330c565b87521660208601521686840152166060820152835195868094819363fc6f786560e01b835260048301614518565b03925af190811561480d57506147f2575b808080808061470c565b8161480892903d10613a7d57613a6b8183613360565b6147e8565b8351903d90823e3d90fd5b6147d7929850859491509261483a8794853d8711613a7d57613a6b8183613360565b999099929550925092614783565b85513d86823e3d90fd5b865162461bcd60e51b815260206004820152600360248201526257544f60e81b6044820152606490fd5b1615905084386146ed565b915091506148a2929450803d10613603576135ec8183613360565b9c9a5098505050945050505050909338806146d7565b87513d8a823e3d90fd5b9060020b908115613f535760020b0790565b806148dc5750565b6001600160801b03806148ee836152b8565b16806149cf575b506001600160a01b039182614908613b48565b16926149496040809481519061491d8261330c565b8582523060208301528083830152606082015281518093819263fc6f786560e01b835260048301614518565b0381600080995af180156144b8576149b3575b50614965613b48565b1690813b156149af5783916024839285519687938492630852cd8d60e31b845260048401525af19182156149a557505061499c5750565b613d54906132e2565b51903d90823e3d90fd5b8380fd5b6149c990843d8611613a7d57613a6b8183613360565b5061495c565b60006001600160a01b036149e1613b48565b1691614a2b60409384928351906149f782613328565b888252602082015284848201528460608201524260808201528351948580948193630624e65f60e11b835260048301614647565b03925af18015614a5b57614a40575b506148f5565b81614a5692903d10613a7d57613a6b8183613360565b614a3a565b82513d6000823e3d90fd5b929392909180158080614c9c575b614c9257614a806154f1565b9260020b9260020b838112801580614c86575b15614c5d5750508015614c55575b614c4c575b6001600160a01b03614ab6613b48565b16946040519061016082019282841067ffffffffffffffff8511176132f65760409384526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811684527f00000000000000000000000000000000000000000000000000000000000000008116602085019081526000858701818152606087019889526002998a0b608080890191825260a0890196875260c0890197885260e089018481526101008a01858152306101208c01908152426101408d019081529c5163fe3f3be760e01b81529b51891660048d01529651881660248c01529351871660448b01529a518c0b60648a01529051909a0b6084880152935160a4870152935160c4860152955160e4850152905161010484015293519093166101248201529051610144820152938491610164918391905af1918215610f7c57600092614c0b575b50613d5482614ca4565b9091506080813d8211614c44575b81614c2660809383613360565b810103126109bb57614c3c6020825192016134c9565b509038614c01565b3d9150614c19565b50600093505050565b508415614aa1565b15614c6d5750614c4c575b614aa6565b90508360020b13614aa65784614c685750600093505050565b508560020b8212614a93565b5060009450505050565b508515614a74565b60408051633e75444760e21b8152600092906001600160a01b039060209081816004817f000000000000000000000000000000000000000000000000000000000000000087165afa90811561447f57908392918791614ecc575b50608090602487518096819363ff69b50960e01b8352817f0000000000000000000000000000000000000000000000000000000000000000166004840152165afa92831561447f578693614e59575b505080848301511615614e525780614d63613b48565b1681614d6d613bd3565b16813b156120495786916064839288519485938492634197b18560e11b84528a60048501526001602485015260448401525af1801561447f57614e3f575b50614db4613bd3565b1690813b156121c9578351635739f0b960e01b815281516001600160a01b0390811660048301526020830151811660248301526040830151166044820152606090910151606482015260848101929092529091908390839060a490829084905af1908115614e365750614e25575050565b614e2f82916132e2565b61029e5750565b513d84823e3d90fd5b614e4b909591956132e2565b9338614dab565b5050505050565b909192506080813d8211614ec4575b81614e7560809383613360565b8101031261132c57606090855192614e8c8461330c565b614e95826134a7565b8452614ea28183016134a7565b90840152614eb18682016134a7565b8684015201516060820152903880614d4d565b3d9150614e68565b82809450819392503d8311614f01575b614ee68183613360565b8101031261132c57906080614efb84936134a7565b90614cfe565b503d614edc565b9190820391821161338f57565b614f20600a54615328565b90929150614f2f600b54615328565b6040516370a0823160e01b80825230600483015296919493506020926001600160a01b039284836024817f000000000000000000000000000000000000000000000000000000000000000088165afa8015610f7c578593600091615023575b50614f9d9291612e5e91613382565b9660246040518094819382523060048301527f0000000000000000000000000000000000000000000000000000000000000000165afa918215610f7c57600092614ff2575b50506135849291612e5e91613382565b81819392933d831161501c575b6150098183613360565b8101031261029e57505181612e5e614fe2565b503d614fff565b91929382813d8311615050575b61503a8183613360565b8101031261029e57505184929190614f9d614f8e565b503d615030565b90614f2f61506783600a5461506f565b92915093600b545b91909180156152ad576001600160a01b03615088613b48565b1690604093845192839263133f757160e31b845260048401528260246101809586935afa92831561526b576000958692879488938997615276575b50507362a7d1fa1e67000e70e2a7ed59a99e39d8265da1825163986cfba360e01b998a825260020b60048201526020958682602481865af491821561526b57600092615234575b5084519a8b5260020b60048b0152858a602481855af4928315615229578798999a6000989798946151e2575b50845163c72e160b60e01b81526001600160a01b039182166004820152918116602483015290921660448301526001600160801b03909416606482015293509091819084908180608481015b03915af49283156145fa576151bc93600093928492916151c0575b50506151b4906001600160801b0380931690613382565b941690613382565b9092565b6151b494506151db9250803d10613a7d57613a6b8183613360565b923861519d565b8093959750889196989492943d8311615222575b6152008183613360565b8101031261029e575091849391615219889796946134a7565b92879695615136565b503d6151f6565b84513d6000823e3d90fd5b90918782813d8311615264575b61524b8183613360565b8101031261029e575061525d906134a7565b903861510a565b503d615241565b85513d6000823e3d90fd5b93509350945095506152949250803d10613603576135ec8183613360565b98509950505095509892509050969293919438806150c3565b506000915081908190565b801561360a576001600160a01b036152ce613b48565b169060405191829163133f757160e31b835260048301528160246101809485935afa918215610f7c5760009261530357505090565b6153199250803d10613603576135ec8183613360565b50505050965050505050505090565b9081156154e7576001600160a01b039182615341613b48565b1690604093845192839263133f757160e31b845260048401528260246101809586935afa92831561526b5760009586928794889389976154a9575b505060c06004918351928380926339db007960e21b82527f0000000000000000000000000000000000000000000000000000000000000000165afa908115614a5b57600091615486575b507362a7d1fa1e67000e70e2a7ed59a99e39d8265da1825163986cfba360e01b998a825260020b60048201526020958682602481865af491821561526b57600092615234575084519a8b5260020b60048b0152858a602481855af4928315615229578798999a6000989798946151e25750845163c72e160b60e01b81526001600160a01b039182166004820152918116602483015290921660448301526001600160801b0390941660648201529350909181908490818060848101615182565b61549e915060c03d8111610544576105308183613360565b5050505050386153c6565b91965091945060c09750600493506154cd9250803d10613603576135ec8183613360565b9a509b985050509794509a9250905098949593969161537c565b6000915081908190565b6040516339db007960e21b815260c0816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa8015610f7c576000918291615574575b50156155495790565b60405162461bcd60e51b815260206004820152600360248201526214125360ea1b6044820152606490fd5b905061558e915060c03d8111610544576105308183613360565b94505050509038615540565b60029190910b81526001600160801b039190911660208201526001600160a01b0391821660408201529116606082015260800190565b60405163ef01df4f60e01b81526001600160a01b0391906020907f000000000000000000000000000000000000000000000000000000000000000084168282600481845afa918215610f7c576000926156d3575b506040516330ea6ca760e11b8152948216600486015260248501529281816044817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af4908115610f7c5760009161569e575b50156156745750565b6064906040519062461bcd60e51b82526004820152600360248201526204144560ec1b6044820152fd5b908282813d83116156cc575b6156b48183613360565b8101031261029e57506156c6906136b5565b3861566b565b503d6156aa565b90918382813d8311615703575b6156ea8183613360565b8101031261029e57506156fc906134a7565b9038615624565b503d6156e0565b95919360c0959198979360e0880199885260018060a01b038096166020890152604088015260020b6060870152608086015260a085015216910152565b6001600160a01b039081169182156159285781169283156158d7576000838152806020526040928382205483811061588457839086845283602052038483205585825283822083815401905585857fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60208751878152a37f000000000000000000000000000000000000000000000000000000000000000093600460c0600254938351928380926339db007960e21b82528a165afa90811561587a579161584d939185937f3aba9fb77678760b537dcec639050ddd940cae3a850b34b8fc37f5c47d40d6ff9897969491615852575b5061584084615057565b939092519788978861570a565b0390a3565b905061586d91935060c03d8111610544576105308183613360565b5050505092909238615836565b82513d86823e3d90fd5b845162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608490fd5b60405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608490fd5b60405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608490fdfea164736f6c6343000814000a0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000d50b5ad0d8d9ccafe837162abb80f9d612026a130000000000000000000000000000000000000000000000000000000000000e100000000000000000000000000000000000000000000000000000000000000009

Deployed Bytecode

0x6080604052600436101561001257600080fd5b6000803560e01c8062f714ce14612cf157806302eec56814612cc8578063065e536014612cad57806306fdde0314612beb578063095ea7b314612bc45780630dfe168114612b7f5780630f35bcac14612b6457806316f0115b14612b1f57806318160ddd14612b0157806322401d7c14612ae357806323b872dd14612a275780632bbb56d9146129ba5780632c8958f61461289c578063313ce567146128805780633505b09f1461273057806337e41b40146126f357806339509351146126a35780633e091ee914612647578063400f0ceb146125b457806345e05f431461258b5780634d461fbb1461256d57806351e87af7146125525780635ffc1ff714612502578063648cab85146124e457806370a08231146124ac57806370bb45b314612459578063715018a6146123fc5780637aea5309146123de5780637f7a1eec146123a157806381de128b14612361578063888a913414612346578063897f078c1461231d5780638da5cb5b146122f45780638dbdbe6d1461171757806391563d32146116f157806395d89b41146115e4578063a049de6b146115c5578063a457c2d714611520578063a9059cbb146114ee578063aaf5eb68146114cb578063c4a7761e146114a4578063c879657214611470578063d0c93a7c146113c7578063d21220a714611382578063d2eabcfc14611338578063d87346aa14610608578063d940d768146105ea578063dd62ed3e1461059b578063dd81fa6314610556578063ddca3f43146104aa578063e7bbf2b21461043d578063f2fde38b14610377578063f620732614610353578063f9c95d46146102a15763fa0827431461027957600080fd5b3461029e578060031936011261029e576020610293613587565b6040519060020b8152f35b80fd5b503461029e57602036600319011261029e5760043563ffffffff811680820361034f576102cc6136c2565b801561032457600f805463ffffffff191690911790556040805133815263ffffffff90921660208301527fe4c60f4984caeb7f45b0cfe6d4233c115601ab11d141bc2cbf68b48346cdef389190819081015b0390a180f35b60405162461bcd60e51b815260206004820152600360248201526226a82960e91b6044820152606490fd5b8280fd5b503461029e578060031936011261029e57602063ffffffff600f5416604051908152f35b503461029e57602036600319011261029e57610391613234565b61039961328a565b6001600160a01b039081169081156103e957600654826001600160601b0360a01b821617600655167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a380f35b60405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b6064820152608490fd5b503461029e57602036600319011261029e57610457613234565b61045f6136c2565b60018060a01b0316806001600160601b0360a01b60095416176009556040519081527f52879d117cfbdc2394606bb3ec87af61be311fea7f1fe0ad192d4058ed7d18fa60203392a280f35b503461029e578060031936011261029e576040516339db007960e21b815260c0816004817f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b26001600160a01b03165afa90811561054b5760209291610517575b5061ffff60405191168152f35b610538915060c03d8111610544575b6105308183613360565b810190613c68565b5050509150503861050a565b503d610526565b6040513d84823e3d90fd5b503461029e578060031936011261029e576040517f000000000000000000000000a6ceef2a9b7b080f62ea2f73f2271214f0d928f86001600160a01b03168152602090f35b503461029e57604036600319011261029e576105b5613234565b60406105bf61321e565b9260018060a01b03809316815260016020522091166000526020526020604060002054604051908152f35b503461029e578060031936011261029e576020600a54604051908152f35b503461029e5760a036600319011261029e5760043560020b80600435036109bb5760243560020b9081602435036109bb5760443560020b80604435036109bb5760643560020b9182606435036109bb57610660613701565b6106686136c2565b6040516334324e9f60e21b81526020816004817f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b26001600160a01b03165afa908115610a2f5786916112fa575b50848212806112e4575b806112ce575b156112a357838312908161128b575b81611274575b501561124957149182159261123e575b50501561121357600080600a54806111f5575b50600b54806111cd575b5080158015906111c4575b610be1575b610722600a546148d4565b61072d600b546148d4565b608435610ab6575b6040516370a0823160e01b81523060048201526020816024817f0000000000000000000000003bd359c1119da7da1d913d1c4d2b7c461115433a6001600160a01b03165afa908115610aab578491610a79575b506040516370a0823160e01b8152306004820152916020836024817f0000000000000000000000008498312a6b3cbd158bf0c93abdcf29e6e4f550816001600160a01b03165afa928315610a6e578593610a3a575b506040516339db007960e21b81529360c0856004817f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b26001600160a01b03165afa8015610a2f576108c7957f9681fa3ae1d0b9be922122be8d3a08c714fb9a23b5a9cdb2f53f2183e9c3080f936101009389928a94610a05575b50600254916040519460020b85528760208601528860408601526060850152608084015260a083015260018060a01b037f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b21660c083015260018060a01b031660e0820152a1602435600435614a66565b600a556040516370a0823160e01b81523060048201526020816024817f0000000000000000000000003bd359c1119da7da1d913d1c4d2b7c461115433a6001600160a01b03165afa90811561054b5782916109d3575b506040516370a0823160e01b8152306004820152906020826024817f0000000000000000000000008498312a6b3cbd158bf0c93abdcf29e6e4f550816001600160a01b03165afa9081156109c857839161098d575b6109829250606435604435614a66565b600b55600160055580f35b90506020823d6020116109c0575b816109a860209383613360565b810103126109bb57610982915190610972565b600080fd5b3d915061099b565b6040513d85823e3d90fd5b90506020813d6020116109fd575b816109ee60209383613360565b810103126109bb57513861091d565b3d91506109e1565b909350610a2191925060c03d8111610544576105308183613360565b505050509190919238610857565b6040513d88823e3d90fd5b9092506020813d602011610a66575b81610a5660209383613360565b810103126109bb575191386107dd565b3d9150610a49565b6040513d87823e3d90fd5b90506020813d602011610aa3575b81610a9460209383613360565b810103126109bb575138610788565b3d9150610a87565b6040513d86823e3d90fd5b826084351380600014610bb45760406084355b8215610b99576401000276a4925b610b2e835130602082015260208152610aef81613344565b84519586948594630251596160e31b86523060048701526024860152604485015260018060a01b0316606484015260a0608484015260a483019061324a565b0381877f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b26001600160a01b03165af18015610aab57610b6e575b50610735565b604090813d8311610b92575b610b848183613360565b8101031261034f5738610b68565b503d610b7a565b73fffd8963efd1fc6a506488495d951d5263988d2592610ad7565b608435600160ff1b14610bcd5760406084358503610ac9565b634e487b7160e01b84526011600452602484fd5b60405163665a17c560e01b81526020816004817f000000000000000000000000a6ceef2a9b7b080f62ea2f73f2271214f0d928f86001600160a01b03165afa908115610f7c57600091611192575b506040516337792e1d60e11b81526020816004817f000000000000000000000000a6ceef2a9b7b080f62ea2f73f2271214f0d928f86001600160a01b03165afa908115610f7c57600091611160575b506040516370a0823160e01b81523060048201526020816024817f0000000000000000000000003bd359c1119da7da1d913d1c4d2b7c461115433a6001600160a01b03165afa908115610f7c5760009161112e575b5080841015611128575082915b6040516370a0823160e01b81523060048201526020816024817f0000000000000000000000008498312a6b3cbd158bf0c93abdcf29e6e4f550816001600160a01b03165afa908115610f7c576000916110f6575b50808610156110f0575084905b801515806110dc575b61101e575b5081610d5e575b505050610717565b6008546000906001600160a01b0316610f885750670de0b6b3a7640000905b60405163011a412160e61b8152936020856004817f000000000000000000000000a6ceef2a9b7b080f62ea2f73f2271214f0d928f86001600160a01b03165afa948515610f7c57600095610f3f575b50808491610e91575b505080610de3575b50610d56565b610e4292610e0a610e1292610e02670de0b6b3a7640000938492613f36565b049384613f36565b048092614f08565b927f0000000000000000000000008498312a6b3cbd158bf0c93abdcf29e6e4f550816001600160a01b031661460e565b80610e50575b808080610ddd565b600854610e8b91906001600160a01b03908116907f0000000000000000000000008498312a6b3cbd158bf0c93abdcf29e6e4f550811661460e565b38610e48565b610ec0610ef191610eac670de0b6b3a7640000948592613f36565b0492610eb88685613f36565b048093614f08565b91867f0000000000000000000000003bd359c1119da7da1d913d1c4d2b7c461115433a6001600160a01b031661460e565b80610efe575b8390610dd5565b600854610f3991906001600160a01b03908116907f0000000000000000000000003bd359c1119da7da1d913d1c4d2b7c461115433a1661460e565b38610ef7565b90946020823d602011610f74575b81610f5a60209383613360565b8101031261029e5750610f6d84916134a7565b9490610dcc565b3d9150610f4d565b6040513d6000823e3d90fd5b60405163acc8247d60e01b81526020816004817f000000000000000000000000a6ceef2a9b7b080f62ea2f73f2271214f0d928f86001600160a01b03165afa918215611012578092610fdd575b505090610d7d565b9091506020823d60201161100a575b81610ff960209383613360565b8101031261029e5750513880610fd5565b3d9150610fec565b604051903d90823e3d90fd5b83611083575b8115610d4f5761107d90670de0b6b3a764000061104c60018060a01b03600754169285613f36565b04907f0000000000000000000000008498312a6b3cbd158bf0c93abdcf29e6e4f550816001600160a01b031661460e565b38610d4f565b6007546110d7906001600160a01b0316670de0b6b3a76400006110a68488613f36565b04907f0000000000000000000000003bd359c1119da7da1d913d1c4d2b7c461115433a6001600160a01b031661460e565b611024565b506007546001600160a01b03161515610d4a565b90610d41565b906020823d602011611120575b8161111060209383613360565b8101031261029e57505138610d34565b3d9150611103565b91610ce0565b906020823d602011611158575b8161114860209383613360565b8101031261029e57505138610cd3565b3d915061113b565b906020823d60201161118a575b8161117a60209383613360565b8101031261029e57505138610c7e565b3d915061116d565b906020823d6020116111bc575b816111ac60209383613360565b8101031261029e57505138610c2f565b3d915061119f565b50811515610712565b906111da6111ee9261376d565b6111e86111e8600b54614556565b92613382565b9038610707565b9050611201915061376d565b61120c600a54614556565b90386106fd565b60405162461bcd60e51b815260206004820152600360248201526204949560ec1b6044820152606490fd5b1415905038806106ea565b60405162461bcd60e51b81526020600482015260036024820152624c504960e81b6044820152606490fd5b61128191506064356148c2565b60020b15386106da565b9050611299816044356148c2565b60020b15906106d4565b60405162461bcd60e51b815260206004820152600360248201526242504960e81b6044820152606490fd5b506112db816024356148c2565b60020b156106c5565b506112f1816004356148c2565b60020b156106bf565b90506020813d602011611330575b8161131560209383613360565b8101031261132c57611326906134bb565b386106b5565b8580fd5b3d9150611308565b503461029e578060031936011261029e5761137e611357600a54615328565b604080516001600160801b0390941684526020840192909252908201529081906060820190565b0390f35b503461029e578060031936011261029e576040517f0000000000000000000000008498312a6b3cbd158bf0c93abdcf29e6e4f550816001600160a01b03168152602090f35b503461029e578060031936011261029e576040516334324e9f60e21b8152906020826004817f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b26001600160a01b03165afa908115611012578091611434575b6020826040519060020b8152f35b90506020823d8211611468575b8161144e60209383613360565b8101031261029e57506114626020916134bb565b38611426565b3d9150611441565b503461029e578060031936011261029e57611489613701565b6040611493613f69565b600160055582519182526020820152f35b503461029e578060031936011261029e5760406114bf614f15565b82519182526020820152f35b503461029e578060031936011261029e576020604051670de0b6b3a76400008152f35b503461029e57604036600319011261029e5761151561150b613234565b6024359033615747565b602060405160018152f35b503461029e57604036600319011261029e5761153a613234565b60406024359233815260016020522060018060a01b0382166000526020526040600020549180831061157257611515920390336133a5565b60405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608490fd5b503461029e578060031936011261029e5761137e611357600b54615328565b503461029e578060031936011261029e57604051908060045491600183811c928185169485156116e7575b60209586861081146116d3578588528794939291879082156116b1575050600114611657575b505061164392500383613360565b61137e60405192828493845283019061324a565b90859250600482527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b5b85831061169957505061164393508201013880611635565b80548389018501528794508693909201918101611681565b925093505061164394915060ff191682840152151560051b8201013880611635565b634e487b7160e01b83526022600452602483fd5b93607f169361160f565b503461029e578060031936011261029e576020600f5463ffffffff60405191831c168152f35b503461029e57606036600319011261029e576044356001600160a01b03811681036122f057611744613701565b7f0000000000000000000000000000000000000000000000000000000000000000806122e5575b806122d8575b806122ce575b8015612278575b1561224d576001600160a01b03811615158061223a575b61179e90613c27565b6040516339db007960e21b815260c0816004817f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b26001600160a01b03165afa80156109c85783918491612215575b5060405163809fdd3360e01b8152670de0b6b3a76400006004820152926020846024817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af4938415610a6e5785946121d5575b50602061189a94604051809681926343c57a2760e01b83527f0000000000000000000000008498312a6b3cbd158bf0c93abdcf29e6e4f55081907f0000000000000000000000003bd359c1119da7da1d913d1c4d2b7c461115433a90886004860161559a565b03817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af4938415610a6e578594612199575b509061191091602063ffffffff600f54166118da6155d0565b604051638241348960e01b81526001600160a01b03909116600482015263ffffffff909116602482015293849081906044820190565b03817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af4928315610a2f57869361215d575b5060405163809fdd3360e01b8152670de0b6b3a764000060048201526020816024817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af490811561205557879161211b575b506040516343c57a2760e01b815293602091859182916119e8917f0000000000000000000000008498312a6b3cbd158bf0c93abdcf29e6e4f55081917f0000000000000000000000003bd359c1119da7da1d913d1c4d2b7c461115433a9160020b6004860161559a565b03817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af4928315610a2f5786936120e7575b50600f5460201c63ffffffff1680156120e0576020611a6691611a306155d0565b604051638241348960e01b81526001600160a01b03909116600482015263ffffffff909116602482015291829081906044820190565b03817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af49081156120555787916120a6575b5060405163809fdd3360e01b8152670de0b6b3a764000060048201526020816024817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af4908115612010578891612060575b506040516343c57a2760e01b81529160209183918291611b3e917f0000000000000000000000008498312a6b3cbd158bf0c93abdcf29e6e4f55081917f0000000000000000000000003bd359c1119da7da1d913d1c4d2b7c461115433a9160020b6004860161559a565b03817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af490811561205557879161201f575b505b63ffffffff600f5460201c16600e54611b7e6155d0565b907362a7d1fa1e67000e70e2a7ed59a99e39d8265da13b1561201b57604051630333977f60e51b8152600481018a90526024810188905260448101859052606481019390935260848301526001600160a01b031660a4820152878160c4817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af4801561201057611ffd575b50611c07613f69565b5050611c11614f15565b80959192600435611fc1575b602435611f85575b828910908115611f7e5789905b8163ffffffff600f5460201c1615159283611f45575b50670de0b6b3a7640000611c61611c6a92600435613f36565b04602435613382565b946002549b8c94851515600014611f1057611cbd9796946111e894611cb79794670de0b6b3a764000094611cb094600014611f0957505b8092611eee575b505089613f36565b0494613f36565b90613f49565b955b6001600160a01b03831615611ea95786611cd891613382565b6002556001600160a01b03821680885260208881526040808a2080548a0190555188815289917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a36002546040516339db007960e21b815260c0816004817f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b26001600160a01b03165afa8015611e9e578493898b7f3aba9fb77678760b537dcec639050ddd940cae3a850b34b8fc37f5c47d40d6ff611e69967f130b253b739caf04e8881d257635ce95d7231a9056540dac5ed79f3ffb1c22f19a9960209f611e2498611e1a98611e0e92918791611e79575b50611dd682615057565b9160405196879660018060a01b03169a7f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b2908861570a565b0390a360043590613382565b9560243590613382565b956002549360405194859460018060a01b03169833987f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b26024358d600435908a613cc0565b0390a36001600555604051908152f35b9050611e94915060c03d60c011610544576105308183613360565b5050505038611dcc565b6040513d8b823e3d90fd5b60405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606490fd5b90915081811015611f0257505b3880611ca8565b9050611efb565b9050611ca1565b505050505050506103e890818102918183041490151715611f315795611cbf565b634e487b7160e01b88526011600452602488fd5b905081811015611f6857670de0b6b3a7640000611c61611c6a925b925050611c48565b50611c6a670de0b6b3a7640000611c6183611f60565b8390611c32565b611fbc60243530337f0000000000000000000000008498312a6b3cbd158bf0c93abdcf29e6e4f550816001600160a01b0316613d0d565b611c25565b611ff860043530337f0000000000000000000000003bd359c1119da7da1d913d1c4d2b7c461115433a6001600160a01b0316613d0d565b611c1d565b612009909791976132e2565b9538611bfe565b6040513d8a823e3d90fd5b8980fd5b90506020813d60201161204d575b8161203a60209383613360565b81010312612049575138611b65565b8680fd5b3d915061202d565b6040513d89823e3d90fd5b90506020813d60201161209e575b8161207b60209383613360565b8101031261209a57611b3e916120926020926134c9565b915091611ad4565b8780fd5b3d915061206e565b90506020813d6020116120d8575b816120c160209383613360565b81010312612049576120d2906134bb565b38611a8d565b3d91506120b4565b5082611b67565b9092506020813d602011612113575b8161210360209383613360565b8101031261132c57519138611a0f565b3d91506120f6565b90506020813d602011612155575b8161213660209383613360565b81010312612049576119e89361214d6020926134c9565b91509361197e565b3d9150612129565b9092506020813d602011612191575b8161217960209383613360565b8101031261132c5761218a906134bb565b9138611937565b3d915061216c565b919093506020823d6020116121cd575b816121b660209383613360565b810103126121c9579051926119106118c1565b8480fd5b3d91506121a9565b93506020843d60201161220d575b816121f060209383613360565b810103126121c957602061220661189a956134c9565b9450611834565b3d91506121e3565b9050612230915060c03d60c011610544576105308183613360565b50505050386117ec565b506001600160a01b038116301415611795565b60405162461bcd60e51b8152602060048201526003602482015262444e4160e81b6044820152606490fd5b507f0000000000000000000000000000000000000000000000000000000000000001806122c3575b806122b6575b801561177e57506004351561177e565b50600d54602435106122a6565b5060243515156122a0565b5060243515611777565b50600c5460043510611771565b50600435151561176b565b5080fd5b503461029e578060031936011261029e576006546040516001600160a01b039091168152602090f35b503461029e578060031936011261029e576007546040516001600160a01b039091168152602090f35b503461029e578060031936011261029e576020610293613610565b503461029e57602036600319011261029e5761237b613234565b6123836136c2565b60018060a01b03166001600160601b0360a01b600754161760075580f35b503461029e578060031936011261029e5760206040517f000000000000000000000000000000000000000000000000000000000000000015158152f35b503461029e578060031936011261029e576020600e54604051908152f35b503461029e578060031936011261029e5761241561328a565b600680546001600160a01b0319811690915581906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b503461029e578060031936011261029e57612472613701565b600a548061249d575b50600b548061248e575b50600160055580f35b6124979061376d565b38612485565b6124a69061376d565b3861247b565b503461029e57602036600319011261029e576020906040906001600160a01b036124d4613234565b1681528083522054604051908152f35b503461029e578060031936011261029e576020600c54604051908152f35b503461029e57602036600319011261029e5760043561251f6136c2565b80600e556040519081527f529698f34660760dcb172def5c99d62e1b5b74b444df322e8f7da31f2bd0a86b60203392a280f35b503461029e578060031936011261029e576020610293613683565b503461029e578060031936011261029e576020600d54604051908152f35b503461029e578060031936011261029e576008546040516001600160a01b039091168152602090f35b503461029e57602036600319011261029e5760043563ffffffff811681036122f05761031e7f39da19f5960a3f182ced1ff1853b7be54f37150799b3003a40bf4e0d4c740c85916126036136c2565b600f805467ffffffff000000001916602083811b67ffffffff0000000016919091179091556040805133815263ffffffff9093169183019190915290918291820190565b503461029e57604036600319011261029e576004356024356126676136c2565b81600c5580600d5560405191825260208201527fafd3b05a4086b378b6f291200a528d8aed8c5e0317af77436b001f1bec28821a60403392a280f35b503461029e57604036600319011261029e57611515906126ec6126c4613234565b9133815260016020526040812060018060a01b03841682526020526040602435912054613382565b90336133a5565b503461029e578060031936011261029e5760206040517f000000000000000000000000000000000000000000000000000000000000000115158152f35b503461029e578060031936011261029e576127496136c2565b6001600160a01b038061275a613b48565b16906040519063095ea7b360e01b918281528360048201526000199384602483015260209386858460448184897f0000000000000000000000003bd359c1119da7da1d913d1c4d2b7c461115433a165af1938415612873578694612838575b50604492939460405197889586948552600485015260248401527f0000000000000000000000008498312a6b3cbd158bf0c93abdcf29e6e4f55081165af180156109c857612805578280f35b81813d8311612831575b6128198183613360565b810103126122f05761282a906136b5565b5038808280f35b503d61280f565b929383813d831161286c575b61284e8183613360565b8101031261029e5785946128636044946136b5565b509493926127b9565b503d612844565b50604051903d90823e3d90fd5b503461029e578060031936011261029e57602060405160128152f35b503461029e57606036600319011261029e5760243560043560443567ffffffffffffffff8082116121c957366023830112156121c95781600401359081116121c9573691016024011161034f576001600160a01b03917f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b28316330361298f578382131561295457506129519133907f0000000000000000000000003bd359c1119da7da1d913d1c4d2b7c461115433a1661460e565b80f35b905082811361296257505080f35b6129519133907f0000000000000000000000008498312a6b3cbd158bf0c93abdcf29e6e4f550811661460e565b60405162461bcd60e51b815260206004820152600360248201526231b11960e91b6044820152606490fd5b503461029e57602036600319011261029e576129d4613234565b6129dc6136c2565b60018060a01b0316806001600160601b0360a01b60085416176008556040519081527f3066ef5dd340e8b2ea28d62f5a8391eb7a82d3ee87532724a1ca4386d34f752360203392a280f35b503461029e57606036600319011261029e57612a41613234565b90612a4a61321e565b6001600160a01b03831682526001602081815260408085203386529091529092205492604435928401612a82575b6115159350615747565b828410612a9e57612a9983611515950333836133a5565b612a78565b60405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606490fd5b503461029e578060031936011261029e576020600b54604051908152f35b503461029e578060031936011261029e576020600254604051908152f35b503461029e578060031936011261029e576040517f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b26001600160a01b03168152602090f35b503461029e578060031936011261029e57602061029361369c565b503461029e578060031936011261029e576040517f0000000000000000000000003bd359c1119da7da1d913d1c4d2b7c461115433a6001600160a01b03168152602090f35b503461029e57604036600319011261029e57611515612be1613234565b60243590336133a5565b503461029e578060031936011261029e57604051908060035491600183811c92818516948515612ca3575b60209586861081146116d3578588528794939291879082156116b1575050600114612c4957505061164392500383613360565b90859250600382527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b5b858310612c8b57505061164393508201013880611635565b80548389018501528794508693909201918101612c73565b93607f1693612c16565b503461029e578060031936011261029e5760206102936154f1565b503461029e578060031936011261029e576009546040516001600160a01b039091168152602090f35b503461029e57604036600319011261029e57600435612d0e61321e565b90612d17613701565b80156131f3576001600160a01b03612d328382161515613c27565b6002549182811480156131ca575b1561319f57612d4d613f69565b5050849185948687600a5480613184575b50828786600b548061316c575b50505050837f0000000000000000000000003bd359c1119da7da1d913d1c4d2b7c461115433a1690604051966370a0823160e01b908189523060048a01526020988c8a82602481895afa8015612873578a928d9291613133575b50612dd892612dd391613f36565b613f49565b91877f0000000000000000000000008498312a6b3cbd158bf0c93abdcf29e6e4f5508116906040519081523060048201528d8b82602481865afa8015612873578d928c92916130ee575b5093612e5e969593612e42612e5e94612dd3612e699c95612e6399613f36565b98858c816130dd575b90508a8092506130cc575b505050613382565b613382565b99613382565b94331561307d57338852878552604088205484811061302d578490338a5289875203604089205583600254039081600255886040518681527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef883392a37f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b2848116604051936339db007960e21b8086528c60c0968781600481885afa801561054b57889487612f578e947f3aba9fb77678760b537dcec639050ddd940cae3a850b34b8fc37f5c47d40d6ff948791889161300a575b50612f4882615057565b91604051968796339a8861570a565b0390a360046040518094819382525afa938415612fff57937fb825c5045d957b2dd950081018da46e8ba5127fe05785c8099ecbd5cb0376e479593612fc2938d938d9a999760409f9594612fd4575b5050612fb0614f15565b918f8e9051998a99169c339c8a613cc0565b0390a360016005558351928352820152f35b612ff09395508091929450903d10610544576105308183613360565b50505050929092913880612fa6565b6040513d8d823e3d90fd5b90506130239150893d8b11610544576105308183613360565b5050505038612f3e565b60405162461bcd60e51b815260048101879052602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608490fd5b60405162461bcd60e51b815260048101869052602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608490fd5b6130d59261460e565b38888b612e56565b6130e69261460e565b38858c612e4b565b925050508a818196959394963d831161312c575b61310c8183613360565b810103126131285751929390929091908b908a90612e5e612e22565b8d80fd5b503d613102565b925050508981813d8311613165575b61314c8183613360565b81010312613161575188908b90612dd8612dc5565b8c80fd5b503d613142565b909192935061317b9450614684565b82878638612d6b565b61319692985083919650858891614684565b96909438612d5e565b60405162461bcd60e51b8152602060048201526003602482015262574d5360e81b6044820152606490fd5b506103e881018082116131df57831015612d40565b634e487b7160e01b86526011600452602486fd5b60405162461bcd60e51b81526020600482015260036024820152620aeb4960eb1b6044820152606490fd5b602435906001600160a01b03821682036109bb57565b600435906001600160a01b03821682036109bb57565b919082519283825260005b848110613276575050826000602080949584010152601f8019910116010190565b602081830181015184830182015201613255565b6006546001600160a01b0316330361329e57565b606460405162461bcd60e51b815260206004820152602060248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152fd5b67ffffffffffffffff81116132f657604052565b634e487b7160e01b600052604160045260246000fd5b6080810190811067ffffffffffffffff8211176132f657604052565b60a0810190811067ffffffffffffffff8211176132f657604052565b6040810190811067ffffffffffffffff8211176132f657604052565b90601f8019910116810190811067ffffffffffffffff8211176132f657604052565b9190820180921161338f57565b634e487b7160e01b600052601160045260246000fd5b6001600160a01b0390811691821561345657169182156134065760207f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925918360005260018252604060002085600052825280604060002055604051908152a3565b60405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608490fd5b60405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608490fd5b51906001600160a01b03821682036109bb57565b51908160020b82036109bb57565b51906001600160801b03821682036109bb57565b9190826101809103126109bb5781516affffffffffffffffffffff811681036109bb579161350d602082016134a7565b9161351a604083016134a7565b91613527606082016134a7565b91613534608083016134a7565b9161354160a082016134bb565b9161354e60c083016134bb565b9161355b60e082016134c9565b91610100820151916101208101519161358461016061357d61014085016134c9565b93016134c9565b90565b600a54801561360a576001600160a01b036135a0613b48565b169060405191829163133f757160e31b835260048301528160246101809485935afa918215610f7c576000926135d557505090565b6135f49250803d10613603575b6135ec8183613360565b8101906134dd565b50505050505094505050505090565b503d6135e2565b50600090565b600a54801561360a576001600160a01b03613629613b48565b169060405191829163133f757160e31b835260048301528160246101809485935afa918215610f7c5760009261365e57505090565b6136749250803d10613603576135ec8183613360565b50505050509550505050505090565b600b54801561360a576001600160a01b036135a0613b48565b600b54801561360a576001600160a01b03613629613b48565b519081151582036109bb57565b6006546001600160a01b031633036136d657565b60405162461bcd60e51b81526020600482015260036024820152624f4e4f60e81b6044820152606490fd5b600260055414613712576002600555565b60405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606490fd5b91908260409103126109bb576020825192015190565b908115613b44576040908151916137838361330c565b60009283815283606060209282848201528285820152015260018060a01b0390602481836137af613bd3565b16855192838092630b02c43d60e41b82528b60048301525afa908115613b0d578691613b17575b506080836137e2613bd3565b16916024865180948193634613f8fb60e11b835260048301525afa928315613b0d578693879288908992613aaf575b508290818851976138218961330c565b168752818688019516855216908187870152606086015215613aa55760095481168015613a9957905b80821615613a8e57856138c0899a836138659b999a9b613bd3565b8451633578057760e11b81528a516001600160a01b03908116600483015260208c01518116602483015260408c015116604482015260608b01516064820152608481019390935291998a9391909216918391829060a4820190565b03925af1948515613a845789968a96613a4f575b508487806139b1575b50505084613918575b5050507f86116443bd63d647e9aa2e093f847ef30ee2a359ffcba4bdf4bb7eb0929cce8b9495508351928352820152a1565b6139679284928a83889461392a613bd3565b169351168a5196879586948593632f2d783d60e01b85526004850160409194939294606082019560018060a01b0380921683521660208201520152565b03925af180156139a75761397d575b80806138e6565b8190813d83116139a0575b6139928183613360565b8101031261132c5785613976565b503d613988565b85513d89823e3d90fd5b6139fe92858d86806139c1613bd3565b169351168d5196879586948593632f2d783d60e01b85526004850160409194939294606082019560018060a01b0380921683521660208201520152565b03925af18015613a4557908591613a18575b5080876138dd565b813d8311613a3e575b613a2b8183613360565b81010312613a3a578338613a10565b8880fd5b503d613a21565b88513d8c823e3d90fd5b909550613a73919650873d8911613a7d575b613a6b8183613360565b810190613757565b95909594386138d4565b503d613a61565b87513d8b823e3d90fd5b505050505050915050565b5080600854169061384a565b5050505050915050565b9350505092506080813d8211613b05575b81613acd60809383613360565b8101031261132c57613ade816134a7565b92613aea8383016134a7565b93816060613af98886016134a7565b94015191959390613811565b3d9150613ac0565b84513d88823e3d90fd5b90508181813d8311613b3d575b613b2e8183613360565b8101031261132c5751386137d6565b503d613b24565b9050565b604051637445c8f560e11b81526001600160a01b03906020816004817f000000000000000000000000a6ceef2a9b7b080f62ea2f73f2271214f0d928f886165afa908115610f7c57600091613b9c57501690565b906020823d8211613bcb575b81613bb560209383613360565b8101031261029e5750613bc7906134a7565b1690565b3d9150613ba8565b604051631baadcbb60e31b81526001600160a01b03906020816004817f000000000000000000000000a6ceef2a9b7b080f62ea2f73f2271214f0d928f886165afa908115610f7c57600091613b9c57501690565b15613c2e57565b60405162461bcd60e51b815260206004820152600360248201526216905160ea1b6044820152606490fd5b519061ffff821682036109bb57565b91908260c09103126109bb57613c7d826134a7565b91613c8a602082016134bb565b91613c9760408301613c59565b91606081015160ff811681036109bb579161358460a0613cb960808501613c59565b93016136b5565b979395919261010097939a9995919a6101208a019b8a5260208a0152604089015260018060a01b038096166060890152608088015260a087015260c086015260020b60e085015216910152565b6040516323b872dd60e01b60208201526001600160a01b039283166024820152929091166044830152606480830193909352918152613d5491613d4f82613328565b613d56565b565b60018060a01b031690604051613d6b81613344565b6020928382527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564848301526000808486829651910182855af13d15613e8f573d9167ffffffffffffffff8311613e7b5790613de693929160405192613dd988601f19601f8401160185613360565b83523d868885013e613e99565b90815190838215928315613e59575b505050905015613e025750565b6084906040519062461bcd60e51b82526004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152fd5b84809293945001031261029e575081613e7291016136b5565b80388381613df5565b634e487b7160e01b85526041600452602485fd5b90613de692916060915b91929015613efb5750815115613ead575090565b3b15613eb65790565b60405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606490fd5b825190915015613f0e5750805190602001fd5b60405162461bcd60e51b815260206004820152908190613f3290602483019061324a565b0390fd5b8181029291811591840414171561338f57565b8115613f53570490565b634e487b7160e01b600052601260045260246000fd5b60009060009081600a54806144f5575b50600b54806144cb575b5083158015906144c2575b613f955750565b6040805163665a17c560e01b81526020926001600160a01b039290916004907f000000000000000000000000a6ceef2a9b7b080f62ea2f73f2271214f0d928f8851686828481845afa9182156144b8578592614489575b5083516337792e1d60e11b81529087828581845afa91821561447f578692614450575b5084516370a0823160e01b808252308683015293907f0000000000000000000000003bd359c1119da7da1d913d1c4d2b7c461115433a8916908a81602481855afa8015614446578e8a91614417575b8192501060001461441257508c5b897f0000000000000000000000008498312a6b3cbd158bf0c93abdcf29e6e4f550811695885190815230888201528b816024818a5afa9081156142e6578e899796959493928d928d916143d4575b50808210156143cc5750935b801515806143bf575b614361575b5050846141c2575b50505050505050837f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b2169060c0835180926339db007960e21b825281855afa9081156141b557849161418d575b5061413384615057565b939092600254918a8151998d8b528a0152880152606087015260020b608086015260a085015260c08401521660e08201527fd60cb839fcc616abcef8f3fdb4081a15ede9d5e0c919cc0122169d74f65f00456101003392a2565b90506141a891935060c03d8111610544576105308183613360565b5050505092909238614129565b50505051903d90823e3d90fd5b6008548b166142f0578b670de0b6b3a7640000945b8a5163011a412160e61b815297889182905afa9586156142e6578a966142ae575b5080859161425c575b50505080614212575b8086946140dc565b61423892610e0a61423192610e02670de0b6b3a7640000938492613f36565b928461460e565b80614246575b80808061420a565b6142559186600854169061460e565b388061423e565b61428361428b91614277670de0b6b3a7640000948592613f36565b0492610eb88785613f36565b91878461460e565b80614298575b8490614201565b6142a7918b600854169061460e565b3880614291565b9095508b81813d83116142df575b6142c68183613360565b8101031261201b576142d885916134a7565b95906141f8565b503d6142bc565b89513d8c823e3d90fd5b909192939450875163acc8247d60e01b81528b818981885afa9081156142e657889695949392918d918c91614327575b50946141d7565b929394959697505081813d831161435a575b6143438183613360565b8101031261201b57908b8896959493925138614320565b503d614339565b82614397575b84156140d457670de0b6b3a764000061438861439093600754169287613f36565b04908961460e565b8a386140d4565b6143ba8260075416670de0b6b3a76400006143b28487613f36565b04908661460e565b614367565b50816007541615156140cf565b9050936140c6565b939495969798505050508b81813d831161440b575b6143f38183613360565b8101031261201b57908a8e89979695949351386140ba565b503d6143e9565b61406c565b50508a81813d831161443f575b61442e8183613360565b81010312613a3a578d90518161405e565b503d614424565b88513d8b823e3d90fd5b9091508781813d8311614478575b6144688183613360565b8101031261132c5751903861400f565b503d61445e565b85513d88823e3d90fd5b9091508681813d83116144b1575b6144a18183613360565b810103126121c957519038613fec565b503d614497565b84513d87823e3d90fd5b50821515613f8e565b936144da6144ee92949561376d565b6144e86111e8600b54614556565b94613382565b9138613f83565b90925061450391935061376d565b61450e600a54614556565b9290929138613f79565b919091606060808201938051835260018060a01b036020820151166020840152816001600160801b0391826040820151166040860152015116910152565b801561460557600091906001600160a01b03614570613b48565b16906145bb60409283928351906145868261330c565b81523060208201526001600160801b0380858301526060820152835196878094819363fc6f786560e01b835260048301614518565b03925af19283156145fa5760009182946145d6575b50509190565b6145f193945080919250903d10613a7d57613a6b8183613360565b919038806145d0565b50513d6000823e3d90fd5b50600090600090565b60405163a9059cbb60e01b60208201526001600160a01b039092166024830152604480830193909352918152613d5491613d4f8261330c565b91909160808060a0830194805184526001600160801b03602082015116602085015260408101516040850152606081015160608501520151910152565b600094859490936001600160a01b03938693909291856146a2613b48565b16906040948551809363133f757160e31b82528560048301528160246101809687935afa80156148b857889189958a92614887575b50506001600160801b038080961615918261487c575b5050156148525791612dd36147059285809516613f36565b1680614715575b50505050505050565b86995085985061477090859761472e9693949596613b48565b169083519061473c82613328565b8682526020820152878482015287606082015242608082015283519a8b80948193630624e65f60e11b835260048301614647565b03925af180156148485784978591614818575b5092859282856147d79488979b809d8061479b613b48565b16968951966147a98861330c565b87521660208601521686840152166060820152835195868094819363fc6f786560e01b835260048301614518565b03925af190811561480d57506147f2575b808080808061470c565b8161480892903d10613a7d57613a6b8183613360565b6147e8565b8351903d90823e3d90fd5b6147d7929850859491509261483a8794853d8711613a7d57613a6b8183613360565b999099929550925092614783565b85513d86823e3d90fd5b865162461bcd60e51b815260206004820152600360248201526257544f60e81b6044820152606490fd5b1615905084386146ed565b915091506148a2929450803d10613603576135ec8183613360565b9c9a5098505050945050505050909338806146d7565b87513d8a823e3d90fd5b9060020b908115613f535760020b0790565b806148dc5750565b6001600160801b03806148ee836152b8565b16806149cf575b506001600160a01b039182614908613b48565b16926149496040809481519061491d8261330c565b8582523060208301528083830152606082015281518093819263fc6f786560e01b835260048301614518565b0381600080995af180156144b8576149b3575b50614965613b48565b1690813b156149af5783916024839285519687938492630852cd8d60e31b845260048401525af19182156149a557505061499c5750565b613d54906132e2565b51903d90823e3d90fd5b8380fd5b6149c990843d8611613a7d57613a6b8183613360565b5061495c565b60006001600160a01b036149e1613b48565b1691614a2b60409384928351906149f782613328565b888252602082015284848201528460608201524260808201528351948580948193630624e65f60e11b835260048301614647565b03925af18015614a5b57614a40575b506148f5565b81614a5692903d10613a7d57613a6b8183613360565b614a3a565b82513d6000823e3d90fd5b929392909180158080614c9c575b614c9257614a806154f1565b9260020b9260020b838112801580614c86575b15614c5d5750508015614c55575b614c4c575b6001600160a01b03614ab6613b48565b16946040519061016082019282841067ffffffffffffffff8511176132f65760409384526001600160a01b037f0000000000000000000000003bd359c1119da7da1d913d1c4d2b7c461115433a811684527f0000000000000000000000008498312a6b3cbd158bf0c93abdcf29e6e4f550818116602085019081526000858701818152606087019889526002998a0b608080890191825260a0890196875260c0890197885260e089018481526101008a01858152306101208c01908152426101408d019081529c5163fe3f3be760e01b81529b51891660048d01529651881660248c01529351871660448b01529a518c0b60648a01529051909a0b6084880152935160a4870152935160c4860152955160e4850152905161010484015293519093166101248201529051610144820152938491610164918391905af1918215610f7c57600092614c0b575b50613d5482614ca4565b9091506080813d8211614c44575b81614c2660809383613360565b810103126109bb57614c3c6020825192016134c9565b509038614c01565b3d9150614c19565b50600093505050565b508415614aa1565b15614c6d5750614c4c575b614aa6565b90508360020b13614aa65784614c685750600093505050565b508560020b8212614a93565b5060009450505050565b508515614a74565b60408051633e75444760e21b8152600092906001600160a01b039060209081816004817f000000000000000000000000a6ceef2a9b7b080f62ea2f73f2271214f0d928f887165afa90811561447f57908392918791614ecc575b50608090602487518096819363ff69b50960e01b8352817f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b2166004840152165afa92831561447f578693614e59575b505080848301511615614e525780614d63613b48565b1681614d6d613bd3565b16813b156120495786916064839288519485938492634197b18560e11b84528a60048501526001602485015260448401525af1801561447f57614e3f575b50614db4613bd3565b1690813b156121c9578351635739f0b960e01b815281516001600160a01b0390811660048301526020830151811660248301526040830151166044820152606090910151606482015260848101929092529091908390839060a490829084905af1908115614e365750614e25575050565b614e2f82916132e2565b61029e5750565b513d84823e3d90fd5b614e4b909591956132e2565b9338614dab565b5050505050565b909192506080813d8211614ec4575b81614e7560809383613360565b8101031261132c57606090855192614e8c8461330c565b614e95826134a7565b8452614ea28183016134a7565b90840152614eb18682016134a7565b8684015201516060820152903880614d4d565b3d9150614e68565b82809450819392503d8311614f01575b614ee68183613360565b8101031261132c57906080614efb84936134a7565b90614cfe565b503d614edc565b9190820391821161338f57565b614f20600a54615328565b90929150614f2f600b54615328565b6040516370a0823160e01b80825230600483015296919493506020926001600160a01b039284836024817f0000000000000000000000003bd359c1119da7da1d913d1c4d2b7c461115433a88165afa8015610f7c578593600091615023575b50614f9d9291612e5e91613382565b9660246040518094819382523060048301527f0000000000000000000000008498312a6b3cbd158bf0c93abdcf29e6e4f55081165afa918215610f7c57600092614ff2575b50506135849291612e5e91613382565b81819392933d831161501c575b6150098183613360565b8101031261029e57505181612e5e614fe2565b503d614fff565b91929382813d8311615050575b61503a8183613360565b8101031261029e57505184929190614f9d614f8e565b503d615030565b90614f2f61506783600a5461506f565b92915093600b545b91909180156152ad576001600160a01b03615088613b48565b1690604093845192839263133f757160e31b845260048401528260246101809586935afa92831561526b576000958692879488938997615276575b50507362a7d1fa1e67000e70e2a7ed59a99e39d8265da1825163986cfba360e01b998a825260020b60048201526020958682602481865af491821561526b57600092615234575b5084519a8b5260020b60048b0152858a602481855af4928315615229578798999a6000989798946151e2575b50845163c72e160b60e01b81526001600160a01b039182166004820152918116602483015290921660448301526001600160801b03909416606482015293509091819084908180608481015b03915af49283156145fa576151bc93600093928492916151c0575b50506151b4906001600160801b0380931690613382565b941690613382565b9092565b6151b494506151db9250803d10613a7d57613a6b8183613360565b923861519d565b8093959750889196989492943d8311615222575b6152008183613360565b8101031261029e575091849391615219889796946134a7565b92879695615136565b503d6151f6565b84513d6000823e3d90fd5b90918782813d8311615264575b61524b8183613360565b8101031261029e575061525d906134a7565b903861510a565b503d615241565b85513d6000823e3d90fd5b93509350945095506152949250803d10613603576135ec8183613360565b98509950505095509892509050969293919438806150c3565b506000915081908190565b801561360a576001600160a01b036152ce613b48565b169060405191829163133f757160e31b835260048301528160246101809485935afa918215610f7c5760009261530357505090565b6153199250803d10613603576135ec8183613360565b50505050965050505050505090565b9081156154e7576001600160a01b039182615341613b48565b1690604093845192839263133f757160e31b845260048401528260246101809586935afa92831561526b5760009586928794889389976154a9575b505060c06004918351928380926339db007960e21b82527f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b2165afa908115614a5b57600091615486575b507362a7d1fa1e67000e70e2a7ed59a99e39d8265da1825163986cfba360e01b998a825260020b60048201526020958682602481865af491821561526b57600092615234575084519a8b5260020b60048b0152858a602481855af4928315615229578798999a6000989798946151e25750845163c72e160b60e01b81526001600160a01b039182166004820152918116602483015290921660448301526001600160801b0390941660648201529350909181908490818060848101615182565b61549e915060c03d8111610544576105308183613360565b5050505050386153c6565b91965091945060c09750600493506154cd9250803d10613603576135ec8183613360565b9a509b985050509794509a9250905098949593969161537c565b6000915081908190565b6040516339db007960e21b815260c0816004817f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b26001600160a01b03165afa8015610f7c576000918291615574575b50156155495790565b60405162461bcd60e51b815260206004820152600360248201526214125360ea1b6044820152606490fd5b905061558e915060c03d8111610544576105308183613360565b94505050509038615540565b60029190910b81526001600160801b039190911660208201526001600160a01b0391821660408201529116606082015260800190565b60405163ef01df4f60e01b81526001600160a01b0391906020907f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b284168282600481845afa918215610f7c576000926156d3575b506040516330ea6ca760e11b8152948216600486015260248501529281816044817362a7d1fa1e67000e70e2a7ed59a99e39d8265da15af4908115610f7c5760009161569e575b50156156745750565b6064906040519062461bcd60e51b82526004820152600360248201526204144560ec1b6044820152fd5b908282813d83116156cc575b6156b48183613360565b8101031261029e57506156c6906136b5565b3861566b565b503d6156aa565b90918382813d8311615703575b6156ea8183613360565b8101031261029e57506156fc906134a7565b9038615624565b503d6156e0565b95919360c0959198979360e0880199885260018060a01b038096166020890152604088015260020b6060870152608086015260a085015216910152565b6001600160a01b039081169182156159285781169283156158d7576000838152806020526040928382205483811061588457839086845283602052038483205585825283822083815401905585857fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60208751878152a37f0000000000000000000000008b4e859058fab262ba216d64a92a83ad231fe8b293600460c0600254938351928380926339db007960e21b82528a165afa90811561587a579161584d939185937f3aba9fb77678760b537dcec639050ddd940cae3a850b34b8fc37f5c47d40d6ff9897969491615852575b5061584084615057565b939092519788978861570a565b0390a3565b905061586d91935060c03d8111610544576105308183613360565b5050505092909238615836565b82513d86823e3d90fd5b845162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608490fd5b60405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608490fd5b60405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608490fdfea164736f6c6343000814000a

Block Transaction Gas Used Reward
view all blocks produced

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
[ Download: CSV Export  ]
[ 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.