ETH Price: $3,374.12 (+5.24%)
Gas: 0.07 GWei

Contract

0xeD48f13B3525B39B0b8E1a9FF95a78e77ab8e33f

Overview

ETH Balance

Linea Mainnet LogoLinea Mainnet LogoLinea Mainnet Logo0 ETH

ETH Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

> 10 Internal Transactions found.

Latest 25 internal transactions (View All)

Parent Transaction Hash Block From To
149935522025-01-24 19:10:2016 secs ago1737745820
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
149935512025-01-24 19:10:1818 secs ago1737745818
0xeD48f13B...77ab8e33f
0 ETH
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
ClPool

Compiler Version
v0.7.6+commit.7338295f

Optimization Enabled:
Yes with 530 runs

Other Settings:
default evmVersion
File 1 of 37 : ClPool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;

import "./interfaces/IClPool.sol";

import "./libraries/LowGasSafeMath.sol";
import "./libraries/SafeCast.sol";
import "./libraries/Tick.sol";
import "./libraries/TickBitmap.sol";
import "./libraries/Position.sol";
import "./libraries/Oracle.sol";
import "./libraries/States.sol";
import "./libraries/ProtocolActions.sol";

import "./libraries/FullMath.sol";
import "./libraries/FixedPoint128.sol";
import "./libraries/TransferHelper.sol";
import "./libraries/TickMath.sol";
import "./libraries/LiquidityMath.sol";
import "./libraries/SqrtPriceMath.sol";
import "./libraries/SwapMath.sol";

import "./interfaces/IClPoolDeployer.sol";
import "./interfaces/IClPoolFactory.sol";
import "./interfaces/callback/IRamsesV2MintCallback.sol";
import "./interfaces/callback/IRamsesV2SwapCallback.sol";
import "./interfaces/callback/IRamsesV2FlashCallback.sol";

import "./../interfaces/IVotingEscrow.sol";
import "./../interfaces/IVoter.sol";

contract ClPool is IClPool {
    using LowGasSafeMath for uint256;
    using LowGasSafeMath for int256;
    using SafeCast for uint256;
    using SafeCast for int256;
    using TickBitmap for mapping(int16 => uint256);

    // To avoid stack-too-deep
    struct TokenAmounts {
        uint256 token0;
        uint256 token1;
    }

    // To avoid stack-too-deep
    struct TokenAmountInts {
        int256 token0;
        int256 token1;
    }

    bytes32 STATES_SLOT = keccak256("states.storage");

    /// @dev Mutually exclusive reentrancy protection into the pool to/from a method. This method also prevents entrance
    /// to a function before the pool is initialized. The reentrancy guard is required throughout the contract because
    /// we use balance checks to determine the payment status of interactions such as mint, swap and flash.
    modifier lock() {
        _lock();
        _;
        _unlock();
    }

    // separated for code size
    function _lock() internal {
        States.PoolStates storage states = States.getStorage();

        require(states.slot0.unlocked, "LOK");
        states.slot0.unlocked = false;
    }

    function _unlock() internal {
        States.getStorage().slot0.unlocked = true;
    }

    /// @dev Prevents calling a function from anyone except the address returned by IRamsesV2Factory#feeCollector()
    modifier onlyFeeCollector() {
        States.PoolStates storage states = States.getStorage();

        require(msg.sender == IClPoolFactory(states.factory).feeCollector());
        _;
    }

    /// @dev Advances period if it's a new week
    modifier advancePeriod() {
        _advancePeriod();
        _;
    }

    /// @dev Advances period if it's a new week
    function _advancePeriod() public override {
        States.PoolStates storage states = States.getStorage();

        // if in new week, record lastTick for previous period
        // also record secondsPerLiquidityCumulativeX128 for the start of the new period
        uint256 _lastPeriod = states.lastPeriod;
        if ((States._blockTimestamp() / 1 weeks) != _lastPeriod) {
            Slot0 memory _slot0 = states.slot0;
            uint256 period = States._blockTimestamp() / 1 weeks;
            states.lastPeriod = period;

            // start new period in obervations
            (
                uint160 secondsPerLiquidityCumulativeX128,
                uint160 secondsPerBoostedLiquidityCumulativeX128,
                uint32 boostedInRange
            ) = Oracle.newPeriod(
                    states.observations,
                    _slot0.observationIndex,
                    period
                );

            // reset boostedLiquidity
            states.boostedLiquidity = 0;

            // record last tick and secondsPerLiquidityCumulativeX128 for old period
            states.periods[_lastPeriod].lastTick = _slot0.tick;
            states
                .periods[_lastPeriod]
                .endSecondsPerLiquidityPeriodX128 = secondsPerLiquidityCumulativeX128;
            states
                .periods[_lastPeriod]
                .endSecondsPerBoostedLiquidityPeriodX128 = secondsPerBoostedLiquidityCumulativeX128;
            states.periods[_lastPeriod].boostedInRange = boostedInRange;

            // record start tick and secondsPerLiquidityCumulativeX128 for new period
            PeriodInfo memory _newPeriod;

            _newPeriod.previousPeriod = uint32(_lastPeriod);
            _newPeriod.startTick = _slot0.tick;
            states.periods[period] = _newPeriod;
        }
    }

    /// @dev initilializes
    function initialize(
        address _factory,
        address _nfpManager,
        address _votingEscrow,
        address _voter,
        address _token0,
        address _token1,
        uint24 _fee,
        int24 _tickSpacing
    ) public override {
        States.PoolStates storage states = States.getStorage();

        require(!states.initialized);

        states.factory = _factory;
        states.nfpManager = _nfpManager;
        states.votingEscrow = _votingEscrow;
        states.voter = _voter;
        states.token0 = _token0;
        states.token1 = _token1;
        states.fee = _fee;
        states.initialFee = _fee;
        states.tickSpacing = _tickSpacing;

        states.maxLiquidityPerTick = Tick.tickSpacingToMaxLiquidityPerTick(
            _tickSpacing
        );

        states.initialized = true;
    }

    /// View Functions

    // Get the address of the factory that created the pool
    /// @inheritdoc IClPoolImmutables
    function factory() external view override returns (address) {
        return States.getStorage().factory;
    }

    // Get the address of the NFP manager for the pool
    /// @inheritdoc IClPoolImmutables
    function nfpManager() external view override returns (address) {
        return States.getStorage().nfpManager;
    }

    /// @inheritdoc IClPoolImmutables
    function votingEscrow() external view override returns (address) {
        return States.getStorage().votingEscrow;
    }

    // Get the address of the voter contract for the pool
    /// @inheritdoc IClPoolImmutables
    function voter() external view override returns (address) {
        return States.getStorage().voter;
    }

    // Get the address of the first token in the pool
    /// @inheritdoc IClPoolImmutables
    function token0() external view override returns (address) {
        return States.getStorage().token0;
    }

    // Get the address of the second token in the pool
    /// @inheritdoc IClPoolImmutables
    function token1() external view override returns (address) {
        return States.getStorage().token1;
    }

    // Get the fee charged by the pool for swaps and liquidity provision
    /// @inheritdoc IClPoolImmutables
    function fee() external view override returns (uint24) {
        return States.getStorage().initialFee;
    }

    /// @inheritdoc IClPoolImmutables
    function currentFee() external view override returns (uint24) {
        return States.getStorage().fee;
    }

    // Get the tick spacing for the pool
    /// @inheritdoc IClPoolImmutables
    function tickSpacing() external view override returns (int24) {
        return States.getStorage().tickSpacing;
    }

    // Get the maximum amount of liquidity that can be added to the pool at each tick
    /// @inheritdoc IClPoolImmutables
    function maxLiquidityPerTick() external view override returns (uint128) {
        return States.getStorage().maxLiquidityPerTick;
    }

    /// @inheritdoc IClPoolState
    function readStorage(
        bytes32[] calldata slots
    ) external view override returns (bytes32[] memory returnData) {
        uint256 slotsLength = slots.length;
        returnData = new bytes32[](slotsLength);

        for (uint256 i = 0; i < slotsLength; ++i) {
            bytes32 slot = slots[i];
            bytes32 _returnData;
            assembly {
                _returnData := sload(slot)
            }
            returnData[i] = _returnData;
        }
    }

    // Get the Slot0 struct for the pool
    /// @inheritdoc IClPoolState
    function slot0()
        external
        view
        override
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        )
    {
        Slot0 memory _slot0 = States.getStorage().slot0;

        return (
            _slot0.sqrtPriceX96,
            _slot0.tick,
            _slot0.observationIndex,
            _slot0.observationCardinality,
            _slot0.observationCardinalityNext,
            _slot0.feeProtocol,
            _slot0.unlocked
        );
    }

    // Get the PeriodInfo struct for a given period in the pool
    /// @inheritdoc IClPoolState
    function periods(
        uint256 period
    )
        external
        view
        override
        returns (
            uint32 previousPeriod,
            int24 startTick,
            int24 lastTick,
            uint160 endSecondsPerLiquidityPeriodX128,
            uint160 endSecondsPerBoostedLiquidityPeriodX128,
            uint32 boostedInRange
        )
    {
        PeriodInfo memory periodData = States.getStorage().periods[period];
        return (
            periodData.previousPeriod,
            periodData.startTick,
            periodData.lastTick,
            periodData.endSecondsPerLiquidityPeriodX128,
            periodData.endSecondsPerBoostedLiquidityPeriodX128,
            periodData.boostedInRange
        );
    }

    // Get the index of the last period in the pool
    /// @inheritdoc IClPoolState
    function lastPeriod() external view override returns (uint256) {
        return States.getStorage().lastPeriod;
    }

    // Get the accumulated fee growth for the first token in the pool
    /// @inheritdoc IClPoolState
    function feeGrowthGlobal0X128() external view override returns (uint256) {
        return States.getStorage().feeGrowthGlobal0X128;
    }

    // Get the accumulated fee growth for the second token in the pool
    /// @inheritdoc IClPoolState
    function feeGrowthGlobal1X128() external view override returns (uint256) {
        return States.getStorage().feeGrowthGlobal1X128;
    }

    // Get the protocol fees accumulated by the pool
    /// @inheritdoc IClPoolState
    function protocolFees() external view override returns (uint128, uint128) {
        ProtocolFees memory protocolFeesData = States.getStorage().protocolFees;
        return (protocolFeesData.token0, protocolFeesData.token1);
    }

    // Get the total liquidity of the pool
    /// @inheritdoc IClPoolState
    function liquidity() external view override returns (uint128) {
        return States.getStorage().liquidity;
    }

    // Get the boosted liquidity of the pool
    /// @inheritdoc IClPoolState
    function boostedLiquidity() external view override returns (uint128) {
        return States.getStorage().boostedLiquidity;
    }

    // Get the ticks of the pool
    /// @inheritdoc IClPoolState
    function ticks(
        int24 tick
    )
        external
        view
        override
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint128 boostedLiquidityGross,
            int128 boostedLiquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        )
    {
        uint256 period = States._blockTimestamp() / 1 weeks;
        TickInfo storage tickData = States.getStorage()._ticks[tick];
        liquidityGross = tickData.liquidityGross;
        liquidityNet = tickData.liquidityNet;
        boostedLiquidityGross = tickData.boostedLiquidityGross[period];
        boostedLiquidityNet = tickData.boostedLiquidityNet[period];
        feeGrowthOutside0X128 = tickData.feeGrowthOutside0X128;
        feeGrowthOutside1X128 = tickData.feeGrowthOutside1X128;
        tickCumulativeOutside = tickData.tickCumulativeOutside;
        secondsPerLiquidityOutsideX128 = tickData
            .secondsPerLiquidityOutsideX128;
        secondsOutside = tickData.secondsOutside;
        initialized = tickData.initialized;
    }

    // Get the tick bitmap of the pool
    /// @inheritdoc IClPoolState
    function tickBitmap(int16 tick) external view override returns (uint256) {
        return States.getStorage().tickBitmap[tick];
    }

    // Get information about a specific position in the pool
    /// @inheritdoc IClPoolState
    function positions(
        bytes32 key
    )
        external
        view
        override
        returns (uint128, uint256, uint256, uint128, uint128, uint256)
    {
        PositionInfo memory positionData = States.getStorage().positions[key];
        return (
            positionData.liquidity,
            positionData.feeGrowthInside0LastX128,
            positionData.feeGrowthInside1LastX128,
            positionData.tokensOwed0,
            positionData.tokensOwed1,
            positionData.attachedVeNftTokenId
        );
    }

    // Get the boost information for a specific period
    /// @inheritdoc IClPoolState
    function boostInfos(
        uint256 period
    )
        external
        view
        override
        returns (uint128 totalBoostAmount, int128 totalVeNftAmount)
    {
        PeriodBoostInfo storage periodBoostInfoData = States
            .getStorage()
            .boostInfos[period];
        return (
            periodBoostInfoData.totalBoostAmount,
            periodBoostInfoData.totalVeNftAmount
        );
    }

    // Get the boost information for a specific position at a period
    /// @inheritdoc IClPoolState
    function boostInfos(
        uint256 period,
        bytes32 key
    )
        external
        view
        override
        returns (
            uint128 boostAmount,
            int128 veNftAmount,
            int256 secondsDebtX96,
            int256 boostedSecondsDebtX96
        )
    {
        BoostInfo memory boostInfo = States
            .getStorage()
            .boostInfos[period]
            .positions[key];
        return (
            boostInfo.boostAmount,
            boostInfo.veNftAmount,
            boostInfo.secondsDebtX96,
            boostInfo.boostedSecondsDebtX96
        );
    }

    // Get the period seconds debt of a specific position
    /// @inheritdoc IClPoolState
    function positionPeriodDebt(
        uint256 period,
        address owner,
        uint256 index,
        int24 tickLower,
        int24 tickUpper
    )
        external
        view
        override
        returns (int256 secondsDebtX96, int256 boostedSecondsDebtX96)
    {
        States.PoolStates storage states = States.getStorage();
        BoostInfo storage position = Position.get(
            states.boostInfos[period],
            owner,
            index,
            tickLower,
            tickUpper
        );

        secondsDebtX96 = position.secondsDebtX96;
        boostedSecondsDebtX96 = position.boostedSecondsDebtX96;

        return (secondsDebtX96, boostedSecondsDebtX96);
    }

    // Get the period seconds in range of a specific position
    /// @inheritdoc IClPoolState
    function positionPeriodSecondsInRange(
        uint256 period,
        address owner,
        uint256 index,
        int24 tickLower,
        int24 tickUpper
    )
        external
        view
        override
        returns (
            uint256 periodSecondsInsideX96,
            uint256 periodBoostedSecondsInsideX96
        )
    {
        (periodSecondsInsideX96, periodBoostedSecondsInsideX96) = Position
            .positionPeriodSecondsInRange(
                Position.PositionPeriodSecondsInRangeParams({
                    period: period,
                    owner: owner,
                    index: index,
                    tickLower: tickLower,
                    tickUpper: tickUpper
                })
            );

        return (periodSecondsInsideX96, periodBoostedSecondsInsideX96);
    }

    // Get the observations recorded by the pool
    /// @inheritdoc IClPoolState
    function observations(
        uint256 index
    )
        external
        view
        override
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized,
            uint160 secondsPerBoostedLiquidityPeriodX128
        )
    {
        Observation memory observationData = States.getStorage().observations[
            index
        ];
        return (
            observationData.blockTimestamp,
            observationData.tickCumulative,
            observationData.secondsPerLiquidityCumulativeX128,
            observationData.initialized,
            observationData.secondsPerBoostedLiquidityPeriodX128
        );
    }

    /// @inheritdoc IClPoolDerivedState
    function snapshotCumulativesInside(
        int24 tickLower,
        int24 tickUpper
    )
        external
        view
        override
        returns (
            int56 tickCumulativeInside,
            uint160 secondsPerLiquidityInsideX128,
            uint160 secondsPerBoostedLiquidityInsideX128,
            uint32 secondsInside
        )
    {
        // check ticks
        require(tickLower < tickUpper, "TLU");
        require(tickLower >= TickMath.MIN_TICK, "TLM");
        require(tickUpper <= TickMath.MAX_TICK, "TUM");

        return Oracle.snapshotCumulativesInside(tickLower, tickUpper);
    }

    /// @inheritdoc IClPoolDerivedState
    function periodCumulativesInside(
        uint32 period,
        int24 tickLower,
        int24 tickUpper
    )
        external
        view
        override
        returns (
            uint160 secondsPerLiquidityInsideX128,
            uint160 secondsPerBoostedLiquidityInsideX128
        )
    {
        return Oracle.periodCumulativesInside(period, tickLower, tickUpper);
    }

    /// @inheritdoc IClPoolDerivedState
    function observe(
        uint32[] calldata secondsAgos
    )
        external
        view
        override
        returns (
            int56[] memory tickCumulatives,
            uint160[] memory secondsPerLiquidityCumulativeX128s,
            uint160[] memory secondsPerBoostedLiquidityPeriodX128s
        )
    {
        States.PoolStates storage states = States.getStorage();

        return
            Oracle.observe(
                states.observations,
                States._blockTimestamp(),
                secondsAgos,
                states.slot0.tick,
                states.slot0.observationIndex,
                states.liquidity,
                states.boostedLiquidity,
                states.slot0.observationCardinality
            );
    }

    /// @inheritdoc IClPoolActions
    function increaseObservationCardinalityNext(
        uint16 observationCardinalityNext
    ) external override lock {
        States.PoolStates storage states = States.getStorage();

        uint16 observationCardinalityNextOld = states
            .slot0
            .observationCardinalityNext; // for the event
        uint16 observationCardinalityNextNew = Oracle.grow(
            states.observations,
            observationCardinalityNextOld,
            observationCardinalityNext
        );
        states.slot0.observationCardinalityNext = observationCardinalityNextNew;
        if (observationCardinalityNextOld != observationCardinalityNextNew)
            emit IncreaseObservationCardinalityNext(
                observationCardinalityNextOld,
                observationCardinalityNextNew
            );
    }

    /// @inheritdoc IClPoolActions
    /// @dev not locked because it initializes unlocked
    function initialize(uint160 sqrtPriceX96) external override {
        States.PoolStates storage states = States.getStorage();

        require(states.slot0.sqrtPriceX96 == 0, "AI");

        int24 tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96);

        (uint16 cardinality, uint16 cardinalityNext) = Oracle.initialize(
            states.observations,
            0
        );

        _advancePeriod();

        states.slot0 = Slot0({
            sqrtPriceX96: sqrtPriceX96,
            tick: tick,
            observationIndex: 0,
            observationCardinality: cardinality,
            observationCardinalityNext: cardinalityNext,
            feeProtocol: 0,
            unlocked: true
        });

        emit Initialize(sqrtPriceX96, tick);
    }

    /// @inheritdoc IClPoolActions
    /// @dev lock and advancePeriod is applied indirectly in mint()
    function mint(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    ) external override returns (uint256 amount0, uint256 amount1) {
        return
            mint(
                recipient,
                0,
                tickLower,
                tickUpper,
                amount,
                type(uint256).max,
                data
            );
    }

    /// @inheritdoc IClPoolActions
    function mint(
        address recipient,
        uint256 index,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        uint256 veNftTokenId,
        bytes calldata data
    )
        public
        override
        lock
        advancePeriod
        returns (uint256 amount0, uint256 amount1)
    {
        require(amount > 0);
        if (veNftTokenId != type(uint256).max) {
            require(recipient == msg.sender);
        }

        TokenAmountInts memory amountInt;
        (, amountInt.token0, amountInt.token1) = Position._modifyPosition(
            Position.ModifyPositionParams({
                owner: recipient,
                index: index,
                tickLower: tickLower,
                tickUpper: tickUpper,
                liquidityDelta: int256(amount).toInt128(),
                veNftTokenId: veNftTokenId
            })
        );

        amount0 = uint256(amountInt.token0);
        amount1 = uint256(amountInt.token1);

        uint256 balance0Before;
        uint256 balance1Before;
        if (amount0 > 0) balance0Before = States.balance0();
        if (amount1 > 0) balance1Before = States.balance1();
        IRamsesV2MintCallback(msg.sender).ramsesV2MintCallback(
            amount0,
            amount1,
            data
        );
        if (amount0 > 0)
            require(balance0Before.add(amount0) <= States.balance0(), "M0");
        if (amount1 > 0)
            require(balance1Before.add(amount1) <= States.balance1(), "M1");

        emit Mint(
            msg.sender,
            recipient,
            tickLower,
            tickUpper,
            amount,
            amount0,
            amount1
        );
    }

    /// @inheritdoc IClPoolActions
    function collect(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external override returns (uint128 amount0, uint128 amount1) {
        return
            collect(
                recipient,
                0,
                tickLower,
                tickUpper,
                amount0Requested,
                amount1Requested
            );
    }

    /// @inheritdoc IClPoolActions
    function collect(
        address recipient,
        uint256 index,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) public override lock returns (uint128 amount0, uint128 amount1) {
        States.PoolStates storage states = States.getStorage();

        // we don't need to checkTicks here, because invalid positions will never have non-zero tokensOwed{0,1}
        PositionInfo storage position = Position.get(
            states.positions,
            msg.sender,
            index,
            tickLower,
            tickUpper
        );

        amount0 = amount0Requested > position.tokensOwed0
            ? position.tokensOwed0
            : amount0Requested;
        amount1 = amount1Requested > position.tokensOwed1
            ? position.tokensOwed1
            : amount1Requested;

        if (amount0 > 0) {
            position.tokensOwed0 -= amount0;
            TransferHelper.safeTransfer(states.token0, recipient, amount0);
        }
        if (amount1 > 0) {
            position.tokensOwed1 -= amount1;
            TransferHelper.safeTransfer(states.token1, recipient, amount1);
        }

        emit Collect(
            msg.sender,
            recipient,
            tickLower,
            tickUpper,
            amount0,
            amount1
        );
    }

    /// @inheritdoc IClPoolActions
    /// @dev lock and advancePeriod is applied indirectly in burn()
    function burn(
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    ) external override returns (uint256 amount0, uint256 amount1) {
        return burn(0, tickLower, tickUpper, amount, type(uint256).max);
    }

    /// @dev lock and advancePeriod is applied indirectly in burn()
    /// @inheritdoc IClPoolActions
    function burn(
        uint256 index,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    ) external override returns (uint256 amount0, uint256 amount1) {
        return burn(index, tickLower, tickUpper, amount, type(uint256).max);
    }

    /// @inheritdoc IClPoolActions
    function burn(
        uint256 index,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        uint256 veNftTokenId
    )
        public
        override
        lock
        advancePeriod
        returns (uint256 amount0, uint256 amount1)
    {
        (
            PositionInfo storage position,
            int256 amount0Int,
            int256 amount1Int
        ) = Position._modifyPosition(
                Position.ModifyPositionParams({
                    owner: msg.sender,
                    index: index,
                    tickLower: tickLower,
                    tickUpper: tickUpper,
                    liquidityDelta: -int256(amount).toInt128(),
                    veNftTokenId: veNftTokenId
                })
            );

        amount0 = uint256(-amount0Int);
        amount1 = uint256(-amount1Int);

        if (amount0 > 0 || amount1 > 0) {
            (position.tokensOwed0, position.tokensOwed1) = (
                position.tokensOwed0 + uint128(amount0),
                position.tokensOwed1 + uint128(amount1)
            );
        }

        emit Burn(msg.sender, tickLower, tickUpper, amount, amount0, amount1);
    }

    struct SwapCache {
        // the protocol fee for the input token
        uint8 feeProtocol;
        // liquidity at the beginning of the swap
        uint128 liquidityStart;
        // boosted liquidity at the beginning of the swap
        uint128 boostedLiquidityStart;
        // the timestamp of the current block
        uint32 blockTimestamp;
        // the current value of the tick accumulator, computed only if we cross an initialized tick
        int56 tickCumulative;
        // the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick
        uint160 secondsPerLiquidityCumulativeX128;
        // the current value of seconds per boosted liquidity accumulator, computed only if we cross an initialized tick
        uint160 secondsPerBoostedLiquidityPeriodX128;
        // whether we've computed and cached the above two accumulators
        bool computedLatestObservation;
        // whether the swap has exactInput
        bool exactInput;
        // timestamp of the previous period
        uint32 previousPeriod;
    }

    // the top level state of the swap, the results of which are recorded in storage at the end
    struct SwapState {
        // the amount remaining to be swapped in/out of the input/output asset
        int256 amountSpecifiedRemaining;
        // the amount already swapped out/in of the output/input asset
        int256 amountCalculated;
        // current sqrt(price)
        uint160 sqrtPriceX96;
        // the tick associated with the current price
        int24 tick;
        // the global fee growth of the input token
        uint256 feeGrowthGlobalX128;
        // amount of input token paid as protocol fee
        uint128 protocolFee;
        // the current liquidity in range
        uint128 liquidity;
        // the current boosted liquidity in range
        uint128 boostedLiquidity;
        // seconds per liquidity at the end of the previous period
        uint256 endSecondsPerLiquidityPeriodX128;
        // seconds per boosted liquidity at the end of the previous period
        uint256 endSecondsPerBoostedLiquidityPeriodX128;
        // starting tick of the current period
        int24 periodStartTick;
    }

    struct StepComputations {
        // the price at the beginning of the step
        uint160 sqrtPriceStartX96;
        // the next tick to swap to from the current tick in the swap direction
        int24 tickNext;
        // whether tickNext is initialized or not
        bool initialized;
        // sqrt(price) for the next tick (1/0)
        uint160 sqrtPriceNextX96;
        // how much is being swapped in in this step
        uint256 amountIn;
        // how much is being swapped out
        uint256 amountOut;
        // how much fee is being paid in
        uint256 feeAmount;
    }

    struct CrossCache {
        int128 liquidityNet;
        int128 boostedLiquidityNet;
        uint256 feeGrowthGlobal0X128;
        uint256 feeGrowthGlobal1X128;
    }

    /// @inheritdoc IClPoolActions
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external override advancePeriod returns (int256 amount0, int256 amount1) {
        States.PoolStates storage states = States.getStorage();

        require(amountSpecified != 0, "AS");

        Slot0 memory slot0Start = states.slot0;

        require(slot0Start.unlocked, "LOK");
        require(
            zeroForOne
                ? sqrtPriceLimitX96 < slot0Start.sqrtPriceX96 &&
                    sqrtPriceLimitX96 > TickMath.MIN_SQRT_RATIO
                : sqrtPriceLimitX96 > slot0Start.sqrtPriceX96 &&
                    sqrtPriceLimitX96 < TickMath.MAX_SQRT_RATIO,
            "SPL"
        );

        states.slot0.unlocked = false;

        SwapCache memory cache;
        SwapState memory state;

        {
            uint256 period = States._blockTimestamp() / 1 weeks;

            cache = SwapCache({
                liquidityStart: states.liquidity,
                boostedLiquidityStart: states.boostedLiquidity,
                blockTimestamp: States._blockTimestamp(),
                feeProtocol: slot0Start.feeProtocol,
                secondsPerLiquidityCumulativeX128: 0,
                secondsPerBoostedLiquidityPeriodX128: 0,
                tickCumulative: 0,
                computedLatestObservation: false,
                exactInput: amountSpecified > 0,
                previousPeriod: states.periods[period].previousPeriod
            });

            state = SwapState({
                amountSpecifiedRemaining: amountSpecified,
                amountCalculated: 0,
                sqrtPriceX96: slot0Start.sqrtPriceX96,
                tick: slot0Start.tick,
                feeGrowthGlobalX128: zeroForOne
                    ? states.feeGrowthGlobal0X128
                    : states.feeGrowthGlobal1X128,
                protocolFee: 0,
                liquidity: cache.liquidityStart,
                boostedLiquidity: cache.boostedLiquidityStart,
                endSecondsPerLiquidityPeriodX128: states
                    .periods[cache.previousPeriod]
                    .endSecondsPerLiquidityPeriodX128,
                endSecondsPerBoostedLiquidityPeriodX128: states
                    .periods[cache.previousPeriod]
                    .endSecondsPerBoostedLiquidityPeriodX128,
                periodStartTick: states.periods[period].startTick
            });
        }

        // continue swapping as long as we haven't used the entire input/output and haven't reached the price limit
        while (
            state.amountSpecifiedRemaining != 0 &&
            state.sqrtPriceX96 != sqrtPriceLimitX96
        ) {
            StepComputations memory step;

            step.sqrtPriceStartX96 = state.sqrtPriceX96;

            (step.tickNext, step.initialized) = TickBitmap
                .nextInitializedTickWithinOneWord(
                    states.tickBitmap,
                    state.tick,
                    states.tickSpacing,
                    zeroForOne
                );

            // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds
            if (step.tickNext < TickMath.MIN_TICK) {
                step.tickNext = TickMath.MIN_TICK;
            } else if (step.tickNext > TickMath.MAX_TICK) {
                step.tickNext = TickMath.MAX_TICK;
            }

            // get the price for the next tick
            step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);

            // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted
            (
                state.sqrtPriceX96,
                step.amountIn,
                step.amountOut,
                step.feeAmount
            ) = SwapMath.computeSwapStep(
                state.sqrtPriceX96,
                (
                    zeroForOne
                        ? step.sqrtPriceNextX96 < sqrtPriceLimitX96
                        : step.sqrtPriceNextX96 > sqrtPriceLimitX96
                )
                    ? sqrtPriceLimitX96
                    : step.sqrtPriceNextX96,
                state.liquidity,
                state.amountSpecifiedRemaining,
                states.fee
            );

            if (cache.exactInput) {
                state.amountSpecifiedRemaining -= (step.amountIn +
                    step.feeAmount).toInt256();
                state.amountCalculated = state.amountCalculated.sub(
                    step.amountOut.toInt256()
                );
            } else {
                state.amountSpecifiedRemaining += step.amountOut.toInt256();
                state.amountCalculated = state.amountCalculated.add(
                    (step.amountIn + step.feeAmount).toInt256()
                );
            }

            // if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee
            if (cache.feeProtocol > 0) {
                uint256 delta = (step.feeAmount * cache.feeProtocol) / 100;
                step.feeAmount -= delta;
                state.protocolFee += uint128(delta);
            }

            // update global fee tracker
            if (state.liquidity > 0)
                state.feeGrowthGlobalX128 += FullMath.mulDiv(
                    step.feeAmount,
                    FixedPoint128.Q128,
                    state.liquidity
                );

            // shift tick if we reached the next price
            if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {
                // if the tick is initialized, run the tick transition
                if (step.initialized) {
                    // check for the placeholder value, which we replace with the actual value the first time the swap
                    // crosses an initialized tick
                    if (!cache.computedLatestObservation) {
                        (
                            cache.tickCumulative,
                            cache.secondsPerLiquidityCumulativeX128,
                            cache.secondsPerBoostedLiquidityPeriodX128
                        ) = Oracle.observeSingle(
                            states.observations,
                            cache.blockTimestamp,
                            0,
                            slot0Start.tick,
                            slot0Start.observationIndex,
                            cache.liquidityStart,
                            cache.boostedLiquidityStart,
                            slot0Start.observationCardinality
                        );
                        cache.computedLatestObservation = true;
                    }
                    CrossCache memory crossCache; // stack too deep

                    if (zeroForOne) {
                        // yes, one uses state and the other uses states, this is not a typo
                        crossCache.feeGrowthGlobal0X128 = state
                            .feeGrowthGlobalX128;
                        crossCache.feeGrowthGlobal1X128 = states
                            .feeGrowthGlobal1X128;
                    } else {
                        crossCache.feeGrowthGlobal0X128 = states
                            .feeGrowthGlobal0X128;
                        crossCache.feeGrowthGlobal1X128 = state
                            .feeGrowthGlobalX128;
                    }
                    (
                        crossCache.liquidityNet,
                        crossCache.boostedLiquidityNet
                    ) = Tick.cross(
                        states._ticks,
                        Tick.CrossParams(
                            step.tickNext,
                            crossCache.feeGrowthGlobal0X128,
                            crossCache.feeGrowthGlobal1X128,
                            cache.secondsPerLiquidityCumulativeX128,
                            cache.secondsPerBoostedLiquidityPeriodX128,
                            state.endSecondsPerLiquidityPeriodX128,
                            state.endSecondsPerBoostedLiquidityPeriodX128,
                            state.periodStartTick,
                            cache.tickCumulative,
                            cache.blockTimestamp
                        )
                    );
                    // if we're moving leftward, we interpret liquidityNet as the opposite sign
                    // safe because liquidityNet cannot be type(int128).min
                    if (zeroForOne) {
                        crossCache.liquidityNet = -crossCache.liquidityNet;
                        crossCache.boostedLiquidityNet = -crossCache
                            .boostedLiquidityNet;
                    }

                    state.liquidity = LiquidityMath.addDelta(
                        state.liquidity,
                        crossCache.liquidityNet
                    );
                    state.boostedLiquidity = LiquidityMath.addDelta(
                        state.boostedLiquidity,
                        crossCache.boostedLiquidityNet
                    );
                }

                state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;
            } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {
                // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved
                state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);
            }
        }

        // update tick and write an oracle entry if the tick change
        if (state.tick != slot0Start.tick) {
            (uint16 observationIndex, uint16 observationCardinality) = Oracle
                .write(
                    states.observations,
                    slot0Start.observationIndex,
                    cache.blockTimestamp,
                    slot0Start.tick,
                    cache.liquidityStart,
                    cache.boostedLiquidityStart,
                    slot0Start.observationCardinality,
                    slot0Start.observationCardinalityNext
                );
            (
                states.slot0.sqrtPriceX96,
                states.slot0.tick,
                states.slot0.observationIndex,
                states.slot0.observationCardinality
            ) = (
                state.sqrtPriceX96,
                state.tick,
                observationIndex,
                observationCardinality
            );
        } else {
            // otherwise just update the price
            states.slot0.sqrtPriceX96 = state.sqrtPriceX96;
        }

        // update liquidity if it changed
        if (cache.liquidityStart != state.liquidity) {
            states.liquidity = state.liquidity;
        }

        // update if boosted changed, need a separate check because boosted can change without liquidity changing
        if (cache.boostedLiquidityStart != state.boostedLiquidity) {
            states.boostedLiquidity = state.boostedLiquidity;
        }

        // update fee growth global and, if necessary, protocol fees
        // overflow is acceptable, protocol has to withdraw before it hits type(uint128).max fees
        if (zeroForOne) {
            states.feeGrowthGlobal0X128 = state.feeGrowthGlobalX128;
            if (state.protocolFee > 0)
                states.protocolFees.token0 += state.protocolFee;
        } else {
            states.feeGrowthGlobal1X128 = state.feeGrowthGlobalX128;
            if (state.protocolFee > 0)
                states.protocolFees.token1 += state.protocolFee;
        }

        (amount0, amount1) = zeroForOne == cache.exactInput
            ? (
                amountSpecified - state.amountSpecifiedRemaining,
                state.amountCalculated
            )
            : (
                state.amountCalculated,
                amountSpecified - state.amountSpecifiedRemaining
            );

        // do the transfers and collect payment
        if (zeroForOne) {
            if (amount1 < 0)
                TransferHelper.safeTransfer(
                    states.token1,
                    recipient,
                    uint256(-amount1)
                );

            uint256 balance0Before = States.balance0();
            IRamsesV2SwapCallback(msg.sender).ramsesV2SwapCallback(
                amount0,
                amount1,
                data
            );
            require(
                balance0Before.add(uint256(amount0)) <= States.balance0(),
                "IIA"
            );
        } else {
            if (amount0 < 0)
                TransferHelper.safeTransfer(
                    states.token0,
                    recipient,
                    uint256(-amount0)
                );

            uint256 balance1Before = States.balance1();
            IRamsesV2SwapCallback(msg.sender).ramsesV2SwapCallback(
                amount0,
                amount1,
                data
            );
            require(
                balance1Before.add(uint256(amount1)) <= States.balance1(),
                "IIA"
            );
        }

        emit Swap(
            msg.sender,
            recipient,
            amount0,
            amount1,
            state.sqrtPriceX96,
            state.liquidity,
            state.tick
        );
        states.slot0.unlocked = true;
    }

    /// @inheritdoc IClPoolActions
    function flash(
        address recipient,
        uint256 amount0,
        uint256 amount1,
        bytes calldata data
    ) external override lock {
        States.PoolStates storage states = States.getStorage();

        uint128 _liquidity = states.liquidity;
        require(_liquidity > 0, "L");

        uint256 fee0 = FullMath.mulDivRoundingUp(amount0, states.fee, 1e6);
        uint256 fee1 = FullMath.mulDivRoundingUp(amount1, states.fee, 1e6);
        uint256 balance0Before = States.balance0();
        uint256 balance1Before = States.balance1();

        if (amount0 > 0)
            TransferHelper.safeTransfer(states.token0, recipient, amount0);
        if (amount1 > 0)
            TransferHelper.safeTransfer(states.token1, recipient, amount1);

        IRamsesV2FlashCallback(msg.sender).ramsesV2FlashCallback(
            fee0,
            fee1,
            data
        );

        TokenAmounts memory balanceAfter;
        balanceAfter.token0 = States.balance0();
        balanceAfter.token1 = States.balance1();

        require(balance0Before.add(fee0) <= balanceAfter.token0);
        require(balance1Before.add(fee1) <= balanceAfter.token1, "F1");

        // sub is safe because we know balanceAfter is gt balanceBefore by at least fee
        TokenAmounts memory paid;
        paid.token0 = balanceAfter.token0 - balance0Before;
        paid.token1 = balanceAfter.token1 - balance1Before;

        if (paid.token0 > 0) {
            uint8 feeProtocol0 = states.slot0.feeProtocol;
            uint256 fees0 = feeProtocol0 == 0
                ? 0
                : (paid.token0 * feeProtocol0) / 100;
            if (uint128(fees0) > 0)
                states.protocolFees.token0 += uint128(fees0);
            states.feeGrowthGlobal0X128 += FullMath.mulDiv(
                paid.token0 - fees0,
                FixedPoint128.Q128,
                _liquidity
            );
        }
        if (paid.token1 > 0) {
            uint8 feeProtocol1 = states.slot0.feeProtocol;
            uint256 fees1 = feeProtocol1 == 0
                ? 0
                : (paid.token1 * feeProtocol1) / 100;
            if (uint128(fees1) > 0)
                states.protocolFees.token1 += uint128(fees1);
            states.feeGrowthGlobal1X128 += FullMath.mulDiv(
                paid.token1 - fees1,
                FixedPoint128.Q128,
                _liquidity
            );
        }

        emit Flash(
            msg.sender,
            recipient,
            amount0,
            amount1,
            paid.token0,
            paid.token1
        );
    }

    /// @inheritdoc IClPoolOwnerActions
    function setFeeProtocol() external override lock {
        ProtocolActions.setFeeProtocol();
    }

    /// @inheritdoc IClPoolOwnerActions
    function collectProtocol(
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    )
        external
        override
        lock
        onlyFeeCollector
        returns (uint128 amount0, uint128 amount1)
    {
        return
            ProtocolActions.collectProtocol(
                recipient,
                amount0Requested,
                amount1Requested
            );
    }

    function setFee(uint24 _fee) external override {
        ProtocolActions.setFee(_fee);
    }
}

