ETH Price: $2,957.20 (+0.01%)

Contract

0xF802D5c44dC4E3bB0eCcf680a6bA82Cbd24B9F33

Overview

ETH Balance

0 ETH

ETH Value

$0.00

Token Holdings

More Info

Private Name Tags

TokenTracker

Multichain Info

No addresses found
Transaction Hash
Block
From
To
0x759f2372385392622026-01-24 20:47:012 hrs ago1769287621IN
0xF802D5c4...bd24B9F33
0 ETH0.000000970.0006974
Approve379301282026-01-17 19:34:477 days ago1768678487IN
0xF802D5c4...bd24B9F33
0 ETH00.00010025
Approve374220812026-01-11 22:27:2013 days ago1768170440IN
0xF802D5c4...bd24B9F33
0 ETH00.00000028
0x759f2372363892862025-12-30 23:34:0524 days ago1767137645IN
0xF802D5c4...bd24B9F33
0 ETH00.00000037
0x759f2372358188542025-12-24 9:06:5331 days ago1766567213IN
0xF802D5c4...bd24B9F33
0 ETH0.000000050.00010031
0x759f2372358188372025-12-24 9:06:3631 days ago1766567196IN
0xF802D5c4...bd24B9F33
0 ETH0.000000090.00010031
0x759f2372356470822025-12-22 9:24:0133 days ago1766395441IN
0xF802D5c4...bd24B9F33
0 ETH0.000000130.00010031
0x759f2372354057502025-12-19 14:21:4936 days ago1766154109IN
0xF802D5c4...bd24B9F33
0 ETH0.000000140.00010031
0x759f2372353208072025-12-18 14:46:0637 days ago1766069166IN
0xF802D5c4...bd24B9F33
0 ETH0.000000720.00052738
0x759f2372352175632025-12-17 10:05:2238 days ago1765965922IN
0xF802D5c4...bd24B9F33
0 ETH0.000000130.00010029
0x759f2372346978682025-12-11 9:43:4744 days ago1765446227IN
0xF802D5c4...bd24B9F33
0 ETH00.00000035
0x759f2372341742722025-12-05 8:17:1150 days ago1764922631IN
0xF802D5c4...bd24B9F33
0 ETH0.000000140.00010025
0x759f2372341365452025-12-04 21:48:2451 days ago1764884904IN
0xF802D5c4...bd24B9F33
0 ETH00.00000036
0x759f2372340371872025-12-03 18:12:2652 days ago1764785546IN
0xF802D5c4...bd24B9F33
0 ETH0.000000140.0001057
Approve335477122025-11-28 2:14:3157 days ago1764296071IN
0xF802D5c4...bd24B9F33
0 ETH00.00000384
0x759f2372332556952025-11-24 17:07:3461 days ago1764004054IN
0xF802D5c4...bd24B9F33
0 ETH00.00000034
0x759f2372332094772025-11-24 4:17:1661 days ago1763957836IN
0xF802D5c4...bd24B9F33
0 ETH00.00000377
Approve326218862025-11-17 9:04:0568 days ago1763370245IN
0xF802D5c4...bd24B9F33
0 ETH00.00010029
0x759f2372316549972025-11-06 4:29:1679 days ago1762403356IN
0xF802D5c4...bd24B9F33
0 ETH0.000000070.00004973
0x759f2372315370072025-11-04 19:42:4681 days ago1762285366IN
0xF802D5c4...bd24B9F33
0 ETH0.000000130.00008244
0x759f2372311795302025-10-31 16:24:4985 days ago1761927889IN
0xF802D5c4...bd24B9F33
0 ETH0.000000020.0000129
Approve308093452025-10-27 9:35:0489 days ago1761557704IN
0xF802D5c4...bd24B9F33
0 ETH00.00010029
0x759f2372304418862025-10-23 3:30:4593 days ago1761190245IN
0xF802D5c4...bd24B9F33
0 ETH0.000002590.002
Approve303781102025-10-22 9:47:4994 days ago1761126469IN
0xF802D5c4...bd24B9F33
0 ETH00.00010028
0x759f2372300699222025-10-18 20:11:2198 days ago1760818281IN
0xF802D5c4...bd24B9F33
0 ETH0.000000270.00019996
View all transactions

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block From To
385392622026-01-24 20:47:012 hrs ago1769287621
0xF802D5c4...bd24B9F33
0.75591862 ETH
385392622026-01-24 20:47:012 hrs ago1769287621
0xF802D5c4...bd24B9F33
0.75591862 ETH
383622502026-01-22 19:36:492 days ago1769110609
0xF802D5c4...bd24B9F33
0.0002815 ETH
381039032026-01-19 19:51:025 days ago1768852262
0xF802D5c4...bd24B9F33
0.000001 ETH
379297972026-01-17 19:29:167 days ago1768678156
0xF802D5c4...bd24B9F33
0.00028049 ETH
371239432026-01-08 11:38:2216 days ago1767872302
0xF802D5c4...bd24B9F33
0.32083443 ETH
371239352026-01-08 11:38:1416 days ago1767872294
0xF802D5c4...bd24B9F33
0.32083443 ETH
363892862025-12-30 23:34:0524 days ago1767137645
0xF802D5c4...bd24B9F33
0.42464912 ETH
363892862025-12-30 23:34:0524 days ago1767137645
0xF802D5c4...bd24B9F33
0.42464912 ETH
363494542025-12-30 12:30:1325 days ago1767097813
0xF802D5c4...bd24B9F33
0.00000154 ETH
363386792025-12-30 9:30:3825 days ago1767087038
0xF802D5c4...bd24B9F33
0.00000154 ETH
358188542025-12-24 9:06:5331 days ago1766567213
0xF802D5c4...bd24B9F33
0.00002219 ETH
358188542025-12-24 9:06:5331 days ago1766567213
0xF802D5c4...bd24B9F33
0.00002219 ETH
358188372025-12-24 9:06:3631 days ago1766567196
0xF802D5c4...bd24B9F33
0.00002219 ETH
358188372025-12-24 9:06:3631 days ago1766567196
0xF802D5c4...bd24B9F33
0.00002219 ETH
356470822025-12-22 9:24:0133 days ago1766395441
0xF802D5c4...bd24B9F33
0.00000548 ETH
356470822025-12-22 9:24:0133 days ago1766395441
0xF802D5c4...bd24B9F33
0.00000548 ETH
355745202025-12-21 13:14:3934 days ago1766322879
0xF802D5c4...bd24B9F33
1 wei
355658782025-12-21 10:50:3734 days ago1766314237
0xF802D5c4...bd24B9F33
1 wei
354057502025-12-19 14:21:4936 days ago1766154109
0xF802D5c4...bd24B9F33
0.00000813 ETH
354057502025-12-19 14:21:4936 days ago1766154109
0xF802D5c4...bd24B9F33
0.00000813 ETH
353620222025-12-19 2:13:0136 days ago1766110381
0xF802D5c4...bd24B9F33
0.00000833 ETH
353208072025-12-18 14:46:0637 days ago1766069166
0xF802D5c4...bd24B9F33
0 ETH
353208072025-12-18 14:46:0637 days ago1766069166
0xF802D5c4...bd24B9F33
0.00000169 ETH
353208072025-12-18 14:46:0637 days ago1766069166
0xF802D5c4...bd24B9F33
0.00000169 ETH
View All Internal Transactions

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
MultiPositionManager

Compiler Version
v0.8.26+commit.8a97fa7a

Optimization Enabled:
Yes with 800 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.8.26;

import { IERC20 } from "@openzeppelin/contracts/interfaces/IERC20.sol";
import { ERC20, ERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { SignedMath } from "@openzeppelin/contracts/utils/math/SignedMath.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { IPoolManager } from "v4-core/interfaces/IPoolManager.sol";
import { IHooks } from "v4-core/interfaces/IHooks.sol";
import { StateLibrary } from "v4-core/libraries/StateLibrary.sol";
import { Currency } from "v4-core/types/Currency.sol";
import { PoolKey } from "v4-core/types/PoolKey.sol";
import { BalanceDelta } from "v4-core/types/BalanceDelta.sol";
import { TransientStateLibrary } from "v4-core/libraries/TransientStateLibrary.sol";
import { FullMath } from "v4-core/libraries/FullMath.sol";
import { TickMath } from "v4-core/libraries/TickMath.sol";
import { SafeCast } from "v4-core/libraries/SafeCast.sol";
import { FixedPoint128 } from "v4-core/libraries/FixedPoint128.sol";
import { SafeCallback } from "v4-periphery/src/base/SafeCallback.sol";

import { IMultiPositionManager } from "./interfaces/IMultiPositionManager.sol";
import { PoolManagerUtils } from "./PoolManagerUtils.sol";

contract MultiPositionManager is 
  IMultiPositionManager,
  ERC20Permit,
  ReentrancyGuard,
  Ownable,
  SafeCallback,
  Pausable
{
  using SafeERC20 for IERC20;
  using StateLibrary for IPoolManager;
  using TransientStateLibrary for IPoolManager;
  using SignedMath for int256;
  using Math for uint256;
  using SafeCast for *;

  enum Action {
    WITHDRAW,
    REBALANCE,
    COMPOUND,
    ZERO_BURN,
    PULL_LIQUIDITY,
    CLAIM_FEE
  }

  Currency currency0;
  Currency currency1;

  uint256 public basePositionsLength;
  mapping(uint256 => Position) public basePositions;
  Position[2] public limitPositions;

  address public feeRecipient;
  address public whitelistedAddress;

  uint16 public fee;

  error InvalidFee();
  error ZeroAddress();
  error ZeroValue();
  error WhitelistedAddress();
  error InvalidTickRange();
  error InvalidAction();
  error InvalidRebalanceParams();
  error InvalidPoolKeyTokens();
  error InvalidDepositAmount(uint256 amount);
  error TickOffsetExceeded();
  error CurrencyDeltaError();
  error DuplicatedPosition(Position position);
  error NotANativeTokenPair();

  event Deposit(
    address indexed from,
    address indexed to,
    uint256 shares,
    uint256 deposit0,
    uint256 deposit1
  );
  event Withdraw(
    address indexed sender,
    address indexed to,
    uint256 shares,
    uint256 amount0,
    uint256 amount1
  );

  event LogTotalAmounts(
    uint256 totalAmount0,
    uint256 totalAmount1
  );
  event Rebalance(Position[]);
  event FeeChanged(uint16 newFee);


  /**
   * 
   * @param _poolManager pool manager
   * @param _owner owner of a hypervisor
   * @param name name
   * @param symbol symbol
   */
  constructor(
    IPoolManager _poolManager,
    address _token0,
    address _token1,
    address _owner,
    string memory name,
    string memory symbol
  ) ERC20Permit(name) ERC20(name, symbol) Ownable(_owner) SafeCallback(_poolManager) {
    if (_owner == address(0)) revert ZeroAddress();
    currency0 = Currency.wrap(_token0);
    currency1 = Currency.wrap(_token1);
    feeRecipient = _owner;

    fee = 1;
    
  }

  receive() external payable {}

  /**
   * @notice Deposit tokens
   * @param to Address to which liquidity tokens are minted
   * @param from Address from which asset tokens are transferred
   * @return shares Number of shares to mint
   * @return deposit0 Quantity of token0 to be deposited
   * @return deposit1 Quantity of token1 to be deposited
   */
  function deposit(
    uint256 deposit0Desired,
    uint256 deposit1Desired,
    address to,
    address from
  ) nonReentrant whenNotPaused external payable returns (
    uint256 shares,
    uint256 deposit0,
    uint256 deposit1
  ) {
    if (to == address(0) || to == address(this)) {
      revert ZeroAddress();
    }

    if (msg.sender != whitelistedAddress) revert WhitelistedAddress();
    if (
      !currency0.isAddressZero() &&
      msg.value > 0
    ) {
      revert NotANativeTokenPair();
    }

    // zero burn
    _zeroBurnAll();

    (shares, deposit0, deposit1) = _calcSharesAndAmounts(
      deposit0Desired,
      deposit1Desired
    );
    assert(shares > 0);
    
    _transferIn(from, currency0, deposit0);
    _transferIn(from, currency1, deposit1);
    
    _mint(to, shares);
    emit Deposit(from, to, shares, deposit0, deposit1);

    logTotalAmounts();
  }

  /**
   * 
   * @param shares Number of liquidity tokens to redeem as pool assets
   * @param to Address to which redeemed pool assets are sent
   * @param outMin min amount returned for shares of liq
   * @return amount0 Amount of token0 redeemed by the submitted liquidity tokens
   * @return amount1 Amount of token1 redeemed by the submitted liquidity tokens
   */
  function withdraw(
    uint256 shares,
    address to,
    uint256[2][] memory outMin
  ) nonReentrant whenNotPaused external returns (uint256 amount0, uint256 amount1) {
    if (shares == 0) revert ZeroValue();
    if (to == address(0)) revert ZeroAddress();

    bytes memory params = abi.encode(shares, outMin);
    bytes memory result = poolManager.unlock(
      abi.encode(Action.WITHDRAW, params)
    );
    (
      amount0,
      amount1
    ) = abi.decode(result, (uint256, uint256));

    currency0.transfer(to, amount0);
    currency1.transfer(to, amount1);

    uint256 unusedAmount0 = FullMath.mulDiv(currency0.balanceOfSelf(), shares, totalSupply());
    uint256 unusedAmount1 = FullMath.mulDiv(currency1.balanceOfSelf(), shares, totalSupply());
    if (unusedAmount0 > 0) {
      amount0 = amount0 + unusedAmount0;
      currency0.transfer(to, unusedAmount0);
    }
    if (unusedAmount1 > 0) {
      amount1 = amount1 + unusedAmount1;
      currency1.transfer(to, unusedAmount1);
    }

    _burn(msg.sender, shares);

    emit Withdraw(msg.sender, to, shares, amount0, amount1);

    logTotalAmounts();
  }

  function zeroBurnAll() nonReentrant external {
    if (msg.sender != whitelistedAddress) revert WhitelistedAddress();
    
    _zeroBurnAll();
  }

  /**
   * 
   * @param baseRanges Array of base positions
   * @param inMin min spend 
   * @param outMin min amount0,1 returned for shares of liq 
   */
  function rebalance(
    Position[] memory baseRanges,
    uint128[] memory liquidities,
    int24 limitWidth,
    uint256[2][] memory inMin,
    uint256[2][] memory outMin,
    int24 aimTick,
    uint24 tickOffset
  ) nonReentrant external onlyOwner {
    // Validate that all poolKeys have the same tokens as the contract
    for (uint8 i = 0; i < baseRanges.length; i++) {
      if (baseRanges[i].poolKey.currency0.toId() != currency0.toId() || 
          baseRanges[i].poolKey.currency1.toId() != currency1.toId()) {
        revert InvalidPoolKeyTokens();
      }
    }
    
    _checkTickOffset(baseRanges, aimTick, tickOffset);
    if (
      inMin.length != baseRanges.length ||
      liquidities.length != baseRanges.length ||
      outMin.length != basePositionsLength
    ) {
      revert InvalidRebalanceParams();
    }

    bytes memory params = abi.encode(
      baseRanges,
      liquidities,
      limitWidth,
      inMin,
      outMin
    );
    poolManager.unlock(
      abi.encode(Action.REBALANCE, params)
    );
    emit Rebalance(baseRanges);
    logTotalAmounts();
  }

  /**
   * @notice Compound pending fees
   * @param inMin min spend 
   */
  function compound(
    uint128[] memory liquidities,
    uint256[2][] memory inMin,
    int24 aimTick,
    uint24 tickOffset
  ) external onlyOwner {
    _checkTickOffset(aimTick, tickOffset);

    bytes memory params = abi.encode(liquidities, inMin);
    poolManager.unlock(
      abi.encode(Action.COMPOUND, params)
    );

    logTotalAmounts();
  }

  /**
   * @notice Pull liquidity tokens from liquidity and receive the tokens
   * 
   * @param tickLower lower tick
   * @param tickUpper upper tick
   * @param outMin min outs
   */
  function pullLiquidity(
    PoolKey memory _poolKey,
    int24 tickLower,
    int24 tickUpper,
    uint256[2] memory outMin
  ) external onlyOwner {
    bytes memory params = abi.encode(_poolKey, tickLower, tickUpper, outMin);
    poolManager.unlock(
      abi.encode(Action.PULL_LIQUIDITY, params)
    );
  }

  function claimFee() external onlyOwner {
    _zeroBurnAll();
    poolManager.unlock(
      abi.encode(Action.CLAIM_FEE, "")
    );
  }

  /// @param _whitelistedAddress whitelisted address
  function setWhitelist(address _whitelistedAddress) external onlyOwner {
    whitelistedAddress = _whitelistedAddress;
  }

  function setFee(uint16 newFee) external onlyOwner {
    if (fee < 1) revert InvalidFee();
    // burn all pending fees before changing fee
    _zeroBurnAll();

    fee = newFee;
    emit FeeChanged(newFee);
  }

  function setFeeRecipient(address _feeRecipient) external onlyOwner {
    require(_feeRecipient != address(0));
    feeRecipient = _feeRecipient;
  }

  function pause() external onlyOwner {
    _pause();
  }

  function unpause() external onlyOwner {
    _unpause();
  }

  function getPositions() public view returns (
    Position[] memory,
    PositionData[] memory
  ) {
    Position[] memory positions = new Position[](basePositionsLength + 2);
    PositionData[] memory positionData = new PositionData[](basePositionsLength + 2);

    uint128 liquidity;
    uint256 amount0;
    uint256 amount1;

    // include base positions
    for (uint8 i = 0; i < basePositionsLength; ) {
      positions[i] = basePositions[i];
      
      (
        liquidity,
        amount0,
        amount1,
        ,
      ) = PoolManagerUtils.getAmountsOf(
        poolManager,
        positions[i]
      );

      positionData[i] = PositionData({
        liquidity: liquidity,
        amount0: amount0,
        amount1: amount1
      });

      unchecked {
        i = i + 1;
      }
    }

    // include limit positions
    for (uint8 i = 0; i < 2; ) {
      positions[basePositionsLength + i] = limitPositions[i];
      
      (
        liquidity,
        amount0,
        amount1,
        ,
      ) = PoolManagerUtils.getAmountsOf(
        poolManager,
        positions[basePositionsLength + i]
      );

      positionData[basePositionsLength + i] = PositionData({
        liquidity: liquidity,
        amount0: amount0,
        amount1: amount1
      });

      unchecked {
        i = i + 1;
      }
    }

    return (
      positions,
      positionData
    );
  }

  function getTotalAmounts() external view returns (
    uint256 total0,
    uint256 total1,
    uint256 totalFee0,
    uint256 totalFee1
  ) {
    return _getTotalAmounts();
  }

  function currentTicks() external view returns (int24[] memory ticks) {
    if (basePositionsLength == 0) {
      return new int24[](0);
    }

    ticks = new int24[](basePositionsLength + 2);
    for (uint8 i = 0; i < basePositionsLength; ) {
      ticks[i] = currentTick(basePositions[i].poolKey);
      
      unchecked {
        i = i + 1;
      }
    }

    ticks[basePositionsLength] = currentTick(limitPositions[0].poolKey);
    ticks[basePositionsLength + 1] = currentTick(limitPositions[1].poolKey);
  }
  
  function currentTick(PoolKey memory poolKey) public view returns (int24 tick) {
    (, tick, , ) = poolManager.getSlot0(poolKey.toId());
  }

  function token0() external view returns (IERC20) {
    return IERC20(Currency.unwrap(currency0));
  }

  function token1() external view returns (IERC20) {
    return IERC20(Currency.unwrap(currency1));
  }

  function _unlockCallback(bytes calldata data) internal override returns (bytes memory) {
    (Action selector, bytes memory params) = abi.decode(
      data,
      (Action, bytes)
    );
    bytes memory result = _executeActionWithoutUnlock(selector, params);
    _closePair();
    return result;
  }

  function _mintLiquidities(
    uint128[] memory liquidities,
    uint256[2][] memory inMin
  ) internal {
    Position[] memory basePositionsArray = _getBasePositionsArray();
    
    PoolManagerUtils.mintLiquidities(
      poolManager,
      basePositionsArray,
      limitPositions,
      liquidities,
      inMin
    );
  }

  function _burnLiquidities(
    uint256 shares,
    uint256[2][] memory outMin
  ) internal returns (uint256 amount0, uint256 amount1) {
    if (shares == 0) return (amount0, amount1);

    Position[] memory basePositionsArray = _getBasePositionsArray();

    (amount0, amount1) = PoolManagerUtils.burnLiquidities(
      poolManager,
      basePositionsArray,
      limitPositions,
      shares,
      totalSupply(),
      outMin
    );
  }

  function _zeroBurnAllWithoutUnlock() internal returns (
    uint256 totalFee0,
    uint256 totalFee1
  ) {
    Position[] memory basePositionsArray = _getBasePositionsArray();
    (totalFee0, totalFee1) = PoolManagerUtils.zeroBurnAll(
      poolManager,
      basePositionsArray,
      limitPositions,
      currency0,
      currency1,
      fee
    );
  }

  function _executeActionWithoutUnlock(
    Action selector,
    bytes memory params
  ) internal returns (bytes memory result) {
    if (selector == Action.WITHDRAW) {
      _zeroBurnAllWithoutUnlock();
      (
        uint256 shares,
        uint256[2][] memory outMin
      ) = abi.decode(params, (uint256, uint256[2][]));
      (uint256 amountOut0, uint256 amountOut1) = _burnLiquidities(shares, outMin);
      return abi.encode(amountOut0, amountOut1);
    } else if (selector == Action.ZERO_BURN) {
      _zeroBurnAllWithoutUnlock();
    } else if (selector == Action.REBALANCE) {
      _zeroBurnAllWithoutUnlock();
      (
        Position[] memory baseRanges,
        uint128[] memory liquidities,
        int24 limitWidth,
        uint256[2][] memory inMin,
        uint256[2][] memory outMin
      ) = abi.decode(params, (Position[], uint128[], int24, uint256[2][], uint256[2][]));
      _burnLiquidities(totalSupply(), outMin);

      Position[] memory allRanges = new Position[](baseRanges.length + 2);
      basePositionsLength = baseRanges.length;
      for (uint8 i = 0; i < baseRanges.length; ) {
        basePositions[i] = baseRanges[i];
        allRanges[i] = baseRanges[i];
        
        unchecked {
          i = i + 1;
        }
      }
      _setLimitRanges(baseRanges[0].poolKey, limitWidth);
      allRanges[baseRanges.length] = limitPositions[0];
      allRanges[baseRanges.length + 1] = limitPositions[1];
      _checkRanges(allRanges);

      _mintLiquidities(liquidities, inMin);
    } else if (selector == Action.COMPOUND) {
      _zeroBurnAllWithoutUnlock();
      (
        uint128[] memory liquidities,
        uint256[2][] memory inMin
      ) = abi.decode(params, (uint128[], uint256[2][]));
      _mintLiquidities(liquidities, inMin);
    } else if (selector == Action.PULL_LIQUIDITY) {
      (
        PoolKey memory _poolKey,
        int24 tickLower,
        int24 tickUpper,
        uint256[2] memory outMin
      ) = abi.decode(params, (PoolKey, int24, int24, uint256[2]));
      _zeroBurnAllWithoutUnlock();
      Position memory position = Position(_poolKey, tickLower, tickUpper);
      PoolManagerUtils.burnLiquidityForShare(
        poolManager,
        position,
        totalSupply(),
        totalSupply(),
        outMin
      );
    } else if (selector == Action.CLAIM_FEE) {
      _claimFee(currency0);
      _claimFee(currency1);
    } else revert InvalidAction();
  }

  function _claimFee(Currency currency) internal {
    uint256 amount = poolManager.balanceOf(address(this), currency.toId());
    if (amount == 0) return;
    poolManager.burn(address(this), currency.toId(), amount);
    poolManager.take(currency, feeRecipient, amount);
  }

  function _zeroBurnAll() internal {
    poolManager.unlock(
      abi.encode(Action.ZERO_BURN, "")
    );
  }

  /**
   * @notice 
   *  account for balanceDelta
   *  receive the tokens it's supposed to receive, 
   *  or pay the tokens it's supposed to pay, 
   *  from or to the PoolManager
   */
  function _closePair() internal {
    PoolManagerUtils.close(poolManager, currency1);
    PoolManagerUtils.close(poolManager, currency0);
  }

  function _transferIn(address from, Currency currency, uint256 amount) internal {
    if (amount == 0) return;
    if (currency.isAddressZero()) {
      if (msg.value < amount) revert InvalidDepositAmount(amount);
      if (msg.value > amount)
        payable(msg.sender).transfer(msg.value - amount);
    } else {
      IERC20(Currency.unwrap(currency)).safeTransferFrom(from, address(this), amount);
    }
  }

  function _getTotalAmounts() internal view returns (
    uint256 total0,
    uint256 total1,
    uint256 totalFee0,
    uint256 totalFee1
  ) {
    // base positions
    for (uint8 i = 0; i < basePositionsLength; ) {
      (
        ,
        uint256 amount0,
        uint256 amount1,
        uint256 feesOwed0,
        uint256 feesOwed1
      ) = PoolManagerUtils.getAmountsOf(
        poolManager,
        basePositions[i]
      );
      total0 = total0 + amount0;
      total1 = total1 + amount1;
      totalFee0 = totalFee0 + feesOwed0;
      totalFee1 = totalFee1 + feesOwed1;
      
      unchecked {
        i++;
      }
    }

    // limit positions
    (
      ,
      uint256 limitAmount0,
      uint256 limitAmount1,
      uint256 limitFeesOwed0,
      uint256 limitFeesOwed1
    ) = PoolManagerUtils.getAmountsOf(
      poolManager,
      limitPositions[0]
    );
    total0 = total0 + limitAmount0;
    total1 = total1 + limitAmount1;
    totalFee0 = totalFee0 + limitFeesOwed0;
    totalFee1 = totalFee1 + limitFeesOwed1;

    (
      ,
      limitAmount0,
      limitAmount1,
      limitFeesOwed0,
      limitFeesOwed1
    ) = PoolManagerUtils.getAmountsOf(
      poolManager,
      limitPositions[1]
    );
    total0 = total0 + limitAmount0;
    total1 = total1 + limitAmount1;
    totalFee0 = totalFee0 + limitFeesOwed0;
    totalFee1 = totalFee1 + limitFeesOwed1;

    // exclude protocol fee from the total amount
    totalFee0 = totalFee0 - (totalFee0 / fee);
    totalFee1 = totalFee1 - (totalFee1 / fee);

    // Add fees net of protocol fees to the total amount
    total0 = total0 + totalFee0;
    total1 = total1 + totalFee1;

    // balance of contract
    total0 = total0 + currency0.balanceOfSelf();
    total1 = total1 + currency1.balanceOfSelf();
  }

  function _setLimitRanges(
    PoolKey memory _poolKey,
    int24 limitWidth
  ) internal {
    if (limitWidth == 0) {
      delete limitPositions;
      return;
    }
    limitPositions[0].poolKey = _poolKey;
    limitPositions[1].poolKey = _poolKey;
    
    int24 tickSpacing = _poolKey.tickSpacing;

    if (limitWidth % tickSpacing != 0) {
      // increase `limitWidth` to round up multiple of tickSpacing
      limitWidth = (limitWidth / tickSpacing + 1) * tickSpacing;
    }

    int24 tick = currentTick(_poolKey);
    int24 baseTick;

    if (tick % tickSpacing == 0) {
      baseTick = tick;
    } else if (tick % tickSpacing > 0) {
      baseTick = (tick / tickSpacing) * tickSpacing;
    } else {
      baseTick = (tick / tickSpacing - 1) * tickSpacing;
    }

    (
      limitPositions[0].lowerTick,
      limitPositions[0].upperTick
    ) = _roundUp(baseTick - limitWidth, baseTick, tickSpacing);
    (
      limitPositions[1].lowerTick,
      limitPositions[1].upperTick
    ) = _roundUp(baseTick + tickSpacing, baseTick + tickSpacing + limitWidth, tickSpacing);
  }

  function _roundUp(
    int24 tickLower,
    int24 tickUpper,
    int24 tickSpacing
  ) internal pure returns (int24, int24) {
    // Get min/max usable ticks that are aligned with tick spacing
    int24 minUsableTick = TickMath.minUsableTick(tickSpacing);
    int24 maxUsableTick = TickMath.maxUsableTick(tickSpacing);
    
    // Ensure lower tick is at least the min usable tick
    if (tickLower < minUsableTick) {
      tickLower = minUsableTick;
    } 
    // Ensure upper tick is at most the max usable tick
    if (tickUpper > maxUsableTick) {
      tickUpper = maxUsableTick;
    } 
    // Handle invalid ranges
    if (tickLower >= tickUpper) {
      return (0, 0);
    }
    
    return (tickLower, tickUpper);
  }

  function _checkTickOffset(
    Position[] memory baseRanges,
    int24 aimTick,
    uint24 tickOffset
  ) internal view {
    for (uint8 i = 0; i < baseRanges.length; ) {
      if (SignedMath.abs(currentTick(baseRanges[i].poolKey) - aimTick) > tickOffset) {
        revert TickOffsetExceeded();
      }
      
      unchecked {
        i = i + 1;
      }
    }
  }

  function _checkTickOffset(int24 aimTick, uint24 tickOffset) internal view {
    for (uint8 i = 0; i < basePositionsLength; ) {
      if (SignedMath.abs(currentTick(basePositions[i].poolKey) - aimTick) > tickOffset) {
        revert TickOffsetExceeded();
      }
      
      unchecked {
        i = i + 1;
      }
    }
  }

  function _checkRanges(Position[] memory ranges) internal pure {
    for (uint8 i = 0; i < ranges.length; i++) {
      bytes32 hashI = keccak256(abi.encode(ranges[i]));
      for (uint8 j = i + 1; j < ranges.length; j++) {
        if (ranges[j].lowerTick == ranges[j].upperTick) continue;
        bytes32 hashJ = keccak256(abi.encode(ranges[j]));
        if (hashI == hashJ) {
          revert DuplicatedPosition(ranges[j]);
        }
      }
    }
  }

  function logTotalAmounts() internal {
    (uint256 total0, uint256 total1, , ) = _getTotalAmounts();
    emit LogTotalAmounts(total0, total1);
  }

  function _calcSharesAndAmounts(uint256 amount0Desired, uint256 amount1Desired)
    internal
    view
    returns (
      uint256 shares,
      uint256 amount0,
      uint256 amount1
    )
  {
    uint256 totalSupply = totalSupply();
    (uint256 total0, uint256 total1, , ) = _getTotalAmounts();


    // deduct native token deposit amount from total amount
    if (currency0.isAddressZero()) {
      total0 = total0 - msg.value;
    }
    
    // If total supply > 0, vault can't be empty
    assert(totalSupply == 0 || total0 > 0 || total1 > 0);

    if (totalSupply == 0) {
      // For first deposit, just use the amounts desired
      amount0 = amount0Desired;
      amount1 = amount1Desired;
      shares = Math.max(amount0, amount1);
    } else if (total0 == 0) {
      amount1 = amount1Desired;
      shares = FullMath.mulDiv(amount1, totalSupply, total1);
    } else if (total1 == 0) {
      amount0 = amount0Desired;
      shares = FullMath.mulDiv(amount0, totalSupply, total0);
    } else {
      uint256 cross = Math.min(amount0Desired * total1, amount1Desired * total0);
      if (cross == 0) revert ZeroValue();

      // Round up amounts
      amount0 = (cross - 1) / total1 + 1;
      amount1 = (cross - 1) / total0 + 1;
      shares = FullMath.mulDiv(cross, totalSupply, total0 * total1);
    }
  }

  function _getBasePositionsArray() internal view returns (
    Position[] memory basePositionsArray
  ) {
    basePositionsArray = new Position[](basePositionsLength);

    for (uint8 i = 0; i < basePositionsLength; ) {
      basePositionsArray[i] = basePositions[i];

      unchecked {
        i = i + 1;
      }
    }
  }
}

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

pragma solidity ^0.8.20;

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Permit.sol)

