Contract

0x82c4b472484a6C4Cd8063dF849e8f6fe588EB10b

Overview

S Balance

Sonic LogoSonic LogoSonic Logo0 S

S Value

-

Token Holdings

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Increase Observa...13854732024-12-23 20:49:022 days ago1734986942IN
0x82c4b472...e588EB10b
0 S0.006115131.1

Latest 1 internal transaction

Parent Transaction Hash Block From To
12567762024-12-23 0:23:533 days ago1734913433  Contract Creation0 S
Loading...
Loading

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

Contract Name:
RamsesV3Pool

Compiler Version
v0.8.28+commit.7893614a

Optimization Enabled:
Yes with 933 runs

Other Settings:
cancun EvmVersion
File 1 of 34 : RamsesV3Pool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.26;

import {IRamsesV3PoolActions, IRamsesV3PoolDerivedState, IRamsesV3PoolOwnerActions, IRamsesV3Pool} from './interfaces/IRamsesV3Pool.sol';

import {SafeCast} from './libraries/SafeCast.sol';
import {Tick} from './libraries/Tick.sol';
import {TickBitmap} from './libraries/TickBitmap.sol';
import {Position} from './libraries/Position.sol';
import {Oracle} from './libraries/Oracle.sol';

import {FullMath} from './libraries/FullMath.sol';
import {FixedPoint128} from './libraries/FixedPoint128.sol';
import {TransferHelper} from './libraries/TransferHelper.sol';
import {TickMath} from './libraries/TickMath.sol';
import {SqrtPriceMath} from './libraries/SqrtPriceMath.sol';
import {SwapMath} from './libraries/SwapMath.sol';

import {IRamsesV3PoolDeployer} from './interfaces/IRamsesV3PoolDeployer.sol';
import {IRamsesV3Factory} from './interfaces/IRamsesV3Factory.sol';
import {IERC20Minimal} from './interfaces/IERC20Minimal.sol';
import {IUniswapV3MintCallback} from './interfaces/callback/IUniswapV3MintCallback.sol';
import {IUniswapV3SwapCallback} from './interfaces/callback/IUniswapV3SwapCallback.sol';
import {IUniswapV3FlashCallback} from './interfaces/callback/IUniswapV3FlashCallback.sol';

import {ProtocolActions} from './libraries/ProtocolActions.sol';
import {PoolStorage, Slot0, Observation, PositionInfo, TickInfo, PeriodInfo, ProtocolFees} from './libraries/PoolStorage.sol';
import {IERC20} from '@openzeppelin/contracts/interfaces/IERC20.sol';