File 2 of 37 : Math.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @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, so we distribute
        return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
    }
}

File 3 of 37 : IVoter.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6 || ^0.8.13;
pragma abicoder v2;

interface IVoter {
    function _ve() external view returns (address);

    function governor() external view returns (address);

    function emergencyCouncil() external view returns (address);

    function attachTokenToGauge(uint256 _tokenId, address account) external;

    function detachTokenFromGauge(uint256 _tokenId, address account) external;

    function emitDeposit(
        uint256 _tokenId,
        address account,
        uint256 amount
    ) external;

    function emitWithdraw(
        uint256 _tokenId,
        address account,
        uint256 amount
    ) external;

    function isWhitelisted(address token) external view returns (bool);

    function notifyRewardAmount(uint256 amount) external;

    function distribute(address _gauge) external;

    function gauges(address pool) external view returns (address);

    function feeDistributors(address gauge) external view returns (address);

    function gaugefactory() external view returns (address);

    function feeDistributorFactory() external view returns (address);

    function minter() external view returns (address);

    function factory() external view returns (address);

    function length() external view returns (uint256);

    function pools(uint256) external view returns (address);

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

    function setXRatio(uint256 _xRatio) external;

    function setPoolXRatio(
        address[] calldata _gauges,
        uint256[] calldata _xRaRatios
    ) external;

    function resetGaugeXRatio(address[] calldata _gauges) external;

    function whitelist(address _token) external;

    function forbid(address _token, bool _status) external;

    function whitelistOperator() external view returns (address);

    function gaugeXRatio(address gauge) external view returns (uint256);

    function isGauge(address gauge) external view returns (bool);

    function killGauge(address _gauge) external;

    function reviveGauge(address _gauge) external;

    function stale(uint256 _tokenID) external view returns (bool);

    function poolForGauge(address gauge) external view returns (address pool);

    function recoverFees(
        address[] calldata fees,
        address[][] calldata tokens
    ) external;

    function designateStale(uint256 _tokenId, bool _status) external;

    function base() external view returns (address);

    function xToken() external view returns (address);

    function addClGaugeReward(address gauge, address reward) external;

    function removeClGaugeReward(address gauge, address reward) external;

    function addInitialRewardPerGauge(address _gauge, address token) external;

    function clawBackUnusedEmissions(address[] calldata _gauges) external;

    function customGaugeForPool(
        address pool
    ) external view returns (address customGauge);
}

File 4 of 37 : IVotingEscrow.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6 || ^0.8.13;
pragma abicoder v2;

interface IVotingEscrow {
    struct Point {
        int128 bias;
        int128 slope; // # -dweight / dt
        uint256 ts;
        uint256 blk; // block
    }

    struct LockedBalance {
        int128 amount;
        uint256 end;
    }

    function emissionsToken() external view returns (address);

    function team() external returns (address);

    function epoch() external view returns (uint256);

    function pointHistory(uint256 loc) external view returns (Point memory);

    function userPointHistory(
        uint256 tokenId,
        uint256 loc
    ) external view returns (Point memory);

    function userPointEpoch(uint256 tokenId) external view returns (uint256);

    function ownerOf(uint256) external view returns (address);

    function isApprovedOrOwner(address, uint256) external view returns (bool);

    function transferFrom(address, address, uint256) external;

    function voting(uint256 tokenId) external;

    function abstain(uint256 tokenId) external;

    function attach(uint256 tokenId) external;

    function detach(uint256 tokenId) external;

    function checkpoint() external;

    function depositFor(uint256 tokenId, uint256 value) external;

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

    function balanceOfNFT(uint256) external view returns (uint256);

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

    function totalSupply() external view returns (uint256);

    function locked__end(uint256) external view returns (uint256);

    function balanceOf(address) external view returns (uint256);

    function tokenOfOwnerByIndex(
        address,
        uint256
    ) external view returns (uint256);

    function increaseUnlockTime(uint256 tokenID, uint256 duration) external;

    function locked(
        uint256 tokenID
    ) external view returns (uint256 amount, uint256 unlockTime);

    function increaseAmount(uint256 _tokenId, uint256 _value) external;

    function isDelegate(
        address _operator,
        uint256 _tokenId
    ) external view returns (bool);
}

File 5 of 37 : LiquidityAmounts.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

File 6 of 37 : IRamsesV2FlashCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Callback for IClPoolActions#flash
/// @notice Any contract that calls IClPoolActions#flash must implement this interface
interface IRamsesV2FlashCallback {
    /// @notice Called to `msg.sender` after transferring to the recipient from IClPool#flash.
    /// @dev In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts.
    /// The caller of this method must be checked to be a ClPool deployed by the canonical ClPoolFactory.
    /// @param fee0 The fee amount in token0 due to the pool by the end of the flash
    /// @param fee1 The fee amount in token1 due to the pool by the end of the flash
    /// @param data Any data passed through by the caller via the IClPoolActions#flash call
    function ramsesV2FlashCallback(
        uint256 fee0,
        uint256 fee1,
        bytes calldata data
    ) external;
}

File 7 of 37 : IRamsesV2MintCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Callback for IClPoolActions#mint
/// @notice Any contract that calls IClPoolActions#mint must implement this interface
interface IRamsesV2MintCallback {
    /// @notice Called to `msg.sender` after minting liquidity to a position from IClPool#mint.
    /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
    /// The caller of this method must be checked to be a ClPool deployed by the canonical ClPoolFactory.
    /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
    /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
    /// @param data Any data passed through by the caller via the IClPoolActions#mint call
    function ramsesV2MintCallback(
        uint256 amount0Owed,
        uint256 amount1Owed,
        bytes calldata data
    ) external;
}

File 8 of 37 : IRamsesV2SwapCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Callback for IClPoolActions#swap
/// @notice Any contract that calls IClPoolActions#swap must implement this interface
interface IRamsesV2SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via IClPool#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 ClPool deployed by the canonical ClPoolFactory.
    /// 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 IClPoolActions#swap call
    function ramsesV2SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

File 9 of 37 : IClPool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import "./pool/IClPoolImmutables.sol";
import "./pool/IClPoolState.sol";
import "./pool/IClPoolDerivedState.sol";
import "./pool/IClPoolActions.sol";
import "./pool/IClPoolOwnerActions.sol";
import "./pool/IClPoolEvents.sol";

/// @title The interface for a CL V2 Pool
/// @notice A CL pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IClPool is
    IClPoolImmutables,
    IClPoolState,
    IClPoolDerivedState,
    IClPoolActions,
    IClPoolOwnerActions,
    IClPoolEvents
{
    /// @notice Initializes a pool with parameters provided
    function initialize(
        address _factory,
        address _nfpManager,
        address _veRam,
        address _voter,
        address _token0,
        address _token1,
        uint24 _fee,
        int24 _tickSpacing
    ) external;

    function _advancePeriod() external;
}

File 10 of 37 : IClPoolDeployer.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title An interface for a contract that is capable of deploying CL Pools
/// @notice A contract that constructs a pool must implement this to pass arguments to the pool
/// @dev The store and retrieve method of supplying constructor arguments for CREATE2 isn't needed anymore
/// since we now use a beacon pattern
interface IClPoolDeployer {

}

File 11 of 37 : IClPoolFactory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma abicoder v2;

/// @title The interface for the CL Factory
/// @notice The CL Factory facilitates creation of CL pools and control over the protocol fees
interface IClPoolFactory {
    /// @notice Emitted when the owner of the factory is changed
    /// @param oldOwner The owner before the owner was changed
    /// @param newOwner The owner after the owner was changed
    event OwnerChanged(address indexed oldOwner, address indexed newOwner);

    /// @notice Emitted when a pool is created
    /// @param token0 The first token of the pool by address sort order
    /// @param token1 The second token of the pool by address sort order
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks
    /// @param pool The address of the created pool
    event PoolCreated(
        address indexed token0,
        address indexed token1,
        uint24 indexed fee,
        int24 tickSpacing,
        address pool
    );

    /// @notice Emitted when a new fee amount is enabled for pool creation via the factory
    /// @param fee The enabled fee, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
    event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);

    /// @notice Emitted when pairs implementation is changed
    /// @param oldImplementation The previous implementation
    /// @param newImplementation The new implementation
    event ImplementationChanged(
        address indexed oldImplementation,
        address indexed newImplementation
    );

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

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

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

    /// @notice Emitted when the feeSetter of the factory is changed
    /// @param oldSetter The feeSetter before the setter was changed
    /// @param newSetter The feeSetter after the setter was changed
    event FeeSetterChanged(
        address indexed oldSetter,
        address indexed newSetter
    );

    /// @notice Returns the current owner of the factory
    /// @dev Can be changed by the current owner via setOwner
    /// @return The address of the factory owner
    function owner() external view returns (address);

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

    /// @notice Returns the votingEscrow address
    function votingEscrow() external view returns (address);

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

    /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
    /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
    /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
    /// @return The tick spacing
    function feeAmountTickSpacing(uint24 fee) external view returns (int24);

    /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
    /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
    /// @param tokenA The contract address of either token0 or token1
    /// @param tokenB The contract address of the other token
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @return pool The pool address
    function getPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) external view returns (address pool);

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

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

    /// @notice Updates the owner of the factory
    /// @dev Must be called by the current owner
    /// @param _owner The new owner of the factory
    function setOwner(address _owner) external;

    /// @notice Enables a fee amount with the given tickSpacing
    /// @dev Fee amounts may never be removed once enabled
    /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
    /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
    function enableFeeAmount(uint24 fee, int24 tickSpacing) external;

    /// @notice returns the default protocol fee.
    function feeProtocol() external view returns (uint8);

    /// @notice returns the protocol fee for both tokens of a pool.
    function poolFeeProtocol(address pool) external view returns (uint8);

    /// @notice Sets the default protocol's % share of the fees
    /// @param _feeProtocol new default protocol fee for token0 and token1
    function setFeeProtocol(uint8 _feeProtocol) external;

    /// @notice Sets the fee collector address
    /// @param _feeCollector the fee collector address
    function setFeeCollector(address _feeCollector) external;

    function setFeeSetter(address _newFeeSetter) external;

    function setFee(address _pool, uint24 _fee) external;

    /// @notice Sets the default protocol's % share of the fees
    /// @param pool the pool address
    /// @param feeProtocol new protocol fee for the pool for token0 and token1
    function setPoolFeeProtocol(address pool, uint8 feeProtocol) external;
}

File 12 of 37 : IERC20Minimal.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Minimal ERC20 interface for RA
/// @notice Contains a subset of the full ERC20 interface that is used in RA V2
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);
}

File 13 of 37 : IClPoolActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

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

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

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

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

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

    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position at index 0
    /// @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 tickLower The lower tick of the position for which to burn liquidity
    /// @param tickUpper The upper tick of the position for which to burn liquidity
    /// @param amount How much liquidity to burn
    /// @return amount0 The amount of token0 sent to the recipient
    /// @return amount1 The amount of token1 sent to the recipient
    function burn(
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    ) external returns (uint256 amount0, uint256 amount1);

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

    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
    /// @dev Fees must be collected separately via a call to #collect
    /// @param index The index for which the liquidity will be burned
    /// @param tickLower The lower tick of the position for which to burn liquidity
    /// @param tickUpper The upper tick of the position for which to burn liquidity
    /// @param amount How much liquidity to burn
    /// @param veNFTTokenId The veNFT Token Id to attach
    /// @return amount0 The amount of token0 sent to the recipient
    /// @return amount1 The amount of token1 sent to the recipient
    function burn(
        uint256 index,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        uint256 veNFTTokenId
    ) 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 IRamsesV2SwapCallback#ramsesV2SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

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

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

File 14 of 37 : IClPoolDerivedState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

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

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

    /// @notice Returns the seconds per liquidity and seconds inside a tick range for a period
    /// @param tickLower The lower tick of the range
    /// @param tickUpper The upper tick of the range
    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
    /// @return secondsPerBoostedLiquidityInsideX128 The snapshot of seconds per boosted liquidity for the range
    function periodCumulativesInside(
        uint32 period,
        int24 tickLower,
        int24 tickUpper
    )
        external
        view
        returns (
            uint160 secondsPerLiquidityInsideX128,
            uint160 secondsPerBoostedLiquidityInsideX128
        );
}

File 15 of 37 : IClPoolEvents.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

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

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

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

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

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

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

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

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

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

File 16 of 37 : IClPoolImmutables.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

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

    /// @notice The contract that manages CL NFPs, which must adhere to the INonfungiblePositionManager interface
    /// @return The contract address
    function nfpManager() external view returns (address);

    /// @notice The contract that manages veNFTs, which must adhere to the IVotingEscrow interface
    /// @return The contract address
    function votingEscrow() external view returns (address);

    /// @notice The contract that manages RA votes, which must adhere to the IVoter interface
    /// @return The contract address
    function voter() external view returns (address);

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

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

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

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

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

    /// @notice returns the current fee set for the pool
    function currentFee() external view returns (uint24);
}

File 17 of 37 : IClPoolOwnerActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IClPoolOwnerActions {
    /// @notice Set the protocol's % share of the fees
    /// @dev Fees start at 50%, with 5% increments
    function setFeeProtocol() external;

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

    function setFee(uint24 _fee) external;
}

File 18 of 37 : IClPoolState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IClPoolState {
    /// @notice reads arbitrary storage slots and returns the bytes
    /// @param slots The slots to read from
    /// @return returnData The data read from the slots
    function readStorage(
        bytes32[] calldata slots
    ) external view returns (bytes32[] memory returnData);

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

    /// @notice Returns the last tick of a given period
    /// @param period The period in question
    /// @return previousPeriod The period before current period
    /// @dev this is because there might be periods without trades
    ///  startTick The start tick of the period
    ///  lastTick The last tick of the period, if the period is finished
    ///  endSecondsPerLiquidityPeriodX128 Seconds per liquidity at period's end
    ///  endSecondsPerBoostedLiquidityPeriodX128 Seconds per boosted liquidity at period's end
    function periods(
        uint256 period
    )
        external
        view
        returns (
            uint32 previousPeriod,
            int24 startTick,
            int24 lastTick,
            uint160 endSecondsPerLiquidityCumulativeX128,
            uint160 endSecondsPerBoostedLiquidityCumulativeX128,
            uint32 boostedInRange
        );

    /// @notice The last period where a trade or liquidity change happened
    function lastPeriod() 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
    function feeGrowthGlobal0X128() external view returns (uint256);

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

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

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

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

    /// @notice Get the boost information for a specific position at a period
    /// @return boostAmount the amount of boost this position has for this period,
    /// veNFTAmount the amount of veNFTs attached to this position for this period,
    /// secondsDebtX96 used to account for changes in the deposit amount during the period
    /// boostedSecondsDebtX96 used to account for changes in the boostAmount and veNFT locked during the period,
    function boostInfos(
        uint256 period,
        bytes32 key
    )
        external
        view
        returns (
            uint128 boostAmount,
            int128 veNFTAmount,
            int256 secondsDebtX96,
            int256 boostedSecondsDebtX96
        );

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

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

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

    /// @notice Returns a period's total boost amount and total veNFT attached
    /// @param period Period timestamp
    /// @return totalBoostAmount The total amount of boost this period has,
    /// @return totalVeNFTAmount The total amount of veNFTs attached to this period
    function boostInfos(
        uint256 period
    ) external view returns (uint128 totalBoostAmount, int128 totalVeNFTAmount);

    /// @notice Get the period seconds debt of a specific position
    /// @param period the period number
    /// @param recipient recipient address
    /// @param index position index
    /// @param tickLower lower bound of range
    /// @param tickUpper upper bound of range
    /// @return secondsDebtX96 seconds the position was not in range for the period
    /// @return boostedSecondsDebtX96 boosted seconds the period
    function positionPeriodDebt(
        uint256 period,
        address recipient,
        uint256 index,
        int24 tickLower,
        int24 tickUpper
    )
        external
        view
        returns (int256 secondsDebtX96, int256 boostedSecondsDebtX96);

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

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

File 19 of 37 : BitMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
library BitMath {
    /// @notice Returns the index of the most significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @dev The function satisfies the property:
    ///     x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)
    /// @param x the value for which to compute the most significant bit, must be greater than 0
    /// @return r the index of the most significant bit
    function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        if (x >= 0x100000000000000000000000000000000) {
            x >>= 128;
            r += 128;
        }
        if (x >= 0x10000000000000000) {
            x >>= 64;
            r += 64;
        }
        if (x >= 0x100000000) {
            x >>= 32;
            r += 32;
        }
        if (x >= 0x10000) {
            x >>= 16;
            r += 16;
        }
        if (x >= 0x100) {
            x >>= 8;
            r += 8;
        }
        if (x >= 0x10) {
            x >>= 4;
            r += 4;
        }
        if (x >= 0x4) {
            x >>= 2;
            r += 2;
        }
        if (x >= 0x2) r += 1;
    }

    /// @notice Returns the index of the least significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @dev The function satisfies the property:
    ///     (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)
    /// @param x the value for which to compute the least significant bit, must be greater than 0
    /// @return r the index of the least significant bit
    function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        r = 255;
        if (x & type(uint128).max > 0) {
            r -= 128;
        } else {
            x >>= 128;
        }
        if (x & type(uint64).max > 0) {
            r -= 64;
        } else {
            x >>= 64;
        }
        if (x & type(uint32).max > 0) {
            r -= 32;
        } else {
            x >>= 32;
        }
        if (x & type(uint16).max > 0) {
            r -= 16;
        } else {
            x >>= 16;
        }
        if (x & type(uint8).max > 0) {
            r -= 8;
        } else {
            x >>= 8;
        }
        if (x & 0xf > 0) {
            r -= 4;
        } else {
            x >>= 4;
        }
        if (x & 0x3 > 0) {
            r -= 2;
        } else {
            x >>= 2;
        }
        if (x & 0x1 > 0) r -= 1;
    }
}

File 20 of 37 : FixedPoint128.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;

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

File 21 of 37 : FixedPoint32.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;

/// @title FixedPoint32
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint32 {
    uint8 internal constant RESOLUTION = 32;
    uint256 internal constant Q32 = 0x100000000;
}

File 22 of 37 : FixedPoint96.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;

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

File 23 of 37 : FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0 <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) {
        // 512-bit multiply [prod1 prod0] = a * b
        // Compute the product mod 2**256 and mod 2**256 - 1
        // then use the Chinese Remainder Theorem to reconstruct
        // the 512 bit result. The result is stored in two 256
        // variables such that product = prod1 * 2**256 + prod0
        uint256 prod0; // Least significant 256 bits of the product
        uint256 prod1; // Most significant 256 bits of the product
        assembly {
            let mm := mulmod(a, b, not(0))
            prod0 := mul(a, b)
            prod1 := sub(sub(mm, prod0), lt(mm, prod0))
        }

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

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

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

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

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

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

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

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

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

File 24 of 37 : LiquidityMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './FullMath.sol';
import './SafeCast.sol';
import '@openzeppelin-3.4.2/contracts/math/Math.sol';

/// @title Math library for liquidity
library LiquidityMath {
    /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
    /// @param x The liquidity before change
    /// @param y The delta by which liquidity should be changed
    /// @return z The liquidity delta
    function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
        if (y < 0) {
            require((z = x - uint128(-y)) < x, 'LS');
        } else {
            require((z = x + uint128(y)) >= x, 'LA');
        }
    }

    /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
    /// @param x The liquidity before change
    /// @param y The delta by which liquidity should be changed
    /// @return z The liquidity delta
    function addDelta256(uint256 x, int256 y) internal pure returns (uint256 z) {
        if (y < 0) {
            require((z = x - uint256(-y)) < x, 'LS');
        } else {
            require((z = x + uint256(y)) >= x, 'LA');
        }
    }

    function calculateBoostedLiquidity(
        uint128 liquidity,
        int128 veNftAmount,
        int128 totalVeNftAmount
    ) internal pure returns (uint256 veNftRatio, uint128 boostedLiquidity) {
        veNftRatio = FullMath.mulDiv(
            uint256(veNftAmount),
            1.5e18,
            totalVeNftAmount != 0 ? uint256(totalVeNftAmount) : 1
        );

        // users acheive full boost if their veRA is >=10% of the total veRA attached to the pool
        // full boost is 1x original + 1.5x boost
        //uint256 boostRatio = Math.min(veNftRatio * 10, 1.5e18); // veNftAmount and totalVeNftAmount can't go below 0
        uint256 boostRatio = 1.5e18;

        boostedLiquidity = SafeCast.toUint128(FullMath.mulDiv(liquidity, boostRatio, 1e18));
    }
}

File 25 of 37 : LowGasSafeMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.0;

/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
library LowGasSafeMath {
    /// @notice Returns x + y, reverts if sum overflows uint256
    /// @param x The augend
    /// @param y The addend
    /// @return z The sum of x and y
    function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
        require((z = x + y) >= x);
    }

    /// @notice Returns x - y, reverts if underflows
    /// @param x The minuend
    /// @param y The subtrahend
    /// @return z The difference of x and y
    function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        require((z = x - y) <= x);
    }

    /// @notice Returns x * y, reverts if overflows
    /// @param x The multiplicand
    /// @param y The multiplier
    /// @return z The product of x and y
    function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        require(x == 0 || (z = x * y) / x == y);
    }

    /// @notice Returns x + y, reverts if overflows or underflows
    /// @param x The augend
    /// @param y The addend
    /// @return z The sum of x and y
    function add(int256 x, int256 y) internal pure returns (int256 z) {
        require((z = x + y) >= x == (y >= 0));
    }

    /// @notice Returns x - y, reverts if overflows or underflows
    /// @param x The minuend
    /// @param y The subtrahend
    /// @return z The difference of x and y
    function sub(int256 x, int256 y) internal pure returns (int256 z) {
        require((z = x - y) <= x == (y >= 0));
    }
}

File 26 of 37 : Oracle.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.8.0;

import './Tick.sol';
import './States.sol';

