POL Price: $0.521399 (-7.94%)
 

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Burn R Tokens443261932023-06-25 15:47:21542 days ago1687708041IN
0xea698cfB...8105b115a
0 POL0.030195200
Transfer414765762023-04-13 7:48:08615 days ago1681372088IN
0xea698cfB...8105b115a
0 POL0.0059302200
Burn R Tokens414075642023-04-11 13:14:25617 days ago1681218865IN
0xea698cfB...8105b115a
0 POL0.03346875250
Burn R Tokens401835822023-03-10 12:39:01649 days ago1678451941IN
0xea698cfB...8105b115a
0 POL0.0211683164
Burn R Tokens389895832023-02-06 19:27:39681 days ago1675711659IN
0xea698cfB...8105b115a
0 POL0.025815200
Burn R Tokens368708902022-12-15 18:49:45734 days ago1671130185IN
0xea698cfB...8105b115a
0 POL0.01350886128

Latest 1 internal transaction

Parent Transaction Hash Block From To
318457142022-08-13 14:05:35858 days ago1660399535  Contract Creation0 POL
Loading...
Loading

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

Contract Name:
Pool

Compiler Version
v0.8.9+commit.e5eed63a

Optimization Enabled:
Yes with 2000 runs

Other Settings:
default evmVersion
File 1 of 28 : Pool.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;

import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';

import {LiqDeltaMath} from './libraries/LiqDeltaMath.sol';
import {QtyDeltaMath} from './libraries/QtyDeltaMath.sol';
import {MathConstants as C} from './libraries/MathConstants.sol';
import {ReinvestmentMath} from './libraries/ReinvestmentMath.sol';
import {SwapMath} from './libraries/SwapMath.sol';
import {FullMath} from './libraries/FullMath.sol';
import {SafeCast} from './libraries/SafeCast.sol';
import {TickMath} from './libraries/TickMath.sol';

import {IPool} from './interfaces/IPool.sol';
import {IPoolActions} from './interfaces/pool/IPoolActions.sol';
import {IFactory} from './interfaces/IFactory.sol';
import {IMintCallback} from './interfaces/callback/IMintCallback.sol';
import {ISwapCallback} from './interfaces/callback/ISwapCallback.sol';
import {IFlashCallback} from './interfaces/callback/IFlashCallback.sol';

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

contract Pool is IPool, PoolTicksState, ERC20('KyberSwap v2 Reinvestment Token', 'KS2-RT') {
  using SafeCast for uint256;
  using SafeCast for int256;
  using SafeERC20 for IERC20;

  /// @dev Mutually exclusive reentrancy protection into the pool from/to a method.
  /// Also prevents entrance to pool actions prior to initalization
  modifier lock() {
    require(poolData.locked == false, 'locked');
    poolData.locked = true;
    _;
    poolData.locked = false;
  }

  constructor() {}

  /// @dev Get pool's balance of token0
  /// Gas saving to avoid a redundant extcodesize check
  /// in addition to the returndatasize check
  function _poolBalToken0() private view returns (uint256) {
    (bool success, bytes memory data) = address(token0).staticcall(
      abi.encodeWithSelector(IERC20.balanceOf.selector, address(this))
    );
    require(success && data.length >= 32);
    return abi.decode(data, (uint256));
  }

  /// @dev Get pool's balance of token1
  /// Gas saving to avoid a redundant extcodesize check
  /// in addition to the returndatasize check
  function _poolBalToken1() private view returns (uint256) {
    (bool success, bytes memory data) = address(token1).staticcall(
      abi.encodeWithSelector(IERC20.balanceOf.selector, address(this))
    );
    require(success && data.length >= 32);
    return abi.decode(data, (uint256));
  }

  /// @inheritdoc IPoolActions
  function unlockPool(uint160 initialSqrtP)
    external
    override
    returns (uint256 qty0, uint256 qty1)
  {
    require(poolData.sqrtP == 0, 'already inited');
    // initial tick bounds (min & max price limits) are checked in this function
    int24 initialTick = TickMath.getTickAtSqrtRatio(initialSqrtP);
    (qty0, qty1) = QtyDeltaMath.calcUnlockQtys(initialSqrtP);
    // because of price bounds, qty0 and qty1 >= 1
    require(qty0 <= _poolBalToken0(), 'lacking qty0');
    require(qty1 <= _poolBalToken1(), 'lacking qty1');
    _mint(address(this), C.MIN_LIQUIDITY);

    _initPoolStorage(initialSqrtP, initialTick);

    emit Initialize(initialSqrtP, initialTick);
  }

  /// @dev Make changes to a position
  /// @param posData the position details and the change to the position's liquidity to effect
  /// @return qty0 token0 qty owed to the pool, negative if the pool should pay the recipient
  /// @return qty1 token1 qty owed to the pool, negative if the pool should pay the recipient
  function _tweakPosition(UpdatePositionData memory posData)
    private
    returns (
      int256 qty0,
      int256 qty1,
      uint256 feeGrowthInsideLast
    )
  {
    require(posData.tickLower < posData.tickUpper, 'invalid tick range');
    require(TickMath.MIN_TICK <= posData.tickLower, 'invalid lower tick');
    require(posData.tickUpper <= TickMath.MAX_TICK, 'invalid upper tick');
    require(
      posData.tickLower % tickDistance == 0 && posData.tickUpper % tickDistance == 0,
      'tick not in distance'
    );

    // SLOAD variables into memory
    uint160 sqrtP = poolData.sqrtP;
    int24 currentTick = poolData.currentTick;
    uint128 baseL = poolData.baseL;
    uint128 reinvestL = poolData.reinvestL;
    CumulativesData memory cumulatives;
    cumulatives.feeGrowth = _syncFeeGrowth(baseL, reinvestL, poolData.feeGrowthGlobal, true);
    cumulatives.secondsPerLiquidity = _syncSecondsPerLiquidity(
      poolData.secondsPerLiquidityGlobal,
      baseL
    );

    uint256 feesClaimable;
    (feesClaimable, feeGrowthInsideLast) = _updatePosition(posData, currentTick, cumulatives);
    if (feesClaimable != 0) _transfer(address(this), posData.owner, feesClaimable);

    if (currentTick < posData.tickLower) {
      // current tick < position range
      // liquidity only comes in range when tick increases
      // which occurs when pool increases in token1, decreases in token0
      // means token0 is appreciating more against token1
      // hence user should provide token0
      return (
        QtyDeltaMath.calcRequiredQty0(
          TickMath.getSqrtRatioAtTick(posData.tickLower),
          TickMath.getSqrtRatioAtTick(posData.tickUpper),
          posData.liquidityDelta,
          posData.isAddLiquidity
        ),
        0,
        feeGrowthInsideLast
      );
    }
    if (currentTick >= posData.tickUpper) {
      // current tick > position range
      // liquidity only comes in range when tick decreases
      // which occurs when pool decreases in token1, increases in token0
      // means token1 is appreciating more against token0
      // hence user should provide token1
      return (
        0,
        QtyDeltaMath.calcRequiredQty1(
          TickMath.getSqrtRatioAtTick(posData.tickLower),
          TickMath.getSqrtRatioAtTick(posData.tickUpper),
          posData.liquidityDelta,
          posData.isAddLiquidity
        ),
        feeGrowthInsideLast
      );
    }
    // current tick is inside the passed range
    qty0 = QtyDeltaMath.calcRequiredQty0(
      sqrtP,
      TickMath.getSqrtRatioAtTick(posData.tickUpper),
      posData.liquidityDelta,
      posData.isAddLiquidity
    );
    qty1 = QtyDeltaMath.calcRequiredQty1(
      TickMath.getSqrtRatioAtTick(posData.tickLower),
      sqrtP,
      posData.liquidityDelta,
      posData.isAddLiquidity
    );

    // in addition, add liquidityDelta to current poolData.baseL
    // since liquidity is in range
    poolData.baseL = LiqDeltaMath.applyLiquidityDelta(
      baseL,
      posData.liquidityDelta,
      posData.isAddLiquidity
    );
  }

  /// @inheritdoc IPoolActions
  function mint(
    address recipient,
    int24 tickLower,
    int24 tickUpper,
    int24[2] calldata ticksPrevious,
    uint128 qty,
    bytes calldata data
  )
    external
    override
    lock
    returns (
      uint256 qty0,
      uint256 qty1,
      uint256 feeGrowthInsideLast
    )
  {
    require(qty != 0, '0 qty');
    require(factory.isWhitelistedNFTManager(msg.sender), 'forbidden');
    int256 qty0Int;
    int256 qty1Int;
    (qty0Int, qty1Int, feeGrowthInsideLast) = _tweakPosition(
      UpdatePositionData({
        owner: recipient,
        tickLower: tickLower,
        tickUpper: tickUpper,
        tickLowerPrevious: ticksPrevious[0],
        tickUpperPrevious: ticksPrevious[1],
        liquidityDelta: qty,
        isAddLiquidity: true
      })
    );
    qty0 = uint256(qty0Int);
    qty1 = uint256(qty1Int);

    uint256 balance0Before;
    uint256 balance1Before;
    if (qty0 > 0) balance0Before = _poolBalToken0();
    if (qty1 > 0) balance1Before = _poolBalToken1();
    IMintCallback(msg.sender).mintCallback(qty0, qty1, data);
    if (qty0 > 0) require(balance0Before + qty0 <= _poolBalToken0(), 'lacking qty0');
    if (qty1 > 0) require(balance1Before + qty1 <= _poolBalToken1(), 'lacking qty1');

    emit Mint(msg.sender, recipient, tickLower, tickUpper, qty, qty0, qty1);
  }

  /// @inheritdoc IPoolActions
  function burn(
    int24 tickLower,
    int24 tickUpper,
    uint128 qty
  )
    external
    override
    lock
    returns (
      uint256 qty0,
      uint256 qty1,
      uint256 feeGrowthInsideLast
    )
  {
    require(qty != 0, '0 qty');
    int256 qty0Int;
    int256 qty1Int;
    (qty0Int, qty1Int, feeGrowthInsideLast) = _tweakPosition(
      UpdatePositionData({
        owner: msg.sender,
        tickLower: tickLower,
        tickUpper: tickUpper,
        tickLowerPrevious: 0, // no use as there is no insertion
        tickUpperPrevious: 0, // no use as there is no insertion
        liquidityDelta: qty,
        isAddLiquidity: false
      })
    );

    if (qty0Int < 0) {
      qty0 = qty0Int.revToUint256();
      token0.safeTransfer(msg.sender, qty0);
    }
    if (qty1Int < 0) {
      qty1 = qty1Int.revToUint256();
      token1.safeTransfer(msg.sender, qty1);
    }

    emit Burn(msg.sender, tickLower, tickUpper, qty, qty0, qty1);
  }

  /// @inheritdoc IPoolActions
  function burnRTokens(uint256 _qty, bool isLogicalBurn)
    external
    override
    lock
    returns (uint256 qty0, uint256 qty1)
  {
    if (isLogicalBurn) {
      _burn(msg.sender, _qty);

      emit BurnRTokens(msg.sender, _qty, 0, 0);
      return (0, 0);
    }
    // SLOADs for gas optimizations
    uint128 baseL = poolData.baseL;
    uint128 reinvestL = poolData.reinvestL;
    uint160 sqrtP = poolData.sqrtP;
    _syncFeeGrowth(baseL, reinvestL, poolData.feeGrowthGlobal, false);

    // totalSupply() is the reinvestment token supply after syncing, but before burning
    uint256 deltaL = FullMath.mulDivFloor(_qty, reinvestL, totalSupply());
    reinvestL = reinvestL - deltaL.toUint128();
    poolData.reinvestL = reinvestL;
    poolData.reinvestLLast = reinvestL;
    // finally, calculate and send token quantities to user
    qty0 = QtyDeltaMath.getQty0FromBurnRTokens(sqrtP, deltaL);
    qty1 = QtyDeltaMath.getQty1FromBurnRTokens(sqrtP, deltaL);

    _burn(msg.sender, _qty);

    if (qty0 > 0) token0.safeTransfer(msg.sender, qty0);
    if (qty1 > 0) token1.safeTransfer(msg.sender, qty1);

    emit BurnRTokens(msg.sender, _qty, qty0, qty1);
  }

  // temporary swap variables, some of which will be used to update the pool state
  struct SwapData {
    int256 specifiedAmount; // the specified amount (could be tokenIn or tokenOut)
    int256 returnedAmount; // the opposite amout of sourceQty
    uint160 sqrtP; // current sqrt(price), multiplied by 2^96
    int24 currentTick; // the tick associated with the current price
    int24 nextTick; // the next initialized tick
    uint160 nextSqrtP; // the price of nextTick
    bool isToken0; // true if specifiedAmount is in token0, false if in token1
    bool isExactInput; // true = input qty, false = output qty
    uint128 baseL; // the cached base pool liquidity without reinvestment liquidity
    uint128 reinvestL; // the cached reinvestment liquidity
  }

  // variables below are loaded only when crossing a tick
  struct SwapCache {
    uint256 rTotalSupply; // cache of total reinvestment token supply
    uint128 reinvestLLast; // collected liquidity
    uint256 feeGrowthGlobal; // cache of fee growth of the reinvestment token, multiplied by 2^96
    uint128 secondsPerLiquidityGlobal; // all-time seconds per liquidity, multiplied by 2^96
    address feeTo; // recipient of govt fees
    uint24 governmentFeeUnits; // governmentFeeUnits to be charged
    uint256 governmentFee; // qty of reinvestment token for government fee
    uint256 lpFee; // qty of reinvestment token for liquidity provider
  }

  // @inheritdoc IPoolActions
  function swap(
    address recipient,
    int256 swapQty,
    bool isToken0,
    uint160 limitSqrtP,
    bytes calldata data
  ) external override lock returns (int256 deltaQty0, int256 deltaQty1) {
    require(swapQty != 0, '0 swapQty');

    SwapData memory swapData;
    swapData.specifiedAmount = swapQty;
    swapData.isToken0 = isToken0;
    swapData.isExactInput = swapData.specifiedAmount > 0;
    // tick (token1Qty/token0Qty) will increase for swapping from token1 to token0
    bool willUpTick = (swapData.isExactInput != isToken0);
    (
      swapData.baseL,
      swapData.reinvestL,
      swapData.sqrtP,
      swapData.currentTick,
      swapData.nextTick
    ) = _getInitialSwapData(willUpTick);
    // verify limitSqrtP
    if (willUpTick) {
      require(
        limitSqrtP > swapData.sqrtP && limitSqrtP < TickMath.MAX_SQRT_RATIO,
        'bad limitSqrtP'
      );
    } else {
      require(
        limitSqrtP < swapData.sqrtP && limitSqrtP > TickMath.MIN_SQRT_RATIO,
        'bad limitSqrtP'
      );
    }
    SwapCache memory cache;
    // continue swapping while specified input/output isn't satisfied or price limit not reached
    while (swapData.specifiedAmount != 0 && swapData.sqrtP != limitSqrtP) {
      // math calculations work with the assumption that the price diff is capped to 5%
      // since tick distance is uncapped between currentTick and nextTick
      // we use tempNextTick to satisfy our assumption with MAX_TICK_DISTANCE is set to be matched this condition
      int24 tempNextTick = swapData.nextTick;
      if (willUpTick && tempNextTick > C.MAX_TICK_DISTANCE + swapData.currentTick) {
        tempNextTick = swapData.currentTick + C.MAX_TICK_DISTANCE;
      } else if (!willUpTick && tempNextTick < swapData.currentTick - C.MAX_TICK_DISTANCE) {
        tempNextTick = swapData.currentTick - C.MAX_TICK_DISTANCE;
      }

      swapData.nextSqrtP = TickMath.getSqrtRatioAtTick(tempNextTick);

      // local scope for targetSqrtP, usedAmount, returnedAmount and deltaL
      {
        uint160 targetSqrtP = swapData.nextSqrtP;
        // ensure next sqrtP (and its corresponding tick) does not exceed price limit
        if (willUpTick == (swapData.nextSqrtP > limitSqrtP)) {
          targetSqrtP = limitSqrtP;
        }

        int256 usedAmount;
        int256 returnedAmount;
        uint256 deltaL;
        (usedAmount, returnedAmount, deltaL, swapData.sqrtP) = SwapMath.computeSwapStep(
          swapData.baseL + swapData.reinvestL,
          swapData.sqrtP,
          targetSqrtP,
          swapFeeUnits,
          swapData.specifiedAmount,
          swapData.isExactInput,
          swapData.isToken0
        );

        swapData.specifiedAmount -= usedAmount;
        swapData.returnedAmount += returnedAmount;
        swapData.reinvestL += deltaL.toUint128();
      }

      // if price has not reached the next sqrt price
      if (swapData.sqrtP != swapData.nextSqrtP) {
        swapData.currentTick = TickMath.getTickAtSqrtRatio(swapData.sqrtP);
        break;
      }
      swapData.currentTick = willUpTick ? tempNextTick : tempNextTick - 1;
      // if tempNextTick is not next initialized tick
      if (tempNextTick != swapData.nextTick) continue;

      if (cache.rTotalSupply == 0) {
        // load variables that are only initialized when crossing a tick
        cache.rTotalSupply = totalSupply();
        cache.reinvestLLast = poolData.reinvestLLast;
        cache.feeGrowthGlobal = poolData.feeGrowthGlobal;
        cache.secondsPerLiquidityGlobal = _syncSecondsPerLiquidity(
          poolData.secondsPerLiquidityGlobal,
          swapData.baseL
        );
        (cache.feeTo, cache.governmentFeeUnits) = factory.feeConfiguration();
      }
      // update rTotalSupply, feeGrowthGlobal and reinvestL
      uint256 rMintQty = ReinvestmentMath.calcrMintQty(
        swapData.reinvestL,
        cache.reinvestLLast,
        swapData.baseL,
        cache.rTotalSupply
      );
      if (rMintQty != 0) {
        cache.rTotalSupply += rMintQty;
        // overflow/underflow not possible bc governmentFeeUnits < 20000
        unchecked {
          uint256 governmentFee = (rMintQty * cache.governmentFeeUnits) / C.FEE_UNITS;
          cache.governmentFee += governmentFee;

          uint256 lpFee = rMintQty - governmentFee;
          cache.lpFee += lpFee;

          cache.feeGrowthGlobal += FullMath.mulDivFloor(lpFee, C.TWO_POW_96, swapData.baseL);
        }
      }
      cache.reinvestLLast = swapData.reinvestL;

      (swapData.baseL, swapData.nextTick) = _updateLiquidityAndCrossTick(
        swapData.nextTick,
        swapData.baseL,
        cache.feeGrowthGlobal,
        cache.secondsPerLiquidityGlobal,
        willUpTick
      );
    }

    // if the swap crosses at least 1 initalized tick
    if (cache.rTotalSupply != 0) {
      if (cache.governmentFee > 0) _mint(cache.feeTo, cache.governmentFee);
      if (cache.lpFee > 0) _mint(address(this), cache.lpFee);
      poolData.reinvestLLast = cache.reinvestLLast;
      poolData.feeGrowthGlobal = cache.feeGrowthGlobal;
    }

    _updatePoolData(
      swapData.baseL,
      swapData.reinvestL,
      swapData.sqrtP,
      swapData.currentTick,
      swapData.nextTick
    );

    (deltaQty0, deltaQty1) = isToken0
      ? (swapQty - swapData.specifiedAmount, swapData.returnedAmount)
      : (swapData.returnedAmount, swapQty - swapData.specifiedAmount);

    // handle token transfers and perform callback
    if (willUpTick) {
      // outbound deltaQty0 (negative), inbound deltaQty1 (positive)
      // transfer deltaQty0 to recipient
      if (deltaQty0 < 0) token0.safeTransfer(recipient, deltaQty0.revToUint256());

      // collect deltaQty1
      uint256 balance1Before = _poolBalToken1();
      ISwapCallback(msg.sender).swapCallback(deltaQty0, deltaQty1, data);
      require(_poolBalToken1() >= balance1Before + uint256(deltaQty1), 'lacking deltaQty1');
    } else {
      // inbound deltaQty0 (positive), outbound deltaQty1 (negative)
      // transfer deltaQty1 to recipient
      if (deltaQty1 < 0) token1.safeTransfer(recipient, deltaQty1.revToUint256());

      // collect deltaQty0
      uint256 balance0Before = _poolBalToken0();
      ISwapCallback(msg.sender).swapCallback(deltaQty0, deltaQty1, data);
      require(_poolBalToken0() >= balance0Before + uint256(deltaQty0), 'lacking deltaQty0');
    }

    emit Swap(
      msg.sender,
      recipient,
      deltaQty0,
      deltaQty1,
      swapData.sqrtP,
      swapData.baseL,
      swapData.currentTick
    );
  }

  /// @inheritdoc IPoolActions
  function flash(
    address recipient,
    uint256 qty0,
    uint256 qty1,
    bytes calldata data
  ) external override lock {
    // send all collected fees to feeTo
    (address feeTo, ) = factory.feeConfiguration();
    uint256 feeQty0;
    uint256 feeQty1;
    if (feeTo != address(0)) {
      feeQty0 = (qty0 * swapFeeUnits) / C.FEE_UNITS;
      feeQty1 = (qty1 * swapFeeUnits) / C.FEE_UNITS;
    }
    uint256 balance0Before = _poolBalToken0();
    uint256 balance1Before = _poolBalToken1();

    if (qty0 > 0) token0.safeTransfer(recipient, qty0);
    if (qty1 > 0) token1.safeTransfer(recipient, qty1);

    IFlashCallback(msg.sender).flashCallback(feeQty0, feeQty1, data);

    uint256 balance0After = _poolBalToken0();
    uint256 balance1After = _poolBalToken1();

    require(balance0Before + feeQty0 <= balance0After, 'lacking feeQty0');
    require(balance1Before + feeQty1 <= balance1After, 'lacking feeQty1');

    uint256 paid0;
    uint256 paid1;
    unchecked {
      paid0 = balance0After - balance0Before;
      paid1 = balance1After - balance1Before;
    }

    if (paid0 > 0) token0.safeTransfer(feeTo, paid0);
    if (paid1 > 0) token1.safeTransfer(feeTo, paid1);

    emit Flash(msg.sender, recipient, qty0, qty1, paid0, paid1);
  }

  /// @dev sync the value of secondsPerLiquidity data to current block.timestamp
  /// @return new value of _secondsPerLiquidityGlobal
  function _syncSecondsPerLiquidity(uint128 _secondsPerLiquidityGlobal, uint128 baseL)
    internal
    returns (uint128)
  {
    uint256 secondsElapsed = _blockTimestamp() - poolData.secondsPerLiquidityUpdateTime;
    // update secondsPerLiquidityGlobal and secondsPerLiquidityUpdateTime if needed
    if (secondsElapsed > 0 && baseL > 0) {
      _secondsPerLiquidityGlobal += uint128((secondsElapsed << C.RES_96) / baseL);
      // write to storage
      poolData.secondsPerLiquidityGlobal = _secondsPerLiquidityGlobal;
      poolData.secondsPerLiquidityUpdateTime = _blockTimestamp();
    }
    return _secondsPerLiquidityGlobal;
  }

  /// @dev sync the value of feeGrowthGlobal and the value of each reinvestment token.
  /// @dev update reinvestLLast to latest value if necessary
  /// @return the lastest value of _feeGrowthGlobal
  function _syncFeeGrowth(
    uint128 baseL,
    uint128 reinvestL,
    uint256 _feeGrowthGlobal,
    bool updateReinvestLLast
  ) internal returns (uint256) {
    uint256 rMintQty = ReinvestmentMath.calcrMintQty(
      uint256(reinvestL),
      uint256(poolData.reinvestLLast),
      baseL,
      totalSupply()
    );
    if (rMintQty != 0) {
      rMintQty = _deductGovermentFee(rMintQty);
      _mint(address(this), rMintQty);
      // baseL != 0 because baseL = 0 => rMintQty = 0
      unchecked {
        _feeGrowthGlobal += FullMath.mulDivFloor(rMintQty, C.TWO_POW_96, baseL);
      }
      poolData.feeGrowthGlobal = _feeGrowthGlobal;
    }
    // update poolData.reinvestLLast if required
    if (updateReinvestLLast) poolData.reinvestLLast = reinvestL;
    return _feeGrowthGlobal;
  }

  /// @return the lp fee without governance fee
  function _deductGovermentFee(uint256 rMintQty) internal returns (uint256) {
    // fetch governmentFeeUnits
    (address feeTo, uint24 governmentFeeUnits) = factory.feeConfiguration();
    if (governmentFeeUnits == 0) {
      return rMintQty;
    }

    // unchecked due to governmentFeeUnits <= 20000
    unchecked {
      uint256 rGovtQty = (rMintQty * governmentFeeUnits) / C.FEE_UNITS;
      if (rGovtQty != 0) {
        _mint(feeTo, rGovtQty);
      }
      return rMintQty - rGovtQty;
    }
  }
}