pragma solidity ^0.8.20;

import {IERC20Permit} from "./IERC20Permit.sol";
import {ERC20} from "../ERC20.sol";
import {ECDSA} from "../../../utils/cryptography/ECDSA.sol";
import {EIP712} from "../../../utils/cryptography/EIP712.sol";
import {Nonces} from "../../../utils/Nonces.sol";

/**
 * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712, Nonces {
    bytes32 private constant PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");

    /**
     * @dev Permit deadline has expired.
     */
    error ERC2612ExpiredSignature(uint256 deadline);

    /**
     * @dev Mismatched signature.
     */
    error ERC2612InvalidSigner(address signer, address owner);

    /**
     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
     *
     * It's a good idea to use the same `name` that is defined as the ERC20 token name.
     */
    constructor(string memory name) EIP712(name, "1") {}

    /**
     * @inheritdoc IERC20Permit
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        if (block.timestamp > deadline) {
            revert ERC2612ExpiredSignature(deadline);
        }

        bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));

        bytes32 hash = _hashTypedDataV4(structHash);

        address signer = ECDSA.recover(hash, v, r, s);
        if (signer != owner) {
            revert ERC2612InvalidSigner(signer, owner);
        }

        _approve(owner, spender, value);
    }

    /**
     * @inheritdoc IERC20Permit
     */
    function nonces(address owner) public view virtual override(IERC20Permit, Nonces) returns (uint256) {
        return super.nonces(owner);
    }

    /**
     * @inheritdoc IERC20Permit
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
        return _domainSeparatorV4();
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

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

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @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);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

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

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

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

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

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

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

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

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

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";

/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
    /// @notice Thrown when a currency is not netted out after the contract is unlocked
    error CurrencyNotSettled();

    /// @notice Thrown when trying to interact with a non-initialized pool
    error PoolNotInitialized();

    /// @notice Thrown when unlock is called, but the contract is already unlocked
    error AlreadyUnlocked();

    /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
    error ManagerLocked();

    /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
    error TickSpacingTooLarge(int24 tickSpacing);

    /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
    error TickSpacingTooSmall(int24 tickSpacing);

    /// @notice PoolKey must have currencies where address(currency0) < address(currency1)
    error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);

    /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
    /// or on a pool that does not have a dynamic swap fee.
    error UnauthorizedDynamicLPFeeUpdate();

    /// @notice Thrown when trying to swap amount of 0
    error SwapAmountCannotBeZero();

    ///@notice Thrown when native currency is passed to a non native settlement
    error NonzeroNativeValue();

    /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
    error MustClearExactPositiveDelta();

    /// @notice Emitted when a new pool is initialized
    /// @param id The abi encoded hash of the pool key struct for the new pool
    /// @param currency0 The first currency of the pool by address sort order
    /// @param currency1 The second currency of the pool by address sort order
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks
    /// @param hooks The hooks contract address for the pool, or address(0) if none
    /// @param sqrtPriceX96 The price of the pool on initialization
    /// @param tick The initial tick of the pool corresponding to the initialized price
    event Initialize(
        PoolId indexed id,
        Currency indexed currency0,
        Currency indexed currency1,
        uint24 fee,
        int24 tickSpacing,
        IHooks hooks,
        uint160 sqrtPriceX96,
        int24 tick
    );

    /// @notice Emitted when a liquidity position is modified
    /// @param id The abi encoded hash of the pool key struct for the pool that was modified
    /// @param sender The address that modified the pool
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param liquidityDelta The amount of liquidity that was added or removed
    /// @param salt The extra data to make positions unique
    event ModifyLiquidity(
        PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
    );

    /// @notice Emitted for swaps between currency0 and currency1
    /// @param id The abi encoded hash of the pool key struct for the pool that was modified
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param amount0 The delta of the currency0 balance of the pool
    /// @param amount1 The delta of the currency1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of the price of the pool after the swap
    /// @param fee The swap fee in hundredths of a bip
    event Swap(
        PoolId indexed id,
        address indexed sender,
        int128 amount0,
        int128 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick,
        uint24 fee
    );

    /// @notice Emitted for donations
    /// @param id The abi encoded hash of the pool key struct for the pool that was donated to
    /// @param sender The address that initiated the donate call
    /// @param amount0 The amount donated in currency0
    /// @param amount1 The amount donated in currency1
    event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);

    /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
    /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
    /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
    /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
    /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
    function unlock(bytes calldata data) external returns (bytes memory);

    /// @notice Initialize the state for a given pool ID
    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
    /// @param key The pool key for the pool to initialize
    /// @param sqrtPriceX96 The initial square root price
    /// @return tick The initial tick of the pool
    function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);

    struct ModifyLiquidityParams {
        // the lower and upper tick of the position
        int24 tickLower;
        int24 tickUpper;
        // how to modify the liquidity
        int256 liquidityDelta;
        // a value to set if you want unique liquidity positions at the same range
        bytes32 salt;
    }

    /// @notice Modify the liquidity for the given pool
    /// @dev Poke by calling with a zero liquidityDelta
    /// @param key The pool to modify liquidity in
    /// @param params The parameters for modifying the liquidity
    /// @param hookData The data to pass through to the add/removeLiquidity hooks
    /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
    /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
    function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);

    struct SwapParams {
        /// Whether to swap token0 for token1 or vice versa
        bool zeroForOne;
        /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
        int256 amountSpecified;
        /// The sqrt price at which, if reached, the swap will stop executing
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swap against the given pool
    /// @param key The pool to swap in
    /// @param params The parameters for swapping
    /// @param hookData The data to pass through to the swap hooks
    /// @return swapDelta The balance delta of the address swapping
    /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
    /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
    /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
    function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta swapDelta);

    /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
    /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
    /// Donors should keep this in mind when designing donation mechanisms.
    /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
    /// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
    /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
    /// Read the comments in `Pool.swap()` for more information about this.
    /// @param key The key of the pool to donate to
    /// @param amount0 The amount of currency0 to donate
    /// @param amount1 The amount of currency1 to donate
    /// @param hookData The data to pass through to the donate hooks
    /// @return BalanceDelta The delta of the caller after the donate
    function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        external
        returns (BalanceDelta);

    /// @notice Writes the current ERC20 balance of the specified currency to transient storage
    /// This is used to checkpoint balances for the manager and derive deltas for the caller.
    /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
    /// for native tokens because the amount to settle is determined by the sent value.
    /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
    /// native funds, this function can be called with the native currency to then be able to settle the native currency
    function sync(Currency currency) external;

    /// @notice Called by the user to net out some value owed to the user
    /// @dev Will revert if the requested amount is not available, consider using `mint` instead
    /// @dev Can also be used as a mechanism for free flash loans
    /// @param currency The currency to withdraw from the pool manager
    /// @param to The address to withdraw to
    /// @param amount The amount of currency to withdraw
    function take(Currency currency, address to, uint256 amount) external;

    /// @notice Called by the user to pay what is owed
    /// @return paid The amount of currency settled
    function settle() external payable returns (uint256 paid);

    /// @notice Called by the user to pay on behalf of another address
    /// @param recipient The address to credit for the payment
    /// @return paid The amount of currency settled
    function settleFor(address recipient) external payable returns (uint256 paid);

    /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
    /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
    /// @dev This could be used to clear a balance that is considered dust.
    /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
    function clear(Currency currency, uint256 amount) external;

    /// @notice Called by the user to move value into ERC6909 balance
    /// @param to The address to mint the tokens to
    /// @param id The currency address to mint to ERC6909s, as a uint256
    /// @param amount The amount of currency to mint
    /// @dev The id is converted to a uint160 to correspond to a currency address
    /// If the upper 12 bytes are not 0, they will be 0-ed out
    function mint(address to, uint256 id, uint256 amount) external;

    /// @notice Called by the user to move value from ERC6909 balance
    /// @param from The address to burn the tokens from
    /// @param id The currency address to burn from ERC6909s, as a uint256
    /// @param amount The amount of currency to burn
    /// @dev The id is converted to a uint160 to correspond to a currency address
    /// If the upper 12 bytes are not 0, they will be 0-ed out
    function burn(address from, uint256 id, uint256 amount) external;

    /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
    /// @param key The key of the pool to update dynamic LP fees for
    /// @param newDynamicLPFee The new dynamic pool LP fee
    function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {IPoolManager} from "./IPoolManager.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";

/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
    /// @notice The hook called before the state of a pool is initialized
    /// @param sender The initial msg.sender for the initialize call
    /// @param key The key for the pool being initialized
    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
    /// @return bytes4 The function selector for the hook
    function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);

    /// @notice The hook called after the state of a pool is initialized
    /// @param sender The initial msg.sender for the initialize call
    /// @param key The key for the pool being initialized
    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
    /// @param tick The current tick after the state of a pool is initialized
    /// @return bytes4 The function selector for the hook
    function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
        external
        returns (bytes4);

    /// @notice The hook called before liquidity is added
    /// @param sender The initial msg.sender for the add liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for adding liquidity
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeAddLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after liquidity is added
    /// @param sender The initial msg.sender for the add liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for adding liquidity
    /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
    /// @param feesAccrued The fees accrued since the last time fees were collected from this position
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterAddLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external returns (bytes4, BalanceDelta);

    /// @notice The hook called before liquidity is removed
    /// @param sender The initial msg.sender for the remove liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for removing liquidity
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after liquidity is removed
    /// @param sender The initial msg.sender for the remove liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for removing liquidity
    /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
    /// @param feesAccrued The fees accrued since the last time fees were collected from this position
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external returns (bytes4, BalanceDelta);

    /// @notice The hook called before a swap
    /// @param sender The initial msg.sender for the swap call
    /// @param key The key for the pool
    /// @param params The parameters for the swap
    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
    function beforeSwap(
        address sender,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4, BeforeSwapDelta, uint24);

    /// @notice The hook called after a swap
    /// @param sender The initial msg.sender for the swap call
    /// @param key The key for the pool
    /// @param params The parameters for the swap
    /// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterSwap(
        address sender,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata hookData
    ) external returns (bytes4, int128);

    /// @notice The hook called before donate
    /// @param sender The initial msg.sender for the donate call
    /// @param key The key for the pool
    /// @param amount0 The amount of token0 being donated
    /// @param amount1 The amount of token1 being donated
    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after donate
    /// @param sender The initial msg.sender for the donate call
    /// @param key The key for the pool
    /// @param amount0 The amount of token0 being donated
    /// @param amount1 The amount of token1 being donated
    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function afterDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external returns (bytes4);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {PoolId} from "../types/PoolId.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Position} from "./Position.sol";

/// @notice A helper library to provide state getters that use extsload
library StateLibrary {
    /// @notice index of pools mapping in the PoolManager
    bytes32 public constant POOLS_SLOT = bytes32(uint256(6));

    /// @notice index of feeGrowthGlobal0X128 in Pool.State
    uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;

    // feeGrowthGlobal1X128 offset in Pool.State = 2

    /// @notice index of liquidity in Pool.State
    uint256 public constant LIQUIDITY_OFFSET = 3;

    /// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;
    uint256 public constant TICKS_OFFSET = 4;

    /// @notice index of tickBitmap mapping in Pool.State
    uint256 public constant TICK_BITMAP_OFFSET = 5;

    /// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;
    uint256 public constant POSITIONS_OFFSET = 6;

    /**
     * @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee
     * @dev Corresponds to pools[poolId].slot0
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.
     * @return tick The current tick of the pool.
     * @return protocolFee The protocol fee of the pool.
     * @return lpFee The swap fee of the pool.
     */
    function getSlot0(IPoolManager manager, PoolId poolId)
        internal
        view
        returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        bytes32 data = manager.extsload(stateSlot);

        //   24 bits  |24bits|24bits      |24 bits|160 bits
        // 0x000000   |000bb8|000000      |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7
        // ---------- | fee  |protocolfee | tick  | sqrtPriceX96
        assembly ("memory-safe") {
            // bottom 160 bits of data
            sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
            // next 24 bits of data
            tick := signextend(2, shr(160, data))
            // next 24 bits of data
            protocolFee := and(shr(184, data), 0xFFFFFF)
            // last 24 bits of data
            lpFee := and(shr(208, data), 0xFFFFFF)
        }
    }

    /**
     * @notice Retrieves the tick information of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].ticks[tick]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve information for.
     * @return liquidityGross The total position liquidity that references this tick
     * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
     * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     */
    function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128
        )
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        // read all 3 words of the TickInfo struct
        bytes32[] memory data = manager.extsload(slot, 3);
        assembly ("memory-safe") {
            let firstWord := mload(add(data, 32))
            liquidityNet := sar(128, firstWord)
            liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
            feeGrowthOutside0X128 := mload(add(data, 64))
            feeGrowthOutside1X128 := mload(add(data, 96))
        }
    }

    /**
     * @notice Retrieves the liquidity information of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve liquidity for.
     * @return liquidityGross The total position liquidity that references this tick
     * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
     */
    function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (uint128 liquidityGross, int128 liquidityNet)
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        bytes32 value = manager.extsload(slot);
        assembly ("memory-safe") {
            liquidityNet := sar(128, value)
            liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
        }
    }

    /**
     * @notice Retrieves the fee growth outside a tick range of a pool
     * @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve fee growth for.
     * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     */
    function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        // offset by 1 word, since the first word is liquidityGross + liquidityNet
        bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);
        assembly ("memory-safe") {
            feeGrowthOutside0X128 := mload(add(data, 32))
            feeGrowthOutside1X128 := mload(add(data, 64))
        }
    }

    /**
     * @notice Retrieves the global fee growth of a pool.
     * @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return feeGrowthGlobal0 The global fee growth for token0.
     * @return feeGrowthGlobal1 The global fee growth for token1.
     */
    function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)
        internal
        view
        returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State, `uint256 feeGrowthGlobal0X128`
        bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);

        // read the 2 words of feeGrowthGlobal
        bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);
        assembly ("memory-safe") {
            feeGrowthGlobal0 := mload(add(data, 32))
            feeGrowthGlobal1 := mload(add(data, 64))
        }
    }

    /**
     * @notice Retrieves total the liquidity of a pool.
     * @dev Corresponds to pools[poolId].liquidity
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return liquidity The liquidity of the pool.
     */
    function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `uint128 liquidity`
        bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);

        liquidity = uint128(uint256(manager.extsload(slot)));
    }

    /**
     * @notice Retrieves the tick bitmap of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].tickBitmap[tick]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve the bitmap for.
     * @return tickBitmap The bitmap of the tick.
     */
    function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)
        internal
        view
        returns (uint256 tickBitmap)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(int16 => uint256) tickBitmap;`
        bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);

        // slot id of the mapping key: `pools[poolId].tickBitmap[tick]
        bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));

        tickBitmap = uint256(manager.extsload(slot));
    }

    /**
     * @notice Retrieves the position information of a pool without needing to calculate the `positionId`.
     * @dev Corresponds to pools[poolId].positions[positionId]
     * @param poolId The ID of the pool.
     * @param owner The owner of the liquidity position.
     * @param tickLower The lower tick of the liquidity range.
     * @param tickUpper The upper tick of the liquidity range.
     * @param salt The bytes32 randomness to further distinguish position state.
     * @return liquidity The liquidity of the position.
     * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
     * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
     */
    function getPositionInfo(
        IPoolManager manager,
        PoolId poolId,
        address owner,
        int24 tickLower,
        int24 tickUpper,
        bytes32 salt
    ) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {
        // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
        bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);

        (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);
    }

    /**
     * @notice Retrieves the position information of a pool at a specific position ID.
     * @dev Corresponds to pools[poolId].positions[positionId]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param positionId The ID of the position.
     * @return liquidity The liquidity of the position.
     * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
     * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
     */
    function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)
        internal
        view
        returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)
    {
        bytes32 slot = _getPositionInfoSlot(poolId, positionId);

        // read all 3 words of the Position.State struct
        bytes32[] memory data = manager.extsload(slot, 3);

        assembly ("memory-safe") {
            liquidity := mload(add(data, 32))
            feeGrowthInside0LastX128 := mload(add(data, 64))
            feeGrowthInside1LastX128 := mload(add(data, 96))
        }
    }

    /**
     * @notice Retrieves the liquidity of a position.
     * @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param positionId The ID of the position.
     * @return liquidity The liquidity of the position.
     */
    function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)
        internal
        view
        returns (uint128 liquidity)
    {
        bytes32 slot = _getPositionInfoSlot(poolId, positionId);
        liquidity = uint128(uint256(manager.extsload(slot)));
    }

    /**
     * @notice Calculate the fee growth inside a tick range of a pool
     * @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tickLower The lower tick of the range.
     * @param tickUpper The upper tick of the range.
     * @return feeGrowthInside0X128 The fee growth inside the tick range for token0.
     * @return feeGrowthInside1X128 The fee growth inside the tick range for token1.
     */
    function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)
        internal
        view
        returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)
    {
        (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);

        (uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =
            getTickFeeGrowthOutside(manager, poolId, tickLower);
        (uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =
            getTickFeeGrowthOutside(manager, poolId, tickUpper);
        (, int24 tickCurrent,,) = getSlot0(manager, poolId);
        unchecked {
            if (tickCurrent < tickLower) {
                feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
                feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
            } else if (tickCurrent >= tickUpper) {
                feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;
                feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;
            } else {
                feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
                feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
            }
        }
    }

    function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));
    }

    function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(int24 => TickInfo) ticks`
        bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);

        // slot key of the tick key: `pools[poolId].ticks[tick]
        return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));
    }

    function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(bytes32 => Position.State) positions;`
        bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);

        // slot of the mapping key: `pools[poolId].positions[positionId]
        return keccak256(abi.encodePacked(positionId, positionMapping));
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";

type Currency is address;

using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;

function equals(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) == Currency.unwrap(other);
}

function greaterThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) > Currency.unwrap(other);
}

function lessThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) < Currency.unwrap(other);
}

function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) >= Currency.unwrap(other);
}

/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
    /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
    error NativeTransferFailed();

    /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
    error ERC20TransferFailed();

    /// @notice A constant to represent the native currency
    Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));

    function transfer(Currency currency, address to, uint256 amount) internal {
        // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
        // modified custom error selectors

        bool success;
        if (currency.isAddressZero()) {
            assembly ("memory-safe") {
                // Transfer the ETH and revert if it fails.
                success := call(gas(), to, amount, 0, 0, 0, 0)
            }
            // revert with NativeTransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
            }
        } else {
            assembly ("memory-safe") {
                // Get a pointer to some free memory.
                let fmp := mload(0x40)

                // Write the abi-encoded calldata into memory, beginning with the function selector.
                mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

                success :=
                    and(
                        // Set success to whether the call reverted, if not we check it either
                        // returned exactly 1 (can't just be non-zero data), or had no return data.
                        or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                        // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                        // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                        // Counterintuitively, this call must be positioned second to the or() call in the
                        // surrounding and() call or else returndatasize() will be zero during the computation.
                        call(gas(), currency, 0, fmp, 68, 0, 32)
                    )

                // Now clean the memory we used
                mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
                mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
                mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
            }
            // revert with ERC20TransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(
                    Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
                );
            }
        }
    }

    function balanceOfSelf(Currency currency) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return address(this).balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
        }
    }

    function balanceOf(Currency currency, address owner) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return owner.balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
        }
    }

    function isAddressZero(Currency currency) internal pure returns (bool) {
        return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
    }

    function toId(Currency currency) internal pure returns (uint256) {
        return uint160(Currency.unwrap(currency));
    }

    // If the upper 12 bytes are non-zero, they will be zero-ed out
    // Therefore, fromId() and toId() are not inverses of each other
    function fromId(uint256 id) internal pure returns (Currency) {
        return Currency.wrap(address(uint160(id)));
    }
}

File 14 of 58 : PoolKey.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";

using PoolIdLibrary for PoolKey global;

/// @notice Returns the key for identifying a pool
struct PoolKey {
    /// @notice The lower currency of the pool, sorted numerically
    Currency currency0;
    /// @notice The higher currency of the pool, sorted numerically
    Currency currency1;
    /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
    uint24 fee;
    /// @notice Ticks that involve positions must be a multiple of tick spacing
    int24 tickSpacing;
    /// @notice The hooks of the pool
    IHooks hooks;
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {SafeCast} from "../libraries/SafeCast.sol";

/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;

using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;

function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
    assembly ("memory-safe") {
        balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
    }
}