/// @title Oracle
/// @notice Provides price and liquidity data useful for a wide variety of system designs
/// @dev Instances of stored oracle data, "observations", are collected in the oracle array
/// Every pool is initialized with an oracle array length of 1. Anyone can pay the SSTOREs to increase the
/// maximum length of the oracle array. New slots will be added when the array is fully populated.
/// Observations are overwritten when the full length of the oracle array is populated.
/// The most recent observation is available, independent of the length of the oracle array, by passing 0 to observe()
library Oracle {
    /// @notice Transforms a previous observation into a new observation, given the passage of time and the current tick and liquidity values
    /// @dev blockTimestamp _must_ be chronologically equal to or greater than last.blockTimestamp, safe for 0 or 1 overflows
    /// @param last The specified observation to be transformed
    /// @param blockTimestamp The timestamp of the new observation
    /// @param tick The active tick at the time of the new observation
    /// @param liquidity The total in-range liquidity at the time of the new observation
    /// @return Observation The newly populated observation
    function transform(
        Observation memory last,
        uint32 blockTimestamp,
        int24 tick,
        uint128 liquidity,
        uint128 boostedLiquidity
    ) internal pure returns (Observation memory) {
        uint32 delta = blockTimestamp - last.blockTimestamp;
        return
            Observation({
                blockTimestamp: blockTimestamp,
                tickCumulative: last.tickCumulative + int56(tick) * delta,
                secondsPerLiquidityCumulativeX128: last.secondsPerLiquidityCumulativeX128 +
                    ((uint160(delta) << 128) / (liquidity > 0 ? liquidity : 1)),
                secondsPerBoostedLiquidityPeriodX128: last.secondsPerBoostedLiquidityPeriodX128 +
                    ((uint160(delta) << 128) / (boostedLiquidity > 0 ? boostedLiquidity : 1)),
                initialized: true,
                boostedInRange: boostedLiquidity > 0 ? last.boostedInRange + delta : last.boostedInRange
            });
    }

    /// @notice Initialize the oracle array by writing the first slot. Called once for the lifecycle of the observations array
    /// @param self The stored oracle array
    /// @param time The time of the oracle initialization, via block.timestamp truncated to uint32
    /// @return cardinality The number of populated elements in the oracle array
    /// @return cardinalityNext The new length of the oracle array, independent of population
    function initialize(
        Observation[65535] storage self,
        uint32 time
    ) external returns (uint16 cardinality, uint16 cardinalityNext) {
        self[0] = Observation({
            blockTimestamp: time,
            tickCumulative: 0,
            secondsPerLiquidityCumulativeX128: 0,
            secondsPerBoostedLiquidityPeriodX128: 0,
            initialized: true,
            boostedInRange: 0
        });
        return (1, 1);
    }

    /// @notice Writes an oracle observation to the array
    /// @dev Writable at most once per block. Index represents the most recently written element. cardinality and index must be tracked publicly.
    /// If the index is at the end of the allowable array length (according to cardinality), and the next cardinality
    /// is greater than the current one, cardinality may be increased. This restriction is created to preserve ordering.
    /// @param self The stored oracle array
    /// @param index The index of the observation that was most recently written to the observations array
    /// @param blockTimestamp The timestamp of the new observation
    /// @param tick The active tick at the time of the new observation
    /// @param liquidity The total in-range liquidity at the time of the new observation
    /// @param cardinality The number of populated elements in the oracle array
    /// @param cardinalityNext The new length of the oracle array, independent of population
    /// @return indexUpdated The new index of the most recently written element in the oracle array
    /// @return cardinalityUpdated The new cardinality of the oracle array
    function write(
        Observation[65535] storage self,
        uint16 index,
        uint32 blockTimestamp,
        int24 tick,
        uint128 liquidity,
        uint128 boostedLiquidity,
        uint16 cardinality,
        uint16 cardinalityNext
    ) external returns (uint16 indexUpdated, uint16 cardinalityUpdated) {
        Observation memory last = self[index];

        // early return if we've already written an observation this block
        if (last.blockTimestamp == blockTimestamp) return (index, cardinality);

        // if the conditions are right, we can bump the cardinality
        if (cardinalityNext > cardinality && index == (cardinality - 1)) {
            cardinalityUpdated = cardinalityNext;
        } else {
            cardinalityUpdated = cardinality;
        }

        indexUpdated = (index + 1) % cardinalityUpdated;
        self[indexUpdated] = transform(last, blockTimestamp, tick, liquidity, boostedLiquidity);
    }

    /// @notice Prepares the oracle array to store up to `next` observations
    /// @param self The stored oracle array
    /// @param current The current next cardinality of the oracle array
    /// @param next The proposed next cardinality which will be populated in the oracle array
    /// @return next The next cardinality which will be populated in the oracle array
    function grow(Observation[65535] storage self, uint16 current, uint16 next) external returns (uint16) {
        require(current > 0, 'I');
        // no-op if the passed next value isn't greater than the current next value
        if (next <= current) return current;
        // store in each slot to prevent fresh SSTOREs in swaps
        // this data will not be used because the initialized boolean is still false
        for (uint16 i = current; i < next; i++) self[i].blockTimestamp = 1;
        return next;
    }

    /// @notice comparator for 32-bit timestamps
    /// @dev safe for 0 or 1 overflows, a and b _must_ be chronologically before or equal to time
    /// @param time A timestamp truncated to 32 bits
    /// @param a A comparison timestamp from which to determine the relative position of `time`
    /// @param b From which to determine the relative position of `time`
    /// @return bool Whether `a` is chronologically <= `b`
    function lte(uint32 time, uint32 a, uint32 b) internal pure returns (bool) {
        // if there hasn't been overflow, no need to adjust
        if (a <= time && b <= time) return a <= b;

        uint256 aAdjusted = a > time ? a : a + 2 ** 32;
        uint256 bAdjusted = b > time ? b : b + 2 ** 32;

        return aAdjusted <= bAdjusted;
    }

    /// @notice Fetches the observations beforeOrAt and atOrAfter a target, i.e. where [beforeOrAt, atOrAfter] is satisfied.
    /// The result may be the same observation, or adjacent observations.
    /// @dev The answer must be contained in the array, used when the target is located within the stored observation
    /// boundaries: older than the most recent observation and younger, or the same age as, the oldest observation
    /// @param self The stored oracle array
    /// @param time The current block.timestamp
    /// @param target The timestamp at which the reserved observation should be for
    /// @param index The index of the observation that was most recently written to the observations array
    /// @param cardinality The number of populated elements in the oracle array
    /// @return beforeOrAt The observation recorded before, or at, the target
    /// @return atOrAfter The observation recorded at, or after, the target
    function binarySearch(
        Observation[65535] storage self,
        uint32 time,
        uint32 target,
        uint16 index,
        uint16 cardinality
    ) internal view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
        uint256 l = (index + 1) % cardinality; // oldest observation
        uint256 r = l + cardinality - 1; // newest observation
        uint256 i;
        while (true) {
            i = (l + r) / 2;

            beforeOrAt = self[i % cardinality];

            // we've landed on an uninitialized tick, keep searching higher (more recently)
            if (!beforeOrAt.initialized) {
                l = i + 1;
                continue;
            }

            atOrAfter = self[(i + 1) % cardinality];

            bool targetAtOrAfter = lte(time, beforeOrAt.blockTimestamp, target);

            // check if we've found the answer!
            if (targetAtOrAfter && lte(time, target, atOrAfter.blockTimestamp)) break;

            if (!targetAtOrAfter) r = i - 1;
            else l = i + 1;
        }
    }

    /// @notice Fetches the observations beforeOrAt and atOrAfter a given target, i.e. where [beforeOrAt, atOrAfter] is satisfied
    /// @dev Assumes there is at least 1 initialized observation.
    /// Used by observeSingle() to compute the counterfactual accumulator values as of a given block timestamp.
    /// @param self The stored oracle array
    /// @param time The current block.timestamp
    /// @param target The timestamp at which the reserved observation should be for
    /// @param tick The active tick at the time of the returned or simulated observation
    /// @param index The index of the observation that was most recently written to the observations array
    /// @param liquidity The total pool liquidity at the time of the call
    /// @param cardinality The number of populated elements in the oracle array
    /// @return beforeOrAt The observation which occurred at, or before, the given timestamp
    /// @return atOrAfter The observation which occurred at, or after, the given timestamp
    function getSurroundingObservations(
        Observation[65535] storage self,
        uint32 time,
        uint32 target,
        int24 tick,
        uint16 index,
        uint128 liquidity,
        uint128 boostedLiquidity,
        uint16 cardinality
    ) internal view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
        // optimistically set before to the newest observation
        beforeOrAt = self[index];

        // if the target is chronologically at or after the newest observation, we can early return
        if (lte(time, beforeOrAt.blockTimestamp, target)) {
            if (beforeOrAt.blockTimestamp == target) {
                // if newest observation equals target, we're in the same block, so we can ignore atOrAfter
                return (beforeOrAt, atOrAfter);
            } else {
                // otherwise, we need to transform
                return (beforeOrAt, transform(beforeOrAt, target, tick, liquidity, boostedLiquidity));
            }
        }

        // now, set before to the oldest observation
        beforeOrAt = self[(index + 1) % cardinality];
        if (!beforeOrAt.initialized) beforeOrAt = self[0];

        // ensure that the target is chronologically at or after the oldest observation
        require(lte(time, beforeOrAt.blockTimestamp, target), 'OLD');

        // if we've reached this point, we have to binary search
        return binarySearch(self, time, target, index, cardinality);
    }

    /// @dev Reverts if an observation at or before the desired observation timestamp does not exist.
    /// 0 may be passed as `secondsAgo' to return the current cumulative values.
    /// If called with a timestamp falling between two observations, returns the counterfactual accumulator values
    /// at exactly the timestamp between the two observations.
    /// @param self The stored oracle array
    /// @param time The current block timestamp
    /// @param secondsAgo The amount of time to look back, in seconds, at which point to return an observation
    /// @param tick The current tick
    /// @param index The index of the observation that was most recently written to the observations array
    /// @param liquidity The current in-range pool liquidity
    /// @param cardinality The number of populated elements in the oracle array
    /// @return tickCumulative The tick * time elapsed since the pool was first initialized, as of `secondsAgo`
    /// @return secondsPerLiquidityCumulativeX128 The time elapsed / max(1, liquidity) since the pool was first initialized, as of `secondsAgo`
    function observeSingle(
        Observation[65535] storage self,
        uint32 time,
        uint32 secondsAgo,
        int24 tick,
        uint16 index,
        uint128 liquidity,
        uint128 boostedLiquidity,
        uint16 cardinality
    )
        public
        view
        returns (
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            uint160 periodSecondsPerBoostedLiquidityX128
        )
    {
        if (secondsAgo == 0) {
            Observation memory last = self[index];
            if (last.blockTimestamp != time) {
                last = transform(last, time, tick, liquidity, boostedLiquidity);
            }
            return (
                last.tickCumulative,
                last.secondsPerLiquidityCumulativeX128,
                last.secondsPerBoostedLiquidityPeriodX128
            );
        }

        uint32 target = time - secondsAgo;

        (Observation memory beforeOrAt, Observation memory atOrAfter) = getSurroundingObservations(
            self,
            time,
            target,
            tick,
            index,
            liquidity,
            boostedLiquidity,
            cardinality
        );

        if (target == beforeOrAt.blockTimestamp) {
            // we're at the left boundary
            return (
                beforeOrAt.tickCumulative,
                beforeOrAt.secondsPerLiquidityCumulativeX128,
                beforeOrAt.secondsPerBoostedLiquidityPeriodX128
            );
        } else if (target == atOrAfter.blockTimestamp) {
            // we're at the right boundary
            return (
                atOrAfter.tickCumulative,
                atOrAfter.secondsPerLiquidityCumulativeX128,
                atOrAfter.secondsPerBoostedLiquidityPeriodX128
            );
        } else {
            // we're in the middle
            uint32 observationTimeDelta = atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp;
            uint32 targetDelta = target - beforeOrAt.blockTimestamp;
            return (
                beforeOrAt.tickCumulative +
                    ((atOrAfter.tickCumulative - beforeOrAt.tickCumulative) / observationTimeDelta) *
                    targetDelta,
                beforeOrAt.secondsPerLiquidityCumulativeX128 +
                    uint160(
                        (uint256(
                            atOrAfter.secondsPerLiquidityCumulativeX128 - beforeOrAt.secondsPerLiquidityCumulativeX128
                        ) * targetDelta) / observationTimeDelta
                    ),
                beforeOrAt.secondsPerBoostedLiquidityPeriodX128 +
                    uint160(
                        (uint256(
                            atOrAfter.secondsPerBoostedLiquidityPeriodX128 -
                                beforeOrAt.secondsPerBoostedLiquidityPeriodX128
                        ) * targetDelta) / observationTimeDelta
                    )
            );
        }
    }

    /// @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 observation
    /// @param self The stored oracle array
    /// @param time The current block.timestamp
    /// @param secondsAgos Each amount of time to look back, in seconds, at which point to return an observation
    /// @param tick The current tick
    /// @param index The index of the observation that was most recently written to the observations array
    /// @param liquidity The current in-range pool liquidity
    /// @param cardinality The number of populated elements in the oracle array
    /// @return tickCumulatives The tick * time elapsed since the pool was first initialized, as of each `secondsAgo`
    /// @return secondsPerLiquidityCumulativeX128s The cumulative seconds / max(1, liquidity) since the pool was first initialized, as of each `secondsAgo`
    function observe(
        Observation[65535] storage self,
        uint32 time,
        uint32[] memory secondsAgos,
        int24 tick,
        uint16 index,
        uint128 liquidity,
        uint128 boostedLiquidity,
        uint16 cardinality
    )
        external
        view
        returns (
            int56[] memory tickCumulatives,
            uint160[] memory secondsPerLiquidityCumulativeX128s,
            uint160[] memory periodSecondsPerBoostedLiquidityX128s
        )
    {
        require(cardinality > 0, 'I');

        tickCumulatives = new int56[](secondsAgos.length);
        secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length);
        periodSecondsPerBoostedLiquidityX128s = new uint160[](secondsAgos.length);

        for (uint256 i = 0; i < secondsAgos.length; i++) {
            (
                tickCumulatives[i],
                secondsPerLiquidityCumulativeX128s[i],
                periodSecondsPerBoostedLiquidityX128s[i]
            ) = observeSingle(self, time, secondsAgos[i], tick, index, liquidity, boostedLiquidity, cardinality);
        }
    }

    function newPeriod(
        Observation[65535] storage self,
        uint16 index,
        uint256 period
    )
        external
        returns (
            uint160 secondsPerLiquidityCumulativeX128,
            uint160 secondsPerBoostedLiquidityCumulativeX128,
            uint32 boostedInRange
        )
    {
        Observation memory last = self[index];
        States.PoolStates storage states = States.getStorage();

        uint32 delta = uint32(period) * 1 weeks - last.blockTimestamp;

        secondsPerLiquidityCumulativeX128 =
            last.secondsPerLiquidityCumulativeX128 +
            ((uint160(delta) << 128) / (states.liquidity > 0 ? states.liquidity : 1));

        secondsPerBoostedLiquidityCumulativeX128 =
            last.secondsPerBoostedLiquidityPeriodX128 +
            ((uint160(delta) << 128) / (states.boostedLiquidity > 0 ? states.boostedLiquidity : 1));

        boostedInRange = states.boostedLiquidity > 0 ? last.boostedInRange + delta : last.boostedInRange;

        self[index] = Observation({
            blockTimestamp: uint32(period) * 1 weeks,
            tickCumulative: last.tickCumulative + int56(states.slot0.tick) * delta,
            secondsPerLiquidityCumulativeX128: secondsPerLiquidityCumulativeX128,
            secondsPerBoostedLiquidityPeriodX128: secondsPerBoostedLiquidityCumulativeX128,
            initialized: last.initialized,
            boostedInRange: 0
        });
    }

    struct SnapShot {
        int56 tickCumulativeLower;
        int56 tickCumulativeUpper;
        uint160 secondsPerLiquidityOutsideLowerX128;
        uint160 secondsPerLiquidityOutsideUpperX128;
        uint160 secondsPerBoostedLiquidityOutsideLowerX128;
        uint160 secondsPerBoostedLiquidityOutsideUpperX128;
        uint32 secondsOutsideLower;
        uint32 secondsOutsideUpper;
    }

    struct SnapshotCumulativesInsideCache {
        uint32 time;
        int56 tickCumulative;
        uint160 secondsPerLiquidityCumulativeX128;
        uint160 secondsPerBoostedLiquidityCumulativeX128;
    }

    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
    /// snapshot is taken and the second snapshot is taken. Boosted data is only valid if it's within the same period
    /// @param tickLower The lower tick of the range
    /// @param tickUpper The upper tick of the range
    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range
    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
    /// @return secondsPerBoostedLiquidityInsideX128 The snapshot of seconds per boosted liquidity for the range
    /// @return secondsInside The snapshot of seconds per liquidity for the range
    function snapshotCumulativesInside(
        int24 tickLower,
        int24 tickUpper
    )
        external
        view
        returns (
            int56 tickCumulativeInside,
            uint160 secondsPerLiquidityInsideX128,
            uint160 secondsPerBoostedLiquidityInsideX128,
            uint32 secondsInside
        )
    {
        States.PoolStates storage states = States.getStorage();

        TickInfo storage lower = states._ticks[tickLower];
        TickInfo storage upper = states._ticks[tickUpper];

        SnapShot memory snapshot;

        {
            uint256 period = States._blockTimestamp() / 1 weeks;
            bool initializedLower;
            (
                snapshot.tickCumulativeLower,
                snapshot.secondsPerLiquidityOutsideLowerX128,
                snapshot.secondsPerBoostedLiquidityOutsideLowerX128,
                snapshot.secondsOutsideLower,
                initializedLower
            ) = (
                lower.tickCumulativeOutside,
                lower.secondsPerLiquidityOutsideX128,
                uint160(lower.periodSecondsPerBoostedLiquidityOutsideX128[period]),
                lower.secondsOutside,
                lower.initialized
            );
            require(initializedLower);

            bool initializedUpper;
            (
                snapshot.tickCumulativeUpper,
                snapshot.secondsPerLiquidityOutsideUpperX128,
                snapshot.secondsPerBoostedLiquidityOutsideUpperX128,
                snapshot.secondsOutsideUpper,
                initializedUpper
            ) = (
                upper.tickCumulativeOutside,
                upper.secondsPerLiquidityOutsideX128,
                uint160(upper.periodSecondsPerBoostedLiquidityOutsideX128[period]),
                upper.secondsOutside,
                upper.initialized
            );
            require(initializedUpper);
        }

        Slot0 memory _slot0 = states.slot0;

        if (_slot0.tick < tickLower) {
            return (
                snapshot.tickCumulativeLower - snapshot.tickCumulativeUpper,
                snapshot.secondsPerLiquidityOutsideLowerX128 - snapshot.secondsPerLiquidityOutsideUpperX128,
                snapshot.secondsPerBoostedLiquidityOutsideLowerX128 -
                    snapshot.secondsPerBoostedLiquidityOutsideUpperX128,
                snapshot.secondsOutsideLower - snapshot.secondsOutsideUpper
            );
        } else if (_slot0.tick < tickUpper) {
            SnapshotCumulativesInsideCache memory cache;
            cache.time = States._blockTimestamp();
            (
                cache.tickCumulative,
                cache.secondsPerLiquidityCumulativeX128,
                cache.secondsPerBoostedLiquidityCumulativeX128
            ) = observeSingle(
                states.observations,
                cache.time,
                0,
                _slot0.tick,
                _slot0.observationIndex,
                states.liquidity,
                states.boostedLiquidity,
                _slot0.observationCardinality
            );
            return (
                cache.tickCumulative - snapshot.tickCumulativeLower - snapshot.tickCumulativeUpper,
                cache.secondsPerLiquidityCumulativeX128 -
                    snapshot.secondsPerLiquidityOutsideLowerX128 -
                    snapshot.secondsPerLiquidityOutsideUpperX128,
                cache.secondsPerBoostedLiquidityCumulativeX128 -
                    snapshot.secondsPerBoostedLiquidityOutsideLowerX128 -
                    snapshot.secondsPerBoostedLiquidityOutsideUpperX128,
                cache.time - snapshot.secondsOutsideLower - snapshot.secondsOutsideUpper
            );
        } else {
            return (
                snapshot.tickCumulativeUpper - snapshot.tickCumulativeLower,
                snapshot.secondsPerLiquidityOutsideUpperX128 - snapshot.secondsPerLiquidityOutsideLowerX128,
                snapshot.secondsPerBoostedLiquidityOutsideUpperX128 -
                    snapshot.secondsPerBoostedLiquidityOutsideLowerX128,
                snapshot.secondsOutsideUpper - snapshot.secondsOutsideLower
            );
        }
    }

    /// @notice Returns the seconds per liquidity and seconds inside a tick range for a period
    /// @dev This does not ensure the range is a valid range
    /// @param period The timestamp of the period
    /// @param tickLower The lower tick of the range
    /// @param tickUpper The upper tick of the range
    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
    /// @return secondsPerBoostedLiquidityInsideX128 The snapshot of seconds per boosted liquidity for the range
    function periodCumulativesInside(
        uint32 period,
        int24 tickLower,
        int24 tickUpper
    ) external view returns (uint160 secondsPerLiquidityInsideX128, uint160 secondsPerBoostedLiquidityInsideX128) {
        States.PoolStates storage states = States.getStorage();

        TickInfo storage lower = states._ticks[tickLower];
        TickInfo storage upper = states._ticks[tickUpper];

        SnapShot memory snapshot;

        {
            int24 startTick = states.periods[period].startTick;
            uint256 previousPeriod = states.periods[period].previousPeriod;

            (snapshot.secondsPerLiquidityOutsideLowerX128, snapshot.secondsPerBoostedLiquidityOutsideLowerX128) = (
                uint160(lower.periodSecondsPerLiquidityOutsideX128[period]),
                uint160(lower.periodSecondsPerBoostedLiquidityOutsideX128[period])
            );
            if (tickLower <= startTick && snapshot.secondsPerLiquidityOutsideLowerX128 == 0) {
                snapshot.secondsPerLiquidityOutsideLowerX128 = states
                    .periods[previousPeriod]
                    .endSecondsPerLiquidityPeriodX128;
            }

            // separate conditions because liquidity and boosted liquidity can be different
            if (tickLower <= startTick && snapshot.secondsPerBoostedLiquidityOutsideLowerX128 == 0) {
                snapshot.secondsPerBoostedLiquidityOutsideLowerX128 = states
                    .periods[previousPeriod]
                    .endSecondsPerBoostedLiquidityPeriodX128;
            }

            (snapshot.secondsPerLiquidityOutsideUpperX128, snapshot.secondsPerBoostedLiquidityOutsideUpperX128) = (
                uint160(upper.periodSecondsPerLiquidityOutsideX128[period]),
                uint160(upper.periodSecondsPerBoostedLiquidityOutsideX128[period])
            );
            if (tickUpper <= startTick && snapshot.secondsPerLiquidityOutsideUpperX128 == 0) {
                snapshot.secondsPerLiquidityOutsideUpperX128 = states
                    .periods[previousPeriod]
                    .endSecondsPerLiquidityPeriodX128;
            }

            // separate conditions because liquidity and boosted liquidity can be different
            if (tickUpper <= startTick && snapshot.secondsPerBoostedLiquidityOutsideUpperX128 == 0) {
                snapshot.secondsPerBoostedLiquidityOutsideUpperX128 = states
                    .periods[previousPeriod]
                    .endSecondsPerBoostedLiquidityPeriodX128;
            }
        }

        int24 lastTick;
        uint256 currentPeriod = states.lastPeriod;
        {
            // if period is already finalized, use period's last tick, if not, use current tick
            if (currentPeriod > period) {
                lastTick = states.periods[period].lastTick;
            } else {
                lastTick = states.slot0.tick;
            }
        }

        if (lastTick < tickLower) {
            return (
                snapshot.secondsPerLiquidityOutsideLowerX128 - snapshot.secondsPerLiquidityOutsideUpperX128,
                snapshot.secondsPerBoostedLiquidityOutsideLowerX128 -
                    snapshot.secondsPerBoostedLiquidityOutsideUpperX128
            );
        } else if (lastTick < tickUpper) {
            SnapshotCumulativesInsideCache memory cache;
            // if period's on-going, observeSingle, if finalized, use endSecondsPerLiquidityPeriodX128
            if (currentPeriod <= period) {
                cache.time = States._blockTimestamp();
                // limit to the end of period
                if (cache.time > currentPeriod * 1 weeks + 1 weeks) {
                    cache.time = uint32(currentPeriod * 1 weeks + 1 weeks);
                }

                Slot0 memory _slot0 = states.slot0;

                (
                    ,
                    cache.secondsPerLiquidityCumulativeX128,
                    cache.secondsPerBoostedLiquidityCumulativeX128
                ) = observeSingle(
                    states.observations,
                    cache.time,
                    0,
                    _slot0.tick,
                    _slot0.observationIndex,
                    states.liquidity,
                    states.boostedLiquidity,
                    _slot0.observationCardinality
                );
            } else {
                cache.secondsPerLiquidityCumulativeX128 = states.periods[period].endSecondsPerLiquidityPeriodX128;
                cache.secondsPerBoostedLiquidityCumulativeX128 = states
                    .periods[period]
                    .endSecondsPerBoostedLiquidityPeriodX128;
            }

            return (
                cache.secondsPerLiquidityCumulativeX128 -
                    snapshot.secondsPerLiquidityOutsideLowerX128 -
                    snapshot.secondsPerLiquidityOutsideUpperX128,
                cache.secondsPerBoostedLiquidityCumulativeX128 -
                    snapshot.secondsPerBoostedLiquidityOutsideLowerX128 -
                    snapshot.secondsPerBoostedLiquidityOutsideUpperX128
            );
        } else {
            return (
                snapshot.secondsPerLiquidityOutsideUpperX128 - snapshot.secondsPerLiquidityOutsideLowerX128,
                snapshot.secondsPerBoostedLiquidityOutsideUpperX128 -
                    snapshot.secondsPerBoostedLiquidityOutsideLowerX128
            );
        }
    }
}

File 27 of 37 : Position.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.8.0;
pragma abicoder v2;

import './FullMath.sol';
import './FixedPoint128.sol';
import './FixedPoint32.sol';
import './LiquidityMath.sol';
import './SqrtPriceMath.sol';
import './States.sol';
import './Tick.sol';
import './TickMath.sol';
import './TickBitmap.sol';
import './Oracle.sol';

import '../../v2-periphery/libraries/LiquidityAmounts.sol';

import '../../interfaces/IVotingEscrow.sol';
import '../../interfaces/IVoter.sol';

