ETH Price: $1,780.48 (+4.46%)
 

Overview

ETH Balance

Scroll LogoScroll LogoScroll Logo0 ETH

ETH Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

Parent Transaction Hash Block From To
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 800 runs

Other Settings:
default evmVersion
File 1 of 33 : 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";

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

    constructor() {
        States.PoolStates storage states = States.getStorage();

        states.initialized = true;
    }

    /// @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 = Oracle.newPeriod(
                states.observations,
                _slot0.observationIndex,
                period
            );

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

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

    // 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
        )
    {
        PeriodInfo memory periodData = States.getStorage().periods[period];
        return (
            periodData.previousPeriod,
            periodData.startTick,
            periodData.lastTick,
            periodData.endSecondsPerLiquidityPeriodX128
        );
    }

    // 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 ticks of the pool
    /// @inheritdoc IClPoolState
    function ticks(
        int24 tick
    )
        external
        view
        override
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        )
    {
        TickInfo storage tickData = States.getStorage()._ticks[tick];
        liquidityGross = tickData.liquidityGross;
        liquidityNet = tickData.liquidityNet;
        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)
    {
        PositionInfo storage positionData = States.getStorage().positions[key];
        return (
            positionData.liquidity,
            positionData.feeGrowthInside0LastX128,
            positionData.feeGrowthInside1LastX128,
            positionData.tokensOwed0,
            positionData.tokensOwed1
        );
    }

    // 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) {
        States.PoolStates storage states = States.getStorage();
        PositionInfo storage position = Position.get(
            states.positions,
            owner,
            index,
            tickLower,
            tickUpper
        );
        secondsDebtX96 = position.periodRewardInfo[period].secondsDebtX96;
    }

    // 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) {
        periodSecondsInsideX96 = Position.positionPeriodSecondsInRange(
            Position.PositionPeriodSecondsInRangeParams({
                period: period,
                owner: owner,
                index: index,
                tickLower: tickLower,
                tickUpper: tickUpper
            })
        );

        return periodSecondsInsideX96;
    }

    // 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
        )
    {
        Observation memory observationData = States.getStorage().observations[
            index
        ];
        return (
            observationData.blockTimestamp,
            observationData.tickCumulative,
            observationData.secondsPerLiquidityCumulativeX128,
            observationData.initialized
        );
    }

    /// @inheritdoc IClPoolDerivedState
    function snapshotCumulativesInside(
        int24 tickLower,
        int24 tickUpper
    )
        external
        view
        override
        returns (
            int56 tickCumulativeInside,
            uint160 secondsPerLiquidityInsideX128,
            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) {
        return Oracle.periodCumulativesInside(period, tickLower, tickUpper);
    }

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

        return
            Oracle.observe(
                states.observations,
                States._blockTimestamp(),
                secondsAgos,
                states.slot0.tick,
                states.slot0.observationIndex,
                states.liquidity,
                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, data);
    }

    /// @inheritdoc IClPoolActions
    function mint(
        address recipient,
        uint256 index,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    )
        public
        override
        lock
        advancePeriod
        returns (uint256 amount0, uint256 amount1)
    {
        require(amount > 0);

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

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

    /// @inheritdoc IClPoolActions
    function burn(
        uint256 index,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    )
        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()
                })
            );

        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;
        // 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;
        // 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;
        // seconds per liquidity at the end of the previous period
        uint256 endSecondsPerLiquidityPeriodX128;
        // 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;
        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,
                blockTimestamp: States._blockTimestamp(),
                feeProtocol: zeroForOne
                    ? (slot0Start.feeProtocol % 16)
                    : (slot0Start.feeProtocol >> 4),
                secondsPerLiquidityCumulativeX128: 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,
                endSecondsPerLiquidityPeriodX128: states
                    .periods[cache.previousPeriod]
                    .endSecondsPerLiquidityPeriodX128,
                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 * 5 + 50)) / 100;
                step.feeAmount -= delta;
                state.protocolFee += uint128(delta);
            } else {
                uint256 delta = (step.feeAmount * 5) / 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
                        ) = Oracle.observeSingle(
                            states.observations,
                            cache.blockTimestamp,
                            0,
                            slot0Start.tick,
                            slot0Start.observationIndex,
                            cache.liquidityStart,
                            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 = Tick.cross(
                        states._ticks,
                        Tick.CrossParams(
                            step.tickNext,
                            crossCache.feeGrowthGlobal0X128,
                            crossCache.feeGrowthGlobal1X128,
                            cache.secondsPerLiquidityCumulativeX128,
                            state.endSecondsPerLiquidityPeriodX128,
                            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;
                    }

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

                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,
                    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 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, "F0");
        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 % 16;
            uint256 fees0 = feeProtocol0 == 0 ? 0 : paid.token0 / feeProtocol0;
            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 >> 4;
            uint256 fees1 = feeProtocol1 == 0 ? 0 : paid.token1 / feeProtocol1;
            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 33 : 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 3 of 33 : 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 4 of 33 : 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 5 of 33 : 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 _token0,
        address _token1,
        uint24 _fee,
        int24 _tickSpacing
    ) external;

    function _advancePeriod() external;
}

File 6 of 33 : 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 7 of 33 : 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 default protocol's % share of the fees
    /// @param pool the pool address
    /// @param feeProtocol0 new protocol fee for token0 of the pool
    /// @param feeProtocol1 new protocol fee for token1 of the pool
    function setPoolFeeProtocol(
        address pool,
        uint8 feeProtocol0,
        uint8 feeProtocol1
    ) 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;
}

File 8 of 33 : 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 9 of 33 : 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 data Any data that should be passed through to the callback
    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
    function mint(
        address recipient,
        uint256 index,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Collects tokens owed to a position
    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
    /// @param recipient The address which should receive the fees collected
    /// @param 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 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 10 of 33 : 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
    function observe(
        uint32[] calldata secondsAgos
    )
        external
        view
        returns (
            int56[] memory tickCumulatives,
            uint160[] memory secondsPerLiquidityCumulativeX128s
        );

    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
    /// snapshot is taken and the second snapshot is taken. 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
    function snapshotCumulativesInside(
        int24 tickLower,
        int24 tickUpper
    )
        external
        view
        returns (
            int56 tickCumulativeInside,
            uint160 secondsPerLiquidityInsideX128,
            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
    function periodCumulativesInside(
        uint32 period,
        int24 tickLower,
        int24 tickUpper
    ) external view returns (uint160 secondsPerLiquidityInsideX128);
}

File 11 of 33 : 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 12 of 33 : 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 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 13 of 33 : 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 14 of 33 : 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
    function periods(
        uint256 period
    )
        external
        view
        returns (
            uint32 previousPeriod,
            int24 startTick,
            int24 lastTick,
            uint160 endSecondsPerLiquidityCumulativeX128
        );

    /// @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 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,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

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

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

    /// @notice 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
    function positionPeriodDebt(
        uint256 period,
        address recipient,
        uint256 index,
        int24 tickLower,
        int24 tickUpper
    ) external view returns (int256 secondsDebtX96);

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

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

File 15 of 33 : 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 16 of 33 : 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 17 of 33 : 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 18 of 33 : 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 19 of 33 : 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 20 of 33 : LiquidityMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './FullMath.sol';
import './SafeCast.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');
        }
    }
}

File 21 of 33 : 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 22 of 33 : 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
    ) 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)),
                initialized: true
            });
    }

    /// @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,
            initialized: true
        });
        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,
        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);
    }

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

        // 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,
        uint16 cardinality
    ) public view returns (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) {
        if (secondsAgo == 0) {
            Observation memory last = self[index];
            if (last.blockTimestamp != time) {
                last = transform(last, time, tick, liquidity);
            }
            return (last.tickCumulative, last.secondsPerLiquidityCumulativeX128);
        }

        uint32 target = time - secondsAgo;

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

        if (target == beforeOrAt.blockTimestamp) {
            // we're at the left boundary
            return (beforeOrAt.tickCumulative, beforeOrAt.secondsPerLiquidityCumulativeX128);
        } else if (target == atOrAfter.blockTimestamp) {
            // we're at the right boundary
            return (atOrAfter.tickCumulative, atOrAfter.secondsPerLiquidityCumulativeX128);
        } 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
                    )
            );
        }
    }

    /// @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,
        uint16 cardinality
    ) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) {
        require(cardinality > 0, 'I');

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

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

    function newPeriod(
        Observation[65535] storage self,
        uint16 index,
        uint256 period
    ) external returns (uint160 secondsPerLiquidityCumulativeX128) {
        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));

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

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

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

    /// @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 secondsInside The snapshot of seconds per liquidity for the range
    function snapshotCumulativesInside(
        int24 tickLower,
        int24 tickUpper
    ) external view returns (int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside) {
        States.PoolStates storage states = States.getStorage();

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

        SnapShot memory snapshot;

        {
            bool initializedLower;
            (
                snapshot.tickCumulativeLower,
                snapshot.secondsPerLiquidityOutsideLowerX128,
                snapshot.secondsOutsideLower,
                initializedLower
            ) = (
                lower.tickCumulativeOutside,
                lower.secondsPerLiquidityOutsideX128,
                lower.secondsOutside,
                lower.initialized
            );
            require(initializedLower);

            bool initializedUpper;
            (
                snapshot.tickCumulativeUpper,
                snapshot.secondsPerLiquidityOutsideUpperX128,
                snapshot.secondsOutsideUpper,
                initializedUpper
            ) = (
                upper.tickCumulativeOutside,
                upper.secondsPerLiquidityOutsideX128,
                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.secondsOutsideLower - snapshot.secondsOutsideUpper
            );
        } else if (_slot0.tick < tickUpper) {
            SnapshotCumulativesInsideCache memory cache;
            cache.time = States._blockTimestamp();
            (cache.tickCumulative, cache.secondsPerLiquidityCumulativeX128) = observeSingle(
                states.observations,
                cache.time,
                0,
                _slot0.tick,
                _slot0.observationIndex,
                states.liquidity,
                _slot0.observationCardinality
            );
            return (
                cache.tickCumulative - snapshot.tickCumulativeLower - snapshot.tickCumulativeUpper,
                cache.secondsPerLiquidityCumulativeX128 -
                    snapshot.secondsPerLiquidityOutsideLowerX128 -
                    snapshot.secondsPerLiquidityOutsideUpperX128,
                cache.time - snapshot.secondsOutsideLower - snapshot.secondsOutsideUpper
            );
        } else {
            return (
                snapshot.tickCumulativeUpper - snapshot.tickCumulativeLower,
                snapshot.secondsPerLiquidityOutsideUpperX128 - snapshot.secondsPerLiquidityOutsideLowerX128,
                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
    function periodCumulativesInside(
        uint32 period,
        int24 tickLower,
        int24 tickUpper
    ) external view returns (uint160 secondsPerLiquidityInsideX128) {
        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 = uint160(lower.periodSecondsPerLiquidityOutsideX128[period]);

            if (tickLower <= startTick && snapshot.secondsPerLiquidityOutsideLowerX128 == 0) {
                snapshot.secondsPerLiquidityOutsideLowerX128 = states
                    .periods[previousPeriod]
                    .endSecondsPerLiquidityPeriodX128;
            }

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

        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;
        } 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) = observeSingle(
                    states.observations,
                    cache.time,
                    0,
                    _slot0.tick,
                    _slot0.observationIndex,
                    states.liquidity,
                    _slot0.observationCardinality
                );
            } else {
                cache.secondsPerLiquidityCumulativeX128 = states.periods[period].endSecondsPerLiquidityPeriodX128;
            }

            return
                cache.secondsPerLiquidityCumulativeX128 -
                snapshot.secondsPerLiquidityOutsideLowerX128 -
                snapshot.secondsPerLiquidityOutsideUpperX128;
        } else {
            return snapshot.secondsPerLiquidityOutsideUpperX128 - snapshot.secondsPerLiquidityOutsideLowerX128;
        }
    }
}

File 23 of 33 : 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';