function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
    int256 res0;
    int256 res1;
    assembly ("memory-safe") {
        let a0 := sar(128, a)
        let a1 := signextend(15, a)
        let b0 := sar(128, b)
        let b1 := signextend(15, b)
        res0 := add(a0, b0)
        res1 := add(a1, b1)
    }
    return toBalanceDelta(res0.toInt128(), res1.toInt128());
}

function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
    int256 res0;
    int256 res1;
    assembly ("memory-safe") {
        let a0 := sar(128, a)
        let a1 := signextend(15, a)
        let b0 := sar(128, b)
        let b1 := signextend(15, b)
        res0 := sub(a0, b0)
        res1 := sub(a1, b1)
    }
    return toBalanceDelta(res0.toInt128(), res1.toInt128());
}

function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
    return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}

function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
    return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}

/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
    /// @notice A BalanceDelta of 0
    BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);

    function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
        assembly ("memory-safe") {
            _amount0 := sar(128, balanceDelta)
        }
    }

    function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
        assembly ("memory-safe") {
            _amount1 := signextend(15, balanceDelta)
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Currency} from "../types/Currency.sol";
import {CurrencyReserves} from "./CurrencyReserves.sol";
import {NonzeroDeltaCount} from "./NonzeroDeltaCount.sol";
import {Lock} from "./Lock.sol";