/// @title Position
/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary
/// @dev Positions store additional state for tracking fees owed to the position
library Position {
    // no limit if a your veNFT reaches a threshold
    // if veNFTRatio is more than 2.5% of total (2.5% * 1.5e18 =  3.75e+16)
    uint256 internal constant veNftUncapThreshold = 37500000000000000;

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

    /// @notice Returns the Info struct of a position, given an owner and position boundaries
    /// @param self The mapping containing all user positions
    /// @param owner The address of the position owner
    /// @param index The index of the position
    /// @param tickLower The lower tick boundary of the position
    /// @param tickUpper The upper tick boundary of the position
    /// @return position The position info struct of the given owners' position
    function get(
        mapping(bytes32 => PositionInfo) storage self,
        address owner,
        uint256 index,
        int24 tickLower,
        int24 tickUpper
    ) public view returns (PositionInfo storage position) {
        position = self[positionHash(owner, index, tickLower, tickUpper)];
    }

    /// @notice Returns the BoostInfo struct of a position, given an owner, index, and position boundaries
    /// @param self The mapping containing all user boosted positions within the period
    /// @param owner The address of the position owner
    /// @param index The index of the position
    /// @param tickLower The lower tick boundary of the position
    /// @param tickUpper The upper tick boundary of the position
    /// @return position The position BoostInfo struct of the given owners' position within the period
    function get(
        PeriodBoostInfo storage self,
        address owner,
        uint256 index,
        int24 tickLower,
        int24 tickUpper
    ) public view returns (BoostInfo storage position) {
        position = self.positions[positionHash(owner, index, tickLower, tickUpper)];
    }

    /// @notice Credits accumulated fees to a user's position
    /// @param self The individual position to update
    /// @param liquidityDelta The change in pool liquidity as a result of the position update
    /// @param feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries
    /// @param feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries
    function _updatePositionLiquidity(
        PositionInfo storage self,
        States.PoolStates storage states,
        uint256 period,
        bytes32 _positionHash,
        int128 liquidityDelta,
        uint256 feeGrowthInside0X128,
        uint256 feeGrowthInside1X128
    ) internal {
        PositionInfo memory _self = self;

        uint128 liquidityNext;
        if (liquidityDelta == 0) {
            require(_self.liquidity > 0, 'NP'); // disallow pokes for 0 liquidity positions
            liquidityNext = _self.liquidity;
        } else {
            liquidityNext = LiquidityMath.addDelta(_self.liquidity, liquidityDelta);
        }

        // calculate accumulated fees
        uint128 tokensOwed0 = uint128(
            FullMath.mulDiv(feeGrowthInside0X128 - _self.feeGrowthInside0LastX128, _self.liquidity, FixedPoint128.Q128)
        );
        uint128 tokensOwed1 = uint128(
            FullMath.mulDiv(feeGrowthInside1X128 - _self.feeGrowthInside1LastX128, _self.liquidity, FixedPoint128.Q128)
        );

        // update the position
        if (liquidityDelta != 0) {
            self.liquidity = liquidityNext;
        }
        self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
        self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
        if (tokensOwed0 > 0 || tokensOwed1 > 0) {
            // overflow is acceptable, have to withdraw before you hit type(uint128).max fees
            self.tokensOwed0 += tokensOwed0;
            self.tokensOwed1 += tokensOwed1;
        }

        // write checkpoint, push a checkpoint if the last period is different, overwrite if not
        uint256 checkpointLength = states.positionCheckpoints[_positionHash].length;
        if (checkpointLength == 0 || states.positionCheckpoints[_positionHash][checkpointLength - 1].period != period) {
            states.positionCheckpoints[_positionHash].push(
                PositionCheckpoint({period: period, liquidity: liquidityNext})
            );
        } else {
            states.positionCheckpoints[_positionHash][checkpointLength - 1].liquidity = liquidityNext;
        }
    }

    /// @notice Updates boosted balances to a user's position
    /// @param self The individual boosted position to update
    /// @param boostedLiquidityDelta The change in pool liquidity as a result of the position update
    /// @param secondsPerBoostedLiquidityPeriodX128 The seconds in range gained per unit of liquidity, inside the position's tick boundaries for this period
    function _updateBoostedPosition(
        BoostInfo storage self,
        int128 liquidityDelta,
        int128 boostedLiquidityDelta,
        uint160 secondsPerLiquidityPeriodX128,
        uint160 secondsPerBoostedLiquidityPeriodX128
    ) internal {
        // negative expected sometimes, which is allowed
        int160 secondsPerLiquidityPeriodIntX128 = int160(secondsPerLiquidityPeriodX128);
        int160 secondsPerBoostedLiquidityPeriodIntX128 = int160(secondsPerBoostedLiquidityPeriodX128);

        self.boostAmount = LiquidityMath.addDelta(self.boostAmount, boostedLiquidityDelta);

        int160 secondsPerLiquidityPeriodStartX128 = self.secondsPerLiquidityPeriodStartX128;
        int160 secondsPerBoostedLiquidityPeriodStartX128 = self.secondsPerBoostedLiquidityPeriodStartX128;

        // take the difference to make the delta positive or zero
        secondsPerLiquidityPeriodIntX128 -= secondsPerLiquidityPeriodStartX128;
        secondsPerBoostedLiquidityPeriodIntX128 -= secondsPerBoostedLiquidityPeriodStartX128;

        // these int should never be negative
        if (secondsPerLiquidityPeriodIntX128 < 0) {
            secondsPerLiquidityPeriodIntX128 = 0;
        }
        if (secondsPerBoostedLiquidityPeriodIntX128 < 0) {
            secondsPerBoostedLiquidityPeriodIntX128 = 0;
        }

        int256 secondsDebtDeltaX96 = SafeCast.toInt256(
            FullMath.mulDivRoundingUp(
                liquidityDelta > 0 ? uint256(liquidityDelta) : uint256(-liquidityDelta),
                uint256(secondsPerLiquidityPeriodIntX128),
                FixedPoint32.Q32
            )
        );

        int256 boostedSecondsDebtDeltaX96 = SafeCast.toInt256(
            FullMath.mulDivRoundingUp(
                boostedLiquidityDelta > 0 ? uint256(boostedLiquidityDelta) : uint256(-boostedLiquidityDelta),
                uint256(secondsPerBoostedLiquidityPeriodIntX128),
                FixedPoint32.Q32
            )
        );

        self.boostedSecondsDebtX96 = boostedLiquidityDelta > 0
            ? self.boostedSecondsDebtX96 + boostedSecondsDebtDeltaX96
            : self.boostedSecondsDebtX96 - boostedSecondsDebtDeltaX96; // can't overflow since each period is way less than uint31

        self.secondsDebtX96 = liquidityDelta > 0
            ? self.secondsDebtX96 + secondsDebtDeltaX96
            : self.secondsDebtX96 - secondsDebtDeltaX96; // can't overflow since each period is way less than uint31
    }

    /// @notice Initializes secondsPerLiquidityPeriodStartX128 for a position
    /// @param self The individual boosted position to update
    /// @param position The individual position
    /// @param secondsInRangeParams Parameters used to find the seconds in range
    /// @param secondsPerLiquidityPeriodX128 The seconds in range gained per unit of liquidity, inside the position's tick boundaries for this period
    /// @param secondsPerBoostedLiquidityPeriodX128 The seconds in range gained per unit of liquidity, inside the position's tick boundaries for this period
    function initializeSecondsStart(
        BoostInfo storage self,
        PositionInfo storage position,
        PositionPeriodSecondsInRangeParams memory secondsInRangeParams,
        uint160 secondsPerLiquidityPeriodX128,
        uint160 secondsPerBoostedLiquidityPeriodX128
    ) internal {
        // record initialized
        self.initialized = true;

        // record owed tokens if liquidity > 0 (means position existed before period change)
        if (position.liquidity > 0) {
            (uint256 periodSecondsInsideX96, uint256 periodBoostedSecondsInsideX96) = positionPeriodSecondsInRange(
                secondsInRangeParams
            );

            self.secondsDebtX96 = -int256(periodSecondsInsideX96);
            self.boostedSecondsDebtX96 = -int256(periodBoostedSecondsInsideX96);
        }

        // convert uint to int
        // negative expected sometimes, which is allowed
        int160 secondsPerLiquidityPeriodIntX128 = int160(secondsPerLiquidityPeriodX128);
        int160 secondsPerBoostedLiquidityPeriodIntX128 = int160(secondsPerBoostedLiquidityPeriodX128);

        self.secondsPerLiquidityPeriodStartX128 = secondsPerLiquidityPeriodIntX128;

        self.secondsPerBoostedLiquidityPeriodStartX128 = secondsPerBoostedLiquidityPeriodIntX128;
    }

    struct ModifyPositionParams {
        // the address that owns the position
        address owner;
        uint256 index;
        // the lower and upper tick of the position
        int24 tickLower;
        int24 tickUpper;
        // any change in liquidity
        int128 liquidityDelta;
        uint256 veNftTokenId;
    }

    /// @dev Effect some changes to a position
    /// @param params the position details and the change to the position's liquidity to effect
    /// @return position a storage pointer referencing the position with the given owner and tick range
    /// @return amount0 the amount of token0 owed to the pool, negative if the pool should pay the recipient
    /// @return amount1 the amount of token1 owed to the pool, negative if the pool should pay the recipient
    function _modifyPosition(
        ModifyPositionParams memory params
    ) external returns (PositionInfo storage position, int256 amount0, int256 amount1) {
        States.PoolStates storage states = States.getStorage();

        // check ticks
        require(params.tickLower < params.tickUpper, 'TLU');
        require(params.tickLower >= TickMath.MIN_TICK, 'TLM');
        require(params.tickUpper <= TickMath.MAX_TICK, 'TUM');

        Slot0 memory _slot0 = states.slot0; // SLOAD for gas optimization

        int128 boostedLiquidityDelta;
        (position, boostedLiquidityDelta) = _updatePosition(
            UpdatePositionParams({
                owner: params.owner,
                index: params.index,
                tickLower: params.tickLower,
                tickUpper: params.tickUpper,
                liquidityDelta: params.liquidityDelta,
                tick: _slot0.tick,
                veNftTokenId: params.veNftTokenId
            })
        );

        if (params.liquidityDelta != 0 || boostedLiquidityDelta != 0) {
            if (_slot0.tick < params.tickLower) {
                // current tick is below the passed range; liquidity can only become in range by crossing from left to
                // right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it
                amount0 = SqrtPriceMath.getAmount0Delta(
                    TickMath.getSqrtRatioAtTick(params.tickLower),
                    TickMath.getSqrtRatioAtTick(params.tickUpper),
                    params.liquidityDelta
                );
            } else if (_slot0.tick < params.tickUpper) {
                // current tick is inside the passed range
                uint128 liquidityBefore = states.liquidity; // SLOAD for gas optimization
                uint128 boostedLiquidityBefore = states.boostedLiquidity;

                // write an oracle entry
                (states.slot0.observationIndex, states.slot0.observationCardinality) = Oracle.write(
                    states.observations,
                    _slot0.observationIndex,
                    States._blockTimestamp(),
                    _slot0.tick,
                    liquidityBefore,
                    boostedLiquidityBefore,
                    _slot0.observationCardinality,
                    _slot0.observationCardinalityNext
                );

                amount0 = SqrtPriceMath.getAmount0Delta(
                    _slot0.sqrtPriceX96,
                    TickMath.getSqrtRatioAtTick(params.tickUpper),
                    params.liquidityDelta
                );
                amount1 = SqrtPriceMath.getAmount1Delta(
                    TickMath.getSqrtRatioAtTick(params.tickLower),
                    _slot0.sqrtPriceX96,
                    params.liquidityDelta
                );

                states.liquidity = LiquidityMath.addDelta(liquidityBefore, params.liquidityDelta);
                states.boostedLiquidity = LiquidityMath.addDelta(boostedLiquidityBefore, boostedLiquidityDelta);
            } else {
                // current tick is above the passed range; liquidity can only become in range by crossing from right to
                // left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it
                amount1 = SqrtPriceMath.getAmount1Delta(
                    TickMath.getSqrtRatioAtTick(params.tickLower),
                    TickMath.getSqrtRatioAtTick(params.tickUpper),
                    params.liquidityDelta
                );
            }
        }
    }

    struct UpdatePositionParams {
        // the owner of the position
        address owner;
        // the index of the position
        uint256 index;
        // the lower tick of the position's tick range
        int24 tickLower;
        // the upper tick of the position's tick range
        int24 tickUpper;
        // the amount liquidity changes by
        int128 liquidityDelta;
        // the current tick, passed to avoid sloads
        int24 tick;
        // the veNFTTokenId to be attached
        uint256 veNftTokenId;
    }

    struct UpdatePositionCache {
        uint256 feeGrowthGlobal0X128;
        uint256 feeGrowthGlobal1X128;
        bool flippedUpper;
        bool flippedLower;
        uint256 feeGrowthInside0X128;
        uint256 feeGrowthInside1X128;
    }

    struct ObservationCache {
        int56 tickCumulative;
        uint160 secondsPerLiquidityCumulativeX128;
        uint160 secondsPerBoostedLiquidityPeriodX128;
    }

    struct PoolBalanceCache {
        uint256 hypBalance0;
        uint256 hypBalance1;
        uint256 poolBalance0;
        uint256 poolBalance1;
    }

    struct BoostedLiquidityCache {
        uint256 veNftRatio;
        uint256 newBoostedLiquidity;
        uint160 lowerSqrtRatioX96;
        uint160 upperSqrtRatioX96;
        uint160 currentSqrtRatioX96;
    }

    struct VeNftBoostCache {
        uint256 veNftBoostUsedRatio;
        uint256 positionBoostUsedRatio;
    }

    /// @dev Gets and updates a position with the given liquidity delta
    /// @param params the position details and the change to the position's liquidity to effect
    function _updatePosition(
        UpdatePositionParams memory params
    ) private returns (PositionInfo storage position, int128 boostedLiquidityDelta) {
        States.PoolStates storage states = States.getStorage();

        uint256 period = States._blockTimestamp() / 1 weeks;

        bytes32 _positionHash = positionHash(params.owner, params.index, params.tickLower, params.tickUpper);
        position = states.positions[_positionHash];
        BoostInfo storage boostedPosition = states.boostInfos[period].positions[_positionHash];

        {
            // this is needed to determine attachment and newBoostedLiquidity
            uint128 newLiquidity = LiquidityMath.addDelta(position.liquidity, params.liquidityDelta);

            // detach if new liquidity is 0
            if (newLiquidity == 0) {
                _switchAttached(position, boostedPosition, 0, period, _positionHash);
                params.veNftTokenId = 0;
            }

            // type(uint256).max serves as a signal to not switch attachment
            if (params.veNftTokenId != type(uint256).max) {
                _switchAttached(position, boostedPosition, params.veNftTokenId, period, _positionHash);
            }

            {
                BoostedLiquidityCache memory boostedLiquidityCache;
                (boostedLiquidityCache.veNftRatio, boostedLiquidityCache.newBoostedLiquidity) = LiquidityMath
                    .calculateBoostedLiquidity(
                        newLiquidity,
                        boostedPosition.veNftAmount,
                        states.boostInfos[period].totalVeNftAmount
                    );

                if (boostedLiquidityCache.newBoostedLiquidity > 0) {
                    PoolBalanceCache memory poolBalanceCache;

                    poolBalanceCache.poolBalance0 = States.balance0();
                    poolBalanceCache.poolBalance1 = States.balance1();

                    boostedLiquidityCache.lowerSqrtRatioX96 = TickMath.getSqrtRatioAtTick(params.tickLower);

                    boostedLiquidityCache.upperSqrtRatioX96 = TickMath.getSqrtRatioAtTick(params.tickUpper);

                    boostedLiquidityCache.currentSqrtRatioX96 = states.slot0.sqrtPriceX96;

                    // boosted liquidity cap
                    // no limit if a your veNFT reaches a threshold
                    if (boostedLiquidityCache.veNftRatio < veNftUncapThreshold) {
                        uint160 midSqrtRatioX96 = TickMath.getSqrtRatioAtTick(
                            (params.tickLower + params.tickUpper) / 2
                        );

                        // check max balance allowed
                        {
                            uint256 maxBalance0 = LiquidityAmounts.getAmount0ForLiquidity(
                                midSqrtRatioX96,
                                boostedLiquidityCache.upperSqrtRatioX96,
                                type(uint128).max
                            );
                            uint256 maxBalance1 = LiquidityAmounts.getAmount1ForLiquidity(
                                boostedLiquidityCache.lowerSqrtRatioX96,
                                midSqrtRatioX96,
                                type(uint128).max
                            );

                            if (poolBalanceCache.poolBalance0 > maxBalance0) {
                                poolBalanceCache.hypBalance0 = maxBalance0;
                            } else {
                                poolBalanceCache.hypBalance0 = poolBalanceCache.poolBalance0;
                            }
                            if (poolBalanceCache.poolBalance1 > maxBalance1) {
                                poolBalanceCache.hypBalance1 = maxBalance1;
                            } else {
                                poolBalanceCache.hypBalance1 = poolBalanceCache.poolBalance1;
                            }
                        }

                        // hypothetical liquidity is found by using all of balance0 and balance1
                        // at this position's midpoint and range
                        // using midpoint to discourage making out of range positions
                        uint256 hypotheticalLiquidity = LiquidityAmounts.getLiquidityForAmounts(
                            midSqrtRatioX96,
                            boostedLiquidityCache.lowerSqrtRatioX96,
                            boostedLiquidityCache.upperSqrtRatioX96,
                            poolBalanceCache.hypBalance0,
                            poolBalanceCache.hypBalance1
                        );

                        // limit newBoostedLiquidity to a portion of hypotheticalLiquidity based on how much veNFT is attached
                        uint256 boostedLiquidityCap = FullMath.mulDiv(
                            hypotheticalLiquidity,
                            boostedLiquidityCache.veNftRatio,
                            1e18
                        );

                        if (boostedLiquidityCache.newBoostedLiquidity > boostedLiquidityCap) {
                            boostedLiquidityCache.newBoostedLiquidity = boostedLiquidityCap;
                        }
                    }

                    // veNFT boost available
                    uint256 veNftBoostAvailable;
                    VeNftBoostCache memory veNftBoostCache;
                    {
                        // fetch existing data
                        veNftBoostCache.positionBoostUsedRatio = states
                            .boostInfos[period]
                            .veNftInfos[params.veNftTokenId]
                            .positionBoostUsedRatio[_positionHash];

                        veNftBoostCache.veNftBoostUsedRatio = states
                            .boostInfos[period]
                            .veNftInfos[params.veNftTokenId]
                            .veNftBoostUsedRatio;

                        // prevents underflows
                        veNftBoostCache.veNftBoostUsedRatio = veNftBoostCache.veNftBoostUsedRatio >
                            veNftBoostCache.positionBoostUsedRatio
                            ? veNftBoostCache.veNftBoostUsedRatio - veNftBoostCache.positionBoostUsedRatio
                            : 0;

                        uint256 veNftBoostAvailableRatio = 1e18 > veNftBoostCache.veNftBoostUsedRatio
                            ? 1e18 - veNftBoostCache.veNftBoostUsedRatio
                            : 0;

                        // no limit if a your veNFT reaches a threshold
                        // hypothetical balances still have to be calculated in case
                        // the veNFT falls below threshold later
                        if (boostedLiquidityCache.veNftRatio >= veNftUncapThreshold) {
                            veNftBoostAvailableRatio = 1e18;
                        }

                        // assign hypBalances
                        {
                            uint256 maxBalance0 = 0;
                            uint256 maxBalance1 = 0;

                            if (boostedLiquidityCache.currentSqrtRatioX96 < boostedLiquidityCache.lowerSqrtRatioX96) {
                                maxBalance0 = LiquidityAmounts.getAmount0ForLiquidity(
                                    boostedLiquidityCache.lowerSqrtRatioX96,
                                    boostedLiquidityCache.upperSqrtRatioX96,
                                    type(uint128).max
                                );
                            } else if (
                                boostedLiquidityCache.currentSqrtRatioX96 < boostedLiquidityCache.upperSqrtRatioX96
                            ) {
                                maxBalance0 = LiquidityAmounts.getAmount0ForLiquidity(
                                    boostedLiquidityCache.currentSqrtRatioX96,
                                    boostedLiquidityCache.upperSqrtRatioX96,
                                    type(uint128).max
                                );
                                maxBalance1 = LiquidityAmounts.getAmount1ForLiquidity(
                                    boostedLiquidityCache.lowerSqrtRatioX96,
                                    boostedLiquidityCache.currentSqrtRatioX96,
                                    type(uint128).max
                                );
                            } else {
                                maxBalance1 = LiquidityAmounts.getAmount1ForLiquidity(
                                    boostedLiquidityCache.lowerSqrtRatioX96,
                                    boostedLiquidityCache.upperSqrtRatioX96,
                                    type(uint128).max
                                );
                            }

                            if (poolBalanceCache.poolBalance0 > maxBalance0) {
                                poolBalanceCache.hypBalance0 = maxBalance0;
                            } else {
                                poolBalanceCache.hypBalance0 = poolBalanceCache.poolBalance0;
                            }
                            if (poolBalanceCache.poolBalance1 > maxBalance1) {
                                poolBalanceCache.hypBalance1 = maxBalance1;
                            } else {
                                poolBalanceCache.hypBalance1 = poolBalanceCache.poolBalance1;
                            }
                        }

                        // hypothetical liquidity is found by using all of balance0 and balance1
                        // at current price to determine % boost used since boost will fill up fast otherwise
                        uint256 hypotheticalLiquidity = LiquidityAmounts.getLiquidityForAmounts(
                            boostedLiquidityCache.currentSqrtRatioX96,
                            boostedLiquidityCache.lowerSqrtRatioX96,
                            boostedLiquidityCache.upperSqrtRatioX96,
                            poolBalanceCache.hypBalance0,
                            poolBalanceCache.hypBalance1
                        );

                        hypotheticalLiquidity = FullMath.mulDiv(
                            hypotheticalLiquidity,
                            boostedLiquidityCache.veNftRatio,
                            1e18
                        );

                        veNftBoostAvailable = FullMath.mulDiv(hypotheticalLiquidity, veNftBoostAvailableRatio, 1e18);

                        if (
                            boostedLiquidityCache.newBoostedLiquidity > veNftBoostAvailable &&
                            boostedLiquidityCache.veNftRatio < veNftUncapThreshold
                        ) {
                            boostedLiquidityCache.newBoostedLiquidity = veNftBoostAvailable;
                        }

                        veNftBoostCache.positionBoostUsedRatio = hypotheticalLiquidity == 0
                            ? 0
                            : FullMath.mulDiv(boostedLiquidityCache.newBoostedLiquidity, 1e18, hypotheticalLiquidity);
                    }

                    // update veNFTBoostUsedRatio and positionBoostUsedRatio
                    states.boostInfos[period].veNftInfos[params.veNftTokenId].positionBoostUsedRatio[
                        _positionHash
                    ] = veNftBoostCache.positionBoostUsedRatio;

                    states.boostInfos[period].veNftInfos[params.veNftTokenId].veNftBoostUsedRatio = uint128(
                        veNftBoostCache.veNftBoostUsedRatio + veNftBoostCache.positionBoostUsedRatio
                    );
                }

                boostedLiquidityDelta = int128(boostedLiquidityCache.newBoostedLiquidity - boostedPosition.boostAmount);
            }
        }

        UpdatePositionCache memory cache;

        cache.feeGrowthGlobal0X128 = states.feeGrowthGlobal0X128; // SLOAD for gas optimization
        cache.feeGrowthGlobal1X128 = states.feeGrowthGlobal1X128; // SLOAD for gas optimization

        // if we need to update the ticks, do it
        if (params.liquidityDelta != 0 || boostedLiquidityDelta != 0) {
            uint32 time = States._blockTimestamp();
            ObservationCache memory observationCache;
            (
                observationCache.tickCumulative,
                observationCache.secondsPerLiquidityCumulativeX128,
                observationCache.secondsPerBoostedLiquidityPeriodX128
            ) = Oracle.observeSingle(
                states.observations,
                time,
                0,
                states.slot0.tick,
                states.slot0.observationIndex,
                states.liquidity,
                states.boostedLiquidity,
                states.slot0.observationCardinality
            );

            cache.flippedLower = Tick.update(
                states._ticks,
                Tick.UpdateTickParams(
                    params.tickLower,
                    params.tick,
                    params.liquidityDelta,
                    boostedLiquidityDelta,
                    cache.feeGrowthGlobal0X128,
                    cache.feeGrowthGlobal1X128,
                    observationCache.secondsPerLiquidityCumulativeX128,
                    observationCache.secondsPerBoostedLiquidityPeriodX128,
                    observationCache.tickCumulative,
                    time,
                    false,
                    states.maxLiquidityPerTick
                )
            );
            cache.flippedUpper = Tick.update(
                states._ticks,
                Tick.UpdateTickParams(
                    params.tickUpper,
                    params.tick,
                    params.liquidityDelta,
                    boostedLiquidityDelta,
                    cache.feeGrowthGlobal0X128,
                    cache.feeGrowthGlobal1X128,
                    observationCache.secondsPerLiquidityCumulativeX128,
                    observationCache.secondsPerBoostedLiquidityPeriodX128,
                    observationCache.tickCumulative,
                    time,
                    true,
                    states.maxLiquidityPerTick
                )
            );

            if (cache.flippedLower) {
                TickBitmap.flipTick(states.tickBitmap, params.tickLower, states.tickSpacing);
            }
            if (cache.flippedUpper) {
                TickBitmap.flipTick(states.tickBitmap, params.tickUpper, states.tickSpacing);
            }
        }

        (cache.feeGrowthInside0X128, cache.feeGrowthInside1X128) = Tick.getFeeGrowthInside(
            states._ticks,
            params.tickLower,
            params.tickUpper,
            params.tick,
            cache.feeGrowthGlobal0X128,
            cache.feeGrowthGlobal1X128
        );

        {
            (uint160 secondsPerLiquidityPeriodX128, uint160 secondsPerBoostedLiquidityPeriodX128) = Oracle
                .periodCumulativesInside(uint32(period), params.tickLower, params.tickUpper);

            if (!boostedPosition.initialized) {
                initializeSecondsStart(
                    boostedPosition,
                    position,
                    PositionPeriodSecondsInRangeParams({
                        period: period,
                        owner: params.owner,
                        index: params.index,
                        tickLower: params.tickLower,
                        tickUpper: params.tickUpper
                    }),
                    secondsPerLiquidityPeriodX128,
                    secondsPerBoostedLiquidityPeriodX128
                );
            }

            _updatePositionLiquidity(
                position,
                states,
                period,
                _positionHash,
                params.liquidityDelta,
                cache.feeGrowthInside0X128,
                cache.feeGrowthInside1X128
            );

            _updateBoostedPosition(
                boostedPosition,
                params.liquidityDelta,
                boostedLiquidityDelta,
                secondsPerLiquidityPeriodX128,
                secondsPerBoostedLiquidityPeriodX128
            );
        }

        // clear any tick data that is no longer needed
        if (params.liquidityDelta < 0) {
            if (cache.flippedLower) {
                Tick.clear(states._ticks, params.tickLower);
            }
            if (cache.flippedUpper) {
                Tick.clear(states._ticks, params.tickUpper);
            }
        }
    }

    /// @notice updates attached veNFT tokenId and veNFT amount
    /// @dev can only be called in _updatePostion since boostedSecondsDebt needs to be updated when this is called
    /// @param position the user's position
    /// @param boostedPosition the user's boosted position
    /// @param veNftTokenId the veNFT tokenId to switch to
    /// @param _positionHash the position's hash identifier
    function _switchAttached(
        PositionInfo storage position,
        BoostInfo storage boostedPosition,
        uint256 veNftTokenId,
        uint256 period,
        bytes32 _positionHash
    ) private {
        States.PoolStates storage states = States.getStorage();
        address _votingEscrow = states.votingEscrow;

        require(
            veNftTokenId == 0 ||
                msg.sender == states.nfpManager ||
                IVotingEscrow(_votingEscrow).isApprovedOrOwner(msg.sender, veNftTokenId),
            'TNA' // tokenId not authorized
        );

        int128 veNftAmountDelta;
        uint256 oldAttached = position.attachedVeNftTokenId;

        // call detach and attach if needed
        if (veNftTokenId != oldAttached) {
            address _voter = states.voter;

            // detach, remove position from VeNFTAttachments, and update total veNFTAmount
            if (oldAttached != 0) {
                // call voter to notify detachment
                IVoter(_voter).detachTokenFromGauge(oldAttached, IVotingEscrow(_votingEscrow).ownerOf(oldAttached));

                // update times attached and veNFTAmountDelta
                uint128 timesAttached = states.boostInfos[period].veNftInfos[oldAttached].timesAttached;

                // only modify veNFTAmountDelta if this is the last time
                // this veNFT has been used to attach to a position
                if (timesAttached == 1) {
                    veNftAmountDelta -= boostedPosition.veNftAmount;
                }

                // update times this veNFT NFT has been attached to this pool
                states.boostInfos[period].veNftInfos[oldAttached].timesAttached = timesAttached - 1;

                // update veNFTBoostUsedRatio and positionBoostUsedRatio
                uint256 positionBoostUsedRatio = states
                    .boostInfos[period]
                    .veNftInfos[oldAttached]
                    .positionBoostUsedRatio[_positionHash];

                states.boostInfos[period].veNftInfos[oldAttached].veNftBoostUsedRatio -= uint128(
                    positionBoostUsedRatio
                );

                states.boostInfos[period].veNftInfos[oldAttached].positionBoostUsedRatio[_positionHash] = 0;
            }

            if (veNftTokenId != 0) {
                // call voter to notify attachment
                IVoter(_voter).attachTokenToGauge(veNftTokenId, IVotingEscrow(_votingEscrow).ownerOf(veNftTokenId));
            }

            position.attachedVeNftTokenId = veNftTokenId;
        }

        if (veNftTokenId != 0) {
            // record new attachment amount
            int128 veNftAmountAfter = int128(IVotingEscrow(_votingEscrow).balanceOfNFT(veNftTokenId)); // can't overflow because bias is lower than locked, which is an int128
            boostedPosition.veNftAmount = veNftAmountAfter;

            // update times attached and veNFTAmountDelta
            uint128 timesAttached = states.boostInfos[period].veNftInfos[veNftTokenId].timesAttached;

            // only add to veNFT total amount if it's newly attached to the pool
            if (timesAttached == 0) {
                veNftAmountDelta += veNftAmountAfter;
            }

            // update times attached
            states.boostInfos[period].veNftInfos[veNftTokenId].timesAttached = timesAttached + 1;
        } else {
            boostedPosition.veNftAmount = 0;
        }

        // update total veNFT amount
        int128 totalVeNftAmount = states.boostInfos[period].totalVeNftAmount;
        totalVeNftAmount += veNftAmountDelta;
        if (totalVeNftAmount < 0) {
            totalVeNftAmount = 0;
        }

        states.boostInfos[period].totalVeNftAmount = totalVeNftAmount;
    }

    /// @notice gets the checkpoint directly before the period
    /// @dev returns the 0th index if there's no checkpoints
    /// @param checkpoints the position's checkpoints in storage
    /// @param period the period of interest
    function getCheckpoint(
        PositionCheckpoint[] storage checkpoints,
        uint256 period
    ) internal view returns (uint256 checkpointIndex, uint256 checkpointPeriod) {
        {
            uint256 checkpointLength = checkpoints.length;

            // return 0 if length is 0
            if (checkpointLength == 0) {
                return (0, 0);
            }

            checkpointPeriod = checkpoints[0].period;

            // return 0 if first checkpoint happened after period
            if (checkpointPeriod > period) {
                return (0, 0);
            }

            checkpointIndex = checkpointLength - 1;
        }

        checkpointPeriod = checkpoints[checkpointIndex].period;

        // Find relevant checkpoint if latest checkpoint isn't before period of interest
        if (checkpointPeriod > period) {
            uint256 lower = 0;
            uint256 upper = checkpointIndex;

            while (upper > lower) {
                uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
                checkpointPeriod = checkpoints[center].period;
                if (checkpointPeriod == period) {
                    checkpointIndex = center;
                    return (checkpointIndex, checkpointPeriod);
                } else if (checkpointPeriod < period) {
                    lower = center;
                } else {
                    upper = center - 1;
                }
            }
            checkpointIndex = lower;
            checkpointPeriod = checkpoints[checkpointIndex].period;
        }

        return (checkpointIndex, checkpointPeriod);
    }

    struct PositionPeriodSecondsInRangeParams {
        uint256 period;
        address owner;
        uint256 index;
        int24 tickLower;
        int24 tickUpper;
    }

    // Get the period seconds in range of a specific position
    /// @return periodSecondsInsideX96 seconds the position was not in range for the period
    /// @return periodBoostedSecondsInsideX96 boosted seconds the period
    function positionPeriodSecondsInRange(
        PositionPeriodSecondsInRangeParams memory params
    ) public view returns (uint256 periodSecondsInsideX96, uint256 periodBoostedSecondsInsideX96) {
        States.PoolStates storage states = States.getStorage();

        {
            uint256 currentPeriod = states.lastPeriod;
            require(params.period <= currentPeriod, 'FTR'); // Future period, or current period hasn't been updated
        }

        bytes32 _positionHash = positionHash(params.owner, params.index, params.tickLower, params.tickUpper);

        uint256 liquidity;
        uint256 boostedLiquidity;
        int160 secondsPerLiquidityPeriodStartX128;
        int160 secondsPerBoostedLiquidityPeriodStartX128;

        {
            PositionCheckpoint[] storage checkpoints = states.positionCheckpoints[_positionHash];

            // get checkpoint at period, or last checkpoint before the period
            (uint256 checkpointIndex, uint256 checkpointPeriod) = getCheckpoint(checkpoints, params.period);

            // Return 0s if checkpointPeriod is 0
            if (checkpointPeriod == 0) {
                return (0, 0);
            }

            liquidity = checkpoints[checkpointIndex].liquidity;
            // use period instead of checkpoint period for boosted liquidity because it needs to be renewed weekly
            boostedLiquidity = states.boostInfos[params.period].positions[_positionHash].boostAmount;

            secondsPerLiquidityPeriodStartX128 = states
                .boostInfos[params.period]
                .positions[_positionHash]
                .secondsPerLiquidityPeriodStartX128;
            secondsPerBoostedLiquidityPeriodStartX128 = states
                .boostInfos[params.period]
                .positions[_positionHash]
                .secondsPerBoostedLiquidityPeriodStartX128;
        }

        (uint160 secondsPerLiquidityInsideX128, uint160 secondsPerBoostedLiquidityInsideX128) = Oracle
            .periodCumulativesInside(uint32(params.period), params.tickLower, params.tickUpper);

        // underflow will be protected by sanity check
        secondsPerLiquidityInsideX128 = uint160(
            int160(secondsPerLiquidityInsideX128) - secondsPerLiquidityPeriodStartX128
        );

        secondsPerBoostedLiquidityInsideX128 = uint160(
            int160(secondsPerBoostedLiquidityInsideX128) - secondsPerBoostedLiquidityPeriodStartX128
        );

        BoostInfo storage boostPosition = states.boostInfos[params.period].positions[_positionHash];

        int256 secondsDebtX96 = boostPosition.secondsDebtX96;
        int256 boostedSecondsDebtX96 = boostPosition.boostedSecondsDebtX96;

        // addDelta checks for under and overflows
        periodSecondsInsideX96 = FullMath.mulDiv(liquidity, secondsPerLiquidityInsideX128, FixedPoint32.Q32);

        // Need to check if secondsDebtX96>periodSecondsInsideX96, since rounding can cause underflows
        if (secondsDebtX96 < 0 || periodSecondsInsideX96 > uint256(secondsDebtX96)) {
            periodSecondsInsideX96 = LiquidityMath.addDelta256(periodSecondsInsideX96, -secondsDebtX96);
        } else {
            periodSecondsInsideX96 = 0;
        }

        // addDelta checks for under and overflows
        periodBoostedSecondsInsideX96 = FullMath.mulDiv(
            boostedLiquidity,
            secondsPerBoostedLiquidityInsideX128,
            FixedPoint32.Q32
        );

        // Need to check if secondsDebtX96>periodSecondsInsideX96, since rounding can cause underflows
        if (boostedSecondsDebtX96 < 0 || periodBoostedSecondsInsideX96 > uint256(boostedSecondsDebtX96)) {
            periodBoostedSecondsInsideX96 = LiquidityMath.addDelta256(
                periodBoostedSecondsInsideX96,
                -boostedSecondsDebtX96
            );
        } else {
            periodBoostedSecondsInsideX96 = 0;
        }

        // sanity
        if (periodSecondsInsideX96 > 1 weeks * FixedPoint96.Q96) {
            periodSecondsInsideX96 = 0;
        }

        if (periodBoostedSecondsInsideX96 > 1 weeks * FixedPoint96.Q96) {
            periodBoostedSecondsInsideX96 = 0;
        }
        // require(periodSecondsInsideX96 <= 1 weeks * FixedPoint96.Q96);
        // require(periodBoostedSecondsInsideX96 <= 1 weeks * FixedPoint96.Q96);
    }
}

File 28 of 37 : ProtocolActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.8.0;
pragma abicoder v2;

import './States.sol';
import './TransferHelper.sol';
import '../interfaces/IClPoolFactory.sol';
import '../interfaces/pool/IClPoolOwnerActions.sol';
import '../interfaces/pool/IClPoolEvents.sol';

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

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

    event FeeAdjustment(uint24 oldFee, uint24 newFee);

    /// @notice Set the protocol's % share of the fees
    /// @dev Fees start at 50%, with 5% increments
    function setFeeProtocol() external {
        States.PoolStates storage states = States.getStorage();

        uint8 feeProtocolOld = states.slot0.feeProtocol;

        uint8 feeProtocol = IClPoolFactory(states.factory).poolFeeProtocol(address(this));

        if (feeProtocol != feeProtocolOld) {
            states.slot0.feeProtocol = feeProtocol;

            emit SetFeeProtocol(feeProtocolOld % 16, feeProtocolOld >> 4, feeProtocol % 16, feeProtocol >> 4);
        }
    }

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

        amount0 = amount0Requested > states.protocolFees.token0 ? states.protocolFees.token0 : amount0Requested;
        amount1 = amount1Requested > states.protocolFees.token1 ? states.protocolFees.token1 : amount1Requested;

        if (amount0 > 0) {
            if (amount0 == states.protocolFees.token0) amount0--; // ensure that the slot is not cleared, for gas savings
            states.protocolFees.token0 -= amount0;
            TransferHelper.safeTransfer(states.token0, recipient, amount0);
        }
        if (amount1 > 0) {
            if (amount1 == states.protocolFees.token1) amount1--; // ensure that the slot is not cleared, for gas savings
            states.protocolFees.token1 -= amount1;
            TransferHelper.safeTransfer(states.token1, recipient, amount1);
        }

        emit CollectProtocol(msg.sender, recipient, amount0, amount1);
    }

    function setFee(uint24 _fee) external {
        States.PoolStates storage states = States.getStorage();
        require(msg.sender == states.factory, 'AUTH');
        require(_fee <= 100000);
        uint24 _oldFee = states.fee;
        states.fee = _fee;
        emit FeeAdjustment(_oldFee, _fee);
    }
}

File 29 of 37 : SafeCast.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
    /// @notice Cast a uint256 to a uint128, revert on overflow
    /// @param y The uint256 to be downcasted
    /// @return z The downcasted integer, now type uint160
    function toUint128(uint256 y) internal pure returns (uint128 z) {
        require((z = uint128(y)) == y);
    }

    /// @notice Cast a uint256 to a uint160, revert on overflow
    /// @param y The uint256 to be downcasted
    /// @return z The downcasted integer, now type uint160
    function toUint160(uint256 y) internal pure returns (uint160 z) {
        require((z = uint160(y)) == y);
    }

    /// @notice Cast a int256 to a int128, revert on overflow or underflow
    /// @param y The int256 to be downcasted
    /// @return z The downcasted integer, now type int128
    function toInt128(int256 y) internal pure returns (int128 z) {
        require((z = int128(y)) == y);
    }

    /// @notice Cast a uint256 to a int256, revert on overflow
    /// @param y The uint256 to be casted
    /// @return z The casted integer, now type int256
    function toInt256(uint256 y) internal pure returns (int256 z) {
        require(y < 2 ** 255);
        z = int256(y);
    }
}

File 30 of 37 : SqrtPriceMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import './LowGasSafeMath.sol';
import './SafeCast.sol';

import './FullMath.sol';
import './UnsafeMath.sol';
import './FixedPoint96.sol';

/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
    using LowGasSafeMath for uint256;
    using SafeCast for uint256;

    /// @notice Gets the next sqrt price given a delta of token0
    /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
    /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
    /// price less in order to not send too much output.
    /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
    /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
    /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta
    /// @param liquidity The amount of usable liquidity
    /// @param amount How much of token0 to add or remove from virtual reserves
    /// @param add Whether to add or remove the amount of token0
    /// @return The price after adding or removing amount, depending on add
    function getNextSqrtPriceFromAmount0RoundingUp(
        uint160 sqrtPX96,
        uint128 liquidity,
        uint256 amount,
        bool add
    ) internal pure returns (uint160) {
        // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
        if (amount == 0) return sqrtPX96;
        uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;

        if (add) {
            uint256 product;
            if ((product = amount * sqrtPX96) / amount == sqrtPX96) {
                uint256 denominator = numerator1 + product;
                if (denominator >= numerator1)
                    // always fits in 160 bits
                    return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
            }

            return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));
        } else {
            uint256 product;
            // if the product overflows, we know the denominator underflows
            // in addition, we must check that the denominator does not underflow
            require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);
            uint256 denominator = numerator1 - product;
            return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
        }
    }

    /// @notice Gets the next sqrt price given a delta of token1
    /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
    /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
    /// price less in order to not send too much output.
    /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
    /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta
    /// @param liquidity The amount of usable liquidity
    /// @param amount How much of token1 to add, or remove, from virtual reserves
    /// @param add Whether to add, or remove, the amount of token1
    /// @return The price after adding or removing `amount`
    function getNextSqrtPriceFromAmount1RoundingDown(
        uint160 sqrtPX96,
        uint128 liquidity,
        uint256 amount,
        bool add
    ) internal pure returns (uint160) {
        // if we're adding (subtracting), rounding down requires rounding the quotient down (up)
        // in both cases, avoid a mulDiv for most inputs
        if (add) {
            uint256 quotient = (
                amount <= type(uint160).max
                    ? (amount << FixedPoint96.RESOLUTION) / liquidity
                    : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
            );

            return uint256(sqrtPX96).add(quotient).toUint160();
        } else {
            uint256 quotient = (
                amount <= type(uint160).max
                    ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
                    : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
            );

            require(sqrtPX96 > quotient);
            // always fits 160 bits
            return uint160(sqrtPX96 - quotient);
        }
    }

    /// @notice Gets the next sqrt price given an input amount of token0 or token1
    /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
    /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
    /// @param liquidity The amount of usable liquidity
    /// @param amountIn How much of token0, or token1, is being swapped in
    /// @param zeroForOne Whether the amount in is token0 or token1
    /// @return sqrtQX96 The price after adding the input amount to token0 or token1
    function getNextSqrtPriceFromInput(
        uint160 sqrtPX96,
        uint128 liquidity,
        uint256 amountIn,
        bool zeroForOne
    ) internal pure returns (uint160 sqrtQX96) {
        require(sqrtPX96 > 0);
        require(liquidity > 0);

        // round to make sure that we don't pass the target price
        return
            zeroForOne
                ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
                : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
    }

    /// @notice Gets the next sqrt price given an output amount of token0 or token1
    /// @dev Throws if price or liquidity are 0 or the next price is out of bounds
    /// @param sqrtPX96 The starting price before accounting for the output amount
    /// @param liquidity The amount of usable liquidity
    /// @param amountOut How much of token0, or token1, is being swapped out
    /// @param zeroForOne Whether the amount out is token0 or token1
    /// @return sqrtQX96 The price after removing the output amount of token0 or token1
    function getNextSqrtPriceFromOutput(
        uint160 sqrtPX96,
        uint128 liquidity,
        uint256 amountOut,
        bool zeroForOne
    ) internal pure returns (uint160 sqrtQX96) {
        require(sqrtPX96 > 0);
        require(liquidity > 0);

        // round to make sure that we pass the target price
        return
            zeroForOne
                ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
                : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
    }

    /// @notice Gets the amount0 delta between two prices
    /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
    /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
    /// @param sqrtRatioAX96 A sqrt price
    /// @param sqrtRatioBX96 Another sqrt price
    /// @param liquidity The amount of usable liquidity
    /// @param roundUp Whether to round the amount up or down
    /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices
    function getAmount0Delta(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity,
        bool roundUp
    ) internal pure returns (uint256 amount0) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
        uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;

        require(sqrtRatioAX96 > 0);

        return
            roundUp
                ? UnsafeMath.divRoundingUp(
                    FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),
                    sqrtRatioAX96
                )
                : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;
    }

    /// @notice Gets the amount1 delta between two prices
    /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
    /// @param sqrtRatioAX96 A sqrt price
    /// @param sqrtRatioBX96 Another sqrt price
    /// @param liquidity The amount of usable liquidity
    /// @param roundUp Whether to round the amount up, or down
    /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices
    function getAmount1Delta(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity,
        bool roundUp
    ) internal pure returns (uint256 amount1) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        return
            roundUp
                ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)
                : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
    }

    /// @notice Helper that gets signed token0 delta
    /// @param sqrtRatioAX96 A sqrt price
    /// @param sqrtRatioBX96 Another sqrt price
    /// @param liquidity The change in liquidity for which to compute the amount0 delta
    /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices
    function getAmount0Delta(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        int128 liquidity
    ) internal pure returns (int256 amount0) {
        return
            liquidity < 0
                ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
                : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
    }

    /// @notice Helper that gets signed token1 delta
    /// @param sqrtRatioAX96 A sqrt price
    /// @param sqrtRatioBX96 Another sqrt price
    /// @param liquidity The change in liquidity for which to compute the amount1 delta
    /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices
    function getAmount1Delta(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        int128 liquidity
    ) internal pure returns (int256 amount1) {
        return
            liquidity < 0
                ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
                : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
    }
}