/// @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 {
    /// @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 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,
        uint160 secondsPerLiquidityPeriodX128
    ) internal {
        uint128 liquidity = self.liquidity;
        uint128 liquidityNext;

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

        // calculate accumulated fees
        uint128 tokensOwed0 = uint128(
            FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128)
        );
        uint128 tokensOwed1 = uint128(
            FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, 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;
            }
        }
        {
            int160 secondsPerLiquidityPeriodIntX128 = int160(secondsPerLiquidityPeriodX128);

            int160 secondsPerLiquidityPeriodStartX128 = self
                .periodRewardInfo[period]
                .secondsPerLiquidityPeriodStartX128;

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

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

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

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

    /// @notice Initializes secondsPerLiquidityPeriodStartX128 for a position
    /// @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
    function initializeSecondsStart(
        PositionInfo storage position,
        PositionPeriodSecondsInRangeParams memory secondsInRangeParams,
        uint160 secondsPerLiquidityPeriodX128
    ) internal {
        // record initialized
        position.periodRewardInfo[secondsInRangeParams.period].initialized = true;

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

            position.periodRewardInfo[secondsInRangeParams.period].secondsDebtX96 = -int256(periodSecondsInsideX96);
        }

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

        position
            .periodRewardInfo[secondsInRangeParams.period]
            .secondsPerLiquidityPeriodStartX128 = secondsPerLiquidityPeriodIntX128;
    }

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

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

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

        if (params.liquidityDelta != 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

                // write an oracle entry
                (states.slot0.observationIndex, states.slot0.observationCardinality) = Oracle.write(
                    states.observations,
                    _slot0.observationIndex,
                    States._blockTimestamp(),
                    _slot0.tick,
                    liquidityBefore,
                    _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);
            } 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;
    }

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

    struct ObservationCache {
        int56 tickCumulative;
        uint160 secondsPerLiquidityCumulativeX128;
    }

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

        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) {
            uint32 time = States._blockTimestamp();
            ObservationCache memory observationCache;
            (observationCache.tickCumulative, observationCache.secondsPerLiquidityCumulativeX128) = Oracle
                .observeSingle(
                    states.observations,
                    time,
                    0,
                    states.slot0.tick,
                    states.slot0.observationIndex,
                    states.liquidity,
                    states.slot0.observationCardinality
                );

            cache.flippedLower = Tick.update(
                states._ticks,
                Tick.UpdateTickParams(
                    params.tickLower,
                    params.tick,
                    params.liquidityDelta,
                    cache.feeGrowthGlobal0X128,
                    cache.feeGrowthGlobal1X128,
                    observationCache.secondsPerLiquidityCumulativeX128,
                    observationCache.tickCumulative,
                    time,
                    false,
                    states.maxLiquidityPerTick
                )
            );
            cache.flippedUpper = Tick.update(
                states._ticks,
                Tick.UpdateTickParams(
                    params.tickUpper,
                    params.tick,
                    params.liquidityDelta,
                    cache.feeGrowthGlobal0X128,
                    cache.feeGrowthGlobal1X128,
                    observationCache.secondsPerLiquidityCumulativeX128,
                    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 = Oracle.periodCumulativesInside(
                uint32(period),
                params.tickLower,
                params.tickUpper
            );

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

            _updatePositionLiquidity(
                position,
                states,
                period,
                _positionHash,
                params.liquidityDelta,
                cache.feeGrowthInside0X128,
                cache.feeGrowthInside1X128,
                secondsPerLiquidityPeriodX128
            );
            /*
            _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 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
    function positionPeriodSecondsInRange(
        PositionPeriodSecondsInRangeParams memory params
    ) public view returns (uint256 periodSecondsInsideX96) {
        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;
        int160 secondsPerLiquidityPeriodStartX128;

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

            liquidity = checkpoints[checkpointIndex].liquidity;

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

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

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

        RewardInfo storage rewardInfo = states.positions[_positionHash].periodRewardInfo[params.period];
        int256 secondsDebtX96 = rewardInfo.secondsDebtX96;

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

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

File 24 of 33 : 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 25 of 33 : 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 26 of 33 : 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 27 of 33 : 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;
}

struct RewardInfo {
    // 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;
}

// 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;
    mapping(uint256 => RewardInfo) periodRewardInfo;
}

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

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

// 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 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;
        mapping(int24 => TickInfo) _ticks;
        mapping(int16 => uint256) tickBitmap;
        mapping(bytes32 => PositionInfo) positions;
        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 28 of 33 : 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 29 of 33 : 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;
    }

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

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

    /// @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 previous period end's seconds per liquidity
        uint256 endSecondsPerLiquidityPeriodX128;
        // 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)
    function cross(
        mapping(int24 => TickInfo) storage self,
        CrossParams calldata params
    ) external returns (int128 liquidityNet) {
        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;
        }

        info.tickCumulativeOutside = params.tickCumulative - info.tickCumulativeOutside;
        info.secondsOutside = params.time - info.secondsOutside;
        liquidityNet = info.liquidityNet;
    }

    /// @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 30 of 33 : 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 31 of 33 : 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 32 of 33 : 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 33 of 33 : 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": 800
  },
  "metadata": {
    "bytecodeHash": "none"
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {
    "contracts/v2/libraries/Oracle.sol": {
      "Oracle": "0x4a76a2f26cb26d4d4246470cc95e4da4ab0a0e92"
    },
    "contracts/v2/libraries/Position.sol": {
      "Position": "0x1c16c172abcf809b89c0cb838c0bb4d9add01daf"
    },
    "contracts/v2/libraries/ProtocolActions.sol": {
      "ProtocolActions": "0xa2fb4a2f2e7bb3f8e97aced35ab6e59bea226262"
    },
    "contracts/v2/libraries/Tick.sol": {
      "Tick": "0xfc07c1996f8987e39e271b389c39a148baf24ba4"
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"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":"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":"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":"_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":"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"}],"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[]"}],"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"}],"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"}],"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"}],"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"}],"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"}],"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":"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":"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"}]

6080604052600080516020620058ed8339815191526000553480156200002457600080fd5b5060006200003c6200005960201b620030ae1760201c565b6201000f01805463ff00000019166301000000179055506200006c565b600080516020620058ed83398151915290565b615871806200007c6000396000f3fe608060405234801561001057600080fd5b50600436106102c85760003560e01c806398bbc3c71161017b578063d340ef8a116100d8578063ea4a11041161008c578063f305839911610071578063f3058399146105bd578063f30dba93146105c5578063f637731d146105ec576102c8565b8063ea4a110414610587578063eabb5622146105aa576102c8565b8063ddca3f43116100bd578063ddca3f431461054c578063dfc8b61514610554578063e57c0ca914610567576102c8565b8063d340ef8a1461052f578063da3c300d14610537576102c8565b8063add5887e1161012f578063c45a015511610114578063c45a01551461050a578063d0c93a7c14610512578063d21220a714610527576102c8565b8063add5887e146104ef578063c2e0f9b214610502576102c8565b8063a02f106911610160578063a02f1069146104a7578063a34123a7146104ba578063a38807f2146104cd576102c8565b806398bbc3c71461048c5780639918fbb614610494576102c8565b80634f1eb3d811610229578063725d13ae116101dd5780638221b8c1116101c25780638221b8c11461044557806385b6672914610458578063883bdbfd1461046b576102c8565b8063725d13ae1461042a5780637b7d549d1461043d576102c8565b80635339c2961161020e5780635339c296146103fc5780636847456a1461040f57806370cf754a14610422576102c8565b80634f1eb3d8146103c5578063514ea4bf146103d8576102c8565b806332148f67116102805780633c8a7d8d116102655780633c8a7d8d1461038a578063461413191461039d578063490e6cbc146103b2576102c8565b806332148f671461035a5780633850c7bd1461036f576102c8565b80631a686502116102b15780631a6865021461030c5780631ad8b03b14610321578063252c09d714610337576102c8565b80630dfe1681146102cd578063128acb08146102eb575b600080fd5b6102d56105ff565b6040516102e29190614fce565b60405180910390f35b6102fe6102f9366004614829565b61061b565b6040516102e292919061528b565b6103146113bf565b6040516102e291906155d5565b6103296113db565b6040516102e2929190615641565b61034a610345366004614c24565b611421565b6040516102e294939291906157a5565b61036d610368366004614df8565b6114b3565b005b6103776115e0565b6040516102e297969594939291906156ca565b6102fe6103983660046148b0565b611698565b6103a56116bb565b6040516102e29190615282565b61036d6103c0366004614abb565b6116ce565b6103296103d33660046148ff565b611a3e565b6103eb6103e6366004614c24565b611a5e565b6040516102e295949392919061567c565b6103a561040a366004614c5d565b611ab7565b6102fe61041d366004614eec565b611ae4565b610314611c90565b61036d6104383660046147ae565b611cac565b61036d611e4d565b6102fe6104533660046149b5565b611ebb565b61032961046636600461496b565b612122565b61047e610479366004614b23565b612272565b6040516102e292919061507f565b6102d561237c565b6103a56104a2366004614e94565b612398565b6103296104b5366004614a47565b61245d565b6102fe6104c8366004614cca565b612676565b6104e06104db366004614c98565b612692565b6040516102e2939291906152f1565b6102d56104fd366004614f3a565b6127a1565b61036d612839565b6102d5612b07565b61051a612b20565b6040516102e29190615260565b6102d5612b3d565b6103a5612b59565b61053f612b6c565b6040516102e29190615728565b61053f612b8b565b6103a5610562366004614e94565b612ba5565b61057a610575366004614b23565b612c62565b6040516102e2919061503b565b61059a610595366004614c24565b612cfb565b6040516102e29493929190615775565b61036d6105b8366004614e7a565b612d86565b6103a5612de9565b6105d86105d3366004614c7e565b612dfc565b6040516102e29897969594939291906155e9565b61036d6105fa366004614e14565b612e97565b60006106096130ae565b600201546001600160a01b0316905090565b600080610626612839565b60006106306130ae565b9050866106585760405162461bcd60e51b815260040161064f90615408565b60405180910390fd5b6040805160e08101825260058301546001600160a01b0381168252600160a01b8104600290810b810b900b602083015261ffff600160b81b8204811693830193909352600160c81b810483166060830152600160d81b8104909216608082015260ff600160e81b8304811660a0830152600160f01b909204909116151560c082018190526106f85760405162461bcd60e51b815260040161064f90615506565b886107435780600001516001600160a01b0316876001600160a01b031611801561073e575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038816105b610775565b80600001516001600160a01b0316876001600160a01b031610801561077557506401000276a36001600160a01b038816115b6107915760405162461bcd60e51b815260040161064f906154cd565b60058201805460ff60f01b191690556107a8614533565b6107b0614577565b600062093a806107be6130d2565b63ffffffff16816107cb57fe5b0463ffffffff1690506040518061010001604052808d6107f65760048660a0015160ff16901c610809565b60108660a0015160ff168161080757fe5b065b60ff168152600b8701546001600160801b0316602082015260400161082c6130d2565b63ffffffff168152602001600060060b815260200160006001600160a01b0316815260200160001515815260200160008d131515815260200186600601600084815260200190815260200160002060000160009054906101000a900463ffffffff1663ffffffff1681525092506040518061012001604052808c81526020016000815260200185600001516001600160a01b03168152602001856020015160020b81526020018d6108e15786600901546108e7565b86600801545b815260006020808301829052868101516001600160801b031660408085019190915260e088015163ffffffff16835260068a0180835281842054600160501b90046001600160a01b0316606086015295835294905292909220546401000000009004600290810b900b60809092019190915290505b8051158015906109825750886001600160a01b031681604001516001600160a01b031614155b15610efb5761098f6145c3565b60408201516001600160a01b03168152606082015160038601546109c291600d880191600160b81b900460020b8f6130d6565b15156040830152600290810b810b60208301819052620d89e719910b12156109f357620d89e7196020820152610a12565b6020810151620d89e860029190910b1315610a1257620d89e860208201525b610a1f8160200151613218565b6001600160a01b031660608201526040820151610aa0908d610a59578b6001600160a01b031683606001516001600160a01b031611610a73565b8b6001600160a01b031683606001516001600160a01b0316105b610a81578260600151610a83565b8b5b60c0850151855160038a0154600160a01b900462ffffff1661354a565b60c08086019190915260a085019190915260808401919091526001600160a01b03909116604084015283015115610b1057610ae48160c0015182608001510161373c565b825103825260a0810151610b0690610afb9061373c565b602084015190613752565b6020830152610b4b565b610b1d8160a0015161373c565b825101825260c08101516080820151610b4591610b3a910161373c565b60208401519061376e565b60208301525b825160ff1615610b9e5760006064846000015160050260320160ff168360c001510281610b7457fe5b60c0840180519290910491829003905260a0840180519091016001600160801b0316905250610bd7565b600060648260c0015160050281610bb157fe5b60c0840180519290910491829003905260a0840180519091016001600160801b03169052505b60c08201516001600160801b031615610c1657610c0a8160c00151600160801b8460c001516001600160801b0316613784565b60808301805190910190525b80606001516001600160a01b031682604001516001600160a01b03161415610eba57806040015115610e91578260a00151610d1757734a76a2f26cb26d4d4246470cc95e4da4ab0a0e92634e81939d86600f01856040015160008860200151896040015189602001518b606001516040518863ffffffff1660e01b8152600401610ca69796959493929190615215565b604080518083038186803b158015610cbd57600080fd5b505af4158015610cd1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cf59190614cf5565b6001600160a01b03166080850152600690810b900b6060840152600160a08401525b610d1f6145ff565b8c15610d3e576080830151602082015260098601546040820152610d53565b60088601546020820152608083015160408201525b73fc07c1996f8987e39e271b389c39a148baf24ba463bf7ca94e87600c01604051806101000160405280866020015160020b8152602001856020015181526020018560400151815260200188608001516001600160a01b031681526020018760e00151815260200187610100015160020b8152602001886060015160060b8152602001886040015163ffffffff168152506040518363ffffffff1660e01b8152600401610e0192919061534d565b60206040518083038186803b158015610e1957600080fd5b505af4158015610e2d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e519190614c3c565b600f90810b900b81528c15610e6f578051600003600f90810b900b81525b610e818360c001518260000151613833565b6001600160801b031660c0840152505b8b610ea0578060200151610ea9565b60018160200151035b600290810b900b6060830152610ef5565b80600001516001600160a01b031682604001516001600160a01b031614610ef557610ee882604001516138e9565b600290810b900b60608301525b5061095c565b826020015160020b816060015160020b1461107657600080734a76a2f26cb26d4d4246470cc95e4da4ab0a0e9263875f3f1287600f0187604001518760400151896020015189602001518b606001518c608001516040518863ffffffff1660e01b8152600401610f719796959493929190615140565b604080518083038186803b158015610f8857600080fd5b505af4158015610f9c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fc09190614e4c565b6040850151606086015160058a0180547fffffffffff0000ffffffffffffffffffffffffffffffffffffffffffffffffff16600160c81b61ffff95861602177fffffffffffffff0000ffffffffffffffffffffffffffffffffffffffffffffff16600160b81b95909416949094029290921762ffffff60a01b1916600160a01b62ffffff60029490940b9390931692909202919091176001600160a01b0319166001600160a01b039091161790555061109d9050565b60408101516005850180546001600160a01b0319166001600160a01b039092169190911790555b8060c001516001600160801b031682602001516001600160801b0316146110e55760c0810151600b850180546001600160801b0319166001600160801b039092169190911790555b8a15611139576080810151600885015560a08101516001600160801b0316156111345760a0810151600a850180546001600160801b031981166001600160801b03918216909301169190911790555b611183565b6080810151600985015560a08101516001600160801b0316156111835760a0810151600a850180546001600160801b03808216600160801b92839004821690940116029190911790555b8160c0015115158b1515146111a057602081015181518b036111ad565b80600001518a0381602001515b90965094508a1561127c5760008512156111de5760038401546111de906001600160a01b03168d6000889003613c15565b60006111e8613d5c565b60405163654b648760e01b8152909150339063654b648790611214908a908a908e908e90600401615299565b600060405180830381600087803b15801561122e57600080fd5b505af1158015611242573d6000803e3d6000fd5b5050505061124e613d5c565b6112588289613e81565b11156112765760405162461bcd60e51b815260040161064f90615523565b5061133c565b60008612156112a25760028401546112a2906001600160a01b03168d6000899003613c15565b60006112ac613e91565b60405163654b648760e01b8152909150339063654b6487906112d8908a908a908e908e90600401615299565b600060405180830381600087803b1580156112f257600080fd5b505af1158015611306573d6000803e3d6000fd5b50505050611312613e91565b61131c8288613e81565b111561133a5760405162461bcd60e51b815260040161064f90615523565b505b8b6001600160a01b0316336001600160a01b03167fc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67888885604001518660c0015187606001516040516113939594939291906152b9565b60405180910390a3505050600501805460ff60f01b1916600160f01b1790559097909650945050505050565b60006113c96130ae565b600b01546001600160801b0316905090565b60008060006113e86130ae565b60408051808201909152600a91909101546001600160801b03808216808452600160801b90920416602090920182905293509150509091565b60008060008060006114316130ae565b600f018661ffff811061144057fe5b60408051608081018252919092015463ffffffff81168083526401000000008204600690810b810b900b602084018190526b01000000000000000000000083046001600160a01b0316948401859052600160f81b90920460ff161515606090930183905299909850919650945092505050565b6114bb613f14565b60006114c56130ae565b6005810154604051630e51299960e01b8152919250600160d81b900461ffff1690600090734a76a2f26cb26d4d4246470cc95e4da4ab0a0e9290630e5129999061151a90600f8701908690899060040161510c565b60206040518083038186803b15801561153257600080fd5b505af4158015611546573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061156a9190614e30565b60058401805461ffff808416600160d81b810261ffff60d81b19909316929092179092559192508316146115d2577fac49e518f90a358f652e4400164f05a5d8f7e35e7747279bc3a93dbf584e125a82826040516115c9929190615713565b60405180910390a15b5050506115dd613f5c565b50565b6000806000806000806000806115f46130ae565b6040805160e081018252600592909201546001600160a01b038116808452600160a01b8204600290810b810b900b6020850181905261ffff600160b81b84048116948601859052600160c81b8404811660608701819052600160d81b85049091166080870181905260ff600160e81b8604811660a08901819052600160f01b90960416151560c0909701879052929e919d50939b5092995097509550909350915050565b6000806116ab8860008989898989611ebb565b915091505b965096945050505050565b60006116c56130ae565b60090154905090565b6116d6613f14565b60006116e06130ae565b600b8101549091506001600160801b03168061170e5760405162461bcd60e51b815260040161064f9061545c565b6003820154600090611731908890600160a01b900462ffffff16620f4240613f85565b6003840154909150600090611757908890600160a01b900462ffffff16620f4240613f85565b90506000611763613d5c565b9050600061176f613e91565b90508915611790576002860154611790906001600160a01b03168c8c613c15565b88156117af5760038601546117af906001600160a01b03168c8b613c15565b604051633797d3b360e21b8152339063de5f4ecc906117d890879087908d908d90600401615299565b600060405180830381600087803b1580156117f257600080fd5b505af1158015611806573d6000803e3d6000fd5b50505050611812614623565b61181a613d5c565b8152611824613e91565b602082015280516118358487613e81565b11156118535760405162461bcd60e51b815260040161064f906153cf565b60208101516118628386613e81565b11156118805760405162461bcd60e51b815260040161064f90615424565b611888614623565b81518490038082526020808401518590039083015215611931576005880154600160e81b9004600f16600081156118cd57825160ff831690816118c757fe5b046118d0565b60005b90506001600160801b0381161561190557600a8a0180546001600160801b038082168401166001600160801b03199091161790555b61192381846000015103600160801b8b6001600160801b0316613784565b60088b018054909101905550505b6020810151156119ce576005880154600160e81b900460041c600f166000811561196b578160ff1683602001518161196557fe5b0461196e565b60005b90506001600160801b038116156119a257600a8a0180546001600160801b03600160801b8083048216850182160291161790555b6119c081846020015103600160801b8b6001600160801b0316613784565b60098b018054909101905550505b8c6001600160a01b0316336001600160a01b03167fbdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca6338e8e85600001518660200151604051611a1f9493929190615738565b60405180910390a35050505050505050611a37613f5c565b5050505050565b600080611a508760008888888861245d565b915091509550959350505050565b600080600080600080611a6f6130ae565b6000978852600e01602052505060409094208054600182015460028301546003909301546001600160801b03928316989197509295508183169450600160801b909204169150565b6000611ac16130ae565b600d0160008360010b60010b81526020019081526020016000205490505b919050565b600080611aef613f14565b611af7612839565b6000806000731c16c172abcf809b89c0cb838c0bb4d9add01daf6368e5d9076040518060a00160405280336001600160a01b031681526020018c81526020018b60020b81526020018a60020b8152602001611b5a8a6001600160801b0316613fbf565b600003600f0b8152506040518263ffffffff1660e01b8152600401611b7f9190615540565b60606040518083038186803b158015611b9757600080fd5b505af4158015611bab573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bcf9190614d81565b9250925092508160000394508060000393506000851180611bf05750600084115b15611c2f576003830180546001600160801b038082168089018216600160801b93849004831689019092169092029091176001600160801b0319161790555b8660020b8860020b336001600160a01b03167f0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c898989604051611c749392919061565b565b60405180910390a4505050611c87613f5c565b94509492505050565b6000611c9a6130ae565b600401546001600160801b0316905090565b6000611cb66130ae565b6201000f8101549091506301000000900460ff1615611cd457600080fd5b80546001600160a01b038089166001600160a01b0319928316178355600183018054898316908416179055600280840180548984169085161790556003840180546201000f8601805462ffffff191662ffffff808b169182179092559388900b16600160b81b027fffffffffffff000000ffffffffffffffffffffffffffffffffffffffffffffff600160a01b9490940262ffffff60a01b19958b1692909616919091179390931693909317161790556040516382c66f8760e01b815273fc07c1996f8987e39e271b389c39a148baf24ba4906382c66f8790611dbb908590600401615260565b60206040518083038186803b158015611dd357600080fd5b505af4158015611de7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e0b9190614dae565b6004820180546001600160801b03929092166001600160801b03199092169190911790556201000f01805463ff00000019166301000000179055505050505050565b611e55613f14565b73a2fb4a2f2e7bb3f8e97aced35ab6e59bea226262637b7d549d6040518163ffffffff1660e01b815260040160006040518083038186803b158015611e9957600080fd5b505af4158015611ead573d6000803e3d6000fd5b50505050611eb9613f5c565b565b600080611ec6613f14565b611ece612839565b6000856001600160801b031611611ee457600080fd5b611eec614623565b731c16c172abcf809b89c0cb838c0bb4d9add01daf6368e5d9076040518060a001604052808d6001600160a01b031681526020018c81526020018b60020b81526020018a60020b8152602001611f4a8a6001600160801b0316613fbf565b600f0b8152506040518263ffffffff1660e01b8152600401611f6c9190615540565b60606040518083038186803b158015611f8457600080fd5b505af4158015611f98573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fbc9190614d81565b60208401819052818452909450925060009050808415611fe157611fde613d5c565b91505b8315611ff257611fef613e91565b90505b604051633e48f41760e01b81523390633e48f4179061201b90889088908c908c90600401615299565b600060405180830381600087803b15801561203557600080fd5b505af1158015612049573d6000803e3d6000fd5b5050505060008511156120865761205e613d5c565b6120688387613e81565b11156120865760405162461bcd60e51b815260040161064f90615494565b83156120bc57612094613e91565b61209e8286613e81565b11156120bc5760405162461bcd60e51b815260040161064f906154ea565b8860020b8a60020b8d6001600160a01b03167f7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde338c8a8a6040516121039493929190614fe2565b60405180910390a4505050612116613f5c565b97509795505050505050565b60008061212d613f14565b60006121376130ae565b8054604080516331056e5760e21b815290519293506001600160a01b039091169163c415b95c91600480820192602092909190829003018186803b15801561217e57600080fd5b505afa158015612192573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121b69190614792565b6001600160a01b0316336001600160a01b0316146121d357600080fd5b6040516385b6672960e01b815273a2fb4a2f2e7bb3f8e97aced35ab6e59bea226262906385b667299061220e90899089908990600401615011565b604080518083038186803b15801561222557600080fd5b505af4158015612239573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061225d9190614dca565b925092505061226a613f5c565b935093915050565b606080600061227f6130ae565b9050734a76a2f26cb26d4d4246470cc95e4da4ab0a0e926326e0776782600f016122a76130d2565b6005850154600b8601546040517fffffffff0000000000000000000000000000000000000000000000000000000060e087901b16815261231b9493928c928c92600160a01b830460020b9261ffff600160b81b82048116936001600160801b031692600160c81b9092041690600401615188565b60006040518083038186803b15801561233357600080fd5b505af4158015612347573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261236f9190810190614b63565b92509250505b9250929050565b60006123866130ae565b600101546001600160a01b0316905090565b6040805160a0810182528681526001600160a01b0386166020820152808201859052600284810b606083015283900b6080820152905163d2e6311b60e01b8152600091731c16c172abcf809b89c0cb838c0bb4d9add01daf9163d2e6311b916124039160040161558c565b60206040518083038186803b15801561241b57600080fd5b505af415801561242f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124539190614d69565b9695505050505050565b600080612468613f14565b60006124726130ae565b90506000731c16c172abcf809b89c0cb838c0bb4d9add01daf639c766c9d83600e01338c8c8c6040518663ffffffff1660e01b81526004016124b895949392919061531b565b60206040518083038186803b1580156124d057600080fd5b505af41580156124e4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125089190614d69565b60038101549091506001600160801b03908116908716116125295785612538565b60038101546001600160801b03165b60038201549094506001600160801b03600160801b9091048116908616116125605784612576565b6003810154600160801b90046001600160801b03165b92506001600160801b038416156125ca576003810180546001600160801b031981166001600160801b0391821687900382161790915560028301546125ca916001600160a01b03909116908c908716613c15565b6001600160801b0383161561261f57600380820180546001600160801b03600160801b8083048216889003821602918116919091179091559083015461261f916001600160a01b03909116908c908616613c15565b8660020b8860020b336001600160a01b03167f70935338e69775456a85ddef226c395fb668b63fa0115f5f20610b388e6ca9c08d888860405161266493929190615011565b60405180910390a450506116b0613f5c565b6000806126866000868686611ae4565b91509150935093915050565b60008060008360020b8560020b126126bc5760405162461bcd60e51b815260040161064f906153eb565b620d89e719600286900b12156126e45760405162461bcd60e51b815260040161064f906154b0565b620d89e8600285900b131561270b5760405162461bcd60e51b815260040161064f90615477565b6040516351c403f960e11b8152734a76a2f26cb26d4d4246470cc95e4da4ab0a0e929063a38807f290612744908890889060040161526e565b60606040518083038186803b15801561275c57600080fd5b505af4158015612770573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127949190614d2b565b9250925092509250925092565b6040516356eac43f60e11b8152600090734a76a2f26cb26d4d4246470cc95e4da4ab0a0e929063add5887e906127df90879087908790600401615753565b60206040518083038186803b1580156127f757600080fd5b505af415801561280b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061282f9190614792565b90505b9392505050565b60006128436130ae565b60078101549091508062093a806128586130d2565b63ffffffff168161286557fe5b0463ffffffff1614612b03576040805160e08101825260058401546001600160a01b0381168252600160a01b8104600290810b810b900b602083015261ffff600160b81b8204811693830193909352600160c81b810483166060830152600160d81b8104909216608082015260ff600160e81b8304811660a0830152600160f01b909204909116151560c0820152600062093a806129016130d2565b63ffffffff168161290e57fe5b0463ffffffff1690508084600701819055506000734a76a2f26cb26d4d4246470cc95e4da4ab0a0e9263c51185d886600f018560400151856040518463ffffffff1660e01b815260040161296493929190615126565b60206040518083038186803b15801561297c57600080fd5b505af4158015612990573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129b49190614792565b6020848101516000878152600689019092526040909120805469ffffff00000000000000191667010000000000000062ffffff60029490940b9390931692909202919091177fffff0000000000000000000000000000000000000000ffffffffffffffffffff16600160501b6001600160a01b038416021790559050612a3861463d565b63ffffffff8086168252602094850151600290810b810b868401908152600095865260068901909652604094859020835181549751968501516060909501516001600160a01b0316600160501b027fffff0000000000000000000000000000000000000000ffffffffffffffffffff95840b62ffffff9081166701000000000000000269ffffff00000000000000199990950b166401000000000266ffffff00000000199290951663ffffffff19909916989098171692909217949094169390931716929092179055505b5050565b6000612b116130ae565b546001600160a01b0316905090565b6000612b2a6130ae565b60030154600160b81b900460020b905090565b6000612b476130ae565b600301546001600160a01b0316905090565b6000612b636130ae565b60070154905090565b6000612b766130ae565b60030154600160a01b900462ffffff16919050565b6000612b956130ae565b6201000f015462ffffff16905090565b600080612bb06130ae565b90506000731c16c172abcf809b89c0cb838c0bb4d9add01daf639c766c9d83600e01898989896040518663ffffffff1660e01b8152600401612bf695949392919061531b565b60206040518083038186803b158015612c0e57600080fd5b505af4158015612c22573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c469190614d69565b6000988952600401602052505060409095205495945050505050565b6060818067ffffffffffffffff81118015612c7c57600080fd5b50604051908082528060200260200182016040528015612ca6578160200160208202803683370190505b50915060005b81811015612cf3576000858583818110612cc257fe5b90506020020135905060008154905080858481518110612cde57fe5b60209081029190910101525050600101612cac565b505092915050565b6000806000806000612d0b6130ae565b600096875260060160209081526040968790208751608081018952905463ffffffff81168083526401000000008204600290810b810b810b9484018590526701000000000000008304810b810b900b9983018a9052600160501b9091046001600160a01b031660609092018290529891979650945092505050565b60405163755dab1160e11b815273a2fb4a2f2e7bb3f8e97aced35ab6e59bea2262629063eabb562290612dbd908490600401615728565b60006040518083038186803b158015612dd557600080fd5b505af4158015611a37573d6000803e3d6000fd5b6000612df36130ae565b60080154905090565b6000806000806000806000806000612e126130ae565b60029a8b0b8b0b6000908152600c9190910160205260409020805460018201549b8201546003909201546001600160801b0382169d600160801b909204600f0b9c9b50919950600682900b985067010000000000000082046001600160a01b03169750600160d81b820463ffffffff169650600160f81b90910460ff16945092505050565b6000612ea16130ae565b60058101549091506001600160a01b031615612ecf5760405162461bcd60e51b815260040161064f90615440565b6000612eda836138e9565b9050600080734a76a2f26cb26d4d4246470cc95e4da4ab0a0e9263eed5cff985600f0160006040518363ffffffff1660e01b8152600401612f1c9291906150f8565b604080518083038186803b158015612f3357600080fd5b505af4158015612f47573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f6b9190614e4c565b91509150612f77612839565b6040805160e0810182526001600160a01b038716808252600286810b60208401819052600084860181905261ffff888116606087018190529088166080870181905260a0870192909252600160c09096019590955260058a018054600160f01b6001600160a01b031990911690951762ffffff60a01b1916600160a01b62ffffff9490950b9390931693909302919091177fffffffffff00000000ffffffffffffffffffffffffffffffffffffffffffffff16600160c81b9094029390931761ffff60d81b1916600160d81b909302929092177fff0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff16179055517f98636036cb66a9c19a37435efc1e90142190214e8abeb821bdba3f2990dd4c959061309f90879086906156ae565b60405180910390a15050505050565b7f568f905fee3c29dbecf3583ddfaf086f7336b6bee88b499cc887c595fb7bf1da90565b4290565b60008060008460020b8660020b816130ea57fe5b05905060008660020b12801561311157508460020b8660020b8161310a57fe5b0760020b15155b1561311b57600019015b83156131905760008061312d83613fd0565b600182810b810b600090815260208d9052604090205460ff83169190911b8001600019019081168015159750929450909250908561317257888360ff16860302613185565b8861317c82613fe2565b840360ff168603025b96505050505061320e565b60008061319f83600101613fd0565b91509150600060018260ff166001901b031990506000818b60008660010b60010b81526020019081526020016000205416905080600014159550856131f157888360ff0360ff16866001010102613207565b88836131fc83614082565b0360ff168660010101025b9650505050505b5094509492505050565b60008060008360020b1261322f578260020b613237565b8260020b6000035b9050620d89e8811115613275576040805162461bcd60e51b81526020600482015260016024820152601560fa1b604482015290519081900360640190fd5b60006001821661328957600160801b61329b565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff16905060028216156132cf576ffff97272373d413259a46990580e213a0260801c5b60048216156132ee576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b600882161561330d576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b601082161561332c576fffcb9843d60f6159c9db58835c9266440260801c5b602082161561334b576fff973b41fa98c081472e6896dfb254c00260801c5b604082161561336a576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615613389576ffe5dee046a99a2a811c461f1969c30530260801c5b6101008216156133a9576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b6102008216156133c9576ff987a7253ac413176f2b074cf7815e540260801c5b6104008216156133e9576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615613409576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615613429576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615613449576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615613469576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615613489576f31be135f97d08fd981231505542fcfa60260801c5b620100008216156134aa576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b620200008216156134ca576e5d6af8dedb81196699c329225ee6040260801c5b620400008216156134e9576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615613506576b048a170391f7dc42444e8fa20260801c5b60008460020b131561352157806000198161351d57fe5b0490505b640100000000810615613535576001613538565b60005b60ff16602082901c0192505050919050565b60008080806001600160a01b03808916908a1610158187128015906135cf5760006135838989620f42400362ffffff16620f4240613784565b90508261359c576135978c8c8c600161416c565b6135a9565b6135a98b8d8c60016141e7565b95508581106135ba578a96506135c9565b6135c68c8b83866142a4565b96505b50613619565b816135e6576135e18b8b8b60006141e7565b6135f3565b6135f38a8c8b600061416c565b935083886000031061360757899550613619565b6136168b8a8a600003856142f0565b95505b6001600160a01b038a811690871614821561367c578080156136385750815b61364e57613649878d8c60016141e7565b613650565b855b955080801561365d575081155b6136735761366e878d8c600061416c565b613675565b845b94506136c6565b8080156136865750815b61369c576136978c888c600161416c565b61369e565b855b95508080156136ab575081155b6136c1576136bc8c888c60006141e7565b6136c3565b845b94505b811580156136d657508860000385115b156136e2578860000394505b81801561370157508a6001600160a01b0316876001600160a01b031614155b1561371057858903935061372d565b61372a868962ffffff168a620f42400362ffffff16613f85565b93505b50505095509550955095915050565b6000600160ff1b821061374e57600080fd5b5090565b8082038281131560008312151461376857600080fd5b92915050565b8181018281121560008312151461376857600080fd5b60008080600019858709868602925082811090839003039050806137ba57600084116137af57600080fd5b508290049050612832565b8084116137c657600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b60008082600f0b121561389857826001600160801b03168260000384039150816001600160801b031610613893576040805162461bcd60e51b81526020600482015260026024820152614c5360f01b604482015290519081900360640190fd5b613768565b826001600160801b03168284019150816001600160801b03161015613768576040805162461bcd60e51b81526020600482015260026024820152614c4160f01b604482015290519081900360640190fd5b60006401000276a36001600160a01b03831610801590613925575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038316105b61395a576040805162461bcd60e51b81526020600482015260016024820152602960f91b604482015290519081900360640190fd5b77ffffffffffffffffffffffffffffffffffffffff00000000602083901b166001600160801b03811160071b81811c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211600190811b92831c979088119617909417909217179091171717608081106139fb57607f810383901c9150613a05565b80607f0383901b91505b908002607f81811c60ff83811c9190911c800280831c81831c1c800280841c81841c1c800280851c81851c1c800280861c81861c1c800280871c81871c1c800280881c81881c1c800280891c81891c1c8002808a1c818a1c1c8002808b1c818b1c1c8002808c1c818c1c1c8002808d1c818d1c1c8002808e1c9c81901c9c909c1c80029c8d901c9e9d607f198f0160401b60c09190911c678000000000000000161760c19b909b1c674000000000000000169a909a1760c29990991c672000000000000000169890981760c39790971c671000000000000000169690961760c49590951c670800000000000000169490941760c59390931c670400000000000000169290921760c69190911c670200000000000000161760c79190911c670100000000000000161760c89190911c6680000000000000161760c99190911c6640000000000000161760ca9190911c6620000000000000161760cb9190911c6610000000000000161760cc9190911c6608000000000000161760cd9190911c66040000000000001617693627a301d71055774c8581026f028f6481ab7f045a5af012a19d003aa9198101608090811d906fdb2df09e81959a81455e260799a0632f8301901d600281810b9083900b14613c0657886001600160a01b0316613bea82613218565b6001600160a01b03161115613bff5781613c01565b805b613c08565b815b9998505050505050505050565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b1781529251825160009485949389169392918291908083835b60208310613c915780518252601f199092019160209182019101613c72565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114613cf3576040519150601f19603f3d011682016040523d82523d6000602084013e613cf8565b606091505b5091509150818015613d26575080511580613d265750808060200190516020811015613d2357600080fd5b50515b611a37576040805162461bcd60e51b81526020600482015260026024820152612a2360f11b604482015290519081900360640190fd5b600080613d676130ae565b6002810154604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b1781529151815194955060009485946001600160a01b03169382918083835b60208310613de05780518252601f199092019160209182019101613dc1565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855afa9150503d8060008114613e40576040519150601f19603f3d011682016040523d82523d6000602084013e613e45565b606091505b5091509150818015613e5957506020815110155b613e6257600080fd5b808060200190516020811015613e7757600080fd5b5051935050505090565b8082018281101561376857600080fd5b600080613e9c6130ae565b6003810154604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b1781529151815194955060009485946001600160a01b031693829180838360208310613de05780518252601f199092019160209182019101613dc1565b6000613f1e6130ae565b6005810154909150600160f01b900460ff16613f4c5760405162461bcd60e51b815260040161064f90615506565b600501805460ff60f01b19169055565b6001613f666130ae565b6005018054911515600160f01b0260ff60f01b19909216919091179055565b6000613f92848484613784565b905060008280613f9e57fe5b8486091115612832576000198110613fb557600080fd5b6001019392505050565b80600f81900b8114611adf57600080fd5b60020b600881901d9161010090910790565b6000808211613ff057600080fd5b600160801b821061400357608091821c91015b68010000000000000000821061401b57604091821c91015b640100000000821061402f57602091821c91015b62010000821061404157601091821c91015b610100821061405257600891821c91015b6010821061406257600491821c91015b6004821061407257600291821c91015b60028210611adf57600101919050565b600080821161409057600080fd5b5060ff6001600160801b038216156140ab57607f19016140b3565b608082901c91505b67ffffffffffffffff8216156140cc57603f19016140d4565b604082901c91505b63ffffffff8216156140e957601f19016140f1565b602082901c91505b61ffff82161561410457600f190161410c565b601082901c91505b60ff82161561411e5760071901614126565b600882901c91505b600f8216156141385760031901614140565b600482901c91505b6003821615614152576001190161415a565b600282901c91505b6001821615611adf5760001901919050565b6000836001600160a01b0316856001600160a01b0316111561418c579293925b816141b9576141b4836001600160801b03168686036001600160a01b0316600160601b613784565b6141dc565b6141dc836001600160801b03168686036001600160a01b0316600160601b613f85565b90505b949350505050565b6000836001600160a01b0316856001600160a01b03161115614207579293925b7bffffffffffffffffffffffffffffffff000000000000000000000000606084901b166001600160a01b03868603811690871661424357600080fd5b8361427357866001600160a01b03166142668383896001600160a01b0316613784565b8161426d57fe5b04614299565b61429961428a8383896001600160a01b0316613f85565b886001600160a01b031661433c565b979650505050505050565b600080856001600160a01b0316116142bb57600080fd5b6000846001600160801b0316116142d157600080fd5b816142e3576141b48585856001614347565b6141dc8585856001614428565b600080856001600160a01b03161161430757600080fd5b6000846001600160801b03161161431d57600080fd5b8161432f576141b48585856000614428565b6141dc8585856000614347565b808204910615150190565b600081156143ba5760006001600160a01b0384111561437d5761437884600160601b876001600160801b0316613784565b614395565b6001600160801b038516606085901b8161439357fe5b045b90506143b26143ad6001600160a01b03881683613e81565b61451d565b9150506141df565b60006001600160a01b038411156143e8576143e384600160601b876001600160801b0316613f85565b6143ff565b6143ff606085901b6001600160801b03871661433c565b905080866001600160a01b03161161441657600080fd5b6001600160a01b0386160390506141df565b6000826144365750836141df565b7bffffffffffffffffffffffffffffffff000000000000000000000000606085901b1682156144d6576001600160a01b0386168481029085828161447657fe5b0414156144a7578181018281106144a55761449b83896001600160a01b031683613f85565b93505050506141df565b505b6144cd826144c8878a6001600160a01b031686816144c157fe5b0490613e81565b61433c565b925050506141df565b6001600160a01b038616848102908582816144ed57fe5b041480156144fa57508082115b61450357600080fd5b80820361449b6143ad846001600160a01b038b1684613f85565b806001600160a01b0381168114611adf57600080fd5b6040805161010081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081019190915290565b6040805161012081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e0810182905261010081019190915290565b6040805160e081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c081019190915290565b60405180606001604052806000600f0b815260200160008152602001600081525090565b604051806040016040528060008152602001600081525090565b60408051608081018252600080825260208201819052918101829052606081019190915290565b60008083601f840112614675578182fd5b50813567ffffffffffffffff81111561468c578182fd5b602083019150836020808302850101111561237557600080fd5b600082601f8301126146b6578081fd5b815160206146cb6146c6836157fa565b6157d6565b82815281810190858301838502870184018810156146e7578586fd5b855b8581101561470e5781516146fc81615818565b845292840192908401906001016146e9565b5090979650505050505050565b60008083601f84011261472c578182fd5b50813567ffffffffffffffff811115614743578182fd5b60208301915083602082850101111561237557600080fd5b8035600281900b8114611adf57600080fd5b8051600681900b8114611adf57600080fd5b803562ffffff81168114611adf57600080fd5b6000602082840312156147a3578081fd5b815161283281615818565b60008060008060008060c087890312156147c6578182fd5b86356147d181615818565b955060208701356147e181615818565b945060408701356147f181615818565b9350606087013561480181615818565b925061480f6080880161477f565b915061481d60a0880161475b565b90509295509295509295565b60008060008060008060a08789031215614841578384fd5b863561484c81615818565b955060208701358015158114614860578485fd5b945060408701359350606087013561487781615818565b9250608087013567ffffffffffffffff811115614892578283fd5b61489e89828a0161471b565b979a9699509497509295939492505050565b60008060008060008060a087890312156148c8578384fd5b86356148d381615818565b95506148e16020880161475b565b94506148ef6040880161475b565b935060608701356148778161582d565b600080600080600060a08688031215614916578283fd5b853561492181615818565b945061492f6020870161475b565b935061493d6040870161475b565b9250606086013561494d8161582d565b9150608086013561495d8161582d565b809150509295509295909350565b60008060006060848603121561497f578081fd5b833561498a81615818565b9250602084013561499a8161582d565b915060408401356149aa8161582d565b809150509250925092565b600080600080600080600060c0888a0312156149cf578485fd5b87356149da81615818565b9650602088013595506149ef6040890161475b565b94506149fd6060890161475b565b93506080880135614a0d8161582d565b925060a088013567ffffffffffffffff811115614a28578182fd5b614a348a828b0161471b565b989b979a50959850939692959293505050565b60008060008060008060c08789031215614a5f578384fd5b8635614a6a81615818565b955060208701359450614a7f6040880161475b565b9350614a8d6060880161475b565b92506080870135614a9d8161582d565b915060a0870135614aad8161582d565b809150509295509295509295565b600080600080600060808688031215614ad2578283fd5b8535614add81615818565b94506020860135935060408601359250606086013567ffffffffffffffff811115614b06578182fd5b614b128882890161471b565b969995985093965092949392505050565b60008060208385031215614b35578182fd5b823567ffffffffffffffff811115614b4b578283fd5b614b5785828601614664565b90969095509350505050565b60008060408385031215614b75578182fd5b825167ffffffffffffffff80821115614b8c578384fd5b818501915085601f830112614b9f578384fd5b81516020614baf6146c6836157fa565b82815281810190858301838502870184018b1015614bcb578889fd5b8896505b84871015614bf457614be08161476d565b835260019690960195918301918301614bcf565b5091880151919650909350505080821115614c0d578283fd5b50614c1a858286016146a6565b9150509250929050565b600060208284031215614c35578081fd5b5035919050565b600060208284031215614c4d578081fd5b815180600f0b8114612832578182fd5b600060208284031215614c6e578081fd5b81358060010b8114612832578182fd5b600060208284031215614c8f578081fd5b6128328261475b565b60008060408385031215614caa578182fd5b614cb38361475b565b9150614cc16020840161475b565b90509250929050565b600080600060608486031215614cde578081fd5b614ce78461475b565b925061499a6020850161475b565b60008060408385031215614d07578182fd5b614d108361476d565b91506020830151614d2081615818565b809150509250929050565b600080600060608486031215614d3f578081fd5b614d488461476d565b92506020840151614d5881615818565b60408501519092506149aa81615852565b600060208284031215614d7a578081fd5b5051919050565b600080600060608486031215614d95578081fd5b8351925060208401519150604084015190509250925092565b600060208284031215614dbf578081fd5b81516128328161582d565b60008060408385031215614ddc578182fd5b8251614de78161582d565b6020840151909250614d208161582d565b600060208284031215614e09578081fd5b813561283281615842565b600060208284031215614e25578081fd5b813561283281615818565b600060208284031215614e41578081fd5b815161283281615842565b60008060408385031215614e5e578182fd5b8251614e6981615842565b6020840151909250614d2081615842565b600060208284031215614e8b578081fd5b6128328261477f565b600080600080600060a08688031215614eab578283fd5b853594506020860135614ebd81615818565b935060408601359250614ed26060870161475b565b9150614ee06080870161475b565b90509295509295909350565b60008060008060808587031215614f01578182fd5b84359350614f116020860161475b565b9250614f1f6040860161475b565b91506060850135614f2f8161582d565b939692955090935050565b600080600060608486031215614f4e578081fd5b8335614f5981615852565b9250614f676020850161475b565b9150614f756040850161475b565b90509250925092565b60008284528282602086013780602084860101526020601f19601f85011685010190509392505050565b60060b9052565b6001600160801b03169052565b61ffff169052565b63ffffffff169052565b6001600160a01b0391909116815260200190565b6001600160a01b039490941684526001600160801b039290921660208401526040830152606082015260800190565b6001600160a01b039390931683526001600160801b03918216602084015216604082015260600190565b6020808252825182820181905260009190848201906040850190845b8181101561507357835183529284019291840191600101615057565b50909695505050505050565b604080825283519082018190526000906020906060840190828701845b828110156150bb57815160060b8452928401929084019060010161509c565b50505083810382850152845180825285830191830190845b8181101561470e5783516001600160a01b0316835292840192918401916001016150d3565b91825263ffffffff16602082015260400190565b92835261ffff918216602084015216604082015260600190565b92835261ffff919091166020830152604082015260600190565b96875261ffff958616602088015263ffffffff94909416604087015260029290920b60608601526001600160801b03166080850152821660a08401521660c082015260e00190565b600060e082018a8352602063ffffffff808c168286015260e06040860152828a8452610100860190508b9350845b8b8110156151dd5784356151c981615852565b8316825293830193908301906001016151b6565b50809450505050508560020b60608301526151fb6080830186614fbc565b61520860a0830185614faf565b613c0860c0830184614fbc565b96875263ffffffff958616602088015293909416604086015260029190910b606085015261ffff90811660808501526001600160801b0390921660a08401521660c082015260e00190565b60029190910b815260200190565b600292830b8152910b602082015260400190565b90815260200190565b918252602082015260400190565b600085825284602083015260606040830152612453606083018486614f7e565b94855260208501939093526001600160a01b039190911660408401526001600160801b0316606083015260020b608082015260a00190565b60069390930b83526001600160a01b0391909116602083015263ffffffff16604082015260600190565b9485526001600160a01b039390931660208501526040840191909152600290810b60608401520b608082015260a00190565b600061012082019050838252825160020b602083015260208301516040830152604083015160608301526001600160a01b036060840151166080830152608083015160a083015260a083015160020b60c083015260c08301516153b360e0840182614fa8565b5060e08301516153c7610100840182614fc4565b509392505050565b602080825260029082015261046360f41b604082015260600190565b602080825260039082015262544c5560e81b604082015260600190565b602080825260029082015261415360f01b604082015260600190565b602080825260029082015261463160f01b604082015260600190565b602080825260029082015261414960f01b604082015260600190565b6020808252600190820152601360fa1b604082015260600190565b60208082526003908201526254554d60e81b604082015260600190565b60208082526002908201526104d360f41b604082015260600190565b602080825260039082015262544c4d60e81b604082015260600190565b60208082526003908201526214d41360ea1b604082015260600190565b6020808252600290820152614d3160f01b604082015260600190565b6020808252600390820152624c4f4b60e81b604082015260600190565b60208082526003908201526249494160e81b604082015260600190565b600060a0820190506001600160a01b03835116825260208301516020830152604083015160020b6040830152606083015160020b60608301526080830151600f0b608083015292915050565b600060a082019050825182526001600160a01b03602084015116602083015260408301516040830152606083015160020b6060830152608083015160020b608083015292915050565b6001600160801b0391909116815260200190565b6001600160801b03989098168852600f9690960b60208801526040870194909452606086019290925260060b60808501526001600160a01b031660a084015263ffffffff1660c0830152151560e08201526101000190565b6001600160801b0392831681529116602082015260400190565b6001600160801b039390931683526020830191909152604082015260600190565b6001600160801b0395861681526020810194909452604084019290925283166060830152909116608082015260a00190565b6001600160a01b0392909216825260020b602082015260400190565b6001600160a01b0397909716875260029590950b602087015261ffff93841660408701529183166060860152909116608084015260ff1660a0830152151560c082015260e00190565b61ffff92831681529116602082015260400190565b62ffffff91909116815260200190565b93845260208401929092526040830152606082015260800190565b63ffffffff939093168352600291820b6020840152900b604082015260600190565b63ffffffff949094168452600292830b6020850152910b60408301526001600160a01b0316606082015260800190565b63ffffffff94909416845260069290920b60208401526001600160a01b031660408301521515606082015260800190565b60405181810167ffffffffffffffff811182821017156157f257fe5b604052919050565b600067ffffffffffffffff82111561580e57fe5b5060209081020190565b6001600160a01b03811681146115dd57600080fd5b6001600160801b03811681146115dd57600080fd5b61ffff811681146115dd57600080fd5b63ffffffff811681146115dd57600080fdfea164736f6c6343000706000a568f905fee3c29dbecf3583ddfaf086f7336b6bee88b499cc887c595fb7bf1da

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106102c85760003560e01c806398bbc3c71161017b578063d340ef8a116100d8578063ea4a11041161008c578063f305839911610071578063f3058399146105bd578063f30dba93146105c5578063f637731d146105ec576102c8565b8063ea4a110414610587578063eabb5622146105aa576102c8565b8063ddca3f43116100bd578063ddca3f431461054c578063dfc8b61514610554578063e57c0ca914610567576102c8565b8063d340ef8a1461052f578063da3c300d14610537576102c8565b8063add5887e1161012f578063c45a015511610114578063c45a01551461050a578063d0c93a7c14610512578063d21220a714610527576102c8565b8063add5887e146104ef578063c2e0f9b214610502576102c8565b8063a02f106911610160578063a02f1069146104a7578063a34123a7146104ba578063a38807f2146104cd576102c8565b806398bbc3c71461048c5780639918fbb614610494576102c8565b80634f1eb3d811610229578063725d13ae116101dd5780638221b8c1116101c25780638221b8c11461044557806385b6672914610458578063883bdbfd1461046b576102c8565b8063725d13ae1461042a5780637b7d549d1461043d576102c8565b80635339c2961161020e5780635339c296146103fc5780636847456a1461040f57806370cf754a14610422576102c8565b80634f1eb3d8146103c5578063514ea4bf146103d8576102c8565b806332148f67116102805780633c8a7d8d116102655780633c8a7d8d1461038a578063461413191461039d578063490e6cbc146103b2576102c8565b806332148f671461035a5780633850c7bd1461036f576102c8565b80631a686502116102b15780631a6865021461030c5780631ad8b03b14610321578063252c09d714610337576102c8565b80630dfe1681146102cd578063128acb08146102eb575b600080fd5b6102d56105ff565b6040516102e29190614fce565b60405180910390f35b6102fe6102f9366004614829565b61061b565b6040516102e292919061528b565b6103146113bf565b6040516102e291906155d5565b6103296113db565b6040516102e2929190615641565b61034a610345366004614c24565b611421565b6040516102e294939291906157a5565b61036d610368366004614df8565b6114b3565b005b6103776115e0565b6040516102e297969594939291906156ca565b6102fe6103983660046148b0565b611698565b6103a56116bb565b6040516102e29190615282565b61036d6103c0366004614abb565b6116ce565b6103296103d33660046148ff565b611a3e565b6103eb6103e6366004614c24565b611a5e565b6040516102e295949392919061567c565b6103a561040a366004614c5d565b611ab7565b6102fe61041d366004614eec565b611ae4565b610314611c90565b61036d6104383660046147ae565b611cac565b61036d611e4d565b6102fe6104533660046149b5565b611ebb565b61032961046636600461496b565b612122565b61047e610479366004614b23565b612272565b6040516102e292919061507f565b6102d561237c565b6103a56104a2366004614e94565b612398565b6103296104b5366004614a47565b61245d565b6102fe6104c8366004614cca565b612676565b6104e06104db366004614c98565b612692565b6040516102e2939291906152f1565b6102d56104fd366004614f3a565b6127a1565b61036d612839565b6102d5612b07565b61051a612b20565b6040516102e29190615260565b6102d5612b3d565b6103a5612b59565b61053f612b6c565b6040516102e29190615728565b61053f612b8b565b6103a5610562366004614e94565b612ba5565b61057a610575366004614b23565b612c62565b6040516102e2919061503b565b61059a610595366004614c24565b612cfb565b6040516102e29493929190615775565b61036d6105b8366004614e7a565b612d86565b6103a5612de9565b6105d86105d3366004614c7e565b612dfc565b6040516102e29897969594939291906155e9565b61036d6105fa366004614e14565b612e97565b60006106096130ae565b600201546001600160a01b0316905090565b600080610626612839565b60006106306130ae565b9050866106585760405162461bcd60e51b815260040161064f90615408565b60405180910390fd5b6040805160e08101825260058301546001600160a01b0381168252600160a01b8104600290810b810b900b602083015261ffff600160b81b8204811693830193909352600160c81b810483166060830152600160d81b8104909216608082015260ff600160e81b8304811660a0830152600160f01b909204909116151560c082018190526106f85760405162461bcd60e51b815260040161064f90615506565b886107435780600001516001600160a01b0316876001600160a01b031611801561073e575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038816105b610775565b80600001516001600160a01b0316876001600160a01b031610801561077557506401000276a36001600160a01b038816115b6107915760405162461bcd60e51b815260040161064f906154cd565b60058201805460ff60f01b191690556107a8614533565b6107b0614577565b600062093a806107be6130d2565b63ffffffff16816107cb57fe5b0463ffffffff1690506040518061010001604052808d6107f65760048660a0015160ff16901c610809565b60108660a0015160ff168161080757fe5b065b60ff168152600b8701546001600160801b0316602082015260400161082c6130d2565b63ffffffff168152602001600060060b815260200160006001600160a01b0316815260200160001515815260200160008d131515815260200186600601600084815260200190815260200160002060000160009054906101000a900463ffffffff1663ffffffff1681525092506040518061012001604052808c81526020016000815260200185600001516001600160a01b03168152602001856020015160020b81526020018d6108e15786600901546108e7565b86600801545b815260006020808301829052868101516001600160801b031660408085019190915260e088015163ffffffff16835260068a0180835281842054600160501b90046001600160a01b0316606086015295835294905292909220546401000000009004600290810b900b60809092019190915290505b8051158015906109825750886001600160a01b031681604001516001600160a01b031614155b15610efb5761098f6145c3565b60408201516001600160a01b03168152606082015160038601546109c291600d880191600160b81b900460020b8f6130d6565b15156040830152600290810b810b60208301819052620d89e719910b12156109f357620d89e7196020820152610a12565b6020810151620d89e860029190910b1315610a1257620d89e860208201525b610a1f8160200151613218565b6001600160a01b031660608201526040820151610aa0908d610a59578b6001600160a01b031683606001516001600160a01b031611610a73565b8b6001600160a01b031683606001516001600160a01b0316105b610a81578260600151610a83565b8b5b60c0850151855160038a0154600160a01b900462ffffff1661354a565b60c08086019190915260a085019190915260808401919091526001600160a01b03909116604084015283015115610b1057610ae48160c0015182608001510161373c565b825103825260a0810151610b0690610afb9061373c565b602084015190613752565b6020830152610b4b565b610b1d8160a0015161373c565b825101825260c08101516080820151610b4591610b3a910161373c565b60208401519061376e565b60208301525b825160ff1615610b9e5760006064846000015160050260320160ff168360c001510281610b7457fe5b60c0840180519290910491829003905260a0840180519091016001600160801b0316905250610bd7565b600060648260c0015160050281610bb157fe5b60c0840180519290910491829003905260a0840180519091016001600160801b03169052505b60c08201516001600160801b031615610c1657610c0a8160c00151600160801b8460c001516001600160801b0316613784565b60808301805190910190525b80606001516001600160a01b031682604001516001600160a01b03161415610eba57806040015115610e91578260a00151610d1757734a76a2f26cb26d4d4246470cc95e4da4ab0a0e92634e81939d86600f01856040015160008860200151896040015189602001518b606001516040518863ffffffff1660e01b8152600401610ca69796959493929190615215565b604080518083038186803b158015610cbd57600080fd5b505af4158015610cd1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cf59190614cf5565b6001600160a01b03166080850152600690810b900b6060840152600160a08401525b610d1f6145ff565b8c15610d3e576080830151602082015260098601546040820152610d53565b60088601546020820152608083015160408201525b73fc07c1996f8987e39e271b389c39a148baf24ba463bf7ca94e87600c01604051806101000160405280866020015160020b8152602001856020015181526020018560400151815260200188608001516001600160a01b031681526020018760e00151815260200187610100015160020b8152602001886060015160060b8152602001886040015163ffffffff168152506040518363ffffffff1660e01b8152600401610e0192919061534d565b60206040518083038186803b158015610e1957600080fd5b505af4158015610e2d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e519190614c3c565b600f90810b900b81528c15610e6f578051600003600f90810b900b81525b610e818360c001518260000151613833565b6001600160801b031660c0840152505b8b610ea0578060200151610ea9565b60018160200151035b600290810b900b6060830152610ef5565b80600001516001600160a01b031682604001516001600160a01b031614610ef557610ee882604001516138e9565b600290810b900b60608301525b5061095c565b826020015160020b816060015160020b1461107657600080734a76a2f26cb26d4d4246470cc95e4da4ab0a0e9263875f3f1287600f0187604001518760400151896020015189602001518b606001518c608001516040518863ffffffff1660e01b8152600401610f719796959493929190615140565b604080518083038186803b158015610f8857600080fd5b505af4158015610f9c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fc09190614e4c565b6040850151606086015160058a0180547fffffffffff0000ffffffffffffffffffffffffffffffffffffffffffffffffff16600160c81b61ffff95861602177fffffffffffffff0000ffffffffffffffffffffffffffffffffffffffffffffff16600160b81b95909416949094029290921762ffffff60a01b1916600160a01b62ffffff60029490940b9390931692909202919091176001600160a01b0319166001600160a01b039091161790555061109d9050565b60408101516005850180546001600160a01b0319166001600160a01b039092169190911790555b8060c001516001600160801b031682602001516001600160801b0316146110e55760c0810151600b850180546001600160801b0319166001600160801b039092169190911790555b8a15611139576080810151600885015560a08101516001600160801b0316156111345760a0810151600a850180546001600160801b031981166001600160801b03918216909301169190911790555b611183565b6080810151600985015560a08101516001600160801b0316156111835760a0810151600a850180546001600160801b03808216600160801b92839004821690940116029190911790555b8160c0015115158b1515146111a057602081015181518b036111ad565b80600001518a0381602001515b90965094508a1561127c5760008512156111de5760038401546111de906001600160a01b03168d6000889003613c15565b60006111e8613d5c565b60405163654b648760e01b8152909150339063654b648790611214908a908a908e908e90600401615299565b600060405180830381600087803b15801561122e57600080fd5b505af1158015611242573d6000803e3d6000fd5b5050505061124e613d5c565b6112588289613e81565b11156112765760405162461bcd60e51b815260040161064f90615523565b5061133c565b60008612156112a25760028401546112a2906001600160a01b03168d6000899003613c15565b60006112ac613e91565b60405163654b648760e01b8152909150339063654b6487906112d8908a908a908e908e90600401615299565b600060405180830381600087803b1580156112f257600080fd5b505af1158015611306573d6000803e3d6000fd5b50505050611312613e91565b61131c8288613e81565b111561133a5760405162461bcd60e51b815260040161064f90615523565b505b8b6001600160a01b0316336001600160a01b03167fc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67888885604001518660c0015187606001516040516113939594939291906152b9565b60405180910390a3505050600501805460ff60f01b1916600160f01b1790559097909650945050505050565b60006113c96130ae565b600b01546001600160801b0316905090565b60008060006113e86130ae565b60408051808201909152600a91909101546001600160801b03808216808452600160801b90920416602090920182905293509150509091565b60008060008060006114316130ae565b600f018661ffff811061144057fe5b60408051608081018252919092015463ffffffff81168083526401000000008204600690810b810b900b602084018190526b01000000000000000000000083046001600160a01b0316948401859052600160f81b90920460ff161515606090930183905299909850919650945092505050565b6114bb613f14565b60006114c56130ae565b6005810154604051630e51299960e01b8152919250600160d81b900461ffff1690600090734a76a2f26cb26d4d4246470cc95e4da4ab0a0e9290630e5129999061151a90600f8701908690899060040161510c565b60206040518083038186803b15801561153257600080fd5b505af4158015611546573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061156a9190614e30565b60058401805461ffff808416600160d81b810261ffff60d81b19909316929092179092559192508316146115d2577fac49e518f90a358f652e4400164f05a5d8f7e35e7747279bc3a93dbf584e125a82826040516115c9929190615713565b60405180910390a15b5050506115dd613f5c565b50565b6000806000806000806000806115f46130ae565b6040805160e081018252600592909201546001600160a01b038116808452600160a01b8204600290810b810b900b6020850181905261ffff600160b81b84048116948601859052600160c81b8404811660608701819052600160d81b85049091166080870181905260ff600160e81b8604811660a08901819052600160f01b90960416151560c0909701879052929e919d50939b5092995097509550909350915050565b6000806116ab8860008989898989611ebb565b915091505b965096945050505050565b60006116c56130ae565b60090154905090565b6116d6613f14565b60006116e06130ae565b600b8101549091506001600160801b03168061170e5760405162461bcd60e51b815260040161064f9061545c565b6003820154600090611731908890600160a01b900462ffffff16620f4240613f85565b6003840154909150600090611757908890600160a01b900462ffffff16620f4240613f85565b90506000611763613d5c565b9050600061176f613e91565b90508915611790576002860154611790906001600160a01b03168c8c613c15565b88156117af5760038601546117af906001600160a01b03168c8b613c15565b604051633797d3b360e21b8152339063de5f4ecc906117d890879087908d908d90600401615299565b600060405180830381600087803b1580156117f257600080fd5b505af1158015611806573d6000803e3d6000fd5b50505050611812614623565b61181a613d5c565b8152611824613e91565b602082015280516118358487613e81565b11156118535760405162461bcd60e51b815260040161064f906153cf565b60208101516118628386613e81565b11156118805760405162461bcd60e51b815260040161064f90615424565b611888614623565b81518490038082526020808401518590039083015215611931576005880154600160e81b9004600f16600081156118cd57825160ff831690816118c757fe5b046118d0565b60005b90506001600160801b0381161561190557600a8a0180546001600160801b038082168401166001600160801b03199091161790555b61192381846000015103600160801b8b6001600160801b0316613784565b60088b018054909101905550505b6020810151156119ce576005880154600160e81b900460041c600f166000811561196b578160ff1683602001518161196557fe5b0461196e565b60005b90506001600160801b038116156119a257600a8a0180546001600160801b03600160801b8083048216850182160291161790555b6119c081846020015103600160801b8b6001600160801b0316613784565b60098b018054909101905550505b8c6001600160a01b0316336001600160a01b03167fbdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca6338e8e85600001518660200151604051611a1f9493929190615738565b60405180910390a35050505050505050611a37613f5c565b5050505050565b600080611a508760008888888861245d565b915091509550959350505050565b600080600080600080611a6f6130ae565b6000978852600e01602052505060409094208054600182015460028301546003909301546001600160801b03928316989197509295508183169450600160801b909204169150565b6000611ac16130ae565b600d0160008360010b60010b81526020019081526020016000205490505b919050565b600080611aef613f14565b611af7612839565b6000806000731c16c172abcf809b89c0cb838c0bb4d9add01daf6368e5d9076040518060a00160405280336001600160a01b031681526020018c81526020018b60020b81526020018a60020b8152602001611b5a8a6001600160801b0316613fbf565b600003600f0b8152506040518263ffffffff1660e01b8152600401611b7f9190615540565b60606040518083038186803b158015611b9757600080fd5b505af4158015611bab573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bcf9190614d81565b9250925092508160000394508060000393506000851180611bf05750600084115b15611c2f576003830180546001600160801b038082168089018216600160801b93849004831689019092169092029091176001600160801b0319161790555b8660020b8860020b336001600160a01b03167f0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c898989604051611c749392919061565b565b60405180910390a4505050611c87613f5c565b94509492505050565b6000611c9a6130ae565b600401546001600160801b0316905090565b6000611cb66130ae565b6201000f8101549091506301000000900460ff1615611cd457600080fd5b80546001600160a01b038089166001600160a01b0319928316178355600183018054898316908416179055600280840180548984169085161790556003840180546201000f8601805462ffffff191662ffffff808b169182179092559388900b16600160b81b027fffffffffffff000000ffffffffffffffffffffffffffffffffffffffffffffff600160a01b9490940262ffffff60a01b19958b1692909616919091179390931693909317161790556040516382c66f8760e01b815273fc07c1996f8987e39e271b389c39a148baf24ba4906382c66f8790611dbb908590600401615260565b60206040518083038186803b158015611dd357600080fd5b505af4158015611de7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e0b9190614dae565b6004820180546001600160801b03929092166001600160801b03199092169190911790556201000f01805463ff00000019166301000000179055505050505050565b611e55613f14565b73a2fb4a2f2e7bb3f8e97aced35ab6e59bea226262637b7d549d6040518163ffffffff1660e01b815260040160006040518083038186803b158015611e9957600080fd5b505af4158015611ead573d6000803e3d6000fd5b50505050611eb9613f5c565b565b600080611ec6613f14565b611ece612839565b6000856001600160801b031611611ee457600080fd5b611eec614623565b731c16c172abcf809b89c0cb838c0bb4d9add01daf6368e5d9076040518060a001604052808d6001600160a01b031681526020018c81526020018b60020b81526020018a60020b8152602001611f4a8a6001600160801b0316613fbf565b600f0b8152506040518263ffffffff1660e01b8152600401611f6c9190615540565b60606040518083038186803b158015611f8457600080fd5b505af4158015611f98573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fbc9190614d81565b60208401819052818452909450925060009050808415611fe157611fde613d5c565b91505b8315611ff257611fef613e91565b90505b604051633e48f41760e01b81523390633e48f4179061201b90889088908c908c90600401615299565b600060405180830381600087803b15801561203557600080fd5b505af1158015612049573d6000803e3d6000fd5b5050505060008511156120865761205e613d5c565b6120688387613e81565b11156120865760405162461bcd60e51b815260040161064f90615494565b83156120bc57612094613e91565b61209e8286613e81565b11156120bc5760405162461bcd60e51b815260040161064f906154ea565b8860020b8a60020b8d6001600160a01b03167f7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde338c8a8a6040516121039493929190614fe2565b60405180910390a4505050612116613f5c565b97509795505050505050565b60008061212d613f14565b60006121376130ae565b8054604080516331056e5760e21b815290519293506001600160a01b039091169163c415b95c91600480820192602092909190829003018186803b15801561217e57600080fd5b505afa158015612192573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121b69190614792565b6001600160a01b0316336001600160a01b0316146121d357600080fd5b6040516385b6672960e01b815273a2fb4a2f2e7bb3f8e97aced35ab6e59bea226262906385b667299061220e90899089908990600401615011565b604080518083038186803b15801561222557600080fd5b505af4158015612239573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061225d9190614dca565b925092505061226a613f5c565b935093915050565b606080600061227f6130ae565b9050734a76a2f26cb26d4d4246470cc95e4da4ab0a0e926326e0776782600f016122a76130d2565b6005850154600b8601546040517fffffffff0000000000000000000000000000000000000000000000000000000060e087901b16815261231b9493928c928c92600160a01b830460020b9261ffff600160b81b82048116936001600160801b031692600160c81b9092041690600401615188565b60006040518083038186803b15801561233357600080fd5b505af4158015612347573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261236f9190810190614b63565b92509250505b9250929050565b60006123866130ae565b600101546001600160a01b0316905090565b6040805160a0810182528681526001600160a01b0386166020820152808201859052600284810b606083015283900b6080820152905163d2e6311b60e01b8152600091731c16c172abcf809b89c0cb838c0bb4d9add01daf9163d2e6311b916124039160040161558c565b60206040518083038186803b15801561241b57600080fd5b505af415801561242f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124539190614d69565b9695505050505050565b600080612468613f14565b60006124726130ae565b90506000731c16c172abcf809b89c0cb838c0bb4d9add01daf639c766c9d83600e01338c8c8c6040518663ffffffff1660e01b81526004016124b895949392919061531b565b60206040518083038186803b1580156124d057600080fd5b505af41580156124e4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125089190614d69565b60038101549091506001600160801b03908116908716116125295785612538565b60038101546001600160801b03165b60038201549094506001600160801b03600160801b9091048116908616116125605784612576565b6003810154600160801b90046001600160801b03165b92506001600160801b038416156125ca576003810180546001600160801b031981166001600160801b0391821687900382161790915560028301546125ca916001600160a01b03909116908c908716613c15565b6001600160801b0383161561261f57600380820180546001600160801b03600160801b8083048216889003821602918116919091179091559083015461261f916001600160a01b03909116908c908616613c15565b8660020b8860020b336001600160a01b03167f70935338e69775456a85ddef226c395fb668b63fa0115f5f20610b388e6ca9c08d888860405161266493929190615011565b60405180910390a450506116b0613f5c565b6000806126866000868686611ae4565b91509150935093915050565b60008060008360020b8560020b126126bc5760405162461bcd60e51b815260040161064f906153eb565b620d89e719600286900b12156126e45760405162461bcd60e51b815260040161064f906154b0565b620d89e8600285900b131561270b5760405162461bcd60e51b815260040161064f90615477565b6040516351c403f960e11b8152734a76a2f26cb26d4d4246470cc95e4da4ab0a0e929063a38807f290612744908890889060040161526e565b60606040518083038186803b15801561275c57600080fd5b505af4158015612770573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127949190614d2b565b9250925092509250925092565b6040516356eac43f60e11b8152600090734a76a2f26cb26d4d4246470cc95e4da4ab0a0e929063add5887e906127df90879087908790600401615753565b60206040518083038186803b1580156127f757600080fd5b505af415801561280b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061282f9190614792565b90505b9392505050565b60006128436130ae565b60078101549091508062093a806128586130d2565b63ffffffff168161286557fe5b0463ffffffff1614612b03576040805160e08101825260058401546001600160a01b0381168252600160a01b8104600290810b810b900b602083015261ffff600160b81b8204811693830193909352600160c81b810483166060830152600160d81b8104909216608082015260ff600160e81b8304811660a0830152600160f01b909204909116151560c0820152600062093a806129016130d2565b63ffffffff168161290e57fe5b0463ffffffff1690508084600701819055506000734a76a2f26cb26d4d4246470cc95e4da4ab0a0e9263c51185d886600f018560400151856040518463ffffffff1660e01b815260040161296493929190615126565b60206040518083038186803b15801561297c57600080fd5b505af4158015612990573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129b49190614792565b6020848101516000878152600689019092526040909120805469ffffff00000000000000191667010000000000000062ffffff60029490940b9390931692909202919091177fffff0000000000000000000000000000000000000000ffffffffffffffffffff16600160501b6001600160a01b038416021790559050612a3861463d565b63ffffffff8086168252602094850151600290810b810b868401908152600095865260068901909652604094859020835181549751968501516060909501516001600160a01b0316600160501b027fffff0000000000000000000000000000000000000000ffffffffffffffffffff95840b62ffffff9081166701000000000000000269ffffff00000000000000199990950b166401000000000266ffffff00000000199290951663ffffffff19909916989098171692909217949094169390931716929092179055505b5050565b6000612b116130ae565b546001600160a01b0316905090565b6000612b2a6130ae565b60030154600160b81b900460020b905090565b6000612b476130ae565b600301546001600160a01b0316905090565b6000612b636130ae565b60070154905090565b6000612b766130ae565b60030154600160a01b900462ffffff16919050565b6000612b956130ae565b6201000f015462ffffff16905090565b600080612bb06130ae565b90506000731c16c172abcf809b89c0cb838c0bb4d9add01daf639c766c9d83600e01898989896040518663ffffffff1660e01b8152600401612bf695949392919061531b565b60206040518083038186803b158015612c0e57600080fd5b505af4158015612c22573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c469190614d69565b6000988952600401602052505060409095205495945050505050565b6060818067ffffffffffffffff81118015612c7c57600080fd5b50604051908082528060200260200182016040528015612ca6578160200160208202803683370190505b50915060005b81811015612cf3576000858583818110612cc257fe5b90506020020135905060008154905080858481518110612cde57fe5b60209081029190910101525050600101612cac565b505092915050565b6000806000806000612d0b6130ae565b600096875260060160209081526040968790208751608081018952905463ffffffff81168083526401000000008204600290810b810b810b9484018590526701000000000000008304810b810b900b9983018a9052600160501b9091046001600160a01b031660609092018290529891979650945092505050565b60405163755dab1160e11b815273a2fb4a2f2e7bb3f8e97aced35ab6e59bea2262629063eabb562290612dbd908490600401615728565b60006040518083038186803b158015612dd557600080fd5b505af4158015611a37573d6000803e3d6000fd5b6000612df36130ae565b60080154905090565b6000806000806000806000806000612e126130ae565b60029a8b0b8b0b6000908152600c9190910160205260409020805460018201549b8201546003909201546001600160801b0382169d600160801b909204600f0b9c9b50919950600682900b985067010000000000000082046001600160a01b03169750600160d81b820463ffffffff169650600160f81b90910460ff16945092505050565b6000612ea16130ae565b60058101549091506001600160a01b031615612ecf5760405162461bcd60e51b815260040161064f90615440565b6000612eda836138e9565b9050600080734a76a2f26cb26d4d4246470cc95e4da4ab0a0e9263eed5cff985600f0160006040518363ffffffff1660e01b8152600401612f1c9291906150f8565b604080518083038186803b158015612f3357600080fd5b505af4158015612f47573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f6b9190614e4c565b91509150612f77612839565b6040805160e0810182526001600160a01b038716808252600286810b60208401819052600084860181905261ffff888116606087018190529088166080870181905260a0870192909252600160c09096019590955260058a018054600160f01b6001600160a01b031990911690951762ffffff60a01b1916600160a01b62ffffff9490950b9390931693909302919091177fffffffffff00000000ffffffffffffffffffffffffffffffffffffffffffffff16600160c81b9094029390931761ffff60d81b1916600160d81b909302929092177fff0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff16179055517f98636036cb66a9c19a37435efc1e90142190214e8abeb821bdba3f2990dd4c959061309f90879086906156ae565b60405180910390a15050505050565b7f568f905fee3c29dbecf3583ddfaf086f7336b6bee88b499cc887c595fb7bf1da90565b4290565b60008060008460020b8660020b816130ea57fe5b05905060008660020b12801561311157508460020b8660020b8161310a57fe5b0760020b15155b1561311b57600019015b83156131905760008061312d83613fd0565b600182810b810b600090815260208d9052604090205460ff83169190911b8001600019019081168015159750929450909250908561317257888360ff16860302613185565b8861317c82613fe2565b840360ff168603025b96505050505061320e565b60008061319f83600101613fd0565b91509150600060018260ff166001901b031990506000818b60008660010b60010b81526020019081526020016000205416905080600014159550856131f157888360ff0360ff16866001010102613207565b88836131fc83614082565b0360ff168660010101025b9650505050505b5094509492505050565b60008060008360020b1261322f578260020b613237565b8260020b6000035b9050620d89e8811115613275576040805162461bcd60e51b81526020600482015260016024820152601560fa1b604482015290519081900360640190fd5b60006001821661328957600160801b61329b565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff16905060028216156132cf576ffff97272373d413259a46990580e213a0260801c5b60048216156132ee576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b600882161561330d576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b601082161561332c576fffcb9843d60f6159c9db58835c9266440260801c5b602082161561334b576fff973b41fa98c081472e6896dfb254c00260801c5b604082161561336a576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615613389576ffe5dee046a99a2a811c461f1969c30530260801c5b6101008216156133a9576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b6102008216156133c9576ff987a7253ac413176f2b074cf7815e540260801c5b6104008216156133e9576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615613409576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615613429576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615613449576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615613469576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615613489576f31be135f97d08fd981231505542fcfa60260801c5b620100008216156134aa576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b620200008216156134ca576e5d6af8dedb81196699c329225ee6040260801c5b620400008216156134e9576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615613506576b048a170391f7dc42444e8fa20260801c5b60008460020b131561352157806000198161351d57fe5b0490505b640100000000810615613535576001613538565b60005b60ff16602082901c0192505050919050565b60008080806001600160a01b03808916908a1610158187128015906135cf5760006135838989620f42400362ffffff16620f4240613784565b90508261359c576135978c8c8c600161416c565b6135a9565b6135a98b8d8c60016141e7565b95508581106135ba578a96506135c9565b6135c68c8b83866142a4565b96505b50613619565b816135e6576135e18b8b8b60006141e7565b6135f3565b6135f38a8c8b600061416c565b935083886000031061360757899550613619565b6136168b8a8a600003856142f0565b95505b6001600160a01b038a811690871614821561367c578080156136385750815b61364e57613649878d8c60016141e7565b613650565b855b955080801561365d575081155b6136735761366e878d8c600061416c565b613675565b845b94506136c6565b8080156136865750815b61369c576136978c888c600161416c565b61369e565b855b95508080156136ab575081155b6136c1576136bc8c888c60006141e7565b6136c3565b845b94505b811580156136d657508860000385115b156136e2578860000394505b81801561370157508a6001600160a01b0316876001600160a01b031614155b1561371057858903935061372d565b61372a868962ffffff168a620f42400362ffffff16613f85565b93505b50505095509550955095915050565b6000600160ff1b821061374e57600080fd5b5090565b8082038281131560008312151461376857600080fd5b92915050565b8181018281121560008312151461376857600080fd5b60008080600019858709868602925082811090839003039050806137ba57600084116137af57600080fd5b508290049050612832565b8084116137c657600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b60008082600f0b121561389857826001600160801b03168260000384039150816001600160801b031610613893576040805162461bcd60e51b81526020600482015260026024820152614c5360f01b604482015290519081900360640190fd5b613768565b826001600160801b03168284019150816001600160801b03161015613768576040805162461bcd60e51b81526020600482015260026024820152614c4160f01b604482015290519081900360640190fd5b60006401000276a36001600160a01b03831610801590613925575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038316105b61395a576040805162461bcd60e51b81526020600482015260016024820152602960f91b604482015290519081900360640190fd5b77ffffffffffffffffffffffffffffffffffffffff00000000602083901b166001600160801b03811160071b81811c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211600190811b92831c979088119617909417909217179091171717608081106139fb57607f810383901c9150613a05565b80607f0383901b91505b908002607f81811c60ff83811c9190911c800280831c81831c1c800280841c81841c1c800280851c81851c1c800280861c81861c1c800280871c81871c1c800280881c81881c1c800280891c81891c1c8002808a1c818a1c1c8002808b1c818b1c1c8002808c1c818c1c1c8002808d1c818d1c1c8002808e1c9c81901c9c909c1c80029c8d901c9e9d607f198f0160401b60c09190911c678000000000000000161760c19b909b1c674000000000000000169a909a1760c29990991c672000000000000000169890981760c39790971c671000000000000000169690961760c49590951c670800000000000000169490941760c59390931c670400000000000000169290921760c69190911c670200000000000000161760c79190911c670100000000000000161760c89190911c6680000000000000161760c99190911c6640000000000000161760ca9190911c6620000000000000161760cb9190911c6610000000000000161760cc9190911c6608000000000000161760cd9190911c66040000000000001617693627a301d71055774c8581026f028f6481ab7f045a5af012a19d003aa9198101608090811d906fdb2df09e81959a81455e260799a0632f8301901d600281810b9083900b14613c0657886001600160a01b0316613bea82613218565b6001600160a01b03161115613bff5781613c01565b805b613c08565b815b9998505050505050505050565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b1781529251825160009485949389169392918291908083835b60208310613c915780518252601f199092019160209182019101613c72565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114613cf3576040519150601f19603f3d011682016040523d82523d6000602084013e613cf8565b606091505b5091509150818015613d26575080511580613d265750808060200190516020811015613d2357600080fd5b50515b611a37576040805162461bcd60e51b81526020600482015260026024820152612a2360f11b604482015290519081900360640190fd5b600080613d676130ae565b6002810154604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b1781529151815194955060009485946001600160a01b03169382918083835b60208310613de05780518252601f199092019160209182019101613dc1565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855afa9150503d8060008114613e40576040519150601f19603f3d011682016040523d82523d6000602084013e613e45565b606091505b5091509150818015613e5957506020815110155b613e6257600080fd5b808060200190516020811015613e7757600080fd5b5051935050505090565b8082018281101561376857600080fd5b600080613e9c6130ae565b6003810154604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b1781529151815194955060009485946001600160a01b031693829180838360208310613de05780518252601f199092019160209182019101613dc1565b6000613f1e6130ae565b6005810154909150600160f01b900460ff16613f4c5760405162461bcd60e51b815260040161064f90615506565b600501805460ff60f01b19169055565b6001613f666130ae565b6005018054911515600160f01b0260ff60f01b19909216919091179055565b6000613f92848484613784565b905060008280613f9e57fe5b8486091115612832576000198110613fb557600080fd5b6001019392505050565b80600f81900b8114611adf57600080fd5b60020b600881901d9161010090910790565b6000808211613ff057600080fd5b600160801b821061400357608091821c91015b68010000000000000000821061401b57604091821c91015b640100000000821061402f57602091821c91015b62010000821061404157601091821c91015b610100821061405257600891821c91015b6010821061406257600491821c91015b6004821061407257600291821c91015b60028210611adf57600101919050565b600080821161409057600080fd5b5060ff6001600160801b038216156140ab57607f19016140b3565b608082901c91505b67ffffffffffffffff8216156140cc57603f19016140d4565b604082901c91505b63ffffffff8216156140e957601f19016140f1565b602082901c91505b61ffff82161561410457600f190161410c565b601082901c91505b60ff82161561411e5760071901614126565b600882901c91505b600f8216156141385760031901614140565b600482901c91505b6003821615614152576001190161415a565b600282901c91505b6001821615611adf5760001901919050565b6000836001600160a01b0316856001600160a01b0316111561418c579293925b816141b9576141b4836001600160801b03168686036001600160a01b0316600160601b613784565b6141dc565b6141dc836001600160801b03168686036001600160a01b0316600160601b613f85565b90505b949350505050565b6000836001600160a01b0316856001600160a01b03161115614207579293925b7bffffffffffffffffffffffffffffffff000000000000000000000000606084901b166001600160a01b03868603811690871661424357600080fd5b8361427357866001600160a01b03166142668383896001600160a01b0316613784565b8161426d57fe5b04614299565b61429961428a8383896001600160a01b0316613f85565b886001600160a01b031661433c565b979650505050505050565b600080856001600160a01b0316116142bb57600080fd5b6000846001600160801b0316116142d157600080fd5b816142e3576141b48585856001614347565b6141dc8585856001614428565b600080856001600160a01b03161161430757600080fd5b6000846001600160801b03161161431d57600080fd5b8161432f576141b48585856000614428565b6141dc8585856000614347565b808204910615150190565b600081156143ba5760006001600160a01b0384111561437d5761437884600160601b876001600160801b0316613784565b614395565b6001600160801b038516606085901b8161439357fe5b045b90506143b26143ad6001600160a01b03881683613e81565b61451d565b9150506141df565b60006001600160a01b038411156143e8576143e384600160601b876001600160801b0316613f85565b6143ff565b6143ff606085901b6001600160801b03871661433c565b905080866001600160a01b03161161441657600080fd5b6001600160a01b0386160390506141df565b6000826144365750836141df565b7bffffffffffffffffffffffffffffffff000000000000000000000000606085901b1682156144d6576001600160a01b0386168481029085828161447657fe5b0414156144a7578181018281106144a55761449b83896001600160a01b031683613f85565b93505050506141df565b505b6144cd826144c8878a6001600160a01b031686816144c157fe5b0490613e81565b61433c565b925050506141df565b6001600160a01b038616848102908582816144ed57fe5b041480156144fa57508082115b61450357600080fd5b80820361449b6143ad846001600160a01b038b1684613f85565b806001600160a01b0381168114611adf57600080fd5b6040805161010081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081019190915290565b6040805161012081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e0810182905261010081019190915290565b6040805160e081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c081019190915290565b60405180606001604052806000600f0b815260200160008152602001600081525090565b604051806040016040528060008152602001600081525090565b60408051608081018252600080825260208201819052918101829052606081019190915290565b60008083601f840112614675578182fd5b50813567ffffffffffffffff81111561468c578182fd5b602083019150836020808302850101111561237557600080fd5b600082601f8301126146b6578081fd5b815160206146cb6146c6836157fa565b6157d6565b82815281810190858301838502870184018810156146e7578586fd5b855b8581101561470e5781516146fc81615818565b845292840192908401906001016146e9565b5090979650505050505050565b60008083601f84011261472c578182fd5b50813567ffffffffffffffff811115614743578182fd5b60208301915083602082850101111561237557600080fd5b8035600281900b8114611adf57600080fd5b8051600681900b8114611adf57600080fd5b803562ffffff81168114611adf57600080fd5b6000602082840312156147a3578081fd5b815161283281615818565b60008060008060008060c087890312156147c6578182fd5b86356147d181615818565b955060208701356147e181615818565b945060408701356147f181615818565b9350606087013561480181615818565b925061480f6080880161477f565b915061481d60a0880161475b565b90509295509295509295565b60008060008060008060a08789031215614841578384fd5b863561484c81615818565b955060208701358015158114614860578485fd5b945060408701359350606087013561487781615818565b9250608087013567ffffffffffffffff811115614892578283fd5b61489e89828a0161471b565b979a9699509497509295939492505050565b60008060008060008060a087890312156148c8578384fd5b86356148d381615818565b95506148e16020880161475b565b94506148ef6040880161475b565b935060608701356148778161582d565b600080600080600060a08688031215614916578283fd5b853561492181615818565b945061492f6020870161475b565b935061493d6040870161475b565b9250606086013561494d8161582d565b9150608086013561495d8161582d565b809150509295509295909350565b60008060006060848603121561497f578081fd5b833561498a81615818565b9250602084013561499a8161582d565b915060408401356149aa8161582d565b809150509250925092565b600080600080600080600060c0888a0312156149cf578485fd5b87356149da81615818565b9650602088013595506149ef6040890161475b565b94506149fd6060890161475b565b93506080880135614a0d8161582d565b925060a088013567ffffffffffffffff811115614a28578182fd5b614a348a828b0161471b565b989b979a50959850939692959293505050565b60008060008060008060c08789031215614a5f578384fd5b8635614a6a81615818565b955060208701359450614a7f6040880161475b565b9350614a8d6060880161475b565b92506080870135614a9d8161582d565b915060a0870135614aad8161582d565b809150509295509295509295565b600080600080600060808688031215614ad2578283fd5b8535614add81615818565b94506020860135935060408601359250606086013567ffffffffffffffff811115614b06578182fd5b614b128882890161471b565b969995985093965092949392505050565b60008060208385031215614b35578182fd5b823567ffffffffffffffff811115614b4b578283fd5b614b5785828601614664565b90969095509350505050565b60008060408385031215614b75578182fd5b825167ffffffffffffffff80821115614b8c578384fd5b818501915085601f830112614b9f578384fd5b81516020614baf6146c6836157fa565b82815281810190858301838502870184018b1015614bcb578889fd5b8896505b84871015614bf457614be08161476d565b835260019690960195918301918301614bcf565b5091880151919650909350505080821115614c0d578283fd5b50614c1a858286016146a6565b9150509250929050565b600060208284031215614c35578081fd5b5035919050565b600060208284031215614c4d578081fd5b815180600f0b8114612832578182fd5b600060208284031215614c6e578081fd5b81358060010b8114612832578182fd5b600060208284031215614c8f578081fd5b6128328261475b565b60008060408385031215614caa578182fd5b614cb38361475b565b9150614cc16020840161475b565b90509250929050565b600080600060608486031215614cde578081fd5b614ce78461475b565b925061499a6020850161475b565b60008060408385031215614d07578182fd5b614d108361476d565b91506020830151614d2081615818565b809150509250929050565b600080600060608486031215614d3f578081fd5b614d488461476d565b92506020840151614d5881615818565b60408501519092506149aa81615852565b600060208284031215614d7a578081fd5b5051919050565b600080600060608486031215614d95578081fd5b8351925060208401519150604084015190509250925092565b600060208284031215614dbf578081fd5b81516128328161582d565b60008060408385031215614ddc578182fd5b8251614de78161582d565b6020840151909250614d208161582d565b600060208284031215614e09578081fd5b813561283281615842565b600060208284031215614e25578081fd5b813561283281615818565b600060208284031215614e41578081fd5b815161283281615842565b60008060408385031215614e5e578182fd5b8251614e6981615842565b6020840151909250614d2081615842565b600060208284031215614e8b578081fd5b6128328261477f565b600080600080600060a08688031215614eab578283fd5b853594506020860135614ebd81615818565b935060408601359250614ed26060870161475b565b9150614ee06080870161475b565b90509295509295909350565b60008060008060808587031215614f01578182fd5b84359350614f116020860161475b565b9250614f1f6040860161475b565b91506060850135614f2f8161582d565b939692955090935050565b600080600060608486031215614f4e578081fd5b8335614f5981615852565b9250614f676020850161475b565b9150614f756040850161475b565b90509250925092565b60008284528282602086013780602084860101526020601f19601f85011685010190509392505050565b60060b9052565b6001600160801b03169052565b61ffff169052565b63ffffffff169052565b6001600160a01b0391909116815260200190565b6001600160a01b039490941684526001600160801b039290921660208401526040830152606082015260800190565b6001600160a01b039390931683526001600160801b03918216602084015216604082015260600190565b6020808252825182820181905260009190848201906040850190845b8181101561507357835183529284019291840191600101615057565b50909695505050505050565b604080825283519082018190526000906020906060840190828701845b828110156150bb57815160060b8452928401929084019060010161509c565b50505083810382850152845180825285830191830190845b8181101561470e5783516001600160a01b0316835292840192918401916001016150d3565b91825263ffffffff16602082015260400190565b92835261ffff918216602084015216604082015260600190565b92835261ffff919091166020830152604082015260600190565b96875261ffff958616602088015263ffffffff94909416604087015260029290920b60608601526001600160801b03166080850152821660a08401521660c082015260e00190565b600060e082018a8352602063ffffffff808c168286015260e06040860152828a8452610100860190508b9350845b8b8110156151dd5784356151c981615852565b8316825293830193908301906001016151b6565b50809450505050508560020b60608301526151fb6080830186614fbc565b61520860a0830185614faf565b613c0860c0830184614fbc565b96875263ffffffff958616602088015293909416604086015260029190910b606085015261ffff90811660808501526001600160801b0390921660a08401521660c082015260e00190565b60029190910b815260200190565b600292830b8152910b602082015260400190565b90815260200190565b918252602082015260400190565b600085825284602083015260606040830152612453606083018486614f7e565b94855260208501939093526001600160a01b039190911660408401526001600160801b0316606083015260020b608082015260a00190565b60069390930b83526001600160a01b0391909116602083015263ffffffff16604082015260600190565b9485526001600160a01b039390931660208501526040840191909152600290810b60608401520b608082015260a00190565b600061012082019050838252825160020b602083015260208301516040830152604083015160608301526001600160a01b036060840151166080830152608083015160a083015260a083015160020b60c083015260c08301516153b360e0840182614fa8565b5060e08301516153c7610100840182614fc4565b509392505050565b602080825260029082015261046360f41b604082015260600190565b602080825260039082015262544c5560e81b604082015260600190565b602080825260029082015261415360f01b604082015260600190565b602080825260029082015261463160f01b604082015260600190565b602080825260029082015261414960f01b604082015260600190565b6020808252600190820152601360fa1b604082015260600190565b60208082526003908201526254554d60e81b604082015260600190565b60208082526002908201526104d360f41b604082015260600190565b602080825260039082015262544c4d60e81b604082015260600190565b60208082526003908201526214d41360ea1b604082015260600190565b6020808252600290820152614d3160f01b604082015260600190565b6020808252600390820152624c4f4b60e81b604082015260600190565b60208082526003908201526249494160e81b604082015260600190565b600060a0820190506001600160a01b03835116825260208301516020830152604083015160020b6040830152606083015160020b60608301526080830151600f0b608083015292915050565b600060a082019050825182526001600160a01b03602084015116602083015260408301516040830152606083015160020b6060830152608083015160020b608083015292915050565b6001600160801b0391909116815260200190565b6001600160801b03989098168852600f9690960b60208801526040870194909452606086019290925260060b60808501526001600160a01b031660a084015263ffffffff1660c0830152151560e08201526101000190565b6001600160801b0392831681529116602082015260400190565b6001600160801b039390931683526020830191909152604082015260600190565b6001600160801b0395861681526020810194909452604084019290925283166060830152909116608082015260a00190565b6001600160a01b0392909216825260020b602082015260400190565b6001600160a01b0397909716875260029590950b602087015261ffff93841660408701529183166060860152909116608084015260ff1660a0830152151560c082015260e00190565b61ffff92831681529116602082015260400190565b62ffffff91909116815260200190565b93845260208401929092526040830152606082015260800190565b63ffffffff939093168352600291820b6020840152900b604082015260600190565b63ffffffff949094168452600292830b6020850152910b60408301526001600160a01b0316606082015260800190565b63ffffffff94909416845260069290920b60208401526001600160a01b031660408301521515606082015260800190565b60405181810167ffffffffffffffff811182821017156157f257fe5b604052919050565b600067ffffffffffffffff82111561580e57fe5b5060209081020190565b6001600160a01b03811681146115dd57600080fd5b6001600160801b03811681146115dd57600080fd5b61ffff811681146115dd57600080fd5b63ffffffff811681146115dd57600080fdfea164736f6c6343000706000a

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

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.