File 2 of 28 : SafeERC20.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

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

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

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

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

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

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

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

File 3 of 28 : ERC20.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

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

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

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

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

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

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

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

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

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

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

    /**
     * @dev See {IERC20-approve}.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * Requirements:
     *
     * - `sender` and `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     * - the caller must have allowance for ``sender``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);

        uint256 currentAllowance = _allowances[sender][_msgSender()];
        require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
        unchecked {
            _approve(sender, _msgSender(), currentAllowance - amount);
        }

        return true;
    }

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

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

        return true;
    }

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

        _beforeTokenTransfer(sender, recipient, amount);

        uint256 senderBalance = _balances[sender];
        require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[sender] = senderBalance - amount;
        }
        _balances[recipient] += amount;

        emit Transfer(sender, recipient, amount);

        _afterTokenTransfer(sender, recipient, amount);
    }

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

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

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);

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

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

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

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;

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

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

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

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

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

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

File 4 of 28 : IERC20.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

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

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

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

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

File 5 of 28 : LiqDeltaMath.sol
// SPDX-License-Identifier: agpl-3.0
pragma solidity >=0.8.0;

/// @title Contains helper function to add or remove uint128 liquidityDelta to uint128 liquidity
library LiqDeltaMath {
  function applyLiquidityDelta(
    uint128 liquidity,
    uint128 liquidityDelta,
    bool isAddLiquidity
  ) internal pure returns (uint128) {
    return isAddLiquidity ? liquidity + liquidityDelta : liquidity - liquidityDelta;
  }
}

File 6 of 28 : QtyDeltaMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;

import {MathConstants as C} from './MathConstants.sol';
import {TickMath} from './TickMath.sol';
import {FullMath} from './FullMath.sol';
import {SafeCast} from './SafeCast.sol';

/// @title Contains helper functions for calculating
/// token0 and token1 quantites from differences in prices
/// or from burning reinvestment tokens
library QtyDeltaMath {
  using SafeCast for uint256;
  using SafeCast for int128;

  function calcUnlockQtys(uint160 initialSqrtP)
    internal
    pure
    returns (uint256 qty0, uint256 qty1)
  {
    qty0 = FullMath.mulDivCeiling(C.MIN_LIQUIDITY, C.TWO_POW_96, initialSqrtP);
    qty1 = FullMath.mulDivCeiling(C.MIN_LIQUIDITY, initialSqrtP, C.TWO_POW_96);
  }

  /// @notice Gets the qty0 delta between two prices
  /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
  /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
  /// rounds up if adding liquidity, rounds down if removing liquidity
  /// @param lowerSqrtP The lower sqrt price.
  /// @param upperSqrtP The upper sqrt price. Should be >= lowerSqrtP
  /// @param liquidity Liquidity quantity
  /// @param isAddLiquidity true = add liquidity, false = remove liquidity
  /// @return token0 qty required for position with liquidity between the 2 sqrt prices
  function calcRequiredQty0(
    uint160 lowerSqrtP,
    uint160 upperSqrtP,
    uint128 liquidity,
    bool isAddLiquidity
  ) internal pure returns (int256) {
    uint256 numerator1 = uint256(liquidity) << C.RES_96;
    uint256 numerator2;
    unchecked {
      numerator2 = upperSqrtP - lowerSqrtP;
    }
    return
      isAddLiquidity
        ? (divCeiling(FullMath.mulDivCeiling(numerator1, numerator2, upperSqrtP), lowerSqrtP))
          .toInt256()
        : (FullMath.mulDivFloor(numerator1, numerator2, upperSqrtP) / lowerSqrtP).revToInt256();
  }

  /// @notice Gets the token1 delta quantity between two prices
  /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
  /// rounds up if adding liquidity, rounds down if removing liquidity
  /// @param lowerSqrtP The lower sqrt price.
  /// @param upperSqrtP The upper sqrt price. Should be >= lowerSqrtP
  /// @param liquidity Liquidity quantity
  /// @param isAddLiquidity true = add liquidity, false = remove liquidity
  /// @return token1 qty required for position with liquidity between the 2 sqrt prices
  function calcRequiredQty1(
    uint160 lowerSqrtP,
    uint160 upperSqrtP,
    uint128 liquidity,
    bool isAddLiquidity
  ) internal pure returns (int256) {
    unchecked {
      return
        isAddLiquidity
          ? (FullMath.mulDivCeiling(liquidity, upperSqrtP - lowerSqrtP, C.TWO_POW_96)).toInt256()
          : (FullMath.mulDivFloor(liquidity, upperSqrtP - lowerSqrtP, C.TWO_POW_96)).revToInt256();
    }
  }

  /// @notice Calculates the token0 quantity proportion to be sent to the user
  /// for burning reinvestment tokens
  /// @param sqrtP Current pool sqrt price
  /// @param liquidity Difference in reinvestment liquidity due to reinvestment token burn
  /// @return token0 quantity to be sent to the user
  function getQty0FromBurnRTokens(uint160 sqrtP, uint256 liquidity)
    internal
    pure
    returns (uint256)
  {
    return FullMath.mulDivFloor(liquidity, C.TWO_POW_96, sqrtP);
  }

  /// @notice Calculates the token1 quantity proportion to be sent to the user
  /// for burning reinvestment tokens
  /// @param sqrtP Current pool sqrt price
  /// @param liquidity Difference in reinvestment liquidity due to reinvestment token burn
  /// @return token1 quantity to be sent to the user
  function getQty1FromBurnRTokens(uint160 sqrtP, uint256 liquidity)
    internal
    pure
    returns (uint256)
  {
    return FullMath.mulDivFloor(liquidity, sqrtP, C.TWO_POW_96);
  }

  /// @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 divCeiling(uint256 x, uint256 y) internal pure returns (uint256 z) {
    // return x / y + ((x % y == 0) ? 0 : 1);
    require(y > 0);
    assembly {
      z := add(div(x, y), gt(mod(x, y), 0))
    }
  }
}

File 7 of 28 : MathConstants.sol
// SPDX-License-Identifier: agpl-3.0
pragma solidity >=0.8.0;

/// @title Contains constants needed for math libraries
library MathConstants {
  uint256 internal constant TWO_FEE_UNITS = 200_000;
  uint256 internal constant TWO_POW_96 = 2**96;
  uint128 internal constant MIN_LIQUIDITY = 100000;
  uint8 internal constant RES_96 = 96;
  uint24 internal constant BPS = 10000;
  uint24 internal constant FEE_UNITS = 100000;
  // it is strictly less than 5% price movement if jumping MAX_TICK_DISTANCE ticks
  int24 internal constant MAX_TICK_DISTANCE = 480;
  // max number of tick travel when inserting if data changes
  uint256 internal constant MAX_TICK_TRAVEL = 10;
}

File 8 of 28 : ReinvestmentMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;

import {MathConstants as C} from './MathConstants.sol';
import {FullMath} from './FullMath.sol';

/// @title Contains helper function to calculate the number of reinvestment tokens to be minted
library ReinvestmentMath {
  /// @dev calculate the mint amount with given reinvestL, reinvestLLast, baseL and rTotalSupply
  /// contribution of lp to the increment is calculated by the proportion of baseL with reinvestL + baseL
  /// then rMintQty is calculated by mutiplying this with the liquidity per reinvestment token
  /// rMintQty = rTotalSupply * (reinvestL - reinvestLLast) / reinvestLLast * baseL / (baseL + reinvestL)
  function calcrMintQty(
    uint256 reinvestL,
    uint256 reinvestLLast,
    uint128 baseL,
    uint256 rTotalSupply
  ) internal pure returns (uint256 rMintQty) {
    uint256 lpContribution = FullMath.mulDivFloor(
      baseL,
      reinvestL - reinvestLLast,
      baseL + reinvestL
    );
    rMintQty = FullMath.mulDivFloor(rTotalSupply, lpContribution, reinvestLLast);
  }
}

File 9 of 28 : SwapMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;

import {MathConstants as C} from './MathConstants.sol';
import {FullMath} from './FullMath.sol';
import {QuadMath} from './QuadMath.sol';
import {SafeCast} from './SafeCast.sol';

/// @title Contains helper functions for swaps
library SwapMath {
  using SafeCast for uint256;
  using SafeCast for int256;

  /// @dev Computes the actual swap input / output amounts to be deducted or added,
  /// the swap fee to be collected and the resulting sqrtP.
  /// @notice nextSqrtP should not exceed targetSqrtP.
  /// @param liquidity active base liquidity + reinvest liquidity
  /// @param currentSqrtP current sqrt price
  /// @param targetSqrtP sqrt price limit the new sqrt price can take
  /// @param feeInFeeUnits swap fee in basis points
  /// @param specifiedAmount the amount remaining to be used for the swap
  /// @param isExactInput true if specifiedAmount refers to input amount, false if specifiedAmount refers to output amount
  /// @param isToken0 true if specifiedAmount is in token0, false if specifiedAmount is in token1
  /// @return usedAmount actual amount to be used for the swap
  /// @return returnedAmount output qty to be accumulated if isExactInput = true, input qty if isExactInput = false
  /// @return deltaL collected swap fee, to be incremented to reinvest liquidity
  /// @return nextSqrtP the new sqrt price after the computed swap step
  function computeSwapStep(
    uint256 liquidity,
    uint160 currentSqrtP,
    uint160 targetSqrtP,
    uint256 feeInFeeUnits,
    int256 specifiedAmount,
    bool isExactInput,
    bool isToken0
  )
    internal
    pure
    returns (
      int256 usedAmount,
      int256 returnedAmount,
      uint256 deltaL,
      uint160 nextSqrtP
    )
  {
    // in the event currentSqrtP == targetSqrtP because of tick movements, return
    // eg. swapped up tick where specified price limit is on an initialised tick
    // then swapping down tick will cause next tick to be the same as the current tick
    if (currentSqrtP == targetSqrtP) return (0, 0, 0, currentSqrtP);
    usedAmount = calcReachAmount(
      liquidity,
      currentSqrtP,
      targetSqrtP,
      feeInFeeUnits,
      isExactInput,
      isToken0
    );

    if (
      (isExactInput && usedAmount >= specifiedAmount) ||
      (!isExactInput && usedAmount <= specifiedAmount)
    ) {
      usedAmount = specifiedAmount;
    } else {
      nextSqrtP = targetSqrtP;
    }

    uint256 absDelta = usedAmount >= 0 ? uint256(usedAmount) : usedAmount.revToUint256();
    if (nextSqrtP == 0) {
      deltaL = estimateIncrementalLiquidity(
        absDelta,
        liquidity,
        currentSqrtP,
        feeInFeeUnits,
        isExactInput,
        isToken0
      );
      nextSqrtP = calcFinalPrice(absDelta, liquidity, deltaL, currentSqrtP, isExactInput, isToken0)
      .toUint160();
    } else {
      deltaL = calcIncrementalLiquidity(
        absDelta,
        liquidity,
        currentSqrtP,
        nextSqrtP,
        isExactInput,
        isToken0
      );
    }
    returnedAmount = calcReturnedAmount(
      liquidity,
      currentSqrtP,
      nextSqrtP,
      deltaL,
      isExactInput,
      isToken0
    );
  }

  /// @dev calculates the amount needed to reach targetSqrtP from currentSqrtP
  /// @dev we cast currentSqrtP and targetSqrtP to uint256 as they are multiplied by TWO_FEE_UNITS or feeInFeeUnits
  function calcReachAmount(
    uint256 liquidity,
    uint256 currentSqrtP,
    uint256 targetSqrtP,
    uint256 feeInFeeUnits,
    bool isExactInput,
    bool isToken0
  ) internal pure returns (int256 reachAmount) {
    uint256 absPriceDiff;
    unchecked {
      absPriceDiff = (currentSqrtP >= targetSqrtP)
        ? (currentSqrtP - targetSqrtP)
        : (targetSqrtP - currentSqrtP);
    }
    if (isExactInput) {
      // we round down so that we avoid taking giving away too much for the specified input
      // ie. require less input qty to move ticks
      if (isToken0) {
        // numerator = 2 * liquidity * absPriceDiff
        // denominator = currentSqrtP * (2 * targetSqrtP - currentSqrtP * feeInFeeUnits / FEE_UNITS)
        // overflow should not happen because the absPriceDiff is capped to ~5%
        uint256 denominator = C.TWO_FEE_UNITS * targetSqrtP - feeInFeeUnits * currentSqrtP;
        uint256 numerator = FullMath.mulDivFloor(
          liquidity,
          C.TWO_FEE_UNITS * absPriceDiff,
          denominator
        );
        reachAmount = FullMath.mulDivFloor(numerator, C.TWO_POW_96, currentSqrtP).toInt256();
      } else {
        // numerator = 2 * liquidity * absPriceDiff * currentSqrtP
        // denominator = 2 * currentSqrtP - targetSqrtP * feeInFeeUnits / FEE_UNITS
        // overflow should not happen because the absPriceDiff is capped to ~5%
        uint256 denominator = C.TWO_FEE_UNITS * currentSqrtP - feeInFeeUnits * targetSqrtP;
        uint256 numerator = FullMath.mulDivFloor(
          liquidity,
          C.TWO_FEE_UNITS * absPriceDiff,
          denominator
        );
        reachAmount = FullMath.mulDivFloor(numerator, currentSqrtP, C.TWO_POW_96).toInt256();
      }
    } else {
      // we will perform negation as the last step
      // we round down so that we require less output qty to move ticks
      if (isToken0) {
        // numerator: (liquidity)(absPriceDiff)(2 * currentSqrtP - deltaL * (currentSqrtP + targetSqrtP))
        // denominator: (currentSqrtP * targetSqrtP) * (2 * currentSqrtP - deltaL * targetSqrtP)
        // overflow should not happen because the absPriceDiff is capped to ~5%
        uint256 denominator = C.TWO_FEE_UNITS * currentSqrtP - feeInFeeUnits * targetSqrtP;
        uint256 numerator = denominator - feeInFeeUnits * currentSqrtP;
        numerator = FullMath.mulDivFloor(liquidity << C.RES_96, numerator, denominator);
        reachAmount = (FullMath.mulDivFloor(numerator, absPriceDiff, currentSqrtP) / targetSqrtP)
        .revToInt256();
      } else {
        // numerator: liquidity * absPriceDiff * (TWO_FEE_UNITS * targetSqrtP - feeInFeeUnits * (targetSqrtP + currentSqrtP))
        // denominator: (TWO_FEE_UNITS * targetSqrtP - feeInFeeUnits * currentSqrtP)
        // overflow should not happen because the absPriceDiff is capped to ~5%
        uint256 denominator = C.TWO_FEE_UNITS * targetSqrtP - feeInFeeUnits * currentSqrtP;
        uint256 numerator = denominator - feeInFeeUnits * targetSqrtP;
        numerator = FullMath.mulDivFloor(liquidity, numerator, denominator);
        reachAmount = FullMath.mulDivFloor(numerator, absPriceDiff, C.TWO_POW_96).revToInt256();
      }
    }
  }

  /// @dev estimates deltaL, the swap fee to be collected based on amount specified
  /// for the final swap step to be performed,
  /// where the next (temporary) tick will not be crossed
  function estimateIncrementalLiquidity(
    uint256 absDelta,
    uint256 liquidity,
    uint160 currentSqrtP,
    uint256 feeInFeeUnits,
    bool isExactInput,
    bool isToken0
  ) internal pure returns (uint256 deltaL) {
    if (isExactInput) {
      if (isToken0) {
        // deltaL = feeInFeeUnits * absDelta * currentSqrtP / 2
        deltaL = FullMath.mulDivFloor(
          currentSqrtP,
          absDelta * feeInFeeUnits,
          C.TWO_FEE_UNITS << C.RES_96
        );
      } else {
        // deltaL = feeInFeeUnits * absDelta * / (currentSqrtP * 2)
        // Because nextSqrtP = (liquidity + absDelta / currentSqrtP) * currentSqrtP / (liquidity + deltaL)
        // so we round up deltaL, to round down nextSqrtP
        deltaL = FullMath.mulDivFloor(
          C.TWO_POW_96,
          absDelta * feeInFeeUnits,
          C.TWO_FEE_UNITS * currentSqrtP
        );
      }
    } else {
      // obtain the smaller root of the quadratic equation
      // ax^2 - 2bx + c = 0 such that b > 0, and x denotes deltaL
      uint256 a = feeInFeeUnits;
      uint256 b = (C.FEE_UNITS - feeInFeeUnits) * liquidity;
      uint256 c = feeInFeeUnits * liquidity * absDelta;
      if (isToken0) {
        // a = feeInFeeUnits
        // b = (FEE_UNITS - feeInFeeUnits) * liquidity - FEE_UNITS * absDelta * currentSqrtP
        // c = feeInFeeUnits * liquidity * absDelta * currentSqrtP
        b -= FullMath.mulDivFloor(C.FEE_UNITS * absDelta, currentSqrtP, C.TWO_POW_96);
        c = FullMath.mulDivFloor(c, currentSqrtP, C.TWO_POW_96);
      } else {
        // a = feeInFeeUnits
        // b = (FEE_UNITS - feeInFeeUnits) * liquidity - FEE_UNITS * absDelta / currentSqrtP
        // c = liquidity * feeInFeeUnits * absDelta / currentSqrtP
        b -= FullMath.mulDivFloor(C.FEE_UNITS * absDelta, C.TWO_POW_96, currentSqrtP);
        c = FullMath.mulDivFloor(c, C.TWO_POW_96, currentSqrtP);
      }
      deltaL = QuadMath.getSmallerRootOfQuadEqn(a, b, c);
    }
  }

  /// @dev calculates deltaL, the swap fee to be collected for an intermediate swap step,
  /// where the next (temporary) tick will be crossed
  function calcIncrementalLiquidity(
    uint256 absDelta,
    uint256 liquidity,
    uint160 currentSqrtP,
    uint160 nextSqrtP,
    bool isExactInput,
    bool isToken0
  ) internal pure returns (uint256 deltaL) {
    if (isToken0) {
      // deltaL = nextSqrtP * (liquidity / currentSqrtP +/- absDelta)) - liquidity
      // needs to be minimum
      uint256 tmp1 = FullMath.mulDivFloor(liquidity, C.TWO_POW_96, currentSqrtP);
      uint256 tmp2 = isExactInput ? tmp1 + absDelta : tmp1 - absDelta;
      uint256 tmp3 = FullMath.mulDivFloor(nextSqrtP, tmp2, C.TWO_POW_96);
      // in edge cases where liquidity or absDelta is small
      // liquidity might be greater than nextSqrtP * ((liquidity / currentSqrtP) +/- absDelta))
      // due to rounding
      deltaL = (tmp3 > liquidity) ? tmp3 - liquidity : 0;
    } else {
      // deltaL = (liquidity * currentSqrtP +/- absDelta) / nextSqrtP - liquidity
      // needs to be minimum
      uint256 tmp1 = FullMath.mulDivFloor(liquidity, currentSqrtP, C.TWO_POW_96);
      uint256 tmp2 = isExactInput ? tmp1 + absDelta : tmp1 - absDelta;
      uint256 tmp3 = FullMath.mulDivFloor(tmp2, C.TWO_POW_96, nextSqrtP);
      // in edge cases where liquidity or absDelta is small
      // liquidity might be greater than nextSqrtP * ((liquidity / currentSqrtP) +/- absDelta))
      // due to rounding
      deltaL = (tmp3 > liquidity) ? tmp3 - liquidity : 0;
    }
  }

  /// @dev calculates the sqrt price of the final swap step
  /// where the next (temporary) tick will not be crossed
  function calcFinalPrice(
    uint256 absDelta,
    uint256 liquidity,
    uint256 deltaL,
    uint160 currentSqrtP,
    bool isExactInput,
    bool isToken0
  ) internal pure returns (uint256) {
    if (isToken0) {
      // if isExactInput: swap 0 -> 1, sqrtP decreases, we round up
      // else swap: 1 -> 0, sqrtP increases, we round down
      uint256 tmp = FullMath.mulDivFloor(absDelta, currentSqrtP, C.TWO_POW_96);
      if (isExactInput) {
        return FullMath.mulDivCeiling(liquidity + deltaL, currentSqrtP, liquidity + tmp);
      } else {
        return FullMath.mulDivFloor(liquidity + deltaL, currentSqrtP, liquidity - tmp);
      }
    } else {
      // if isExactInput: swap 1 -> 0, sqrtP increases, we round down
      // else swap: 0 -> 1, sqrtP decreases, we round up
      if (isExactInput) {
        uint256 tmp = FullMath.mulDivFloor(absDelta, C.TWO_POW_96, currentSqrtP);
        return FullMath.mulDivFloor(liquidity + tmp, currentSqrtP, liquidity + deltaL);
      } else {
        uint256 tmp = FullMath.mulDivFloor(absDelta, C.TWO_POW_96, currentSqrtP);
        return FullMath.mulDivCeiling(liquidity - tmp, currentSqrtP, liquidity + deltaL);
      }
    }
  }

  /// @dev calculates returned output | input tokens in exchange for specified amount
  /// @dev round down when calculating returned output (isExactInput) so we avoid sending too much
  /// @dev round up when calculating returned input (!isExactInput) so we get desired output amount
  function calcReturnedAmount(
    uint256 liquidity,
    uint160 currentSqrtP,
    uint160 nextSqrtP,
    uint256 deltaL,
    bool isExactInput,
    bool isToken0
  ) internal pure returns (int256 returnedAmount) {
    if (isToken0) {
      if (isExactInput) {
        // minimise actual output (<0, make less negative) so we avoid sending too much
        // returnedAmount = deltaL * nextSqrtP - liquidity * (currentSqrtP - nextSqrtP)
        returnedAmount =
          FullMath.mulDivCeiling(deltaL, nextSqrtP, C.TWO_POW_96).toInt256() +
          FullMath.mulDivFloor(liquidity, currentSqrtP - nextSqrtP, C.TWO_POW_96).revToInt256();
      } else {
        // maximise actual input (>0) so we get desired output amount
        // returnedAmount = deltaL * nextSqrtP + liquidity * (nextSqrtP - currentSqrtP)
        returnedAmount =
          FullMath.mulDivCeiling(deltaL, nextSqrtP, C.TWO_POW_96).toInt256() +
          FullMath.mulDivCeiling(liquidity, nextSqrtP - currentSqrtP, C.TWO_POW_96).toInt256();
      }
    } else {
      // returnedAmount = (liquidity + deltaL)/nextSqrtP - (liquidity)/currentSqrtP
      // if exactInput, minimise actual output (<0, make less negative) so we avoid sending too much
      // if exactOutput, maximise actual input (>0) so we get desired output amount
      returnedAmount =
        FullMath.mulDivCeiling(liquidity + deltaL, C.TWO_POW_96, nextSqrtP).toInt256() +
        FullMath.mulDivFloor(liquidity, C.TWO_POW_96, currentSqrtP).revToInt256();
    }

    if (isExactInput && returnedAmount == 1) {
      // rounding make returnedAmount == 1
      returnedAmount = 0;
    }
  }
}

File 10 of 28 : FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
/// @dev Code has been modified to be compatible with sol 0.8
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 mulDivFloor(
    uint256 a,
    uint256 b,
    uint256 denominator
  ) internal pure returns (uint256 result) {
    // 512-bit multiply [prod1 prod0] = a * b
    // Compute the product mod 2**256 and mod 2**256 - 1
    // then use the Chinese Remainder Theorem to reconstruct
    // the 512 bit result. The result is stored in two 256
    // variables such that product = prod1 * 2**256 + prod0
    uint256 prod0; // Least significant 256 bits of the product
    uint256 prod1; // Most significant 256 bits of the product
    assembly {
      let mm := mulmod(a, b, not(0))
      prod0 := mul(a, b)
      prod1 := sub(sub(mm, prod0), lt(mm, prod0))
    }

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

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

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

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

    // Factor powers of two out of denominator
    // Compute largest power of two divisor of denominator.
    // Always >= 1.
    uint256 twos = denominator & (~denominator + 1);
    // 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)
    }
    unchecked {
      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 mulDivCeiling(
    uint256 a,
    uint256 b,
    uint256 denominator
  ) internal pure returns (uint256 result) {
    result = mulDivFloor(a, b, denominator);
    if (mulmod(a, b, denominator) > 0) {
      result++;
    }
  }
}

File 11 of 28 : SafeCast.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;

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

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

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

  /// @notice Cast a int128 to a uint128 and reverses the sign.
  /// @param y The int128 to be casted
  /// @return z = -y, now type uint128
  function revToUint128(int128 y) internal pure returns (uint128 z) {
    unchecked {
      return type(uint128).max - uint128(y) + 1;
    }
  }

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

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

  /// @notice Cast a int256 to a uint256 and reverses the sign.
  /// @param y The int256 to be casted
  /// @return z = -y, now type uint256
  function revToUint256(int256 y) internal pure returns (uint256 z) {
    unchecked {
      return type(uint256).max - uint256(y) + 1;
    }
  }
}

File 12 of 28 : TickMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
  /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
  int24 internal constant MIN_TICK = -887272;
  /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
  int24 internal constant MAX_TICK = -MIN_TICK;

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

  /// @notice Calculates sqrt(1.0001^tick) * 2^96
  /// @dev Throws if |tick| > max tick
  /// @param tick The input tick for the above formula
  /// @return sqrtP 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 sqrtP) {
    unchecked {
      uint256 absTick = uint256(tick < 0 ? -int256(tick) : int256(tick));
      require(absTick <= uint256(int256(MAX_TICK)), 'T');

      // do bitwise comparison, if i-th bit is turned on,
      // multiply ratio by hardcoded values of sqrt(1.0001^-(2^i)) * 2^128
      // where 0 <= i <= 19
      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;

      // take reciprocal for positive tick values
      if (tick > 0) ratio = type(uint256).max / ratio;

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

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

    uint256 r = ratio;
    uint256 msb = 0;

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

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

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

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

      int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number

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

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

  function getMaxNumberTicks(int24 _tickDistance) internal pure returns (uint24 numTicks) {
    return uint24(TickMath.MAX_TICK / _tickDistance) * 2;
  }
}

File 13 of 28 : IPool.sol
// SPDX-License-Identifier: agpl-3.0
pragma solidity >=0.8.0;

import {IPoolActions} from './pool/IPoolActions.sol';
import {IPoolEvents} from './pool/IPoolEvents.sol';
import {IPoolStorage} from './pool/IPoolStorage.sol';

interface IPool is IPoolActions, IPoolEvents, IPoolStorage {}

File 14 of 28 : IPoolActions.sol
// SPDX-License-Identifier: agpl-3.0
pragma solidity >=0.8.0;

interface IPoolActions {
  /// @notice Sets the initial price for the pool and seeds reinvestment liquidity
  /// @dev Assumes the caller has sent the necessary token amounts
  /// required for initializing reinvestment liquidity prior to calling this function
  /// @param initialSqrtP the initial sqrt price of the pool
  /// @param qty0 token0 quantity sent to and locked permanently in the pool
  /// @param qty1 token1 quantity sent to and locked permanently in the pool
  function unlockPool(uint160 initialSqrtP) external returns (uint256 qty0, uint256 qty1);

  /// @notice Adds liquidity for the specified recipient/tickLower/tickUpper position
  /// @dev Any token0 or token1 owed for the liquidity provision have to be paid for when
  /// the IMintCallback#mintCallback is called to this method's caller
  /// The quantity of token0/token1 to be sent depends on
  /// tickLower, tickUpper, the amount of liquidity, and the current price of the pool.
  /// Also sends reinvestment tokens (fees) to the recipient for any fees collected
  /// while the position is in range
  /// Reinvestment tokens have to be burnt via #burnRTokens in exchange for token0 and token1
  /// @param recipient Address for which the added liquidity is credited to
  /// @param tickLower Recipient position's lower tick
  /// @param tickUpper Recipient position's upper tick
  /// @param ticksPrevious The nearest tick that is initialized and <= the lower & upper ticks
  /// @param qty Liquidity quantity to mint
  /// @param data Data (if any) to be passed through to the callback
  /// @return qty0 token0 quantity sent to the pool in exchange for the minted liquidity
  /// @return qty1 token1 quantity sent to the pool in exchange for the minted liquidity
  /// @return feeGrowthInside position's updated feeGrowthInside value
  function mint(
    address recipient,
    int24 tickLower,
    int24 tickUpper,
    int24[2] calldata ticksPrevious,
    uint128 qty,
    bytes calldata data
  )
    external
    returns (
      uint256 qty0,
      uint256 qty1,
      uint256 feeGrowthInside
    );

  /// @notice Remove liquidity from the caller
  /// Also sends reinvestment tokens (fees) to the caller for any fees collected
  /// while the position is in range
  /// Reinvestment tokens have to be burnt via #burnRTokens in exchange for token0 and token1
  /// @param tickLower Position's lower tick for which to burn liquidity
  /// @param tickUpper Position's upper tick for which to burn liquidity
  /// @param qty Liquidity quantity to burn
  /// @return qty0 token0 quantity sent to the caller
  /// @return qty1 token1 quantity sent to the caller
  /// @return feeGrowthInside position's updated feeGrowthInside value
  function burn(
    int24 tickLower,
    int24 tickUpper,
    uint128 qty
  )
    external
    returns (
      uint256 qty0,
      uint256 qty1,
      uint256 feeGrowthInside
    );

  /// @notice Burns reinvestment tokens in exchange to receive the fees collected in token0 and token1
  /// @param qty Reinvestment token quantity to burn
  /// @param isLogicalBurn true if burning rTokens without returning any token0/token1
  ///         otherwise should transfer token0/token1 to sender
  /// @return qty0 token0 quantity sent to the caller for burnt reinvestment tokens
  /// @return qty1 token1 quantity sent to the caller for burnt reinvestment tokens
  function burnRTokens(uint256 qty, bool isLogicalBurn)
    external
    returns (uint256 qty0, uint256 qty1);

  /// @notice Swap token0 -> token1, or vice versa
  /// @dev This method's caller receives a callback in the form of ISwapCallback#swapCallback
  /// @dev swaps will execute up to limitSqrtP or swapQty is fully used
  /// @param recipient The address to receive the swap output
  /// @param swapQty The swap quantity, which implicitly configures the swap as exact input (>0), or exact output (<0)
  /// @param isToken0 Whether the swapQty is specified in token0 (true) or token1 (false)
  /// @param limitSqrtP the limit of sqrt price after swapping
  /// could be MAX_SQRT_RATIO-1 when swapping 1 -> 0 and MIN_SQRT_RATIO+1 when swapping 0 -> 1 for no limit swap
  /// @param data Any data to be passed through to the callback
  /// @return qty0 Exact token0 qty sent to recipient if < 0. Minimally received quantity if > 0.
  /// @return qty1 Exact token1 qty sent to recipient if < 0. Minimally received quantity if > 0.
  function swap(
    address recipient,
    int256 swapQty,
    bool isToken0,
    uint160 limitSqrtP,
    bytes calldata data
  ) external returns (int256 qty0, int256 qty1);

  /// @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 IFlashCallback#flashCallback
  /// @dev Fees collected are sent to the feeTo address if it is set in Factory
  /// @param recipient The address which will receive the token0 and token1 quantities
  /// @param qty0 token0 quantity to be loaned to the recipient
  /// @param qty1 token1 quantity to be loaned to the recipient
  /// @param data Any data to be passed through to the callback
  function flash(
    address recipient,
    uint256 qty0,
    uint256 qty1,
    bytes calldata data
  ) external;
}

File 15 of 28 : IFactory.sol
// SPDX-License-Identifier: agpl-3.0
pragma solidity >=0.8.0;

/// @title KyberSwap v2 factory
/// @notice Deploys KyberSwap v2 pools and manages control over government fees
interface IFactory {
  /// @notice Emitted when a pool is created
  /// @param token0 First pool token by address sort order
  /// @param token1 Second pool token by address sort order
  /// @param swapFeeUnits Fee to be collected upon every swap in the pool, in fee units
  /// @param tickDistance 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 swapFeeUnits,
    int24 tickDistance,
    address pool
  );

  /// @notice Emitted when a new fee is enabled for pool creation via the factory
  /// @param swapFeeUnits Fee to be collected upon every swap in the pool, in fee units
  /// @param tickDistance Minimum number of ticks between initialized ticks for pools created with the given fee
  event SwapFeeEnabled(uint24 indexed swapFeeUnits, int24 indexed tickDistance);

  /// @notice Emitted when vesting period changes
  /// @param vestingPeriod The maximum time duration for which LP fees
  /// are proportionally burnt upon LP removals
  event VestingPeriodUpdated(uint32 vestingPeriod);

  /// @notice Emitted when configMaster changes
  /// @param oldConfigMaster configMaster before the update
  /// @param newConfigMaster configMaster after the update
  event ConfigMasterUpdated(address oldConfigMaster, address newConfigMaster);

  /// @notice Emitted when fee configuration changes
  /// @param feeTo Recipient of government fees
  /// @param governmentFeeUnits Fee amount, in fee units,
  /// to be collected out of the fee charged for a pool swap
  event FeeConfigurationUpdated(address feeTo, uint24 governmentFeeUnits);

  /// @notice Emitted when whitelist feature is enabled
  event WhitelistEnabled();

  /// @notice Emitted when whitelist feature is disabled
  event WhitelistDisabled();

  /// @notice Returns the maximum time duration for which LP fees
  /// are proportionally burnt upon LP removals
  function vestingPeriod() external view returns (uint32);

  /// @notice Returns the tick distance for a specified fee.
  /// @dev Once added, cannot be updated or removed.
  /// @param swapFeeUnits Swap fee, in fee units.
  /// @return The tick distance. Returns 0 if fee has not been added.
  function feeAmountTickDistance(uint24 swapFeeUnits) external view returns (int24);

  /// @notice Returns the address which can update the fee configuration
  function configMaster() external view returns (address);

  /// @notice Returns the keccak256 hash of the Pool creation code
  /// This is used for pre-computation of pool addresses
  function poolInitHash() external view returns (bytes32);

  /// @notice Fetches the recipient of government fees
  /// and current government fee charged in fee units
  function feeConfiguration() external view returns (address _feeTo, uint24 _governmentFeeUnits);

  /// @notice Returns the status of whitelisting feature of NFT managers
  /// If true, anyone can mint liquidity tokens
  /// Otherwise, only whitelisted NFT manager(s) are allowed to mint liquidity tokens
  function whitelistDisabled() external view returns (bool);

  //// @notice Returns all whitelisted NFT managers
  /// If the whitelisting feature is turned on,
  /// only whitelisted NFT manager(s) are allowed to mint liquidity tokens
  function getWhitelistedNFTManagers() external view returns (address[] memory);

  /// @notice Checks if sender is a whitelisted NFT manager
  /// If the whitelisting feature is turned on,
  /// only whitelisted NFT manager(s) are allowed to mint liquidity tokens
  /// @param sender address to be checked
  /// @return true if sender is a whistelisted NFT manager, false otherwise
  function isWhitelistedNFTManager(address sender) external view returns (bool);

  /// @notice Returns the pool address for a given pair of tokens and a swap fee
  /// @dev Token order does not matter
  /// @param tokenA Contract address of either token0 or token1
  /// @param tokenB Contract address of the other token
  /// @param swapFeeUnits Fee to be collected upon every swap in the pool, in fee units
  /// @return pool The pool address. Returns null address if it does not exist
  function getPool(
    address tokenA,
    address tokenB,
    uint24 swapFeeUnits
  ) external view returns (address pool);

  /// @notice Fetch parameters to be used for pool creation
  /// @dev Called by the pool constructor to fetch the parameters of the pool
  /// @return factory The factory address
  /// @return token0 First pool token by address sort order
  /// @return token1 Second pool token by address sort order
  /// @return swapFeeUnits Fee to be collected upon every swap in the pool, in fee units
  /// @return tickDistance Minimum number of ticks between initialized ticks
  function parameters()
    external
    view
    returns (
      address factory,
      address token0,
      address token1,
      uint24 swapFeeUnits,
      int24 tickDistance
    );

  /// @notice Creates a pool for the given two tokens and fee
  /// @param tokenA One of the two tokens in the desired pool
  /// @param tokenB The other of the two tokens in the desired pool
  /// @param swapFeeUnits Desired swap fee for the pool, in fee units
  /// @dev Token order does not matter. tickDistance is determined from the fee.
  /// Call will revert under any of these conditions:
  ///     1) pool already exists
  ///     2) invalid swap fee
  ///     3) invalid token arguments
  /// @return pool The address of the newly created pool
  function createPool(
    address tokenA,
    address tokenB,
    uint24 swapFeeUnits
  ) external returns (address pool);

  /// @notice Enables a fee amount with the given tickDistance
  /// @dev Fee amounts may never be removed once enabled
  /// @param swapFeeUnits The fee amount to enable, in fee units
  /// @param tickDistance The distance between ticks to be enforced for all pools created with the given fee amount
  function enableSwapFee(uint24 swapFeeUnits, int24 tickDistance) external;

  /// @notice Updates the address which can update the fee configuration
  /// @dev Must be called by the current configMaster
  function updateConfigMaster(address) external;

  /// @notice Updates the vesting period
  /// @dev Must be called by the current configMaster
  function updateVestingPeriod(uint32) external;

  /// @notice Updates the address receiving government fees and fee quantity
  /// @dev Only configMaster is able to perform the update
  /// @param feeTo Address to receive government fees collected from pools
  /// @param governmentFeeUnits Fee amount, in fee units,
  /// to be collected out of the fee charged for a pool swap
  function updateFeeConfiguration(address feeTo, uint24 governmentFeeUnits) external;

  /// @notice Enables the whitelisting feature
  /// @dev Only configMaster is able to perform the update
  function enableWhitelist() external;

  /// @notice Disables the whitelisting feature
  /// @dev Only configMaster is able to perform the update
  function disableWhitelist() external;
}

File 16 of 28 : IMintCallback.sol
// SPDX-License-Identifier: agpl-3.0
pragma solidity >=0.8.0;

/// @title Callback for IPool#mint
/// @notice Any contract that calls IPool#mint must implement this interface
interface IMintCallback {
  /// @notice Called to `msg.sender` after minting liquidity via IPool#mint.
  /// @dev This function's implementation must send pool tokens to the pool for the minted LP tokens.
  /// The caller of this method must be checked to be a Pool deployed by the canonical Factory.
  /// @param deltaQty0 The token0 quantity to be sent to the pool.
  /// @param deltaQty1 The token1 quantity to be sent to the pool.
  /// @param data Data passed through by the caller via the IPool#mint call
  function mintCallback(
    uint256 deltaQty0,
    uint256 deltaQty1,
    bytes calldata data
  ) external;
}

File 17 of 28 : ISwapCallback.sol
// SPDX-License-Identifier: agpl-3.0
pragma solidity >=0.8.0;

/// @title Callback for IPool#swap
/// @notice Any contract that calls IPool#swap must implement this interface
interface ISwapCallback {
  /// @notice Called to `msg.sender` after swap execution of IPool#swap.
  /// @dev This function's implementation must pay tokens owed to the pool for the swap.
  /// The caller of this method must be checked to be a Pool deployed by the canonical Factory.
  /// deltaQty0 and deltaQty1 can both be 0 if no tokens were swapped.
  /// @param deltaQty0 The token0 quantity that was sent (negative) or must be received (positive) by the pool by
  /// the end of the swap. If positive, the callback must send deltaQty0 of token0 to the pool.
  /// @param deltaQty1 The token1 quantity that was sent (negative) or must be received (positive) by the pool by
  /// the end of the swap. If positive, the callback must send deltaQty1 of token1 to the pool.
  /// @param data Data passed through by the caller via the IPool#swap call
  function swapCallback(
    int256 deltaQty0,
    int256 deltaQty1,
    bytes calldata data
  ) external;
}

File 18 of 28 : IFlashCallback.sol
// SPDX-License-Identifier: agpl-3.0
pragma solidity >=0.8.0;

/// @title Callback for IPool#flash
/// @notice Any contract that calls IPool#flash must implement this interface
interface IFlashCallback {
  /// @notice Called to `msg.sender` after flash loaning to the recipient from IPool#flash.
  /// @dev This function's implementation must send the loaned amounts with computed fee amounts
  /// The caller of this method must be checked to be a Pool deployed by the canonical Factory.
  /// @param feeQty0 The token0 fee to be sent to the pool.
  /// @param feeQty1 The token1 fee to be sent to the pool.
  /// @param data Data passed through by the caller via the IPool#flash call
  function flashCallback(
    uint256 feeQty0,
    uint256 feeQty1,
    bytes calldata data
  ) external;
}

File 19 of 28 : PoolTicksState.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;

import {LiqDeltaMath} from './libraries/LiqDeltaMath.sol';
import {SafeCast} from './libraries/SafeCast.sol';
import {MathConstants} from './libraries/MathConstants.sol';
import {FullMath} from './libraries/FullMath.sol';
import {TickMath} from './libraries/TickMath.sol';
import {Linkedlist} from './libraries/Linkedlist.sol';

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

contract PoolTicksState is PoolStorage {
  using SafeCast for int128;
  using SafeCast for uint128;
  using Linkedlist for mapping(int24 => Linkedlist.Data);

  struct UpdatePositionData {
    // address of owner of the position
    address owner;
    // position's lower and upper ticks
    int24 tickLower;
    int24 tickUpper;
    // if minting, need to pass the previous initialized ticks for tickLower and tickUpper
    int24 tickLowerPrevious;
    int24 tickUpperPrevious;
    // any change in liquidity
    uint128 liquidityDelta;
    // true = adding liquidity, false = removing liquidity
    bool isAddLiquidity;
  }

  function _updatePosition(
    UpdatePositionData memory updateData,
    int24 currentTick,
    CumulativesData memory cumulatives
  ) internal returns (uint256 feesClaimable, uint256 feeGrowthInside) {
    // update ticks if necessary
    uint256 feeGrowthOutsideLowerTick = _updateTick(
      updateData.tickLower,
      currentTick,
      updateData.tickLowerPrevious,
      updateData.liquidityDelta,
      updateData.isAddLiquidity,
      cumulatives,
      true
    );

    uint256 feeGrowthOutsideUpperTick = _updateTick(
      updateData.tickUpper,
      currentTick,
      updateData.tickUpperPrevious,
      updateData.liquidityDelta,
      updateData.isAddLiquidity,
      cumulatives,
      false
    );

    // calculate feeGrowthInside
    unchecked {
      if (currentTick < updateData.tickLower) {
        feeGrowthInside = feeGrowthOutsideLowerTick - feeGrowthOutsideUpperTick;
      } else if (currentTick >= updateData.tickUpper) {
        feeGrowthInside = feeGrowthOutsideUpperTick - feeGrowthOutsideLowerTick;
      } else {
        feeGrowthInside =
          cumulatives.feeGrowth -
          feeGrowthOutsideLowerTick -
          feeGrowthOutsideUpperTick;
      }
    }

    // calc rTokens to be minted for the position's accumulated fees
    feesClaimable = _updatePositionData(updateData, feeGrowthInside);
  }

  /// @dev Update liquidity net data and do cross tick
  function _updateLiquidityAndCrossTick(
    int24 nextTick,
    uint128 currentLiquidity,
    uint256 feeGrowthGlobal,
    uint128 secondsPerLiquidityGlobal,
    bool willUpTick
  ) internal returns (uint128 newLiquidity, int24 newNextTick) {
    unchecked {
      ticks[nextTick].feeGrowthOutside = feeGrowthGlobal - ticks[nextTick].feeGrowthOutside;
      ticks[nextTick].secondsPerLiquidityOutside =
        secondsPerLiquidityGlobal -
        ticks[nextTick].secondsPerLiquidityOutside;
    }
    int128 liquidityNet = ticks[nextTick].liquidityNet;
    if (willUpTick) {
      newNextTick = initializedTicks[nextTick].next;
    } else {
      newNextTick = initializedTicks[nextTick].previous;
      liquidityNet = -liquidityNet;
    }
    newLiquidity = LiqDeltaMath.applyLiquidityDelta(
      currentLiquidity,
      liquidityNet >= 0 ? uint128(liquidityNet) : liquidityNet.revToUint128(),
      liquidityNet >= 0
    );
  }

  function _updatePoolData(
    uint128 baseL,
    uint128 reinvestL,
    uint160 sqrtP,
    int24 currentTick,
    int24 nextTick
  ) internal {
    poolData.baseL = baseL;
    poolData.reinvestL = reinvestL;
    poolData.sqrtP = sqrtP;
    poolData.currentTick = currentTick;
    poolData.nearestCurrentTick = nextTick > currentTick
      ? initializedTicks[nextTick].previous
      : nextTick;
  }

  /// @dev Return initial data before swapping
  /// @param willUpTick whether is up/down tick
  /// @return baseL current pool base liquidity without reinvestment liquidity
  /// @return reinvestL current pool reinvestment liquidity
  /// @return sqrtP current pool sqrt price
  /// @return currentTick current pool tick
  /// @return nextTick next tick to calculate data
  function _getInitialSwapData(bool willUpTick)
    internal
    view
    returns (
      uint128 baseL,
      uint128 reinvestL,
      uint160 sqrtP,
      int24 currentTick,
      int24 nextTick
    )
  {
    baseL = poolData.baseL;
    reinvestL = poolData.reinvestL;
    sqrtP = poolData.sqrtP;
    currentTick = poolData.currentTick;
    nextTick = poolData.nearestCurrentTick;
    if (willUpTick) {
      nextTick = initializedTicks[nextTick].next;
    }
  }

  function _updatePositionData(UpdatePositionData memory _data, uint256 feeGrowthInside)
    private
    returns (uint256 feesClaimable)
  {
    bytes32 key = _positionKey(_data.owner, _data.tickLower, _data.tickUpper);
    // calculate accumulated fees for current liquidity
    // feeGrowthInside is relative value, hence underflow is acceptable
    uint256 feeGrowth;
    unchecked {
      feeGrowth = feeGrowthInside - positions[key].feeGrowthInsideLast;
    }
    uint128 prevLiquidity = positions[key].liquidity;
    feesClaimable = FullMath.mulDivFloor(feeGrowth, prevLiquidity, MathConstants.TWO_POW_96);
    // update the position
    positions[key].liquidity = LiqDeltaMath.applyLiquidityDelta(
      prevLiquidity,
      _data.liquidityDelta,
      _data.isAddLiquidity
    );
    positions[key].feeGrowthInsideLast = feeGrowthInside;
  }

  /// @notice Updates a tick and returns the fee growth outside of that tick
  /// @param tick Tick to be updated
  /// @param tickCurrent Current tick
  /// @param tickPrevious the nearest initialized tick which is lower than or equal to `tick`
  /// @param liquidityDelta Liquidity quantity to be added | removed when tick is crossed up | down
  /// @param cumulatives All-time global fee growth and seconds, per unit of liquidity
  /// @param isLower true | false if updating a position's lower | upper tick
  /// @return feeGrowthOutside last value of feeGrowthOutside
  function _updateTick(
    int24 tick,
    int24 tickCurrent,
    int24 tickPrevious,
    uint128 liquidityDelta,
    bool isAdd,
    CumulativesData memory cumulatives,
    bool isLower
  ) private returns (uint256 feeGrowthOutside) {
    uint128 liquidityGrossBefore = ticks[tick].liquidityGross;
    uint128 liquidityGrossAfter = LiqDeltaMath.applyLiquidityDelta(
      liquidityGrossBefore,
      liquidityDelta,
      isAdd
    );
    require(liquidityGrossAfter <= maxTickLiquidity, '> max liquidity');
    int128 signedLiquidityDelta = isAdd ? liquidityDelta.toInt128() : -(liquidityDelta.toInt128());

    // if lower tick, liquidityDelta should be added | removed when crossed up | down
    // else, for upper tick, liquidityDelta should be removed | added when crossed up | down
    int128 liquidityNetAfter = isLower
      ? ticks[tick].liquidityNet + signedLiquidityDelta
      : ticks[tick].liquidityNet - signedLiquidityDelta;

    if (liquidityGrossBefore == 0) {
      // by convention, all growth before a tick was initialized is assumed to happen below it
      if (tick <= tickCurrent) {
        ticks[tick].feeGrowthOutside = cumulatives.feeGrowth;
        ticks[tick].secondsPerLiquidityOutside = cumulatives.secondsPerLiquidity;
      }
    }

    ticks[tick].liquidityGross = liquidityGrossAfter;
    ticks[tick].liquidityNet = liquidityNetAfter;
    feeGrowthOutside = ticks[tick].feeGrowthOutside;

    if (liquidityGrossBefore > 0 && liquidityGrossAfter == 0) {
      delete ticks[tick];
    }

    if ((liquidityGrossBefore > 0) != (liquidityGrossAfter > 0)) {
      _updateTickList(tick, tickPrevious, tickCurrent, isAdd);
    }
  }

  /// @dev Update the tick linkedlist, assume that tick is not in the list
  /// @param tick tick index to update
  /// @param currentTick the pool currentt tick
  /// @param previousTick the nearest initialized tick that is lower than the tick, in case adding
  /// @param isAdd whether is add or remove the tick
  function _updateTickList(
    int24 tick,
    int24 previousTick,
    int24 currentTick,
    bool isAdd
  ) internal {
    if (isAdd) {
      if (tick == TickMath.MIN_TICK || tick == TickMath.MAX_TICK) return;
      // find the correct previousTick to the `tick`, avoid revert when new liquidity has been added between tick & previousTick
      int24 nextTick = initializedTicks[previousTick].next;
      require(
        nextTick != initializedTicks[previousTick].previous,
        'previous tick has been removed'
      );
      uint256 iteration = 0;
      while (nextTick <= tick && iteration < MathConstants.MAX_TICK_TRAVEL) {
        previousTick = nextTick;
        nextTick = initializedTicks[previousTick].next;
        iteration++;
      }
      initializedTicks.insert(tick, previousTick, nextTick);
      if (poolData.nearestCurrentTick < tick && tick <= currentTick) {
        poolData.nearestCurrentTick = tick;
      }
    } else {
      if (tick == poolData.nearestCurrentTick) {
        poolData.nearestCurrentTick = initializedTicks.remove(tick);
      } else {
        initializedTicks.remove(tick);
      }
    }
  }
}

File 20 of 28 : Address.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        assembly {
            size := extcodesize(account)
        }
        return size > 0;
    }

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

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

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

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

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

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

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

File 21 of 28 : IERC20Metadata.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../IERC20.sol";

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

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

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

File 22 of 28 : Context.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

File 23 of 28 : QuadMath.sol
// SPDX-License-Identifier: agpl-3.0
pragma solidity >=0.8.0;

library QuadMath {
  // our equation is ax^2 - 2bx + c = 0, where a, b and c > 0
  // the qudratic formula to obtain the smaller root is (2b - sqrt((2*b)^2 - 4ac)) / 2a
  // which can be simplified to (b - sqrt(b^2 - ac)) / a
  function getSmallerRootOfQuadEqn(
    uint256 a,
    uint256 b,
    uint256 c
  ) internal pure returns (uint256 smallerRoot) {
    smallerRoot = (b - sqrt(b * b - a * c)) / a;
  }

  // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
  function sqrt(uint256 y) internal pure returns (uint256 z) {
    unchecked {
      if (y > 3) {
        z = y;
        uint256 x = y / 2 + 1;
        while (x < z) {
          z = x;
          x = (y / x + x) / 2;
        }
      } else if (y != 0) {
        z = 1;
      }
    }
  }
}

File 24 of 28 : IPoolEvents.sol
// SPDX-License-Identifier: agpl-3.0
pragma solidity >=0.8.0;

interface IPoolEvents {
  /// @notice Emitted only once per pool when #initialize is first called
  /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
  /// @param sqrtP The initial price of the pool
  /// @param tick The initial tick of the pool
  event Initialize(uint160 sqrtP, int24 tick);

  /// @notice Emitted when liquidity is minted for a given position
  /// @dev transfers reinvestment tokens for any collected fees earned by the position
  /// @param sender address that minted the liquidity
  /// @param owner address of owner of the position
  /// @param tickLower position's lower tick
  /// @param tickUpper position's upper tick
  /// @param qty liquidity minted to the position range
  /// @param qty0 token0 quantity needed to mint the liquidity
  /// @param qty1 token1 quantity needed to mint the liquidity
  event Mint(
    address sender,
    address indexed owner,
    int24 indexed tickLower,
    int24 indexed tickUpper,
    uint128 qty,
    uint256 qty0,
    uint256 qty1
  );

  /// @notice Emitted when a position's liquidity is removed
  /// @dev transfers reinvestment tokens for any collected fees earned by the position
  /// @param owner address of owner of the position
  /// @param tickLower position's lower tick
  /// @param tickUpper position's upper tick
  /// @param qty liquidity removed
  /// @param qty0 token0 quantity withdrawn from removal of liquidity
  /// @param qty1 token1 quantity withdrawn from removal of liquidity
  event Burn(
    address indexed owner,
    int24 indexed tickLower,
    int24 indexed tickUpper,
    uint128 qty,
    uint256 qty0,
    uint256 qty1
  );

  /// @notice Emitted when reinvestment tokens are burnt
  /// @param owner address which burnt the reinvestment tokens
  /// @param qty reinvestment token quantity burnt
  /// @param qty0 token0 quantity sent to owner for burning reinvestment tokens
  /// @param qty1 token1 quantity sent to owner for burning reinvestment tokens
  event BurnRTokens(address indexed owner, uint256 qty, uint256 qty0, uint256 qty1);

  /// @notice Emitted for swaps by the pool between token0 and token1
  /// @param sender Address that initiated the swap call, and that received the callback
  /// @param recipient Address that received the swap output
  /// @param deltaQty0 Change in pool's token0 balance
  /// @param deltaQty1 Change in pool's token1 balance
  /// @param sqrtP Pool's sqrt price after the swap
  /// @param liquidity Pool's liquidity after the swap
  /// @param currentTick Log base 1.0001 of pool's price after the swap
  event Swap(
    address indexed sender,
    address indexed recipient,
    int256 deltaQty0,
    int256 deltaQty1,
    uint160 sqrtP,
    uint128 liquidity,
    int24 currentTick
  );

  /// @notice Emitted by the pool for any flash loans of token0/token1
  /// @param sender The address that initiated the flash loan, and that received the callback
  /// @param recipient The address that received the flash loan quantities
  /// @param qty0 token0 quantity loaned to the recipient
  /// @param qty1 token1 quantity loaned to the recipient
  /// @param paid0 token0 quantity paid for the flash, which can exceed qty0 + fee
  /// @param paid1 token1 quantity paid for the flash, which can exceed qty0 + fee
  event Flash(
    address indexed sender,
    address indexed recipient,
    uint256 qty0,
    uint256 qty1,
    uint256 paid0,
    uint256 paid1
  );
}

File 25 of 28 : IPoolStorage.sol
// SPDX-License-Identifier: agpl-3.0
pragma solidity >=0.8.0;

import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';

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

interface IPoolStorage {
  /// @notice The contract that deployed the pool, which must adhere to the IFactory interface
  /// @return The contract address
  function factory() external view returns (IFactory);

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

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

  /// @notice The fee to be charged for a swap in basis points
  /// @return The swap fee in basis points
  function swapFeeUnits() external view returns (uint24);

  /// @notice The pool tick distance
  /// @dev Ticks can only be initialized and used at multiples of this value
  /// It remains an int24 to avoid casting even though it is >= 1.
  /// e.g: a tickDistance of 5 means ticks can be initialized every 5th tick, i.e., ..., -10, -5, 0, 5, 10, ...
  /// @return The tick distance
  function tickDistance() external view returns (int24);

  /// @notice Maximum gross liquidity that an initialized tick can have
  /// @dev This is to prevent overflow the pool's active base liquidity (uint128)
  /// 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 maxTickLiquidity() external view returns (uint128);

  /// @notice Look up information about a specific tick in the pool
  /// @param tick The tick to look up
  /// @return liquidityGross total liquidity amount from positions that uses this tick as a lower or upper tick
  /// liquidityNet how much liquidity changes when the pool tick crosses above the tick
  /// feeGrowthOutside the fee growth on the other side of the tick relative to the current tick
  /// secondsPerLiquidityOutside the seconds spent on the other side of the tick relative to the current tick
  function ticks(int24 tick)
    external
    view
    returns (
      uint128 liquidityGross,
      int128 liquidityNet,
      uint256 feeGrowthOutside,
      uint128 secondsPerLiquidityOutside
    );

  /// @notice Returns the previous and next initialized ticks of a specific tick
  /// @dev If specified tick is uninitialized, the returned values are zero.
  /// @param tick The tick to look up
  function initializedTicks(int24 tick) external view returns (int24 previous, int24 next);

  /// @notice Returns the information about a position by the position's key
  /// @return liquidity the liquidity quantity of the position
  /// @return feeGrowthInsideLast fee growth inside the tick range as of the last mint / burn action performed
  function getPositions(
    address owner,
    int24 tickLower,
    int24 tickUpper
  ) external view returns (uint128 liquidity, uint256 feeGrowthInsideLast);

  /// @notice Fetches the pool's prices, ticks and lock status
  /// @return sqrtP sqrt of current price: sqrt(token1/token0)
  /// @return currentTick pool's current tick
  /// @return nearestCurrentTick pool's nearest initialized tick that is <= currentTick
  /// @return locked true if pool is locked, false otherwise
  function getPoolState()
    external
    view
    returns (
      uint160 sqrtP,
      int24 currentTick,
      int24 nearestCurrentTick,
      bool locked
    );

  /// @notice Fetches the pool's liquidity values
  /// @return baseL pool's base liquidity without reinvest liqudity
  /// @return reinvestL the liquidity is reinvested into the pool
  /// @return reinvestLLast last cached value of reinvestL, used for calculating reinvestment token qty
  function getLiquidityState()
    external
    view
    returns (
      uint128 baseL,
      uint128 reinvestL,
      uint128 reinvestLLast
    );

  /// @return feeGrowthGlobal All-time fee growth per unit of liquidity of the pool
  function getFeeGrowthGlobal() external view returns (uint256);

  /// @return secondsPerLiquidityGlobal All-time seconds per unit of liquidity of the pool
  /// @return lastUpdateTime The timestamp in which secondsPerLiquidityGlobal was last updated
  function getSecondsPerLiquidityData()
    external
    view
    returns (uint128 secondsPerLiquidityGlobal, uint32 lastUpdateTime);

  /// @notice Calculates and returns the active time per unit of liquidity until current block.timestamp
  /// @param tickLower The lower tick (of a position)
  /// @param tickUpper The upper tick (of a position)
  /// @return secondsPerLiquidityInside active time (multiplied by 2^96)
  /// between the 2 ticks, per unit of liquidity.
  function getSecondsPerLiquidityInside(int24 tickLower, int24 tickUpper)
    external
    view
    returns (uint128 secondsPerLiquidityInside);
}

File 26 of 28 : Linkedlist.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;

/// @title The implementation for a LinkedList
library Linkedlist {
  struct Data {
    int24 previous;
    int24 next;
  }

  /// @dev init data with the lowest and highest value of the LinkedList
  /// @param lowestValue the lowest and also the HEAD of LinkedList
  /// @param highestValue the highest and also the TAIL of the LinkedList
  function init(
    mapping(int24 => Linkedlist.Data) storage self,
    int24 lowestValue,
    int24 highestValue
  ) internal {
    (self[lowestValue].previous, self[lowestValue].next) = (lowestValue, highestValue);
    (self[highestValue].previous, self[highestValue].next) = (lowestValue, highestValue);
  }

  /// @dev Remove a value from the linked list, return the lower value
  ///   Return the lower value after removing, in case removedValue is the lowest/highest, no removing is done
  function remove(mapping(int24 => Linkedlist.Data) storage self, int24 removedValue)
    internal
    returns (int24 lowerValue)
  {
    Data memory removedValueData = self[removedValue];
    require(removedValueData.next != removedValueData.previous, 'remove non-existent value');
    if (removedValueData.previous == removedValue) return removedValue; // remove the lowest value, nothing is done
    lowerValue = removedValueData.previous;
    if (removedValueData.next == removedValue) return lowerValue; // remove the highest value, nothing is done
    self[removedValueData.previous].next = removedValueData.next;
    self[removedValueData.next].previous = removedValueData.previous;
    delete self[removedValue];
  }

  /// @dev Insert a new value to the linked list given its lower value that is inside the linked list
  /// @param newValue the new value to insert, it must not exist in the LinkedList
  /// @param lowerValue the nearest value which is <= newValue and is in the LinkedList
  function insert(
    mapping(int24 => Linkedlist.Data) storage self,
    int24 newValue,
    int24 lowerValue,
    int24 nextValue
  ) internal {
    require(nextValue != self[lowerValue].previous, 'lower value is not initialized');
    require(lowerValue < newValue && nextValue > newValue, 'invalid lower value');
    self[newValue].next = nextValue;
    self[newValue].previous = lowerValue;
    self[nextValue].previous = newValue;
    self[lowerValue].next = newValue;
  }
}

File 27 of 28 : PoolStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;

import {Clones} from '@openzeppelin/contracts/proxy/Clones.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';

import {Linkedlist} from './libraries/Linkedlist.sol';
import {TickMath} from './libraries/TickMath.sol';
import {MathConstants as C} from './libraries/MathConstants.sol';

import {IFactory} from './interfaces/IFactory.sol';
import {IPoolStorage} from './interfaces/pool/IPoolStorage.sol';

abstract contract PoolStorage is IPoolStorage {
  using Clones for address;
  using Linkedlist for mapping(int24 => Linkedlist.Data);

  address internal constant LIQUIDITY_LOCKUP_ADDRESS = 0xD444422222222222222222222222222222222222;

  struct PoolData {
    uint160 sqrtP;
    int24 nearestCurrentTick;
    int24 currentTick;
    bool locked;
    uint128 baseL;
    uint128 reinvestL;
    uint128 reinvestLLast;
    uint256 feeGrowthGlobal;
    uint128 secondsPerLiquidityGlobal;
    uint32 secondsPerLiquidityUpdateTime;
  }

  // data stored for each initialized individual tick
  struct TickData {
    // gross liquidity of all positions in tick
    uint128 liquidityGross;
    // liquidity quantity to be added | removed when tick is crossed up | down
    int128 liquidityNet;
    // fee growth per unit of liquidity on the other side of this tick (relative to current tick)
    // only has relative meaning, not absolute — the value depends on when the tick is initialized
    uint256 feeGrowthOutside;
    // seconds spent on the other side of this tick (relative to current tick)
    // only has relative meaning, not absolute — the value depends on when the tick is initialized
    uint128 secondsPerLiquidityOutside;
  }

  // data stored for each user's position
  struct Position {
    // the amount of liquidity owned by this position
    uint128 liquidity;
    // fee growth per unit of liquidity as of the last update to liquidity
    uint256 feeGrowthInsideLast;
  }

  struct CumulativesData {
    uint256 feeGrowth;
    uint128 secondsPerLiquidity;
  }

  /// see IPoolStorage for explanations of the immutables below
  IFactory public immutable override factory;
  IERC20 public immutable override token0;
  IERC20 public immutable override token1;
  uint128 public immutable override maxTickLiquidity;
  uint24 public immutable override swapFeeUnits;
  int24 public immutable override tickDistance;

  mapping(int24 => TickData) public override ticks;
  mapping(int24 => Linkedlist.Data) public override initializedTicks;

  mapping(bytes32 => Position) internal positions;

  PoolData internal poolData;

  constructor() {
    // fetch data from factory constructor
    (
      address _factory,
      address _token0,
      address _token1,
      uint24 _swapFeeUnits,
      int24 _tickDistance
    ) = IFactory(msg.sender).parameters();
    factory = IFactory(_factory);
    token0 = IERC20(_token0);
    token1 = IERC20(_token1);
    swapFeeUnits = _swapFeeUnits;
    tickDistance = _tickDistance;

    maxTickLiquidity = type(uint128).max / TickMath.getMaxNumberTicks(_tickDistance);
    poolData.locked = true; // set pool to locked state
  }

  function _initPoolStorage(uint160 initialSqrtP, int24 initialTick) internal {
    poolData.baseL = 0;
    poolData.reinvestL = C.MIN_LIQUIDITY;
    poolData.reinvestLLast = C.MIN_LIQUIDITY;

    poolData.sqrtP = initialSqrtP;
    poolData.currentTick = initialTick;
    poolData.nearestCurrentTick = TickMath.MIN_TICK;

    initializedTicks.init(TickMath.MIN_TICK, TickMath.MAX_TICK);
    poolData.locked = false; // unlock the pool
  }

  function getPositions(
    address owner,
    int24 tickLower,
    int24 tickUpper
  ) external view override returns (uint128 liquidity, uint256 feeGrowthInsideLast) {
    bytes32 key = _positionKey(owner, tickLower, tickUpper);
    return (positions[key].liquidity, positions[key].feeGrowthInsideLast);
  }

  /// @inheritdoc IPoolStorage
  function getPoolState()
    external
    view
    override
    returns (
      uint160 sqrtP,
      int24 currentTick,
      int24 nearestCurrentTick,
      bool locked
    )
  {
    sqrtP = poolData.sqrtP;
    currentTick = poolData.currentTick;
    nearestCurrentTick = poolData.nearestCurrentTick;
    locked = poolData.locked;
  }

  /// @inheritdoc IPoolStorage
  function getLiquidityState()
    external
    view
    override
    returns (
      uint128 baseL,
      uint128 reinvestL,
      uint128 reinvestLLast
    )
  {
    baseL = poolData.baseL;
    reinvestL = poolData.reinvestL;
    reinvestLLast = poolData.reinvestLLast;
  }

  function getFeeGrowthGlobal() external view override returns (uint256) {
    return poolData.feeGrowthGlobal;
  }

  function getSecondsPerLiquidityData()
    external
    view
    override
    returns (uint128 secondsPerLiquidityGlobal, uint32 lastUpdateTime)
  {
    secondsPerLiquidityGlobal = poolData.secondsPerLiquidityGlobal;
    lastUpdateTime = poolData.secondsPerLiquidityUpdateTime;
  }

  function getSecondsPerLiquidityInside(int24 tickLower, int24 tickUpper)
    external
    view
    override
    returns (uint128 secondsPerLiquidityInside)
  {
    require(tickLower <= tickUpper, 'bad tick range');
    int24 currentTick = poolData.currentTick;
    uint128 secondsPerLiquidityGlobal = poolData.secondsPerLiquidityGlobal;
    uint32 lastUpdateTime = poolData.secondsPerLiquidityUpdateTime;

    uint128 lowerValue = ticks[tickLower].secondsPerLiquidityOutside;
    uint128 upperValue = ticks[tickUpper].secondsPerLiquidityOutside;

    unchecked {
      if (currentTick < tickLower) {
        secondsPerLiquidityInside = lowerValue - upperValue;
      } else if (currentTick >= tickUpper) {
        secondsPerLiquidityInside = upperValue - lowerValue;
      } else {
        secondsPerLiquidityInside = secondsPerLiquidityGlobal - (lowerValue + upperValue);
      }
    }

    // in the case where position is in range (tickLower <= _poolTick < tickUpper),
    // need to add timeElapsed per liquidity
    if (tickLower <= currentTick && currentTick < tickUpper) {
      uint256 secondsElapsed = _blockTimestamp() - lastUpdateTime;
      uint128 baseL = poolData.baseL;
      if (secondsElapsed > 0 && baseL > 0) {
        unchecked {
          secondsPerLiquidityInside += uint128((secondsElapsed << 96) / baseL);
        }
      }
    }
  }

  function _positionKey(
    address owner,
    int24 tickLower,
    int24 tickUpper
  ) internal pure returns (bytes32) {
    return keccak256(abi.encodePacked(owner, tickLower, tickUpper));
  }

  /// @dev For overriding in tests
  function _blockTimestamp() internal view virtual returns (uint32) {
    return uint32(block.timestamp);
  }
}

File 28 of 28 : Clones.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 *
 * _Available since v3.4._
 */