File 31 of 37 : States.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.9.0;

import './../interfaces/IERC20Minimal.sol';

struct Slot0 {
    // the current price
    uint160 sqrtPriceX96;
    // the current tick
    int24 tick;
    // the most-recently updated index of the observations array
    uint16 observationIndex;
    // the current maximum number of observations that are being stored
    uint16 observationCardinality;
    // the next maximum number of observations to store, triggered in observations.write
    uint16 observationCardinalityNext;
    // the current protocol fee as a percentage of the swap fee taken on withdrawal
    // represented as an integer denominator (1/x)%
    uint8 feeProtocol;
    // whether the pool is locked
    bool unlocked;
}

struct Observation {
    // the block timestamp of the observation
    uint32 blockTimestamp;
    // the tick accumulator, i.e. tick * time elapsed since the pool was first initialized
    int56 tickCumulative;
    // the seconds per liquidity, i.e. seconds elapsed / max(1, liquidity) since the pool was first initialized
    uint160 secondsPerLiquidityCumulativeX128;
    // whether or not the observation is initialized
    bool initialized;
    // see secondsPerLiquidityCumulativeX128 but with boost, only valid if timestamp < new period
    // recorded at the end to not breakup struct slot
    uint160 secondsPerBoostedLiquidityPeriodX128;
    // the seconds boosted positions were in range in this period
    uint32 boostedInRange;
}

// info stored for each user's position
struct PositionInfo {
    // the amount of liquidity owned by this position
    uint128 liquidity;
    // fee growth per unit of liquidity as of the last update to liquidity or fees owed
    uint256 feeGrowthInside0LastX128;
    uint256 feeGrowthInside1LastX128;
    // the fees owed to the position owner in token0/token1
    uint128 tokensOwed0;
    uint128 tokensOwed1;
    uint256 attachedVeNftTokenId;
}

struct PeriodBoostInfo {
    // the total amount of boost this period has
    uint128 totalBoostAmount;
    // the total amount of veNFT attached to this period
    int128 totalVeNftAmount;
    // individual positions' boost info for this period
    mapping(bytes32 => BoostInfo) positions;
    // how a veNFT has been attached to this pool
    mapping(uint256 => VeNftInfo) veNftInfos;
}

struct VeNftInfo {
    // how many times a veNFT has been attached to this pool
    uint128 timesAttached;
    // boost ratio used, out of 1e18
    uint128 veNftBoostUsedRatio;
    // how much boost ratio is used by each position
    mapping(bytes32 => uint256) positionBoostUsedRatio;
}

struct BoostInfo {
    // the amount of boost this position has for this period
    uint128 boostAmount;
    // the amount of veNFT attached to this position for this period
    int128 veNftAmount;
    // used to account for changes in the boostAmount and veNFT locked during the period
    int256 boostedSecondsDebtX96;
    // used to account for changes in the deposit amount
    int256 secondsDebtX96;
    // used to check if starting seconds have already been written
    bool initialized;
    // used to account for changes in secondsPerLiquidity
    int160 secondsPerLiquidityPeriodStartX128;
    int160 secondsPerBoostedLiquidityPeriodStartX128;
}

// info stored for each initialized individual tick
struct TickInfo {
    // the total position liquidity that references this tick
    uint128 liquidityGross;
    // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left),
    int128 liquidityNet;
    // the total position boosted liquidity that references this tick
    uint128 cleanUnusedSlot;
    // clean unused slot
    int128 cleanUnusedSlot2;
    // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
    // only has relative meaning, not absolute — the value depends on when the tick is initialized
    uint256 feeGrowthOutside0X128;
    uint256 feeGrowthOutside1X128;
    // the cumulative tick value on the other side of the tick
    int56 tickCumulativeOutside;
    // the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick)
    // only has relative meaning, not absolute — the value depends on when the tick is initialized
    uint160 secondsPerLiquidityOutsideX128;
    // the seconds spent on the other side of the tick (relative to the current tick)
    // only has relative meaning, not absolute — the value depends on when the tick is initialized
    uint32 secondsOutside;
    // true iff the tick is initialized, i.e. the value is exactly equivalent to the expression liquidityGross != 0
    // these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks
    bool initialized;
    // secondsPerLiquidityOutsideX128 separated into periods, placed here to preserve struct slots
    mapping(uint256 => uint256) periodSecondsPerLiquidityOutsideX128;
    // see secondsPerLiquidityOutsideX128, for boosted liquidity
    mapping(uint256 => uint256) periodSecondsPerBoostedLiquidityOutsideX128;
    // the total position boosted liquidity that references this tick
    mapping(uint256 => uint128) boostedLiquidityGross;
    // period amount of net boosted liquidity added (subtracted) when tick is crossed from left to right (right to left),
    mapping(uint256 => int128) boostedLiquidityNet;
}

// info stored for each period
struct PeriodInfo {
    uint32 previousPeriod;
    int24 startTick;
    int24 lastTick;
    uint160 endSecondsPerLiquidityPeriodX128;
    uint160 endSecondsPerBoostedLiquidityPeriodX128;
    uint32 boostedInRange;
}

// accumulated protocol fees in token0/token1 units
struct ProtocolFees {
    uint128 token0;
    uint128 token1;
}

// Position period and liquidity
struct PositionCheckpoint {
    uint256 period;
    uint256 liquidity;
}

library States {
    bytes32 public constant STATES_SLOT = keccak256('states.storage');

    struct PoolStates {
        address factory;
        address nfpManager;
        address votingEscrow;
        address voter;
        address token0;
        address token1;
        uint24 fee;
        int24 tickSpacing;
        uint128 maxLiquidityPerTick;
        Slot0 slot0;
        mapping(uint256 => PeriodInfo) periods;
        uint256 lastPeriod;
        uint256 feeGrowthGlobal0X128;
        uint256 feeGrowthGlobal1X128;
        ProtocolFees protocolFees;
        uint128 liquidity;
        uint128 boostedLiquidity;
        mapping(int24 => TickInfo) _ticks;
        mapping(int16 => uint256) tickBitmap;
        mapping(bytes32 => PositionInfo) positions;
        mapping(uint256 => PeriodBoostInfo) boostInfos;
        mapping(bytes32 => uint256) cleanUnusedSlot;
        Observation[65535] observations;
        mapping(bytes32 => PositionCheckpoint[]) positionCheckpoints;
        uint24 initialFee;
        bool initialized;
    }

    // Return state storage struct for reading and writing
    function getStorage() internal pure returns (PoolStates storage storageStruct) {
        bytes32 position = STATES_SLOT;
        assembly {
            storageStruct.slot := position
        }
    }

    /// @dev Returns the block timestamp truncated to 32 bits, i.e. mod 2**32. This method is overridden in tests.
    function _blockTimestamp() internal view returns (uint32) {
        return uint32(block.timestamp); // truncation is desired
    }

    /// @dev Get the pool's balance of token0
    /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize
    /// check
    function balance0() internal view returns (uint256) {
        PoolStates storage states = getStorage();

        (bool success, bytes memory data) = states.token0.staticcall(
            abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this))
        );
        require(success && data.length >= 32);
        return abi.decode(data, (uint256));
    }

    /// @dev Get the pool's balance of token1
    /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize
    /// check
    function balance1() internal view returns (uint256) {
        PoolStates storage states = getStorage();

        (bool success, bytes memory data) = states.token1.staticcall(
            abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this))
        );
        require(success && data.length >= 32);
        return abi.decode(data, (uint256));
    }
}

File 32 of 37 : SwapMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import './FullMath.sol';
import './SqrtPriceMath.sol';

/// @title Computes the result of a swap within ticks
/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.
library SwapMath {
    /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap
    /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive
    /// @param sqrtRatioCurrentX96 The current sqrt price of the pool
    /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred
    /// @param liquidity The usable liquidity
    /// @param amountRemaining How much input or output amount is remaining to be swapped in/out
    /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip
    /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target
    /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap
    /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap
    /// @return feeAmount The amount of input that will be taken as a fee
    function computeSwapStep(
        uint160 sqrtRatioCurrentX96,
        uint160 sqrtRatioTargetX96,
        uint128 liquidity,
        int256 amountRemaining,
        uint24 feePips
    )
        internal
        pure
        returns (
            uint160 sqrtRatioNextX96,
            uint256 amountIn,
            uint256 amountOut,
            uint256 feeAmount
        )
    {
        bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;
        bool exactIn = amountRemaining >= 0;

        if (exactIn) {
            uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6);
            amountIn = zeroForOne
                ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)
                : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);
            if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96;
            else
                sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(
                    sqrtRatioCurrentX96,
                    liquidity,
                    amountRemainingLessFee,
                    zeroForOne
                );
        } else {
            amountOut = zeroForOne
                ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)
                : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);
            if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96;
            else
                sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(
                    sqrtRatioCurrentX96,
                    liquidity,
                    uint256(-amountRemaining),
                    zeroForOne
                );
        }

        bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;

        // get the input/output amounts
        if (zeroForOne) {
            amountIn = max && exactIn
                ? amountIn
                : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);
            amountOut = max && !exactIn
                ? amountOut
                : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);
        } else {
            amountIn = max && exactIn
                ? amountIn
                : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);
            amountOut = max && !exactIn
                ? amountOut
                : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);
        }

        // cap the output amount to not exceed the remaining output amount
        if (!exactIn && amountOut > uint256(-amountRemaining)) {
            amountOut = uint256(-amountRemaining);
        }

        if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {
            // we didn't reach the target, so take the remainder of the maximum input as fee
            feeAmount = uint256(amountRemaining) - amountIn;
        } else {
            feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips);
        }
    }
}

File 33 of 37 : Tick.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.8.0;
pragma abicoder v2;

import './LowGasSafeMath.sol';
import './SafeCast.sol';

import './TickMath.sol';
import './LiquidityMath.sol';
import './States.sol';

/// @title Tick
/// @notice Contains functions for managing tick processes and relevant calculations
library Tick {
    using LowGasSafeMath for int256;
    using SafeCast for int256;

    /// @notice Derives max liquidity per tick from given tick spacing
    /// @dev Executed within the pool constructor
    /// @param tickSpacing The amount of required tick separation, realized in multiples of `tickSpacing`
    ///     e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ...
    /// @return The max liquidity per tick
    function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) external pure returns (uint128) {
        int24 minTick = (TickMath.MIN_TICK / tickSpacing) * tickSpacing;
        int24 maxTick = (TickMath.MAX_TICK / tickSpacing) * tickSpacing;
        uint24 numTicks = uint24((maxTick - minTick) / tickSpacing) + 1;
        return type(uint128).max / numTicks;
    }

    /// @notice Retrieves fee growth data
    /// @param self The mapping containing all tick information for initialized ticks
    /// @param tickLower The lower tick boundary of the position
    /// @param tickUpper The upper tick boundary of the position
    /// @param tickCurrent The current tick
    /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0
    /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1
    /// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries
    /// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries
    function getFeeGrowthInside(
        mapping(int24 => TickInfo) storage self,
        int24 tickLower,
        int24 tickUpper,
        int24 tickCurrent,
        uint256 feeGrowthGlobal0X128,
        uint256 feeGrowthGlobal1X128
    ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) {
        TickInfo storage lower = self[tickLower];
        TickInfo storage upper = self[tickUpper];

        // calculate fee growth below
        uint256 feeGrowthBelow0X128;
        uint256 feeGrowthBelow1X128;
        if (tickCurrent >= tickLower) {
            feeGrowthBelow0X128 = lower.feeGrowthOutside0X128;
            feeGrowthBelow1X128 = lower.feeGrowthOutside1X128;
        } else {
            feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lower.feeGrowthOutside0X128;
            feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lower.feeGrowthOutside1X128;
        }

        // calculate fee growth above
        uint256 feeGrowthAbove0X128;
        uint256 feeGrowthAbove1X128;
        if (tickCurrent < tickUpper) {
            feeGrowthAbove0X128 = upper.feeGrowthOutside0X128;
            feeGrowthAbove1X128 = upper.feeGrowthOutside1X128;
        } else {
            feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upper.feeGrowthOutside0X128;
            feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upper.feeGrowthOutside1X128;
        }

        feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128;
        feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128;
    }

    /// @notice Retrieves fee growth data
    /// @param self The mapping containing all tick information for initialized ticks
    /// @param tickLower The lower tick boundary of the position
    /// @param tickUpper The upper tick boundary of the position
    /// @param tickCurrent The current tick
    /// @param endSecondsPerBoostedLiquidityPeriodX128 The seconds in range, per unit of liquidity
    /// @param period The period's timestamp
    /// @return secondsInsidePerBoostedLiquidityX128 The seconds per unit of liquidity, inside the position's tick boundaries
    function getSecondsInsidePerBoostedLiquidity(
        mapping(int24 => TickInfo) storage self,
        int24 tickLower,
        int24 tickUpper,
        int24 tickCurrent,
        uint256 endSecondsPerBoostedLiquidityPeriodX128,
        uint256 period
    ) external view returns (uint256 secondsInsidePerBoostedLiquidityX128) {
        TickInfo storage lower = self[tickLower];
        TickInfo storage upper = self[tickUpper];

        // calculate secondInside growth below
        uint256 secondsInsidePerBoostedLiquidityBelowX128;
        if (tickCurrent >= tickLower) {
            secondsInsidePerBoostedLiquidityBelowX128 = lower.periodSecondsPerBoostedLiquidityOutsideX128[period];
        } else {
            secondsInsidePerBoostedLiquidityBelowX128 =
                endSecondsPerBoostedLiquidityPeriodX128 -
                lower.periodSecondsPerBoostedLiquidityOutsideX128[period];
        }

        // calculate secondsInside growth above
        uint256 secondsInsidePerBoostedLiquidityAboveX128;
        if (tickCurrent < tickUpper) {
            secondsInsidePerBoostedLiquidityAboveX128 = upper.periodSecondsPerBoostedLiquidityOutsideX128[period];
        } else {
            secondsInsidePerBoostedLiquidityAboveX128 =
                endSecondsPerBoostedLiquidityPeriodX128 -
                upper.periodSecondsPerBoostedLiquidityOutsideX128[period];
        }

        secondsInsidePerBoostedLiquidityX128 =
            endSecondsPerBoostedLiquidityPeriodX128 -
            secondsInsidePerBoostedLiquidityBelowX128 -
            secondsInsidePerBoostedLiquidityAboveX128;
    }

    struct UpdateTickParams {
        // the tick that will be updated
        int24 tick;
        // the current tick
        int24 tickCurrent;
        // a new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left)
        int128 liquidityDelta;
        // a new amount of boosted liquidity to be added (subtracted) when tick is crossed from left to right (right to left)
        int128 boostedLiquidityDelta;
        // the all-time global fee growth, per unit of liquidity, in token0
        uint256 feeGrowthGlobal0X128;
        // the all-time global fee growth, per unit of liquidity, in token1
        uint256 feeGrowthGlobal1X128;
        // The all-time seconds per max(1, liquidity) of the pool
        uint160 secondsPerLiquidityCumulativeX128;
        // The period seconds per max(1, boostedLiquidity) of the pool
        uint160 secondsPerBoostedLiquidityPeriodX128;
        // the tick * time elapsed since the pool was first initialized
        int56 tickCumulative;
        // the current block timestamp cast to a uint32
        uint32 time;
        // true for updating a position's upper tick, or false for updating a position's lower tick
        bool upper;
        // the maximum liquidity allocation for a single tick
        uint128 maxLiquidity;
    }

    /// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa
    /// @param self The mapping containing all tick information for initialized ticks
    /// @param params the tick details and changes
    /// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa
    function update(
        mapping(int24 => TickInfo) storage self,
        UpdateTickParams memory params
    ) internal returns (bool flipped) {
        TickInfo storage info = self[params.tick];

        uint128 liquidityGrossBefore = info.liquidityGross;
        uint128 liquidityGrossAfter = LiquidityMath.addDelta(liquidityGrossBefore, params.liquidityDelta);

        require(liquidityGrossAfter <= params.maxLiquidity, 'LO');

        flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0);

        if (liquidityGrossBefore == 0) {
            // by convention, we assume that all growth before a tick was initialized happened _below_ the tick
            if (params.tick <= params.tickCurrent) {
                info.feeGrowthOutside0X128 = params.feeGrowthGlobal0X128;
                info.feeGrowthOutside1X128 = params.feeGrowthGlobal1X128;
                info.secondsPerLiquidityOutsideX128 = params.secondsPerLiquidityCumulativeX128;
                info.tickCumulativeOutside = params.tickCumulative;
                info.secondsOutside = params.time;
            }
            info.initialized = true;
        }

        info.liquidityGross = liquidityGrossAfter;
        info.boostedLiquidityGross[params.time / 1 weeks] = LiquidityMath.addDelta(
            info.boostedLiquidityGross[params.time / 1 weeks],
            params.boostedLiquidityDelta
        );

        // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed)
        info.liquidityNet = params.upper
            ? int256(info.liquidityNet).sub(params.liquidityDelta).toInt128()
            : int256(info.liquidityNet).add(params.liquidityDelta).toInt128();

        // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed)
        info.boostedLiquidityNet[params.time / 1 weeks] = params.upper
            ? int256(info.boostedLiquidityNet[params.time / 1 weeks]).sub(params.boostedLiquidityDelta).toInt128()
            : int256(info.boostedLiquidityNet[params.time / 1 weeks]).add(params.boostedLiquidityDelta).toInt128();
    }

    /// @notice Clears tick data
    /// @param self The mapping containing all initialized tick information for initialized ticks
    /// @param tick The tick that will be cleared
    function clear(mapping(int24 => TickInfo) storage self, int24 tick) internal {
        delete self[tick];
    }

    struct CrossParams {
        // The destination tick of the transition
        int24 tick;
        // The all-time global fee growth, per unit of liquidity, in token0
        uint256 feeGrowthGlobal0X128;
        // The all-time global fee growth, per unit of liquidity, in token1
        uint256 feeGrowthGlobal1X128;
        // The current seconds per liquidity
        uint160 secondsPerLiquidityCumulativeX128;
        // The current seconds per boosted liquidity
        uint160 secondsPerBoostedLiquidityCumulativeX128;
        // The previous period end's seconds per liquidity
        uint256 endSecondsPerLiquidityPeriodX128;
        // The previous period end's seconds per boosted liquidity
        uint256 endSecondsPerBoostedLiquidityPeriodX128;
        // The starting tick of the period
        int24 periodStartTick;
        // The tick * time elapsed since the pool was first initialized
        int56 tickCumulative;
        // The current block.timestamp
        uint32 time;
    }

    /// @notice Transitions to next tick as needed by price movement
    /// @param self The mapping containing all tick information for initialized ticks
    /// @param params Structured cross params
    /// @return liquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left)
    /// @return boostedLiquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left)
    function cross(
        mapping(int24 => TickInfo) storage self,
        CrossParams calldata params
    ) external returns (int128 liquidityNet, int128 boostedLiquidityNet) {
        TickInfo storage info = self[params.tick];
        uint256 period = params.time / 1 weeks;

        info.feeGrowthOutside0X128 = params.feeGrowthGlobal0X128 - info.feeGrowthOutside0X128;
        info.feeGrowthOutside1X128 = params.feeGrowthGlobal1X128 - info.feeGrowthOutside1X128;
        info.secondsPerLiquidityOutsideX128 =
            params.secondsPerLiquidityCumulativeX128 -
            info.secondsPerLiquidityOutsideX128;

        {
            uint256 periodSecondsPerLiquidityOutsideX128;
            uint256 periodSecondsPerLiquidityOutsideBeforeX128 = info.periodSecondsPerLiquidityOutsideX128[period];
            if (params.tick <= params.periodStartTick && periodSecondsPerLiquidityOutsideBeforeX128 == 0) {
                periodSecondsPerLiquidityOutsideX128 =
                    params.secondsPerLiquidityCumulativeX128 -
                    periodSecondsPerLiquidityOutsideBeforeX128 -
                    params.endSecondsPerLiquidityPeriodX128;
            } else {
                periodSecondsPerLiquidityOutsideX128 =
                    params.secondsPerLiquidityCumulativeX128 -
                    periodSecondsPerLiquidityOutsideBeforeX128;
            }
            info.periodSecondsPerLiquidityOutsideX128[period] = periodSecondsPerLiquidityOutsideX128;
        }
        {
            uint256 periodSecondsPerBoostedLiquidityOutsideX128;
            uint256 periodSecondsPerBoostedLiquidityOutsideBeforeX128 = info
                .periodSecondsPerBoostedLiquidityOutsideX128[period];
            if (params.tick <= params.periodStartTick && periodSecondsPerBoostedLiquidityOutsideBeforeX128 == 0) {
                periodSecondsPerBoostedLiquidityOutsideX128 =
                    params.secondsPerBoostedLiquidityCumulativeX128 -
                    params.endSecondsPerBoostedLiquidityPeriodX128;
            } else {
                periodSecondsPerBoostedLiquidityOutsideX128 =
                    params.secondsPerBoostedLiquidityCumulativeX128 -
                    periodSecondsPerBoostedLiquidityOutsideBeforeX128;
            }

            info.periodSecondsPerBoostedLiquidityOutsideX128[period] = periodSecondsPerBoostedLiquidityOutsideX128;
        }
        info.tickCumulativeOutside = params.tickCumulative - info.tickCumulativeOutside;
        info.secondsOutside = params.time - info.secondsOutside;
        liquidityNet = info.liquidityNet;
        boostedLiquidityNet = info.boostedLiquidityNet[period];
    }

    /// @dev Common checks for valid tick inputs.
    function checkTicks(int24 tickLower, int24 tickUpper) external pure {
        require(tickLower < tickUpper, 'TLU');
        require(tickLower >= TickMath.MIN_TICK, 'TLM');
        require(tickUpper <= TickMath.MAX_TICK, 'TUM');
    }
}

File 34 of 37 : TickBitmap.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <=0.7.6;

import './BitMath.sol';

/// @title Packed tick initialized state library
/// @notice Stores a packed mapping of tick index to its initialized state
/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.
library TickBitmap {
    /// @notice Computes the position in the mapping where the initialized bit for a tick lives
    /// @param tick The tick for which to compute the position
    /// @return wordPos The key in the mapping containing the word in which the bit is stored
    /// @return bitPos The bit position in the word where the flag is stored
    function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {
        wordPos = int16(tick >> 8);
        bitPos = uint8(tick % 256);
    }

    /// @notice Flips the initialized state for a given tick from false to true, or vice versa
    /// @param self The mapping in which to flip the tick
    /// @param tick The tick to flip
    /// @param tickSpacing The spacing between usable ticks
    function flipTick(mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing) internal {
        require(tick % tickSpacing == 0); // ensure that the tick is spaced
        (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing);
        uint256 mask = 1 << bitPos;
        self[wordPos] ^= mask;
    }

    /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either
    /// to the left (less than or equal to) or right (greater than) of the given tick
    /// @param self The mapping in which to compute the next initialized tick
    /// @param tick The starting tick
    /// @param tickSpacing The spacing between usable ticks
    /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)
    /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick
    /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks
    function nextInitializedTickWithinOneWord(
        mapping(int16 => uint256) storage self,
        int24 tick,
        int24 tickSpacing,
        bool lte
    ) internal view returns (int24 next, bool initialized) {
        int24 compressed = tick / tickSpacing;
        if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity

        if (lte) {
            (int16 wordPos, uint8 bitPos) = position(compressed);
            // all the 1s at or to the right of the current bitPos
            uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);
            uint256 masked = self[wordPos] & mask;

            // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word
            initialized = masked != 0;
            // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
            next = initialized
                ? (compressed - int24(bitPos - BitMath.mostSignificantBit(masked))) * tickSpacing
                : (compressed - int24(bitPos)) * tickSpacing;
        } else {
            // start from the word of the next tick, since the current tick state doesn't matter
            (int16 wordPos, uint8 bitPos) = position(compressed + 1);
            // all the 1s at or to the left of the bitPos
            uint256 mask = ~((1 << bitPos) - 1);
            uint256 masked = self[wordPos] & mask;

            // if there are no initialized ticks to the left of the current tick, return leftmost in the word
            initialized = masked != 0;
            // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
            next = initialized
                ? (compressed + 1 + int24(BitMath.leastSignificantBit(masked) - bitPos)) * tickSpacing
                : (compressed + 1 + int24(type(uint8).max - bitPos)) * tickSpacing;
        }
    }
}

File 35 of 37 : TickMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.8.0;

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
    /// @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 sqrtPriceX96 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 sqrtPriceX96) {
        uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
        require(absTick <= uint256(MAX_TICK), 'T');

        uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
        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 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
        if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;

        if (tick > 0) ratio = type(uint256).max / 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
        sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
    }

    /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
    /// ever return.
    /// @param sqrtPriceX96 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 sqrtPriceX96) internal pure returns (int24 tick) {
        // second inequality must be < because the price can never reach the price at the max tick
        require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
        uint256 ratio = uint256(sqrtPriceX96) << 32;

        uint256 r = ratio;
        uint256 msb = 0;

        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) <= sqrtPriceX96 ? tickHi : tickLow;
    }
}

File 36 of 37 : TransferHelper.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;

import '../interfaces/IERC20Minimal.sol';

/// @title TransferHelper
/// @notice Contains helper methods for interacting with ERC20 tokens that do not consistently return true/false
library TransferHelper {
    /// @notice Transfers tokens from msg.sender to a recipient
    /// @dev Calls transfer on token contract, errors with TF if transfer fails
    /// @param token The contract address of the token which will be transferred
    /// @param to The recipient of the transfer
    /// @param value The value of the transfer
    function safeTransfer(address token, address to, uint256 value) internal {
        (bool success, bytes memory data) = token.call(
            abi.encodeWithSelector(IERC20Minimal.transfer.selector, to, value)
        );
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'TF');
    }
}

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

/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
    /// @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 divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := add(div(x, y), gt(mod(x, y), 0))
        }
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 530
  },
  "metadata": {
    "bytecodeHash": "none"
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {
    "contracts/v2/libraries/Oracle.sol": {
      "Oracle": "0xe7f0bdbdaebbf97e70c1182bd861388597079178"
    },
    "contracts/v2/libraries/Position.sol": {
      "Position": "0xc66a64f8c1d14fa2e888cf67cf187782b9dabe80"
    },
    "contracts/v2/libraries/ProtocolActions.sol": {
      "ProtocolActions": "0xdba1ddc96d2df6850808f0317ceef773a74e565c"
    },
    "contracts/v2/libraries/Tick.sol": {
      "Tick": "0x7533a573b325589717ae145b7df69f023ebbd683"
    }
  }
}

Contract Security Audit

Contract ABI