/// @notice A helper library to provide state getters that use exttload
library TransientStateLibrary {
    /// @notice returns the reserves for the synced currency
    /// @param manager The pool manager contract.

    /// @return uint256 The reserves of the currency.
    /// @dev returns 0 if the reserves are not synced or value is 0.
    /// Checks the synced currency to only return valid reserve values (after a sync and before a settle).
    function getSyncedReserves(IPoolManager manager) internal view returns (uint256) {
        if (getSyncedCurrency(manager).isAddressZero()) return 0;
        return uint256(manager.exttload(CurrencyReserves.RESERVES_OF_SLOT));
    }

    function getSyncedCurrency(IPoolManager manager) internal view returns (Currency) {
        return Currency.wrap(address(uint160(uint256(manager.exttload(CurrencyReserves.CURRENCY_SLOT)))));
    }

    /// @notice Returns the number of nonzero deltas open on the PoolManager that must be zeroed out before the contract is locked
    function getNonzeroDeltaCount(IPoolManager manager) internal view returns (uint256) {
        return uint256(manager.exttload(NonzeroDeltaCount.NONZERO_DELTA_COUNT_SLOT));
    }

    /// @notice Get the current delta for a caller in the given currency
    /// @param target The credited account address
    /// @param currency The currency for which to lookup the delta
    function currencyDelta(IPoolManager manager, address target, Currency currency) internal view returns (int256) {
        bytes32 key;
        assembly ("memory-safe") {
            mstore(0, and(target, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(32, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
            key := keccak256(0, 64)
        }
        return int256(uint256(manager.exttload(key)));
    }

    /// @notice Returns whether the contract is unlocked or not
    function isUnlocked(IPoolManager manager) internal view returns (bool) {
        return manager.exttload(Lock.IS_UNLOCKED_SLOT) != 0x0;
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

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

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

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

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

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

            // Divide [prod1 prod0] by the factors of two
            assembly ("memory-safe") {
                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 ("memory-safe") {
                twos := add(div(sub(0, twos), twos), 1)
            }
            prod0 |= prod1 * twos;

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

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

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

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
    using CustomRevert for bytes4;

    /// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
    error InvalidTick(int24 tick);
    /// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
    error InvalidSqrtPrice(uint160 sqrtPriceX96);

    /// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
    int24 internal constant MAX_TICK = 887272;

    /// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
    int24 internal constant MIN_TICK_SPACING = 1;
    /// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
    int24 internal constant MAX_TICK_SPACING = type(int16).max;

    /// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_PRICE = 4295128739;
    /// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
    /// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
    uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
        1461446703485210103287273052203988822378723970342 - 4295128739 - 1;

    /// @notice Given a tickSpacing, compute the maximum usable tick
    function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
        unchecked {
            return (MAX_TICK / tickSpacing) * tickSpacing;
        }
    }

    /// @notice Given a tickSpacing, compute the minimum usable tick
    function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
        unchecked {
            return (MIN_TICK / tickSpacing) * tickSpacing;
        }
    }

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
    /// at the given tick
    function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        unchecked {
            uint256 absTick;
            assembly ("memory-safe") {
                tick := signextend(2, tick)
                // mask = 0 if tick >= 0 else -1 (all 1s)
                let mask := sar(255, tick)
                // if tick >= 0, |tick| = tick = 0 ^ tick
                // if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
                // either way, |tick| = mask ^ (tick + mask)
                absTick := xor(mask, add(mask, tick))
            }

            if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);

            // The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
            // is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer

            // Equivalent to:
            //     price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
            //     or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
            uint256 price;
            assembly ("memory-safe") {
                price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
            }
            if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
            if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
            if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
            if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
            if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
            if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
            if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
            if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
            if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
            if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
            if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
            if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
            if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
            if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
            if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
            if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
            if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
            if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
            if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;

            assembly ("memory-safe") {
                // if (tick > 0) price = type(uint256).max / price;
                if sgt(tick, 0) { price := div(not(0), price) }

                // 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 getTickAtSqrtPrice of the output price is always consistent
                // `sub(shl(32, 1), 1)` is `type(uint32).max`
                // `price + type(uint32).max` will not overflow because `price` fits in 192 bits
                sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
            }
        }
    }

    /// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
    /// ever return.
    /// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
    /// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
    function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
        unchecked {
            // Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
            // second inequality must be >= because the price can never reach the price at the max tick
            // if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
            // if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
            if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
                InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
            }

            uint256 price = uint256(sqrtPriceX96) << 32;

            uint256 r = price;
            uint256 msb = BitMath.mostSignificantBit(r);

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

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

            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(63, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(62, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(61, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(60, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(59, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(58, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(57, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(56, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(55, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(54, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(53, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(52, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(51, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                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; // Q22.128 number

            // Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
            int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);

            // Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
            // sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
            // is changed, this may need to be changed too
            int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);

            tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {CustomRevert} from "./CustomRevert.sol";

/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
    using CustomRevert for bytes4;

    error SafeCastOverflow();

    /// @notice Cast a uint256 to a uint160, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return y The downcasted integer, now type uint160
    function toUint160(uint256 x) internal pure returns (uint160 y) {
        y = uint160(x);
        if (y != x) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a uint128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return y The downcasted integer, now type uint128
    function toUint128(uint256 x) internal pure returns (uint128 y) {
        y = uint128(x);
        if (x != y) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a int128 to a uint128, revert on overflow or underflow
    /// @param x The int128 to be casted
    /// @return y The casted integer, now type uint128
    function toUint128(int128 x) internal pure returns (uint128 y) {
        if (x < 0) SafeCastOverflow.selector.revertWith();
        y = uint128(x);
    }

    /// @notice Cast a int256 to a int128, revert on overflow or underflow
    /// @param x The int256 to be downcasted
    /// @return y The downcasted integer, now type int128
    function toInt128(int256 x) internal pure returns (int128 y) {
        y = int128(x);
        if (y != x) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a int256, revert on overflow
    /// @param x The uint256 to be casted
    /// @return y The casted integer, now type int256
    function toInt256(uint256 x) internal pure returns (int256 y) {
        y = int256(x);
        if (y < 0) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a int128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return The downcasted integer, now type int128
    function toInt128(uint256 x) internal pure returns (int128) {
        if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
        return int128(int256(x));
    }
}

File 20 of 58 : FixedPoint128.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {ImmutableState} from "./ImmutableState.sol";

/// @title Safe Callback
/// @notice A contract that only allows the Uniswap v4 PoolManager to call the unlockCallback
abstract contract SafeCallback is ImmutableState, IUnlockCallback {
    /// @notice Thrown when calling unlockCallback where the caller is not PoolManager
    error NotPoolManager();

    constructor(IPoolManager _poolManager) ImmutableState(_poolManager) {}

    /// @notice Only allow calls from the PoolManager contract
    modifier onlyPoolManager() {
        if (msg.sender != address(poolManager)) revert NotPoolManager();
        _;
    }

    /// @inheritdoc IUnlockCallback
    /// @dev We force the onlyPoolManager modifier by exposing a virtual function after the onlyPoolManager check.
    function unlockCallback(bytes calldata data) external onlyPoolManager returns (bytes memory) {
        return _unlockCallback(data);
    }

    /// @dev to be implemented by the child contract, to safely guarantee the logic is only executed by the PoolManager
    function _unlockCallback(bytes calldata data) internal virtual returns (bytes memory);
}

/// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IHooks } from "v4-core/interfaces/IHooks.sol";
import { PoolKey } from "v4-core/types/PoolKey.sol";
import {IImmutableState} from "v4-periphery/src/interfaces/IImmutableState.sol";
import { IPoolManager } from "v4-core/interfaces/IPoolManager.sol";

interface IMultiPositionManager is IERC20, IImmutableState {
  struct Position {
    PoolKey poolKey;
    int24 lowerTick;
    int24 upperTick;
  }

  struct PositionData {
    uint128 liquidity;
    uint256 amount0;
    uint256 amount1;
  }
  function getPositions() external view returns (
      Position[] memory,
      PositionData[] memory
  );
  function basePositionsLength() external view returns (uint256);
  function token0() external view returns (IERC20);
  function token1() external view returns (IERC20);
  function getTotalAmounts() external view returns (
    uint256 total0,
    uint256 total1,
    uint256 totalFee0,
    uint256 totalFee1
  );
  function currentTicks() external view returns (int24[] memory);
  function rebalance(
    Position[] memory baseRanges,
    uint128[] memory liquidities,
    int24 limitWidth,
    uint256[2][] memory inMin,
    uint256[2][] memory outMin,
    int24 aimTick,
    uint24 tickOffset
  ) external;
  function compound(
    uint128[] memory liquidities,
    uint256[2][] memory inMin,
    int24 aimTick,
    uint24 tickOffset
  ) external;
  function claimFee() external;
  function setWhitelist(address _whitelist) external;
  function setFeeRecipient(address _feeRecipient) external;
  function setFee(uint16 fee) external;
  // function setTickOffset(uint24 offset) external;
  function deposit(
    uint256 deposit0Desired,
    uint256 deposit1Desired,
    address to,
    address from
  ) external payable returns (uint256, uint256, uint256);
  function zeroBurnAll() external;
  
}

// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.8.26;

import { IPoolManager } from "v4-core/interfaces/IPoolManager.sol";
import { PoolKey } from "v4-core/types/PoolKey.sol";
import { BalanceDelta } from "v4-core/types/BalanceDelta.sol";
import { StateLibrary } from "v4-core/libraries/StateLibrary.sol";
import { TransientStateLibrary } from "v4-core/libraries/TransientStateLibrary.sol";
import { Currency } from "v4-core/types/Currency.sol";
import { CurrencySettler } from "v4-periphery/lib/v4-core/test/utils/CurrencySettler.sol";
import { FullMath } from "v4-core/libraries/FullMath.sol";
import { FixedPoint128 } from "v4-core/libraries/FixedPoint128.sol";
import { LiquidityAmounts } from "v4-periphery/lib/v4-core/test/utils/LiquidityAmounts.sol";
import { TickMath } from "v4-core/libraries/TickMath.sol";
import { SafeCast } from "v4-core/libraries/SafeCast.sol";
import { SignedMath } from "@openzeppelin/contracts/utils/math/SignedMath.sol";
import { IMultiPositionManager } from "./interfaces/IMultiPositionManager.sol";

library PoolManagerUtils {
  using StateLibrary for IPoolManager;
  using TransientStateLibrary for IPoolManager;
  using CurrencySettler for Currency;
  using SignedMath for int256;
  using SafeCast for *;

  bytes32 constant POSITION_ID = bytes32(uint256(1));
  bytes constant HOOK_DATA = "";

  event ZeroBurn(
    int24 tickLower,
    int24 tickUpper,
    uint256 amount0,
    uint256 amount1
  );
  event LiquidityMinted(
    IMultiPositionManager.Position position,
    uint128 liquidity
  );
  event LiquidityBurnt(
    IMultiPositionManager.Position position,
    uint256 liquidity
  );
  
  error PSC();
  error InvalidPositionData(
    IMultiPositionManager.Position position
  );
  error PoolNotInitialized(
    PoolKey poolKey
  );
  error DuplicatedPosition(
    IMultiPositionManager.Position position
  );
  error ZeroLiquidityAmount(
    IMultiPositionManager.Position position
  );

  function mintLiquidities(
    IPoolManager poolManager,
    IMultiPositionManager.Position[] memory basePositions,
    IMultiPositionManager.Position[2] memory limitPositions,
    uint128[] memory liquidities,
    uint256[2][] memory inMin
  ) external {
    for (uint8 i = 0; i < basePositions.length; ) {
      (
        uint256 currencyDelta0,
        uint256 currencyDelta1
      ) = _getCurrencyDeltas(
        poolManager,
        basePositions[i].poolKey.currency0,
        basePositions[i].poolKey.currency1
      );
      (uint256 amount0, uint256 amount1) = getAmountsForLiquidity(
        poolManager,
        basePositions[i],
        liquidities[i]
      );
      if (amount0 > currencyDelta0) {
        amount0 = currencyDelta0;
      }
      if (amount1 > currencyDelta1) {
        amount1 = currencyDelta1;
      }
      
      _mintLiquidityForAmounts(
        poolManager,
        basePositions[i],
        amount0,
        amount1,
        inMin[i]
      );

      unchecked {
        i = i + 1;
      }
    }

    // mint limit positions
    _mintLimitPositions(
      poolManager,
      limitPositions
    );
  }

  // if there's still remaining tokens, create a limit position(single-sided position)
  function _mintLimitPositions(
    IPoolManager poolManager,
    IMultiPositionManager.Position[2] memory limitPositions
  ) internal {
    if (limitPositions[0].lowerTick != limitPositions[0].upperTick) {
      uint256 currencyDelta1 = _getCurrencyDelta(
        poolManager,
        limitPositions[0].poolKey.currency1
      );
      
      if (currencyDelta1 > 0) {
        _mintLiquidityForAmounts(
          poolManager,
          limitPositions[0],
          0,
          currencyDelta1,
          [uint256(0), uint256(0)]
        );
      }
    }

    if (limitPositions[1].lowerTick != limitPositions[1].upperTick) {
      uint256 currencyDelta0 = _getCurrencyDelta(
        poolManager,
        limitPositions[1].poolKey.currency0
      );

      if (currencyDelta0 > 0) {
        _mintLiquidityForAmounts(
          poolManager,
          limitPositions[1],
          currencyDelta0,
          0,
          [uint256(0), uint256(0)]
        );
      }
    }
  }

  function _mintLiquidityForAmounts(
    IPoolManager poolManager,
    IMultiPositionManager.Position memory position,
    uint256 amount0,
    uint256 amount1,
    uint256[2] memory inMin
  ) internal {
    (uint160 sqrtPriceX96, , , ) = poolManager.getSlot0(position.poolKey.toId());
    if (sqrtPriceX96 == 0) {
      revert PoolNotInitialized(position.poolKey);
    }

    if (
      position.lowerTick >= position.upperTick ||
      position.lowerTick % position.poolKey.tickSpacing != 0 ||
      position.upperTick % position.poolKey.tickSpacing != 0
    ) {
      revert InvalidPositionData(position);
    }

    uint128 liquidity = LiquidityAmounts.getLiquidityForAmounts(
      sqrtPriceX96,
      TickMath.getSqrtPriceAtTick(position.lowerTick),
      TickMath.getSqrtPriceAtTick(position.upperTick),
      amount0,
      amount1
    );

    if (liquidity > 0) {
      (BalanceDelta callerDelta, ) = poolManager.modifyLiquidity(
        position.poolKey,
        IPoolManager.ModifyLiquidityParams({
          tickLower: position.lowerTick,
          tickUpper: position.upperTick,
          liquidityDelta: liquidity.toInt128(),
          salt: POSITION_ID
        }),
        HOOK_DATA
      );

      /// callerDelta.amount0() and callerDelta.amount0() are all negative
      if (
        int256(callerDelta.amount0()).abs() < inMin[0] ||
        int256(callerDelta.amount1()).abs() < inMin[1]
      ) {
        revert PSC();
      }
      emit LiquidityMinted(position, liquidity);
    }
  }

  function burnLiquidities(
    IPoolManager poolManager,
    IMultiPositionManager.Position[] memory basePositions,
    IMultiPositionManager.Position[2] memory limitPositions,
    uint256 shares,
    uint256 totalSupply,
    uint256[2][] memory outMin
  ) external returns (uint256 amount0, uint256 amount1) {
    if (shares == 0) return (amount0, amount1);

    uint256 amountOut0;
    uint256 amountOut1;
    for (uint8 i = 0; i < basePositions.length; ) {
      (amountOut0, amountOut1) = burnLiquidityForShare(
        poolManager,
        basePositions[i],
        shares,
        totalSupply,
        outMin[i]
      );

      amount0 = amount0 + amountOut0;
      amount1 = amount1 + amountOut1;

      unchecked {
        i = i + 1;
      }
    }

    (amountOut0, amountOut1) = _burnLimitPositions(
      poolManager,
      limitPositions,
      shares,
      totalSupply
    );
    amount0 = amount0 + amountOut0;
    amount1 = amount1 + amountOut1;
  }

  function _burnLimitPositions(
    IPoolManager poolManager,
    IMultiPositionManager.Position[2] memory limitPositions,
    uint256 shares,
    uint256 totalSupply
  ) internal returns (uint256 amount0, uint256 amount1) {
    if (shares == 0) return (0, 0);

    for (uint8 i = 0; i < 2; ) {
      (uint256 amountOut0, uint256 amountOut1) = burnLiquidityForShare(
        poolManager,
        limitPositions[i],
        shares,
        totalSupply,
        [uint256(0), uint256(0)]
      );
      
      amount0 = amount0 + amountOut0;
      amount1 = amount1 + amountOut1;

      unchecked {
        i = i + 1;
      }
    }
  }

  function burnLiquidityForShare(
    IPoolManager poolManager,
    IMultiPositionManager.Position memory position,
    uint256 shares,
    uint256 totalSupply,
    uint256[2] memory outMin
  ) public returns (uint256 amountOut0, uint256 amountOut1) {
    if (position.lowerTick == position.upperTick) {
      return (0, 0);
    }
    (uint128 liquidity, , ) = poolManager.getPositionInfo(
      position.poolKey.toId(),
      address(this),
      position.lowerTick,
      position.upperTick,
      POSITION_ID
    );
    
    uint256 liquidityForShares = FullMath.mulDiv(liquidity, shares, totalSupply);

    if (liquidityForShares > 0) {
      (BalanceDelta callerDelta, ) = poolManager.modifyLiquidity(
        position.poolKey,
        IPoolManager.ModifyLiquidityParams({
          tickLower: position.lowerTick,
          tickUpper: position.upperTick,
          liquidityDelta: -(liquidityForShares).toInt128(),
          salt: POSITION_ID
        }),
        HOOK_DATA
      );

      // when withdrawing liquidity or collecting fee (collecting fee is same as withdrawing liquidity 0 ), 
      // callerDelta is always positive
      // when adding liquidity, most of time callerDelta is negative but could be positive 
      //  when fee is larger than liquidity itself (but fee already settled in `zeroBurn`)
      amountOut0 = callerDelta.amount0().toUint128();
      amountOut1 = callerDelta.amount1().toUint128();
      
      if (
        amountOut0 < outMin[0] ||
        amountOut1 < outMin[1]
      ) {
        revert PSC();
      }
      
      emit LiquidityBurnt(position, liquidityForShares);
    }
  }

  function zeroBurnAll(
    IPoolManager poolManager,
    IMultiPositionManager.Position[] memory basePositions,
    IMultiPositionManager.Position[2] memory limitPositions,
    Currency currency0,
    Currency currency1,
    uint16 fee
  ) external returns (uint256 totalFee0, uint256 totalFee1) {
    uint256 fee0;
    uint256 fee1;
    for (uint8 i = 0; i < basePositions.length; ) {
      (fee0, fee1) = _zeroBurnWithoutUnlock(
        poolManager,
        basePositions[i]
      );
      totalFee0 = totalFee0 + fee0;
      totalFee1 = totalFee1 + fee1;
      
      unchecked {
        i++;
      }
    }

    (fee0, fee1) = _zeroBurnWithoutUnlock(
      poolManager,
      limitPositions[0]
    );
    totalFee0 = totalFee0 + fee0;
    totalFee1 = totalFee1 + fee1;
    (fee0, fee1) = _zeroBurnWithoutUnlock(
      poolManager,
      limitPositions[1]
    );
    totalFee0 = totalFee0 + fee0;
    totalFee1 = totalFee1 + fee1;

    // Calculate fees by dividing by fee denominator
    uint256 treasuryFee0 = totalFee0 / fee;
    uint256 treasuryFee1 = totalFee1 / fee;

    if (treasuryFee0 > 0) {
      poolManager.mint(
        address(this),
        uint256(uint160(Currency.unwrap(currency0))),
        treasuryFee0
      );
    }
    if (treasuryFee1 > 0) {
      poolManager.mint(
        address(this),
        uint256(uint160(Currency.unwrap(currency1))),
        treasuryFee1
      );
    }
  }

  function _zeroBurnWithoutUnlock(
    IPoolManager poolManager,
    IMultiPositionManager.Position memory position
  ) internal returns (uint256 fee0, uint256 fee1) {
    if (position.lowerTick == position.upperTick) {
      return (0, 0);
    }
    (uint128 liquidity, , ) = poolManager.getPositionInfo(
      position.poolKey.toId(),
      address(this),
      position.lowerTick,
      position.upperTick,
      POSITION_ID
    );
    
    if (liquidity > 0) {
      // Check fees first
      (uint256 feesOwed0, uint256 feesOwed1) = _getFeesOwed(poolManager, position);
      // Only proceed with modifyLiquidity if either fee is non-zero
      if (feesOwed0 != 0 || feesOwed1 != 0) {
        (, BalanceDelta feesAccrued) = poolManager.modifyLiquidity(
          position.poolKey,
          IPoolManager.ModifyLiquidityParams({
              tickLower: position.lowerTick,
              tickUpper: position.upperTick,
              liquidityDelta: 0,
              salt: POSITION_ID
          }),
          HOOK_DATA
        );

        fee0 = uint128(feesAccrued.amount0());
        fee1 = uint128(feesAccrued.amount1());
        emit ZeroBurn(
            position.lowerTick,
            position.upperTick,
            fee0,
            fee1
        );
      }
    }
  }

  function close(
    IPoolManager poolManager,
    Currency currency
  ) external {
    int256 currencyDelta = poolManager.currencyDelta(
      address(this),
      currency
    );
    if (currencyDelta == 0) return;
    else if (currencyDelta < 0) {
      currency.settle(poolManager, address(this), uint256(-currencyDelta), false);
    } else {
      currency.take(poolManager, address(this), uint256(currencyDelta), false);
    }
  }

  function _getCurrencyDelta(
    IPoolManager poolManager,
    Currency currency
  ) internal view returns (
    uint256 delta
  ) {
    int256 currencyDelta = poolManager.currencyDelta(
      address(this),
      currency
    );

    if (currencyDelta > 0) {
      delta = currency.balanceOfSelf() + uint256(currencyDelta);
    } else {
      delta = currency.balanceOfSelf() - uint256(-currencyDelta);
    }

    return delta;
  }

  function _getCurrencyDeltas(
    IPoolManager poolManager,
    Currency currency0,
    Currency currency1
  ) internal view returns (uint256 delta0, uint256 delta1) {
    int256 currencyDelta0 = poolManager.currencyDelta(
      address(this),
      currency0
    );
    int256 currencyDelta1 = poolManager.currencyDelta(
      address(this),
      currency1
    );
    
    if (currencyDelta0 > 0) {
      delta0 = currency0.balanceOfSelf() + uint256(currencyDelta0);
    } else {
      delta0 = currency0.balanceOfSelf() - uint256(-currencyDelta0);
    }
    if (currencyDelta1 > 0) {
      delta1 = currency1.balanceOfSelf() + uint256(currencyDelta1);
    } else {
      delta1 = currency1.balanceOfSelf() - uint256(-currencyDelta1);
    }
    
    return (delta0, delta1);
  }

  function getAmountsForLiquidity(
    IPoolManager poolManager,
    IMultiPositionManager.Position memory position,
    uint128 liquidity
  ) internal view returns (
    uint256 amount0,
    uint256 amount1
  ) {
    (uint160 sqrtPriceX96, , , ) = poolManager.getSlot0(position.poolKey.toId());
    (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
      sqrtPriceX96,
      TickMath.getSqrtPriceAtTick(position.lowerTick),
      TickMath.getSqrtPriceAtTick(position.upperTick),
      liquidity
    );
  }

  function getAmountsOf(
    IPoolManager poolManager,
    IMultiPositionManager.Position memory position
  ) external view returns (
    uint128 liquidity,
    uint256 amount0,
    uint256 amount1,
    uint256 feesOwed0,
    uint256 feesOwed1
  ) {
    if (position.lowerTick == position.upperTick) {
      return (0, 0, 0, 0, 0);
    }
    (liquidity, , ) = poolManager.getPositionInfo(
      position.poolKey.toId(),
      address(this),
      position.lowerTick,
      position.upperTick,
      POSITION_ID
    );
    
    (uint160 sqrtPriceX96, , , ) = poolManager.getSlot0(position.poolKey.toId());
    
    (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
      sqrtPriceX96,
      TickMath.getSqrtPriceAtTick(position.lowerTick),
      TickMath.getSqrtPriceAtTick(position.upperTick),
      liquidity
    );

    (feesOwed0, feesOwed1) = _getFeesOwed(
      poolManager,
      position
    );
  }

  function _getFeesOwed(
    IPoolManager poolManager,
    IMultiPositionManager.Position memory position
  ) internal view returns (
    uint256 feesOwed0,
    uint256 feesOwed1
  ) {
    (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) =
      poolManager.getFeeGrowthInside(
        position.poolKey.toId(),
        position.lowerTick,
        position.upperTick
      );

    (
      uint128 liquidity, 
      uint256 feeGrowthInside0LastX128,
      uint256 feeGrowthInside1LastX128
    ) = poolManager.getPositionInfo(
      position.poolKey.toId(),
      address(this),
      position.lowerTick,
      position.upperTick,
      POSITION_ID
    );

    unchecked {
      feesOwed0 =
        FullMath.mulDiv(feeGrowthInside0X128 - feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);
      feesOwed1 =
        FullMath.mulDiv(feeGrowthInside1X128 - feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);
    }
  }
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.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}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

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

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

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

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

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

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

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

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` 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.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     * ```
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     */
    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError, bytes32) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/EIP712.sol)

pragma solidity ^0.8.20;

import {MessageHashUtils} from "./MessageHashUtils.sol";
import {ShortStrings, ShortString} from "../ShortStrings.sol";
import {IERC5267} from "../../interfaces/IERC5267.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
 * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
 * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
 * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
 * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
 * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
 *
 * @custom:oz-upgrades-unsafe-allow state-variable-immutable
 */
abstract contract EIP712 is IERC5267 {
    using ShortStrings for *;

    bytes32 private constant TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _cachedDomainSeparator;
    uint256 private immutable _cachedChainId;
    address private immutable _cachedThis;

    bytes32 private immutable _hashedName;
    bytes32 private immutable _hashedVersion;

    ShortString private immutable _name;
    ShortString private immutable _version;
    string private _nameFallback;
    string private _versionFallback;

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        _name = name.toShortStringWithFallback(_nameFallback);
        _version = version.toShortStringWithFallback(_versionFallback);
        _hashedName = keccak256(bytes(name));
        _hashedVersion = keccak256(bytes(version));

        _cachedChainId = block.chainid;
        _cachedDomainSeparator = _buildDomainSeparator();
        _cachedThis = address(this);
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
            return _cachedDomainSeparator;
        } else {
            return _buildDomainSeparator();
        }
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
    }

    /**
     * @dev See {IERC-5267}.
     */
    function eip712Domain()
        public
        view
        virtual
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        )
    {
        return (
            hex"0f", // 01111
            _EIP712Name(),
            _EIP712Version(),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }

    /**
     * @dev The name parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _name which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Name() internal view returns (string memory) {
        return _name.toStringWithFallback(_nameFallback);
    }

    /**
     * @dev The version parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _version which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Version() internal view returns (string memory) {
        return _version.toStringWithFallback(_versionFallback);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)
pragma solidity ^0.8.20;

/**
 * @dev Provides tracking nonces for addresses. Nonces will only increment.
 */
abstract contract Nonces {
    /**
     * @dev The nonce used for an `account` is not the expected current nonce.
     */
    error InvalidAccountNonce(address account, uint256 currentNonce);

    mapping(address account => uint256) private _nonces;

    /**
     * @dev Returns the next unused nonce for an address.
     */
    function nonces(address owner) public view virtual returns (uint256) {
        return _nonces[owner];
    }

    /**
     * @dev Consumes a nonce.
     *
     * Returns the current value and increments nonce.
     */
    function _useNonce(address owner) internal virtual returns (uint256) {
        // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
        // decremented or reset. This guarantees that the nonce never overflows.
        unchecked {
            // It is important to do x++ and not ++x here.
            return _nonces[owner]++;
        }
    }

    /**
     * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
     */
    function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
        uint256 current = _useNonce(owner);
        if (nonce != current) {
            revert InvalidAccountNonce(owner, current);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

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

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @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 or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * 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.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @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`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert FailedInnerCall();
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

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

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event OperatorSet(address indexed owner, address indexed operator, bool approved);

    event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);

    event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                                 FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /// @notice Owner balance of an id.
    /// @param owner The address of the owner.
    /// @param id The id of the token.
    /// @return amount The balance of the token.
    function balanceOf(address owner, uint256 id) external view returns (uint256 amount);

    /// @notice Spender allowance of an id.
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @param id The id of the token.
    /// @return amount The allowance of the token.
    function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);

    /// @notice Checks if a spender is approved by an owner as an operator
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @return approved The approval status.
    function isOperator(address owner, address spender) external view returns (bool approved);

    /// @notice Transfers an amount of an id from the caller to a receiver.
    /// @param receiver The address of the receiver.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always, unless the function reverts
    function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);

    /// @notice Transfers an amount of an id from a sender to a receiver.
    /// @param sender The address of the sender.
    /// @param receiver The address of the receiver.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always, unless the function reverts
    function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);

    /// @notice Approves an amount of an id to a spender.
    /// @param spender The address of the spender.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always
    function approve(address spender, uint256 id, uint256 amount) external returns (bool);

    /// @notice Sets or removes an operator for the caller.
    /// @param operator The address of the operator.
    /// @param approved The approval status.
    /// @return bool True, always
    function setOperator(address operator, bool approved) external returns (bool);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";

/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
    /// @notice Thrown when protocol fee is set too high
    error ProtocolFeeTooLarge(uint24 fee);

    /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
    error InvalidCaller();

    /// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
    error ProtocolFeeCurrencySynced();

    /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
    event ProtocolFeeControllerUpdated(address indexed protocolFeeController);

    /// @notice Emitted when the protocol fee is updated for a pool.
    event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);

    /// @notice Given a currency address, returns the protocol fees accrued in that currency
    /// @param currency The currency to check
    /// @return amount The amount of protocol fees accrued in the currency
    function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);

    /// @notice Sets the protocol fee for the given pool
    /// @param key The key of the pool to set a protocol fee for
    /// @param newProtocolFee The fee to set
    function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;

    /// @notice Sets the protocol fee controller
    /// @param controller The new protocol fee controller
    function setProtocolFeeController(address controller) external;

    /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
    /// @dev This will revert if the contract is unlocked
    /// @param recipient The address to receive the protocol fees
    /// @param currency The currency to withdraw
    /// @param amount The amount of currency to withdraw
    /// @return amountCollected The amount of currency successfully withdrawn
    function collectProtocolFees(address recipient, Currency currency, uint256 amount)
        external
        returns (uint256 amountCollected);

    /// @notice Returns the current protocol fee controller address
    /// @return address The current protocol fee controller address
    function protocolFeeController() external view returns (address);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {PoolKey} from "./PoolKey.sol";

type PoolId is bytes32;

/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
    /// @notice Returns value equal to keccak256(abi.encode(poolKey))
    function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
        assembly ("memory-safe") {
            // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
            poolId := keccak256(poolKey, 0xa0)
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
    /// @notice Called by external contracts to access granular pool state
    /// @param slot Key of slot to sload
    /// @return value The value of the slot as bytes32
    function extsload(bytes32 slot) external view returns (bytes32 value);

    /// @notice Called by external contracts to access granular pool state
    /// @param startSlot Key of slot to start sloading from
    /// @param nSlots Number of slots to load into return value
    /// @return values List of loaded values.
    function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);

    /// @notice Called by external contracts to access sparse pool state
    /// @param slots List of slots to SLOAD from.
    /// @return values List of loaded values.
    function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
    /// @notice Called by external contracts to access transient storage of the contract
    /// @param slot Key of slot to tload
    /// @return value The value of the slot as bytes32
    function exttload(bytes32 slot) external view returns (bytes32 value);

    /// @notice Called by external contracts to access sparse transient pool state
    /// @param slots List of slots to tload
    /// @return values List of loaded values
    function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;

// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
    pure
    returns (BeforeSwapDelta beforeSwapDelta)
{
    assembly ("memory-safe") {
        beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
    }
}

/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
    /// @notice A BeforeSwapDelta of 0
    BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);

    /// extracts int128 from the upper 128 bits of the BeforeSwapDelta
    /// returned by beforeSwap
    function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
        assembly ("memory-safe") {
            deltaSpecified := sar(128, delta)
        }
    }

    /// extracts int128 from the lower 128 bits of the BeforeSwapDelta
    /// returned by beforeSwap and afterSwap
    function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
        assembly ("memory-safe") {
            deltaUnspecified := signextend(15, delta)
        }
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

import {FullMath} from "./FullMath.sol";
import {FixedPoint128} from "./FixedPoint128.sol";
import {LiquidityMath} from "./LiquidityMath.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @title Position
/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary
/// @dev Positions store additional state for tracking fees owed to the position
library Position {
    using CustomRevert for bytes4;

    /// @notice Cannot update a position with no liquidity
    error CannotUpdateEmptyPosition();

    // info stored for each user's position
    struct State {
        // the amount of liquidity owned by this position
        uint128 liquidity;
        // fee growth per unit of liquidity as of the last update to liquidity or fees owed
        uint256 feeGrowthInside0LastX128;
        uint256 feeGrowthInside1LastX128;
    }

    /// @notice Returns the State struct of a position, given an owner and position boundaries
    /// @param self The mapping containing all user positions
    /// @param owner The address of the position owner
    /// @param tickLower The lower tick boundary of the position
    /// @param tickUpper The upper tick boundary of the position
    /// @param salt A unique value to differentiate between multiple positions in the same range
    /// @return position The position info struct of the given owners' position
    function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
        internal
        view
        returns (State storage position)
    {
        bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);
        position = self[positionKey];
    }

    /// @notice A helper function to calculate the position key
    /// @param owner The address of the position owner
    /// @param tickLower the lower tick boundary of the position
    /// @param tickUpper the upper tick boundary of the position
    /// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.
    function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
        internal
        pure
        returns (bytes32 positionKey)
    {
        // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(add(fmp, 0x26), salt) // [0x26, 0x46)
            mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)
            mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)
            mstore(fmp, owner) // [0x0c, 0x20)
            positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes

            // now clean the memory we used
            mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt
            mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt
            mstore(fmp, 0) // fmp held owner
        }
    }

    /// @notice Credits accumulated fees to a user's position
    /// @param self The individual position to update
    /// @param liquidityDelta The change in pool liquidity as a result of the position update
    /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries
    /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries
    /// @return feesOwed0 The amount of currency0 owed to the position owner
    /// @return feesOwed1 The amount of currency1 owed to the position owner
    function update(
        State storage self,
        int128 liquidityDelta,
        uint256 feeGrowthInside0X128,
        uint256 feeGrowthInside1X128
    ) internal returns (uint256 feesOwed0, uint256 feesOwed1) {
        uint128 liquidity = self.liquidity;

        if (liquidityDelta == 0) {
            // disallow pokes for 0 liquidity positions
            if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();
        } else {
            self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);
        }

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

        // update the position
        self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
        self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
    /// @notice Returns an account's balance in the token
    /// @param account The account for which to look up the number of tokens it has, i.e. its balance
    /// @return The number of tokens held by the account
    function balanceOf(address account) external view returns (uint256);

    /// @notice Transfers the amount of token from the `msg.sender` to the recipient
    /// @param recipient The account that will receive the amount transferred
    /// @param amount The number of tokens to send from the sender to the recipient
    /// @return Returns true for a successful transfer, false for an unsuccessful transfer
    function transfer(address recipient, uint256 amount) external returns (bool);

    /// @notice Returns the current allowance given to a spender by an owner
    /// @param owner The account of the token owner
    /// @param spender The account of the token spender
    /// @return The current allowance granted by `owner` to `spender`
    function allowance(address owner, address spender) external view returns (uint256);

    /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
    /// @param spender The account which will be allowed to spend a given amount of the owners tokens
    /// @param amount The amount of tokens allowed to be used by `spender`
    /// @return Returns true for a successful approval, false for unsuccessful
    function approve(address spender, uint256 amount) external returns (bool);

    /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
    /// @param sender The account from which the transfer will be initiated
    /// @param recipient The recipient of the transfer
    /// @param amount The amount of the transfer
    /// @return Returns true for a successful transfer, false for unsuccessful
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
    /// @param from The account from which the tokens were sent, i.e. the balance decreased
    /// @param to The account to which the tokens were sent, i.e. the balance increased
    /// @param value The amount of tokens that were transferred
    event Transfer(address indexed from, address indexed to, uint256 value);

    /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
    /// @param owner The account that approved spending of its tokens
    /// @param spender The account for which the spending allowance was modified
    /// @param value The new allowance from the owner to the spender
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
    /// @dev ERC-7751 error for wrapping bubbled up reverts
    error WrappedError(address target, bytes4 selector, bytes reason, bytes details);

    /// @dev Reverts with the selector of a custom error in the scratch space
    function revertWith(bytes4 selector) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            revert(0, 0x04)
        }
    }

    /// @dev Reverts with a custom error with an address argument in the scratch space
    function revertWith(bytes4 selector, address addr) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with an int24 argument in the scratch space
    function revertWith(bytes4 selector, int24 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, signextend(2, value))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with a uint160 argument in the scratch space
    function revertWith(bytes4 selector, uint160 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with two int24 arguments
    function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), signextend(2, value1))
            mstore(add(fmp, 0x24), signextend(2, value2))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two uint160 arguments
    function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two address arguments
    function revertWith(bytes4 selector, address value1, address value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
    /// @dev this method can be vulnerable to revert data bombs
    function bubbleUpAndRevertWith(
        address revertingContract,
        bytes4 revertingFunctionSelector,
        bytes4 additionalContext
    ) internal pure {
        bytes4 wrappedErrorSelector = WrappedError.selector;
        assembly ("memory-safe") {
            // Ensure the size of the revert data is a multiple of 32 bytes
            let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)

            let fmp := mload(0x40)

            // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
            mstore(fmp, wrappedErrorSelector)
            mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(
                add(fmp, 0x24),
                and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            // offset revert reason
            mstore(add(fmp, 0x44), 0x80)
            // offset additional context
            mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
            // size revert reason
            mstore(add(fmp, 0x84), returndatasize())
            // revert reason
            returndatacopy(add(fmp, 0xa4), 0, returndatasize())
            // size additional context
            mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
            // additional context
            mstore(
                add(fmp, add(0xc4, encodedDataSize)),
                and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            revert(fmp, add(0xe4, encodedDataSize))
        }
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

import {Currency} from "../types/Currency.sol";
import {CustomRevert} from "./CustomRevert.sol";

library CurrencyReserves {
    using CustomRevert for bytes4;

    /// bytes32(uint256(keccak256("ReservesOf")) - 1)
    bytes32 constant RESERVES_OF_SLOT = 0x1e0745a7db1623981f0b2a5d4232364c00787266eb75ad546f190e6cebe9bd95;
    /// bytes32(uint256(keccak256("Currency")) - 1)
    bytes32 constant CURRENCY_SLOT = 0x27e098c505d44ec3574004bca052aabf76bd35004c182099d8c575fb238593b9;

    function getSyncedCurrency() internal view returns (Currency currency) {
        assembly ("memory-safe") {
            currency := tload(CURRENCY_SLOT)
        }
    }

    function resetCurrency() internal {
        assembly ("memory-safe") {
            tstore(CURRENCY_SLOT, 0)
        }
    }

    function syncCurrencyAndReserves(Currency currency, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(CURRENCY_SLOT, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
            tstore(RESERVES_OF_SLOT, value)
        }
    }

    function getSyncedReserves() internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(RESERVES_OF_SLOT)
        }
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)
/// for the nonzero delta count.
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library NonzeroDeltaCount {
    // The slot holding the number of nonzero deltas. bytes32(uint256(keccak256("NonzeroDeltaCount")) - 1)
    bytes32 internal constant NONZERO_DELTA_COUNT_SLOT =
        0x7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b;

    function read() internal view returns (uint256 count) {
        assembly ("memory-safe") {
            count := tload(NONZERO_DELTA_COUNT_SLOT)
        }
    }

    function increment() internal {
        assembly ("memory-safe") {
            let count := tload(NONZERO_DELTA_COUNT_SLOT)
            count := add(count, 1)
            tstore(NONZERO_DELTA_COUNT_SLOT, count)
        }
    }

    /// @notice Potential to underflow. Ensure checks are performed by integrating contracts to ensure this does not happen.
    /// Current usage ensures this will not happen because we call decrement with known boundaries (only up to the number of times we call increment).
    function decrement() internal {
        assembly ("memory-safe") {
            let count := tload(NONZERO_DELTA_COUNT_SLOT)
            count := sub(count, 1)
            tstore(NONZERO_DELTA_COUNT_SLOT, count)
        }
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library Lock {
    // The slot holding the unlocked state, transiently. bytes32(uint256(keccak256("Unlocked")) - 1)
    bytes32 internal constant IS_UNLOCKED_SLOT = 0xc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab23;

    function unlock() internal {
        assembly ("memory-safe") {
            // unlock
            tstore(IS_UNLOCKED_SLOT, true)
        }
    }

    function lock() internal {
        assembly ("memory-safe") {
            tstore(IS_UNLOCKED_SLOT, false)
        }
    }

    function isUnlocked() internal view returns (bool unlocked) {
        assembly ("memory-safe") {
            unlocked := tload(IS_UNLOCKED_SLOT)
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
    /// @notice Returns the index of the most significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @param x the value for which to compute the most significant bit, must be greater than 0
    /// @return r the index of the most significant bit
    function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        assembly ("memory-safe") {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0x0706060506020500060203020504000106050205030304010505030400000000))
        }
    }

    /// @notice Returns the index of the least significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @param x the value for which to compute the least significant bit, must be greater than 0
    /// @return r the index of the least significant bit
    function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        assembly ("memory-safe") {
            // Isolate the least significant bit.
            x := and(x, sub(0, x))
            // For the upper 3 bits of the result, use a De Bruijn-like lookup.
            // Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
            // forgefmt: disable-next-item
            r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
                0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
                0x8040405543005266443200005020610674053026020000107506200176117077)))
            // For the lower 5 bits of the result, use a De Bruijn lookup.
            // forgefmt: disable-next-item
            r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
                0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @notice Interface for the callback executed when an address unlocks the pool manager
interface IUnlockCallback {
    /// @notice Called by the pool manager on `msg.sender` when the manager is unlocked
    /// @param data The data that was passed to the call to unlock
    /// @return Any data that you want to be returned from the unlock call
    function unlockCallback(bytes calldata data) external returns (bytes memory);
}

File 46 of 58 : ImmutableState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IImmutableState} from "../interfaces/IImmutableState.sol";

/// @title Immutable State
/// @notice A collection of immutable state variables, commonly used across multiple contracts
contract ImmutableState is IImmutableState {
    /// @inheritdoc IImmutableState
    IPoolManager public immutable poolManager;

    constructor(IPoolManager _poolManager) {
        poolManager = _poolManager;
    }
}

File 47 of 58 : IImmutableState.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";

/// @title Interface for ImmutableState
interface IImmutableState {
    /// @notice The Uniswap v4 PoolManager contract
    function poolManager() external view returns (IPoolManager);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {Currency} from "../../src/types/Currency.sol";
import {IERC20Minimal} from "../../src/interfaces/external/IERC20Minimal.sol";
import {IPoolManager} from "../../src/interfaces/IPoolManager.sol";

/// @notice Library used to interact with PoolManager.sol to settle any open deltas.
/// To settle a positive delta (a credit to the user), a user may take or mint.
/// To settle a negative delta (a debt on the user), a user make transfer or burn to pay off a debt.
/// @dev Note that sync() is called before any erc-20 transfer in `settle`.
library CurrencySettler {
    /// @notice Settle (pay) a currency to the PoolManager
    /// @param currency Currency to settle
    /// @param manager IPoolManager to settle to
    /// @param payer Address of the payer, the token sender
    /// @param amount Amount to send
    /// @param burn If true, burn the ERC-6909 token, otherwise ERC20-transfer to the PoolManager
    function settle(Currency currency, IPoolManager manager, address payer, uint256 amount, bool burn) internal {
        // for native currencies or burns, calling sync is not required
        // short circuit for ERC-6909 burns to support ERC-6909-wrapped native tokens
        if (burn) {
            manager.burn(payer, currency.toId(), amount);
        } else if (currency.isAddressZero()) {
            manager.settle{value: amount}();
        } else {
            manager.sync(currency);
            if (payer != address(this)) {
                IERC20Minimal(Currency.unwrap(currency)).transferFrom(payer, address(manager), amount);
            } else {
                IERC20Minimal(Currency.unwrap(currency)).transfer(address(manager), amount);
            }
            manager.settle();
        }
    }

    /// @notice Take (receive) a currency from the PoolManager
    /// @param currency Currency to take
    /// @param manager IPoolManager to take from
    /// @param recipient Address of the recipient, the token receiver
    /// @param amount Amount to receive
    /// @param claims If true, mint the ERC-6909 token, otherwise ERC20-transfer from the PoolManager to recipient
    function take(Currency currency, IPoolManager manager, address recipient, uint256 amount, bool claims) internal {
        claims ? manager.mint(recipient, currency.toId(), amount) : manager.take(currency, recipient, amount);
    }
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

import "../../src/libraries/FullMath.sol";
import "../../src/libraries/FixedPoint96.sol";

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

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

    /// @notice Computes the amount of liquidity received for a given amount of token1 and price range
    /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
    /// @param amount1 The amount1 being sent in
    /// @return liquidity The amount of returned liquidity
    function getLiquidityForAmount1(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount1)
        internal
        pure
        returns (uint128 liquidity)
    {
        if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
        return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtPriceBX96 - sqrtPriceAX96));
    }

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

        if (sqrtPriceX96 <= sqrtPriceAX96) {
            liquidity = getLiquidityForAmount0(sqrtPriceAX96, sqrtPriceBX96, amount0);
        } else if (sqrtPriceX96 < sqrtPriceBX96) {
            uint128 liquidity0 = getLiquidityForAmount0(sqrtPriceX96, sqrtPriceBX96, amount0);
            uint128 liquidity1 = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceX96, amount1);

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

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

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

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

        return FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);
    }

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

        if (sqrtPriceX96 <= sqrtPriceAX96) {
            amount0 = getAmount0ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
        } else if (sqrtPriceX96 < sqrtPriceBX96) {
            amount0 = getAmount0ForLiquidity(sqrtPriceX96, sqrtPriceBX96, liquidity);
            amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceX96, liquidity);
        } else {
            amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)

pragma solidity ^0.8.20;

import {Strings} from "../Strings.sol";

/**
 * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
 *
 * The library provides methods for generating a hash of a message that conforms to the
 * https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
 * specifications.
 */
library MessageHashUtils {
    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing a bytes32 `messageHash` with
     * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
     * keccak256, although any bytes32 value can be safely used because the final digest will
     * be re-hashed.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing an arbitrary `message` with
     * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
        return
            keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x00` (data with intended validator).
     *
     * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
     * `validator` address. Then hashing the result.
     *
     * See {ECDSA-recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(hex"19_00", validator, data));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
     *
     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
     * `\x19\x01` and hashing the result. It corresponds to the hash signed by the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
     *
     * See {ECDSA-recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, hex"19_01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            digest := keccak256(ptr, 0x42)
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ShortStrings.sol)

pragma solidity ^0.8.20;

import {StorageSlot} from "./StorageSlot.sol";

// | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
// | length  | 0x                                                              BB |
type ShortString is bytes32;

/**
 * @dev This library provides functions to convert short memory strings
 * into a `ShortString` type that can be used as an immutable variable.
 *
 * Strings of arbitrary length can be optimized using this library if
 * they are short enough (up to 31 bytes) by packing them with their
 * length (1 byte) in a single EVM word (32 bytes). Additionally, a
 * fallback mechanism can be used for every other case.
 *
 * Usage example:
 *
 * ```solidity
 * contract Named {
 *     using ShortStrings for *;
 *
 *     ShortString private immutable _name;
 *     string private _nameFallback;
 *
 *     constructor(string memory contractName) {
 *         _name = contractName.toShortStringWithFallback(_nameFallback);
 *     }
 *
 *     function name() external view returns (string memory) {
 *         return _name.toStringWithFallback(_nameFallback);
 *     }
 * }
 * ```
 */
library ShortStrings {
    // Used as an identifier for strings longer than 31 bytes.
    bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;

    error StringTooLong(string str);
    error InvalidShortString();

    /**
     * @dev Encode a string of at most 31 chars into a `ShortString`.
     *
     * This will trigger a `StringTooLong` error is the input string is too long.
     */
    function toShortString(string memory str) internal pure returns (ShortString) {
        bytes memory bstr = bytes(str);
        if (bstr.length > 31) {
            revert StringTooLong(str);
        }
        return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
    }

    /**
     * @dev Decode a `ShortString` back to a "normal" string.
     */
    function toString(ShortString sstr) internal pure returns (string memory) {
        uint256 len = byteLength(sstr);
        // using `new string(len)` would work locally but is not memory safe.
        string memory str = new string(32);
        /// @solidity memory-safe-assembly
        assembly {
            mstore(str, len)
            mstore(add(str, 0x20), sstr)
        }
        return str;
    }

    /**
     * @dev Return the length of a `ShortString`.
     */
    function byteLength(ShortString sstr) internal pure returns (uint256) {
        uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
        if (result > 31) {
            revert InvalidShortString();
        }
        return result;
    }

    /**
     * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
     */
    function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
        if (bytes(value).length < 32) {
            return toShortString(value);
        } else {
            StorageSlot.getStringSlot(store).value = value;
            return ShortString.wrap(FALLBACK_SENTINEL);
        }
    }

    /**
     * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
     */
    function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return toString(value);
        } else {
            return store;
        }
    }

    /**
     * @dev Return the length of a string that was encoded to `ShortString` or written to storage using
     * {setWithFallback}.
     *
     * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
     * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
     */
    function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return byteLength(value);
        } else {
            return bytes(store).length;
        }
    }
}

File 54 of 58 : IERC5267.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)

pragma solidity ^0.8.20;

interface IERC5267 {
    /**
     * @dev MAY be emitted to signal that the domain could have changed.
     */
    event EIP712DomainChanged();

    /**
     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
     * signature.
     */
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title Math library for liquidity
library LiquidityMath {
    /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
    /// @param x The liquidity before change
    /// @param y The delta by which liquidity should be changed
    /// @return z The liquidity delta
    function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
        assembly ("memory-safe") {
            z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))
            if shr(128, z) {
                // revert SafeCastOverflow()
                mstore(0, 0x93dafdf1)
                revert(0x1c, 0x04)
            }
        }
    }
}

File 56 of 58 : FixedPoint96.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}

Settings
{
  "remappings": [
    "@ensdomains/=lib/v4-periphery/lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "@openzeppelin/contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/",
    "@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
    "ds-test/=lib/v4-periphery/lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-periphery/lib/forge-gas-snapshot/src/",
    "forge-std/=lib/forge-std/src/",
    "hardhat/=lib/v4-periphery/lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
    "v4-core/=lib/v4-periphery/lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 800
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": false,
  "libraries": {
    "src/PoolManagerUtils.sol": {
      "PoolManagerUtils": "0x9b617736CD4033611b905E2D1c736eB9d1f153ac"
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"contract IPoolManager","name":"_poolManager","type":"address"},{"internalType":"address","name":"_token0","type":"address"},{"internalType":"address","name":"_token1","type":"address"},{"internalType":"address","name":"_owner","type":"address"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"CurrencyDeltaError","type":"error"},{"inputs":[{"components":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"int24","name":"lowerTick","type":"int24"},{"internalType":"int24","name":"upperTick","type":"int24"}],"internalType":"struct IMultiPositionManager.Position","name":"position","type":"tuple"}],"name":"DuplicatedPosition","type":"error"},{"inputs":[],"name":"ECDSAInvalidSignature","type":"error"},{"inputs":[{"internalType":"uint256","name":"length","type":"uint256"}],"name":"ECDSAInvalidSignatureLength","type":"error"},{"inputs":[{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"ECDSAInvalidSignatureS","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"allowance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientAllowance","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC20InvalidApprover","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC20InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC20InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"}],"name":"ERC20InvalidSpender","type":"error"},{"inputs":[{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"ERC2612ExpiredSignature","type":"error"},{"inputs":[{"internalType":"address","name":"signer","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"ERC2612InvalidSigner","type":"error"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"currentNonce","type":"uint256"}],"name":"InvalidAccountNonce","type":"error"},{"inputs":[],"name":"InvalidAction","type":"error"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"InvalidDepositAmount","type":"error"},{"inputs":[],"name":"InvalidFee","type":"error"},{"inputs":[],"name":"InvalidPoolKeyTokens","type":"error"},{"inputs":[],"name":"InvalidRebalanceParams","type":"error"},{"inputs":[],"name":"InvalidShortString","type":"error"},{"inputs":[],"name":"InvalidTickRange","type":"error"},{"inputs":[],"name":"NotANativeTokenPair","type":"error"},{"inputs":[],"name":"NotPoolManager","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[{"internalType":"string","name":"str","type":"string"}],"name":"StringTooLong","type":"error"},{"inputs":[],"name":"TickOffsetExceeded","type":"error"},{"inputs":[],"name":"WhitelistedAddress","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"inputs":[],"name":"ZeroValue","type":"error"},{"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":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"deposit0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"deposit1","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[],"name":"EIP712DomainChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint16","name":"newFee","type":"uint16"}],"name":"FeeChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"totalAmount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalAmount1","type":"uint256"}],"name":"LogTotalAmounts","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"components":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"int24","name":"lowerTick","type":"int24"},{"internalType":"int24","name":"upperTick","type":"int24"}],"indexed":false,"internalType":"struct IMultiPositionManager.Position[]","name":"","type":"tuple[]"}],"name":"Rebalance","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"Withdraw","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","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":"uint256","name":"","type":"uint256"}],"name":"basePositions","outputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"int24","name":"lowerTick","type":"int24"},{"internalType":"int24","name":"upperTick","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"basePositionsLength","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"claimFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint128[]","name":"liquidities","type":"uint128[]"},{"internalType":"uint256[2][]","name":"inMin","type":"uint256[2][]"},{"internalType":"int24","name":"aimTick","type":"int24"},{"internalType":"uint24","name":"tickOffset","type":"uint24"}],"name":"compound","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"}],"name":"currentTick","outputs":[{"internalType":"int24","name":"tick","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currentTicks","outputs":[{"internalType":"int24[]","name":"ticks","type":"int24[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"deposit0Desired","type":"uint256"},{"internalType":"uint256","name":"deposit1Desired","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"address","name":"from","type":"address"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"uint256","name":"deposit0","type":"uint256"},{"internalType":"uint256","name":"deposit1","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"eip712Domain","outputs":[{"internalType":"bytes1","name":"fields","type":"bytes1"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"version","type":"string"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"verifyingContract","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256[]","name":"extensions","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"fee","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPositions","outputs":[{"components":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"int24","name":"lowerTick","type":"int24"},{"internalType":"int24","name":"upperTick","type":"int24"}],"internalType":"struct IMultiPositionManager.Position[]","name":"","type":"tuple[]"},{"components":[{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"internalType":"struct IMultiPositionManager.PositionData[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTotalAmounts","outputs":[{"internalType":"uint256","name":"total0","type":"uint256"},{"internalType":"uint256","name":"total1","type":"uint256"},{"internalType":"uint256","name":"totalFee0","type":"uint256"},{"internalType":"uint256","name":"totalFee1","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"limitPositions","outputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"int24","name":"lowerTick","type":"int24"},{"internalType":"int24","name":"upperTick","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"poolManager","outputs":[{"internalType":"contract IPoolManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"_poolKey","type":"tuple"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint256[2]","name":"outMin","type":"uint256[2]"}],"name":"pullLiquidity","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"int24","name":"lowerTick","type":"int24"},{"internalType":"int24","name":"upperTick","type":"int24"}],"internalType":"struct IMultiPositionManager.Position[]","name":"baseRanges","type":"tuple[]"},{"internalType":"uint128[]","name":"liquidities","type":"uint128[]"},{"internalType":"int24","name":"limitWidth","type":"int24"},{"internalType":"uint256[2][]","name":"inMin","type":"uint256[2][]"},{"internalType":"uint256[2][]","name":"outMin","type":"uint256[2][]"},{"internalType":"int24","name":"aimTick","type":"int24"},{"internalType":"uint24","name":"tickOffset","type":"uint24"}],"name":"rebalance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"newFee","type":"uint16"}],"name":"setFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_feeRecipient","type":"address"}],"name":"setFeeRecipient","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_whitelistedAddress","type":"address"}],"name":"setWhitelist","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"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":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"unlockCallback","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"whitelistedAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256[2][]","name":"outMin","type":"uint256[2][]"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"zeroBurnAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

610180604052348015610010575f80fd5b5060405161633538038061633583398101604081905261002f91610368565b8580848480604051806040016040528060018152602001603160f81b8152508787816003908161005f919061049c565b50600461006c828261049c565b5061007c915083905060056101f4565b6101205261008b8160066101f4565b61014052815160208084019190912060e052815190820120610100524660a05261011760e05161010051604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201529081019290925260608201524660808201523060a08201525f9060c00160405160208183030381529060405280519060200120905090565b60805250503060c0525060016008556001600160a01b03811661015457604051631e4fbdf760e01b81525f60048201526024015b60405180910390fd5b61015d81610226565b506001600160a01b03908116610160526009805460ff60a01b191690558416905061019b5760405163d92e233d60e01b815260040160405180910390fd5b5050600a80546001600160a01b039485166001600160a01b031991821617909155600b80549385169382169390931790925560168054919093169116179055506017805461ffff60a01b1916600160a01b1790556105ae565b5f60208351101561020f5761020883610277565b9050610220565b8161021a848261049c565b5060ff90505b92915050565b600980546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b5f80829050601f815111156102a1578260405163305a27a960e01b815260040161014b9190610556565b80516102ac8261058b565b179392505050565b6001600160a01b03811681146102c8575f80fd5b50565b634e487b7160e01b5f52604160045260245ffd5b5f82601f8301126102ee575f80fd5b81516001600160401b03811115610307576103076102cb565b604051601f8201601f19908116603f011681016001600160401b0381118282101715610335576103356102cb565b60405281815283820160200185101561034c575f80fd5b8160208501602083015e5f918101602001919091529392505050565b5f805f805f8060c0878903121561037d575f80fd5b8651610388816102b4565b6020880151909650610399816102b4565b60408801519095506103aa816102b4565b60608801519094506103bb816102b4565b60808801519093506001600160401b038111156103d6575f80fd5b6103e289828a016102df565b60a089015190935090506001600160401b038111156103ff575f80fd5b61040b89828a016102df565b9150509295509295509295565b600181811c9082168061042c57607f821691505b60208210810361044a57634e487b7160e01b5f52602260045260245ffd5b50919050565b601f82111561049757805f5260205f20601f840160051c810160208510156104755750805b601f840160051c820191505b81811015610494575f8155600101610481565b50505b505050565b81516001600160401b038111156104b5576104b56102cb565b6104c9816104c38454610418565b84610450565b6020601f8211600181146104fb575f83156104e45750848201515b5f19600385901b1c1916600184901b178455610494565b5f84815260208120601f198516915b8281101561052a578785015182556020948501946001909201910161050a565b508482101561054757868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b602081525f82518060208401528060208501604085015e5f604082850101526040601f19601f83011684010191505092915050565b8051602080830151919081101561044a575f1960209190910360031b1b16919050565b60805160a05160c05160e05161010051610120516101405161016051615c926106a35f395f818161084901528181610a2201528181610b7601528181610d4e0152818161117c0152818161135f015281816117c5015281816118e0015281816119cd01528181611a36015281816121200152818161298701528181612a7201528181612b470152818161364001528181613752015281816137e301528181613aba01528181613b780152818161404e015281816140aa0152818161416a015261424001525f6127bd01525f61279001525f6120a401525f61207c01525f611fd701525f61200101525f61202b0152615c925ff3fe6080604052600436106102cf575f3560e01c806384715b111161017b57806399d32fc4116100d1578063d505accf11610087578063ddca3f4311610062578063ddca3f43146108af578063e74b981b146108e3578063f2fde38b14610902575f80fd5b8063d505accf14610819578063dc4c90d314610838578063dd62ed3e1461086b575f80fd5b8063b079f163116100b7578063b079f163146107a7578063c4a7761e146107c8578063d21220a7146107fc575f80fd5b806399d32fc414610774578063a9059cbb14610788575f80fd5b80638c4be77a1161013157806390d082e91161010c57806390d082e9146106a957806391dd73461461074157806395d89b4114610760575f80fd5b80638c4be77a1461063b5780638da5cb5b1461066d5780638e0055531461068a575f80fd5b8063854cff2f11610161578063854cff2f146105de57806386a29081146105fd5780638bd9ddb81461061c575f80fd5b806384715b111461058957806384b0196e146105b7575f80fd5b80633f4ba83a1161023057806370a08231116101e65780637ecebe00116101c15780637ecebe001461053457806380275860146105535780638456cb5914610575575f80fd5b806370a08231146104b8578063715018a6146104ec578063759f237214610500575f80fd5b80635c975abb116102165780635c975abb1461044d5780635d0885851461046b578063689b5f4f1461048a575f80fd5b80633f4ba83a1461041a578063469048401461042e575f80fd5b806323b872dd11610285578063313ce5671161026b578063313ce567146103d75780633644e515146103f2578063376c548714610406575f80fd5b806323b872dd1461039757806326f622ec146103b6575f80fd5b8063095ea7b3116102b5578063095ea7b3146103235780630dfe16811461035257806318160ddd14610383575f80fd5b806303e78281146102da57806306fdde0314610302575f80fd5b366102d657005b5f80fd5b3480156102e5575f80fd5b506102ef600c5481565b6040519081526020015b60405180910390f35b34801561030d575f80fd5b50610316610921565b6040516102f99190614605565b34801561032e575f80fd5b5061034261033d36600461462b565b6109b1565b60405190151581526020016102f9565b34801561035d575f80fd5b50600a546001600160a01b03165b6040516001600160a01b0390911681526020016102f9565b34801561038e575f80fd5b506002546102ef565b3480156103a2575f80fd5b506103426103b1366004614655565b6109ca565b3480156103c1575f80fd5b506103d56103d0366004614820565b6109ef565b005b3480156103e2575f80fd5b50604051601281526020016102f9565b3480156103fd575f80fd5b506102ef610ad8565b348015610411575f80fd5b506103d5610ae6565b348015610425575f80fd5b506103d5610b2d565b348015610439575f80fd5b5060165461036b906001600160a01b031681565b348015610458575f80fd5b50600954600160a01b900460ff16610342565b348015610476575f80fd5b506103d5610485366004614987565b610b3d565b348015610495575f80fd5b506104a96104a4366004614a10565b610c34565b6040516102f993929190614a27565b3480156104c3575f80fd5b506102ef6104d2366004614a9d565b6001600160a01b03165f9081526020819052604090205490565b3480156104f7575f80fd5b506103d5610cbc565b34801561050b575f80fd5b5061051f61051a366004614ab8565b610ccd565b604080519283526020830191909152016102f9565b34801561053f575f80fd5b506102ef61054e366004614a9d565b610f62565b34801561055e575f80fd5b50610567610f7f565b6040516102f9929190614bc9565b348015610580575f80fd5b506103d5611476565b61059c610597366004614c3a565b611486565b604080519384526020840192909252908201526060016102f9565b3480156105c2575f80fd5b506105cb611604565b6040516102f99796959493929190614c76565b3480156105e9575f80fd5b506103d56105f8366004614a9d565b611646565b348015610608575f80fd5b5060175461036b906001600160a01b031681565b348015610627575f80fd5b506103d5610636366004614db0565b611670565b348015610646575f80fd5b5061065a610655366004614e99565b6118c7565b60405160029190910b81526020016102f9565b348015610678575f80fd5b506009546001600160a01b031661036b565b348015610695575f80fd5b506103d56106a4366004614eb3565b611910565b3480156106b4575f80fd5b506104a96106c3366004614a10565b600d60209081525f918252604091829020825160a08101845281546001600160a01b03908116825260018301548082169483019490945262ffffff600160a01b85041694820194909452600160b81b909204600290810b606084015280820154909316608083015260030154909181810b9163010000009004900b83565b34801561074c575f80fd5b5061031661075b366004614ed4565b6119c0565b34801561076b575f80fd5b50610316611a15565b34801561077f575f80fd5b506103d5611a24565b348015610793575f80fd5b506103426107a236600461462b565b611ae5565b3480156107b2575f80fd5b506107bb611af2565b6040516102f99190614f42565b3480156107d3575f80fd5b506107dc611ce9565b6040805194855260208501939093529183015260608201526080016102f9565b348015610807575f80fd5b50600b546001600160a01b031661036b565b348015610824575f80fd5b506103d5610833366004614f7c565b611d03565b348015610843575f80fd5b5061036b7f000000000000000000000000000000000000000000000000000000000000000081565b348015610876575f80fd5b506102ef610885366004614fed565b6001600160a01b039182165f90815260016020908152604080832093909416825291909152205490565b3480156108ba575f80fd5b506017546108d090600160a01b900461ffff1681565b60405161ffff90911681526020016102f9565b3480156108ee575f80fd5b506103d56108fd366004614a9d565b611e3e565b34801561090d575f80fd5b506103d561091c366004614a9d565b611e7a565b60606003805461093090615024565b80601f016020809104026020016040519081016040528092919081815260200182805461095c90615024565b80156109a75780601f1061097e576101008083540402835291602001916109a7565b820191905f5260205f20905b81548152906001019060200180831161098a57829003601f168201915b5050505050905090565b5f336109be818585611eb4565b60019150505b92915050565b5f336109d7858285611ec6565b6109e2858585611f41565b60019150505b9392505050565b6109f7611f9e565b5f84848484604051602001610a0f949392919061507e565b60405160208183030381529060405290507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166348c89491600483604051602001610a6392919061512e565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401610a8e9190614605565b5f604051808303815f875af1158015610aa9573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610ad0919081019061517c565b505050505050565b5f610ae1611fcb565b905090565b610aee6120f4565b6017546001600160a01b03163314610b19576040516361a2001160e11b815260040160405180910390fd5b610b2161211e565b610b2b6001600855565b565b610b35611f9e565b610b2b61215f565b610b45611f9e565b610b4f82826121b4565b5f8484604051602001610b63929190615265565b60405160208183030381529060405290507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166348c89491600283604051602001610bb792919061512e565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401610be29190614605565b5f604051808303815f875af1158015610bfd573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610c24919081019061517c565b50610c2d61227c565b5050505050565b600e8160028110610c43575f80fd5b6040805160a0810182526004929092029290920180546001600160a01b0390811683526001820154808216602085015262ffffff600160a01b82041694840194909452600160b81b909304600290810b60608401528082015490931660808301526003015490925080820b916301000000909104900b83565b610cc4611f9e565b610b2b5f6122cb565b5f80610cd76120f4565b610cdf61231c565b845f03610cff57604051637c946ed760e01b815260040160405180910390fd5b6001600160a01b038416610d265760405163d92e233d60e01b815260040160405180910390fd5b5f8584604051602001610d3a929190615289565b60405160208183030381529060405290505f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166348c894915f84604051602001610d8e92919061512e565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401610db99190614605565b5f604051808303815f875af1158015610dd4573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610dfb919081019061517c565b905080806020019051810190610e1191906152a1565b600a549195509350610e2d906001600160a01b03168786612347565b600b54610e44906001600160a01b03168785612347565b600a545f90610e6e90610e5f906001600160a01b03166123e6565b89610e6960025490565b612467565b600b549091505f90610e9690610e8c906001600160a01b03166123e6565b8a610e6960025490565b90508115610ec257610ea882876152d7565b600a54909650610ec2906001600160a01b03168984612347565b8015610eec57610ed281866152d7565b600b54909550610eec906001600160a01b03168983612347565b610ef6338a612503565b604080518a8152602081018890529081018690526001600160a01b0389169033907febff2602b3f468259e1e99f613fed6691f3a6526effe6ef3e768ba7ae7a36c4f9060600160405180910390a3610f4c61227c565b50505050610f5a6001600855565b935093915050565b6001600160a01b0381165f908152600760205260408120546109c4565b6060805f600c546002610f9291906152d7565b67ffffffffffffffff811115610faa57610faa614693565b60405190808252806020026020018201604052801561101657816020015b60408051610100810182525f606082018181526080830182905260a0830182905260c0830182905260e08301829052825260208083018290529282015282525f19909201910181610fc85790505b5090505f600c54600261102991906152d7565b67ffffffffffffffff81111561104157611041614693565b60405190808252806020026020018201604052801561109c57816020015b61108960405180606001604052805f6001600160801b031681526020015f81526020015f81525090565b81526020019060019003908161105f5790505b5090505f8080805b600c548160ff16101561126c5760ff81165f818152600d602090815260409182902082516101008101845281546001600160a01b03908116606083019081526001840154808316608085015262ffffff600160a01b82041660a0850152600160b81b9004600290810b60c08501528085015490921660e0840152825260039092015480830b938201939093526301000000909204900b918101919091528751909188918110611155576111556152ea565b6020026020010181905250739b617736cd4033611b905e2d1c736eb9d1f153ac638363b4e87f0000000000000000000000000000000000000000000000000000000000000000888460ff16815181106111b0576111b06152ea565b60200260200101516040518363ffffffff1660e01b81526004016111d59291906152fe565b60a060405180830381865af41580156111f0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611214919061531c565b5050604080516060810182526001600160801b0385168152602081018490529081018290528851939750919550935090869060ff8416908110611259576112596152ea565b60209081029190910101526001016110a4565b505f5b60028160ff16101561146857600e8160ff1660028110611291576112916152ea565b60408051610100810182526004929092029290920180546001600160a01b03908116606084019081526001830154808316608086015262ffffff600160a01b82041660a0860152600160b81b9004600290810b60c08601528084015490921660e0850152835260039091015480820b602084015263010000009004900b91810191909152600c5487906113289060ff8516906152d7565b81518110611338576113386152ea565b6020026020010181905250739b617736cd4033611b905e2d1c736eb9d1f153ac638363b4e87f0000000000000000000000000000000000000000000000000000000000000000888460ff16600c5461139091906152d7565b815181106113a0576113a06152ea565b60200260200101516040518363ffffffff1660e01b81526004016113c59291906152fe565b60a060405180830381865af41580156113e0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611404919061531c565b5050604080516060810182526001600160801b038516815260208101849052908101829052600c5493975091955093509086906114459060ff8516906152d7565b81518110611455576114556152ea565b602090810291909101015260010161126f565b509396929550919350505050565b61147e611f9e565b610b2b61253b565b5f805f6114916120f4565b61149961231c565b6001600160a01b03851615806114b757506001600160a01b03851630145b156114d55760405163d92e233d60e01b815260040160405180910390fd5b6017546001600160a01b03163314611500576040516361a2001160e11b815260040160405180910390fd5b600a546001600160a01b03161515801561151957505f34115b1561153757604051631ab026e960e31b815260040160405180910390fd5b61153f61211e565b611549878761257e565b919450925090508261155d5761155d615361565b600a546115759085906001600160a01b0316846126c7565b600b5461158d9085906001600160a01b0316836126c7565b6115978584612755565b60408051848152602081018490529081018290526001600160a01b0380871691908616907f4e2ca0515ed1aef1395f66b5303bb5d6f1bf9d61a353fa53f73f8ac9973fa9f69060600160405180910390a36115f061227c565b6115fa6001600855565b9450945094915050565b5f6060805f805f6060611615612789565b61161d6127b6565b604080515f80825260208201909252600f60f81b9b939a50919850469750309650945092509050565b61164e611f9e565b601780546001600160a01b0319166001600160a01b0392909216919091179055565b6116786120f4565b611680611f9e565b5f5b87518160ff16101561174d57600a546001600160a01b03166116cb898360ff16815181106116b2576116b26152ea565b602090810291909101015151516001600160a01b031690565b14158061171e5750600b546001600160a01b031661171b898360ff16815181106116f7576116f76152ea565b60200260200101515f0151602001516001600160a01b03166001600160a01b031690565b14155b1561173b5760405162de216b60e01b815260040160405180910390fd5b8061174581615375565b915050611682565b506117598783836127e3565b8651845114158061176c57508651865114155b8061177a5750600c54835114155b156117985760405163483cb4ab60e11b815260040160405180910390fd5b5f87878787876040516020016117b2959493929190615393565b60405160208183030381529060405290507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166348c8949160018360405160200161180692919061512e565b6040516020818303038152906040526040518263ffffffff1660e01b81526004016118319190614605565b5f604051808303815f875af115801561184c573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611873919081019061517c565b507fda82109922c7702ec52698db387bdfa93c21de784b25f20b35bd750b7b510d95886040516118a391906153f4565b60405180910390a16118b361227c565b506118be6001600855565b50505050505050565b5f6119066118d68360a0902090565b6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169061284a565b5090949350505050565b611918611f9e565b6017546001600160a01b90910461ffff161015611948576040516358d620b360e01b815260040160405180910390fd5b61195061211e565b601780547fffffffffffffffffffff0000ffffffffffffffffffffffffffffffffffffffff16600160a01b61ffff8416908102919091179091556040519081527f931a978d852c1b6fa9dd97300fd89c773ff625b91f697b0911e943ba15f9e2439060200160405180910390a150565b6060336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614611a0b5760405163570c108560e11b815260040160405180910390fd5b6109e883836128fc565b60606004805461093090615024565b611a2c611f9e565b611a3461211e565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166348c894916005604051602001611a759190615406565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401611aa09190614605565b5f604051808303815f875af1158015611abb573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611ae2919081019061517c565b50565b5f336109be818585611f41565b6060600c545f03611b0f5750604080515f81526020810190915290565b600c54611b1d9060026152d7565b67ffffffffffffffff811115611b3557611b35614693565b604051908082528060200260200182016040528015611b5e578160200160208202803683370190505b5090505f5b600c548160ff161015611c135760ff81165f908152600d6020908152604091829020825160a08101845281546001600160a01b03908116825260018301548082169483019490945262ffffff600160a01b85041694820194909452600160b81b909204600290810b606084015201549091166080820152611be3906118c7565b828260ff1681518110611bf857611bf86152ea565b60029290920b60209283029190910190910152600101611b63565b50611c7f600e5f5b6040805160a0810182526004929092029290920180546001600160a01b0390811683526001820154808216602085015262ffffff600160a01b82041694840194909452600160b81b909304600290810b6060840152015490911660808201526118c7565b81600c5481518110611c9357611c936152ea565b60029290920b60209283029190910190910152611cb2600e6001611c1b565b81600c546001611cc291906152d7565b81518110611cd257611cd26152ea565b602002602001019060020b908160020b8152505090565b5f805f80611cf561292e565b935093509350935090919293565b83421115611d2c5760405163313c898160e11b8152600481018590526024015b60405180910390fd5b5f7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9888888611d778c6001600160a01b03165f90815260076020526040902080546001810190915590565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e0016040516020818303038152906040528051906020012090505f611dd182612c9d565b90505f611de082878787612cc9565b9050896001600160a01b0316816001600160a01b031614611e27576040516325c0072360e11b81526001600160a01b0380831660048301528b166024820152604401611d23565b611e328a8a8a611eb4565b50505050505050505050565b611e46611f9e565b6001600160a01b038116611e58575f80fd5b601680546001600160a01b0319166001600160a01b0392909216919091179055565b611e82611f9e565b6001600160a01b038116611eab57604051631e4fbdf760e01b81525f6004820152602401611d23565b611ae2816122cb565b611ec18383836001612cf5565b505050565b6001600160a01b038381165f908152600160209081526040808320938616835292905220545f198114611f3b5781811015611f2d57604051637dc7a0d960e11b81526001600160a01b03841660048201526024810182905260448101839052606401611d23565b611f3b84848484035f612cf5565b50505050565b6001600160a01b038316611f6a57604051634b637e8f60e11b81525f6004820152602401611d23565b6001600160a01b038216611f935760405163ec442f0560e01b81525f6004820152602401611d23565b611ec1838383612dc7565b6009546001600160a01b03163314610b2b5760405163118cdaa760e01b8152336004820152602401611d23565b5f306001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614801561202357507f000000000000000000000000000000000000000000000000000000000000000046145b1561204d57507f000000000000000000000000000000000000000000000000000000000000000090565b610ae1604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527f0000000000000000000000000000000000000000000000000000000000000000918101919091527f000000000000000000000000000000000000000000000000000000000000000060608201524660808201523060a08201525f9060c00160405160208183030381529060405280519060200120905090565b60026008540361211757604051633ee5aeb560e01b815260040160405180910390fd5b6002600855565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166348c894916003604051602001611a759190615406565b612167612eed565b6009805460ff60a01b191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b5f5b600c548160ff161015611ec15760ff81165f908152600d6020908152604091829020825160a08101845281546001600160a01b03908116825260018301548082169483019490945262ffffff600160a01b8504811695830195909552600160b81b909304600290810b606083015290910154909116608082015290831690612255908590612243906118c7565b61224d9190615426565b60020b612f17565b111561227457604051631550f74560e01b815260040160405180910390fd5b6001016121b6565b5f8061228661292e565b505060408051838152602081018390529294509092507ff81653b8c545b1deb0107759b7cfc7146514dd306db7fc1ae72d2984dec08adf910160405180910390a15050565b600980546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b600954600160a01b900460ff1615610b2b5760405163d93c066560e01b815260040160405180910390fd5b5f6001600160a01b03841661237c575f805f8085875af190508061237757612377835f633d2cec6f60e21b612f2c565b611f3b565b60405163a9059cbb60e01b81526001600160a01b038416600482015282602482015260205f6044835f895af13d15601f3d1160015f511416171691505f81525f60208201525f60408201525080611f3b57611f3b8463a9059cbb60e01b633c9fd93960e21b612f2c565b5f6001600160a01b0382166123fc575047919050565b6040516370a0823160e01b81523060048201526001600160a01b038316906370a0823190602401602060405180830381865afa15801561243e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109c4919061544b565b919050565b5f838302815f1985870982811083820303915050808411612486575f80fd5b805f03612498575082900490506109e8565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b6001600160a01b03821661252c57604051634b637e8f60e11b81525f6004820152602401611d23565b612537825f83612dc7565b5050565b61254361231c565b6009805460ff60a01b1916600160a01b1790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586121973390565b5f805f8061258b60025490565b90505f8061259761292e565b5050600a5491935091506001600160a01b03166125bb576125b83483615462565b91505b8215806125c757505f82115b806125d157505f81115b6125dd576125dd615361565b825f036125fb578794508693506125f48585612fa4565b95506126bd565b815f03612610578693506125f4848483612467565b805f03612625578794506125f4858484612467565b5f612642612633838b615475565b61263d858b615475565b612fb9565b9050805f0361266457604051637c946ed760e01b815260040160405180910390fd5b81612670600183615462565b61267a91906154a0565b6126859060016152d7565b955082612693600183615462565b61269d91906154a0565b6126a89060016152d7565b94506126b98185610e698587615475565b9650505b5050509250925092565b805f036126d357505050565b6001600160a01b038216612740578034101561270557604051632097692160e11b815260048101829052602401611d23565b80341115611ec157336108fc61271b8334615462565b6040518115909202915f818181858888f19350505050158015611f3b573d5f803e3d5ffd5b611ec16001600160a01b038316843084612fc7565b6001600160a01b03821661277e5760405163ec442f0560e01b81525f6004820152602401611d23565b6125375f8383612dc7565b6060610ae17f00000000000000000000000000000000000000000000000000000000000000006005613036565b6060610ae17f00000000000000000000000000000000000000000000000000000000000000006006613036565b5f5b83518160ff161015611f3b578162ffffff1661282384612243878560ff1681518110612813576128136152ea565b60200260200101515f01516118c7565b111561284257604051631550f74560e01b815260040160405180910390fd5b6001016127e5565b5f805f805f612858866130df565b604051631e2eaeaf60e01b8152600481018290529091505f906001600160a01b03891690631e2eaeaf90602401602060405180830381865afa1580156128a0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128c4919061544b565b90506001600160a01b03811695508060a01c60020b945062ffffff8160b81c16935062ffffff8160d01c169250505092959194509250565b60605f8061290c848601866154b3565b915091505f61291b838361311b565b9050612925613738565b95945050505050565b5f805f805f5b600c548160ff161015612a3a5760ff81165f908152600d6020526040808220905163106c769d60e31b8152829182918291739b617736cd4033611b905e2d1c736eb9d1f153ac91638363b4e8916129b0917f000000000000000000000000000000000000000000000000000000000000000091906004016155ba565b60a060405180830381865af41580156129cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129ef919061531c565b9450945094509450508389612a0491906152d7565b9850612a1083896152d7565b9750612a1c82886152d7565b9650612a2881876152d7565b95505060019093019250612934915050565b5060405163106c769d60e31b81525f90819081908190739b617736cd4033611b905e2d1c736eb9d1f153ac90638363b4e890612a9d907f000000000000000000000000000000000000000000000000000000000000000090600e906004016155ba565b60a060405180830381865af4158015612ab8573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612adc919061531c565b9450945094509450508388612af191906152d7565b9750612afd83886152d7565b9650612b0982876152d7565b9550612b1581866152d7565b60405163106c769d60e31b8152909550739b617736cd4033611b905e2d1c736eb9d1f153ac90638363b4e890612b72907f0000000000000000000000000000000000000000000000000000000000000000906012906004016155ba565b60a060405180830381865af4158015612b8d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612bb1919061531c565b92975090955093509150612bc7905084896152d7565b9750612bd383886152d7565b9650612bdf82876152d7565b9550612beb81866152d7565b601754909550612c0690600160a01b900461ffff16876154a0565b612c109087615462565b601754909650612c2b90600160a01b900461ffff16866154a0565b612c359086615462565b9450612c4186896152d7565b9750612c4d85886152d7565b600a54909750612c65906001600160a01b03166123e6565b612c6f90896152d7565b600b54909850612c87906001600160a01b03166123e6565b612c9190886152d7565b96505050505090919293565b5f6109c4612ca9611fcb565b8360405161190160f01b8152600281019290925260228201526042902090565b5f805f80612cd98888888861385a565b925092509250612ce9828261391e565b50909695505050505050565b6001600160a01b038416612d1e5760405163e602df0560e01b81525f6004820152602401611d23565b6001600160a01b038316612d4757604051634a1406b160e11b81525f6004820152602401611d23565b6001600160a01b038085165f9081526001602090815260408083209387168352929052208290558015611f3b57826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92584604051612db991815260200190565b60405180910390a350505050565b6001600160a01b038316612df1578060025f828254612de691906152d7565b90915550612e619050565b6001600160a01b0383165f9081526020819052604090205481811015612e435760405163391434e360e21b81526001600160a01b03851660048201526024810182905260448101839052606401611d23565b6001600160a01b0384165f9081526020819052604090209082900390555b6001600160a01b038216612e7d57600280548290039055612e9b565b6001600160a01b0382165f9081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051612ee091815260200190565b60405180910390a3505050565b600954600160a01b900460ff16610b2b57604051638dfc202b60e01b815260040160405180910390fd5b5f80821215612f2857815f036109c4565b5090565b6040516390bfb86560e01b8082526001600160a01b03851660048301526001600160e01b031984166024830152608060448301526020601f3d018190040260a0810160648401523d608484015290913d5f60a483013e60048260a4018201526001600160e01b031984168260c4018201528160e40181fd5b5f818311612fb257816109e8565b5090919050565b5f818310612fb257816109e8565b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166323b872dd60e01b179052611f3b9085906139d6565b606060ff83146130505761304983613a37565b90506109c4565b81805461305c90615024565b80601f016020809104026020016040519081016040528092919081815260200182805461308890615024565b80156130d35780601f106130aa576101008083540402835291602001916130d3565b820191905f5260205f20905b8154815290600101906020018083116130b657829003601f168201915b505050505090506109c4565b6040515f906130fe908390600690602001918252602082015260400190565b604051602081830303815290604052805190602001209050919050565b60605f836005811115613130576131306150fa565b036131945761313d613a74565b50505f80838060200190518101906131559190615681565b915091505f806131658484613b49565b604080516020810193909352828101919091528051808303820181526060909201905294506109c49350505050565b60038360058111156131a8576131a86150fa565b036131bc576131b5613a74565b50506109c4565b60018360058111156131d0576131d06150fa565b03613576576131dd613a74565b50505f805f805f868060200190518101906131f891906157a3565b9450945094509450945061321461320e60025490565b82613b49565b50505f8551600261322591906152d7565b67ffffffffffffffff81111561323d5761323d614693565b6040519080825280602002602001820160405280156132a957816020015b60408051610100810182525f606082018181526080830182905260a0830182905260c0830182905260e08301829052825260208083018290529282015282525f1990920191018161325b5790505b508651600c5590505f5b86518160ff1610156133f857868160ff16815181106132d4576132d46152ea565b60209081029190910181015160ff83165f818152600d84526040908190208351805182546001600160a01b039182166001600160a01b03199182161784558288015160018501805485880151606087015162ffffff908116600160b81b0262ffffff60b81b19928216600160a01b0276ffffffffffffffffffffffffffffffffffffffffffffff1990941695881695909517929092171692909217905560809093015160028501805491909316911617905594840151600390910180549290940151851663010000000265ffffffffffff19909216941693909317929092179055875188919081106133c8576133c86152ea565b6020026020010151828260ff16815181106133e5576133e56152ea565b60209081029190910101526001016132b3565b5061341f865f8151811061340e5761340e6152ea565b60200260200101515f015185613c12565b6040805161010081018252600e546001600160a01b0390811660608301908152600f548083166080850152600160a01b810462ffffff1660a0850152600160b81b9004600290810b60c085015260105490921660e0840152825260115480820b602084015263010000009004900b918101919091528651825183919081106134a9576134a96152ea565b60209081029190910181019190915260408051610100810182526012546001600160a01b03908116606083019081526013548083166080850152600160a01b810462ffffff1660a0850152600160b81b9004600290810b60c085015260145490921660e0840152825260155480820b94830194909452630100000090930490920b908201528651829061353d9060016152d7565b8151811061354d5761354d6152ea565b602002602001018190525061356181613ea7565b61356b8584614013565b5050505050506109c4565b600283600581111561358a5761358a6150fa565b036135bd57613597613a74565b50505f80838060200190518101906135af919061590f565b915091506131b58282614013565b60048360058111156135d1576135d16150fa565b036136d7575f805f80858060200190518101906135ee919061595e565b93509350935093506135fe613a74565b50505f60405180606001604052808681526020018560020b81526020018460020b8152509050739b617736cd4033611b905e2d1c736eb9d1f153ac63391d68e27f00000000000000000000000000000000000000000000000000000000000000008361366960025490565b600254876040518663ffffffff1660e01b815260040161368d9594939291906159ac565b6040805180830381865af41580156136a7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906136cb91906152a1565b505050505050506109c4565b60058360058111156136eb576136eb6150fa565b0361371f57600a54613705906001600160a01b03166140a7565b600b5461371a906001600160a01b03166140a7565b6109c4565b604051634a7f394f60e01b815260040160405180910390fd5b600b54604051637c0045dd60e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301529091166024820152739b617736cd4033611b905e2d1c736eb9d1f153ac90637c0045dd906044015f6040518083038186803b1580156137b5575f80fd5b505af41580156137c7573d5f803e3d5ffd5b5050600a54604051637c0045dd60e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301529091166024820152739b617736cd4033611b905e2d1c736eb9d1f153ac9250637c0045dd91506044015f6040518083038186803b158015613848575f80fd5b505af4158015611f3b573d5f803e3d5ffd5b5f80807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a084111561389357505f915060039050826115fa565b604080515f808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa1580156138e4573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b03811661390f57505f9250600191508290506115fa565b975f9750879650945050505050565b5f826003811115613931576139316150fa565b0361393a575050565b600182600381111561394e5761394e6150fa565b0361396c5760405163f645eedf60e01b815260040160405180910390fd5b6002826003811115613980576139806150fa565b036139a15760405163fce698f760e01b815260048101829052602401611d23565b60038260038111156139b5576139b56150fa565b03612537576040516335e2f38360e21b815260048101829052602401611d23565b5f6139ea6001600160a01b03841683614297565b905080515f14158015613a0e575080806020019051810190613a0c91906159e6565b155b15611ec157604051635274afe760e01b81526001600160a01b0384166004820152602401611d23565b60605f613a43836142a4565b6040805160208082528183019092529192505f91906020820181803683375050509182525060208101929092525090565b5f805f613a7f6142cb565b600a54600b5460175460405163be43e57b60e01b8152939450739b617736cd4033611b905e2d1c736eb9d1f153ac9363be43e57b93613b01937f0000000000000000000000000000000000000000000000000000000000000000938893600e936001600160a01b03908116931691600160a01b900461ffff1690600401615a31565b6040805180830381865af4158015613b1b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613b3f91906152a1565b9094909350915050565b5f808315613c0b575f613b5a6142cb565b9050739b617736cd4033611b905e2d1c736eb9d1f153ac639d83a1237f000000000000000000000000000000000000000000000000000000000000000083600e89613ba460025490565b8a6040518763ffffffff1660e01b8152600401613bc696959493929190615a99565b6040805180830381865af4158015613be0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613c0491906152a1565b9093509150505b9250929050565b8060020b5f03613c9d57600e80546001600160a01b0319908116909155600f80547fffffffffffff000000000000000000000000000000000000000000000000000090811690915560108054831690556011805465ffffffffffff19908116909155601280548416905560138054909216909155601480549092169091556015805490911690555050565b8151600e80546001600160a01b039283166001600160a01b031991821681179092556020850151600f80546040880151606089015162ffffff808216600160b81b0262ffffff60b81b1991909316600160a01b0276ffffffffffffffffffffffffffffffffffffffffffffff19948516968a1696871781178216841790955560808b01516010805491909a169088168117909955601280548816909817909755601380549093169094179092179094161790925560148054909116909217909155613d688183615af7565b60020b15613d935780613d7b8184615b18565b613d86906001615b50565b613d909190615b75565b91505b5f613d9d846118c7565b90505f613daa8383615af7565b60020b5f03613dba575080613e0e565b5f613dc58484615af7565b60020b1315613dea5782613dd98184615b18565b613de39190615b75565b9050613e0e565b826001613df78285615b18565b613e019190615426565b613e0b9190615b75565b90505b613e22613e1b8583615426565b828561441d565b6011805465ffffffffffff1916630100000062ffffff9384160262ffffff19161792909116919091179055613e75613e5a8483615b50565b85613e658685615b50565b613e6f9190615b50565b8561441d565b6015805465ffffffffffff1916630100000062ffffff9384160262ffffff191617929091169190911790555050505050565b5f5b81518160ff161015612537575f828260ff1681518110613ecb57613ecb6152ea565b6020026020010151604051602001613ee39190615b9b565b6040516020818303038152906040528051906020012090505f826001613f099190615ba9565b90505b83518160ff161015613ffe57838160ff1681518110613f2d57613f2d6152ea565b60200260200101516040015160020b848260ff1681518110613f5157613f516152ea565b60200260200101516020015160020b0315613fec575f848260ff1681518110613f7c57613f7c6152ea565b6020026020010151604051602001613f949190615b9b565b604051602081830303815290604052805190602001209050808303613fea57848260ff1681518110613fc857613fc86152ea565b6020026020010151604051630bd27b1160e01b8152600401611d239190615b9b565b505b80613ff681615375565b915050613f0c565b5050808061400b90615375565b915050613ea9565b5f61401c6142cb565b60405163d5230e7160e01b8152909150739b617736cd4033611b905e2d1c736eb9d1f153ac9063d5230e719061407f907f0000000000000000000000000000000000000000000000000000000000000000908590600e9089908990600401615bc2565b5f6040518083038186803b158015614095575f80fd5b505af41580156118be573d5f803e3d5ffd5b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031662fdd58e306140f0856001600160a01b03166001600160a01b031690565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526024820152604401602060405180830381865afa158015614137573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061415b919061544b565b9050805f03614168575050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f5298aca306141b1856001600160a01b03166001600160a01b031690565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526024820152604481018490526064015f604051808303815f87803b1580156141fb575f80fd5b505af115801561420d573d5f803e3d5ffd5b5050601654604051630b0d9c0960e01b81526001600160a01b0386811660048301529182166024820152604481018590527f00000000000000000000000000000000000000000000000000000000000000009091169250630b0d9c0991506064015f604051808303815f87803b158015614285575f80fd5b505af1158015610ad0573d5f803e3d5ffd5b60606109e883835f614480565b5f60ff8216601f8111156109c457604051632cd44ac360e21b815260040160405180910390fd5b6060600c5467ffffffffffffffff8111156142e8576142e8614693565b60405190808252806020026020018201604052801561435457816020015b60408051610100810182525f606082018181526080830182905260a0830182905260c0830182905260e08301829052825260208083018290529282015282525f199092019101816143065790505b5090505f5b600c548160ff161015612f285760ff81165f818152600d602090815260409182902082516101008101845281546001600160a01b03908116606083019081526001840154808316608085015262ffffff600160a01b82041660a0850152600160b81b9004600290810b60c08501528085015490921660e0840152825260039092015480830b938201939093526301000000909204900b91810191909152835190918491811061440a5761440a6152ea565b6020908102919091010152600101614359565b5f805f61442984614519565b90505f6144358561453a565b90508160020b8760020b1215614449578196505b8060020b8660020b131561445b578095505b8560020b8760020b12614475575f80935093505050610f5a565b509495939450505050565b6060814710156144a55760405163cd78605960e01b8152306004820152602401611d23565b5f80856001600160a01b031684866040516144c09190615c46565b5f6040518083038185875af1925050503d805f81146144fa576040519150601f19603f3d011682016040523d82523d5f602084013e6144ff565b606091505b509150915061450f868383614552565b9695505050505050565b5f81600281900b620d89e719816145325761453261548c565b050292915050565b5f81600281900b620d89e8816145325761453261548c565b60608261456757614562826145ae565b6109e8565b815115801561457e57506001600160a01b0384163b155b156145a757604051639996b31560e01b81526001600160a01b0385166004820152602401611d23565b50806109e8565b8051156145be5780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f6109e860208301846145d7565b6001600160a01b0381168114611ae2575f80fd5b5f806040838503121561463c575f80fd5b823561464781614617565b946020939093013593505050565b5f805f60608486031215614667575f80fd5b833561467281614617565b9250602084013561468281614617565b929592945050506040919091013590565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff811182821017156146ca576146ca614693565b60405290565b6040516060810167ffffffffffffffff811182821017156146ca576146ca614693565b604051601f8201601f1916810167ffffffffffffffff8111828210171561471c5761471c614693565b604052919050565b62ffffff81168114611ae2575f80fd5b803561246281614724565b8060020b8114611ae2575f80fd5b80356124628161473f565b5f60a08284031215614768575f80fd5b6147706146a7565b9050813561477d81614617565b8152602082013561478d81614617565b602082015260408201356147a081614724565b604082015260608201356147b38161473f565b606082015260808201356147c681614617565b608082015292915050565b5f82601f8301126147e0575f80fd5b6147ea60406146f3565b8060408401858111156147fb575f80fd5b845b818110156148155780358452602093840193016147fd565b509095945050505050565b5f805f806101208587031215614834575f80fd5b61483e8686614758565b935060a085013561484e8161473f565b925060c085013561485e8161473f565b915061486d8660e087016147d1565b905092959194509250565b5f67ffffffffffffffff82111561489157614891614693565b5060051b60200190565b6001600160801b0381168114611ae2575f80fd5b5f82601f8301126148be575f80fd5b81356148d16148cc82614878565b6146f3565b8082825260208201915060208360051b8601019250858311156148f2575f80fd5b602085015b8381101561491857803561490a8161489b565b8352602092830192016148f7565b5095945050505050565b5f82601f830112614931575f80fd5b813561493f6148cc82614878565b8082825260208201915060208360061b860101925085831115614960575f80fd5b602085015b838110156149185761497787826147d1565b8352602090920191604001614965565b5f805f806080858703121561499a575f80fd5b843567ffffffffffffffff8111156149b0575f80fd5b6149bc878288016148af565b945050602085013567ffffffffffffffff8111156149d8575f80fd5b6149e487828801614922565b93505060408501356149f58161473f565b91506060850135614a0581614724565b939692955090935050565b5f60208284031215614a20575f80fd5b5035919050565b60e08101614a8382866001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b8360020b60a08301528260020b60c0830152949350505050565b5f60208284031215614aad575f80fd5b81356109e881614617565b5f805f60608486031215614aca575f80fd5b833592506020840135614adc81614617565b9150604084013567ffffffffffffffff811115614af7575f80fd5b614b0386828701614922565b9150509250925092565b614b668282516001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b602081015160020b60a0830152604081015160020b60c08301525050565b5f8151808452602084019350602083015f5b82811015614bbf57614ba9868351614b0d565b60e0959095019460209190910190600101614b96565b5093949350505050565b604081525f614bdb6040830185614b84565b82810360208401528084518083526020830191506020860192505f5b81811015612ce95783516001600160801b038151168452602081015160208501526040810151604085015250606083019250602084019350600181019050614bf7565b5f805f8060808587031215614c4d575f80fd5b84359350602085013592506040850135614c6681614617565b91506060850135614a0581614617565b60ff60f81b8816815260e060208201525f614c9460e08301896145d7565b8281036040840152614ca681896145d7565b606084018890526001600160a01b038716608085015260a0840186905283810360c0850152845180825260208087019350909101905f5b81811015614cfb578351835260209384019390920191600101614cdd565b50909b9a5050505050505050505050565b5f82601f830112614d1b575f80fd5b8135614d296148cc82614878565b80828252602082019150602060e08402860101925085831115614d4a575f80fd5b602085015b838110156149185760e08188031215614d66575f80fd5b614d6e6146d0565b614d788883614758565b815260a0820135614d888161473f565b602082015260c0820135614d9b8161473f565b6040820152835260209092019160e001614d4f565b5f805f805f805f60e0888a031215614dc6575f80fd5b873567ffffffffffffffff811115614ddc575f80fd5b614de88a828b01614d0c565b975050602088013567ffffffffffffffff811115614e04575f80fd5b614e108a828b016148af565b965050614e1f6040890161474d565b9450606088013567ffffffffffffffff811115614e3a575f80fd5b614e468a828b01614922565b945050608088013567ffffffffffffffff811115614e62575f80fd5b614e6e8a828b01614922565b935050614e7d60a0890161474d565b9150614e8b60c08901614734565b905092959891949750929550565b5f60a08284031215614ea9575f80fd5b6109e88383614758565b5f60208284031215614ec3575f80fd5b813561ffff811681146109e8575f80fd5b5f8060208385031215614ee5575f80fd5b823567ffffffffffffffff811115614efb575f80fd5b8301601f81018513614f0b575f80fd5b803567ffffffffffffffff811115614f21575f80fd5b856020828401011115614f32575f80fd5b6020919091019590945092505050565b602080825282518282018190525f918401906040840190835b8181101561481557835160020b835260209384019390920191600101614f5b565b5f805f805f805f60e0888a031215614f92575f80fd5b8735614f9d81614617565b96506020880135614fad81614617565b95506040880135945060608801359350608088013560ff81168114614fd0575f80fd5b9699959850939692959460a0840135945060c09093013592915050565b5f8060408385031215614ffe575f80fd5b823561500981614617565b9150602083013561501981614617565b809150509250929050565b600181811c9082168061503857607f821691505b60208210810361505657634e487b7160e01b5f52602260045260245ffd5b50919050565b805f5b6002811015611f3b57815184526020938401939091019060010161505f565b61012081016150db82876001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b8460020b60a08301528360020b60c083015261292560e083018461505c565b634e487b7160e01b5f52602160045260245ffd5b6006811061512a57634e487b7160e01b5f52602160045260245ffd5b9052565b615138818461510e565b604060208201525f61514d60408301846145d7565b949350505050565b5f67ffffffffffffffff82111561516e5761516e614693565b50601f01601f191660200190565b5f6020828403121561518c575f80fd5b815167ffffffffffffffff8111156151a2575f80fd5b8201601f810184136151b2575f80fd5b80516151c06148cc82615155565b8181528560208385010111156151d4575f80fd5b8160208401602083015e5f91810160200191909152949350505050565b5f8151808452602084019350602083015f5b82811015614bbf5781516001600160801b0316865260209586019590910190600101615203565b5f8151808452602084019350602083015f5b82811015614bbf5761524f86835161505c565b604095909501946020919091019060010161523c565b604081525f61527760408301856151f1565b8281036020840152612925818561522a565b828152604060208201525f61514d604083018461522a565b5f80604083850312156152b2575f80fd5b505080516020909101519092909150565b634e487b7160e01b5f52601160045260245ffd5b808201808211156109c4576109c46152c3565b634e487b7160e01b5f52603260045260245ffd5b6001600160a01b038316815261010081016109e86020830184614b0d565b5f805f805f60a08688031215615330575f80fd5b855161533b8161489b565b602087015160408801516060890151608090990151929a91995097965090945092505050565b634e487b7160e01b5f52600160045260245ffd5b5f60ff821660ff810361538a5761538a6152c3565b60010192915050565b60a081525f6153a560a0830188614b84565b82810360208401526153b781886151f1565b90508560020b604084015282810360608401526153d4818661522a565b905082810360808401526153e8818561522a565b98975050505050505050565b602081525f6109e86020830184614b84565b615410818361510e565b6040602082018190525f90820152606001919050565b600282810b9082900b03627fffff198112627fffff821317156109c4576109c46152c3565b5f6020828403121561545b575f80fd5b5051919050565b818103818111156109c4576109c46152c3565b80820281158282048414176109c4576109c46152c3565b634e487b7160e01b5f52601260045260245ffd5b5f826154ae576154ae61548c565b500490565b5f80604083850312156154c4575f80fd5b8235600681106154d2575f80fd5b9150602083013567ffffffffffffffff8111156154ed575f80fd5b8301601f810185136154fd575f80fd5b803561550b6148cc82615155565b81815286602083850101111561551f575f80fd5b816020840160208301375f602083830101528093505050509250929050565b6001600160a01b03815416825260018101546001600160a01b038116602084015262ffffff8160a01c1660408401528060b81c60020b60608401525061558e60028201546001600160a01b031690565b6001600160a01b0316608083015260030154600281810b60a084015260189190911c900b60c090910152565b6001600160a01b038316815261010081016109e8602083018461553e565b5f82601f8301126155e7575f80fd5b6155f160406146f3565b806040840185811115615602575f80fd5b845b81811015614815578051845260209384019301615604565b5f82601f83011261562b575f80fd5b81516156396148cc82614878565b8082825260208201915060208360061b86010192508583111561565a575f80fd5b602085015b838110156149185761567187826155d8565b835260209092019160400161565f565b5f8060408385031215615692575f80fd5b8251602084015190925067ffffffffffffffff8111156156b0575f80fd5b6156bc8582860161561c565b9150509250929050565b80516124628161473f565b5f60a082840312156156e1575f80fd5b6156e96146a7565b905081516156f681614617565b8152602082015161570681614617565b6020820152604082015161571981614724565b6040820152606082015161572c8161473f565b606082015260808201516147c681614617565b5f82601f83011261574e575f80fd5b815161575c6148cc82614878565b8082825260208201915060208360051b86010192508583111561577d575f80fd5b602085015b838110156149185780516157958161489b565b835260209283019201615782565b5f805f805f60a086880312156157b7575f80fd5b855167ffffffffffffffff8111156157cd575f80fd5b8601601f810188136157dd575f80fd5b80516157eb6148cc82614878565b80828252602082019150602060e0840285010192508a83111561580c575f80fd5b6020840193505b828410156158785760e0848c03121561582a575f80fd5b6158326146d0565b61583c8c866156d1565b815260a085015161584c8161473f565b602082015260c085015161585f8161473f565b6040820152825260e09390930192602090910190615813565b80985050505050602086015167ffffffffffffffff811115615898575f80fd5b6158a48882890161573f565b9450506158b3604087016156c6565b9250606086015167ffffffffffffffff8111156158ce575f80fd5b6158da8882890161561c565b925050608086015167ffffffffffffffff8111156158f6575f80fd5b6159028882890161561c565b9150509295509295909350565b5f8060408385031215615920575f80fd5b825167ffffffffffffffff811115615936575f80fd5b6159428582860161573f565b925050602083015167ffffffffffffffff8111156156b0575f80fd5b5f805f806101208587031215615972575f80fd5b61597c86866156d1565b935060a085015161598c8161473f565b60c086015190935061599d8161473f565b915061486d8660e087016155d8565b6001600160a01b038616815261018081016159ca6020830187614b0d565b846101008301528361012083015261450f61014083018461505c565b5f602082840312156159f6575f80fd5b815180151581146109e8575f80fd5b805f5b6002811015611f3b57615a1b848361553e565b60e0939093019260049190910190600101615a08565b6001600160a01b038716815261026060208201525f615a54610260830188614b84565b9050615a636040830187615a05565b6001600160a01b0385166102008301526001600160a01b03841661022083015261ffff8316610240830152979650505050505050565b6001600160a01b038716815261026060208201525f615abc610260830188614b84565b615ac96040840188615a05565b8561020084015284610220840152828103610240840152615aea818561522a565b9998505050505050505050565b5f8260020b80615b0957615b0961548c565b808360020b0791505092915050565b5f8160020b8360020b80615b2e57615b2e61548c565b627fffff1982145f1982141615615b4757615b476152c3565b90059392505050565b600281810b9083900b01627fffff8113627fffff19821217156109c4576109c46152c3565b5f8260020b8260020b028060020b9150808214615b9457615b946152c3565b5092915050565b60e081016109c48284614b0d565b60ff81811683821601908111156109c4576109c46152c3565b6001600160a01b038616815261024060208201525f615be5610240830187614b84565b615bf26040840187615a05565b828103610200840152845180825260208087019201905f5b81811015615c315783516001600160801b0316835260209384019390920191600101615c0a565b5050838103610220850152615aea818661522a565b5f82518060208501845e5f92019182525091905056fea2646970667358221220e28ab45d1d4713973ec2440c9d87c8784ae074302d987b13565c809f67b5bf6064736f6c634300081a00330000000000000000000000001f9840000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000000007dcc39b4d1c53cb31e1abc0e358b43987fef80f700000000000000000000000071e7d05be74ff748c45402c06a941c822d756dc500000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000c784554482d776545544830310000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c784554482d776545544830310000000000000000000000000000000000000000

Deployed Bytecode

0x6080604052600436106102cf575f3560e01c806384715b111161017b57806399d32fc4116100d1578063d505accf11610087578063ddca3f4311610062578063ddca3f43146108af578063e74b981b146108e3578063f2fde38b14610902575f80fd5b8063d505accf14610819578063dc4c90d314610838578063dd62ed3e1461086b575f80fd5b8063b079f163116100b7578063b079f163146107a7578063c4a7761e146107c8578063d21220a7146107fc575f80fd5b806399d32fc414610774578063a9059cbb14610788575f80fd5b80638c4be77a1161013157806390d082e91161010c57806390d082e9146106a957806391dd73461461074157806395d89b4114610760575f80fd5b80638c4be77a1461063b5780638da5cb5b1461066d5780638e0055531461068a575f80fd5b8063854cff2f11610161578063854cff2f146105de57806386a29081146105fd5780638bd9ddb81461061c575f80fd5b806384715b111461058957806384b0196e146105b7575f80fd5b80633f4ba83a1161023057806370a08231116101e65780637ecebe00116101c15780637ecebe001461053457806380275860146105535780638456cb5914610575575f80fd5b806370a08231146104b8578063715018a6146104ec578063759f237214610500575f80fd5b80635c975abb116102165780635c975abb1461044d5780635d0885851461046b578063689b5f4f1461048a575f80fd5b80633f4ba83a1461041a578063469048401461042e575f80fd5b806323b872dd11610285578063313ce5671161026b578063313ce567146103d75780633644e515146103f2578063376c548714610406575f80fd5b806323b872dd1461039757806326f622ec146103b6575f80fd5b8063095ea7b3116102b5578063095ea7b3146103235780630dfe16811461035257806318160ddd14610383575f80fd5b806303e78281146102da57806306fdde0314610302575f80fd5b366102d657005b5f80fd5b3480156102e5575f80fd5b506102ef600c5481565b6040519081526020015b60405180910390f35b34801561030d575f80fd5b50610316610921565b6040516102f99190614605565b34801561032e575f80fd5b5061034261033d36600461462b565b6109b1565b60405190151581526020016102f9565b34801561035d575f80fd5b50600a546001600160a01b03165b6040516001600160a01b0390911681526020016102f9565b34801561038e575f80fd5b506002546102ef565b3480156103a2575f80fd5b506103426103b1366004614655565b6109ca565b3480156103c1575f80fd5b506103d56103d0366004614820565b6109ef565b005b3480156103e2575f80fd5b50604051601281526020016102f9565b3480156103fd575f80fd5b506102ef610ad8565b348015610411575f80fd5b506103d5610ae6565b348015610425575f80fd5b506103d5610b2d565b348015610439575f80fd5b5060165461036b906001600160a01b031681565b348015610458575f80fd5b50600954600160a01b900460ff16610342565b348015610476575f80fd5b506103d5610485366004614987565b610b3d565b348015610495575f80fd5b506104a96104a4366004614a10565b610c34565b6040516102f993929190614a27565b3480156104c3575f80fd5b506102ef6104d2366004614a9d565b6001600160a01b03165f9081526020819052604090205490565b3480156104f7575f80fd5b506103d5610cbc565b34801561050b575f80fd5b5061051f61051a366004614ab8565b610ccd565b604080519283526020830191909152016102f9565b34801561053f575f80fd5b506102ef61054e366004614a9d565b610f62565b34801561055e575f80fd5b50610567610f7f565b6040516102f9929190614bc9565b348015610580575f80fd5b506103d5611476565b61059c610597366004614c3a565b611486565b604080519384526020840192909252908201526060016102f9565b3480156105c2575f80fd5b506105cb611604565b6040516102f99796959493929190614c76565b3480156105e9575f80fd5b506103d56105f8366004614a9d565b611646565b348015610608575f80fd5b5060175461036b906001600160a01b031681565b348015610627575f80fd5b506103d5610636366004614db0565b611670565b348015610646575f80fd5b5061065a610655366004614e99565b6118c7565b60405160029190910b81526020016102f9565b348015610678575f80fd5b506009546001600160a01b031661036b565b348015610695575f80fd5b506103d56106a4366004614eb3565b611910565b3480156106b4575f80fd5b506104a96106c3366004614a10565b600d60209081525f918252604091829020825160a08101845281546001600160a01b03908116825260018301548082169483019490945262ffffff600160a01b85041694820194909452600160b81b909204600290810b606084015280820154909316608083015260030154909181810b9163010000009004900b83565b34801561074c575f80fd5b5061031661075b366004614ed4565b6119c0565b34801561076b575f80fd5b50610316611a15565b34801561077f575f80fd5b506103d5611a24565b348015610793575f80fd5b506103426107a236600461462b565b611ae5565b3480156107b2575f80fd5b506107bb611af2565b6040516102f99190614f42565b3480156107d3575f80fd5b506107dc611ce9565b6040805194855260208501939093529183015260608201526080016102f9565b348015610807575f80fd5b50600b546001600160a01b031661036b565b348015610824575f80fd5b506103d5610833366004614f7c565b611d03565b348015610843575f80fd5b5061036b7f0000000000000000000000001f9840000000000000000000000000000000000481565b348015610876575f80fd5b506102ef610885366004614fed565b6001600160a01b039182165f90815260016020908152604080832093909416825291909152205490565b3480156108ba575f80fd5b506017546108d090600160a01b900461ffff1681565b60405161ffff90911681526020016102f9565b3480156108ee575f80fd5b506103d56108fd366004614a9d565b611e3e565b34801561090d575f80fd5b506103d561091c366004614a9d565b611e7a565b60606003805461093090615024565b80601f016020809104026020016040519081016040528092919081815260200182805461095c90615024565b80156109a75780601f1061097e576101008083540402835291602001916109a7565b820191905f5260205f20905b81548152906001019060200180831161098a57829003601f168201915b5050505050905090565b5f336109be818585611eb4565b60019150505b92915050565b5f336109d7858285611ec6565b6109e2858585611f41565b60019150505b9392505050565b6109f7611f9e565b5f84848484604051602001610a0f949392919061507e565b60405160208183030381529060405290507f0000000000000000000000001f984000000000000000000000000000000000046001600160a01b03166348c89491600483604051602001610a6392919061512e565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401610a8e9190614605565b5f604051808303815f875af1158015610aa9573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610ad0919081019061517c565b505050505050565b5f610ae1611fcb565b905090565b610aee6120f4565b6017546001600160a01b03163314610b19576040516361a2001160e11b815260040160405180910390fd5b610b2161211e565b610b2b6001600855565b565b610b35611f9e565b610b2b61215f565b610b45611f9e565b610b4f82826121b4565b5f8484604051602001610b63929190615265565b60405160208183030381529060405290507f0000000000000000000000001f984000000000000000000000000000000000046001600160a01b03166348c89491600283604051602001610bb792919061512e565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401610be29190614605565b5f604051808303815f875af1158015610bfd573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610c24919081019061517c565b50610c2d61227c565b5050505050565b600e8160028110610c43575f80fd5b6040805160a0810182526004929092029290920180546001600160a01b0390811683526001820154808216602085015262ffffff600160a01b82041694840194909452600160b81b909304600290810b60608401528082015490931660808301526003015490925080820b916301000000909104900b83565b610cc4611f9e565b610b2b5f6122cb565b5f80610cd76120f4565b610cdf61231c565b845f03610cff57604051637c946ed760e01b815260040160405180910390fd5b6001600160a01b038416610d265760405163d92e233d60e01b815260040160405180910390fd5b5f8584604051602001610d3a929190615289565b60405160208183030381529060405290505f7f0000000000000000000000001f984000000000000000000000000000000000046001600160a01b03166348c894915f84604051602001610d8e92919061512e565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401610db99190614605565b5f604051808303815f875af1158015610dd4573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610dfb919081019061517c565b905080806020019051810190610e1191906152a1565b600a549195509350610e2d906001600160a01b03168786612347565b600b54610e44906001600160a01b03168785612347565b600a545f90610e6e90610e5f906001600160a01b03166123e6565b89610e6960025490565b612467565b600b549091505f90610e9690610e8c906001600160a01b03166123e6565b8a610e6960025490565b90508115610ec257610ea882876152d7565b600a54909650610ec2906001600160a01b03168984612347565b8015610eec57610ed281866152d7565b600b54909550610eec906001600160a01b03168983612347565b610ef6338a612503565b604080518a8152602081018890529081018690526001600160a01b0389169033907febff2602b3f468259e1e99f613fed6691f3a6526effe6ef3e768ba7ae7a36c4f9060600160405180910390a3610f4c61227c565b50505050610f5a6001600855565b935093915050565b6001600160a01b0381165f908152600760205260408120546109c4565b6060805f600c546002610f9291906152d7565b67ffffffffffffffff811115610faa57610faa614693565b60405190808252806020026020018201604052801561101657816020015b60408051610100810182525f606082018181526080830182905260a0830182905260c0830182905260e08301829052825260208083018290529282015282525f19909201910181610fc85790505b5090505f600c54600261102991906152d7565b67ffffffffffffffff81111561104157611041614693565b60405190808252806020026020018201604052801561109c57816020015b61108960405180606001604052805f6001600160801b031681526020015f81526020015f81525090565b81526020019060019003908161105f5790505b5090505f8080805b600c548160ff16101561126c5760ff81165f818152600d602090815260409182902082516101008101845281546001600160a01b03908116606083019081526001840154808316608085015262ffffff600160a01b82041660a0850152600160b81b9004600290810b60c08501528085015490921660e0840152825260039092015480830b938201939093526301000000909204900b918101919091528751909188918110611155576111556152ea565b6020026020010181905250739b617736cd4033611b905e2d1c736eb9d1f153ac638363b4e87f0000000000000000000000001f98400000000000000000000000000000000004888460ff16815181106111b0576111b06152ea565b60200260200101516040518363ffffffff1660e01b81526004016111d59291906152fe565b60a060405180830381865af41580156111f0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611214919061531c565b5050604080516060810182526001600160801b0385168152602081018490529081018290528851939750919550935090869060ff8416908110611259576112596152ea565b60209081029190910101526001016110a4565b505f5b60028160ff16101561146857600e8160ff1660028110611291576112916152ea565b60408051610100810182526004929092029290920180546001600160a01b03908116606084019081526001830154808316608086015262ffffff600160a01b82041660a0860152600160b81b9004600290810b60c08601528084015490921660e0850152835260039091015480820b602084015263010000009004900b91810191909152600c5487906113289060ff8516906152d7565b81518110611338576113386152ea565b6020026020010181905250739b617736cd4033611b905e2d1c736eb9d1f153ac638363b4e87f0000000000000000000000001f98400000000000000000000000000000000004888460ff16600c5461139091906152d7565b815181106113a0576113a06152ea565b60200260200101516040518363ffffffff1660e01b81526004016113c59291906152fe565b60a060405180830381865af41580156113e0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611404919061531c565b5050604080516060810182526001600160801b038516815260208101849052908101829052600c5493975091955093509086906114459060ff8516906152d7565b81518110611455576114556152ea565b602090810291909101015260010161126f565b509396929550919350505050565b61147e611f9e565b610b2b61253b565b5f805f6114916120f4565b61149961231c565b6001600160a01b03851615806114b757506001600160a01b03851630145b156114d55760405163d92e233d60e01b815260040160405180910390fd5b6017546001600160a01b03163314611500576040516361a2001160e11b815260040160405180910390fd5b600a546001600160a01b03161515801561151957505f34115b1561153757604051631ab026e960e31b815260040160405180910390fd5b61153f61211e565b611549878761257e565b919450925090508261155d5761155d615361565b600a546115759085906001600160a01b0316846126c7565b600b5461158d9085906001600160a01b0316836126c7565b6115978584612755565b60408051848152602081018490529081018290526001600160a01b0380871691908616907f4e2ca0515ed1aef1395f66b5303bb5d6f1bf9d61a353fa53f73f8ac9973fa9f69060600160405180910390a36115f061227c565b6115fa6001600855565b9450945094915050565b5f6060805f805f6060611615612789565b61161d6127b6565b604080515f80825260208201909252600f60f81b9b939a50919850469750309650945092509050565b61164e611f9e565b601780546001600160a01b0319166001600160a01b0392909216919091179055565b6116786120f4565b611680611f9e565b5f5b87518160ff16101561174d57600a546001600160a01b03166116cb898360ff16815181106116b2576116b26152ea565b602090810291909101015151516001600160a01b031690565b14158061171e5750600b546001600160a01b031661171b898360ff16815181106116f7576116f76152ea565b60200260200101515f0151602001516001600160a01b03166001600160a01b031690565b14155b1561173b5760405162de216b60e01b815260040160405180910390fd5b8061174581615375565b915050611682565b506117598783836127e3565b8651845114158061176c57508651865114155b8061177a5750600c54835114155b156117985760405163483cb4ab60e11b815260040160405180910390fd5b5f87878787876040516020016117b2959493929190615393565b60405160208183030381529060405290507f0000000000000000000000001f984000000000000000000000000000000000046001600160a01b03166348c8949160018360405160200161180692919061512e565b6040516020818303038152906040526040518263ffffffff1660e01b81526004016118319190614605565b5f604051808303815f875af115801561184c573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611873919081019061517c565b507fda82109922c7702ec52698db387bdfa93c21de784b25f20b35bd750b7b510d95886040516118a391906153f4565b60405180910390a16118b361227c565b506118be6001600855565b50505050505050565b5f6119066118d68360a0902090565b6001600160a01b037f0000000000000000000000001f98400000000000000000000000000000000004169061284a565b5090949350505050565b611918611f9e565b6017546001600160a01b90910461ffff161015611948576040516358d620b360e01b815260040160405180910390fd5b61195061211e565b601780547fffffffffffffffffffff0000ffffffffffffffffffffffffffffffffffffffff16600160a01b61ffff8416908102919091179091556040519081527f931a978d852c1b6fa9dd97300fd89c773ff625b91f697b0911e943ba15f9e2439060200160405180910390a150565b6060336001600160a01b037f0000000000000000000000001f984000000000000000000000000000000000041614611a0b5760405163570c108560e11b815260040160405180910390fd5b6109e883836128fc565b60606004805461093090615024565b611a2c611f9e565b611a3461211e565b7f0000000000000000000000001f984000000000000000000000000000000000046001600160a01b03166348c894916005604051602001611a759190615406565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401611aa09190614605565b5f604051808303815f875af1158015611abb573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611ae2919081019061517c565b50565b5f336109be818585611f41565b6060600c545f03611b0f5750604080515f81526020810190915290565b600c54611b1d9060026152d7565b67ffffffffffffffff811115611b3557611b35614693565b604051908082528060200260200182016040528015611b5e578160200160208202803683370190505b5090505f5b600c548160ff161015611c135760ff81165f908152600d6020908152604091829020825160a08101845281546001600160a01b03908116825260018301548082169483019490945262ffffff600160a01b85041694820194909452600160b81b909204600290810b606084015201549091166080820152611be3906118c7565b828260ff1681518110611bf857611bf86152ea565b60029290920b60209283029190910190910152600101611b63565b50611c7f600e5f5b6040805160a0810182526004929092029290920180546001600160a01b0390811683526001820154808216602085015262ffffff600160a01b82041694840194909452600160b81b909304600290810b6060840152015490911660808201526118c7565b81600c5481518110611c9357611c936152ea565b60029290920b60209283029190910190910152611cb2600e6001611c1b565b81600c546001611cc291906152d7565b81518110611cd257611cd26152ea565b602002602001019060020b908160020b8152505090565b5f805f80611cf561292e565b935093509350935090919293565b83421115611d2c5760405163313c898160e11b8152600481018590526024015b60405180910390fd5b5f7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9888888611d778c6001600160a01b03165f90815260076020526040902080546001810190915590565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e0016040516020818303038152906040528051906020012090505f611dd182612c9d565b90505f611de082878787612cc9565b9050896001600160a01b0316816001600160a01b031614611e27576040516325c0072360e11b81526001600160a01b0380831660048301528b166024820152604401611d23565b611e328a8a8a611eb4565b50505050505050505050565b611e46611f9e565b6001600160a01b038116611e58575f80fd5b601680546001600160a01b0319166001600160a01b0392909216919091179055565b611e82611f9e565b6001600160a01b038116611eab57604051631e4fbdf760e01b81525f6004820152602401611d23565b611ae2816122cb565b611ec18383836001612cf5565b505050565b6001600160a01b038381165f908152600160209081526040808320938616835292905220545f198114611f3b5781811015611f2d57604051637dc7a0d960e11b81526001600160a01b03841660048201526024810182905260448101839052606401611d23565b611f3b84848484035f612cf5565b50505050565b6001600160a01b038316611f6a57604051634b637e8f60e11b81525f6004820152602401611d23565b6001600160a01b038216611f935760405163ec442f0560e01b81525f6004820152602401611d23565b611ec1838383612dc7565b6009546001600160a01b03163314610b2b5760405163118cdaa760e01b8152336004820152602401611d23565b5f306001600160a01b037f000000000000000000000000f802d5c44dc4e3bb0eccf680a6ba82cbd24b9f331614801561202357507f000000000000000000000000000000000000000000000000000000000000008246145b1561204d57507fb7cbb477dc5560b7de79a5cc5dc49d0a2a5ef36ba3459a75e23cc817ad5c403290565b610ae1604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527f2524f9b0444403fb8d8351704f10aa4895545f3e66359f60dc7bb0636b4c0fdc918101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a08201525f9060c00160405160208183030381529060405280519060200120905090565b60026008540361211757604051633ee5aeb560e01b815260040160405180910390fd5b6002600855565b7f0000000000000000000000001f984000000000000000000000000000000000046001600160a01b03166348c894916003604051602001611a759190615406565b612167612eed565b6009805460ff60a01b191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b5f5b600c548160ff161015611ec15760ff81165f908152600d6020908152604091829020825160a08101845281546001600160a01b03908116825260018301548082169483019490945262ffffff600160a01b8504811695830195909552600160b81b909304600290810b606083015290910154909116608082015290831690612255908590612243906118c7565b61224d9190615426565b60020b612f17565b111561227457604051631550f74560e01b815260040160405180910390fd5b6001016121b6565b5f8061228661292e565b505060408051838152602081018390529294509092507ff81653b8c545b1deb0107759b7cfc7146514dd306db7fc1ae72d2984dec08adf910160405180910390a15050565b600980546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b600954600160a01b900460ff1615610b2b5760405163d93c066560e01b815260040160405180910390fd5b5f6001600160a01b03841661237c575f805f8085875af190508061237757612377835f633d2cec6f60e21b612f2c565b611f3b565b60405163a9059cbb60e01b81526001600160a01b038416600482015282602482015260205f6044835f895af13d15601f3d1160015f511416171691505f81525f60208201525f60408201525080611f3b57611f3b8463a9059cbb60e01b633c9fd93960e21b612f2c565b5f6001600160a01b0382166123fc575047919050565b6040516370a0823160e01b81523060048201526001600160a01b038316906370a0823190602401602060405180830381865afa15801561243e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109c4919061544b565b919050565b5f838302815f1985870982811083820303915050808411612486575f80fd5b805f03612498575082900490506109e8565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b6001600160a01b03821661252c57604051634b637e8f60e11b81525f6004820152602401611d23565b612537825f83612dc7565b5050565b61254361231c565b6009805460ff60a01b1916600160a01b1790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586121973390565b5f805f8061258b60025490565b90505f8061259761292e565b5050600a5491935091506001600160a01b03166125bb576125b83483615462565b91505b8215806125c757505f82115b806125d157505f81115b6125dd576125dd615361565b825f036125fb578794508693506125f48585612fa4565b95506126bd565b815f03612610578693506125f4848483612467565b805f03612625578794506125f4858484612467565b5f612642612633838b615475565b61263d858b615475565b612fb9565b9050805f0361266457604051637c946ed760e01b815260040160405180910390fd5b81612670600183615462565b61267a91906154a0565b6126859060016152d7565b955082612693600183615462565b61269d91906154a0565b6126a89060016152d7565b94506126b98185610e698587615475565b9650505b5050509250925092565b805f036126d357505050565b6001600160a01b038216612740578034101561270557604051632097692160e11b815260048101829052602401611d23565b80341115611ec157336108fc61271b8334615462565b6040518115909202915f818181858888f19350505050158015611f3b573d5f803e3d5ffd5b611ec16001600160a01b038316843084612fc7565b6001600160a01b03821661277e5760405163ec442f0560e01b81525f6004820152602401611d23565b6125375f8383612dc7565b6060610ae17f784554482d77654554483031000000000000000000000000000000000000000c6005613036565b6060610ae17f31000000000000000000000000000000000000000000000000000000000000016006613036565b5f5b83518160ff161015611f3b578162ffffff1661282384612243878560ff1681518110612813576128136152ea565b60200260200101515f01516118c7565b111561284257604051631550f74560e01b815260040160405180910390fd5b6001016127e5565b5f805f805f612858866130df565b604051631e2eaeaf60e01b8152600481018290529091505f906001600160a01b03891690631e2eaeaf90602401602060405180830381865afa1580156128a0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128c4919061544b565b90506001600160a01b03811695508060a01c60020b945062ffffff8160b81c16935062ffffff8160d01c169250505092959194509250565b60605f8061290c848601866154b3565b915091505f61291b838361311b565b9050612925613738565b95945050505050565b5f805f805f5b600c548160ff161015612a3a5760ff81165f908152600d6020526040808220905163106c769d60e31b8152829182918291739b617736cd4033611b905e2d1c736eb9d1f153ac91638363b4e8916129b0917f0000000000000000000000001f9840000000000000000000000000000000000491906004016155ba565b60a060405180830381865af41580156129cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129ef919061531c565b9450945094509450508389612a0491906152d7565b9850612a1083896152d7565b9750612a1c82886152d7565b9650612a2881876152d7565b95505060019093019250612934915050565b5060405163106c769d60e31b81525f90819081908190739b617736cd4033611b905e2d1c736eb9d1f153ac90638363b4e890612a9d907f0000000000000000000000001f9840000000000000000000000000000000000490600e906004016155ba565b60a060405180830381865af4158015612ab8573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612adc919061531c565b9450945094509450508388612af191906152d7565b9750612afd83886152d7565b9650612b0982876152d7565b9550612b1581866152d7565b60405163106c769d60e31b8152909550739b617736cd4033611b905e2d1c736eb9d1f153ac90638363b4e890612b72907f0000000000000000000000001f98400000000000000000000000000000000004906012906004016155ba565b60a060405180830381865af4158015612b8d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612bb1919061531c565b92975090955093509150612bc7905084896152d7565b9750612bd383886152d7565b9650612bdf82876152d7565b9550612beb81866152d7565b601754909550612c0690600160a01b900461ffff16876154a0565b612c109087615462565b601754909650612c2b90600160a01b900461ffff16866154a0565b612c359086615462565b9450612c4186896152d7565b9750612c4d85886152d7565b600a54909750612c65906001600160a01b03166123e6565b612c6f90896152d7565b600b54909850612c87906001600160a01b03166123e6565b612c9190886152d7565b96505050505090919293565b5f6109c4612ca9611fcb565b8360405161190160f01b8152600281019290925260228201526042902090565b5f805f80612cd98888888861385a565b925092509250612ce9828261391e565b50909695505050505050565b6001600160a01b038416612d1e5760405163e602df0560e01b81525f6004820152602401611d23565b6001600160a01b038316612d4757604051634a1406b160e11b81525f6004820152602401611d23565b6001600160a01b038085165f9081526001602090815260408083209387168352929052208290558015611f3b57826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92584604051612db991815260200190565b60405180910390a350505050565b6001600160a01b038316612df1578060025f828254612de691906152d7565b90915550612e619050565b6001600160a01b0383165f9081526020819052604090205481811015612e435760405163391434e360e21b81526001600160a01b03851660048201526024810182905260448101839052606401611d23565b6001600160a01b0384165f9081526020819052604090209082900390555b6001600160a01b038216612e7d57600280548290039055612e9b565b6001600160a01b0382165f9081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051612ee091815260200190565b60405180910390a3505050565b600954600160a01b900460ff16610b2b57604051638dfc202b60e01b815260040160405180910390fd5b5f80821215612f2857815f036109c4565b5090565b6040516390bfb86560e01b8082526001600160a01b03851660048301526001600160e01b031984166024830152608060448301526020601f3d018190040260a0810160648401523d608484015290913d5f60a483013e60048260a4018201526001600160e01b031984168260c4018201528160e40181fd5b5f818311612fb257816109e8565b5090919050565b5f818310612fb257816109e8565b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166323b872dd60e01b179052611f3b9085906139d6565b606060ff83146130505761304983613a37565b90506109c4565b81805461305c90615024565b80601f016020809104026020016040519081016040528092919081815260200182805461308890615024565b80156130d35780601f106130aa576101008083540402835291602001916130d3565b820191905f5260205f20905b8154815290600101906020018083116130b657829003601f168201915b505050505090506109c4565b6040515f906130fe908390600690602001918252602082015260400190565b604051602081830303815290604052805190602001209050919050565b60605f836005811115613130576131306150fa565b036131945761313d613a74565b50505f80838060200190518101906131559190615681565b915091505f806131658484613b49565b604080516020810193909352828101919091528051808303820181526060909201905294506109c49350505050565b60038360058111156131a8576131a86150fa565b036131bc576131b5613a74565b50506109c4565b60018360058111156131d0576131d06150fa565b03613576576131dd613a74565b50505f805f805f868060200190518101906131f891906157a3565b9450945094509450945061321461320e60025490565b82613b49565b50505f8551600261322591906152d7565b67ffffffffffffffff81111561323d5761323d614693565b6040519080825280602002602001820160405280156132a957816020015b60408051610100810182525f606082018181526080830182905260a0830182905260c0830182905260e08301829052825260208083018290529282015282525f1990920191018161325b5790505b508651600c5590505f5b86518160ff1610156133f857868160ff16815181106132d4576132d46152ea565b60209081029190910181015160ff83165f818152600d84526040908190208351805182546001600160a01b039182166001600160a01b03199182161784558288015160018501805485880151606087015162ffffff908116600160b81b0262ffffff60b81b19928216600160a01b0276ffffffffffffffffffffffffffffffffffffffffffffff1990941695881695909517929092171692909217905560809093015160028501805491909316911617905594840151600390910180549290940151851663010000000265ffffffffffff19909216941693909317929092179055875188919081106133c8576133c86152ea565b6020026020010151828260ff16815181106133e5576133e56152ea565b60209081029190910101526001016132b3565b5061341f865f8151811061340e5761340e6152ea565b60200260200101515f015185613c12565b6040805161010081018252600e546001600160a01b0390811660608301908152600f548083166080850152600160a01b810462ffffff1660a0850152600160b81b9004600290810b60c085015260105490921660e0840152825260115480820b602084015263010000009004900b918101919091528651825183919081106134a9576134a96152ea565b60209081029190910181019190915260408051610100810182526012546001600160a01b03908116606083019081526013548083166080850152600160a01b810462ffffff1660a0850152600160b81b9004600290810b60c085015260145490921660e0840152825260155480820b94830194909452630100000090930490920b908201528651829061353d9060016152d7565b8151811061354d5761354d6152ea565b602002602001018190525061356181613ea7565b61356b8584614013565b5050505050506109c4565b600283600581111561358a5761358a6150fa565b036135bd57613597613a74565b50505f80838060200190518101906135af919061590f565b915091506131b58282614013565b60048360058111156135d1576135d16150fa565b036136d7575f805f80858060200190518101906135ee919061595e565b93509350935093506135fe613a74565b50505f60405180606001604052808681526020018560020b81526020018460020b8152509050739b617736cd4033611b905e2d1c736eb9d1f153ac63391d68e27f0000000000000000000000001f984000000000000000000000000000000000048361366960025490565b600254876040518663ffffffff1660e01b815260040161368d9594939291906159ac565b6040805180830381865af41580156136a7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906136cb91906152a1565b505050505050506109c4565b60058360058111156136eb576136eb6150fa565b0361371f57600a54613705906001600160a01b03166140a7565b600b5461371a906001600160a01b03166140a7565b6109c4565b604051634a7f394f60e01b815260040160405180910390fd5b600b54604051637c0045dd60e01b81526001600160a01b037f0000000000000000000000001f98400000000000000000000000000000000004811660048301529091166024820152739b617736cd4033611b905e2d1c736eb9d1f153ac90637c0045dd906044015f6040518083038186803b1580156137b5575f80fd5b505af41580156137c7573d5f803e3d5ffd5b5050600a54604051637c0045dd60e01b81526001600160a01b037f0000000000000000000000001f98400000000000000000000000000000000004811660048301529091166024820152739b617736cd4033611b905e2d1c736eb9d1f153ac9250637c0045dd91506044015f6040518083038186803b158015613848575f80fd5b505af4158015611f3b573d5f803e3d5ffd5b5f80807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a084111561389357505f915060039050826115fa565b604080515f808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa1580156138e4573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b03811661390f57505f9250600191508290506115fa565b975f9750879650945050505050565b5f826003811115613931576139316150fa565b0361393a575050565b600182600381111561394e5761394e6150fa565b0361396c5760405163f645eedf60e01b815260040160405180910390fd5b6002826003811115613980576139806150fa565b036139a15760405163fce698f760e01b815260048101829052602401611d23565b60038260038111156139b5576139b56150fa565b03612537576040516335e2f38360e21b815260048101829052602401611d23565b5f6139ea6001600160a01b03841683614297565b905080515f14158015613a0e575080806020019051810190613a0c91906159e6565b155b15611ec157604051635274afe760e01b81526001600160a01b0384166004820152602401611d23565b60605f613a43836142a4565b6040805160208082528183019092529192505f91906020820181803683375050509182525060208101929092525090565b5f805f613a7f6142cb565b600a54600b5460175460405163be43e57b60e01b8152939450739b617736cd4033611b905e2d1c736eb9d1f153ac9363be43e57b93613b01937f0000000000000000000000001f98400000000000000000000000000000000004938893600e936001600160a01b03908116931691600160a01b900461ffff1690600401615a31565b6040805180830381865af4158015613b1b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613b3f91906152a1565b9094909350915050565b5f808315613c0b575f613b5a6142cb565b9050739b617736cd4033611b905e2d1c736eb9d1f153ac639d83a1237f0000000000000000000000001f9840000000000000000000000000000000000483600e89613ba460025490565b8a6040518763ffffffff1660e01b8152600401613bc696959493929190615a99565b6040805180830381865af4158015613be0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613c0491906152a1565b9093509150505b9250929050565b8060020b5f03613c9d57600e80546001600160a01b0319908116909155600f80547fffffffffffff000000000000000000000000000000000000000000000000000090811690915560108054831690556011805465ffffffffffff19908116909155601280548416905560138054909216909155601480549092169091556015805490911690555050565b8151600e80546001600160a01b039283166001600160a01b031991821681179092556020850151600f80546040880151606089015162ffffff808216600160b81b0262ffffff60b81b1991909316600160a01b0276ffffffffffffffffffffffffffffffffffffffffffffff19948516968a1696871781178216841790955560808b01516010805491909a169088168117909955601280548816909817909755601380549093169094179092179094161790925560148054909116909217909155613d688183615af7565b60020b15613d935780613d7b8184615b18565b613d86906001615b50565b613d909190615b75565b91505b5f613d9d846118c7565b90505f613daa8383615af7565b60020b5f03613dba575080613e0e565b5f613dc58484615af7565b60020b1315613dea5782613dd98184615b18565b613de39190615b75565b9050613e0e565b826001613df78285615b18565b613e019190615426565b613e0b9190615b75565b90505b613e22613e1b8583615426565b828561441d565b6011805465ffffffffffff1916630100000062ffffff9384160262ffffff19161792909116919091179055613e75613e5a8483615b50565b85613e658685615b50565b613e6f9190615b50565b8561441d565b6015805465ffffffffffff1916630100000062ffffff9384160262ffffff191617929091169190911790555050505050565b5f5b81518160ff161015612537575f828260ff1681518110613ecb57613ecb6152ea565b6020026020010151604051602001613ee39190615b9b565b6040516020818303038152906040528051906020012090505f826001613f099190615ba9565b90505b83518160ff161015613ffe57838160ff1681518110613f2d57613f2d6152ea565b60200260200101516040015160020b848260ff1681518110613f5157613f516152ea565b60200260200101516020015160020b0315613fec575f848260ff1681518110613f7c57613f7c6152ea565b6020026020010151604051602001613f949190615b9b565b604051602081830303815290604052805190602001209050808303613fea57848260ff1681518110613fc857613fc86152ea565b6020026020010151604051630bd27b1160e01b8152600401611d239190615b9b565b505b80613ff681615375565b915050613f0c565b5050808061400b90615375565b915050613ea9565b5f61401c6142cb565b60405163d5230e7160e01b8152909150739b617736cd4033611b905e2d1c736eb9d1f153ac9063d5230e719061407f907f0000000000000000000000001f98400000000000000000000000000000000004908590600e9089908990600401615bc2565b5f6040518083038186803b158015614095575f80fd5b505af41580156118be573d5f803e3d5ffd5b5f7f0000000000000000000000001f984000000000000000000000000000000000046001600160a01b031662fdd58e306140f0856001600160a01b03166001600160a01b031690565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526024820152604401602060405180830381865afa158015614137573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061415b919061544b565b9050805f03614168575050565b7f0000000000000000000000001f984000000000000000000000000000000000046001600160a01b031663f5298aca306141b1856001600160a01b03166001600160a01b031690565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526024820152604481018490526064015f604051808303815f87803b1580156141fb575f80fd5b505af115801561420d573d5f803e3d5ffd5b5050601654604051630b0d9c0960e01b81526001600160a01b0386811660048301529182166024820152604481018590527f0000000000000000000000001f984000000000000000000000000000000000049091169250630b0d9c0991506064015f604051808303815f87803b158015614285575f80fd5b505af1158015610ad0573d5f803e3d5ffd5b60606109e883835f614480565b5f60ff8216601f8111156109c457604051632cd44ac360e21b815260040160405180910390fd5b6060600c5467ffffffffffffffff8111156142e8576142e8614693565b60405190808252806020026020018201604052801561435457816020015b60408051610100810182525f606082018181526080830182905260a0830182905260c0830182905260e08301829052825260208083018290529282015282525f199092019101816143065790505b5090505f5b600c548160ff161015612f285760ff81165f818152600d602090815260409182902082516101008101845281546001600160a01b03908116606083019081526001840154808316608085015262ffffff600160a01b82041660a0850152600160b81b9004600290810b60c08501528085015490921660e0840152825260039092015480830b938201939093526301000000909204900b91810191909152835190918491811061440a5761440a6152ea565b6020908102919091010152600101614359565b5f805f61442984614519565b90505f6144358561453a565b90508160020b8760020b1215614449578196505b8060020b8660020b131561445b578095505b8560020b8760020b12614475575f80935093505050610f5a565b509495939450505050565b6060814710156144a55760405163cd78605960e01b8152306004820152602401611d23565b5f80856001600160a01b031684866040516144c09190615c46565b5f6040518083038185875af1925050503d805f81146144fa576040519150601f19603f3d011682016040523d82523d5f602084013e6144ff565b606091505b509150915061450f868383614552565b9695505050505050565b5f81600281900b620d89e719816145325761453261548c565b050292915050565b5f81600281900b620d89e8816145325761453261548c565b60608261456757614562826145ae565b6109e8565b815115801561457e57506001600160a01b0384163b155b156145a757604051639996b31560e01b81526001600160a01b0385166004820152602401611d23565b50806109e8565b8051156145be5780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f6109e860208301846145d7565b6001600160a01b0381168114611ae2575f80fd5b5f806040838503121561463c575f80fd5b823561464781614617565b946020939093013593505050565b5f805f60608486031215614667575f80fd5b833561467281614617565b9250602084013561468281614617565b929592945050506040919091013590565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff811182821017156146ca576146ca614693565b60405290565b6040516060810167ffffffffffffffff811182821017156146ca576146ca614693565b604051601f8201601f1916810167ffffffffffffffff8111828210171561471c5761471c614693565b604052919050565b62ffffff81168114611ae2575f80fd5b803561246281614724565b8060020b8114611ae2575f80fd5b80356124628161473f565b5f60a08284031215614768575f80fd5b6147706146a7565b9050813561477d81614617565b8152602082013561478d81614617565b602082015260408201356147a081614724565b604082015260608201356147b38161473f565b606082015260808201356147c681614617565b608082015292915050565b5f82601f8301126147e0575f80fd5b6147ea60406146f3565b8060408401858111156147fb575f80fd5b845b818110156148155780358452602093840193016147fd565b509095945050505050565b5f805f806101208587031215614834575f80fd5b61483e8686614758565b935060a085013561484e8161473f565b925060c085013561485e8161473f565b915061486d8660e087016147d1565b905092959194509250565b5f67ffffffffffffffff82111561489157614891614693565b5060051b60200190565b6001600160801b0381168114611ae2575f80fd5b5f82601f8301126148be575f80fd5b81356148d16148cc82614878565b6146f3565b8082825260208201915060208360051b8601019250858311156148f2575f80fd5b602085015b8381101561491857803561490a8161489b565b8352602092830192016148f7565b5095945050505050565b5f82601f830112614931575f80fd5b813561493f6148cc82614878565b8082825260208201915060208360061b860101925085831115614960575f80fd5b602085015b838110156149185761497787826147d1565b8352602090920191604001614965565b5f805f806080858703121561499a575f80fd5b843567ffffffffffffffff8111156149b0575f80fd5b6149bc878288016148af565b945050602085013567ffffffffffffffff8111156149d8575f80fd5b6149e487828801614922565b93505060408501356149f58161473f565b91506060850135614a0581614724565b939692955090935050565b5f60208284031215614a20575f80fd5b5035919050565b60e08101614a8382866001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b8360020b60a08301528260020b60c0830152949350505050565b5f60208284031215614aad575f80fd5b81356109e881614617565b5f805f60608486031215614aca575f80fd5b833592506020840135614adc81614617565b9150604084013567ffffffffffffffff811115614af7575f80fd5b614b0386828701614922565b9150509250925092565b614b668282516001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b602081015160020b60a0830152604081015160020b60c08301525050565b5f8151808452602084019350602083015f5b82811015614bbf57614ba9868351614b0d565b60e0959095019460209190910190600101614b96565b5093949350505050565b604081525f614bdb6040830185614b84565b82810360208401528084518083526020830191506020860192505f5b81811015612ce95783516001600160801b038151168452602081015160208501526040810151604085015250606083019250602084019350600181019050614bf7565b5f805f8060808587031215614c4d575f80fd5b84359350602085013592506040850135614c6681614617565b91506060850135614a0581614617565b60ff60f81b8816815260e060208201525f614c9460e08301896145d7565b8281036040840152614ca681896145d7565b606084018890526001600160a01b038716608085015260a0840186905283810360c0850152845180825260208087019350909101905f5b81811015614cfb578351835260209384019390920191600101614cdd565b50909b9a5050505050505050505050565b5f82601f830112614d1b575f80fd5b8135614d296148cc82614878565b80828252602082019150602060e08402860101925085831115614d4a575f80fd5b602085015b838110156149185760e08188031215614d66575f80fd5b614d6e6146d0565b614d788883614758565b815260a0820135614d888161473f565b602082015260c0820135614d9b8161473f565b6040820152835260209092019160e001614d4f565b5f805f805f805f60e0888a031215614dc6575f80fd5b873567ffffffffffffffff811115614ddc575f80fd5b614de88a828b01614d0c565b975050602088013567ffffffffffffffff811115614e04575f80fd5b614e108a828b016148af565b965050614e1f6040890161474d565b9450606088013567ffffffffffffffff811115614e3a575f80fd5b614e468a828b01614922565b945050608088013567ffffffffffffffff811115614e62575f80fd5b614e6e8a828b01614922565b935050614e7d60a0890161474d565b9150614e8b60c08901614734565b905092959891949750929550565b5f60a08284031215614ea9575f80fd5b6109e88383614758565b5f60208284031215614ec3575f80fd5b813561ffff811681146109e8575f80fd5b5f8060208385031215614ee5575f80fd5b823567ffffffffffffffff811115614efb575f80fd5b8301601f81018513614f0b575f80fd5b803567ffffffffffffffff811115614f21575f80fd5b856020828401011115614f32575f80fd5b6020919091019590945092505050565b602080825282518282018190525f918401906040840190835b8181101561481557835160020b835260209384019390920191600101614f5b565b5f805f805f805f60e0888a031215614f92575f80fd5b8735614f9d81614617565b96506020880135614fad81614617565b95506040880135945060608801359350608088013560ff81168114614fd0575f80fd5b9699959850939692959460a0840135945060c09093013592915050565b5f8060408385031215614ffe575f80fd5b823561500981614617565b9150602083013561501981614617565b809150509250929050565b600181811c9082168061503857607f821691505b60208210810361505657634e487b7160e01b5f52602260045260245ffd5b50919050565b805f5b6002811015611f3b57815184526020938401939091019060010161505f565b61012081016150db82876001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b8460020b60a08301528360020b60c083015261292560e083018461505c565b634e487b7160e01b5f52602160045260245ffd5b6006811061512a57634e487b7160e01b5f52602160045260245ffd5b9052565b615138818461510e565b604060208201525f61514d60408301846145d7565b949350505050565b5f67ffffffffffffffff82111561516e5761516e614693565b50601f01601f191660200190565b5f6020828403121561518c575f80fd5b815167ffffffffffffffff8111156151a2575f80fd5b8201601f810184136151b2575f80fd5b80516151c06148cc82615155565b8181528560208385010111156151d4575f80fd5b8160208401602083015e5f91810160200191909152949350505050565b5f8151808452602084019350602083015f5b82811015614bbf5781516001600160801b0316865260209586019590910190600101615203565b5f8151808452602084019350602083015f5b82811015614bbf5761524f86835161505c565b604095909501946020919091019060010161523c565b604081525f61527760408301856151f1565b8281036020840152612925818561522a565b828152604060208201525f61514d604083018461522a565b5f80604083850312156152b2575f80fd5b505080516020909101519092909150565b634e487b7160e01b5f52601160045260245ffd5b808201808211156109c4576109c46152c3565b634e487b7160e01b5f52603260045260245ffd5b6001600160a01b038316815261010081016109e86020830184614b0d565b5f805f805f60a08688031215615330575f80fd5b855161533b8161489b565b602087015160408801516060890151608090990151929a91995097965090945092505050565b634e487b7160e01b5f52600160045260245ffd5b5f60ff821660ff810361538a5761538a6152c3565b60010192915050565b60a081525f6153a560a0830188614b84565b82810360208401526153b781886151f1565b90508560020b604084015282810360608401526153d4818661522a565b905082810360808401526153e8818561522a565b98975050505050505050565b602081525f6109e86020830184614b84565b615410818361510e565b6040602082018190525f90820152606001919050565b600282810b9082900b03627fffff198112627fffff821317156109c4576109c46152c3565b5f6020828403121561545b575f80fd5b5051919050565b818103818111156109c4576109c46152c3565b80820281158282048414176109c4576109c46152c3565b634e487b7160e01b5f52601260045260245ffd5b5f826154ae576154ae61548c565b500490565b5f80604083850312156154c4575f80fd5b8235600681106154d2575f80fd5b9150602083013567ffffffffffffffff8111156154ed575f80fd5b8301601f810185136154fd575f80fd5b803561550b6148cc82615155565b81815286602083850101111561551f575f80fd5b816020840160208301375f602083830101528093505050509250929050565b6001600160a01b03815416825260018101546001600160a01b038116602084015262ffffff8160a01c1660408401528060b81c60020b60608401525061558e60028201546001600160a01b031690565b6001600160a01b0316608083015260030154600281810b60a084015260189190911c900b60c090910152565b6001600160a01b038316815261010081016109e8602083018461553e565b5f82601f8301126155e7575f80fd5b6155f160406146f3565b806040840185811115615602575f80fd5b845b81811015614815578051845260209384019301615604565b5f82601f83011261562b575f80fd5b81516156396148cc82614878565b8082825260208201915060208360061b86010192508583111561565a575f80fd5b602085015b838110156149185761567187826155d8565b835260209092019160400161565f565b5f8060408385031215615692575f80fd5b8251602084015190925067ffffffffffffffff8111156156b0575f80fd5b6156bc8582860161561c565b9150509250929050565b80516124628161473f565b5f60a082840312156156e1575f80fd5b6156e96146a7565b905081516156f681614617565b8152602082015161570681614617565b6020820152604082015161571981614724565b6040820152606082015161572c8161473f565b606082015260808201516147c681614617565b5f82601f83011261574e575f80fd5b815161575c6148cc82614878565b8082825260208201915060208360051b86010192508583111561577d575f80fd5b602085015b838110156149185780516157958161489b565b835260209283019201615782565b5f805f805f60a086880312156157b7575f80fd5b855167ffffffffffffffff8111156157cd575f80fd5b8601601f810188136157dd575f80fd5b80516157eb6148cc82614878565b80828252602082019150602060e0840285010192508a83111561580c575f80fd5b6020840193505b828410156158785760e0848c03121561582a575f80fd5b6158326146d0565b61583c8c866156d1565b815260a085015161584c8161473f565b602082015260c085015161585f8161473f565b6040820152825260e09390930192602090910190615813565b80985050505050602086015167ffffffffffffffff811115615898575f80fd5b6158a48882890161573f565b9450506158b3604087016156c6565b9250606086015167ffffffffffffffff8111156158ce575f80fd5b6158da8882890161561c565b925050608086015167ffffffffffffffff8111156158f6575f80fd5b6159028882890161561c565b9150509295509295909350565b5f8060408385031215615920575f80fd5b825167ffffffffffffffff811115615936575f80fd5b6159428582860161573f565b925050602083015167ffffffffffffffff8111156156b0575f80fd5b5f805f806101208587031215615972575f80fd5b61597c86866156d1565b935060a085015161598c8161473f565b60c086015190935061599d8161473f565b915061486d8660e087016155d8565b6001600160a01b038616815261018081016159ca6020830187614b0d565b846101008301528361012083015261450f61014083018461505c565b5f602082840312156159f6575f80fd5b815180151581146109e8575f80fd5b805f5b6002811015611f3b57615a1b848361553e565b60e0939093019260049190910190600101615a08565b6001600160a01b038716815261026060208201525f615a54610260830188614b84565b9050615a636040830187615a05565b6001600160a01b0385166102008301526001600160a01b03841661022083015261ffff8316610240830152979650505050505050565b6001600160a01b038716815261026060208201525f615abc610260830188614b84565b615ac96040840188615a05565b8561020084015284610220840152828103610240840152615aea818561522a565b9998505050505050505050565b5f8260020b80615b0957615b0961548c565b808360020b0791505092915050565b5f8160020b8360020b80615b2e57615b2e61548c565b627fffff1982145f1982141615615b4757615b476152c3565b90059392505050565b600281810b9083900b01627fffff8113627fffff19821217156109c4576109c46152c3565b5f8260020b8260020b028060020b9150808214615b9457615b946152c3565b5092915050565b60e081016109c48284614b0d565b60ff81811683821601908111156109c4576109c46152c3565b6001600160a01b038616815261024060208201525f615be5610240830187614b84565b615bf26040840187615a05565b828103610200840152845180825260208087019201905f5b81811015615c315783516001600160801b0316835260209384019390920191600101615c0a565b5050838103610220850152615aea818661522a565b5f82518060208501845e5f92019182525091905056fea2646970667358221220e28ab45d1d4713973ec2440c9d87c8784ae074302d987b13565c809f67b5bf6064736f6c634300081a0033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

0000000000000000000000001f9840000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000000007dcc39b4d1c53cb31e1abc0e358b43987fef80f700000000000000000000000071e7d05be74ff748c45402c06a941c822d756dc500000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000c784554482d776545544830310000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c784554482d776545544830310000000000000000000000000000000000000000

-----Decoded View---------------
Arg [0] : _poolManager (address): 0x1F98400000000000000000000000000000000004
Arg [1] : _token0 (address): 0x0000000000000000000000000000000000000000
Arg [2] : _token1 (address): 0x7DCC39B4d1C53CB31e1aBc0e358b43987FEF80f7
Arg [3] : _owner (address): 0x71E7D05bE74fF748c45402c06A941c822d756dc5
Arg [4] : name (string): xETH-weETH01
Arg [5] : symbol (string): xETH-weETH01

-----Encoded View---------------
10 Constructor Arguments found :
Arg [0] : 0000000000000000000000001f98400000000000000000000000000000000004
Arg [1] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [2] : 0000000000000000000000007dcc39b4d1c53cb31e1abc0e358b43987fef80f7
Arg [3] : 00000000000000000000000071e7d05be74ff748c45402c06a941c822d756dc5
Arg [4] : 00000000000000000000000000000000000000000000000000000000000000c0
Arg [5] : 0000000000000000000000000000000000000000000000000000000000000100
Arg [6] : 000000000000000000000000000000000000000000000000000000000000000c
Arg [7] : 784554482d776545544830310000000000000000000000000000000000000000
Arg [8] : 000000000000000000000000000000000000000000000000000000000000000c
Arg [9] : 784554482d776545544830310000000000000000000000000000000000000000


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

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