library Clones {
    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
            mstore(add(ptr, 0x14), shl(0x60, implementation))
            mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
            instance := create(0, ptr, 0x37)
        }
        require(instance != address(0), "ERC1167: create failed");
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
            mstore(add(ptr, 0x14), shl(0x60, implementation))
            mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
            instance := create2(0, ptr, 0x37, salt)
        }
        require(instance != address(0), "ERC1167: create2 failed");
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
            mstore(add(ptr, 0x14), shl(0x60, implementation))
            mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
            mstore(add(ptr, 0x38), shl(0x60, deployer))
            mstore(add(ptr, 0x4c), salt)
            mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
            predicted := keccak256(add(ptr, 0x37), 0x55)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(address implementation, bytes32 salt)
        internal
        view
        returns (address predicted)
    {
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 2000
  },
  "metadata": {
    "bytecodeHash": "none"
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"int24","name":"tickLower","type":"int24"},{"indexed":true,"internalType":"int24","name":"tickUpper","type":"int24"},{"indexed":false,"internalType":"uint128","name":"qty","type":"uint128"},{"indexed":false,"internalType":"uint256","name":"qty0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"qty1","type":"uint256"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"qty","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"qty0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"qty1","type":"uint256"}],"name":"BurnRTokens","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":"qty0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"qty1","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":"uint160","name":"sqrtP","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":"qty","type":"uint128"},{"indexed":false,"internalType":"uint256","name":"qty0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"qty1","type":"uint256"}],"name":"Mint","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":"deltaQty0","type":"int256"},{"indexed":false,"internalType":"int256","name":"deltaQty1","type":"int256"},{"indexed":false,"internalType":"uint160","name":"sqrtP","type":"uint160"},{"indexed":false,"internalType":"uint128","name":"liquidity","type":"uint128"},{"indexed":false,"internalType":"int24","name":"currentTick","type":"int24"}],"name":"Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint128","name":"qty","type":"uint128"}],"name":"burn","outputs":[{"internalType":"uint256","name":"qty0","type":"uint256"},{"internalType":"uint256","name":"qty1","type":"uint256"},{"internalType":"uint256","name":"feeGrowthInsideLast","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_qty","type":"uint256"},{"internalType":"bool","name":"isLogicalBurn","type":"bool"}],"name":"burnRTokens","outputs":[{"internalType":"uint256","name":"qty0","type":"uint256"},{"internalType":"uint256","name":"qty1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"contract IFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"qty0","type":"uint256"},{"internalType":"uint256","name":"qty1","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"flash","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getFeeGrowthGlobal","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLiquidityState","outputs":[{"internalType":"uint128","name":"baseL","type":"uint128"},{"internalType":"uint128","name":"reinvestL","type":"uint128"},{"internalType":"uint128","name":"reinvestLLast","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPoolState","outputs":[{"internalType":"uint160","name":"sqrtP","type":"uint160"},{"internalType":"int24","name":"currentTick","type":"int24"},{"internalType":"int24","name":"nearestCurrentTick","type":"int24"},{"internalType":"bool","name":"locked","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"}],"name":"getPositions","outputs":[{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"feeGrowthInsideLast","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getSecondsPerLiquidityData","outputs":[{"internalType":"uint128","name":"secondsPerLiquidityGlobal","type":"uint128"},{"internalType":"uint32","name":"lastUpdateTime","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"}],"name":"getSecondsPerLiquidityInside","outputs":[{"internalType":"uint128","name":"secondsPerLiquidityInside","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"int24","name":"","type":"int24"}],"name":"initializedTicks","outputs":[{"internalType":"int24","name":"previous","type":"int24"},{"internalType":"int24","name":"next","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxTickLiquidity","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"int24[2]","name":"ticksPrevious","type":"int24[2]"},{"internalType":"uint128","name":"qty","type":"uint128"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"mint","outputs":[{"internalType":"uint256","name":"qty0","type":"uint256"},{"internalType":"uint256","name":"qty1","type":"uint256"},{"internalType":"uint256","name":"feeGrowthInsideLast","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"int256","name":"swapQty","type":"int256"},{"internalType":"bool","name":"isToken0","type":"bool"},{"internalType":"uint160","name":"limitSqrtP","type":"uint160"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"swap","outputs":[{"internalType":"int256","name":"deltaQty0","type":"int256"},{"internalType":"int256","name":"deltaQty1","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"swapFeeUnits","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tickDistance","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int24","name":"","type":"int24"}],"name":"ticks","outputs":[{"internalType":"uint128","name":"liquidityGross","type":"uint128"},{"internalType":"int128","name":"liquidityNet","type":"int128"},{"internalType":"uint256","name":"feeGrowthOutside","type":"uint256"},{"internalType":"uint128","name":"secondsPerLiquidityOutside","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"token0","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"token1","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint160","name":"initialSqrtP","type":"uint160"}],"name":"unlockPool","outputs":[{"internalType":"uint256","name":"qty0","type":"uint256"},{"internalType":"uint256","name":"qty1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106101e55760003560e01c806395d89b411161010f578063c20830d7116100a2578063d21220a711610071578063d21220a71461059b578063dd62ed3e146105c2578063f2843d1e146105fb578063f30dba931461069957600080fd5b8063c20830d7146104ff578063c45a015514610512578063c5611c6014610539578063c79a590e1461056057600080fd5b8063ab612f2b116100de578063ab612f2b14610429578063aff67f551461045f578063b231a3b81461048b578063c0ac75cf146104b657600080fd5b806395d89b41146103e8578063a34123a7146103f0578063a457c2d714610403578063a9059cbb1461041657600080fd5b806324b31a0c11610187578063490e6cbc11610156578063490e6cbc1461038f57806370a08231146103a457806372cc5148146103cd5780637caae870146103d557600080fd5b806324b31a0c1461030b578063313ce56714610333578063395093511461034257806348626a8c1461035557600080fd5b80630dfe1681116101c35780630dfe16811461025957806318160ddd14610298578063217ac237146102aa57806323b872dd146102f857600080fd5b806306fdde03146101ea578063095ea7b3146102085780630c1225b71461022b575b600080fd5b6101f2610711565b6040516101ff91906151ae565b60405180910390f35b61021b6102163660046151f9565b6107a3565b60405190151581526020016101ff565b61023e610239366004615297565b6107ba565b604080519384526020840192909252908201526060016101ff565b6102807f0000000000000000000000001bfd67037b42cf73acf2047067bd4f2c47d9bfd681565b6040516001600160a01b0390911681526020016101ff565b600a545b6040519081526020016101ff565b600354604080516001600160a01b0383168152600160b81b8304600290810b6020830152600160a01b8404900b91810191909152600160d01b90910460ff16151560608201526080016101ff565b61021b610306366004615337565b610c10565b61031e610319366004615386565b610cd1565b604080519283526020830191909152016101ff565b604051601281526020016101ff565b61021b6103503660046151f9565b61174a565b61037c7f000000000000000000000000000000000000000000000000000000000000000881565b60405160029190910b81526020016101ff565b6103a261039d36600461540b565b611786565b005b61029c6103b2366004615475565b6001600160a01b031660009081526008602052604090205490565b60065461029c565b61031e6103e3366004615475565b611bd7565b6101f2611d60565b61023e6103fe366004615492565b611d6f565b61021b6104113660046151f9565b611f84565b61021b6104243660046151f9565b612035565b600454600554604080516001600160801b038085168252600160801b9094048416602082015292909116908201526060016101ff565b600754604080516001600160801b0383168152600160801b90920463ffffffff166020830152016101ff565b61049e6104993660046154d5565b612042565b6040516001600160801b0390911681526020016101ff565b6104e56104c4366004615508565b600160205260009081526040902054600281810b9163010000009004900b82565b60408051600293840b81529190920b6020820152016101ff565b61031e61050d366004615523565b6121ad565b6102807f0000000000000000000000005f1dddbf348ac2fbe22a163e30f99f9ece3dd50a81565b61049e7f0000000000000000000000000000000000004ba292c741ef0687a72007e73cd681565b6105877f000000000000000000000000000000000000000000000000000000000000002881565b60405162ffffff90911681526020016101ff565b6102807f0000000000000000000000007ceb23fd6bc0add59e62ac25578270cff1b9f61981565b61029c6105d0366004615553565b6001600160a01b03918216600090815260096020908152604080832093909416825291909152205490565b61067a610609366004615581565b6040805160609490941b6bffffffffffffffffffffffff191660208086019190915260e893841b60348601529190921b60378401528151601a818503018152603a909301825282519281019290922060009081526002909252902080546001909101546001600160801b0390911691565b604080516001600160801b0390931683526020830191909152016101ff565b6106df6106a7366004615508565b6000602081905290815260409020805460018201546002909201546001600160801b0380831693600160801b909304600f0b92911684565b604080516001600160801b039586168152600f9490940b602085015283019190915290911660608201526080016101ff565b6060600b8054610720906155bd565b80601f016020809104026020016040519081016040528092919081815260200182805461074c906155bd565b80156107995780601f1061076e57610100808354040283529160200191610799565b820191906000526020600020905b81548152906001019060200180831161077c57829003601f168201915b5050505050905090565b60006107b0338484612426565b5060015b92915050565b60035460009081908190600160d01b900460ff16156108095760405162461bcd60e51b81526020600482015260066024820152651b1bd8dad95960d21b60448201526064015b60405180910390fd5b6003805460ff60d01b1916600160d01b1790556001600160801b0386166108725760405162461bcd60e51b815260206004820152600560248201527f30207174790000000000000000000000000000000000000000000000000000006044820152606401610800565b6040517f4020f01c0000000000000000000000000000000000000000000000000000000081523360048201527f0000000000000000000000005f1dddbf348ac2fbe22a163e30f99f9ece3dd50a6001600160a01b031690634020f01c9060240160206040518083038186803b1580156108ea57600080fd5b505afa1580156108fe573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061092291906155f2565b61096e5760405162461bcd60e51b815260206004820152600960248201527f666f7262696464656e00000000000000000000000000000000000000000000006044820152606401610800565b600080610a026040518060e001604052808e6001600160a01b031681526020018d60020b81526020018c60020b81526020018b6000600281106109b3576109b361560f565b6020020160208101906109c69190615508565b60020b81526020908101906109e19060408e01908e01615508565b60020b81526001600160801b038b166020820152600160409091015261257e565b919650945092508491508390506000808315610a2357610a2061291c565b91505b8515610a3457610a31612a60565b90505b6040517f9f382e9b0000000000000000000000000000000000000000000000000000000081523390639f382e9b90610a76908a908a908e908e90600401615650565b600060405180830381600087803b158015610a9057600080fd5b505af1158015610aa4573d6000803e3d6000fd5b505050506000871115610b1157610ab961291c565b610ac38884615686565b1115610b115760405162461bcd60e51b815260206004820152600c60248201527f6c61636b696e67207174793000000000000000000000000000000000000000006044820152606401610800565b8515610b7757610b1f612a60565b610b298783615686565b1115610b775760405162461bcd60e51b815260206004820152600c60248201527f6c61636b696e67207174793100000000000000000000000000000000000000006044820152606401610800565b8b60020b8d60020b8f6001600160a01b03167f7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde338e8c8c604051610be894939291906001600160a01b039490941684526001600160801b039290921660208401526040830152606082015260800190565b60405180910390a450506003805460ff60d01b1916905550929a919950975095505050505050565b6000610c1d848484612ac5565b6001600160a01b038416600090815260096020908152604080832033845290915290205482811015610cb75760405162461bcd60e51b815260206004820152602860248201527f45524332303a207472616e7366657220616d6f756e742065786365656473206160448201527f6c6c6f77616e63650000000000000000000000000000000000000000000000006064820152608401610800565b610cc48533858403612426565b60019150505b9392505050565b6003546000908190600160d01b900460ff1615610d195760405162461bcd60e51b81526020600482015260066024820152651b1bd8dad95960d21b6044820152606401610800565b6003805460ff60d01b1916600160d01b17905586610d795760405162461bcd60e51b815260206004820152600960248201527f30207377617051747900000000000000000000000000000000000000000000006044820152606401610800565b6040805161014081018252600060208201819052918101829052606081018290526080810182905260a081018290526101008101829052610120810182905288815287151560c0820181905291891360e0820181905290911415610ddc81612cde565b600290810b60808801520b60608601526001600160a01b031660408501526001600160801b03908116610120850152166101008301528015610eaa5781604001516001600160a01b0316876001600160a01b0316118015610e59575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038816105b610ea55760405162461bcd60e51b815260206004820152600e60248201527f626164206c696d697453717274500000000000000000000000000000000000006044820152606401610800565b610f28565b81604001516001600160a01b0316876001600160a01b0316108015610edc57506401000276a36001600160a01b038816115b610f285760405162461bcd60e51b815260206004820152600e60248201527f626164206c696d697453717274500000000000000000000000000000000000006044820152606401610800565b6040805161010081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e08101919091525b825115801590610f905750876001600160a01b031683604001516001600160a01b031614155b15611398576080830151828015610fbc57506060840151610fb3906101e061569e565b60020b8160020b135b15610fda576101e08460600151610fd3919061569e565b9050611018565b82158015610ffe57506101e08460600151610ff591906156e5565b60020b8160020b125b15611018576101e0846060015161101591906156e5565b90505b61102181612d47565b6001600160a01b0390811660a08601819052908a16811184151514156110445750885b60008060006110ab886101200151896101000151611062919061572d565b6001600160801b03168960400151867f000000000000000000000000000000000000000000000000000000000000002862ffffff168c600001518d60e001518e60c00151613096565b6001600160a01b031660408c01528a519295509093509150839089906110d2908390615758565b9052506020880180518391906110e99083906157b0565b9052506110f58161319e565b8861012001818151611107919061572d565b6001600160801b031690525050505060a085015160408601516001600160a01b03918216911614905061114f5761114184604001516131b9565b60020b606085015250611398565b826111645761115f6001826156e5565b611166565b805b600290810b6060860152608085015182820b910b146111855750610f6a565b815161129657600a5482526005546001600160801b03908116602084015260065460408401526007546101008601516111c2929190911690613528565b6001600160801b03166060830152604080517f98c47e8c00000000000000000000000000000000000000000000000000000000815281516001600160a01b037f0000000000000000000000005f1dddbf348ac2fbe22a163e30f99f9ece3dd50a16926398c47e8c9260048082019391829003018186803b15801561124557600080fd5b505afa158015611259573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061127d9190615808565b62ffffff1660a08401526001600160a01b031660808301525b60006112c88561012001516001600160801b031684602001516001600160801b031687610100015186600001516135db565b905080156113435780836000018181516112e29190615686565b90525060a083015160c084018051620186a062ffffff909316840292909204918201905260e084018051828403908101909152610100870151611335908290600160601b906001600160801b031661361f565b604086018051909101905250505b6101208501516001600160801b031660208401526080850151610100860151604085015160608601516113799392919088613763565b60020b60808701526001600160801b031661010086015250610f6a9050565b8051156114095760c0810151156113bb576113bb81608001518260c00151613849565b60e0810151156113d3576113d3308260e00151613849565b6020810151600580546fffffffffffffffffffffffffffffffff19166001600160801b0390921691909117905560408101516006555b61142c836101000151846101200151856040015186606001518760800151613928565b886114475760208301518351611442908c615758565b611459565b8251611453908b615758565b83602001515b9095509350811561158e5760008512156114a5576114a57f0000000000000000000000001bfd67037b42cf73acf2047067bd4f2c47d9bfd66001600160a01b03168c60018819016139d7565b60006114af612a60565b6040517ffa483e72000000000000000000000000000000000000000000000000000000008152909150339063fa483e72906114f490899089908d908d90600401615650565b600060405180830381600087803b15801561150e57600080fd5b505af1158015611522573d6000803e3d6000fd5b5050505084816115329190615686565b61153a612a60565b10156115885760405162461bcd60e51b815260206004820152601160248201527f6c61636b696e672064656c7461517479310000000000000000000000000000006044820152606401610800565b506116b4565b60008412156115cf576115cf7f0000000000000000000000007ceb23fd6bc0add59e62ac25578270cff1b9f6196001600160a01b03168c60018719016139d7565b60006115d961291c565b6040517ffa483e72000000000000000000000000000000000000000000000000000000008152909150339063fa483e729061161e90899089908d908d90600401615650565b600060405180830381600087803b15801561163857600080fd5b505af115801561164c573d6000803e3d6000fd5b50505050858161165c9190615686565b61166461291c565b10156116b25760405162461bcd60e51b815260206004820152601160248201527f6c61636b696e672064656c7461517479300000000000000000000000000000006044820152606401610800565b505b60408084015161010085015160608087015184518a8152602081018a90526001600160a01b03948516958101959095526001600160801b039092169084015260020b60808301528c169033907fc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca679060a00160405180910390a350506003805460ff60d01b19169055509097909650945050505050565b3360008181526009602090815260408083206001600160a01b038716845290915281205490916107b0918590611781908690615686565b612426565b600354600160d01b900460ff16156117c95760405162461bcd60e51b81526020600482015260066024820152651b1bd8dad95960d21b6044820152606401610800565b6003805460ff60d01b1916600160d01b179055604080517f98c47e8c00000000000000000000000000000000000000000000000000000000815281516000926001600160a01b037f0000000000000000000000005f1dddbf348ac2fbe22a163e30f99f9ece3dd50a16926398c47e8c9260048083019392829003018186803b15801561185457600080fd5b505afa158015611868573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061188c9190615808565b5090506000806001600160a01b0383161561192057620186a06118d47f000000000000000000000000000000000000000000000000000000000000002862ffffff1689615855565b6118de9190615874565b9150620186a06119137f000000000000000000000000000000000000000000000000000000000000002862ffffff1688615855565b61191d9190615874565b90505b600061192a61291c565b90506000611936612a60565b90508815611972576119726001600160a01b037f0000000000000000000000001bfd67037b42cf73acf2047067bd4f2c47d9bfd6168b8b6139d7565b87156119ac576119ac6001600160a01b037f0000000000000000000000007ceb23fd6bc0add59e62ac25578270cff1b9f619168b8a6139d7565b6040517fc3924ed6000000000000000000000000000000000000000000000000000000008152339063c3924ed6906119ee90879087908c908c90600401615650565b600060405180830381600087803b158015611a0857600080fd5b505af1158015611a1c573d6000803e3d6000fd5b505050506000611a2a61291c565b90506000611a36612a60565b905081611a438786615686565b1115611a915760405162461bcd60e51b815260206004820152600f60248201527f6c61636b696e67206665655174793000000000000000000000000000000000006044820152606401610800565b80611a9c8685615686565b1115611aea5760405162461bcd60e51b815260206004820152600f60248201527f6c61636b696e67206665655174793100000000000000000000000000000000006044820152606401610800565b838203838203838614611b2b57611b2b6001600160a01b037f0000000000000000000000001bfd67037b42cf73acf2047067bd4f2c47d9bfd6168a846139d7565b8015611b6557611b656001600160a01b037f0000000000000000000000007ceb23fd6bc0add59e62ac25578270cff1b9f619168a836139d7565b604080518e8152602081018e9052908101839052606081018290526001600160a01b038f169033907fbdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca6339060800160405180910390a350506003805460ff60d01b19169055505050505050505050505050565b60035460009081906001600160a01b031615611c355760405162461bcd60e51b815260206004820152600e60248201527f616c726561647920696e697465640000000000000000000000000000000000006044820152606401610800565b6000611c40846131b9565b9050611c4b84613a5c565b9093509150611c5861291c565b831115611ca75760405162461bcd60e51b815260206004820152600c60248201527f6c61636b696e67207174793000000000000000000000000000000000000000006044820152606401610800565b611caf612a60565b821115611cfe5760405162461bcd60e51b815260206004820152600c60248201527f6c61636b696e67207174793100000000000000000000000000000000000000006044820152606401610800565b611d0b30620186a0613849565b611d158482613a9e565b604080516001600160a01b0386168152600283900b60208201527f98636036cb66a9c19a37435efc1e90142190214e8abeb821bdba3f2990dd4c95910160405180910390a150915091565b6060600c8054610720906155bd565b60035460009081908190600160d01b900460ff1615611db95760405162461bcd60e51b81526020600482015260066024820152651b1bd8dad95960d21b6044820152606401610800565b6003805460ff60d01b1916600160d01b1790556001600160801b038416611e225760405162461bcd60e51b815260206004820152600560248201527f30207174790000000000000000000000000000000000000000000000000000006044820152606401610800565b600080611e836040518060e00160405280336001600160a01b031681526020018a60020b81526020018960020b8152602001600060020b8152602001600060020b8152602001886001600160801b031681526020016000151581525061257e565b945090925090506000821215611ece5781196001019450611ece6001600160a01b037f0000000000000000000000001bfd67037b42cf73acf2047067bd4f2c47d9bfd61633876139d7565b6000811215611f125780196001019350611f126001600160a01b037f0000000000000000000000007ceb23fd6bc0add59e62ac25578270cff1b9f6191633866139d7565b604080516001600160801b038816815260208101879052908101859052600288810b91908a900b9033907f0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c9060600160405180910390a450506003805460ff60d01b1916905591959094509092509050565b3360009081526009602090815260408083206001600160a01b03861684529091528120548281101561201e5760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f7760448201527f207a65726f0000000000000000000000000000000000000000000000000000006064820152608401610800565b61202b3385858403612426565b5060019392505050565b60006107b0338484612ac5565b60008160020b8360020b131561209a5760405162461bcd60e51b815260206004820152600e60248201527f626164207469636b2072616e67650000000000000000000000000000000000006044820152606401610800565b600354600754600285810b60008181526020819052604080822084015488850b83529120830154600160b81b90950490920b936001600160801b0380851694600160801b900463ffffffff16938116929116908512156120fe57808203955061211d565b8660020b8560020b1261211557818103955061211d565b808201840395505b8460020b8860020b1315801561213857508660020b8560020b125b156121a25760006121498442615888565b60045463ffffffff9190911691506001600160801b0316811580159061217857506000816001600160801b0316115b1561219f57806001600160801b0316606083901b816121995761219961583f565b04880197505b50505b505050505092915050565b6003546000908190600160d01b900460ff16156121f55760405162461bcd60e51b81526020600482015260066024820152651b1bd8dad95960d21b6044820152606401610800565b6003805460ff60d01b1916600160d01b1790558215612266576122183385613bb1565b6040805185815260006020820181905281830152905133917f324487c99a1f7f0e3127499a548452d3a198e78ccd07add913cb93d59f0f039b919081900360600190a25060009050806123eb565b6004546003546006546001600160801b0380841693600160801b900416916001600160a01b03169061229d90849084906000613d36565b5060006122bc88846001600160801b03166122b7600a5490565b61361f565b90506122c78161319e565b6122d190846158ad565b600480546001600160801b03808416600160801b81029190921617909155600580546fffffffffffffffffffffffffffffffff1916909117905592506123178282613dd2565b95506123238282613dec565b945061232f3389613bb1565b8515612369576123696001600160a01b037f0000000000000000000000001bfd67037b42cf73acf2047067bd4f2c47d9bfd61633886139d7565b84156123a3576123a36001600160a01b037f0000000000000000000000007ceb23fd6bc0add59e62ac25578270cff1b9f6191633876139d7565b604080518981526020810188905290810186905233907f324487c99a1f7f0e3127499a548452d3a198e78ccd07add913cb93d59f0f039b9060600160405180910390a2505050505b6003805460ff60d01b1916905590939092509050565b600081612411620d89e7196158cd565b61241b91906158f0565b6107b490600261592a565b6001600160a01b0383166124a15760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f2061646460448201527f72657373000000000000000000000000000000000000000000000000000000006064820152608401610800565b6001600160a01b03821661251d5760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f20616464726560448201527f73730000000000000000000000000000000000000000000000000000000000006064820152608401610800565b6001600160a01b0383811660008181526009602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6000806000836040015160020b846020015160020b126125e05760405162461bcd60e51b815260206004820152601260248201527f696e76616c6964207469636b2072616e676500000000000000000000000000006044820152606401610800565b602084015160020b620d89e719131561263b5760405162461bcd60e51b815260206004820152601260248201527f696e76616c6964206c6f776572207469636b00000000000000000000000000006044820152606401610800565b612648620d89e7196158cd565b60020b846040015160020b13156126a15760405162461bcd60e51b815260206004820152601260248201527f696e76616c6964207570706572207469636b00000000000000000000000000006044820152606401610800565b7f000000000000000000000000000000000000000000000000000000000000000884602001516126d19190615955565b60020b15801561271157507f0000000000000000000000000000000000000000000000000000000000000008846040015161270c9190615955565b60020b155b61275d5760405162461bcd60e51b815260206004820152601460248201527f7469636b206e6f7420696e2064697374616e63650000000000000000000000006044820152606401610800565b60035460045460408051808201909152600080825260208201526001600160a01b03831692600160b81b900460020b916001600160801b0380821692600160801b90920416906127b4838360038001546001613d36565b81526007546127cc906001600160801b031684613528565b6001600160801b0316602082015260006127e78a8684613e06565b97509050801561280057612800308b6000015183612ac5565b896020015160020b8560020b121561284f5761283e6128228b60200151612d47565b61282f8c60400151612d47565b8c60a001518d60c00151613eaa565b600098509850505050505050612915565b896040015160020b8560020b1261289d57600061288e6128728c60200151612d47565b61287f8d60400151612d47565b8d60a001518e60c00151613f4e565b98509850505050505050612915565b6128ae8661282f8c60400151612d47565b98506128d06128c08b60200151612d47565b878c60a001518d60c00151613f4e565b97506128e5848b60a001518c60c00151613faf565b600480546fffffffffffffffffffffffffffffffff19166001600160801b03929092169190911790555050505050505b9193909250565b604051306024820152600090819081906001600160a01b037f0000000000000000000000001bfd67037b42cf73acf2047067bd4f2c47d9bfd616907f70a0823100000000000000000000000000000000000000000000000000000000906044015b60408051601f198184030181529181526020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fffffffff000000000000000000000000000000000000000000000000000000009094169390931790925290516129e89190615977565b600060405180830381855afa9150503d8060008114612a23576040519150601f19603f3d011682016040523d82523d6000602084013e612a28565b606091505b5091509150818015612a3c57506020815110155b612a4557600080fd5b80806020019051810190612a599190615993565b9250505090565b604051306024820152600090819081906001600160a01b037f0000000000000000000000007ceb23fd6bc0add59e62ac25578270cff1b9f61916907f70a08231000000000000000000000000000000000000000000000000000000009060440161297d565b6001600160a01b038316612b415760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f20616460448201527f64726573730000000000000000000000000000000000000000000000000000006064820152608401610800565b6001600160a01b038216612bbd5760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201527f65737300000000000000000000000000000000000000000000000000000000006064820152608401610800565b6001600160a01b03831660009081526008602052604090205481811015612c4c5760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e742065786365656473206260448201527f616c616e636500000000000000000000000000000000000000000000000000006064820152608401610800565b6001600160a01b03808516600090815260086020526040808220858503905591851681529081208054849290612c83908490615686565b92505081905550826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef84604051612ccf91815260200190565b60405180910390a35b50505050565b6004546003546001600160801b0380831692600160801b900416906001600160a01b03811690600160b81b8104600290810b91600160a01b9004900b8515612d3e57600290810b60009081526001602052604090205463010000009004900b5b91939590929450565b60008060008360020b12612d5e578260020b612d66565b8260020b6000035b9050620d89e8811115612dbb5760405162461bcd60e51b815260206004820152600160248201527f54000000000000000000000000000000000000000000000000000000000000006044820152606401610800565b600060018216612dcf57600160801b612de1565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615612e15576ffff97272373d413259a46990580e213a0260801c5b6004821615612e34576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615612e53576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615612e72576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615612e91576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615612eb0576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615612ecf576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615612eef576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615612f0f576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615612f2f576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615612f4f576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615612f6f576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615612f8f576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615612faf576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615612fcf576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615612ff0576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615613010576e5d6af8dedb81196699c329225ee6040260801c5b6204000082161561302f576d2216e584f5fa1ea926041bedfe980260801c5b6208000082161561304c576b048a170391f7dc42444e8fa20260801c5b60008460020b131561306d5780600019816130695761306961583f565b0490505b640100000000810615613081576001613084565b60005b60ff16602082901c0192505050919050565b600080600080886001600160a01b03168a6001600160a01b031614156130c757506000925082915081905088613190565b6130e78b8b6001600160a01b03168b6001600160a01b03168b8a8a613fd7565b93508580156130f65750868412155b8061310a57508515801561310a5750868413155b156131175786935061311a565b50875b60008085121561312e578419600101613130565b845b90506001600160a01b03821661316d5761314e818d8d8c8b8b614172565b9250613166613161828e868f8c8c6142bc565b6143b5565b915061317e565b61317b818d8d858b8b6143cb565b92505b61318c8c8c84868b8b6144c1565b9350505b975097509750979350505050565b806001600160801b03811681146131b457600080fd5b919050565b60006401000276a36001600160a01b038316108015906131f5575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038316105b6132415760405162461bcd60e51b815260206004820152600160248201527f52000000000000000000000000000000000000000000000000000000000000006044820152606401610800565b77ffffffffffffffffffffffffffffffffffffffff00000000602083901b166001600160801b03811160071b81811c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211600190811b92831c979088119617909417909217179091171717608081106132e257607f810383901c91506132ec565b80607f0383901b91505b908002607f81811c60ff83811c9190911c800280831c81831c1c800280841c81841c1c800280851c81851c1c800280861c81861c1c800280871c81871c1c800280881c81881c1c800280891c81891c1c8002808a1c818a1c1c8002808b1c818b1c1c8002808c1c818c1c1c8002808d1c818d1c1c8002808e1c9c81901c9c909c1c80029c8d901c9e9d7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff808f0160401b60c09190911c678000000000000000161760c19b909b1c674000000000000000169a909a1760c29990991c672000000000000000169890981760c39790971c671000000000000000169690961760c49590951c670800000000000000169490941760c59390931c670400000000000000169290921760c69190911c670200000000000000161760c79190911c670100000000000000161760c89190911c6680000000000000161760c99190911c6640000000000000161760ca9190911c6620000000000000161760cb9190911c6610000000000000161760cc9190911c6608000000000000161760cd9190911c66040000000000001617693627a301d71055774c8581027ffffffffffffffffffffffffffffffffffd709b7e5480fba5a50fed5e62ffc5568101608090811d906fdb2df09e81959a81455e260799a0632f8301901d600281810b9083900b1461351957886001600160a01b03166134fe82612d47565b6001600160a01b03161115613513578161351b565b8061351b565b815b9998505050505050505050565b6007546000908190600160801b900463ffffffff16426135489190615888565b63ffffffff16905060008111801561356957506000836001600160801b0316115b156135d3576135856001600160801b038416606083901b615874565b61358f908561572d565b600780547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160801b03831617600160801b63ffffffff42160217905593505b509192915050565b6000806136086001600160801b0385166135f587896159ac565b6122b7896001600160801b038916615686565b905061361583828761361f565b9695505050505050565b60008080600019858709858702925082811083820303915050806000141561369c57600084116136915760405162461bcd60e51b815260206004820152600760248201527f302064656e6f6d000000000000000000000000000000000000000000000000006044820152606401610800565b508290049050610cca565b8084116136eb5760405162461bcd60e51b815260206004820152600e60248201527f64656e6f6d203c3d2070726f64310000000000000000000000000000000000006044820152606401610800565b600084868809808403938111909203919050600061370b86196001615686565b8616958690049560026003880281188089028203028089028203028089028203028089028203028089028203028089029091030260008290038290046001019490940294049390931791909102925050509392505050565b600285810b60009081526020819052604081206001810180548703905591820180546001600160801b038082168703166fffffffffffffffffffffffffffffffff1990911617905590548190600160801b9004600f0b83156137e357600288810b60009081526001602052604090205463010000009004900b9150613807565b600288810b600090815260016020526040902054900b9150613804816159c3565b90505b61383c87600083600f0b121561382d57600f83900b6001600160801b030360010161382f565b825b600084600f0b1215613faf565b9250509550959350505050565b6001600160a01b03821661389f5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610800565b80600a60008282546138b19190615686565b90915550506001600160a01b038216600090815260086020526040812080548392906138de908490615686565b90915550506040518181526001600160a01b038316906000907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9060200160405180910390a35050565b6001600160801b03848116600160801b02908616176004556003805462ffffff8416600160b81b027fffffffffffff000000ffffff00000000000000000000000000000000000000009091166001600160a01b03861617179055600282810b9082900b1361399657806139ad565b600281810b600090815260016020526040902054900b5b6003805462ffffff92909216600160a01b0262ffffff60a01b199092169190911790555050505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fa9059cbb00000000000000000000000000000000000000000000000000000000179052613a579084906145ae565b505050565b600080613a7a620186a0600160601b6001600160a01b038616614693565b9150613a97620186a06001600160a01b038516600160601b614693565b9050915091565b720186a00000000000000000000000000000000060045560058054620186a06fffffffffffffffffffffffffffffffff19909116179055600380546001600160a01b0384167fffffffffffff000000ffffff000000000000000000000000000000000000000090911617600160b81b62ffffff8416021762ffffff60a01b191676f276180000000000000000000000000000000000000000179055613ba0620d89e719613b4a816158cd565b600282810b600090815260016020526040808220805462ffffff96871662ffffff199787166301000000029790971665ffffffffffff19918216811788179092559490930b825290208054909216179091179055565b50506003805460ff60d01b19169055565b6001600160a01b038216613c2d5760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f2061646472657360448201527f73000000000000000000000000000000000000000000000000000000000000006064820152608401610800565b6001600160a01b03821660009081526008602052604090205481811015613cbc5760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e60448201527f63650000000000000000000000000000000000000000000000000000000000006064820152608401610800565b6001600160a01b03831660009081526008602052604081208383039055600a8054849290613ceb9084906159ac565b90915550506040518281526000906001600160a01b038516907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9060200160405180910390a3505050565b6005546000908190613d5e906001600160801b03808816911688613d59600a5490565b6135db565b90508015613d9d57613d6f816146c5565b9050613d7b3082613849565b613d9381600160601b886001600160801b031661361f565b9093016006819055925b8215613dc857600580546fffffffffffffffffffffffffffffffff19166001600160801b0387161790555b5091949350505050565b6000610cca82600160601b856001600160a01b031661361f565b6000610cca82846001600160a01b0316600160601b61361f565b6000806000613e2b86602001518688606001518960a001518a60c0015189600161479b565b90506000613e4f87604001518789608001518a60a001518b60c001518a600061479b565b9050866020015160020b8660020b1215613e6d578082039250613e94565b866040015160020b8660020b12613e88578181039250613e94565b80828660000151030392505b613e9e87846149ff565b93505050935093915050565b60007bffffffffffffffffffffffffffffffff000000000000000000000000606084901b166001600160a01b038686031683613f1557613f10876001600160a01b0316613f0184848a6001600160a01b031661361f565b613f0b9190615874565b614ae0565b613f43565b613f43613f3e613f2f84848a6001600160a01b0316614693565b896001600160a01b0316614afb565b614b15565b979650505050505050565b600081613f8057613f7b613f0b846001600160801b03168787036001600160a01b0316600160601b61361f565b613fa6565b613fa6613f3e846001600160801b03168787036001600160a01b0316600160601b614693565b95945050505050565b600081613fc557613fc083856158ad565b613fcf565b613fcf838561572d565b949350505050565b60008085871015613fea57868603613fee565b8587035b905083156140a35782156140575760006140088887615855565b6140158862030d40615855565b61401f91906159ac565b9050600061403a8a6140348562030d40615855565b8461361f565b905061404e613f3e82600160601b8c61361f565b93505050614167565b60006140638787615855565b6140708962030d40615855565b61407a91906159ac565b9050600061408f8a6140348562030d40615855565b905061404e613f3e828b600160601b61361f565b82156141065760006140b58787615855565b6140c28962030d40615855565b6140cc91906159ac565b905060006140da8988615855565b6140e490836159ac565b90506140f560608b901b828461361f565b905061404e88613f0183868d61361f565b60006141128887615855565b61411f8862030d40615855565b61412991906159ac565b905060006141378888615855565b61414190836159ac565b905061414e8a828461361f565b9050614162613f0b8285600160601b61361f565b935050505b509695505050505050565b600082156141db5781156141b3576141ac6001600160a01b038616614197868a615855565b6e030d4000000000000000000000000061361f565b9050613615565b6141ac600160601b6141c5868a615855565b6122b76001600160a01b03891662030d40615855565b836000876141ec83620186a06159ac565b6141f69190615855565b90506000896142058a89615855565b61420f9190615855565b905084156142665761423b6142278b620186a0615855565b896001600160a01b0316600160601b61361f565b61424590836159ac565b915061425f81896001600160a01b0316600160601b61361f565b90506142b1565b61428a6142768b620186a0615855565b600160601b8a6001600160a01b031661361f565b61429490836159ac565b91506142ae81600160601b8a6001600160a01b031661361f565b90505b614162838383614b2b565b600081156143355760006142de88866001600160a01b0316600160601b61361f565b905083156143145761430c6142f38789615686565b6001600160a01b038716614307848b615686565b614693565b915050613615565b61430c6143218789615686565b6001600160a01b0387166122b7848b6159ac565b821561437857600061435588600160601b876001600160a01b031661361f565b905061430c6143648289615686565b6001600160a01b0387166122b7898b615686565b600061439288600160601b876001600160a01b031661361f565b905061430c6143a182896159ac565b6001600160a01b038716614307898b615686565b806001600160a01b03811681146131b457600080fd5b6000811561444f5760006143ed87600160601b886001600160a01b031661361f565b90506000846144055761440089836159ac565b61440f565b61440f8983615686565b9050600061442b876001600160a01b031683600160601b61361f565b905088811161443b576000614445565b61444589826159ac565b9350505050613615565b600061446987876001600160a01b0316600160601b61361f565b90506000846144815761447c89836159ac565b61448b565b61448b8983615686565b905060006144a782600160601b896001600160a01b031661361f565b90508881116144b7576000614162565b61416289826159ac565b6000811561454357821561451f576144f3613f0b886144e0888a6159ea565b6001600160a01b0316600160601b61361f565b61450e613f3e86886001600160a01b0316600160601b614693565b61451891906157b0565b905061458f565b6144f3613f3e8861453089896159ea565b6001600160a01b0316600160601b614693565b61455e613f0b88600160601b896001600160a01b031661361f565b614582613f3e61456e878b615686565b600160601b896001600160a01b0316614693565b61458c91906157b0565b90505b82801561459c5750806001145b15613615575060009695505050505050565b6000614603826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316614b689092919063ffffffff16565b805190915015613a57578080602001905181019061462191906155f2565b613a575760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e60448201527f6f742073756363656564000000000000000000000000000000000000000000006064820152608401610800565b60006146a084848461361f565b9050600082806146b2576146b261583f565b8486091115610cca5780613fa681615a0a565b60008060007f0000000000000000000000005f1dddbf348ac2fbe22a163e30f99f9ece3dd50a6001600160a01b03166398c47e8c6040518163ffffffff1660e01b8152600401604080518083038186803b15801561472257600080fd5b505afa158015614736573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061475a9190615808565b915091508062ffffff166000141561477457509192915050565b620186a062ffffff82168502048015614791576147918382613849565b9093039392505050565b600287900b6000908152602081905260408120546001600160801b0316816147c4828888613faf565b90507f0000000000000000000000000000000000004ba292c741ef0687a72007e73cd66001600160801b0316816001600160801b031611156148485760405162461bcd60e51b815260206004820152600f60248201527f3e206d6178206c697175696469747900000000000000000000000000000000006044820152606401610800565b60008661486f57614861886001600160801b0316614b77565b61486a906159c3565b614881565b614881886001600160801b0316614b77565b90506000856148b85760028c900b6000908152602081905260409020546148b3908390600160801b9004600f0b615a25565b6148e1565b60028c900b6000908152602081905260409020546148e1908390600160801b9004600f0b615a7d565b90506001600160801b038416614948578a60020b8c60020b1361494857865160028d810b6000908152602081815260409091206001810193909355890151910180546fffffffffffffffffffffffffffffffff19166001600160801b039092169190911790555b60028c900b60009081526020819052604090206001600160801b03828116600160801b02818616178255600190910154955084161580159061499157506001600160801b038316155b156149cd5760028c810b600090815260208190526040812081815560018101919091550180546fffffffffffffffffffffffffffffffff191690555b6001600160801b0384811615159084161515146149f0576149f08c8b8d8b614b9e565b50505050979650505050505050565b8151602080840151604080860151815160609590951b6bffffffffffffffffffffffff19168585015260e892831b603486015290911b60378401528051601a818503018152603a9093019052815191012060009081906000818152600260205260409020600181015490549192508403906001600160801b0316614a888282600160601b61361f565b9350614a9d818760a001518860c00151613faf565b60009384526002602052604090932080546fffffffffffffffffffffffffffffffff19166001600160801b03909416939093178355505060010191909155919050565b6000600160ff1b8210614af257600080fd5b6107b482615ad5565b6000808211614b0957600080fd5b50808204910615150190565b6000600160ff1b8210614b2757600080fd5b5090565b600083614b54614b3b8483615855565b614b458680615855565b614b4f91906159ac565b614d4e565b614b5e90856159ac565b613fcf9190615874565b6060613fcf8484600085614dab565b60006f80000000000000000000000000000000826001600160801b031610614b2757600080fd5b8015614cf157600284900b620d89e7191480614bcb5750614bc2620d89e7196158cd565b60020b8460020b145b15614bd557612cd8565b600283810b60009081526001602052604090205463010000008104820b910b811415614c435760405162461bcd60e51b815260206004820152601e60248201527f70726576696f7573207469636b20686173206265656e2072656d6f76656400006044820152606401610800565b60005b8560020b8260020b13158015614c5c5750600a81105b15614c9657600282810b600090815260016020526040902054929550630100000090920490910b9080614c8e81615a0a565b915050614c46565b614ca36001878785614edf565b600354600287810b600160a01b909204900b128015614cc857508360020b8660020b13155b15614cea576003805462ffffff60a01b1916600160a01b62ffffff8916021790555b5050612cd8565b600354600285810b600160a01b909204900b1415614d3c57614d1460018561501f565b6003805462ffffff92909216600160a01b0262ffffff60a01b19909216919091179055612cd8565b614d4760018561501f565b5050505050565b60006003821115614d9d575080600160028204015b81811015614d9757809150600281828581614d8057614d8061583f565b040181614d8f57614d8f61583f565b049050614d63565b50919050565b81156131b457506001919050565b606082471015614e235760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f60448201527f722063616c6c00000000000000000000000000000000000000000000000000006064820152608401610800565b843b614e715760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610800565b600080866001600160a01b03168587604051614e8d9190615977565b60006040518083038185875af1925050503d8060008114614eca576040519150601f19603f3d011682016040523d82523d6000602084013e614ecf565b606091505b5091509150613f43828286615149565b600282810b60009081526020869052604090205482820b910b1415614f465760405162461bcd60e51b815260206004820152601e60248201527f6c6f7765722076616c7565206973206e6f7420696e697469616c697a656400006044820152606401610800565b8260020b8260020b128015614f6057508260020b8160020b135b614fac5760405162461bcd60e51b815260206004820152601360248201527f696e76616c6964206c6f7765722076616c7565000000000000000000000000006044820152606401610800565b600283810b60009081526020959095526040808620805465ffffffffffff1916630100000062ffffff868116820262ffffff19908116939093178882161790935594840b885282882080549091169190961690811790955592900b84529220805465ffffff000000191691909202179055565b600281810b60009081526020848152604080832081518083019092525480850b808352630100000090910490940b918101829052919214156150a35760405162461bcd60e51b815260206004820152601960248201527f72656d6f7665206e6f6e2d6578697374656e742076616c7565000000000000006044820152606401610800565b8260020b816000015160020b14156150be57829150506107b4565b806000015191508260020b816020015160020b14156150dd57506107b4565b602081810180518351600290810b6000908152979093526040808820805465ffffff0000001916630100000062ffffff9485160217905593519151830b8752838720805462ffffff1916929091169190911790559290920b83529120805465ffffffffffff1916905590565b60608315615158575081610cca565b8251156151685782518084602001fd5b8160405162461bcd60e51b815260040161080091906151ae565b60005b8381101561519d578181015183820152602001615185565b83811115612cd85750506000910152565b60208152600082518060208401526151cd816040850160208701615182565b601f01601f19169190910160400192915050565b6001600160a01b03811681146151f657600080fd5b50565b6000806040838503121561520c57600080fd5b8235615217816151e1565b946020939093013593505050565b8035600281900b81146131b457600080fd5b80356001600160801b03811681146131b457600080fd5b60008083601f84011261526057600080fd5b50813567ffffffffffffffff81111561527857600080fd5b60208301915083602082850101111561529057600080fd5b9250929050565b600080600080600080600060e0888a0312156152b257600080fd5b87356152bd816151e1565b96506152cb60208901615225565b95506152d960408901615225565b945060a08801898111156152ec57600080fd5b6060890194506152fb81615237565b93505060c088013567ffffffffffffffff81111561531857600080fd5b6153248a828b0161524e565b989b979a50959850939692959293505050565b60008060006060848603121561534c57600080fd5b8335615357816151e1565b92506020840135615367816151e1565b929592945050506040919091013590565b80151581146151f657600080fd5b60008060008060008060a0878903121561539f57600080fd5b86356153aa816151e1565b95506020870135945060408701356153c181615378565b935060608701356153d1816151e1565b9250608087013567ffffffffffffffff8111156153ed57600080fd5b6153f989828a0161524e565b979a9699509497509295939492505050565b60008060008060006080868803121561542357600080fd5b853561542e816151e1565b94506020860135935060408601359250606086013567ffffffffffffffff81111561545857600080fd5b6154648882890161524e565b969995985093965092949392505050565b60006020828403121561548757600080fd5b8135610cca816151e1565b6000806000606084860312156154a757600080fd5b6154b084615225565b92506154be60208501615225565b91506154cc60408501615237565b90509250925092565b600080604083850312156154e857600080fd5b6154f183615225565b91506154ff60208401615225565b90509250929050565b60006020828403121561551a57600080fd5b610cca82615225565b6000806040838503121561553657600080fd5b82359150602083013561554881615378565b809150509250929050565b6000806040838503121561556657600080fd5b8235615571816151e1565b91506020830135615548816151e1565b60008060006060848603121561559657600080fd5b83356155a1816151e1565b92506155af60208501615225565b91506154cc60408501615225565b600181811c908216806155d157607f821691505b60208210811415614d9757634e487b7160e01b600052602260045260246000fd5b60006020828403121561560457600080fd5b8151610cca81615378565b634e487b7160e01b600052603260045260246000fd5b818352818160208501375060006020828401015260006020601f19601f840116840101905092915050565b848152836020820152606060408201526000613615606083018486615625565b634e487b7160e01b600052601160045260246000fd5b6000821982111561569957615699615670565b500190565b60008160020b8360020b6000821282627fffff038213811516156156c4576156c4615670565b82627fffff190382128116156156dc576156dc615670565b50019392505050565b60008160020b8360020b6000811281627fffff190183128115161561570c5761570c615670565b81627fffff01831381161561572357615723615670565b5090039392505050565b60006001600160801b0380831681851680830382111561574f5761574f615670565b01949350505050565b600080831283600160ff1b0183128115161561577657615776615670565b837f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0183138116156157aa576157aa615670565b50500390565b6000808212827f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff038413811516156157ea576157ea615670565b82600160ff1b03841281161561580257615802615670565b50500190565b6000806040838503121561581b57600080fd5b8251615826816151e1565b602084015190925062ffffff8116811461554857600080fd5b634e487b7160e01b600052601260045260246000fd5b600081600019048311821515161561586f5761586f615670565b500290565b6000826158835761588361583f565b500490565b600063ffffffff838116908316818110156158a5576158a5615670565b039392505050565b60006001600160801b03838116908316818110156158a5576158a5615670565b60008160020b627fffff198114156158e7576158e7615670565b60000392915050565b60008160020b8360020b806159075761590761583f565b6000198114627fffff198314161561592157615921615670565b90059392505050565b600062ffffff8083168185168183048111821515161561594c5761594c615670565b02949350505050565b60008260020b806159685761596861583f565b808360020b0791505092915050565b60008251615989818460208701615182565b9190910192915050565b6000602082840312156159a557600080fd5b5051919050565b6000828210156159be576159be615670565b500390565b600081600f0b6f7fffffffffffffffffffffffffffffff198114156158e7576158e7615670565b60006001600160a01b03838116908316818110156158a5576158a5615670565b6000600019821415615a1e57615a1e615670565b5060010190565b600081600f0b83600f0b60008112816f7fffffffffffffffffffffffffffffff1901831281151615615a5957615a59615670565b816f7fffffffffffffffffffffffffffffff01831381161561572357615723615670565b600081600f0b83600f0b60008212826f7fffffffffffffffffffffffffffffff03821381151615615ab057615ab0615670565b826f7fffffffffffffffffffffffffffffff190382128116156156dc576156dc615670565b6000600160ff1b821415615aeb57615aeb615670565b506000039056fea164736f6c6343000809000a

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.