[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"int24","name":"tickLower","type":"int24"},{"indexed":true,"internalType":"int24","name":"tickUpper","type":"int24"},{"indexed":false,"internalType":"uint128","name":"amount","type":"uint128"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":true,"internalType":"int24","name":"tickLower","type":"int24"},{"indexed":true,"internalType":"int24","name":"tickUpper","type":"int24"},{"indexed":false,"internalType":"uint128","name":"amount0","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"amount1","type":"uint128"}],"name":"Collect","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint128","name":"amount0","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"amount1","type":"uint128"}],"name":"CollectProtocol","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"paid0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"paid1","type":"uint256"}],"name":"Flash","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint16","name":"observationCardinalityNextOld","type":"uint16"},{"indexed":false,"internalType":"uint16","name":"observationCardinalityNextNew","type":"uint16"}],"name":"IncreaseObservationCardinalityNext","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"indexed":false,"internalType":"int24","name":"tick","type":"int24"}],"name":"Initialize","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"int24","name":"tickLower","type":"int24"},{"indexed":true,"internalType":"int24","name":"tickUpper","type":"int24"},{"indexed":false,"internalType":"uint128","name":"amount","type":"uint128"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"feeProtocol0Old","type":"uint8"},{"indexed":false,"internalType":"uint8","name":"feeProtocol1Old","type":"uint8"},{"indexed":false,"internalType":"uint8","name":"feeProtocol0New","type":"uint8"},{"indexed":false,"internalType":"uint8","name":"feeProtocol1New","type":"uint8"}],"name":"SetFeeProtocol","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"int256","name":"amount0","type":"int256"},{"indexed":false,"internalType":"int256","name":"amount1","type":"int256"},{"indexed":false,"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"indexed":false,"internalType":"uint128","name":"liquidity","type":"uint128"},{"indexed":false,"internalType":"int24","name":"tick","type":"int24"}],"name":"Swap","type":"event"},{"inputs":[],"name":"_advancePeriod","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"period","type":"uint256"}],"name":"boostInfos","outputs":[{"internalType":"uint128","name":"totalBoostAmount","type":"uint128"},{"internalType":"int128","name":"totalVeNftAmount","type":"int128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"period","type":"uint256"},{"internalType":"bytes32","name":"key","type":"bytes32"}],"name":"boostInfos","outputs":[{"internalType":"uint128","name":"boostAmount","type":"uint128"},{"internalType":"int128","name":"veNftAmount","type":"int128"},{"internalType":"int256","name":"secondsDebtX96","type":"int256"},{"internalType":"int256","name":"boostedSecondsDebtX96","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"boostedLiquidity","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint128","name":"amount","type":"uint128"}],"name":"burn","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint128","name":"amount","type":"uint128"}],"name":"burn","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint128","name":"amount","type":"uint128"},{"internalType":"uint256","name":"veNftTokenId","type":"uint256"}],"name":"burn","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint128","name":"amount0Requested","type":"uint128"},{"internalType":"uint128","name":"amount1Requested","type":"uint128"}],"name":"collect","outputs":[{"internalType":"uint128","name":"amount0","type":"uint128"},{"internalType":"uint128","name":"amount1","type":"uint128"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint128","name":"amount0Requested","type":"uint128"},{"internalType":"uint128","name":"amount1Requested","type":"uint128"}],"name":"collect","outputs":[{"internalType":"uint128","name":"amount0","type":"uint128"},{"internalType":"uint128","name":"amount1","type":"uint128"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint128","name":"amount0Requested","type":"uint128"},{"internalType":"uint128","name":"amount1Requested","type":"uint128"}],"name":"collectProtocol","outputs":[{"internalType":"uint128","name":"amount0","type":"uint128"},{"internalType":"uint128","name":"amount1","type":"uint128"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"currentFee","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"fee","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeGrowthGlobal0X128","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeGrowthGlobal1X128","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"flash","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"observationCardinalityNext","type":"uint16"}],"name":"increaseObservationCardinalityNext","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_factory","type":"address"},{"internalType":"address","name":"_nfpManager","type":"address"},{"internalType":"address","name":"_votingEscrow","type":"address"},{"internalType":"address","name":"_voter","type":"address"},{"internalType":"address","name":"_token0","type":"address"},{"internalType":"address","name":"_token1","type":"address"},{"internalType":"uint24","name":"_fee","type":"uint24"},{"internalType":"int24","name":"_tickSpacing","type":"int24"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"lastPeriod","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"liquidity","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxLiquidityPerTick","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint128","name":"amount","type":"uint128"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"mint","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint128","name":"amount","type":"uint128"},{"internalType":"uint256","name":"veNftTokenId","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"mint","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"nfpManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"name":"observations","outputs":[{"internalType":"uint32","name":"blockTimestamp","type":"uint32"},{"internalType":"int56","name":"tickCumulative","type":"int56"},{"internalType":"uint160","name":"secondsPerLiquidityCumulativeX128","type":"uint160"},{"internalType":"bool","name":"initialized","type":"bool"},{"internalType":"uint160","name":"secondsPerBoostedLiquidityPeriodX128","type":"uint160"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32[]","name":"secondsAgos","type":"uint32[]"}],"name":"observe","outputs":[{"internalType":"int56[]","name":"tickCumulatives","type":"int56[]"},{"internalType":"uint160[]","name":"secondsPerLiquidityCumulativeX128s","type":"uint160[]"},{"internalType":"uint160[]","name":"secondsPerBoostedLiquidityPeriodX128s","type":"uint160[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"period","type":"uint32"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"}],"name":"periodCumulativesInside","outputs":[{"internalType":"uint160","name":"secondsPerLiquidityInsideX128","type":"uint160"},{"internalType":"uint160","name":"secondsPerBoostedLiquidityInsideX128","type":"uint160"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"period","type":"uint256"}],"name":"periods","outputs":[{"internalType":"uint32","name":"previousPeriod","type":"uint32"},{"internalType":"int24","name":"startTick","type":"int24"},{"internalType":"int24","name":"lastTick","type":"int24"},{"internalType":"uint160","name":"endSecondsPerLiquidityPeriodX128","type":"uint160"},{"internalType":"uint160","name":"endSecondsPerBoostedLiquidityPeriodX128","type":"uint160"},{"internalType":"uint32","name":"boostedInRange","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"period","type":"uint256"},{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"}],"name":"positionPeriodDebt","outputs":[{"internalType":"int256","name":"secondsDebtX96","type":"int256"},{"internalType":"int256","name":"boostedSecondsDebtX96","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"period","type":"uint256"},{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"}],"name":"positionPeriodSecondsInRange","outputs":[{"internalType":"uint256","name":"periodSecondsInsideX96","type":"uint256"},{"internalType":"uint256","name":"periodBoostedSecondsInsideX96","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"key","type":"bytes32"}],"name":"positions","outputs":[{"internalType":"uint128","name":"","type":"uint128"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint128","name":"","type":"uint128"},{"internalType":"uint128","name":"","type":"uint128"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolFees","outputs":[{"internalType":"uint128","name":"","type":"uint128"},{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32[]","name":"slots","type":"bytes32[]"}],"name":"readStorage","outputs":[{"internalType":"bytes32[]","name":"returnData","type":"bytes32[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint24","name":"_fee","type":"uint24"}],"name":"setFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"setFeeProtocol","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"slot0","outputs":[{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"internalType":"int24","name":"tick","type":"int24"},{"internalType":"uint16","name":"observationIndex","type":"uint16"},{"internalType":"uint16","name":"observationCardinality","type":"uint16"},{"internalType":"uint16","name":"observationCardinalityNext","type":"uint16"},{"internalType":"uint8","name":"feeProtocol","type":"uint8"},{"internalType":"bool","name":"unlocked","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"}],"name":"snapshotCumulativesInside","outputs":[{"internalType":"int56","name":"tickCumulativeInside","type":"int56"},{"internalType":"uint160","name":"secondsPerLiquidityInsideX128","type":"uint160"},{"internalType":"uint160","name":"secondsPerBoostedLiquidityInsideX128","type":"uint160"},{"internalType":"uint32","name":"secondsInside","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"int256","name":"amountSpecified","type":"int256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"swap","outputs":[{"internalType":"int256","name":"amount0","type":"int256"},{"internalType":"int256","name":"amount1","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"int16","name":"tick","type":"int16"}],"name":"tickBitmap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tickSpacing","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int24","name":"tick","type":"int24"}],"name":"ticks","outputs":[{"internalType":"uint128","name":"liquidityGross","type":"uint128"},{"internalType":"int128","name":"liquidityNet","type":"int128"},{"internalType":"uint128","name":"boostedLiquidityGross","type":"uint128"},{"internalType":"int128","name":"boostedLiquidityNet","type":"int128"},{"internalType":"uint256","name":"feeGrowthOutside0X128","type":"uint256"},{"internalType":"uint256","name":"feeGrowthOutside1X128","type":"uint256"},{"internalType":"int56","name":"tickCumulativeOutside","type":"int56"},{"internalType":"uint160","name":"secondsPerLiquidityOutsideX128","type":"uint160"},{"internalType":"uint32","name":"secondsOutside","type":"uint32"},{"internalType":"bool","name":"initialized","type":"bool"}],"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":"voter","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"votingEscrow","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"}]

60806040527f568f905fee3c29dbecf3583ddfaf086f7336b6bee88b499cc887c595fb7bf1da60005534801561003457600080fd5b50615fb680620000456000396000f3fe608060405234801561001057600080fd5b50600436106102ea5760003560e01c806398bbc3c71161018c578063d21220a7116100ee578063e57c0ca911610097578063f305839911610071578063f305839914610662578063f30dba931461066a578063f637731d14610693576102ea565b8063e57c0ca91461060a578063ea4a11041461062a578063eabb56221461064f576102ea565b8063ddca3f43116100c8578063ddca3f43146105dc578063dfc8b615146105e4578063e3f9b398146105f7576102ea565b8063d21220a7146105b7578063d340ef8a146105bf578063da3c300d146105c7576102ea565b8063a38807f211610150578063c2e0f9b21161012a578063c2e0f9b214610592578063c45a01551461059a578063d0c93a7c146105a2576102ea565b8063a38807f21461053b578063a418e9e01461055e578063add5887e14610571576102ea565b806398bbc3c7146104f25780639918fbb6146104fa5780639fdb26161461050d578063a02f106914610515578063a34123a714610528576102ea565b80634860e05f116102505780635fa9c925116101f95780637b7d549d116101d35780637b7d549d146104b557806385b66729146104bd578063883bdbfd146104d0576102ea565b80635fa9c925146104875780636847456a1461049a57806370cf754a146104ad576102ea565b80634f2bfe5b1161022a5780634f2bfe5b14610447578063514ea4bf1461044f5780635339c29614610474576102ea565b80634860e05f146103fe578063490e6cbc146104215780634f1eb3d814610434576102ea565b8063252c09d7116102b25780633c8a7d8d1161028c5780633c8a7d8d146103ce57806346141319146103e157806346c96aac146103f6576102ea565b8063252c09d71461037a57806332148f671461039e5780633850c7bd146103b3576102ea565b80630d63237f146102ef5780630dfe168114610319578063128acb081461032e5780631a6865021461034f5780631ad8b03b14610364575b600080fd5b6103026102fd366004615103565b6106a6565b604051610310929190615c91565b60405180910390f35b6103216106e0565b604051610310919061563a565b61034161033c366004614cdc565b6106fc565b604051610310929190615916565b610357611504565b6040516103109190615c7d565b61036c611520565b604051610310929190615d42565b61038d610388366004615103565b611566565b604051610310959493929190615ee2565b6103b16103ac36600461530f565b61162a565b005b6103bb611757565b6040516103109796959493929190615dd4565b6103416103dc366004614d63565b61180f565b6103e9611835565b6040516103109190615e5c565b610321611848565b61041161040c366004615472565b611864565b6040516103109493929190615cad565b6103b161042f366004614f77565b61191b565b61036c610442366004614db2565b611c74565b610321611c95565b61046261045d366004615103565b611cb1565b60405161031096959493929190615d7d565b6103e961048236600461514d565b611d46565b6103b1610495366004614c3a565b611d73565b6103416104a8366004615493565b611f1e565b610357611f3d565b6103b1611f59565b61036c6104cb366004614e1e565b611fc7565b6104e36104de366004614fdf565b612117565b604051610310939291906156eb565b610321612231565b61034161050836600461541a565b61224d565b610357612319565b61036c610523366004614e68565b61233c565b6103416105363660046151b1565b612555565b61054e610549366004615188565b612574565b604051610310949392919061597c565b61034161056c366004614edc565b612687565b61058461057f36600461554f565b612913565b604051610310929190615e1d565b6103b16129a0565b610321612cf7565b6105aa612d10565b60405161031091906158f4565b610321612d2d565b6103e9612d49565b6105cf612d5c565b6040516103109190615e4c565b6105cf612d7b565b6103416105f236600461541a565b612d95565b6103416106053660046154d6565b612e60565b61061d610618366004614fdf565b613009565b60405161031091906156a7565b61063d610638366004615103565b6130a2565b60405161031096959493929190615ea2565b6103b161065d366004615400565b613156565b6103e96131b9565b61067d61067836600461516e565b6131cc565b6040516103109a99989796959493929190615cd6565b6103b16106a136600461532b565b613319565b60008060006106b36134fe565b600094855260110160205250506040909120546001600160801b03811692600160801b909104600f0b9150565b60006106ea6134fe565b600401546001600160a01b0316905090565b6000806107076129a0565b60006107116134fe565b9050866107395760405162461bcd60e51b815260040161073090615aa6565b60405180910390fd5b6040805160e08101825260078301546001600160a01b0381168252600160a01b8104600290810b810b900b602083015261ffff600160b81b8204811693830193909352600160c81b810483166060830152600160d81b8104909216608082015260ff600160e81b8304811660a0830152600160f01b909204909116151560c082018190526107d95760405162461bcd60e51b815260040161073090615ba4565b886108245780600001516001600160a01b0316876001600160a01b031611801561081f575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038816105b610856565b80600001516001600160a01b0316876001600160a01b031610801561085657506401000276a36001600160a01b038816115b6108725760405162461bcd60e51b815260040161073090615b6b565b60078201805460ff60f01b1916905561088961496e565b6108916149c2565b600062093a8061089f613522565b63ffffffff16816108ac57fe5b604080516101408101825260a088015160ff168152600d8901546001600160801b038082166020840152600160801b909104169181019190915291900463ffffffff169150606081016108fd613522565b63ffffffff168152602001600060060b815260200160006001600160a01b0316815260200160006001600160a01b0316815260200160001515815260200160008d131515815260200186600801600084815260200190815260200160002060000160009054906101000a900463ffffffff1663ffffffff1681525092506040518061016001604052808c81526020016000815260200185600001516001600160a01b03168152602001856020015160020b81526020018d6109c25786600b01546109c8565b86600a01545b815260006020808301829052868101516001600160801b039081166040808601919091528881015190911660608501526101208801805163ffffffff908116855260088c01808552838620546001600160a01b03600160501b90910481166080890152925190911685528084528285206001015490911660a086015295835294905292909220546401000000009004600290810b900b60c09092019190915290505b805115801590610a905750886001600160a01b031681604001516001600160a01b031614155b1561102757610a9d614a1e565b60408201516001600160a01b0316815260608201516005860154610ad091600f880191600160b81b900460020b8f613526565b15156040830152600290810b810b60208301819052620d89e719910b1215610b0157620d89e7196020820152610b20565b6020810151620d89e860029190910b1315610b2057620d89e860208201525b610b2d8160200151613668565b6001600160a01b031660608201526040820151610bae908d610b67578b6001600160a01b031683606001516001600160a01b031611610b81565b8b6001600160a01b031683606001516001600160a01b0316105b610b8f578260600151610b91565b8b5b60c0850151855160058a0154600160a01b900462ffffff1661399a565b60c085015260a084015260808301526001600160a01b0316604083015261010083015115610c1557610be98160c00151826080015101613b8c565b825103825260a0810151610c0b90610c0090613b8c565b602084015190613ba2565b6020830152610c50565b610c228160a00151613b8c565b825101825260c08101516080820151610c4a91610c3f9101613b8c565b602084015190613bbe565b60208301525b825160ff1615610c995760006064846000015160ff168360c001510281610c7357fe5b60c0840180519290910491829003905260a0840180519091016001600160801b03169052505b60c08201516001600160801b031615610cd857610ccc8160c00151600160801b8460c001516001600160801b0316613bd4565b60808301805190910190525b80606001516001600160a01b031682604001516001600160a01b03161415610fe657806040015115610fbd578260e00151610de85773e7f0bdbdaebbf97e70c1182bd86138859707917863d6b4bf9786601301856060015160008860200151896040015189602001518a604001518c606001516040518963ffffffff1660e01b8152600401610d6e9897969594939291906158a1565b60606040518083038186803b158015610d8657600080fd5b505af4158015610d9a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dbe91906151dc565b6001600160a01b0390811660c08701521660a0850152600690810b900b6080840152600160e08401525b610df0614a5a565b8c15610e0f5760808301516040820152600b8601546060820152610e24565b600a8601546040820152608083015160608201525b737533a573b325589717ae145b7df69f023ebbd68363bf7ca94e87600e01604051806101400160405280866020015160020b815260200185604001518152602001856060015181526020018860a001516001600160a01b031681526020018860c001516001600160a01b031681526020018761010001518152602001876101200151815260200187610140015160020b8152602001886080015160060b8152602001886060015163ffffffff168152506040518363ffffffff1660e01b8152600401610ef19291906159de565b604080518083038186803b158015610f0857600080fd5b505af4158015610f1c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f40919061511b565b600f90810b810b602084015290810b900b81528c15610f795780516000908103600f90810b810b8352602083018051909203810b900b90525b610f8b8360c001518260000151613c84565b6001600160801b031660c084015260e08301516020820151610fad9190613c84565b6001600160801b031660e0840152505b8b610fcc578060200151610fd5565b60018160200151035b600290810b900b6060830152611021565b80600001516001600160a01b031682604001516001600160a01b031614611021576110148260400151613d3a565b600290810b900b60608301525b50610a6a565b826020015160020b816060015160020b146111745760008073e7f0bdbdaebbf97e70c1182bd8613885970791786334ef26e68760130187604001518760600151896020015189602001518a604001518c606001518d608001516040518963ffffffff1660e01b81526004016110a39897969594939291906157a2565b604080518083038186803b1580156110ba57600080fd5b505af41580156110ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110f291906153d2565b6040850151606086015160078a01805461ffff60c81b1916600160c81b61ffff958616021761ffff60b81b1916600160b81b95909416949094029290921762ffffff60a01b1916600160a01b62ffffff60029490940b9390931692909202919091176001600160a01b0319166001600160a01b039091161790555061119b9050565b60408101516007850180546001600160a01b0319166001600160a01b039092169190911790555b8060c001516001600160801b031682602001516001600160801b0316146111e35760c0810151600d850180546001600160801b0319166001600160801b039092169190911790555b8060e001516001600160801b031682604001516001600160801b0316146112295760e0810151600d850180546001600160801b03928316600160801b0292169190911790555b8a1561127d576080810151600a85015560a08101516001600160801b0316156112785760a0810151600c850180546001600160801b031981166001600160801b03918216909301169190911790555b6112c7565b6080810151600b85015560a08101516001600160801b0316156112c75760a0810151600c850180546001600160801b03808216600160801b92839004821690940116029190911790555b81610100015115158b1515146112e557602081015181518b036112f2565b80600001518a0381602001515b90965094508a156113c1576000851215611323576005840154611323906001600160a01b03168d6000889003614062565b600061132d6141a9565b60405163654b648760e01b8152909150339063654b648790611359908a908a908e908e90600401615924565b600060405180830381600087803b15801561137357600080fd5b505af1158015611387573d6000803e3d6000fd5b505050506113936141a9565b61139d82896142ce565b11156113bb5760405162461bcd60e51b815260040161073090615bc1565b50611481565b60008612156113e75760048401546113e7906001600160a01b03168d6000899003614062565b60006113f16142de565b60405163654b648760e01b8152909150339063654b64879061141d908a908a908e908e90600401615924565b600060405180830381600087803b15801561143757600080fd5b505af115801561144b573d6000803e3d6000fd5b505050506114576142de565b61146182886142ce565b111561147f5760405162461bcd60e51b815260040161073090615bc1565b505b8b6001600160a01b0316336001600160a01b03167fc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67888885604001518660c0015187606001516040516114d8959493929190615944565b60405180910390a3505050600701805460ff60f01b1916600160f01b1790559097909650945050505050565b600061150e6134fe565b600d01546001600160801b0316905090565b600080600061152d6134fe565b60408051808201909152600c91909101546001600160801b03808216808452600160801b90920416602090920182905293509150509091565b6000806000806000806115776134fe565b6013018761ffff811061158657fe5b6040805160c08101825260029290920292909201805463ffffffff8082168085526401000000008304600690810b810b900b602086018190526b01000000000000000000000084046001600160a01b03908116978701889052600160f81b90940460ff1615156060870181905260019095015493841660808701819052600160a01b90940490921660a090950194909452929b929a50929850965090945092505050565b611632614361565b600061163c6134fe565b6007810154604051630e51299960e01b8152919250600160d81b900461ffff169060009073e7f0bdbdaebbf97e70c1182bd86138859707917890630e512999906116919060138701908690899060040161576e565b60206040518083038186803b1580156116a957600080fd5b505af41580156116bd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116e191906153b6565b60078401805461ffff808416600160d81b810261ffff60d81b1990931692909217909255919250831614611749577fac49e518f90a358f652e4400164f05a5d8f7e35e7747279bc3a93dbf584e125a8282604051611740929190615e37565b60405180910390a15b5050506117546143a9565b50565b60008060008060008060008061176b6134fe565b6040805160e081018252600792909201546001600160a01b038116808452600160a01b8204600290810b810b900b6020850181905261ffff600160b81b84048116948601859052600160c81b8404811660608701819052600160d81b85049091166080870181905260ff600160e81b8604811660a08901819052600160f01b90960416151560c0909701879052929e919d50939b5092995097509550909350915050565b6000806118258860008989896000198a8a612687565b915091505b965096945050505050565b600061183f6134fe565b600b0154905090565b60006118526134fe565b600301546001600160a01b0316905090565b60008060008060006118746134fe565b6000978852601101602090815260408089209789526001978801825297889020885160e081018a5281546001600160801b038116808352600160801b909104600f90810b810b900b938201849052988201549981018a9052600282015460608201819052600383015460ff8116151560808401526101009004601390810b810b810b60a0840152600490930154830b830b90920b60c0909101529698909795509350505050565b611923614361565b600061192d6134fe565b600d8101549091506001600160801b03168061195b5760405162461bcd60e51b815260040161073090615afa565b600582015460009061197e908890600160a01b900462ffffff16620f42406143d2565b60058401549091506000906119a4908890600160a01b900462ffffff16620f42406143d2565b905060006119b06141a9565b905060006119bc6142de565b905089156119dd5760048601546119dd906001600160a01b03168c8c614062565b88156119fc5760058601546119fc906001600160a01b03168c8b614062565b604051633797d3b360e21b8152339063de5f4ecc90611a2590879087908d908d90600401615924565b600060405180830381600087803b158015611a3f57600080fd5b505af1158015611a53573d6000803e3d6000fd5b50505050611a5f614a88565b611a676141a9565b8152611a716142de565b60208201528051611a8284876142ce565b1115611a8d57600080fd5b6020810151611a9c83866142ce565b1115611aba5760405162461bcd60e51b815260040161073090615ac2565b611ac2614a88565b81518490038082526020808401518590039083015215611b67576007880154600160e81b900460ff1660008115611b0357825160649060ff84160204611b06565b60005b90506001600160801b03811615611b3b57600c8a0180546001600160801b038082168401166001600160801b03199091161790555b611b5981846000015103600160801b8b6001600160801b0316613bd4565b600a8b018054909101905550505b602081015115611c04576007880154600160e81b900460ff1660008115611ba15760648260ff1684602001510281611b9b57fe5b04611ba4565b60005b90506001600160801b03811615611bd857600c8a0180546001600160801b03600160801b8083048216850182160291161790555b611bf681846020015103600160801b8b6001600160801b0316613bd4565b600b8b018054909101905550505b8c6001600160a01b0316336001600160a01b03167fbdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca6338e8e85600001518660200151604051611c559493929190615e65565b60405180910390a35050505050505050611c6d6143a9565b5050505050565b600080611c868760008888888861233c565b915091505b9550959350505050565b6000611c9f6134fe565b600201546001600160a01b0316905090565b6000806000806000806000611cc46134fe565b60009889526010016020908152604098899020895160c081018b5281546001600160801b03908116808352600184015494830185905260028401549c83018d9052600384015480831660608501819052600160801b9091049092166080840181905260049094015460a09093018390529c939b9a509850909650945092505050565b6000611d506134fe565b600f0160008360010b60010b81526020019081526020016000205490505b919050565b6000611d7d6134fe565b620200128101549091506301000000900460ff1615611d9b57600080fd5b80546001600160a01b03199081166001600160a01b038b811691909117835560018301805483168b83161790556002808401805484168b841617905560038401805484168a84161790556004808501805485168a8516179055600585018054620200128701805462ffffff8b811662ffffff19909216821790925591909616948a169490941762ffffff60a01b1916600160a01b9094029390931762ffffff60b81b1916600160b81b9287900b909416919091029290921790556040516382c66f8760e01b8152737533a573b325589717ae145b7df69f023ebbd683916382c66f8791611e8a918691016158f4565b60206040518083038186803b158015611ea257600080fd5b505af4158015611eb6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611eda91906152ba565b6006820180546001600160801b03929092166001600160801b03199092169190911790556202001201805463ff000000191663010000001790555050505050505050565b600080611f3086868686600019612e60565b9150915094509492505050565b6000611f476134fe565b600601546001600160801b0316905090565b611f61614361565b73dba1ddc96d2df6850808f0317ceef773a74e565c637b7d549d6040518163ffffffff1660e01b815260040160006040518083038186803b158015611fa557600080fd5b505af4158015611fb9573d6000803e3d6000fd5b50505050611fc56143a9565b565b600080611fd2614361565b6000611fdc6134fe565b8054604080516331056e5760e21b815290519293506001600160a01b039091169163c415b95c91600480820192602092909190829003018186803b15801561202357600080fd5b505afa158015612037573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061205b9190614c1e565b6001600160a01b0316336001600160a01b03161461207857600080fd5b6040516385b6672960e01b815273dba1ddc96d2df6850808f0317ceef773a74e565c906385b66729906120b39089908990899060040161567d565b604080518083038186803b1580156120ca57600080fd5b505af41580156120de573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061210291906152d6565b925092505061210f6143a9565b935093915050565b606080606060006121266134fe565b905073e7f0bdbdaebbf97e70c1182bd86138859707917863192409788260130161214e613522565b6007850154600d8601546040517fffffffff0000000000000000000000000000000000000000000000000000000060e087901b1681526121cf9493928d928d92600160a01b830460020b9261ffff600160b81b82048116936001600160801b0380821694600160801b9092041692600160c81b9004909116906004016157f3565b60006040518083038186803b1580156121e757600080fd5b505af41580156121fb573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052612223919081019061501f565b935093509350509250925092565b600061223b6134fe565b600101546001600160a01b0316905090565b60008073c66a64f8c1d14fa2e888cf67cf187782b9dabe8063d2e6311b6040518060a001604052808a8152602001896001600160a01b031681526020018881526020018760020b81526020018660020b8152506040518263ffffffff1660e01b81526004016122bc9190615c34565b604080518083038186803b1580156122d357600080fd5b505af41580156122e7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061230b919061552c565b909890975095505050505050565b60006123236134fe565b600d0154600160801b90046001600160801b0316919050565b600080612347614361565b60006123516134fe565b9050600073c66a64f8c1d14fa2e888cf67cf187782b9dabe80639c766c9d83601001338c8c8c6040518663ffffffff1660e01b81526004016123979594939291906159ac565b60206040518083038186803b1580156123af57600080fd5b505af41580156123c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123e79190615275565b60038101549091506001600160801b03908116908716116124085785612417565b60038101546001600160801b03165b60038201549094506001600160801b03600160801b90910481169086161161243f5784612455565b6003810154600160801b90046001600160801b03165b92506001600160801b038416156124a9576003810180546001600160801b031981166001600160801b0391821687900382161790915560048301546124a9916001600160a01b03909116908c908716614062565b6001600160801b038316156124fe576003810180546001600160801b03600160801b80830482168790038216029181169190911790915560058301546124fe916001600160a01b03909116908c908616614062565b8660020b8860020b336001600160a01b03167f70935338e69775456a85ddef226c395fb668b63fa0115f5f20610b388e6ca9c08d88886040516125439392919061567d565b60405180910390a4505061182a6143a9565b6000806125686000868686600019612e60565b91509150935093915050565b6000806000808460020b8660020b1261259f5760405162461bcd60e51b815260040161073090615a89565b620d89e719600287900b12156125c75760405162461bcd60e51b815260040161073090615b4e565b620d89e8600286900b13156125ee5760405162461bcd60e51b815260040161073090615b15565b6040516351c403f960e11b815273e7f0bdbdaebbf97e70c1182bd8613885970791789063a38807f2906126279089908990600401615902565b60806040518083038186803b15801561263f57600080fd5b505af4158015612653573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612677919061521a565b9299919850965090945092505050565b600080612692614361565b61269a6129a0565b6000866001600160801b0316116126b057600080fd5b60001985146126ce576001600160a01b038a1633146126ce57600080fd5b6126d6614a88565b73c66a64f8c1d14fa2e888cf67cf187782b9dabe806368e5d9076040518060c001604052808e6001600160a01b031681526020018d81526020018c60020b81526020018b60020b81526020016127348b6001600160801b031661440c565b600f0b8152602001898152506040518263ffffffff1660e01b815260040161275c9190615bde565b60606040518083038186803b15801561277457600080fd5b505af4158015612788573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127ac919061528d565b602084018190528184529094509250600090508084156127d1576127ce6141a9565b91505b83156127e2576127df6142de565b90505b604051633e48f41760e01b81523390633e48f4179061280b90889088908c908c90600401615924565b600060405180830381600087803b15801561282557600080fd5b505af1158015612839573d6000803e3d6000fd5b5050505060008511156128765761284e6141a9565b61285883876142ce565b11156128765760405162461bcd60e51b815260040161073090615b32565b83156128ac576128846142de565b61288e82866142ce565b11156128ac5760405162461bcd60e51b815260040161073090615b88565b8960020b8b60020b8e6001600160a01b03167f7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde338d8a8a6040516128f3949392919061564e565b60405180910390a45050506129066143a9565b9850989650505050505050565b60008073e7f0bdbdaebbf97e70c1182bd86138859707917863add5887e8686866040518463ffffffff1660e01b815260040161295193929190615e80565b604080518083038186803b15801561296857600080fd5b505af415801561297c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125689190615347565b60006129aa6134fe565b60098101549091508062093a806129bf613522565b63ffffffff16816129cc57fe5b0463ffffffff1614612cf3576040805160e08101825260078401546001600160a01b0381168252600160a01b8104600290810b810b900b602083015261ffff600160b81b8204811693830193909352600160c81b810483166060830152600160d81b8104909216608082015260ff600160e81b8304811660a0830152600160f01b909204909116151560c0820152600062093a80612a68613522565b63ffffffff1681612a7557fe5b0463ffffffff169050808460090181905550600080600073e7f0bdbdaebbf97e70c1182bd86138859707917863c51185d8886013018760400151876040518463ffffffff1660e01b8152600401612ace93929190615788565b60606040518083038186803b158015612ae657600080fd5b505af4158015612afa573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b1e9190615375565b600d8a0180546001600160801b0316905560208089015160008b815260088d01909252604090912080546001600160a01b03808716600160501b027fffff0000000000000000000000000000000000000000ffffffffffffffffffff60029590950b62ffffff16600160381b0269ffffff00000000000000199093169290921793909316178155600101805463ffffffff8416600160a01b0263ffffffff60a01b199386166001600160a01b0319909216919091179290921691909117905591945092509050612bec614aa2565b63ffffffff8781168252602096870151600290810b810b888401908152600097885260088b0190985260409687902083518154995198850151606086015163ffffffff19909b169185169190911766ffffff00000000191664010000000099840b62ffffff9081169a909a021769ffffff000000000000001916600160381b9190930b9890981697909702177fffff0000000000000000000000000000000000000000ffffffffffffffffffff16600160501b6001600160a01b039889160217865560808201516001909601805460a0909301516001600160a01b0319909316969097169590951763ffffffff60a01b1916600160a01b9190951602939093179093555050505b5050565b6000612d016134fe565b546001600160a01b0316905090565b6000612d1a6134fe565b60050154600160b81b900460020b905090565b6000612d376134fe565b600501546001600160a01b0316905090565b6000612d536134fe565b60090154905090565b6000612d666134fe565b60050154600160a01b900462ffffff16919050565b6000612d856134fe565b62020012015462ffffff16905090565b6000806000612da26134fe565b6000898152601182016020526040808220905163156fb10160e21b8152929350909173c66a64f8c1d14fa2e888cf67cf187782b9dabe80916355bec40491612df591908c908c908c908c906004016159ac565b60206040518083038186803b158015612e0d57600080fd5b505af4158015612e21573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e459190615275565b6002810154600190910154909a909950975050505050505050565b600080612e6b614361565b612e736129a0565b600080600073c66a64f8c1d14fa2e888cf67cf187782b9dabe806368e5d9076040518060c00160405280336001600160a01b031681526020018d81526020018c60020b81526020018b60020b8152602001612ed68b6001600160801b031661440c565b600003600f0b8152602001898152506040518263ffffffff1660e01b8152600401612f019190615bde565b60606040518083038186803b158015612f1957600080fd5b505af4158015612f2d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f51919061528d565b9250925092508160000394508060000393506000851180612f725750600084115b15612fb1576003830180546001600160801b038082168089018216600160801b93849004831689019092169092029091176001600160801b0319161790555b8760020b8960020b336001600160a01b03167f0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c8a8989604051612ff693929190615d5c565b60405180910390a4505050611c8b6143a9565b6060818067ffffffffffffffff8111801561302357600080fd5b5060405190808252806020026020018201604052801561304d578160200160208202803683370190505b50915060005b8181101561309a57600085858381811061306957fe5b9050602002013590506000815490508085848151811061308557fe5b60209081029190910101525050600101613053565b505092915050565b60008060008060008060006130b56134fe565b60009889526008016020908152604098899020895160c081018b52815463ffffffff8082168084526401000000008304600290810b810b810b968501879052600160381b8404810b810b900b9d84018e90526001600160a01b03600160501b90930483166060850181905260019095015492831660808501819052600160a01b90930490911660a09093018390529c939b9a50919850909650945092505050565b60405163755dab1160e11b815273dba1ddc96d2df6850808f0317ceef773a74e565c9063eabb56229061318d908490600401615e4c565b60006040518083038186803b1580156131a557600080fd5b505af4158015611c6d573d6000803e3d6000fd5b60006131c36134fe565b600a0154905090565b600080600080600080600080600080600062093a806131e9613522565b63ffffffff16816131f657fe5b0463ffffffff16905060006132096134fe565b600e0160008e60020b60020b815260200190815260200160002090508060000160009054906101000a90046001600160801b03169b508060000160109054906101000a9004600f0b9a5080600701600083815260200190815260200160002060009054906101000a90046001600160801b0316995080600801600083815260200190815260200160002060009054906101000a9004600f0b985080600201549750806003015496508060040160009054906101000a900460060b95508060040160079054906101000a90046001600160a01b0316945080600401601b9054906101000a900463ffffffff16935080600401601f9054906101000a900460ff16925050509193959799509193959799565b60006133236134fe565b60078101549091506001600160a01b0316156133515760405162461bcd60e51b815260040161073090615ade565b600061335c83613d3a565b905060008073e7f0bdbdaebbf97e70c1182bd86138859707917863eed5cff98560130160006040518363ffffffff1660e01b815260040161339e92919061575a565b604080518083038186803b1580156133b557600080fd5b505af41580156133c9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133ed91906153d2565b915091506133f96129a0565b6040805160e0810182526001600160a01b038716808252600286810b60208401819052600084860181905261ffff888116606087018190529088166080870181905260a0870192909252600160c09096019590955260078a018054600160f01b6001600160a01b031990911690951762ffffff60a01b1916600160a01b62ffffff9490950b93909316939093029190911763ffffffff60b81b1916600160c81b9094029390931761ffff60d81b1916600160d81b9093029290921761ffff60e81b1916179055517f98636036cb66a9c19a37435efc1e90142190214e8abeb821bdba3f2990dd4c95906134ef9087908690615db8565b60405180910390a15050505050565b7f568f905fee3c29dbecf3583ddfaf086f7336b6bee88b499cc887c595fb7bf1da90565b4290565b60008060008460020b8660020b8161353a57fe5b05905060008660020b12801561356157508460020b8660020b8161355a57fe5b0760020b15155b1561356b57600019015b83156135e05760008061357d8361441d565b600182810b810b600090815260208d9052604090205460ff83169190911b800160001901908116801515975092945090925090856135c257888360ff168603026135d5565b886135cc8261442f565b840360ff168603025b96505050505061365e565b6000806135ef8360010161441d565b91509150600060018260ff166001901b031990506000818b60008660010b60010b815260200190815260200160002054169050806000141595508561364157888360ff0360ff16866001010102613657565b888361364c836144cf565b0360ff168660010101025b9650505050505b5094509492505050565b60008060008360020b1261367f578260020b613687565b8260020b6000035b9050620d89e88111156136c5576040805162461bcd60e51b81526020600482015260016024820152601560fa1b604482015290519081900360640190fd5b6000600182166136d957600160801b6136eb565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561371f576ffff97272373d413259a46990580e213a0260801c5b600482161561373e576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b600882161561375d576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b601082161561377c576fffcb9843d60f6159c9db58835c9266440260801c5b602082161561379b576fff973b41fa98c081472e6896dfb254c00260801c5b60408216156137ba576fff2ea16466c96a3843ec78b326b528610260801c5b60808216156137d9576ffe5dee046a99a2a811c461f1969c30530260801c5b6101008216156137f9576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615613819576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615613839576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615613859576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615613879576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615613899576fa9f746462d870fdf8a65dc1f90e061e50260801c5b6140008216156138b9576f70d869a156d2a1b890bb3df62baf32f70260801c5b6180008216156138d9576f31be135f97d08fd981231505542fcfa60260801c5b620100008216156138fa576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b6202000082161561391a576e5d6af8dedb81196699c329225ee6040260801c5b62040000821615613939576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615613956576b048a170391f7dc42444e8fa20260801c5b60008460020b131561397157806000198161396d57fe5b0490505b640100000000810615613985576001613988565b60005b60ff16602082901c0192505050919050565b60008080806001600160a01b03808916908a161015818712801590613a1f5760006139d38989620f42400362ffffff16620f4240613bd4565b9050826139ec576139e78c8c8c60016145b9565b6139f9565b6139f98b8d8c6001614634565b9550858110613a0a578a9650613a19565b613a168c8b83866146e8565b96505b50613a69565b81613a3657613a318b8b8b6000614634565b613a43565b613a438a8c8b60006145b9565b9350838860000310613a5757899550613a69565b613a668b8a8a60000385614734565b95505b6001600160a01b038a8116908716148215613acc57808015613a885750815b613a9e57613a99878d8c6001614634565b613aa0565b855b9550808015613aad575081155b613ac357613abe878d8c60006145b9565b613ac5565b845b9450613b16565b808015613ad65750815b613aec57613ae78c888c60016145b9565b613aee565b855b9550808015613afb575081155b613b1157613b0c8c888c6000614634565b613b13565b845b94505b81158015613b2657508860000385115b15613b32578860000394505b818015613b5157508a6001600160a01b0316876001600160a01b031614155b15613b60578589039350613b7d565b613b7a868962ffffff168a620f42400362ffffff166143d2565b93505b50505095509550955095915050565b6000600160ff1b8210613b9e57600080fd5b5090565b80820382811315600083121514613bb857600080fd5b92915050565b81810182811215600083121514613bb857600080fd5b6000808060001985870986860292508281109083900303905080613c0a5760008411613bff57600080fd5b508290049050613c7d565b808411613c1657600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150505b9392505050565b60008082600f0b1215613ce957826001600160801b03168260000384039150816001600160801b031610613ce4576040805162461bcd60e51b81526020600482015260026024820152614c5360f01b604482015290519081900360640190fd5b613bb8565b826001600160801b03168284019150816001600160801b03161015613bb8576040805162461bcd60e51b81526020600482015260026024820152614c4160f01b604482015290519081900360640190fd5b60006401000276a36001600160a01b03831610801590613d76575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038316105b613dab576040805162461bcd60e51b81526020600482015260016024820152602960f91b604482015290519081900360640190fd5b77ffffffffffffffffffffffffffffffffffffffff00000000602083901b166001600160801b03811160071b81811c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211600190811b92831c97908811961790941790921717909117171760808110613e4c57607f810383901c9150613e56565b80607f0383901b91505b908002607f81811c60ff83811c9190911c800280831c81831c1c800280841c81841c1c800280851c81851c1c800280861c81861c1c800280871c81871c1c800280881c81881c1c800280891c81891c1c8002808a1c818a1c1c8002808b1c818b1c1c8002808c1c818c1c1c8002808d1c818d1c1c8002808e1c9c81901c9c909c1c80029c8d901c9e9d607f198f0160401b60c09190911c678000000000000000161760c19b909b1c674000000000000000169a909a1760c29990991c672000000000000000169890981760c39790971c671000000000000000169690961760c49590951c670800000000000000169490941760c59390931c670400000000000000169290921760c69190911c670200000000000000161760c79190911c600160381b161760c89190911c6680000000000000161760c99190911c6640000000000000161760ca9190911c6620000000000000161760cb9190911c6610000000000000161760cc9190911c6608000000000000161760cd9190911c66040000000000001617693627a301d71055774c8581026f028f6481ab7f045a5af012a19d003aa9198101608090811d906fdb2df09e81959a81455e260799a0632f8301901d600281810b9083900b1461405357886001600160a01b031661403782613668565b6001600160a01b0316111561404c578161404e565b805b614055565b815b9998505050505050505050565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b1781529251825160009485949389169392918291908083835b602083106140de5780518252601f1990920191602091820191016140bf565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114614140576040519150601f19603f3d011682016040523d82523d6000602084013e614145565b606091505b5091509150818015614173575080511580614173575080806020019051602081101561417057600080fd5b50515b611c6d576040805162461bcd60e51b81526020600482015260026024820152612a2360f11b604482015290519081900360640190fd5b6000806141b46134fe565b6004810154604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b1781529151815194955060009485946001600160a01b03169382918083835b6020831061422d5780518252601f19909201916020918201910161420e565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855afa9150503d806000811461428d576040519150601f19603f3d011682016040523d82523d6000602084013e614292565b606091505b50915091508180156142a657506020815110155b6142af57600080fd5b8080602001905160208110156142c457600080fd5b5051935050505090565b80820182811015613bb857600080fd5b6000806142e96134fe565b6005810154604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b1781529151815194955060009485946001600160a01b03169382918083836020831061422d5780518252601f19909201916020918201910161420e565b600061436b6134fe565b6007810154909150600160f01b900460ff166143995760405162461bcd60e51b815260040161073090615ba4565b600701805460ff60f01b19169055565b60016143b36134fe565b6007018054911515600160f01b0260ff60f01b19909216919091179055565b60006143df848484613bd4565b9050600082806143eb57fe5b8486091115613c7d57600019811061440257600080fd5b6001019392505050565b80600f81900b8114611d6e57600080fd5b60020b600881901d9161010090910790565b600080821161443d57600080fd5b600160801b821061445057608091821c91015b68010000000000000000821061446857604091821c91015b640100000000821061447c57602091821c91015b62010000821061448e57601091821c91015b610100821061449f57600891821c91015b601082106144af57600491821c91015b600482106144bf57600291821c91015b60028210611d6e57600101919050565b60008082116144dd57600080fd5b5060ff6001600160801b038216156144f857607f1901614500565b608082901c91505b67ffffffffffffffff82161561451957603f1901614521565b604082901c91505b63ffffffff82161561453657601f190161453e565b602082901c91505b61ffff82161561455157600f1901614559565b601082901c91505b60ff82161561456b5760071901614573565b600882901c91505b600f821615614585576003190161458d565b600482901c91505b600382161561459f57600119016145a7565b600282901c91505b6001821615611d6e5760001901919050565b6000836001600160a01b0316856001600160a01b031611156145d9579293925b8161460657614601836001600160801b03168686036001600160a01b0316600160601b613bd4565b614629565b614629836001600160801b03168686036001600160a01b0316600160601b6143d2565b90505b949350505050565b6000836001600160a01b0316856001600160a01b03161115614654579293925b6fffffffffffffffffffffffffffffffff60601b606084901b166001600160a01b03868603811690871661468757600080fd5b836146b757866001600160a01b03166146aa8383896001600160a01b0316613bd4565b816146b157fe5b046146dd565b6146dd6146ce8383896001600160a01b03166143d2565b886001600160a01b0316614780565b979650505050505050565b600080856001600160a01b0316116146ff57600080fd5b6000846001600160801b03161161471557600080fd5b8161472757614601858585600161478b565b614629858585600161486c565b600080856001600160a01b03161161474b57600080fd5b6000846001600160801b03161161476157600080fd5b8161477357614601858585600061486c565b614629858585600061478b565b808204910615150190565b600081156147fe5760006001600160a01b038411156147c1576147bc84600160601b876001600160801b0316613bd4565b6147d9565b6001600160801b038516606085901b816147d757fe5b045b90506147f66147f16001600160a01b038816836142ce565b614958565b91505061462c565b60006001600160a01b0384111561482c5761482784600160601b876001600160801b03166143d2565b614843565b614843606085901b6001600160801b038716614780565b905080866001600160a01b03161161485a57600080fd5b6001600160a01b03861603905061462c565b60008261487a57508361462c565b6fffffffffffffffffffffffffffffffff60601b606085901b168215614911576001600160a01b038616848102908582816148b157fe5b0414156148e2578181018281106148e0576148d683896001600160a01b0316836143d2565b935050505061462c565b505b61490882614903878a6001600160a01b031686816148fc57fe5b04906142ce565b614780565b9250505061462c565b6001600160a01b0386168481029085828161492857fe5b0414801561493557508082115b61493e57600080fd5b8082036148d66147f1846001600160a01b038b16846143d2565b806001600160a01b0381168114611d6e57600080fd5b6040805161014081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e08101829052610100810182905261012081019190915290565b6040805161016081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081018290526101008101829052610120810182905261014081019190915290565b6040805160e081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c081019190915290565b60405180608001604052806000600f0b81526020016000600f0b815260200160008152602001600081525090565b604051806040016040528060008152602001600081525090565b6040805160c081018252600080825260208201819052918101829052606081018290526080810182905260a081019190915290565b60008083601f840112614ae8578182fd5b50813567ffffffffffffffff811115614aff578182fd5b6020830191508360208083028501011115614b1957600080fd5b9250929050565b600082601f830112614b30578081fd5b81516020614b45614b4083615f3f565b615f1b565b8281528181019085830183850287018401881015614b61578586fd5b855b85811015614b88578151614b7681615f5d565b84529284019290840190600101614b63565b5090979650505050505050565b60008083601f840112614ba6578182fd5b50813567ffffffffffffffff811115614bbd578182fd5b602083019150836020828501011115614b1957600080fd5b8051600f81900b8114611d6e57600080fd5b8035600281900b8114611d6e57600080fd5b8051600681900b8114611d6e57600080fd5b803562ffffff81168114611d6e57600080fd5b600060208284031215614c2f578081fd5b8151613c7d81615f5d565b600080600080600080600080610100898b031215614c56578384fd5b8835614c6181615f5d565b97506020890135614c7181615f5d565b96506040890135614c8181615f5d565b95506060890135614c9181615f5d565b94506080890135614ca181615f5d565b935060a0890135614cb181615f5d565b9250614cbf60c08a01614c0b565b9150614ccd60e08a01614be7565b90509295985092959890939650565b60008060008060008060a08789031215614cf4578384fd5b8635614cff81615f5d565b955060208701358015158114614d13578485fd5b9450604087013593506060870135614d2a81615f5d565b9250608087013567ffffffffffffffff811115614d45578283fd5b614d5189828a01614b95565b979a9699509497509295939492505050565b60008060008060008060a08789031215614d7b578384fd5b8635614d8681615f5d565b9550614d9460208801614be7565b9450614da260408801614be7565b93506060870135614d2a81615f72565b600080600080600060a08688031215614dc9578283fd5b8535614dd481615f5d565b9450614de260208701614be7565b9350614df060408701614be7565b92506060860135614e0081615f72565b91506080860135614e1081615f72565b809150509295509295909350565b600080600060608486031215614e32578081fd5b8335614e3d81615f5d565b92506020840135614e4d81615f72565b91506040840135614e5d81615f72565b809150509250925092565b60008060008060008060c08789031215614e80578384fd5b8635614e8b81615f5d565b955060208701359450614ea060408801614be7565b9350614eae60608801614be7565b92506080870135614ebe81615f72565b915060a0870135614ece81615f72565b809150509295509295509295565b60008060008060008060008060e0898b031215614ef7578182fd5b8835614f0281615f5d565b975060208901359650614f1760408a01614be7565b9550614f2560608a01614be7565b94506080890135614f3581615f72565b935060a0890135925060c089013567ffffffffffffffff811115614f57578283fd5b614f638b828c01614b95565b999c989b5096995094979396929594505050565b600080600080600060808688031215614f8e578283fd5b8535614f9981615f5d565b94506020860135935060408601359250606086013567ffffffffffffffff811115614fc2578182fd5b614fce88828901614b95565b969995985093965092949392505050565b60008060208385031215614ff1578182fd5b823567ffffffffffffffff811115615007578283fd5b61501385828601614ad7565b90969095509350505050565b600080600060608486031215615033578081fd5b835167ffffffffffffffff8082111561504a578283fd5b818601915086601f83011261505d578283fd5b8151602061506d614b4083615f3f565b82815281810190858301838502870184018c1015615089578788fd5b8796505b848710156150b25761509e81614bf9565b83526001969096019591830191830161508d565b50918901519197509093505050808211156150cb578283fd5b6150d787838801614b20565b935060408601519150808211156150ec578283fd5b506150f986828701614b20565b9150509250925092565b600060208284031215615114578081fd5b5035919050565b6000806040838503121561512d578182fd5b61513683614bd5565b915061514460208401614bd5565b90509250929050565b60006020828403121561515e578081fd5b81358060010b8114613c7d578182fd5b60006020828403121561517f578081fd5b613c7d82614be7565b6000806040838503121561519a578182fd5b6151a383614be7565b915061514460208401614be7565b6000806000606084860312156151c5578081fd5b6151ce84614be7565b9250614e4d60208501614be7565b6000806000606084860312156151f0578081fd5b6151f984614bf9565b9250602084015161520981615f5d565b6040850151909250614e5d81615f5d565b6000806000806080858703121561522f578182fd5b61523885614bf9565b9350602085015161524881615f5d565b604086015190935061525981615f5d565b606086015190925061526a81615f97565b939692955090935050565b600060208284031215615286578081fd5b5051919050565b6000806000606084860312156152a1578081fd5b8351925060208401519150604084015190509250925092565b6000602082840312156152cb578081fd5b8151613c7d81615f72565b600080604083850312156152e8578182fd5b82516152f381615f72565b602084015190925061530481615f72565b809150509250929050565b600060208284031215615320578081fd5b8135613c7d81615f87565b60006020828403121561533c578081fd5b8135613c7d81615f5d565b60008060408385031215615359578182fd5b825161536481615f5d565b602084015190925061530481615f5d565b600080600060608486031215615389578081fd5b835161539481615f5d565b60208501519093506153a581615f5d565b6040850151909250614e5d81615f97565b6000602082840312156153c7578081fd5b8151613c7d81615f87565b600080604083850312156153e4578182fd5b82516153ef81615f87565b602084015190925061530481615f87565b600060208284031215615411578081fd5b613c7d82614c0b565b600080600080600060a08688031215615431578283fd5b85359450602086013561544381615f5d565b93506040860135925061545860608701614be7565b915061546660808701614be7565b90509295509295909350565b60008060408385031215615484578182fd5b50508035926020909101359150565b600080600080608085870312156154a8578182fd5b843593506154b860208601614be7565b92506154c660408601614be7565b9150606085013561526a81615f72565b600080600080600060a086880312156154ed578283fd5b853594506154fd60208701614be7565b935061550b60408701614be7565b9250606086013561551b81615f72565b949793965091946080013592915050565b6000806040838503121561553e578182fd5b505080516020909101519092909150565b600080600060608486031215615563578081fd5b833561556e81615f97565b925061557c60208501614be7565b915061558a60408501614be7565b90509250925092565b6000815180845260208085019450808401835b838110156155cb5781516001600160a01b0316875295820195908201906001016155a6565b509495945050505050565b60008284528282602086013780602084860101526020601f19601f85011685010190509392505050565b60020b9052565b60060b9052565b6001600160801b03169052565b6001600160a01b03169052565b61ffff169052565b63ffffffff169052565b6001600160a01b0391909116815260200190565b6001600160a01b039490941684526001600160801b039290921660208401526040830152606082015260800190565b6001600160a01b039390931683526001600160801b03918216602084015216604082015260600190565b6020808252825182820181905260009190848201906040850190845b818110156156df578351835292840192918401916001016156c3565b50909695505050505050565b606080825284519082018190526000906020906080840190828801845b8281101561572757815160060b84529284019290840190600101615708565b5050508381038285015261573b8187615593565b91505082810360408401526157508185615593565b9695505050505050565b91825263ffffffff16602082015260400190565b92835261ffff918216602084015216604082015260600190565b92835261ffff919091166020830152604082015260600190565b97885261ffff968716602089015263ffffffff95909516604088015260029390930b60608701526001600160801b0391821660808701521660a0850152821660c08401521660e08201526101000190565b89815263ffffffff8981166020808401919091526101006040840181905283018990526000916101208401918b91845b8c81101561584a57833561583681615f97565b821685529382019392820192600101615823565b505050508091505061585f6060830188615600565b61586c6080830187615628565b61587960a083018661560e565b61588660c083018561560e565b61589360e0830184615628565b9a9950505050505050505050565b97885263ffffffff968716602089015294909516604087015260029290920b606086015261ffff90811660808601526001600160801b0391821660a0860152921660c08401521660e08201526101000190565b60029190910b815260200190565b600292830b8152910b602082015260400190565b918252602082015260400190565b6000858252846020830152606060408301526157506060830184866155d6565b94855260208501939093526001600160a01b039190911660408401526001600160801b0316606083015260020b608082015260a00190565b60069490940b84526001600160a01b0392831660208501529116604083015263ffffffff16606082015260800190565b9485526001600160a01b039390931660208501526040840191909152600290810b60608401520b608082015260a00190565b6000610160820190508382526159f8602083018451615600565b60208301516040830152604083015160608301526060830151615a1e608084018261561b565b506080830151615a3160a084018261561b565b5060a083015160c083015260c083015160e083015260e0830151610100615a5a81850183615600565b8401519050610120615a6e84820183615607565b8401519050615a81610140840182615630565b509392505050565b602080825260039082015262544c5560e81b604082015260600190565b602080825260029082015261415360f01b604082015260600190565b602080825260029082015261463160f01b604082015260600190565b602080825260029082015261414960f01b604082015260600190565b6020808252600190820152601360fa1b604082015260600190565b60208082526003908201526254554d60e81b604082015260600190565b60208082526002908201526104d360f41b604082015260600190565b602080825260039082015262544c4d60e81b604082015260600190565b60208082526003908201526214d41360ea1b604082015260600190565b6020808252600290820152614d3160f01b604082015260600190565b6020808252600390820152624c4f4b60e81b604082015260600190565b60208082526003908201526249494160e81b604082015260600190565b600060c0820190506001600160a01b03835116825260208301516020830152604083015160020b6040830152606083015160020b60608301526080830151600f0b608083015260a083015160a083015292915050565b600060a082019050825182526001600160a01b03602084015116602083015260408301516040830152606083015160020b6060830152608083015160020b608083015292915050565b6001600160801b0391909116815260200190565b6001600160801b03929092168252600f0b602082015260400190565b6001600160801b03949094168452600f9290920b60208401526040830152606082015260800190565b6001600160801b039a8b168152600f998a0b60208201529790991660408801529490960b6060860152608085019290925260a084015260060b60c08301526001600160a01b0390921660e082015263ffffffff9091166101008201529015156101208201526101400190565b6001600160801b0392831681529116602082015260400190565b6001600160801b039390931683526020830191909152604082015260600190565b6001600160801b039687168152602081019590955260408501939093529084166060840152909216608082015260a081019190915260c00190565b6001600160a01b0392909216825260020b602082015260400190565b6001600160a01b0397909716875260029590950b602087015261ffff93841660408701529183166060860152909116608084015260ff1660a0830152151560c082015260e00190565b6001600160a01b0392831681529116602082015260400190565b61ffff92831681529116602082015260400190565b62ffffff91909116815260200190565b90815260200190565b93845260208401929092526040830152606082015260800190565b63ffffffff939093168352600291820b6020840152900b604082015260600190565b63ffffffff9687168152600295860b60208201529390940b60408401526001600160a01b039182166060840152166080820152911660a082015260c00190565b63ffffffff95909516855260069390930b60208501526001600160a01b0391821660408501521515606084015216608082015260a00190565b60405181810167ffffffffffffffff81118282101715615f3757fe5b604052919050565b600067ffffffffffffffff821115615f5357fe5b5060209081020190565b6001600160a01b038116811461175457600080fd5b6001600160801b038116811461175457600080fd5b61ffff8116811461175457600080fd5b63ffffffff8116811461175457600080fdfea164736f6c6343000706000a

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106102ea5760003560e01c806398bbc3c71161018c578063d21220a7116100ee578063e57c0ca911610097578063f305839911610071578063f305839914610662578063f30dba931461066a578063f637731d14610693576102ea565b8063e57c0ca91461060a578063ea4a11041461062a578063eabb56221461064f576102ea565b8063ddca3f43116100c8578063ddca3f43146105dc578063dfc8b615146105e4578063e3f9b398146105f7576102ea565b8063d21220a7146105b7578063d340ef8a146105bf578063da3c300d146105c7576102ea565b8063a38807f211610150578063c2e0f9b21161012a578063c2e0f9b214610592578063c45a01551461059a578063d0c93a7c146105a2576102ea565b8063a38807f21461053b578063a418e9e01461055e578063add5887e14610571576102ea565b806398bbc3c7146104f25780639918fbb6146104fa5780639fdb26161461050d578063a02f106914610515578063a34123a714610528576102ea565b80634860e05f116102505780635fa9c925116101f95780637b7d549d116101d35780637b7d549d146104b557806385b66729146104bd578063883bdbfd146104d0576102ea565b80635fa9c925146104875780636847456a1461049a57806370cf754a146104ad576102ea565b80634f2bfe5b1161022a5780634f2bfe5b14610447578063514ea4bf1461044f5780635339c29614610474576102ea565b80634860e05f146103fe578063490e6cbc146104215780634f1eb3d814610434576102ea565b8063252c09d7116102b25780633c8a7d8d1161028c5780633c8a7d8d146103ce57806346141319146103e157806346c96aac146103f6576102ea565b8063252c09d71461037a57806332148f671461039e5780633850c7bd146103b3576102ea565b80630d63237f146102ef5780630dfe168114610319578063128acb081461032e5780631a6865021461034f5780631ad8b03b14610364575b600080fd5b6103026102fd366004615103565b6106a6565b604051610310929190615c91565b60405180910390f35b6103216106e0565b604051610310919061563a565b61034161033c366004614cdc565b6106fc565b604051610310929190615916565b610357611504565b6040516103109190615c7d565b61036c611520565b604051610310929190615d42565b61038d610388366004615103565b611566565b604051610310959493929190615ee2565b6103b16103ac36600461530f565b61162a565b005b6103bb611757565b6040516103109796959493929190615dd4565b6103416103dc366004614d63565b61180f565b6103e9611835565b6040516103109190615e5c565b610321611848565b61041161040c366004615472565b611864565b6040516103109493929190615cad565b6103b161042f366004614f77565b61191b565b61036c610442366004614db2565b611c74565b610321611c95565b61046261045d366004615103565b611cb1565b60405161031096959493929190615d7d565b6103e961048236600461514d565b611d46565b6103b1610495366004614c3a565b611d73565b6103416104a8366004615493565b611f1e565b610357611f3d565b6103b1611f59565b61036c6104cb366004614e1e565b611fc7565b6104e36104de366004614fdf565b612117565b604051610310939291906156eb565b610321612231565b61034161050836600461541a565b61224d565b610357612319565b61036c610523366004614e68565b61233c565b6103416105363660046151b1565b612555565b61054e610549366004615188565b612574565b604051610310949392919061597c565b61034161056c366004614edc565b612687565b61058461057f36600461554f565b612913565b604051610310929190615e1d565b6103b16129a0565b610321612cf7565b6105aa612d10565b60405161031091906158f4565b610321612d2d565b6103e9612d49565b6105cf612d5c565b6040516103109190615e4c565b6105cf612d7b565b6103416105f236600461541a565b612d95565b6103416106053660046154d6565b612e60565b61061d610618366004614fdf565b613009565b60405161031091906156a7565b61063d610638366004615103565b6130a2565b60405161031096959493929190615ea2565b6103b161065d366004615400565b613156565b6103e96131b9565b61067d61067836600461516e565b6131cc565b6040516103109a99989796959493929190615cd6565b6103b16106a136600461532b565b613319565b60008060006106b36134fe565b600094855260110160205250506040909120546001600160801b03811692600160801b909104600f0b9150565b60006106ea6134fe565b600401546001600160a01b0316905090565b6000806107076129a0565b60006107116134fe565b9050866107395760405162461bcd60e51b815260040161073090615aa6565b60405180910390fd5b6040805160e08101825260078301546001600160a01b0381168252600160a01b8104600290810b810b900b602083015261ffff600160b81b8204811693830193909352600160c81b810483166060830152600160d81b8104909216608082015260ff600160e81b8304811660a0830152600160f01b909204909116151560c082018190526107d95760405162461bcd60e51b815260040161073090615ba4565b886108245780600001516001600160a01b0316876001600160a01b031611801561081f575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038816105b610856565b80600001516001600160a01b0316876001600160a01b031610801561085657506401000276a36001600160a01b038816115b6108725760405162461bcd60e51b815260040161073090615b6b565b60078201805460ff60f01b1916905561088961496e565b6108916149c2565b600062093a8061089f613522565b63ffffffff16816108ac57fe5b604080516101408101825260a088015160ff168152600d8901546001600160801b038082166020840152600160801b909104169181019190915291900463ffffffff169150606081016108fd613522565b63ffffffff168152602001600060060b815260200160006001600160a01b0316815260200160006001600160a01b0316815260200160001515815260200160008d131515815260200186600801600084815260200190815260200160002060000160009054906101000a900463ffffffff1663ffffffff1681525092506040518061016001604052808c81526020016000815260200185600001516001600160a01b03168152602001856020015160020b81526020018d6109c25786600b01546109c8565b86600a01545b815260006020808301829052868101516001600160801b039081166040808601919091528881015190911660608501526101208801805163ffffffff908116855260088c01808552838620546001600160a01b03600160501b90910481166080890152925190911685528084528285206001015490911660a086015295835294905292909220546401000000009004600290810b900b60c09092019190915290505b805115801590610a905750886001600160a01b031681604001516001600160a01b031614155b1561102757610a9d614a1e565b60408201516001600160a01b0316815260608201516005860154610ad091600f880191600160b81b900460020b8f613526565b15156040830152600290810b810b60208301819052620d89e719910b1215610b0157620d89e7196020820152610b20565b6020810151620d89e860029190910b1315610b2057620d89e860208201525b610b2d8160200151613668565b6001600160a01b031660608201526040820151610bae908d610b67578b6001600160a01b031683606001516001600160a01b031611610b81565b8b6001600160a01b031683606001516001600160a01b0316105b610b8f578260600151610b91565b8b5b60c0850151855160058a0154600160a01b900462ffffff1661399a565b60c085015260a084015260808301526001600160a01b0316604083015261010083015115610c1557610be98160c00151826080015101613b8c565b825103825260a0810151610c0b90610c0090613b8c565b602084015190613ba2565b6020830152610c50565b610c228160a00151613b8c565b825101825260c08101516080820151610c4a91610c3f9101613b8c565b602084015190613bbe565b60208301525b825160ff1615610c995760006064846000015160ff168360c001510281610c7357fe5b60c0840180519290910491829003905260a0840180519091016001600160801b03169052505b60c08201516001600160801b031615610cd857610ccc8160c00151600160801b8460c001516001600160801b0316613bd4565b60808301805190910190525b80606001516001600160a01b031682604001516001600160a01b03161415610fe657806040015115610fbd578260e00151610de85773e7f0bdbdaebbf97e70c1182bd86138859707917863d6b4bf9786601301856060015160008860200151896040015189602001518a604001518c606001516040518963ffffffff1660e01b8152600401610d6e9897969594939291906158a1565b60606040518083038186803b158015610d8657600080fd5b505af4158015610d9a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dbe91906151dc565b6001600160a01b0390811660c08701521660a0850152600690810b900b6080840152600160e08401525b610df0614a5a565b8c15610e0f5760808301516040820152600b8601546060820152610e24565b600a8601546040820152608083015160608201525b737533a573b325589717ae145b7df69f023ebbd68363bf7ca94e87600e01604051806101400160405280866020015160020b815260200185604001518152602001856060015181526020018860a001516001600160a01b031681526020018860c001516001600160a01b031681526020018761010001518152602001876101200151815260200187610140015160020b8152602001886080015160060b8152602001886060015163ffffffff168152506040518363ffffffff1660e01b8152600401610ef19291906159de565b604080518083038186803b158015610f0857600080fd5b505af4158015610f1c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f40919061511b565b600f90810b810b602084015290810b900b81528c15610f795780516000908103600f90810b810b8352602083018051909203810b900b90525b610f8b8360c001518260000151613c84565b6001600160801b031660c084015260e08301516020820151610fad9190613c84565b6001600160801b031660e0840152505b8b610fcc578060200151610fd5565b60018160200151035b600290810b900b6060830152611021565b80600001516001600160a01b031682604001516001600160a01b031614611021576110148260400151613d3a565b600290810b900b60608301525b50610a6a565b826020015160020b816060015160020b146111745760008073e7f0bdbdaebbf97e70c1182bd8613885970791786334ef26e68760130187604001518760600151896020015189602001518a604001518c606001518d608001516040518963ffffffff1660e01b81526004016110a39897969594939291906157a2565b604080518083038186803b1580156110ba57600080fd5b505af41580156110ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110f291906153d2565b6040850151606086015160078a01805461ffff60c81b1916600160c81b61ffff958616021761ffff60b81b1916600160b81b95909416949094029290921762ffffff60a01b1916600160a01b62ffffff60029490940b9390931692909202919091176001600160a01b0319166001600160a01b039091161790555061119b9050565b60408101516007850180546001600160a01b0319166001600160a01b039092169190911790555b8060c001516001600160801b031682602001516001600160801b0316146111e35760c0810151600d850180546001600160801b0319166001600160801b039092169190911790555b8060e001516001600160801b031682604001516001600160801b0316146112295760e0810151600d850180546001600160801b03928316600160801b0292169190911790555b8a1561127d576080810151600a85015560a08101516001600160801b0316156112785760a0810151600c850180546001600160801b031981166001600160801b03918216909301169190911790555b6112c7565b6080810151600b85015560a08101516001600160801b0316156112c75760a0810151600c850180546001600160801b03808216600160801b92839004821690940116029190911790555b81610100015115158b1515146112e557602081015181518b036112f2565b80600001518a0381602001515b90965094508a156113c1576000851215611323576005840154611323906001600160a01b03168d6000889003614062565b600061132d6141a9565b60405163654b648760e01b8152909150339063654b648790611359908a908a908e908e90600401615924565b600060405180830381600087803b15801561137357600080fd5b505af1158015611387573d6000803e3d6000fd5b505050506113936141a9565b61139d82896142ce565b11156113bb5760405162461bcd60e51b815260040161073090615bc1565b50611481565b60008612156113e75760048401546113e7906001600160a01b03168d6000899003614062565b60006113f16142de565b60405163654b648760e01b8152909150339063654b64879061141d908a908a908e908e90600401615924565b600060405180830381600087803b15801561143757600080fd5b505af115801561144b573d6000803e3d6000fd5b505050506114576142de565b61146182886142ce565b111561147f5760405162461bcd60e51b815260040161073090615bc1565b505b8b6001600160a01b0316336001600160a01b03167fc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67888885604001518660c0015187606001516040516114d8959493929190615944565b60405180910390a3505050600701805460ff60f01b1916600160f01b1790559097909650945050505050565b600061150e6134fe565b600d01546001600160801b0316905090565b600080600061152d6134fe565b60408051808201909152600c91909101546001600160801b03808216808452600160801b90920416602090920182905293509150509091565b6000806000806000806115776134fe565b6013018761ffff811061158657fe5b6040805160c08101825260029290920292909201805463ffffffff8082168085526401000000008304600690810b810b900b602086018190526b01000000000000000000000084046001600160a01b03908116978701889052600160f81b90940460ff1615156060870181905260019095015493841660808701819052600160a01b90940490921660a090950194909452929b929a50929850965090945092505050565b611632614361565b600061163c6134fe565b6007810154604051630e51299960e01b8152919250600160d81b900461ffff169060009073e7f0bdbdaebbf97e70c1182bd86138859707917890630e512999906116919060138701908690899060040161576e565b60206040518083038186803b1580156116a957600080fd5b505af41580156116bd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116e191906153b6565b60078401805461ffff808416600160d81b810261ffff60d81b1990931692909217909255919250831614611749577fac49e518f90a358f652e4400164f05a5d8f7e35e7747279bc3a93dbf584e125a8282604051611740929190615e37565b60405180910390a15b5050506117546143a9565b50565b60008060008060008060008061176b6134fe565b6040805160e081018252600792909201546001600160a01b038116808452600160a01b8204600290810b810b900b6020850181905261ffff600160b81b84048116948601859052600160c81b8404811660608701819052600160d81b85049091166080870181905260ff600160e81b8604811660a08901819052600160f01b90960416151560c0909701879052929e919d50939b5092995097509550909350915050565b6000806118258860008989896000198a8a612687565b915091505b965096945050505050565b600061183f6134fe565b600b0154905090565b60006118526134fe565b600301546001600160a01b0316905090565b60008060008060006118746134fe565b6000978852601101602090815260408089209789526001978801825297889020885160e081018a5281546001600160801b038116808352600160801b909104600f90810b810b900b938201849052988201549981018a9052600282015460608201819052600383015460ff8116151560808401526101009004601390810b810b810b60a0840152600490930154830b830b90920b60c0909101529698909795509350505050565b611923614361565b600061192d6134fe565b600d8101549091506001600160801b03168061195b5760405162461bcd60e51b815260040161073090615afa565b600582015460009061197e908890600160a01b900462ffffff16620f42406143d2565b60058401549091506000906119a4908890600160a01b900462ffffff16620f42406143d2565b905060006119b06141a9565b905060006119bc6142de565b905089156119dd5760048601546119dd906001600160a01b03168c8c614062565b88156119fc5760058601546119fc906001600160a01b03168c8b614062565b604051633797d3b360e21b8152339063de5f4ecc90611a2590879087908d908d90600401615924565b600060405180830381600087803b158015611a3f57600080fd5b505af1158015611a53573d6000803e3d6000fd5b50505050611a5f614a88565b611a676141a9565b8152611a716142de565b60208201528051611a8284876142ce565b1115611a8d57600080fd5b6020810151611a9c83866142ce565b1115611aba5760405162461bcd60e51b815260040161073090615ac2565b611ac2614a88565b81518490038082526020808401518590039083015215611b67576007880154600160e81b900460ff1660008115611b0357825160649060ff84160204611b06565b60005b90506001600160801b03811615611b3b57600c8a0180546001600160801b038082168401166001600160801b03199091161790555b611b5981846000015103600160801b8b6001600160801b0316613bd4565b600a8b018054909101905550505b602081015115611c04576007880154600160e81b900460ff1660008115611ba15760648260ff1684602001510281611b9b57fe5b04611ba4565b60005b90506001600160801b03811615611bd857600c8a0180546001600160801b03600160801b8083048216850182160291161790555b611bf681846020015103600160801b8b6001600160801b0316613bd4565b600b8b018054909101905550505b8c6001600160a01b0316336001600160a01b03167fbdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca6338e8e85600001518660200151604051611c559493929190615e65565b60405180910390a35050505050505050611c6d6143a9565b5050505050565b600080611c868760008888888861233c565b915091505b9550959350505050565b6000611c9f6134fe565b600201546001600160a01b0316905090565b6000806000806000806000611cc46134fe565b60009889526010016020908152604098899020895160c081018b5281546001600160801b03908116808352600184015494830185905260028401549c83018d9052600384015480831660608501819052600160801b9091049092166080840181905260049094015460a09093018390529c939b9a509850909650945092505050565b6000611d506134fe565b600f0160008360010b60010b81526020019081526020016000205490505b919050565b6000611d7d6134fe565b620200128101549091506301000000900460ff1615611d9b57600080fd5b80546001600160a01b03199081166001600160a01b038b811691909117835560018301805483168b83161790556002808401805484168b841617905560038401805484168a84161790556004808501805485168a8516179055600585018054620200128701805462ffffff8b811662ffffff19909216821790925591909616948a169490941762ffffff60a01b1916600160a01b9094029390931762ffffff60b81b1916600160b81b9287900b909416919091029290921790556040516382c66f8760e01b8152737533a573b325589717ae145b7df69f023ebbd683916382c66f8791611e8a918691016158f4565b60206040518083038186803b158015611ea257600080fd5b505af4158015611eb6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611eda91906152ba565b6006820180546001600160801b03929092166001600160801b03199092169190911790556202001201805463ff000000191663010000001790555050505050505050565b600080611f3086868686600019612e60565b9150915094509492505050565b6000611f476134fe565b600601546001600160801b0316905090565b611f61614361565b73dba1ddc96d2df6850808f0317ceef773a74e565c637b7d549d6040518163ffffffff1660e01b815260040160006040518083038186803b158015611fa557600080fd5b505af4158015611fb9573d6000803e3d6000fd5b50505050611fc56143a9565b565b600080611fd2614361565b6000611fdc6134fe565b8054604080516331056e5760e21b815290519293506001600160a01b039091169163c415b95c91600480820192602092909190829003018186803b15801561202357600080fd5b505afa158015612037573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061205b9190614c1e565b6001600160a01b0316336001600160a01b03161461207857600080fd5b6040516385b6672960e01b815273dba1ddc96d2df6850808f0317ceef773a74e565c906385b66729906120b39089908990899060040161567d565b604080518083038186803b1580156120ca57600080fd5b505af41580156120de573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061210291906152d6565b925092505061210f6143a9565b935093915050565b606080606060006121266134fe565b905073e7f0bdbdaebbf97e70c1182bd86138859707917863192409788260130161214e613522565b6007850154600d8601546040517fffffffff0000000000000000000000000000000000000000000000000000000060e087901b1681526121cf9493928d928d92600160a01b830460020b9261ffff600160b81b82048116936001600160801b0380821694600160801b9092041692600160c81b9004909116906004016157f3565b60006040518083038186803b1580156121e757600080fd5b505af41580156121fb573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052612223919081019061501f565b935093509350509250925092565b600061223b6134fe565b600101546001600160a01b0316905090565b60008073c66a64f8c1d14fa2e888cf67cf187782b9dabe8063d2e6311b6040518060a001604052808a8152602001896001600160a01b031681526020018881526020018760020b81526020018660020b8152506040518263ffffffff1660e01b81526004016122bc9190615c34565b604080518083038186803b1580156122d357600080fd5b505af41580156122e7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061230b919061552c565b909890975095505050505050565b60006123236134fe565b600d0154600160801b90046001600160801b0316919050565b600080612347614361565b60006123516134fe565b9050600073c66a64f8c1d14fa2e888cf67cf187782b9dabe80639c766c9d83601001338c8c8c6040518663ffffffff1660e01b81526004016123979594939291906159ac565b60206040518083038186803b1580156123af57600080fd5b505af41580156123c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123e79190615275565b60038101549091506001600160801b03908116908716116124085785612417565b60038101546001600160801b03165b60038201549094506001600160801b03600160801b90910481169086161161243f5784612455565b6003810154600160801b90046001600160801b03165b92506001600160801b038416156124a9576003810180546001600160801b031981166001600160801b0391821687900382161790915560048301546124a9916001600160a01b03909116908c908716614062565b6001600160801b038316156124fe576003810180546001600160801b03600160801b80830482168790038216029181169190911790915560058301546124fe916001600160a01b03909116908c908616614062565b8660020b8860020b336001600160a01b03167f70935338e69775456a85ddef226c395fb668b63fa0115f5f20610b388e6ca9c08d88886040516125439392919061567d565b60405180910390a4505061182a6143a9565b6000806125686000868686600019612e60565b91509150935093915050565b6000806000808460020b8660020b1261259f5760405162461bcd60e51b815260040161073090615a89565b620d89e719600287900b12156125c75760405162461bcd60e51b815260040161073090615b4e565b620d89e8600286900b13156125ee5760405162461bcd60e51b815260040161073090615b15565b6040516351c403f960e11b815273e7f0bdbdaebbf97e70c1182bd8613885970791789063a38807f2906126279089908990600401615902565b60806040518083038186803b15801561263f57600080fd5b505af4158015612653573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612677919061521a565b9299919850965090945092505050565b600080612692614361565b61269a6129a0565b6000866001600160801b0316116126b057600080fd5b60001985146126ce576001600160a01b038a1633146126ce57600080fd5b6126d6614a88565b73c66a64f8c1d14fa2e888cf67cf187782b9dabe806368e5d9076040518060c001604052808e6001600160a01b031681526020018d81526020018c60020b81526020018b60020b81526020016127348b6001600160801b031661440c565b600f0b8152602001898152506040518263ffffffff1660e01b815260040161275c9190615bde565b60606040518083038186803b15801561277457600080fd5b505af4158015612788573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127ac919061528d565b602084018190528184529094509250600090508084156127d1576127ce6141a9565b91505b83156127e2576127df6142de565b90505b604051633e48f41760e01b81523390633e48f4179061280b90889088908c908c90600401615924565b600060405180830381600087803b15801561282557600080fd5b505af1158015612839573d6000803e3d6000fd5b5050505060008511156128765761284e6141a9565b61285883876142ce565b11156128765760405162461bcd60e51b815260040161073090615b32565b83156128ac576128846142de565b61288e82866142ce565b11156128ac5760405162461bcd60e51b815260040161073090615b88565b8960020b8b60020b8e6001600160a01b03167f7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde338d8a8a6040516128f3949392919061564e565b60405180910390a45050506129066143a9565b9850989650505050505050565b60008073e7f0bdbdaebbf97e70c1182bd86138859707917863add5887e8686866040518463ffffffff1660e01b815260040161295193929190615e80565b604080518083038186803b15801561296857600080fd5b505af415801561297c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125689190615347565b60006129aa6134fe565b60098101549091508062093a806129bf613522565b63ffffffff16816129cc57fe5b0463ffffffff1614612cf3576040805160e08101825260078401546001600160a01b0381168252600160a01b8104600290810b810b900b602083015261ffff600160b81b8204811693830193909352600160c81b810483166060830152600160d81b8104909216608082015260ff600160e81b8304811660a0830152600160f01b909204909116151560c0820152600062093a80612a68613522565b63ffffffff1681612a7557fe5b0463ffffffff169050808460090181905550600080600073e7f0bdbdaebbf97e70c1182bd86138859707917863c51185d8886013018760400151876040518463ffffffff1660e01b8152600401612ace93929190615788565b60606040518083038186803b158015612ae657600080fd5b505af4158015612afa573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b1e9190615375565b600d8a0180546001600160801b0316905560208089015160008b815260088d01909252604090912080546001600160a01b03808716600160501b027fffff0000000000000000000000000000000000000000ffffffffffffffffffff60029590950b62ffffff16600160381b0269ffffff00000000000000199093169290921793909316178155600101805463ffffffff8416600160a01b0263ffffffff60a01b199386166001600160a01b0319909216919091179290921691909117905591945092509050612bec614aa2565b63ffffffff8781168252602096870151600290810b810b888401908152600097885260088b0190985260409687902083518154995198850151606086015163ffffffff19909b169185169190911766ffffff00000000191664010000000099840b62ffffff9081169a909a021769ffffff000000000000001916600160381b9190930b9890981697909702177fffff0000000000000000000000000000000000000000ffffffffffffffffffff16600160501b6001600160a01b039889160217865560808201516001909601805460a0909301516001600160a01b0319909316969097169590951763ffffffff60a01b1916600160a01b9190951602939093179093555050505b5050565b6000612d016134fe565b546001600160a01b0316905090565b6000612d1a6134fe565b60050154600160b81b900460020b905090565b6000612d376134fe565b600501546001600160a01b0316905090565b6000612d536134fe565b60090154905090565b6000612d666134fe565b60050154600160a01b900462ffffff16919050565b6000612d856134fe565b62020012015462ffffff16905090565b6000806000612da26134fe565b6000898152601182016020526040808220905163156fb10160e21b8152929350909173c66a64f8c1d14fa2e888cf67cf187782b9dabe80916355bec40491612df591908c908c908c908c906004016159ac565b60206040518083038186803b158015612e0d57600080fd5b505af4158015612e21573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e459190615275565b6002810154600190910154909a909950975050505050505050565b600080612e6b614361565b612e736129a0565b600080600073c66a64f8c1d14fa2e888cf67cf187782b9dabe806368e5d9076040518060c00160405280336001600160a01b031681526020018d81526020018c60020b81526020018b60020b8152602001612ed68b6001600160801b031661440c565b600003600f0b8152602001898152506040518263ffffffff1660e01b8152600401612f019190615bde565b60606040518083038186803b158015612f1957600080fd5b505af4158015612f2d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f51919061528d565b9250925092508160000394508060000393506000851180612f725750600084115b15612fb1576003830180546001600160801b038082168089018216600160801b93849004831689019092169092029091176001600160801b0319161790555b8760020b8960020b336001600160a01b03167f0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c8a8989604051612ff693929190615d5c565b60405180910390a4505050611c8b6143a9565b6060818067ffffffffffffffff8111801561302357600080fd5b5060405190808252806020026020018201604052801561304d578160200160208202803683370190505b50915060005b8181101561309a57600085858381811061306957fe5b9050602002013590506000815490508085848151811061308557fe5b60209081029190910101525050600101613053565b505092915050565b60008060008060008060006130b56134fe565b60009889526008016020908152604098899020895160c081018b52815463ffffffff8082168084526401000000008304600290810b810b810b968501879052600160381b8404810b810b900b9d84018e90526001600160a01b03600160501b90930483166060850181905260019095015492831660808501819052600160a01b90930490911660a09093018390529c939b9a50919850909650945092505050565b60405163755dab1160e11b815273dba1ddc96d2df6850808f0317ceef773a74e565c9063eabb56229061318d908490600401615e4c565b60006040518083038186803b1580156131a557600080fd5b505af4158015611c6d573d6000803e3d6000fd5b60006131c36134fe565b600a0154905090565b600080600080600080600080600080600062093a806131e9613522565b63ffffffff16816131f657fe5b0463ffffffff16905060006132096134fe565b600e0160008e60020b60020b815260200190815260200160002090508060000160009054906101000a90046001600160801b03169b508060000160109054906101000a9004600f0b9a5080600701600083815260200190815260200160002060009054906101000a90046001600160801b0316995080600801600083815260200190815260200160002060009054906101000a9004600f0b985080600201549750806003015496508060040160009054906101000a900460060b95508060040160079054906101000a90046001600160a01b0316945080600401601b9054906101000a900463ffffffff16935080600401601f9054906101000a900460ff16925050509193959799509193959799565b60006133236134fe565b60078101549091506001600160a01b0316156133515760405162461bcd60e51b815260040161073090615ade565b600061335c83613d3a565b905060008073e7f0bdbdaebbf97e70c1182bd86138859707917863eed5cff98560130160006040518363ffffffff1660e01b815260040161339e92919061575a565b604080518083038186803b1580156133b557600080fd5b505af41580156133c9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133ed91906153d2565b915091506133f96129a0565b6040805160e0810182526001600160a01b038716808252600286810b60208401819052600084860181905261ffff888116606087018190529088166080870181905260a0870192909252600160c09096019590955260078a018054600160f01b6001600160a01b031990911690951762ffffff60a01b1916600160a01b62ffffff9490950b93909316939093029190911763ffffffff60b81b1916600160c81b9094029390931761ffff60d81b1916600160d81b9093029290921761ffff60e81b1916179055517f98636036cb66a9c19a37435efc1e90142190214e8abeb821bdba3f2990dd4c95906134ef9087908690615db8565b60405180910390a15050505050565b7f568f905fee3c29dbecf3583ddfaf086f7336b6bee88b499cc887c595fb7bf1da90565b4290565b60008060008460020b8660020b8161353a57fe5b05905060008660020b12801561356157508460020b8660020b8161355a57fe5b0760020b15155b1561356b57600019015b83156135e05760008061357d8361441d565b600182810b810b600090815260208d9052604090205460ff83169190911b800160001901908116801515975092945090925090856135c257888360ff168603026135d5565b886135cc8261442f565b840360ff168603025b96505050505061365e565b6000806135ef8360010161441d565b91509150600060018260ff166001901b031990506000818b60008660010b60010b815260200190815260200160002054169050806000141595508561364157888360ff0360ff16866001010102613657565b888361364c836144cf565b0360ff168660010101025b9650505050505b5094509492505050565b60008060008360020b1261367f578260020b613687565b8260020b6000035b9050620d89e88111156136c5576040805162461bcd60e51b81526020600482015260016024820152601560fa1b604482015290519081900360640190fd5b6000600182166136d957600160801b6136eb565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561371f576ffff97272373d413259a46990580e213a0260801c5b600482161561373e576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b600882161561375d576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b601082161561377c576fffcb9843d60f6159c9db58835c9266440260801c5b602082161561379b576fff973b41fa98c081472e6896dfb254c00260801c5b60408216156137ba576fff2ea16466c96a3843ec78b326b528610260801c5b60808216156137d9576ffe5dee046a99a2a811c461f1969c30530260801c5b6101008216156137f9576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615613819576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615613839576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615613859576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615613879576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615613899576fa9f746462d870fdf8a65dc1f90e061e50260801c5b6140008216156138b9576f70d869a156d2a1b890bb3df62baf32f70260801c5b6180008216156138d9576f31be135f97d08fd981231505542fcfa60260801c5b620100008216156138fa576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b6202000082161561391a576e5d6af8dedb81196699c329225ee6040260801c5b62040000821615613939576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615613956576b048a170391f7dc42444e8fa20260801c5b60008460020b131561397157806000198161396d57fe5b0490505b640100000000810615613985576001613988565b60005b60ff16602082901c0192505050919050565b60008080806001600160a01b03808916908a161015818712801590613a1f5760006139d38989620f42400362ffffff16620f4240613bd4565b9050826139ec576139e78c8c8c60016145b9565b6139f9565b6139f98b8d8c6001614634565b9550858110613a0a578a9650613a19565b613a168c8b83866146e8565b96505b50613a69565b81613a3657613a318b8b8b6000614634565b613a43565b613a438a8c8b60006145b9565b9350838860000310613a5757899550613a69565b613a668b8a8a60000385614734565b95505b6001600160a01b038a8116908716148215613acc57808015613a885750815b613a9e57613a99878d8c6001614634565b613aa0565b855b9550808015613aad575081155b613ac357613abe878d8c60006145b9565b613ac5565b845b9450613b16565b808015613ad65750815b613aec57613ae78c888c60016145b9565b613aee565b855b9550808015613afb575081155b613b1157613b0c8c888c6000614634565b613b13565b845b94505b81158015613b2657508860000385115b15613b32578860000394505b818015613b5157508a6001600160a01b0316876001600160a01b031614155b15613b60578589039350613b7d565b613b7a868962ffffff168a620f42400362ffffff166143d2565b93505b50505095509550955095915050565b6000600160ff1b8210613b9e57600080fd5b5090565b80820382811315600083121514613bb857600080fd5b92915050565b81810182811215600083121514613bb857600080fd5b6000808060001985870986860292508281109083900303905080613c0a5760008411613bff57600080fd5b508290049050613c7d565b808411613c1657600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150505b9392505050565b60008082600f0b1215613ce957826001600160801b03168260000384039150816001600160801b031610613ce4576040805162461bcd60e51b81526020600482015260026024820152614c5360f01b604482015290519081900360640190fd5b613bb8565b826001600160801b03168284019150816001600160801b03161015613bb8576040805162461bcd60e51b81526020600482015260026024820152614c4160f01b604482015290519081900360640190fd5b60006401000276a36001600160a01b03831610801590613d76575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038316105b613dab576040805162461bcd60e51b81526020600482015260016024820152602960f91b604482015290519081900360640190fd5b77ffffffffffffffffffffffffffffffffffffffff00000000602083901b166001600160801b03811160071b81811c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211600190811b92831c97908811961790941790921717909117171760808110613e4c57607f810383901c9150613e56565b80607f0383901b91505b908002607f81811c60ff83811c9190911c800280831c81831c1c800280841c81841c1c800280851c81851c1c800280861c81861c1c800280871c81871c1c800280881c81881c1c800280891c81891c1c8002808a1c818a1c1c8002808b1c818b1c1c8002808c1c818c1c1c8002808d1c818d1c1c8002808e1c9c81901c9c909c1c80029c8d901c9e9d607f198f0160401b60c09190911c678000000000000000161760c19b909b1c674000000000000000169a909a1760c29990991c672000000000000000169890981760c39790971c671000000000000000169690961760c49590951c670800000000000000169490941760c59390931c670400000000000000169290921760c69190911c670200000000000000161760c79190911c600160381b161760c89190911c6680000000000000161760c99190911c6640000000000000161760ca9190911c6620000000000000161760cb9190911c6610000000000000161760cc9190911c6608000000000000161760cd9190911c66040000000000001617693627a301d71055774c8581026f028f6481ab7f045a5af012a19d003aa9198101608090811d906fdb2df09e81959a81455e260799a0632f8301901d600281810b9083900b1461405357886001600160a01b031661403782613668565b6001600160a01b0316111561404c578161404e565b805b614055565b815b9998505050505050505050565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b1781529251825160009485949389169392918291908083835b602083106140de5780518252601f1990920191602091820191016140bf565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114614140576040519150601f19603f3d011682016040523d82523d6000602084013e614145565b606091505b5091509150818015614173575080511580614173575080806020019051602081101561417057600080fd5b50515b611c6d576040805162461bcd60e51b81526020600482015260026024820152612a2360f11b604482015290519081900360640190fd5b6000806141b46134fe565b6004810154604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b1781529151815194955060009485946001600160a01b03169382918083835b6020831061422d5780518252601f19909201916020918201910161420e565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855afa9150503d806000811461428d576040519150601f19603f3d011682016040523d82523d6000602084013e614292565b606091505b50915091508180156142a657506020815110155b6142af57600080fd5b8080602001905160208110156142c457600080fd5b5051935050505090565b80820182811015613bb857600080fd5b6000806142e96134fe565b6005810154604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b1781529151815194955060009485946001600160a01b03169382918083836020831061422d5780518252601f19909201916020918201910161420e565b600061436b6134fe565b6007810154909150600160f01b900460ff166143995760405162461bcd60e51b815260040161073090615ba4565b600701805460ff60f01b19169055565b60016143b36134fe565b6007018054911515600160f01b0260ff60f01b19909216919091179055565b60006143df848484613bd4565b9050600082806143eb57fe5b8486091115613c7d57600019811061440257600080fd5b6001019392505050565b80600f81900b8114611d6e57600080fd5b60020b600881901d9161010090910790565b600080821161443d57600080fd5b600160801b821061445057608091821c91015b68010000000000000000821061446857604091821c91015b640100000000821061447c57602091821c91015b62010000821061448e57601091821c91015b610100821061449f57600891821c91015b601082106144af57600491821c91015b600482106144bf57600291821c91015b60028210611d6e57600101919050565b60008082116144dd57600080fd5b5060ff6001600160801b038216156144f857607f1901614500565b608082901c91505b67ffffffffffffffff82161561451957603f1901614521565b604082901c91505b63ffffffff82161561453657601f190161453e565b602082901c91505b61ffff82161561455157600f1901614559565b601082901c91505b60ff82161561456b5760071901614573565b600882901c91505b600f821615614585576003190161458d565b600482901c91505b600382161561459f57600119016145a7565b600282901c91505b6001821615611d6e5760001901919050565b6000836001600160a01b0316856001600160a01b031611156145d9579293925b8161460657614601836001600160801b03168686036001600160a01b0316600160601b613bd4565b614629565b614629836001600160801b03168686036001600160a01b0316600160601b6143d2565b90505b949350505050565b6000836001600160a01b0316856001600160a01b03161115614654579293925b6fffffffffffffffffffffffffffffffff60601b606084901b166001600160a01b03868603811690871661468757600080fd5b836146b757866001600160a01b03166146aa8383896001600160a01b0316613bd4565b816146b157fe5b046146dd565b6146dd6146ce8383896001600160a01b03166143d2565b886001600160a01b0316614780565b979650505050505050565b600080856001600160a01b0316116146ff57600080fd5b6000846001600160801b03161161471557600080fd5b8161472757614601858585600161478b565b614629858585600161486c565b600080856001600160a01b03161161474b57600080fd5b6000846001600160801b03161161476157600080fd5b8161477357614601858585600061486c565b614629858585600061478b565b808204910615150190565b600081156147fe5760006001600160a01b038411156147c1576147bc84600160601b876001600160801b0316613bd4565b6147d9565b6001600160801b038516606085901b816147d757fe5b045b90506147f66147f16001600160a01b038816836142ce565b614958565b91505061462c565b60006001600160a01b0384111561482c5761482784600160601b876001600160801b03166143d2565b614843565b614843606085901b6001600160801b038716614780565b905080866001600160a01b03161161485a57600080fd5b6001600160a01b03861603905061462c565b60008261487a57508361462c565b6fffffffffffffffffffffffffffffffff60601b606085901b168215614911576001600160a01b038616848102908582816148b157fe5b0414156148e2578181018281106148e0576148d683896001600160a01b0316836143d2565b935050505061462c565b505b61490882614903878a6001600160a01b031686816148fc57fe5b04906142ce565b614780565b9250505061462c565b6001600160a01b0386168481029085828161492857fe5b0414801561493557508082115b61493e57600080fd5b8082036148d66147f1846001600160a01b038b16846143d2565b806001600160a01b0381168114611d6e57600080fd5b6040805161014081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e08101829052610100810182905261012081019190915290565b6040805161016081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081018290526101008101829052610120810182905261014081019190915290565b6040805160e081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c081019190915290565b60405180608001604052806000600f0b81526020016000600f0b815260200160008152602001600081525090565b604051806040016040528060008152602001600081525090565b6040805160c081018252600080825260208201819052918101829052606081018290526080810182905260a081019190915290565b60008083601f840112614ae8578182fd5b50813567ffffffffffffffff811115614aff578182fd5b6020830191508360208083028501011115614b1957600080fd5b9250929050565b600082601f830112614b30578081fd5b81516020614b45614b4083615f3f565b615f1b565b8281528181019085830183850287018401881015614b61578586fd5b855b85811015614b88578151614b7681615f5d565b84529284019290840190600101614b63565b5090979650505050505050565b60008083601f840112614ba6578182fd5b50813567ffffffffffffffff811115614bbd578182fd5b602083019150836020828501011115614b1957600080fd5b8051600f81900b8114611d6e57600080fd5b8035600281900b8114611d6e57600080fd5b8051600681900b8114611d6e57600080fd5b803562ffffff81168114611d6e57600080fd5b600060208284031215614c2f578081fd5b8151613c7d81615f5d565b600080600080600080600080610100898b031215614c56578384fd5b8835614c6181615f5d565b97506020890135614c7181615f5d565b96506040890135614c8181615f5d565b95506060890135614c9181615f5d565b94506080890135614ca181615f5d565b935060a0890135614cb181615f5d565b9250614cbf60c08a01614c0b565b9150614ccd60e08a01614be7565b90509295985092959890939650565b60008060008060008060a08789031215614cf4578384fd5b8635614cff81615f5d565b955060208701358015158114614d13578485fd5b9450604087013593506060870135614d2a81615f5d565b9250608087013567ffffffffffffffff811115614d45578283fd5b614d5189828a01614b95565b979a9699509497509295939492505050565b60008060008060008060a08789031215614d7b578384fd5b8635614d8681615f5d565b9550614d9460208801614be7565b9450614da260408801614be7565b93506060870135614d2a81615f72565b600080600080600060a08688031215614dc9578283fd5b8535614dd481615f5d565b9450614de260208701614be7565b9350614df060408701614be7565b92506060860135614e0081615f72565b91506080860135614e1081615f72565b809150509295509295909350565b600080600060608486031215614e32578081fd5b8335614e3d81615f5d565b92506020840135614e4d81615f72565b91506040840135614e5d81615f72565b809150509250925092565b60008060008060008060c08789031215614e80578384fd5b8635614e8b81615f5d565b955060208701359450614ea060408801614be7565b9350614eae60608801614be7565b92506080870135614ebe81615f72565b915060a0870135614ece81615f72565b809150509295509295509295565b60008060008060008060008060e0898b031215614ef7578182fd5b8835614f0281615f5d565b975060208901359650614f1760408a01614be7565b9550614f2560608a01614be7565b94506080890135614f3581615f72565b935060a0890135925060c089013567ffffffffffffffff811115614f57578283fd5b614f638b828c01614b95565b999c989b5096995094979396929594505050565b600080600080600060808688031215614f8e578283fd5b8535614f9981615f5d565b94506020860135935060408601359250606086013567ffffffffffffffff811115614fc2578182fd5b614fce88828901614b95565b969995985093965092949392505050565b60008060208385031215614ff1578182fd5b823567ffffffffffffffff811115615007578283fd5b61501385828601614ad7565b90969095509350505050565b600080600060608486031215615033578081fd5b835167ffffffffffffffff8082111561504a578283fd5b818601915086601f83011261505d578283fd5b8151602061506d614b4083615f3f565b82815281810190858301838502870184018c1015615089578788fd5b8796505b848710156150b25761509e81614bf9565b83526001969096019591830191830161508d565b50918901519197509093505050808211156150cb578283fd5b6150d787838801614b20565b935060408601519150808211156150ec578283fd5b506150f986828701614b20565b9150509250925092565b600060208284031215615114578081fd5b5035919050565b6000806040838503121561512d578182fd5b61513683614bd5565b915061514460208401614bd5565b90509250929050565b60006020828403121561515e578081fd5b81358060010b8114613c7d578182fd5b60006020828403121561517f578081fd5b613c7d82614be7565b6000806040838503121561519a578182fd5b6151a383614be7565b915061514460208401614be7565b6000806000606084860312156151c5578081fd5b6151ce84614be7565b9250614e4d60208501614be7565b6000806000606084860312156151f0578081fd5b6151f984614bf9565b9250602084015161520981615f5d565b6040850151909250614e5d81615f5d565b6000806000806080858703121561522f578182fd5b61523885614bf9565b9350602085015161524881615f5d565b604086015190935061525981615f5d565b606086015190925061526a81615f97565b939692955090935050565b600060208284031215615286578081fd5b5051919050565b6000806000606084860312156152a1578081fd5b8351925060208401519150604084015190509250925092565b6000602082840312156152cb578081fd5b8151613c7d81615f72565b600080604083850312156152e8578182fd5b82516152f381615f72565b602084015190925061530481615f72565b809150509250929050565b600060208284031215615320578081fd5b8135613c7d81615f87565b60006020828403121561533c578081fd5b8135613c7d81615f5d565b60008060408385031215615359578182fd5b825161536481615f5d565b602084015190925061530481615f5d565b600080600060608486031215615389578081fd5b835161539481615f5d565b60208501519093506153a581615f5d565b6040850151909250614e5d81615f97565b6000602082840312156153c7578081fd5b8151613c7d81615f87565b600080604083850312156153e4578182fd5b82516153ef81615f87565b602084015190925061530481615f87565b600060208284031215615411578081fd5b613c7d82614c0b565b600080600080600060a08688031215615431578283fd5b85359450602086013561544381615f5d565b93506040860135925061545860608701614be7565b915061546660808701614be7565b90509295509295909350565b60008060408385031215615484578182fd5b50508035926020909101359150565b600080600080608085870312156154a8578182fd5b843593506154b860208601614be7565b92506154c660408601614be7565b9150606085013561526a81615f72565b600080600080600060a086880312156154ed578283fd5b853594506154fd60208701614be7565b935061550b60408701614be7565b9250606086013561551b81615f72565b949793965091946080013592915050565b6000806040838503121561553e578182fd5b505080516020909101519092909150565b600080600060608486031215615563578081fd5b833561556e81615f97565b925061557c60208501614be7565b915061558a60408501614be7565b90509250925092565b6000815180845260208085019450808401835b838110156155cb5781516001600160a01b0316875295820195908201906001016155a6565b509495945050505050565b60008284528282602086013780602084860101526020601f19601f85011685010190509392505050565b60020b9052565b60060b9052565b6001600160801b03169052565b6001600160a01b03169052565b61ffff169052565b63ffffffff169052565b6001600160a01b0391909116815260200190565b6001600160a01b039490941684526001600160801b039290921660208401526040830152606082015260800190565b6001600160a01b039390931683526001600160801b03918216602084015216604082015260600190565b6020808252825182820181905260009190848201906040850190845b818110156156df578351835292840192918401916001016156c3565b50909695505050505050565b606080825284519082018190526000906020906080840190828801845b8281101561572757815160060b84529284019290840190600101615708565b5050508381038285015261573b8187615593565b91505082810360408401526157508185615593565b9695505050505050565b91825263ffffffff16602082015260400190565b92835261ffff918216602084015216604082015260600190565b92835261ffff919091166020830152604082015260600190565b97885261ffff968716602089015263ffffffff95909516604088015260029390930b60608701526001600160801b0391821660808701521660a0850152821660c08401521660e08201526101000190565b89815263ffffffff8981166020808401919091526101006040840181905283018990526000916101208401918b91845b8c81101561584a57833561583681615f97565b821685529382019392820192600101615823565b505050508091505061585f6060830188615600565b61586c6080830187615628565b61587960a083018661560e565b61588660c083018561560e565b61589360e0830184615628565b9a9950505050505050505050565b97885263ffffffff968716602089015294909516604087015260029290920b606086015261ffff90811660808601526001600160801b0391821660a0860152921660c08401521660e08201526101000190565b60029190910b815260200190565b600292830b8152910b602082015260400190565b918252602082015260400190565b6000858252846020830152606060408301526157506060830184866155d6565b94855260208501939093526001600160a01b039190911660408401526001600160801b0316606083015260020b608082015260a00190565b60069490940b84526001600160a01b0392831660208501529116604083015263ffffffff16606082015260800190565b9485526001600160a01b039390931660208501526040840191909152600290810b60608401520b608082015260a00190565b6000610160820190508382526159f8602083018451615600565b60208301516040830152604083015160608301526060830151615a1e608084018261561b565b506080830151615a3160a084018261561b565b5060a083015160c083015260c083015160e083015260e0830151610100615a5a81850183615600565b8401519050610120615a6e84820183615607565b8401519050615a81610140840182615630565b509392505050565b602080825260039082015262544c5560e81b604082015260600190565b602080825260029082015261415360f01b604082015260600190565b602080825260029082015261463160f01b604082015260600190565b602080825260029082015261414960f01b604082015260600190565b6020808252600190820152601360fa1b604082015260600190565b60208082526003908201526254554d60e81b604082015260600190565b60208082526002908201526104d360f41b604082015260600190565b602080825260039082015262544c4d60e81b604082015260600190565b60208082526003908201526214d41360ea1b604082015260600190565b6020808252600290820152614d3160f01b604082015260600190565b6020808252600390820152624c4f4b60e81b604082015260600190565b60208082526003908201526249494160e81b604082015260600190565b600060c0820190506001600160a01b03835116825260208301516020830152604083015160020b6040830152606083015160020b60608301526080830151600f0b608083015260a083015160a083015292915050565b600060a082019050825182526001600160a01b03602084015116602083015260408301516040830152606083015160020b6060830152608083015160020b608083015292915050565b6001600160801b0391909116815260200190565b6001600160801b03929092168252600f0b602082015260400190565b6001600160801b03949094168452600f9290920b60208401526040830152606082015260800190565b6001600160801b039a8b168152600f998a0b60208201529790991660408801529490960b6060860152608085019290925260a084015260060b60c08301526001600160a01b0390921660e082015263ffffffff9091166101008201529015156101208201526101400190565b6001600160801b0392831681529116602082015260400190565b6001600160801b039390931683526020830191909152604082015260600190565b6001600160801b039687168152602081019590955260408501939093529084166060840152909216608082015260a081019190915260c00190565b6001600160a01b0392909216825260020b602082015260400190565b6001600160a01b0397909716875260029590950b602087015261ffff93841660408701529183166060860152909116608084015260ff1660a0830152151560c082015260e00190565b6001600160a01b0392831681529116602082015260400190565b61ffff92831681529116602082015260400190565b62ffffff91909116815260200190565b90815260200190565b93845260208401929092526040830152606082015260800190565b63ffffffff939093168352600291820b6020840152900b604082015260600190565b63ffffffff9687168152600295860b60208201529390940b60408401526001600160a01b039182166060840152166080820152911660a082015260c00190565b63ffffffff95909516855260069390930b60208501526001600160a01b0391821660408501521515606084015216608082015260a00190565b60405181810167ffffffffffffffff81118282101715615f3757fe5b604052919050565b600067ffffffffffffffff821115615f5357fe5b5060209081020190565b6001600160a01b038116811461175457600080fd5b6001600160801b038116811461175457600080fd5b61ffff8116811461175457600080fd5b63ffffffff8116811461175457600080fdfea164736f6c6343000706000a

Block Transaction Gas Used Reward
view all blocks sequenced

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

Validator Index Block Amount
View All Withdrawals

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