contract RamsesV3Pool is IRamsesV3Pool {
    using SafeCast for uint256;
    using SafeCast for int256;
    using Tick for mapping(int24 => TickInfo);
    using TickBitmap for mapping(int16 => uint256);
    using Position for mapping(bytes32 => PositionInfo);
    using Position for PositionInfo;

    address public immutable factory;
    address public immutable token0;
    address public immutable token1;

    int24 public immutable tickSpacing;
    uint128 public immutable maxLiquidityPerTick;

    /// @dev Mutually exclusive reentrancy protection into the pool to/from a method. This method also prevents entrance
    /// @dev to a function before the pool is initialized. The reentrancy guard is required throughout the contract because
    /// @dev we use balance checks to determine the payment status of interactions such as mint, swap and flash.
    modifier lock() {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();
        if (!$.slot0.unlocked) revert LOK();
        $.slot0.unlocked = false;
        _;
        $.slot0.unlocked = true;
    }

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

    constructor() {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();

        (factory, token0, token1, $.fee, tickSpacing) = IRamsesV3PoolDeployer(msg.sender).parameters();

        maxLiquidityPerTick = Tick.tickSpacingToMaxLiquidityPerTick(tickSpacing);
    }

    /// @dev Common checks for valid tick inputs.
    function checkTicks(int24 tickLower, int24 tickUpper) private pure {
        /// @dev ensure lower tick is not greater than or equal to the upper tick
        if (tickLower >= tickUpper) revert TLU();
        /// @dev ensure tickLower is greater than the minimum tick
        if (tickLower < TickMath.MIN_TICK) revert TLM();
        /// @dev ensure tickUpper is less than the maximum tick
        if (tickUpper > TickMath.MAX_TICK) revert TUM();
    }

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

    /// @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
    function balance0() internal view returns (uint256) {
        return IERC20(token0).balanceOf(address(this));
    }

    /// @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
    function balance1() internal view returns (uint256) {
        return IERC20(token1).balanceOf(address(this));
    }

    /// @inheritdoc IRamsesV3PoolDerivedState
    function snapshotCumulativesInside(
        int24 tickLower,
        int24 tickUpper
    )
        external
        view
        override
        returns (int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside)
    {
        checkTicks(tickLower, tickUpper);

        return Oracle.snapshotCumulativesInside(tickLower, tickUpper, _blockTimestamp());
    }

    /// @inheritdoc IRamsesV3PoolDerivedState
    function observe(
        uint32[] calldata secondsAgos
    )
        external
        view
        override
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)
    {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();

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

    /// @inheritdoc IRamsesV3PoolActions
    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external override lock {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();
        /// @dev for the event
        uint16 observationCardinalityNextOld = $.slot0.observationCardinalityNext;
        uint16 observationCardinalityNextNew = Oracle.grow(
            $.observations,
            observationCardinalityNextOld,
            observationCardinalityNext
        );
        $.slot0.observationCardinalityNext = observationCardinalityNextNew;
        if (observationCardinalityNextOld != observationCardinalityNextNew)
            emit IncreaseObservationCardinalityNext(observationCardinalityNextOld, observationCardinalityNextNew);
    }

    /// @dev init
    function initialize(uint160 sqrtPriceX96) external {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();

        if ($.slot0.sqrtPriceX96 != 0) revert AI();

        int24 tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96);

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

        _advancePeriod();

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

        emit Initialize(sqrtPriceX96, tick);
    }

    struct ModifyPositionParams {
        /// @dev the address that owns the position
        address owner;
        uint256 index;
        /// @dev the lower and upper tick of the position
        int24 tickLower;
        int24 tickUpper;
        /// @dev 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
    ) private returns (PositionInfo storage position, int256 amount0, int256 amount1) {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();

        checkTicks(params.tickLower, params.tickUpper);
        /// @dev SLOAD for gas optimization
        Slot0 memory _slot0 = $.slot0;

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

        if (params.liquidityDelta != 0) {
            if (_slot0.tick < params.tickLower) {
                /// @dev current tick is below the passed range; liquidity can only become in range by crossing from left to
                /// @dev 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) {
                /// @dev current tick is inside the passed range
                /// @dev SLOAD for gas optimization
                uint128 liquidityBefore = $.liquidity;

                /// @dev write an oracle entry
                ($.slot0.observationIndex, $.slot0.observationCardinality) = Oracle.write(
                    $.observations,
                    _slot0.observationIndex,
                    _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
                );

                $.liquidity = params.liquidityDelta < 0
                    ? liquidityBefore - uint128(-params.liquidityDelta)
                    : liquidityBefore + uint128(params.liquidityDelta);
            } else {
                /// @dev current tick is above the passed range; liquidity can only become in range by crossing from right to
                /// @dev 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
                );
            }
        }
    }

    /// @inheritdoc IRamsesV3PoolActions
    function mint(
        address recipient,
        uint256 index,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    ) external override lock advancePeriod returns (uint256 amount0, uint256 amount1) {
        require(amount > 0);
        (, int256 amount0Int, int256 amount1Int) = _modifyPosition(
            ModifyPositionParams({
                owner: recipient,
                index: index,
                tickLower: tickLower,
                tickUpper: tickUpper,
                liquidityDelta: int256(uint256(amount)).toInt128()
            })
        );

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

        uint256 balance0Before;
        uint256 balance1Before;
        if (amount0 > 0) balance0Before = balance0();
        if (amount1 > 0) balance1Before = balance1();
        IUniswapV3MintCallback(msg.sender).uniswapV3MintCallback(amount0, amount1, data);
        if (amount0 > 0 && balance0Before + amount0 > balance0()) revert M0();
        if (amount1 > 0 && balance1Before + amount1 > balance1()) revert M1();

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

    /// @inheritdoc IRamsesV3PoolActions
    function collect(
        address recipient,
        uint256 index,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external override lock returns (uint128 amount0, uint128 amount1) {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();

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

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

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

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

    /// @inheritdoc IRamsesV3PoolActions
    function burn(
        uint256 index,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    ) external override lock advancePeriod returns (uint256 amount0, uint256 amount1) {
        unchecked {
            (PositionInfo storage position, int256 amount0Int, int256 amount1Int) = _modifyPosition(
                ModifyPositionParams({
                    owner: msg.sender,
                    index: index,
                    tickLower: tickLower,
                    tickUpper: tickUpper,
                    liquidityDelta: -int256(uint256(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 {
        /// @dev the protocol fee for the input token
        uint8 feeProtocol;
        /// @dev liquidity at the beginning of the swap
        uint128 liquidityStart;
        /// @dev the timestamp of the current block
        uint32 blockTimestamp;
        /// @dev the current value of the tick accumulator, computed only if we cross an initialized tick
        int56 tickCumulative;
        /// @dev the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick
        uint160 secondsPerLiquidityCumulativeX128;
        /// @dev whether we've computed and cached the above two accumulators
        bool computedLatestObservation;
        /// @dev timestamp of the previous period
        uint32 previousPeriod;
    }

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

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

    /// @inheritdoc IRamsesV3PoolActions
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external override returns (int256 amount0, int256 amount1) {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();

        uint256 period = _blockTimestamp() / 1 weeks;
        Slot0 memory slot0Start = $.slot0;

        /// @dev if in a new week, record lastTick for the previous period
        /// @dev also record secondsPerLiquidityCumulativeX128 for the start of the new period
        uint256 _lastPeriod = $.lastPeriod;
        if (period != _lastPeriod) {
            $.lastPeriod = period;

            /// @dev start a new period in observations
            uint160 secondsPerLiquidityCumulativeX128 = Oracle.newPeriod(
                $.observations,
                slot0Start.observationIndex,
                period
            );

            /// @dev record last tick and secondsPerLiquidityCumulativeX128 for old period
            $.periods[_lastPeriod].lastTick = slot0Start.tick;
            $.periods[_lastPeriod].endSecondsPerLiquidityPeriodX128 = secondsPerLiquidityCumulativeX128;

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

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

        if (amountSpecified == 0) revert AS();

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

        $.slot0.unlocked = false;

        SwapCache memory cache = SwapCache({
            liquidityStart: $.liquidity,
            blockTimestamp: _blockTimestamp(),
            feeProtocol: slot0Start.feeProtocol,
            secondsPerLiquidityCumulativeX128: 0,
            tickCumulative: 0,
            computedLatestObservation: false,
            previousPeriod: $.periods[period].previousPeriod
        });

        bool exactInput = amountSpecified > 0;

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

        /// @dev 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(
                state.tick,
                tickSpacing,
                zeroForOne
            );

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

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

            /// @dev 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,
                $.fee
            );

            if (exactInput) {
                /// @dev safe because we test that amountSpecified > amountIn + feeAmount in SwapMath
                unchecked {
                    state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256();
                }
                state.amountCalculated -= step.amountOut.toInt256();
            } else {
                unchecked {
                    state.amountSpecifiedRemaining += step.amountOut.toInt256();
                }
                state.amountCalculated += (step.amountIn + step.feeAmount).toInt256();
            }

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

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

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

                    uint256 _feeGrowthGlobal0X128;
                    uint256 _feeGrowthGlobal1X128;

                    if (zeroForOne) {
                        _feeGrowthGlobal0X128 = state.feeGrowthGlobalX128;
                        _feeGrowthGlobal1X128 = $.feeGrowthGlobal1X128;
                    } else {
                        _feeGrowthGlobal0X128 = $.feeGrowthGlobal0X128;
                        _feeGrowthGlobal1X128 = state.feeGrowthGlobalX128;
                    }

                    int128 liquidityNet = $._ticks.cross(
                        step.tickNext,
                        _feeGrowthGlobal0X128,
                        _feeGrowthGlobal1X128,
                        cache.secondsPerLiquidityCumulativeX128,
                        cache.tickCumulative,
                        cache.blockTimestamp,
                        state.endSecondsPerLiquidityPeriodX128,
                        state.periodStartTick
                    );
                    /// @dev if we're moving leftward, we interpret liquidityNet as the opposite sign
                    /// @dev safe because liquidityNet cannot be type(int128).min
                    unchecked {
                        if (zeroForOne) liquidityNet = -liquidityNet;
                    }

                    state.liquidity = liquidityNet < 0
                        ? state.liquidity - uint128(-liquidityNet)
                        : state.liquidity + uint128(liquidityNet);
                }

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

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

        /// @dev update liquidity if it changed
        if (cache.liquidityStart != state.liquidity) $.liquidity = state.liquidity;

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

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

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

            uint256 balance0Before = balance0();
            IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback(amount0, amount1, data);
            if (balance0Before + uint256(amount0) > balance0()) revert IIA();
        } else {
            unchecked {
                if (amount0 < 0) TransferHelper.safeTransfer(token0, recipient, uint256(-amount0));
            }

            uint256 balance1Before = balance1();
            IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback(amount0, amount1, data);
            if (balance1Before + uint256(amount1) > balance1()) revert IIA();
        }

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

    /// @inheritdoc IRamsesV3PoolActions
    function flash(address recipient, uint256 amount0, uint256 amount1, bytes calldata data) external override lock {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();

        uint128 _liquidity = $.liquidity;
        if (_liquidity == 0) revert L();

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

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

        IUniswapV3FlashCallback(msg.sender).uniswapV3FlashCallback(fee0, fee1, data);

        uint256 balance0After = balance0();
        uint256 balance1After = balance1();

        if (balance0Before + fee0 > balance0After) revert F0();
        if (balance1Before + fee1 > balance1After) revert F1();

        unchecked {
            /// @dev sub is safe because we know balanceAfter is gt balanceBefore by at least fee
            uint256 paid0 = balance0After - balance0Before;
            uint256 paid1 = balance1After - balance1Before;

            uint8 feeProtocol = $.slot0.feeProtocol;
            if (paid0 > 0) {
                uint256 pFees0 = feeProtocol == 0 ? 0 : (paid0 * feeProtocol) / 100;
                if (uint128(pFees0) > 0) $.protocolFees.token0 += uint128(pFees0);
                $.feeGrowthGlobal0X128 += FullMath.mulDiv(paid0 - pFees0, FixedPoint128.Q128, _liquidity);
            }
            if (paid1 > 0) {
                uint256 pFees1 = feeProtocol == 0 ? 0 : (paid1 * feeProtocol) / 100;
                if (uint128(pFees1) > 0) $.protocolFees.token1 += uint128(pFees1);
                $.feeGrowthGlobal1X128 += FullMath.mulDiv(paid1 - pFees1, FixedPoint128.Q128, _liquidity);
            }

            emit Flash(msg.sender, recipient, amount0, amount1, paid0, paid1);
        }
    }

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

    /// @inheritdoc IRamsesV3PoolOwnerActions
    function collectProtocol(
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external override lock returns (uint128 amount0, uint128 amount1) {
        require(msg.sender == IRamsesV3Factory(factory).feeCollector(), ProtocolActions.NOT_AUTHORIZED());

        return ProtocolActions.collectProtocol(recipient, amount0Requested, amount1Requested, token0, token1);
    }

    /// @inheritdoc IRamsesV3PoolOwnerActions
    function setFee(uint24 _fee) external override lock {
        ProtocolActions.setFee(_fee, factory);
    }

    /// @inheritdoc IRamsesV3Pool
    function _advancePeriod() public {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();

        /// @dev if in new week, record lastTick for previous period
        /// @dev also record secondsPerLiquidityCumulativeX128 for the start of the new period
        uint256 _lastPeriod = $.lastPeriod;
        if ((_blockTimestamp() / 1 weeks) != _lastPeriod) {
            uint256 period = _blockTimestamp() / 1 weeks;

            /// @dev use period - 1 if this is a new pool
            if (_lastPeriod == 0) {
                _lastPeriod = period - 1;
            }

            /// @dev loop from last unfilled period to current
            /// @dev testing shows this uses 8m gas at 900 missed periods, around 17 years
            for (uint256 i = _lastPeriod; i < period; ++i) {
                Slot0 memory _slot0 = $.slot0;

                /// @dev start new period in observations
                uint160 secondsPerLiquidityCumulativeX128 = Oracle.newPeriod(
                    $.observations,
                    _slot0.observationIndex,
                    i + 1
                );

                /// @dev record last tick and secondsPerLiquidityCumulativeX128 for old period
                $.periods[i].lastTick = _slot0.tick;
                $.periods[i].endSecondsPerLiquidityPeriodX128 = secondsPerLiquidityCumulativeX128;

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

                _newPeriod.previousPeriod = uint32(i);
                _newPeriod.startTick = _slot0.tick;
                $.periods[i + 1] = _newPeriod;
            }

            $.lastPeriod = period - 1;
        }
    }

    /// @notice get the fee charged by the pool for swaps and liquidity provision
    function fee() external view override returns (uint24) {
        return PoolStorage.getStorage().fee;
    }

    function readStorage(bytes32[] calldata slots) external view 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;
        }
    }

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

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

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

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

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

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

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

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

    /// @notice Get the ticks of the pool
    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 = PoolStorage.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;
    }

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

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

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

        return periodSecondsInsideX96;
    }

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

File 2 of 34 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";

File 3 of 34 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

/// @dev original UniswapV3 callbacks maintained to ensure seamless integrations

/// @title Callback for IUniswapV3PoolActions#flash
/// @notice Any contract that calls IUniswapV3PoolActions#flash must implement this interface
interface IUniswapV3FlashCallback {
    /// @notice Called to `msg.sender` after transferring to the recipient from IUniswapV3Pool#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 UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// @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 IUniswapV3PoolActions#flash call
    function uniswapV3FlashCallback(uint256 fee0, uint256 fee1, bytes calldata data) external;
}

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

/// @dev original UniswapV3 callbacks maintained to ensure seamless integrations

/// @title Callback for IUniswapV3PoolActions#mint
/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
interface IUniswapV3MintCallback {
    /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#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 UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// @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 IUniswapV3PoolActions#mint call
    function uniswapV3MintCallback(uint256 amount0Owed, uint256 amount1Owed, bytes calldata data) external;
}

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

/// @dev original UniswapV3 callbacks maintained to ensure seamless integrations

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

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

/// @title Minimal ERC20 interface for Ramses
/// @notice Contains a subset of the full ERC20 interface that is used in Ramses V3
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 8 of 34 : IRamsesV3Factory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title The interface for the Ramses V3 Factory
/// @notice The Ramses V3 Factory facilitates creation of Ramses V3 pools and control over the protocol fees
interface IRamsesV3Factory {
    error IT();
    /// @dev Fee Too Large
    error FTL();
    error A0();
    error F0();
    error PE();

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

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

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

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

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

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

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

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

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

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

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

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

    /// @notice returns the % of fees directed to governance
    /// @dev if the fee is 0, or the pool is uninitialized this will return the Factory's default feeProtocol
    /// @param pool the address of the pool
    /// @return _feeProtocol the feeProtocol for the pool
    function poolFeeProtocol(address pool) external view returns (uint8 _feeProtocol);

    /// @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 Get the parameters to be used in constructing the pool, set transiently during pool creation.
    /// @dev Called by the pool constructor to fetch the parameters of the pool
    /// @return factory The factory address
    /// @return token0 The first token of the pool by address sort order
    /// @return token1 The second token of the pool by address sort order
    /// @return fee The initialized feetier of the pool, denominated in hundredths of a bip
    /// @return tickSpacing The minimum number of ticks between initialized ticks
    function parameters()
        external
        view
        returns (address factory, address token0, address token1, uint24 fee, int24 tickSpacing);

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

    /// @notice sets the swap fee for a specific pool
    /// @param _pool address of the pool
    /// @param _fee the fee to be assigned to the pool, scaled to 1_000_000 = 100%
    function setFee(address _pool, uint24 _fee) external;

    /// @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 sets the feeProtocol of a specific pool
    /// @param pool address of the pool
    /// @param _feeProtocol the fee protocol to assign
    function setPoolFeeProtocol(address pool, uint8 _feeProtocol) external;

    /// @notice sets the feeProtocol upon a gauge's creation
    /// @param pool address of the pool
    function gaugeFeeSplitEnable(address pool) external;

    /// @notice sets the the voter address
    /// @param _voter the address of the voter
    function setVoter(address _voter) external;

    function initialize(address poolDeployer) external;
}

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

import {IRamsesV3PoolImmutables} from './pool/IRamsesV3PoolImmutables.sol';
import {IRamsesV3PoolState} from './pool/IRamsesV3PoolState.sol';
import {IRamsesV3PoolDerivedState} from './pool/IRamsesV3PoolDerivedState.sol';
import {IRamsesV3PoolActions} from './pool/IRamsesV3PoolActions.sol';
import {IRamsesV3PoolOwnerActions} from './pool/IRamsesV3PoolOwnerActions.sol';
import {IRamsesV3PoolErrors} from './pool/IRamsesV3PoolErrors.sol';
import {IRamsesV3PoolEvents} from './pool/IRamsesV3PoolEvents.sol';

/// @title The interface for a Ramses V3 Pool
/// @notice A Ramses 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 IRamsesV3Pool is
    IRamsesV3PoolImmutables,
    IRamsesV3PoolState,
    IRamsesV3PoolDerivedState,
    IRamsesV3PoolActions,
    IRamsesV3PoolOwnerActions,
    IRamsesV3PoolErrors,
    IRamsesV3PoolEvents
{
    /// @notice if a new period, advance on interaction
    function _advancePeriod() external;
}

File 10 of 34 : IRamsesV3PoolDeployer.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 Ramses V3 Pools
/// @notice A contract that constructs a pool must implement this to pass arguments to the pool
/// @dev This is used to avoid having constructor arguments in the pool contract, which results in the init code hash
/// of the pool being constant allowing the CREATE2 address of the pool to be cheaply computed on-chain
interface IRamsesV3PoolDeployer {
    /// @notice Get the parameters to be used in constructing the pool, set transiently during pool creation.
    /// @dev Called by the pool constructor to fetch the parameters of the pool
    /// Returns factory The factory address
    /// Returns token0 The first token of the pool by address sort order
    /// Returns token1 The second token of the pool by address sort order
    /// Returns fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// Returns tickSpacing The minimum number of ticks between initialized ticks
    function parameters()
        external
        view
        returns (address factory, address token0, address token1, uint24 fee, int24 tickSpacing);

    /// @dev Deploys a pool with the given parameters by transiently setting the parameters storage slot and then
    /// clearing it after deploying the pool.
    /// @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 tickSpacing The tickSpacing of the pool
    function deploy(address token0, address token1, int24 tickSpacing) external returns (address pool);

    function RamsesV3Factory() external view returns (address factory);
}

File 11 of 34 : IRamsesV3PoolActions.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 IRamsesV3PoolActions {
    /// @notice Sets the initial price for the pool
    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initialize(uint160 sqrtPriceX96) external;

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

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

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

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

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

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

File 12 of 34 : IRamsesV3PoolDerivedState.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 IRamsesV3PoolDerivedState {
    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
    /// you must call it with secondsAgos = [3600, 0].
    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
    /// timestamp
    function observe(
        uint32[] calldata secondsAgos
    ) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

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

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

/// @title Errors emitted by a pool
/// @notice Contains all events emitted by the pool
interface IRamsesV3PoolErrors {
    error LOK();
    error TLU();
    error TLM();
    error TUM();
    error AI();
    error M0();
    error M1();
    error AS();
    error IIA();
    error L();
    error F0();
    error F1();
    error SPL();
}

File 14 of 34 : IRamsesV3PoolEvents.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 IRamsesV3PoolEvents {
    /// @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 15 of 34 : IRamsesV3PoolImmutables.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 IRamsesV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the IRamsesV3Factory interface
    /// @return The contract address
    function factory() external view returns (address);

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

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

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

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

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

File 16 of 34 : IRamsesV3PoolOwnerActions.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 IRamsesV3PoolOwnerActions {
    /// @notice Set the denominator of the protocol's % share of the fees
    function setFeeProtocol() external;

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

    function setFee(uint24 _fee) external;
}

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

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

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

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

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

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

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

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

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


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

File 18 of 34 : BitMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.26;

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

        unchecked {
            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);

        unchecked {
            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 19 of 34 : 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 20 of 34 : 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 21 of 34 : 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 22 of 34 : FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

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

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

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

            // Because the division is now exact we can divide by multiplying
            // with the modular inverse of denominator. This will give us the
            // correct result modulo 2**256. Since the 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) {
        unchecked {
            result = mulDiv(a, b, denominator);
            if (mulmod(a, b, denominator) > 0) {
                require(result < type(uint256).max);
                result++;
            }
        }
    }
}

File 23 of 34 : Oracle.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.26;

import {PoolStorage, Observation, TickInfo, Slot0} from './PoolStorage.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 {
    error I();
    error OLD();

    /// @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
    ) private pure returns (Observation memory) {
        unchecked {
            uint32 delta = blockTimestamp - last.blockTimestamp;
            return
                Observation({
                    blockTimestamp: blockTimestamp,
                    tickCumulative: last.tickCumulative + int56(tick) * int56(uint56(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
    ) internal 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 externally.
    /// 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
    ) internal returns (uint16 indexUpdated, uint16 cardinalityUpdated) {
        unchecked {
            Observation memory last = self[index];

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

            /// @dev 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) internal returns (uint16) {
        unchecked {
            if (current <= 0) revert I();
            /// @dev no-op if the passed next value isn't greater than the current next value
            if (next <= current) return current;
            /// @dev store in each slot to prevent fresh SSTOREs in swaps
            /// @dev 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 Whether `a` is chronologically <= `b`
    function lte(uint32 time, uint32 a, uint32 b) private pure returns (bool) {
        unchecked {
            /// @dev 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
    ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
        unchecked {
            /// @dev oldest observation
            uint256 l = (index + 1) % cardinality; 
            /// @dev newest observation
            uint256 r = l + cardinality - 1; 
            uint256 i;
            while (true) {
                i = (l + r) / 2;

                beforeOrAt = self[i % cardinality];

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

                /// @dev 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
    ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
        unchecked {
            /// @dev optimistically set before to the newest observation
            beforeOrAt = self[index];

            /// @dev 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) {
                    /// @dev if newest observation equals target, we're in the same block, so we can ignore atOrAfter
                    return (beforeOrAt, atOrAfter);
                } else {
                    /// @dev otherwise, we need to transform
                    return (beforeOrAt, transform(beforeOrAt, target, tick, liquidity));
                }
            }

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

            /// @dev ensure that the target is chronologically at or after the oldest observation
            if (!lte(time, beforeOrAt.blockTimestamp, target)) revert OLD();

            /// @dev 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
    ) internal view returns (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) {
        unchecked {
            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) {
                /// @dev we're at the left boundary
                return (beforeOrAt.tickCumulative, beforeOrAt.secondsPerLiquidityCumulativeX128);
            } else if (target == atOrAfter.blockTimestamp) {
                /// @dev we're at the right boundary
                return (atOrAfter.tickCumulative, atOrAfter.secondsPerLiquidityCumulativeX128);
            } else {
                /// @dev we're in the middle
                uint32 observationTimeDelta = atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp;
                uint32 targetDelta = target - beforeOrAt.blockTimestamp;
                return (
                    beforeOrAt.tickCumulative +
                        ((atOrAfter.tickCumulative - beforeOrAt.tickCumulative) / int56(uint56(observationTimeDelta))) *
                        int56(uint56(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
    ) internal view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) {
        unchecked {
            if (cardinality <= 0) revert 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];
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();

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

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

            self[index] = Observation({
                blockTimestamp: uint32(period) * 1 weeks - 1,
                tickCumulative: last.tickCumulative + int56($.slot0.tick) * int56(uint56(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,
        uint32 _blockTimestamp
    ) external view returns (int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside) {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();

        TickInfo storage lower = $._ticks[tickLower];
        TickInfo storage upper = $._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 = $.slot0;

        unchecked {
            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 = _blockTimestamp;
                (cache.tickCumulative, cache.secondsPerLiquidityCumulativeX128) = observeSingle(
                    $.observations,
                    cache.time,
                    0,
                    _slot0.tick,
                    _slot0.observationIndex,
                    $.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,
        uint32 _blockTimestamp
    ) external view returns (uint160 secondsPerLiquidityInsideX128) {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();

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

        SnapShot memory snapshot;

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

            snapshot.secondsPerLiquidityOutsideLowerX128 = uint160(lower.periodSecondsPerLiquidityOutsideX128[period]);

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

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

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

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

                    Slot0 memory _slot0 = $.slot0;

                    (, cache.secondsPerLiquidityCumulativeX128) = observeSingle(
                        $.observations,
                        cache.time,
                        0,
                        _slot0.tick,
                        _slot0.observationIndex,
                        $.liquidity,
                        _slot0.observationCardinality
                    );
                } else {
                    cache.secondsPerLiquidityCumulativeX128 = $.periods[period].endSecondsPerLiquidityPeriodX128;
                }
                return
                    cache.secondsPerLiquidityCumulativeX128 -
                    snapshot.secondsPerLiquidityOutsideLowerX128 -
                    snapshot.secondsPerLiquidityOutsideUpperX128;
            } else {
                return snapshot.secondsPerLiquidityOutsideUpperX128 - snapshot.secondsPerLiquidityOutsideLowerX128;
            }
        }
    }
}

File 24 of 34 : PoolStorage.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.26;

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

struct Observation {
    /// @dev the block timestamp of the observation
    uint32 blockTimestamp;
    /// @dev the tick accumulator, i.e. tick * time elapsed since the pool was first initialized
    int56 tickCumulative;
    /// @dev the seconds per liquidity, i.e. seconds elapsed / max(1, liquidity) since the pool was first initialized
    uint160 secondsPerLiquidityCumulativeX128;
    /// @dev whether or not the observation is initialized
    bool initialized;
}

struct RewardInfo {
    /// @dev used to account for changes in the deposit amount
    int256 secondsDebtX96;
    /// @dev used to check if starting seconds have already been written
    bool initialized;
    /// @dev used to account for changes in secondsPerLiquidity
    int160 secondsPerLiquidityPeriodStartX128;
}

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

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

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

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

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

library PoolStorage {
    /// @dev keccak256(abi.encode(uint256(keccak256("pool.storage")) - 1)) & ~bytes32(uint256(0xff));
    bytes32 public constant POOL_STORAGE_LOCATION = 0xf047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb2800;

    /// @custom꞉storage‑location erc7201꞉pool.storage
    struct PoolState {
        Slot0 slot0;
        uint24 fee;
        uint256 feeGrowthGlobal0X128;
        uint256 feeGrowthGlobal1X128;
        ProtocolFees protocolFees;
        uint128 liquidity;
        mapping(int24 => TickInfo) _ticks;
        mapping(int16 => uint256) tickBitmap;
        mapping(bytes32 => PositionInfo) positions;
        Observation[65535] observations;
        mapping(uint256 => PeriodInfo) periods;
        uint256 lastPeriod;
        mapping(bytes32 => PositionCheckpoint[]) positionCheckpoints;
        bool initialized;
        address nfpManager;
    }

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

File 25 of 34 : Position.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.26;

import {FullMath} from './FullMath.sol';
import {FixedPoint128} from './FixedPoint128.sol';
import {FixedPoint32} from './FixedPoint32.sol';
import {FixedPoint96} from './FixedPoint96.sol';
import {Oracle} from './Oracle.sol';
import {SafeCast} from './SafeCast.sol';
import {Tick} from './Tick.sol';
import {TickBitmap} from './TickBitmap.sol';

import {PoolStorage, PositionInfo, PositionCheckpoint, RewardInfo} from './PoolStorage.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 {
    error NP();
    error FTR();

    /// @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 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
    ) internal 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 update(
        PositionInfo storage self,
        int128 liquidityDelta,
        uint256 feeGrowthInside0X128,
        uint256 feeGrowthInside1X128,
        bytes32 _positionHash,
        uint256 period,
        uint160 secondsPerLiquidityPeriodX128
    ) internal {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();

        uint128 liquidity = self.liquidity;
        uint128 liquidityNext;

        if (liquidityDelta == 0) {
            /// @dev disallow pokes for 0 liquidity positions
            if (liquidity <= 0) revert NP();
            liquidityNext = liquidity;
        } else {
            liquidityNext = liquidityDelta < 0
                ? liquidity - uint128(-liquidityDelta)
                : liquidity + uint128(liquidityDelta);
        }

        /// @dev calculate accumulated fees. overflow in the subtraction of fee growth is expected
        uint128 tokensOwed0;
        uint128 tokensOwed1;
        unchecked {
            tokensOwed0 = uint128(
                FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128)
            );
            tokensOwed1 = uint128(
                FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128)
            );

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

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

        int160 secondsPerLiquidityPeriodIntX128 = int160(secondsPerLiquidityPeriodX128);

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

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

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

        /// @dev secondsDebtDeltaX96 is declared differently based on the liquidityDelta
        int256 secondsDebtDeltaX96 = liquidityDelta > 0
        /// @dev case: delta > 0
            ? SafeCast.toInt256(
                /// @dev round upwards
                FullMath.mulDivRoundingUp(
                    uint256(uint128(liquidityDelta)),
                    uint256(uint160(secondsPerLiquidityPeriodIntX128)),
                    FixedPoint32.Q32
                )
            )
        /// @dev case: delta <= 0
            : SafeCast.toInt256(
                /// @dev round downwards 
                FullMath.mulDiv(
                    /// @dev flip liquidityDelta sign 
                    uint256(uint128(-liquidityDelta)),
                    uint256(uint160(secondsPerLiquidityPeriodIntX128)),
                    FixedPoint32.Q32
                )
            );

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

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

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

            checkpointPeriod = checkpoints[0].period;

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

            checkpointIndex = checkpointLength - 1;
        }

        checkpointPeriod = checkpoints[checkpointIndex].period;

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

            while (upper > lower) {
                /// @dev ceil, avoiding overflow
                uint256 center = upper - (upper - lower) / 2;
                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;
        uint32 _blockTimestamp;
    }

    /// @notice 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) {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();

        uint256 currentPeriod = $.lastPeriod;
        if (params.period > currentPeriod) revert FTR();

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

        uint256 liquidity;
        int160 secondsPerLiquidityPeriodStartX128;

        PositionCheckpoint[] storage checkpoints = $.positionCheckpoints[_positionHash];

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

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

        liquidity = checkpoints[checkpointIndex].liquidity;

        secondsPerLiquidityPeriodStartX128 = $
            .positions[_positionHash]
            .periodRewardInfo[params.period]
            .secondsPerLiquidityPeriodStartX128;

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

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

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

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

        /// @dev Need to check if secondsDebtX96>periodSecondsInsideX96, since rounding can cause underflows
        if (secondsDebtX96 < 0 || periodSecondsInsideX96 > uint256(secondsDebtX96)) {
            periodSecondsInsideX96 = secondsDebtX96 < 0
                ? periodSecondsInsideX96 + uint256(-secondsDebtX96)
                : periodSecondsInsideX96 - uint256(secondsDebtX96);
        } else {
            periodSecondsInsideX96 = 0;
        }

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

    struct UpdatePositionParams {
        /// @dev the owner of the position
        address owner;
        /// @dev the index of the position
        uint256 index;
        /// @dev the lower tick of the position's tick range
        int24 tickLower;
        /// @dev the upper tick of the position's tick range
        int24 tickUpper;
        /// @dev the amount liquidity changes by
        int128 liquidityDelta;
        /// @dev the current tick, passed to avoid sloads
        int24 tick;
        uint32 _blockTimestamp;
        int24 tickSpacing;
        uint128 maxLiquidityPerTick;
    }

    /// @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) external returns (PositionInfo storage position) {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();

        /// @dev calculate the period once, and reuse it
        uint256 period = params._blockTimestamp / 1 weeks;

        /// @dev precompute the position hash
        bytes32 _positionHash = positionHash(params.owner, params.index, params.tickLower, params.tickUpper);

        /// @dev fetch the position using the precomputed _positionHash
        position = $.positions[_positionHash];

        /// @dev SLOAD for gas optimization
        uint256 _feeGrowthGlobal0X128 = $.feeGrowthGlobal0X128;
        uint256 _feeGrowthGlobal1X128 = $.feeGrowthGlobal1X128;

        /// @dev use the tick from `$.slot0` instead of `params.tick` for consistency
        int24 currentTick = $.slot0.tick;

        /// @dev check and update ticks if needed
        bool flippedLower;
        bool flippedUpper;
        if (params.liquidityDelta != 0) {
            /// @dev directly use params._blockTimestamp instead of creating a new `time` variable
            (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) = Oracle.observeSingle(
                $.observations,
                params._blockTimestamp,
                0,
                currentTick, /// @dev use `currentTick` consistently
                $.slot0.observationIndex,
                $.liquidity,
                $.slot0.observationCardinality
            );

            flippedLower = Tick.update(
                $._ticks,
                params.tickLower,
                currentTick, /// @dev use `currentTick` consistently
                params.liquidityDelta,
                _feeGrowthGlobal0X128,
                _feeGrowthGlobal1X128,
                secondsPerLiquidityCumulativeX128,
                tickCumulative,
                params._blockTimestamp,
                false,
                params.maxLiquidityPerTick
            );
            flippedUpper = Tick.update(
                $._ticks,
                params.tickUpper,
                currentTick, /// @dev use `currentTick` consistently
                params.liquidityDelta,
                _feeGrowthGlobal0X128,
                _feeGrowthGlobal1X128,
                secondsPerLiquidityCumulativeX128,
                tickCumulative,
                params._blockTimestamp,
                true,
                params.maxLiquidityPerTick
            );

            /// @dev flip ticks if needed
            if (flippedLower) {
                TickBitmap.flipTick($.tickBitmap, params.tickLower, params.tickSpacing);
            }
            if (flippedUpper) {
                TickBitmap.flipTick($.tickBitmap, params.tickUpper, params.tickSpacing);
            }
        }

        /// @dev calculate the fee growth inside
        (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = Tick.getFeeGrowthInside(
            $._ticks,
            params.tickLower,
            params.tickUpper,
            currentTick, /// @dev use `currentTick` consistently
            _feeGrowthGlobal0X128,
            _feeGrowthGlobal1X128
        );

        /// @dev get the seconds per liquidity period cumulatives
        uint160 secondsPerLiquidityPeriodX128 = Oracle.periodCumulativesInside(
            uint32(period),
            params.tickLower,
            params.tickUpper,
            params._blockTimestamp
        );

        /// @dev initialize position reward info if needed
        if (!position.periodRewardInfo[period].initialized || position.liquidity == 0) {
            initializeSecondsStart(
                position,
                PositionPeriodSecondsInRangeParams({
                    period: period,
                    owner: params.owner,
                    index: params.index,
                    tickLower: params.tickLower,
                    tickUpper: params.tickUpper,
                    _blockTimestamp: params._blockTimestamp
                }),
                secondsPerLiquidityPeriodX128
            );
        }

        /// @dev update the position
        update(
            position,
            params.liquidityDelta,
            feeGrowthInside0X128,
            feeGrowthInside1X128,
            _positionHash,
            period,
            secondsPerLiquidityPeriodX128
        );

        /// @dev clear tick data if liquidity delta is negative and the ticks no longer hold liquidity
        if (params.liquidityDelta < 0) {
            if (flippedLower) {
                Tick.clear($._ticks, params.tickLower, period);
            }
            if (flippedUpper) {
                Tick.clear($._ticks, params.tickUpper, period);
            }
        }
    }

    /// @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 {
        /// @dev record initialized
        position.periodRewardInfo[secondsInRangeParams.period].initialized = true;

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

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

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

File 26 of 34 : ProtocolActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.26;
pragma abicoder v2;

import {PoolStorage} from './PoolStorage.sol';
import {TransferHelper} from './TransferHelper.sol';
import {IRamsesV3Factory} from '../interfaces/IRamsesV3Factory.sol';

library ProtocolActions {
    error NOT_AUTHORIZED();
    error INVALID_FEE();

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

    /// @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 % share of the fees that do not go to liquidity providers
    /// @dev Fetches from factory directly
    function setFeeProtocol(address factory) external {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();

        uint8 feeProtocolOld = $.slot0.feeProtocol;
        /// @dev fetch from factory mapping
        uint8 feeProtocol = IRamsesV3Factory(factory).poolFeeProtocol(address(this));
        /// @dev if the two values are not the same, the factory mapping takes precedent
        if (feeProtocol != feeProtocolOld) {
            /// @dev set the storage feeProtocol to the factory's
            $.slot0.feeProtocol = feeProtocol;
            emit SetFeeProtocol(feeProtocolOld, feeProtocol);
        }
    }

    /// @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,
        address token0,
        address token1
    ) external returns (uint128 amount0, uint128 amount1) {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();

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

        unchecked {
            if (amount0 > 0) {
                if (amount0 == $.protocolFees.token0) amount0--; /// @dev ensure that the slot is not cleared, for gas savings
                $.protocolFees.token0 -= amount0;
                TransferHelper.safeTransfer(token0, recipient, amount0);
            }
            if (amount1 > 0) {
                if (amount1 == $.protocolFees.token1) amount1--; /// @dev ensure that the slot is not cleared, for gas savings
                $.protocolFees.token1 -= amount1;
                TransferHelper.safeTransfer(token1, recipient, amount1);
            }
        }
        emit CollectProtocol(msg.sender, recipient, amount0, amount1);
    }

    function setFee(uint24 _fee, address factory) external {
        PoolStorage.PoolState storage $ = PoolStorage.getStorage();
        if (msg.sender != factory) revert NOT_AUTHORIZED();
        if (_fee > 100000) revert INVALID_FEE();
        uint24 _oldFee = $.fee;
        $.fee = _fee;
        emit FeeAdjustment(_oldFee, _fee);
    }
}

File 27 of 34 : 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 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 28 of 34 : SqrtPriceMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.26;

import {SafeCast} from './SafeCast.sol';

import {FullMath} from './FullMath.sol';
import {UnsafeMath} from './UnsafeMath.sol';
import {FixedPoint96} from './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 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) {
        /// @dev 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) {
            unchecked {
                uint256 product;
                if ((product = amount * sqrtPX96) / amount == sqrtPX96) {
                    uint256 denominator = numerator1 + product;
                    if (denominator >= numerator1)
                        /// @dev always fits in 160 bits
                        return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
                }
            }
            /// @dev denominator is checked for overflow
            return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96) + amount));
        } else {
            unchecked {
                uint256 product;
                /// @dev if the product overflows, we know the denominator underflows
                /// @dev 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) {
        /// @dev if we're adding (subtracting), rounding down requires rounding the quotient down (up)
        /// @dev 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) + 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
            unchecked {
                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);

        /// @dev 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) {
        unchecked {
            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) {
        unchecked {
            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) {
        unchecked {
            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) {
        unchecked {
            return
                liquidity < 0
                    ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
                    : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
        }
    }
}

File 29 of 34 : SwapMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.26;

import {FullMath} from './FullMath.sol';
import {SqrtPriceMath} from './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) {
        unchecked {
            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;

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

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

            if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {
                /// @dev 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 30 of 34 : Tick.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.26;

import {SafeCast} from './SafeCast.sol';

import {TickMath} from './TickMath.sol';

import {TickInfo} from './PoolStorage.sol';

/// @title Tick
/// @notice Contains functions for managing tick processes and relevant calculations
library Tick {
    error LO();

    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) internal pure returns (uint128) {
        unchecked {
            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) {
        unchecked {
            TickInfo storage lower = self[tickLower];
            TickInfo storage upper = self[tickUpper];

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

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

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

    /// @notice 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 tick The tick that will be updated
    /// @param tickCurrent The current tick
    /// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left)
    /// @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
    /// @param secondsPerLiquidityCumulativeX128 The all-time seconds per max(1, liquidity) of the pool
    /// @param tickCumulative The tick * time elapsed since the pool was first initialized
    /// @param time The current block timestamp cast to a uint32
    /// @param upper true for updating a position's upper tick, or false for updating a position's lower tick
    /// @param maxLiquidity The maximum liquidity allocation for a single tick
    /// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa
    function update(
        mapping(int24 => TickInfo) storage self,
        int24 tick,
        int24 tickCurrent,
        int128 liquidityDelta,
        uint256 feeGrowthGlobal0X128,
        uint256 feeGrowthGlobal1X128,
        uint160 secondsPerLiquidityCumulativeX128,
        int56 tickCumulative,
        uint32 time,
        bool upper,
        uint128 maxLiquidity
    ) internal returns (bool flipped) {
        TickInfo storage info = self[tick];

        uint128 liquidityGrossBefore = info.liquidityGross;
        uint128 liquidityGrossAfter = liquidityDelta < 0
            ? liquidityGrossBefore - uint128(-liquidityDelta)
            : liquidityGrossBefore + uint128(liquidityDelta);

        if (liquidityGrossAfter > maxLiquidity) revert LO();

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

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

        info.liquidityGross = liquidityGrossAfter;

        /// @dev when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed)
        info.liquidityNet = upper ? info.liquidityNet - liquidityDelta : info.liquidityNet + liquidityDelta;
    }

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

    /// @notice Transitions to next tick as needed by price movement
    /// @param self The mapping containing all tick information for initialized ticks
    /// @param tick The destination tick of the transition
    /// @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
    /// @param secondsPerLiquidityCumulativeX128 The current seconds per liquidity
    /// @param tickCumulative The tick * time elapsed since the pool was first initialized
    /// @param time The current block.timestamp
    /// @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,
        int24 tick,
        uint256 feeGrowthGlobal0X128,
        uint256 feeGrowthGlobal1X128,
        uint160 secondsPerLiquidityCumulativeX128,
        int56 tickCumulative,
        uint32 time,
        uint256 endSecondsPerLiquidityPeriodX128,
        int24 periodStartTick
    ) internal returns (int128 liquidityNet) {
        unchecked {
            TickInfo storage info = self[tick];
            uint256 period = time / 1 weeks;

            info.feeGrowthOutside0X128 = feeGrowthGlobal0X128 - info.feeGrowthOutside0X128;
            info.feeGrowthOutside1X128 = feeGrowthGlobal1X128 - info.feeGrowthOutside1X128;
            info.secondsPerLiquidityOutsideX128 =
                secondsPerLiquidityCumulativeX128 -
                info.secondsPerLiquidityOutsideX128;
            info.tickCumulativeOutside = tickCumulative - info.tickCumulativeOutside;
            info.secondsOutside = time - info.secondsOutside;
            liquidityNet = info.liquidityNet;

            uint256 periodSecondsPerLiquidityOutsideX128;
            uint256 periodSecondsPerLiquidityOutsideBeforeX128 = info.periodSecondsPerLiquidityOutsideX128[period];
            if (tick <= periodStartTick && periodSecondsPerLiquidityOutsideBeforeX128 == 0) {
                periodSecondsPerLiquidityOutsideX128 =
                    secondsPerLiquidityCumulativeX128 -
                    /* periodSecondsPerLiquidityOutsideBeforeX128 - */
                    endSecondsPerLiquidityPeriodX128;
            } else {
                periodSecondsPerLiquidityOutsideX128 =
                    secondsPerLiquidityCumulativeX128 -
                    periodSecondsPerLiquidityOutsideBeforeX128;
            }
            info.periodSecondsPerLiquidityOutsideX128[period] = periodSecondsPerLiquidityOutsideX128;
        }
    }
}

File 31 of 34 : TickBitmap.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.26;

import {BitMath} from './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) {
        unchecked {
            wordPos = int16(tick >> 8);
            bitPos = uint8(int8(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 {
        unchecked {
            /// @dev ensure that the tick is spaced
            require(tick % tickSpacing == 0); 
            (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) {
        unchecked {
            int24 compressed = tick / tickSpacing;
            if (tick < 0 && tick % tickSpacing != 0) compressed--; /// @dev round towards negative infinity

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

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

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

File 32 of 34 : TickMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.26;

/// @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 {
    error T();
    error R();

    /// @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) {
        unchecked {
            uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
            if (absTick > uint256(int256(MAX_TICK))) revert 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;

            /// @dev this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
            /// @dev we then downcast because we know the result always fits within 160 bits due to our tick input constraint
            /// @dev 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) {
        unchecked {
            /// @dev second inequality must be < because the price can never reach the price at the max tick
            if (!(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO)) revert 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; /// @dev 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 33 of 34 : TransferHelper.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;

import {IERC20Minimal} from '../interfaces/IERC20Minimal.sol';

/// @title TransferHelper
/// @notice Contains helper methods for interacting with ERC20 tokens that do not consistently return true/false
library TransferHelper {
    error TF();

    /// @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)
        );
        if (!(success && (data.length == 0 || abi.decode(data, (bool))))) revert TF();
    }
}

File 34 of 34 : 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": 933
  },
  "evmVersion": "cancun",
  "viaIR": true,
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {
    "contracts/CL/core/libraries/Oracle.sol": {
      "Oracle": "0x5699be61618d2386c6f5feb9843490c08507e33f"
    },
    "contracts/CL/core/libraries/Position.sol": {
      "Position": "0xd940fa70289a13075bfef3b5ceca8beb6568aedd"
    },
    "contracts/CL/core/libraries/ProtocolActions.sol": {
      "ProtocolActions": "0x1a161022bf556aaa9b0e0281ec03e19b809e0ae8"
    }
  }
}

Contract Security Audit

Contract ABI

[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AI","type":"error"},{"inputs":[],"name":"AS","type":"error"},{"inputs":[],"name":"F0","type":"error"},{"inputs":[],"name":"F1","type":"error"},{"inputs":[],"name":"I","type":"error"},{"inputs":[],"name":"IIA","type":"error"},{"inputs":[],"name":"L","type":"error"},{"inputs":[],"name":"LOK","type":"error"},{"inputs":[],"name":"M0","type":"error"},{"inputs":[],"name":"M1","type":"error"},{"inputs":[],"name":"NOT_AUTHORIZED","type":"error"},{"inputs":[],"name":"OLD","type":"error"},{"inputs":[],"name":"R","type":"error"},{"inputs":[],"name":"SPL","type":"error"},{"inputs":[],"name":"T","type":"error"},{"inputs":[],"name":"TF","type":"error"},{"inputs":[],"name":"TLM","type":"error"},{"inputs":[],"name":"TLU","type":"error"},{"inputs":[],"name":"TUM","type":"error"},{"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":"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":"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":"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":"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":[{"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":"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":"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":"liquidity","type":"uint128"},{"internalType":"uint256","name":"feeGrowthInside0LastX128","type":"uint256"},{"internalType":"uint256","name":"feeGrowthInside1LastX128","type":"uint256"},{"internalType":"uint128","name":"tokensOwed0","type":"uint128"},{"internalType":"uint128","name":"tokensOwed1","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"}]

Deployed Bytecode

0x6080806040526004361015610012575f80fd5b5f905f3560e01c9081630dfe16811461398257508063128acb081461216c5780631a686502146121395780631ad8b03b146120bb578063252c09d71461202d57806332148f6714611f055780633850c7bd14611e835780634614131914611e46578063490e6cbc14611977578063514ea4bf146118f05780635339c296146118915780636847456a1461170557806370cf754a146116c15780637b7d549d146115c75780638221b8c1146112ed57806385b6672914611021578063883bdbfd14610df95780639918fbb614610c7d578063a02f1069146109e8578063a38807f2146108a7578063c2e0f9b21461088b578063c45a015514610847578063d0c93a7c14610809578063d21220a7146107c5578063d340ef8a14610788578063ddca3f4314610746578063e57c0ca914610674578063ea4a1104146105e7578063eabb5622146104a2578063f305839914610465578063f30dba93146103a65763f637731d1461017e575f80fd5b346103a35760203660031901126103a3576101976139c3565b6001600160a01b035f5160206159005f395f51905f52541661037b576040816101e07f98636036cb66a9c19a37435efc1e90142190214e8abeb821bdba3f2990dd4c9593614632565b9082516101ec81613af7565b8581526020808201878152858301888152600160608501529251905192519290911b6affffffffffffff000000001663ffffffff919091161760589190911b7effffffffffffffffffffffffffffffffffffffff00000000000000000000001617600160f81b175f5160206159405f395f51905f525561026a613d52565b6001600160a01b0383519161027e83613a8e565b16808252600283900b602080840182905285840188905260016060850181905260808501819052600560a08087019190915260c0909501525f5160206159005f395f51905f5280547901000000000000000000000000000000000000000000000000009690951b62ffffff60a01b167fffffffffff00000000000000000000000000000000000000000000000000000090951666ffffffffffffff60a01b1985161794909417949094177fff00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffff167e0105000100000000000000000000000000000000000000000000000000000017909255835190815291820152a180f35b6004827f9cc0b7f8000000000000000000000000000000000000000000000000000000008152fd5b80fd5b50346103a35760203660031901126103a3576101006103f66103c6613a37565b60020b5f527ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb280660205260405f2090565b8054906001810154906003600282015491015491604051936001600160801b038116855260801d600f0b6020850152604084015260608301528060060b60808301526001600160a01b038160381c1660a083015263ffffffff8160d81c1660c083015260f81c151560e0820152f35b50346103a357806003193601126103a35760207ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb280254604051908152f35b50346103a35760203660031901126103a3576004359062ffffff82168092036103a3575f5160206159005f395f51905f52549160ff8360f01c16156105d85760ff60f01b198293165f5160206159005f395f51905f5255731a161022bf556aaa9b0e0281ec03e19b809e0ae890813b156105d45782906044604051809481937f4f67424900000000000000000000000000000000000000000000000000000000835260048301526001600160a01b037f000000000000000000000000ed55fa4772cbb9f45ea8118a39cf640df2fdb2dc1660248301525af480156105c9576105b4575b50600160f01b60ff60f01b195f5160206159005f395f51905f525416175f5160206159005f395f51905f525580f35b816105be91613b13565b6103a357805f610585565b6040513d84823e3d90fd5b5050fd5b6004826350dfbc4360e11b8152fd5b50346103a35760203660031901126103a357604060809160043581525f5160206158e05f395f51905f526020522060606040519161062483613af7565b5463ffffffff8116928381528160201c60020b908160208201526001600160a01b038360381c60020b9384604084015260501c169384910152604051938452602084015260408301526060820152f35b50346103a35760203660031901126103a35760043567ffffffffffffffff8111610742576106a6903690600401613a5d565b906106b082613d3a565b906106be6040519283613b13565b8282526106ca83613d3a565b6020830190601f1901368237845b848110156106fc576001908060051b840135546106f58287614024565b52016106d8565b5091925050604051928392602084019060208552518091526040840192915b818110610729575050500390f35b825184528594506020938401939092019160010161071b565b5080fd5b50346103a357806003193601126103a357602062ffffff7ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb28015416604051908152f35b50346103a357806003193601126103a35760207ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccc280954604051908152f35b50346103a357806003193601126103a35760206040516001600160a01b037f000000000000000000000000d3dce716f3ef535c5ff8d041c1a41c3bd89b97ae168152f35b50346103a357806003193601126103a35760206040517f000000000000000000000000000000000000000000000000000000000000003260020b8152f35b50346103a357806003193601126103a35760206040516001600160a01b037f000000000000000000000000ed55fa4772cbb9f45ea8118a39cf640df2fdb2dc168152f35b50346103a357806003193601126103a3576108a4613d52565b80f35b50346103a35760403660031901126103a3576108c1613a37565b906108ca613a07565b6108d4818461523c565b604051927f9b7beb6000000000000000000000000000000000000000000000000000000000845260020b600484015260020b602483015263ffffffff42166044830152606082606481735699be61618d2386c6f5feb9843490c08507e33f5af49182156109db57818091819461096e575b60608463ffffffff876001600160a01b03876040519460060b8552166020840152166040820152f35b92509250506060813d6060116109d3575b8161098c60609383613b13565b810103126107425780518060060b81036109cf5760406109ae60208401613bab565b9201519263ffffffff841684036103a3575090806001600160a01b03610945565b8280fd5b3d915061097f565b50604051903d90823e3d90fd5b50346103a35760c03660031901126103a357610a026139c3565b90610a0b613a17565b610a13613a27565b92610a1c613a47565b9360a4356001600160801b038116808203610c79575f5160206159005f395f51905f525460ff8160f01c1615610c6a5760ff60f01b19165f5160206159005f395f51905f525560405160208101903360601b825260243560348201528660e81b60548201528460e81b6057820152603a8152610a99605a82613b13565b51902086527ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb280860205260036040872001918254966001600160801b03881698896001600160801b038216115f14610c64575088975b60801c92839150115f14610c5c5750955b856001600160801b0381169182610c06575b50506001600160801b0387169182610ba8575b506001600160a01b03604051941684526020840152604083015260020b9160020b907f70935338e69775456a85ddef226c395fb668b63fa0115f5f20610b388e6ca9c060603392a45f5160206159005f395f51905f52805460ff60f01b1916600160f01b179055604080516001600160801b03928316815292909116602083015290f35b80546001600160801b038116608091821c8a900390911b6fffffffffffffffffffffffffffffffff1916179055610c0082857f000000000000000000000000d3dce716f3ef535c5ff8d041c1a41c3bd89b97ae614bec565b5f610b24565b83546fffffffffffffffffffffffffffffffff19169190036001600160801b0316178255610c5581857f000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad38614bec565b855f610b11565b905095610aff565b97610aee565b6004876350dfbc4360e11b8152fd5b8580fd5b50346103a35760a03660031901126103a357602435906001600160a01b0382168092036103a357610cac613a27565b916084358060020b8091036109cf576040519360c0850185811067ffffffffffffffff821117610de5579063ffffffff939291604052600435865260208601928352604086016044358152606087019160020b8252608087019283526001600160a01b0360a08801948642168652604051987fd2e6311b000000000000000000000000000000000000000000000000000000008a525160048a0152511660248801525160448701525160020b60648601525160020b6084850152511660a483015260208260c48173d940fa70289a13075bfef3b5ceca8beb6568aedd5af4908115610dd95790610da2575b602090604051908152f35b506020813d602011610dd1575b81610dbc60209383613b13565b81010312610dcd5760209051610d97565b5f80fd5b3d9150610daf565b604051903d90823e3d90fd5b602485634e487b7160e01b81526041600452fd5b50346103a35760203660031901126103a35760043567ffffffffffffffff811161074257610e2b903690600401613a5d565b919063ffffffff4216925f5160206159005f395f51905f52548060a01c60020b61ffff8260b81c169061ffff6001600160801b035f5160206158c05f395f51905f5254169360c81c1693610e7e81613d3a565b95610e8c6040519788613b13565b818752602087019160051b81019036821161101d57915b818310610ffc575050508315610fed57845196610ed8610ec289613d3a565b98610ed06040519a8b613b13565b808a52613d3a565b602089019690601f1901368837805196610ef4610ec289613d3a565b602089019190601f1901368337895b8b8451821015610f6457908a610f5882600194816001600160a01b038f8f8f918f918f938f93610f4f9563ffffffff610f3f8a610f4798614024565b51169061497d565b939097614024565b91169052614024565b9060060b905201610f03565b8a90848d8560405194859460408601906040875251809152606086019290845b818110610fd1575050506020908583038287015251918281520192915b818110610faf575050500390f35b82516001600160a01b0316845285945060209384019390920191600101610fa1565b825160060b855288975060209485019490920191600101610f84565b600486636b93000360e11b8152fd5b823563ffffffff8116810361101957815260209283019201610ea3565b8980fd5b8880fd5b50346103a35760603660031901126103a35761103b6139c3565b906024356001600160801b03811680910361074257604435906001600160801b0382168092036109cf575f5160206159005f395f51905f525460ff8160f01c16156112de5760ff60f01b19165f5160206159005f395f51905f52556040517fc415b95c0000000000000000000000000000000000000000000000000000000081526020816004816001600160a01b037f000000000000000000000000ed55fa4772cbb9f45ea8118a39cf640df2fdb2dc165afa80156112d3578490611286575b6001600160a01b03915016330361125e576001600160a01b03604051947fb81955c9000000000000000000000000000000000000000000000000000000008652166004850152602484015260448301526001600160a01b037f000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad381660648301526001600160a01b037f000000000000000000000000d3dce716f3ef535c5ff8d041c1a41c3bd89b97ae16608483015260408260a481731a161022bf556aaa9b0e0281ec03e19b809e0ae85af49182156109db57818093611213575b50505f5160206159005f395f51905f52805460ff60f01b1916600160f01b179055604080516001600160801b03928316815292909116602083015290f35b915091506040823d604011611256575b8161123060409383613b13565b810103126103a3575061124e602061124783613d26565b9201613d26565b905f806111d5565b3d9150611223565b6004837f3d83866f000000000000000000000000000000000000000000000000000000008152fd5b506020813d6020116112cb575b816112a060209383613b13565b810103126112c757516001600160a01b03811681036112c7576001600160a01b03906110fb565b8380fd5b3d9150611293565b6040513d86823e3d90fd5b6004846350dfbc4360e11b8152fd5b50346103a35760c03660031901126103a3576113076139c3565b61130f613a17565b611317613a27565b91611320613a47565b9260a43567ffffffffffffffff8111610c79576113419036906004016139d9565b9390945f5160206159005f395f51905f525460ff8160f01c16156115b85760ff60f01b19165f5160206159005f395f51905f52556001600160801b0390611386613d52565b169586156103a35786600f0b93878503610dcd576113e1906001600160a01b03604051916113b383613adb565b1693848252602435602083015260020b9485604083015260020b95866060830152600f0b6080820152614e88565b969150968290839189151591826115a8575b8915159485611598575b333b15611594578a8c61143f899360405195869485947fd348799700000000000000000000000000000000000000000000000000000000865260048601613c8e565b038183335af18015611589578b9291879161156a575b505082611550575b50506115285786908261150e575b50506114e657507f7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde608060409788519033825260208201528789820152866060820152a4600160f01b60ff60f01b195f5160206159005f395f51905f525416175f5160206159005f395f51905f525582519182526020820152f35b807f20e5672e0000000000000000000000000000000000000000000000000000000060049252fd5b6115189250613be3565b611520614cf1565b10855f61146b565b6004837f748800af000000000000000000000000000000000000000000000000000000008152fd5b61155a9250613be3565b611562614d76565b10885f61145d565b819293509061157891613b13565b611585578990855f611455565b8480fd5b6040513d88823e3d90fd5b8680fd5b93506115a2614cf1565b936113fd565b90506115b2614d76565b906113f3565b6004886350dfbc4360e11b8152fd5b50346103a357806003193601126103a3575f5160206159005f395f51905f525460ff8160f01c16156105d85760ff60f01b19165f5160206159005f395f51905f525580731a161022bf556aaa9b0e0281ec03e19b809e0ae8803b156116be5781602491604051928380927f425fb0030000000000000000000000000000000000000000000000000000000082526001600160a01b037f000000000000000000000000ed55fa4772cbb9f45ea8118a39cf640df2fdb2dc1660048301525af480156105c9576105b45750600160f01b60ff60f01b195f5160206159005f395f51905f525416175f5160206159005f395f51905f525580f35b50fd5b50346103a357806003193601126103a35760206040516001600160801b037f000000000000000000000000000000000001d8b7ac9dd9f54805d403b8d237ee168152f35b50346103a35760803660031901126103a35761171f613a07565b90611728613a17565b606435906001600160801b0382168092036109cf575f5160206159005f395f51905f525460ff8160f01c16156112de5760ff60f01b19165f5160206159005f395f51905f5255611776613d52565b81600f0b90828203610dcd576117c160409586519061179482613adb565b338252600435602083015260020b92838883015260020b938460608301528603600f0b6080820152614e88565b818703968190039592911580159190611887575b50611849575b50855190815284602082015283868201527f0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c60603392a4600160f01b60ff60f01b195f5160206159005f395f51905f525416175f5160206159005f395f51905f525582519182526020820152f35b60030180546001600160801b038781168183160181166fffffffffffffffffffffffffffffffff19918816608093841c0190921b161790555f6117db565b905015155f6117d5565b50346103a35760203660031901126103a357600435908160010b82036103a35760206118e78360010b5f527ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb280760205260405f2090565b54604051908152f35b50346103a35760203660031901126103a357604060a09160043581527ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb2808602052206001600160801b03815416906001810154906003600282015491015491604051938452602084015260408301526001600160801b038116606083015260801c6080820152f35b50346103a35760803660031901126103a3576119916139c3565b906024356044359260643567ffffffffffffffff81116112c7576119b99036906004016139d9565b90945f5160206159005f395f51905f525460ff8160f01c1615611e375760ff60f01b19165f5160206159005f395f51905f52556001600160801b035f5160206158c05f395f51905f525416908115611e0f5762ffffff7ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb2801541691611a47611a408488614e42565b9383614e42565b90611a50614d76565b94611a59614cf1565b9988611ddf575b84611daf575b333b1561101957611aa9918a9160405193849283927fe9cbafb0000000000000000000000000000000000000000000000000000000008452888b60048601613c8e565b038183335af18015611da457908991611d8b575b5050611ac7614d76565b9182611adb611ad4614cf1565b9688613be3565b11611d6357611aeb85918b613be3565b11611d3b576001600160a01b03969798858303948181039660ff5f5160206159005f395f51905f525460e81c169403611c66575b03611b92575b505060405195865260208601526040850152606084015216907fbdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca63360803392a3600160f01b60ff60f01b195f5160206159005f395f51905f525416175f5160206159005f395f51905f525580f35b611bb69180611c5b5750885b6001600160801b03811680611c02575b508503614453565b7ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb280354017ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb2803555f80611b25565b6001600160801b03611c55915f5160206159205f395f51905f525460801c01166001600160801b035f5160206159205f395f51905f52549181199060801b169116175f5160206159205f395f51905f5255565b5f611bae565b606490860204611b9e565b83611d2c57611c89838c5b6001600160801b03811680611cd3575b508803614453565b7ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb280254017ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb280255611b1f565b6001600160801b03611d2691815f5160206159205f395f51905f52541601166001600160801b03166001600160801b03195f5160206159205f395f51905f525416175f5160206159205f395f51905f5255565b5f611c81565b611c8983606486890204611c71565b6004887fe90c3493000000000000000000000000000000000000000000000000000000008152fd5b6004897ff704e899000000000000000000000000000000000000000000000000000000008152fd5b81611d9591613b13565b611da057875f611abd565b8780fd5b6040513d8b823e3d90fd5b611dda85897f000000000000000000000000d3dce716f3ef535c5ff8d041c1a41c3bd89b97ae614bec565b611a66565b611e0a89897f000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad38614bec565b611a60565b6004867f9f13f76d000000000000000000000000000000000000000000000000000000008152fd5b6004866350dfbc4360e11b8152fd5b50346103a357806003193601126103a35760207ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb280354604051908152f35b50346103a357806003193601126103a35760e0611e9e613b35565b6001600160a01b0381511690602081015160020b9061ffff60408201511661ffff60608301511661ffff6080840151169160c060ff60a086015116940151151594604051968752602087015260408601526060850152608084015260a083015260c0820152f35b50346103a35760203660031901126103a35760043561ffff81168103610742575f5160206159005f395f51905f525460ff8160f01c161561201e57907fff00ff0000ffffffffffffffffffffffffffffffffffffffffffffffffffffff7cffff000000000000000000000000000000000000000000000000000000611fae61ffff8560ff60f01b19600160f01b97165f5160206159005f395f51905f525560d81c169384614dcc565b5f5160206159005f395f51905f52549361ffff8216808203611fe7575b505060d81b16911617175f5160206159005f395f51905f525580f35b7fac49e518f90a358f652e4400164f05a5d8f7e35e7747279bc3a93dbf584e125a9160409182519182526020820152a15f80611fcb565b6004836350dfbc4360e11b8152fd5b50346103a35760203660031901126103a35760043561ffff8110156120a75760809150612068905f5160206159405f395f51905f5201613ce3565b63ffffffff81511690602081015160060b9060606001600160a01b03604083015116910151151591604051938452602084015260408301526060820152f35b602482634e487b7160e01b81526032600452fd5b50346103a357806003193601126103a3576040516040810181811067ffffffffffffffff8211176121255760409081525f5160206159205f395f51905f52546001600160801b03811680845260809190911c60209384018190528251918252928101929092529150f35b602483634e487b7160e01b81526041600452fd5b50346103a357806003193601126103a35760206001600160801b035f5160206158c05f395f51905f525416604051908152f35b5034610dcd5760a0366003190112610dcd576121866139c3565b90602435151560243503610dcd57606435906001600160a01b0382168203610dcd5760843567ffffffffffffffff8111610dcd576121c89036906004016139d9565b909263ffffffff42169462093a808604946121e1613b35565b937ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccc2809548063ffffffff8916036136fe575b50604435156136d65760c0850151156136c75760243515613685576001600160a01b038551166001600160a01b038516108061366e575b156136465760409760ff60f01b195f5160206159005f395f51905f5254165f5160206159005f395f51905f52556001600160801b035f5160206158c05f395f51905f5254169760ff60a0880151169863ffffffff82165f525f5160206158e05f395f51905f5260205263ffffffff8b5f205416928b519a6122c98c613a8e565b8b528160208c01528b8b01525f60608b01525f60808b01525f60a08b01528260c08b01526001600160a01b0388511692602089015160020b6024355f1461361e577ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb280254915b5f525f5160206158e05f395f51905f5260205263ffffffff6001600160a01b038e5f205460501c1694165f525f5160206158e05f395f51905f526020528c5f205460201c60020b948d519d8e61238381613abe565b60443581525f6020820152015260608d015260808c01525f60a08c015260c08b015260e08a01526101008901527f000000000000000000000000000000000000000000000000000000000000003260020b15955b88511515806135fe575b156130b6576040516123f281613a8e565b5f81525f60208201525f60408201525f60608201525f60808201525f60a08201525f60c08201526001600160a01b0360408b015116815260608a015160020b88612daf577f000000000000000000000000000000000000000000000000000000000000003260020b8105905f81129081613080575b50613075575b60243515612ebb5761248f8160020b906101008260081d60010b920760ff1690565b909160ff8216926124d46001851b5f19908001019160010b5f527ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb280760205260405f2090565b5416801580159481612e845750815f91610dcd5782600160801b60ff941015612e75575b5080680100000000000000006002921015612e67575b640100000000811015612e59575b62010000811015612e4b575b610100811015612e3d575b6010811015612e2f575b6004811015612e22575b1015612e18575b7f000000000000000000000000000000000000000000000000000000000000003293031660020b900360020b0260020b5b905b1515604083015260020b60208201819052620d89e719811215612dfb5750620d89e71960208201525b6001600160a01b036125c2602083015160020b614042565b168060608301526001600160a01b0360408c015116906024355f14612dea576001600160a01b03881681105b15612de4575086905b60c08c01518c517ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb2801545f808312936001600160a01b03871680871015949362ffffff16928615926001600160801b03168188612cee575061266262ffffff86620f42400316876143de565b998715612cdd57612674828b83615343565b9a5b8b8110612c525750985b6001600160a01b038a169a848c149815612bfc578880612bf5575b15612be4575b998a9880612bdd575b15612bce575050505b955b80612bc3575b612bb8575b81612bad575b5015612b8f5750035b60c085015260a0840152608083015260408b01525f6044351315612b3557608081015160c082015101600160ff1b811015610dcd578a51038a5260a0810151600160ff1b811015610dcd5760208b01515f8282039212818312811691831390151617612b215760208b01525b60ff89511680612aed575b506001600160801b0360c08b01511680612ace575b506001600160a01b0360408b0151166001600160a01b0360608301511681145f14612a9f575060408101516127bb575b602435156127af5760205f1991015160020b0160020b5b60020b60608a01526123d7565b6020015160020b6127a2565b60a089015115612a3e575b60243515612a08576001600160801b038a60808101517ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb280354905b8c602086015160020b6001600160a01b0360808301511663ffffffff6040606085015160060b940151169160e08701519261010088015160020b9461286f8360020b5f527ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb280660205260405f2090565b9763ffffffff62093a808404169760018a01908154900390556002890190815490039055600388019166ffffffffffffff8354927effffffff0000000000000000000000000000000000000000000000000000007affffffffffffffffffffffffffffffffffffffff000000000000006001600160a01b038660381c16890360381b1691827fffffffffff0000000000000000000000000000000000000000ffffffffffffff87161760060b90039363ffffffff858516847fffffffffff0000000000000000000000000000000000000000000000000000008916171760d81c16900360d81b169360ff60f81b16179116171790556004865460801d960193855f528460205260405f205491131580612a00575b156129f7575003915b5f5260205260405f2055806024356129ea575b505f81600f0b125f146129d2576129bf8360c06129c79401511691613c1a565b831690613c3a565b1660c08b015261278b565b8260c06129e59301511690831690613bfa565b6129c7565b90505f03600f0b5f61299f565b9150039161298c565b508015612983565b6001600160801b038a7ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb280254608082015190612800565b6001600160a01b03612a8263ffffffff60408c015116898c602082015160020b61ffff60606001600160801b03602083604088015116950151169401511693614912565b9190911660808b015260060b60608a0152600160a08a01526127c6565b90516001600160a01b03168103612ab7575b506123d7565b612ac090614632565b60020b60608a01525f612ab1565b612adc9060c0830151614453565b60808b01510160808b01525f61275b565b6001600160801b036064819260c085015102048060c08501510360c0850152168160a08d015116011660a08b01525f612746565b634e487b7160e01b5f52601160045260245ffd5b60a0810151600160ff1b811015610dcd578a51018a52612b5e608082015160c083015190613be3565b600160ff1b811015610dcd5760208b01515f8282019283129112908015821691151617612b215760208b015261273b565b9050612ba8915062ffffff81620f424003169084614e6c565b6126cf565b90508614155f6126c6565b9450825f03946126c0565b50835f0386116126bb565b612bd893506153b1565b6126b3565b50896126aa565b50612bf082828c615343565b6126a1565b508561269b565b9099908880612c4b575b15612c3a575b998a9880612c33575b15612c24575050505b956126b5565b612c2e93506152d9565b612c1e565b5089612c15565b50612c4682828c6153e2565b612c0c565b5085612c06565b90508915610dcd578115610dcd578715612c7757612c7190828b6157c9565b98612680565b612caf906001600160a01b038111612cc457612ca0906001600160801b0384169060601b613bf0565b6001600160a01b038b16613be3565b6001600160a01b038116908114612c71575f80fd5b612cd8906001600160801b0384169061452d565b612ca0565b612ce882828c6153e2565b9a612676565b9991508615612dd357612d02818a846153b1565b915b5f879003838110612d16575098612680565b90508915610dcd578115610dcd578715612dc3576001600160a01b038111612d725760601b6001600160801b03821680820615159104015b6001600160a01b038a169080821115610dcd576001600160a01b0391031698612680565b6001600160801b038216612d8b81600160601b846145ad565b918115612daf57600160601b900915612d4e575f19811015610dcd57600101612d4e565b634e487b7160e01b5f52601260045260245ffd5b612dce90828b615756565b612c71565b612dde81838b6152d9565b91612d04565b906125f7565b6001600160a01b03881681116125ee565b620d89e8809113612e0d575b506125aa565b60208201525f612e07565b600101811661254e565b918101831691811c612547565b60049283018416921c61253d565b60089283018416921c612533565b60109283018416921c612528565b60209283018416921c61251c565b60409283018416921c61250e565b60809250821c905060026124f8565b935050507f00000000000000000000000000000000000000000000000000000000000000329160020b900360020b0260020b61257f565b600190810160020b600881901d820b5f9081527ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb280760205260409020545f1960ff61010084071693841b01191680158015939092918361303b578093610dcd5760ff906001600160801b03811615613031575050607f5b67ffffffffffffffff84161561302757603f190160ff165b63ffffffff84161561301d57601f190160ff165b61ffff84161561301357600f190160ff165b60ff841615613009576007190160ff165b600f841615612fff576003190160ff165b6003841615612ff3576001190160ff16926001905b16612fe5575b60ff907f000000000000000000000000000000000000000000000000000000000000003293031660020b0160020b0260020b5b90612581565b5f1990920160ff1691612fac565b9260019060021c612fa6565b9260041c92612f91565b9260081c92612f80565b9260101c92612f6f565b9260201c92612f5d565b9260401c92612f49565b60801c9350612f31565b50915060ff7f00000000000000000000000000000000000000000000000000000000000000329281031660020b0160020b0260020b612fdf565b5f190160020b61246d565b9950505f987f000000000000000000000000000000000000000000000000000000000000003260020b900760020b15155f612467565b88906001600160801b0360208a89606086015160020b8382015160020b809114155f146135b3578161ffff6040613114940151169163ffffffff604086015116908787870151169161ffff6080816060870151169501511694614ab8565b6001600160a01b036040880151169161ffff60b81b73ffffffffffffffffffffffffffffffffffffffff1960608a01519366ffffffffffffff60a01b1961ffff60c81b5f5160206159005f395f51905f52549260c81b16911617169160b81b16179060a01b62ffffff60a01b1617175f5160206159005f395f51905f52555b0151166001600160801b0360c084015116809103613575575b50602435156134db5760808201517ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb2802556001600160801b0360a08301511680613482575b505b60243515155f604435130361347057815160443503936020830151935b602435156133a15782851261336f575b613227614d76565b91333b156112c757613252918491604051938492839263fa461e3360e01b84528a8c60048601613c8e565b038183335af18015613364578691849161334b575b505061327291613be3565b61327a614d76565b1061332357506001600160a01b036040945b8186840151169260606001600160801b0360c08301511691015160020b90875194878652866020870152888601526060850152608084015216907fc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca6760a03392a3600160f01b60ff60f01b195f5160206159005f395f51905f525416175f5160206159005f395f51905f525582519182526020820152f35b807fba0b951e0000000000000000000000000000000000000000000000000000000060049252fd5b8192509061335891613b13565b61074257848288613267565b6040513d85823e3d90fd5b61339c858403887f000000000000000000000000d3dce716f3ef535c5ff8d041c1a41c3bd89b97ae614bec565b61321f565b5f869392931261343e575b6133b4614cf1565b92333b15610dcd576133df915f91604051938492839263fa461e3360e01b84528a8c60048601613c8e565b038183335af190811561343357859161341c575b506133fe9192613be3565b613406614cf1565b1061332357506001600160a01b0360409461328c565b61342992505f9150613b13565b5f836133fe6133f3565b6040513d5f823e3d90fd5b61346b865f03887f000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad38614bec565b6133ac565b6020820151938251604435039361320f565b6001600160801b036134d591815f5160206159205f395f51905f52541601166001600160801b03166001600160801b03195f5160206159205f395f51905f525416175f5160206159205f395f51905f5255565b856131f0565b60808201517ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb2803556001600160801b0360a0830151168061351c575b506131f2565b6001600160801b0361356f915f5160206159205f395f51905f525460801c01166001600160801b035f5160206159205f395f51905f52549181199060801b169116175f5160206159205f395f51905f5255565b85613516565b6135ad906001600160801b03166001600160801b03195f5160206158c05f395f51905f525416175f5160206158c05f395f51905f5255565b856131ac565b50506001600160a01b0360408601511673ffffffffffffffffffffffffffffffffffffffff195f5160206159005f395f51905f525416175f5160206159005f395f51905f5255613193565b506001600160a01b0385166001600160a01b0360408b01511614156123e1565b7ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb2803549161232e565b7ffcdf4aa7000000000000000000000000000000000000000000000000000000005f5260045ffd5b506401000276a36001600160a01b03851611612249565b6001600160a01b038551166001600160a01b038516118015612249575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b03851610612249565b6350dfbc4360e11b5f5260045ffd5b7f03fff018000000000000000000000000000000000000000000000000000000005f5260045ffd5b63ffffffff88167ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccc280981905560408781015190516318a230bb60e31b81525f5160206159405f395f51905f52600482015261ffff9091166024820152604481019190915290602082606481735699be61618d2386c6f5feb9843490c08507e33f5af4918215613433575f92613939575b506001600160a01b0360606139339361384960208b01916137e2835160020b875f525f5160206158e05f395f51905f5260205260405f209081549060381b62ffffff60381b169062ffffff60381b1916179055565b855f525f5160206158e05f395f51905f5260205260405f20907fffff0000000000000000000000000000000000000000ffffffffffffffffffff7dffffffffffffffffffffffffffffffffffffffff0000000000000000000083549260501b169116179055565b63ffffffff613856613bbf565b941684525160020b926020810193845263ffffffff8c165f525f5160206158e05f395f51905f5260205260405f209363ffffffff808351161663ffffffff198654161785555184549060201b66ffffff00000000169066ffffff0000000019161784556138e3604082015160020b859081549060381b62ffffff60381b169062ffffff60381b1916179055565b015182547fffff0000000000000000000000000000000000000000ffffffffffffffffffff16911660501b7dffffffffffffffffffffffffffffffffffffffff0000000000000000000016179055565b5f612212565b91506020823d60201161397a575b8161395460209383613b13565b81010312610dcd576001600160a01b03606061397261393394613bab565b93505061378d565b3d9150613947565b34610dcd575f366003190112610dcd576020906001600160a01b037f000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad38168152f35b600435906001600160a01b0382168203610dcd57565b9181601f84011215610dcd5782359167ffffffffffffffff8311610dcd5760208381860195010111610dcd57565b602435908160020b8203610dcd57565b604435908160020b8203610dcd57565b606435908160020b8203610dcd57565b600435908160020b8203610dcd57565b608435906001600160801b0382168203610dcd57565b9181601f84011215610dcd5782359167ffffffffffffffff8311610dcd576020808501948460051b010111610dcd57565b60e0810190811067ffffffffffffffff821117613aaa57604052565b634e487b7160e01b5f52604160045260245ffd5b610120810190811067ffffffffffffffff821117613aaa57604052565b60a0810190811067ffffffffffffffff821117613aaa57604052565b6080810190811067ffffffffffffffff821117613aaa57604052565b90601f8019910116810190811067ffffffffffffffff821117613aaa57604052565b60405190613b4282613a8e565b8160c060ff5f5160206159005f395f51905f52546001600160a01b03811684528060a01c60020b602085015261ffff8160b81c16604085015261ffff8160c81c16606085015261ffff8160d81c166080850152818160e81c1660a085015260f01c161515910152565b51906001600160a01b0382168203610dcd57565b60405190613bcc82613af7565b5f6060838281528260208201528260408201520152565b91908201809211612b2157565b8115612daf570490565b906001600160801b03809116911601906001600160801b038211612b2157565b600f0b6f7fffffffffffffffffffffffffffffff198114612b21575f0390565b906001600160801b03809116911603906001600160801b038211612b2157565b6001600160801b03166001600160801b03195f5160206158c05f395f51905f525416175f5160206158c05f395f51905f5255565b6060908593602096938252868201528160408201520192818452848401375f828201840152601f01601f1916010190565b61ffff821015613ccf5701905f90565b634e487b7160e01b5f52603260045260245ffd5b90604051613cf081613af7565b606081935463ffffffff811683528060201c60060b60208401526001600160a01b038160581c16604084015260f81c1515910152565b51906001600160801b0382168203610dcd57565b67ffffffffffffffff8111613aaa5760051b60200190565b7ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccc28095462093a8063ffffffff4216049063ffffffff821691818303613d9557505050565b508015614003575b735699be61618d2386c6f5feb9843490c08507e33f905b828110613dec5750505f198101908111612b21577ff047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccc280955565b613df4613b35565b9061ffff6040830151166001820192838311612b21576040516318a230bb60e31b81525f5160206159405f395f51905f52600482015261ffff92909216602483015260448201849052602082606481885af4918215613433575f92613fad575b50926001600160a01b036060613fa793613f1360206001980191613eac835160020b895f525f5160206158e05f395f51905f5260205260405f209081549060381b62ffffff60381b169062ffffff60381b1916179055565b875f525f5160206158e05f395f51905f5260205260405f20907fffff0000000000000000000000000000000000000000ffffffffffffffffffff7dffffffffffffffffffffffffffffffffffffffff0000000000000000000083549260501b169116179055565b613f1b613bbf565b9063ffffffff871682525160020b93602082019485525f525f5160206158e05f395f51905f5260205260405f209363ffffffff808351161663ffffffff198654161785555184549060201b66ffffff00000000169066ffffff0000000019161784556138e3604082015160020b859081549060381b62ffffff60381b169062ffffff60381b1916179055565b01613db4565b9150926020823d8211613ffb575b81613fc860209383613b13565b81010312610dcd576001600160a01b036060600195613f136020613fee613fa797613bab565b9650505092955050613e54565b3d9150613fbb565b505f19810181811115613d9d57634e487b7160e01b5f52601160045260245ffd5b8051821015613ccf5760209160051b010190565b8115612daf570690565b60020b5f8112156143d857805f03905b620d89e882116143b05760018216156143945770ffffffffffffffffffffffffffffffffff6ffffcb933bd6fad37aa2d162d1a5940015b169160028116614378575b6004811661435c575b60088116614340575b60108116614324575b60208116614308575b604081166142ec575b608081166142d0575b61010081166142b4575b6102008116614298575b610400811661427c575b6108008116614260575b6110008116614244575b6120008116614228575b614000811661420c575b61800081166141f0575b6201000081166141d4575b6202000081166141b9575b62040000811661419e575b6208000016614185575b5f12614177575b6001600160a01b039063ffffffff811661416e5760ff5f5b169060201c011690565b60ff6001614164565b8015612daf575f190461414c565b6b048a170391f7dc42444e8fa290910260801c90614145565b6d2216e584f5fa1ea926041bedfe9890920260801c9161413b565b916e5d6af8dedb81196699c329225ee6040260801c91614130565b916f09aa508b5b7a84e1c677de54f3e99bc90260801c91614125565b916f31be135f97d08fd981231505542fcfa60260801c9161411a565b916f70d869a156d2a1b890bb3df62baf32f70260801c91614110565b916fa9f746462d870fdf8a65dc1f90e061e50260801c91614106565b916fd097f3bdfd2022b8845ad8f792aa58250260801c916140fc565b916fe7159475a2c29b7443b29c7fa6e889d90260801c916140f2565b916ff3392b0822b70005940c7a398e4b70f30260801c916140e8565b916ff987a7253ac413176f2b074cf7815e540260801c916140de565b916ffcbe86c7900a88aedcffc83b479aa3a40260801c916140d4565b916ffe5dee046a99a2a811c461f1969c30530260801c916140ca565b916fff2ea16466c96a3843ec78b326b528610260801c916140c1565b916fff973b41fa98c081472e6896dfb254c00260801c916140b8565b916fffcb9843d60f6159c9db58835c9266440260801c916140af565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c916140a6565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c9161409d565b916ffff97272373d413259a46990580e213a0260801c91614094565b70ffffffffffffffffffffffffffffffffff600160801b614089565b7f2bc80f3a000000000000000000000000000000000000000000000000000000005f5260045ffd5b80614052565b9091905f905f1984820990848102928380841093039280840393146144455782620f424011156103a357507fde8f6cefed634549b62c77574f722e1ac57e23f24d8fd5cb790fb65668c261399394620f4240910990828211900360fa1b910360061c170290565b505050620f42409192500490565b5f19600160801b8209918160801b918280851094039380850394146144d35783821115610dcd57600160801b82910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b5080925015610dcd570490565b5f915f1981830991818102938480851094039380850394146145235783600160601b11156103a3575090600160601b910990828211900360a01b910360601c1790565b5050505060601c90565b5f19600160601b8209918160601b918280851094039380850394146144d35783821115610dcd57600160601b82910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b915f1982840992828102928380861095039480860395146146245784831115610dcd5782910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b505080925015610dcd570490565b6001600160a01b038116906401000276a3821015806148f5575b156148cd5777ffffffffffffffffffffffffffffffffffffffff000000009060201b16806001600160801b03811160071b90811c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c9060ff821160031b91821c92600f841160021b93841c94600160038711811b96871c1196171717171717179060808210155f146148c357607e1982011c5b800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c80029081607f1c8260ff1c1c80029283607f1c8460ff1c1c80029485607f1c8660ff1c1c80029687607f1c8860ff1c1c80029889607f1c8a60ff1c1c80029a8b607f1c8c60ff1c1c80029c8d80607f1c9060ff1c1c800260cd1c6604000000000000169d60cc1c6608000000000000169c60cb1c6610000000000000169b60ca1c6620000000000000169a60c91c6640000000000000169960c81c6680000000000000169860c71c670100000000000000169760c61c670200000000000000169660c51c670400000000000000169560c41c670800000000000000169460c31c671000000000000000169360c21c672000000000000000169260c11c674000000000000000169160c01c6780000000000000001690607f190160401b1717171717171717171717171717693627a301d71055774c85026f028f6481ab7f045a5af012a19d003aa919810160801d60020b906fdb2df09e81959a81455e260799a0632f0160801d60020b918282145f146148a3575090505b90565b6001600160a01b036148b484614042565b16116148be575090565b905090565b81607f031b6146e7565b7f4980e1be000000000000000000000000000000000000000000000000000000005f5260045ffd5b5073fffd8963efd1fc6a506488495d951d5263988d26821061464c565b9493509061ffff811015613ccf57614938905f5160206159405f395f51905f5201613ce3565b9363ffffffff85511663ffffffff82160361496a575b5050506001600160a01b036040602084015160060b9301511690565b6149749394615433565b905f808061494e565b95949290939163ffffffff851615614a7d5763ffffffff6149b09588031680975f5160206159405f395f51905f526154fb565b909263ffffffff8451168082145f146149df575050506001600160a01b036040602084015160060b9301511690565b63ffffffff8395935116908183145f14614a1057505050506001600160a01b036040602084015160060b9301511690565b63ffffffff818193031692031693602083015160060b9283602083015160060b0360060b928060060b928315612daf57614a68604092896001600160a01b038096948180888198015116978892015116031602613bf0565b1601169460060b91050260060b0160060b9190565b925090925061ffff811015613ccf57614938905f5160206159405f395f51905f5201613ce3565b9061ffff16908115612daf5761ffff160690565b90919293959461ffff821015613ccf57614ae0825f5160206159405f395f51905f5201613ce3565b9663ffffffff88511663ffffffff851614614be157614b2b949261ffff6001989795938382614b2595168383161180614bd1575b15614bc757509889925b0116614aa4565b96615433565b61ffff841015613ccf57805160208083015160408401516060909401517fff0000000000000000000000000000000000000000000000000000000000000090151560f81b167effffffffffffffffffffffffffffffffffffffff000000000000000000000060589590951b9490941663ffffffff909316911b6affffffffffffff00000000161717175f5160206159405f395f51905f52840155565b9050988992614b1e565b508383165f198201841614614b14565b965050925050509190565b5f9291838093604051906001600160a01b0360208301947fa9059cbb000000000000000000000000000000000000000000000000000000008652166024830152604482015260448152614c40606482613b13565b51925af13d15614cea573d67ffffffffffffffff8111613aaa5760405190614c72601f8201601f191660200183613b13565b81523d5f602083013e5b81614cb2575b5015614c8a57565b7f8b986265000000000000000000000000000000000000000000000000000000005f5260045ffd5b8051801592508215614cc7575b50505f614c82565b8192509060209181010312610dcd57602001518015158103610dcd575f80614cbf565b6060614c7c565b6040516370a0823160e01b81523060048201526020816024816001600160a01b037f000000000000000000000000d3dce716f3ef535c5ff8d041c1a41c3bd89b97ae165afa908115613433575f91614d47575090565b90506020813d602011614d6e575b81614d6260209383613b13565b81010312610dcd575190565b3d9150614d55565b6040516370a0823160e01b81523060048201526020816024816001600160a01b037f000000000000000000000000039e2fb66102314ce7b64ce5ce3e5183bc94ad38165afa908115613433575f91614d47575090565b61ffff8116908115614e335761ffff831691821115614e2d575f5160206159405f395f51905f52905b8261ffff821610614e065750505090565b61ffff811015613ccf5760018161ffff9284018263ffffffff198254161790550116614df5565b91505090565b636b93000360e11b5f5260045ffd5b9190620f424090614e548282866145ad565b9309614e5c57565b905f19811015610dcd5760010190565b929190614e7a8282866145ad565b938215612daf5709614e5c57565b905f905f9060408401805160020b90614eaa6060870192835160020b9061523c565b614eb2613b35565b906001600160a01b03875116602088015192825160020b916001600160801b036080875160020b9b01958651600f0b9463ffffffff602086019d8e5160020b8242169860405197614f0289613abe565b88526020880195865260408801948552606088019283526080880190815260a0880191825260c08801928a845260e08901957f000000000000000000000000000000000000000000000000000000000000003260020b87526101008a0197897f000000000000000000000000000000000001d8b7ac9dd9f54805d403b8d237ee1689526001600160a01b036040519b7ffc322879000000000000000000000000000000000000000000000000000000008d52511660048c01525160248b01525160020b60448a01525160020b606489015251600f0b60848801525160020b60a4870152511660c48501525160020b60e484015251166101048201526020816101248173d940fa70289a13075bfef3b5ceca8beb6568aedd5af4908115613433575f9161520a575b50988451600f0b61503d575b505050505050565b90919293949597815160020b855160020b908181125f14615095575050505050509061507d61507361508894935160020b614042565b925160020b614042565b9051600f0b91615721565b915b5f8080808080615035565b90919293959997809599505160020b135f146151df575050916001600160a01b0361518961517f615197946151096151c698976001600160801b035f5160206158c05f395f51905f5254169b8c61ffff60408a015116925160020b61ffff60608b0151169261ffff60808c01511694614ab8565b907fffffffffff00000000ffffffffffffffffffffffffffffffffffffffffffffff61ffff60c81b61ffff60b81b5f5160206159005f395f51905f52549360b81b169360c81b16911617175f5160206159005f395f51905f525561517484865116915160020b614042565b8751600f0b91615721565b985160020b614042565b9151168351600f0b916156cc565b9381515f81600f0b125f146151cb57506151b7613c5a9251600f0b613c1a565b6001600160801b031690613c3a565b61508a565b613c5a92506001600160801b031690613bfa565b9097506152049596506151f9929493506150739150614042565b9051600f0b916156cc565b9061508a565b90506020813d602011615234575b8161522560209383613b13565b81010312610dcd57515f615029565b3d9150615218565b9060020b9060020b818112156152b157620d89e7191361528957620d89e81261526157565b7fd7b54ab1000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f9ad612e8000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f2fe0284f000000000000000000000000000000000000000000000000000000005f5260045ffd5b6001600160a01b0382166001600160a01b0382161161533d575b6001600160a01b038116918215610dcd576148a0936fffffffffffffffffffffffffffffffff60601b6001600160a01b03615338948185169403169160601b166145ad565b613bf0565b906152f3565b906001600160a01b0381166001600160a01b038316116153ab575b6001600160a01b038216928315610dcd576fffffffffffffffffffffffffffffffff60601b6001600160a01b0361539f948185169403169160601b16614e6c565b90808206151591040190565b9061535e565b6001600160a01b036001600160801b03916148a09493828116838316116153dc575b031691166144e0565b906153d3565b6001600160a01b036001600160801b0391600160601b938281168383161161542d575b03169216916154158282856145ad565b920961541e5790565b5f19811015610dcd5760010190565b90615405565b9192909261543f613bbf565b5063ffffffff8351168403906001600160a01b036040602086015160060b95015116926001600160801b03811615155f146154eb576001600160801b03905b16918215612daf576001600160a01b039473ffffffff000000000000000000000000000000009263ffffffff604051986154b78a613af7565b16885263ffffffff831660060b9060020b0260060b0160060b602087015260801b1604011660408201526001606082015290565b506001600160801b03600161547e565b969294909493919361550b613bbf565b50615514613bbf565b91615528615522858b613cbf565b50613ce3565b9163ffffffff83511661553c88828b615841565b6156a1575050505050600161ffff91011661556361552261555d8784614aa4565b88613cbf565b83606082015115615686575b63ffffffff61558092511686615841565b1561565e5761ffff6155a5868293615596613bbf565b5061559f613bbf565b50614aa4565b169416935f19858201015b80820160011c906155cd6155226155c78985614038565b8a613cbf565b6060810151156156535760018301906155f26155226155ec8b85614038565b8c613cbf565b6156048863ffffffff8451168b615841565b91828061563b575b61562c5750506156235750505f1901905b906155b0565b9150915061561d565b9a509850949650505050505050565b5061564e63ffffffff8351168a8c615841565b61560c565b50915060010161561d565b7f27e8e875000000000000000000000000000000000000000000000000000000005f5260045ffd5b615580915063ffffffff61569989613ce3565b92505061556f565b93995094975090955093915063ffffffff8216036156c0575050509190565b836148a0949650615433565b905f83600f0b125f146156ff576156ee925f036001600160801b0316916153b1565b600160ff1b811015610dcd575f0390565b615712926001600160801b0316916153e2565b600160ff1b811015610dcd5790565b905f83600f0b125f14615743576156ee925f036001600160801b0316916152d9565b615712926001600160801b031691615343565b9082156157c3576fffffffffffffffffffffffffffffffff60601b6001600160a01b039160601b1691168061578e8185029485613bf0565b14806157ba575b15610dcd576157a692820391614e6c565b6001600160a01b038116908103610dcd5790565b50828211615795565b50905090565b909180156157c3576001600160a01b036fffffffffffffffffffffffffffffffff60601b819460601b169216808202816158038483613bf0565b14615829575b509061581861581d9284613bf0565b613be3565b80820615159104011690565b830183811061580957915061583d92614e6c565b1690565b63ffffffff9182169291168083118015806158af575b6158a2579063ffffffff64ffffffffff939484935f1461589357945b1690811115615885575b169116111590565b64010000000001811661587d565b64010000000001831694615873565b505063ffffffff16101590565b508163ffffffff8416111561585756fef047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb2805f047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccc2808f047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb2800f047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb2804f047b0c59244a0faf8e48cb6b6fde518e6717176152b6dd953628cd9dccb2809a2646970667358221220cb9e59aa49c31e37a4052f2b77775af2ab5b6f7e1676a6e572c5bca4231cf76164736f6c634300081c0033

Block Transaction Gas Used Reward
view all blocks produced

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

Validator Index Block Amount
View All Withdrawals

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

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