ETH Price: $2,949.09 (+1.26%)

Contract

0xC1ec78f70680342930F52707D1f653D492BCd603

Overview

ETH Balance

0 ETH

ETH Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Block
From
To

There are no matching entries

1 Internal Transaction and > 10 Token Transfers found.

Latest 1 internal transaction

Parent Transaction Hash Block From To
3304791622025-04-26 17:25:37272 days ago1745688337  Contract Creation0 ETH

Cross-Chain Transactions
Loading...
Loading

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

Contract Name:
LpFeeTaker

Compiler Version
v0.8.28+commit.7893614a

Optimization Enabled:
Yes with 150 runs

Other Settings:
cancun EvmVersion

Contract Source Code (Solidity Standard Json-Input format)

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

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol";
import "@pancakeswap/v3-core/contracts/interfaces/callback/IPancakeV3SwapCallback.sol";

import { PoolOptimalSwapper } from "../../core/PoolOptimalSwapper.sol";
import { ILpFeeTaker } from "../../interfaces/strategies/ILpFeeTaker.sol";
import { FullMath } from "@uniswap/v3-core/contracts/libraries/FullMath.sol";
import { ILpValidator } from "../../interfaces/strategies/ILpValidator.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IUniswapV3Pool } from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import { OptimalSwap, V3PoolCallee } from "../../libraries/OptimalSwap.sol";

contract LpFeeTaker is ILpFeeTaker, IUniswapV3SwapCallback, IPancakeV3SwapCallback {
  using SafeERC20 for IERC20;

  uint256 internal constant Q64 = 0x10000000000000000;
  uint160 internal constant MAX_SQRT_RATIO_LESS_ONE =
    1_461_446_703_485_210_103_287_273_052_203_988_822_378_723_970_342 - 1;
  uint160 internal constant XOR_SQRT_RATIO =
    (4_295_128_739 + 1) ^ (1_461_446_703_485_210_103_287_273_052_203_988_822_378_723_970_342 - 1);

  address private currentPool;

  /// @notice Callback function required by Uniswap V3 to finalize swaps
  /// @param amount0Delta The change in token0 balance
  /// @param amount1Delta The change in token1 balance
  function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata) external override {
    require(msg.sender == currentPool, "Incorrect pool");

    IERC20 token0 = IERC20(IUniswapV3Pool(currentPool).token0());
    IERC20 token1 = IERC20(IUniswapV3Pool(currentPool).token1());

    if (amount0Delta > 0) token0.safeTransfer(msg.sender, uint256(amount0Delta));
    else if (amount1Delta > 0) token1.safeTransfer(msg.sender, uint256(amount1Delta));
  }

  /// @notice Callback function required by Pancake V3 to finalize swaps
  /// @param amount0Delta The change in token0 balance
  /// @param amount1Delta The change in token1 balance
  function pancakeV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata) external override {
    require(msg.sender == currentPool, "Incorrect pool");

    IERC20 token0 = IERC20(IUniswapV3Pool(currentPool).token0());
    IERC20 token1 = IERC20(IUniswapV3Pool(currentPool).token1());

    if (amount0Delta > 0) token0.safeTransfer(msg.sender, uint256(amount0Delta));
    else if (amount1Delta > 0) token1.safeTransfer(msg.sender, uint256(amount1Delta));
  }

  function takeFees(
    address token0,
    uint256 amount0,
    address token1,
    uint256 amount1,
    FeeConfig memory feeConfig,
    address principalToken,
    address pool,
    address validator
  ) external returns (uint256 fee0, uint256 fee1) {
    uint256 principalPlatformFee;
    uint256 principalVaultOwnerFee;
    uint256 principalGasFee;
    uint256 leftOverPlatformFee;
    uint256 leftOverVaultOwnerFee;
    uint256 leftOverGasFee;

    if (amount0 > 0) {
      (fee0, principalPlatformFee, principalVaultOwnerFee, principalGasFee) = _takeFee(amount0, feeConfig);
      if (fee0 > 0) IERC20(token0).safeTransferFrom(msg.sender, address(this), fee0);
    }
    if (amount1 > 0) {
      (fee1, leftOverPlatformFee, leftOverVaultOwnerFee, leftOverGasFee) = _takeFee(amount1, feeConfig);
      if (fee1 > 0) IERC20(token1).safeTransferFrom(msg.sender, address(this), fee1);
    }

    bool token0IsPrincipal = token0 == principalToken;
    address leftOverToken = token1;
    if (!token0IsPrincipal) {
      leftOverToken = token0;
      (principalPlatformFee, leftOverPlatformFee) = (leftOverPlatformFee, principalPlatformFee);
      (principalVaultOwnerFee, leftOverVaultOwnerFee) = (leftOverVaultOwnerFee, principalVaultOwnerFee);
      (principalGasFee, leftOverGasFee) = (leftOverGasFee, principalGasFee);
    }
    {
      // swap leftOver to principal
      uint256 totalLeftOver = leftOverGasFee + leftOverPlatformFee + leftOverVaultOwnerFee;
      if (totalLeftOver > 0) {
        (uint256 amountOut, uint256 amountIn) = _swapToPrincipal(
          SwapToPrincipalParams({
            pool: pool,
            token: leftOverToken,
            amount: totalLeftOver,
            principalToken: principalToken,
            amountOutMin: 0,
            swapData: ""
          }),
          ILpValidator(validator)
        );
        principalPlatformFee += FullMath.mulDiv(amountOut, leftOverPlatformFee, totalLeftOver);
        principalVaultOwnerFee += FullMath.mulDiv(amountOut, leftOverVaultOwnerFee, totalLeftOver);
        principalGasFee += FullMath.mulDiv(amountOut, leftOverGasFee, totalLeftOver);
        if (amountIn == totalLeftOver) {
          leftOverPlatformFee = 0;
          leftOverVaultOwnerFee = 0;
          leftOverGasFee = 0;
        } else {
          // if the swap is not exactIn, we need to calculate the left over tokens
          leftOverPlatformFee -= FullMath.mulDiv(amountIn, leftOverPlatformFee, totalLeftOver);
          leftOverVaultOwnerFee -= FullMath.mulDiv(amountIn, leftOverVaultOwnerFee, totalLeftOver);
          leftOverGasFee -= FullMath.mulDiv(amountIn, leftOverGasFee, totalLeftOver);
        }
      }
    }
    address recipient;
    recipient = feeConfig.platformFeeRecipient;
    if (principalPlatformFee > 0) {
      IERC20(principalToken).safeTransfer(recipient, principalPlatformFee);
      emit FeeCollected(msg.sender, FeeType.PLATFORM, recipient, principalToken, principalPlatformFee);
    }
    if (leftOverPlatformFee > 0) {
      IERC20(leftOverToken).safeTransfer(recipient, leftOverPlatformFee);
      emit FeeCollected(msg.sender, FeeType.PLATFORM, recipient, leftOverToken, leftOverPlatformFee);
    }

    recipient = feeConfig.vaultOwner;
    if (principalVaultOwnerFee > 0) {
      IERC20(principalToken).safeTransfer(recipient, principalVaultOwnerFee);
      emit FeeCollected(msg.sender, FeeType.OWNER, recipient, principalToken, principalVaultOwnerFee);
    }
    if (leftOverVaultOwnerFee > 0) {
      IERC20(leftOverToken).safeTransfer(recipient, leftOverVaultOwnerFee);
      emit FeeCollected(msg.sender, FeeType.OWNER, recipient, leftOverToken, leftOverVaultOwnerFee);
    }

    recipient = feeConfig.gasFeeRecipient;
    if (principalGasFee > 0) {
      IERC20(principalToken).safeTransfer(recipient, principalGasFee);
      emit FeeCollected(msg.sender, FeeType.GAS, recipient, principalToken, principalGasFee);
    }
    if (leftOverGasFee > 0) {
      IERC20(leftOverToken).safeTransfer(recipient, leftOverGasFee);
      emit FeeCollected(msg.sender, FeeType.GAS, recipient, leftOverToken, leftOverGasFee);
    }
  }

  /// @dev Takes the fee from the amount
  /// @param amount The amount to take the fee
  /// @param feeConfig The fee configuration
  /// @return totalFeeAmount The total fee amount
  function _takeFee(uint256 amount, FeeConfig memory feeConfig)
    internal
    pure
    returns (uint256 totalFeeAmount, uint256 platformFeeAmount, uint256 vaultOwnerFeeAmount, uint256 gasFeeAmount)
  {
    if (feeConfig.platformFeeBasisPoint > 0) {
      platformFeeAmount = (amount * feeConfig.platformFeeBasisPoint) / 10_000;
      if (platformFeeAmount > 0) totalFeeAmount += platformFeeAmount;
    }
    if (feeConfig.vaultOwnerFeeBasisPoint > 0) {
      vaultOwnerFeeAmount = (amount * feeConfig.vaultOwnerFeeBasisPoint) / 10_000;
      if (vaultOwnerFeeAmount > 0) totalFeeAmount += vaultOwnerFeeAmount;
    }
    if (feeConfig.gasFeeX64 > 0) {
      gasFeeAmount = FullMath.mulDiv(amount, feeConfig.gasFeeX64, Q64);
      if (gasFeeAmount > 0) totalFeeAmount += gasFeeAmount;
    }
  }

  /// @notice Swaps the token to the principal token
  /// @param params The parameters for swapping the token
  /// @return amountOut The result amount of principal token
  /// @return amountInUsed The amount of token used
  function _swapToPrincipal(SwapToPrincipalParams memory params, ILpValidator validator)
    internal
    returns (uint256 amountOut, uint256 amountInUsed)
  {
    require(params.token != params.principalToken, "token is already principal");

    if (address(validator) != address(0)) validator.validatePriceSanity(params.pool);

    (amountOut, amountInUsed) = _poolSwap(params.pool, params.amount, params.token < params.principalToken);
    require(amountOut >= params.amountOutMin, "Insufficient output amount");
  }

  /// @dev Make a direct `exactIn` pool swap
  /// @param pool The address of the Uniswap V3 pool
  /// @param amountIn The amount of token to be swapped
  /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
  /// @return amountOut The amount of token received after swap
  /// @return amountInUsed The amount of token used for swap
  function _poolSwap(address pool, uint256 amountIn, bool zeroForOne)
    internal
    returns (uint256 amountOut, uint256 amountInUsed)
  {
    if (amountIn != 0) {
      currentPool = pool;
      uint160 sqrtPriceLimitX96;
      // Equivalent to `sqrtPriceLimitX96 = zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1`
      assembly {
        sqrtPriceLimitX96 := xor(MAX_SQRT_RATIO_LESS_ONE, mul(XOR_SQRT_RATIO, zeroForOne))
      }
      (int256 amount0Delta, int256 amount1Delta) =
        V3PoolCallee.wrap(pool).swap(address(this), zeroForOne, int256(amountIn), sqrtPriceLimitX96, "");

      unchecked {
        amountOut = zeroForOne ? uint256(-amount1Delta) : uint256(-amount0Delta);
        amountInUsed = zeroForOne ? uint256(amount0Delta) : uint256(amount1Delta);
      }
    }
  }
}

// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;

/// @title BitMath
/// @author Aperture Finance
/// @author Modified from Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibBit.sol)
/// @dev This library provides functionality for computing bit properties of an unsigned integer
library BitMath {
    /// @notice Returns the index of the most significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @dev The function satisfies the property:
    ///     If x == 0, r == 0. Otherwise
    ///     x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)
    /// @param x the value for which to compute the most significant bit
    /// @return r the index of the most significant bit
    function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
        assembly {
            // r = x >= 2**128 ? 128 : 0
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            // r += (x >> r) >= 2**64 ? 64 : 0
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            // r += (x >> r) >= 2**32 ? 32 : 0
            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))))
            r := or(
                r,
                byte(
                    and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                    0x0706060506020504060203020504030106050205030304010505030400000000
                )
            )
        }
    }

    /// @notice Returns the index of the least significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @dev The function satisfies the property:
    ///     If x == 0, r == 0. Otherwise
    ///     (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)
    /// @param x the value for which to compute the least significant bit
    /// @return r the index of the least significant bit
    function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
        assembly {
            // Isolate the least significant bit, x = x & -x = x & (~x + 1)
            x := and(x, sub(0, x))

            // r = x >= 2**128 ? 128 : 0
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            // r += (x >> r) >= 2**64 ? 64 : 0
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            // r += (x >> r) >= 2**32 ? 32 : 0
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))

            // For the remaining 32 bits, use a De Bruijn lookup.
            // https://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup
            r := or(
                r,
                byte(
                    and(div(0xd76453e0, shr(r, x)), 0x1f),
                    0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405
                )
            )
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

import "solady/src/utils/FixedPointMathLib.sol";

/// @title Contains 512-bit math functions
/// @author Aperture Finance
/// @author Modified from Uniswap (https://github.com/uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol)
/// @author Credit to Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @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 {
    /// @dev The full precision multiply-divide operation failed, either due
    /// to the result being larger than 256 bits, or a division by a zero.
    error FullMulDivFailed();

    /// @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) {
        return FixedPointMathLib.fullMulDiv(a, b, denominator);
    }

    /// @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) {
        return FixedPointMathLib.fullMulDivUp(a, b, denominator);
    }

    /// @notice Calculates a * b / 2^96 with full precision.
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @return result The 256-bit result
    function mulDivQ96(uint256 a, uint256 b) internal pure returns (uint256 result) {
        assembly ("memory-safe") {
            // 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`.

            // Least significant 256 bits of the product.
            let prod0 := mul(a, b)
            let mm := mulmod(a, b, not(0))
            // Most significant 256 bits of the product.
            let prod1 := sub(mm, add(prod0, lt(mm, prod0)))

            // Make sure the result is less than `2**256`.
            if iszero(gt(0x1000000000000000000000000, prod1)) {
                // Store the function selector of `FullMulDivFailed()`.
                mstore(0x00, 0xae47f702)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            // Divide [prod1 prod0] by 2^96.
            result := or(shr(96, prod0), shl(160, prod1))
        }
    }

    /// @notice Calculates a * b / 2^128 with full precision.
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @return result The 256-bit result
    function mulDivQ128(uint256 a, uint256 b) internal pure returns (uint256 result) {
        assembly ("memory-safe") {
            // 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`.

            // Least significant 256 bits of the product.
            let prod0 := mul(a, b)
            let mm := mulmod(a, b, not(0))
            // Most significant 256 bits of the product.
            let prod1 := sub(mm, add(prod0, lt(mm, prod0)))

            // Make sure the result is less than `2**256`.
            if iszero(gt(0x100000000000000000000000000000000, prod1)) {
                // Store the function selector of `FullMulDivFailed()`.
                mstore(0x00, 0xae47f702)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            // Divide [prod1 prod0] by 2^128.
            result := or(shr(128, prod0), shl(128, prod1))
        }
    }

    /// @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
    function sqrt(uint256 x) internal pure returns (uint256) {
        return FixedPointMathLib.sqrt(x);
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// User defined value types are introduced in Solidity v0.8.8.
// https://blog.soliditylang.org/2021/09/27/user-defined-value-types/
pragma solidity >=0.8.8;

import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";

type V3PoolCallee is address;
using PoolCaller for V3PoolCallee global;

/// @title Uniswap v3 Pool Caller
/// @author Aperture Finance
/// @notice Gas efficient library to call `IUniswapV3Pool` assuming the pool exists.
/// @dev Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// However, this is safe because "Note that you do not need to update the free memory pointer if there is no following
/// allocation, but you can only use memory starting from the current offset given by the free memory pointer."
/// according to https://docs.soliditylang.org/en/latest/assembly.html#memory-safety.
library PoolCaller {
    /// @dev Makes a staticcall to a pool with only the selector and returns a memory word.
    function staticcall_0i_1o(V3PoolCallee pool, bytes4 selector) internal view returns (uint256 res) {
        assembly ("memory-safe") {
            // Write the function selector into memory.
            mstore(0, selector)
            // We use 4 because of the length of our calldata.
            // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
            if iszero(staticcall(gas(), pool, 0, 4, 0, 0x20)) {
                revert(0, 0)
            }
            res := mload(0)
        }
    }

    /// @dev Makes a staticcall to a pool with only the selector and returns two memory words.
    function staticcall_0i_2o(V3PoolCallee pool, bytes4 selector) internal view returns (uint256 res0, uint256 res1) {
        assembly ("memory-safe") {
            // Write the function selector into memory.
            mstore(0, selector)
            // We use 4 because of the length of our calldata.
            // We use 0 and 64 to copy up to 64 bytes of return data into the scratch space.
            if iszero(staticcall(gas(), pool, 0, 4, 0, 0x40)) {
                revert(0, 0)
            }
            res0 := mload(0)
            res1 := mload(0x20)
        }
    }

    /// @dev Makes a staticcall to a pool with one argument.
    function staticcall_1i_0o(
        V3PoolCallee pool,
        bytes4 selector,
        uint256 arg,
        uint256 out,
        uint256 outsize
    ) internal view {
        assembly ("memory-safe") {
            // Write the abi-encoded calldata into memory.
            mstore(0, selector)
            mstore(4, arg)
            // We use 36 because of the length of our calldata.
            if iszero(staticcall(gas(), pool, 0, 0x24, out, outsize)) {
                revert(0, 0)
            }
        }
    }

    /// @dev Equivalent to `IUniswapV3Pool.fee`
    /// @param pool Uniswap v3 pool
    function fee(V3PoolCallee pool) internal view returns (uint24 f) {
        uint256 res = staticcall_0i_1o(pool, IUniswapV3PoolImmutables.fee.selector);
        assembly {
            f := res
        }
    }

    /// @dev Equivalent to `IUniswapV3Pool.tickSpacing`
    /// @param pool Uniswap v3 pool
    function tickSpacing(V3PoolCallee pool) internal view returns (int24 ts) {
        uint256 res = staticcall_0i_1o(pool, IUniswapV3PoolImmutables.tickSpacing.selector);
        assembly {
            ts := res
        }
    }

    /// @dev Equivalent to `IUniswapV3Pool.slot0`
    /// @param pool Uniswap v3 pool
    function slot0(
        V3PoolCallee pool
    )
        internal
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        )
    {
        bytes4 selector = IUniswapV3PoolState.slot0.selector;
        assembly ("memory-safe") {
            // Get a pointer to some free memory.
            let fmp := mload(0x40)
            // Write the function selector into memory.
            mstore(0, selector)
            // We use 4 because of the length of our calldata.
            // We copy up to 224 bytes of return data after fmp.
            if iszero(staticcall(gas(), pool, 0, 4, fmp, 0xe0)) {
                revert(0, 0)
            }
            sqrtPriceX96 := mload(fmp)
            tick := mload(add(fmp, 0x20))
            observationIndex := mload(add(fmp, 0x40))
            observationCardinality := mload(add(fmp, 0x60))
            observationCardinalityNext := mload(add(fmp, 0x80))
            feeProtocol := mload(add(fmp, 0xa0))
            unlocked := mload(add(fmp, 0xc0))
        }
    }

    /// @dev Equivalent to `(uint160 sqrtPriceX96, int24 tick, , , , , ) = pool.slot0()`
    /// @param pool Uniswap v3 pool
    function sqrtPriceX96AndTick(V3PoolCallee pool) internal view returns (uint160 sqrtPriceX96, int24 tick) {
        (uint256 res0, uint256 res1) = staticcall_0i_2o(pool, IUniswapV3PoolState.slot0.selector);
        assembly {
            sqrtPriceX96 := res0
            tick := res1
        }
    }

    /// @dev Equivalent to `IUniswapV3Pool.feeGrowthGlobal0X128`
    /// @param pool Uniswap v3 pool
    function feeGrowthGlobal0X128(V3PoolCallee pool) internal view returns (uint256 f) {
        f = staticcall_0i_1o(pool, IUniswapV3PoolState.feeGrowthGlobal0X128.selector);
    }

    /// @dev Equivalent to `IUniswapV3Pool.feeGrowthGlobal1X128`
    /// @param pool Uniswap v3 pool
    function feeGrowthGlobal1X128(V3PoolCallee pool) internal view returns (uint256 f) {
        f = staticcall_0i_1o(pool, IUniswapV3PoolState.feeGrowthGlobal1X128.selector);
    }

    /// @dev Equivalent to `IUniswapV3Pool.protocolFees`
    /// @param pool Uniswap v3 pool
    function protocolFees(V3PoolCallee pool) internal view returns (uint128 token0, uint128 token1) {
        (uint256 res0, uint256 res1) = staticcall_0i_2o(pool, IUniswapV3PoolState.protocolFees.selector);
        assembly {
            token0 := res0
            token1 := res1
        }
    }

    /// @dev Equivalent to `IUniswapV3Pool.liquidity`
    /// @param pool Uniswap v3 pool
    function liquidity(V3PoolCallee pool) internal view returns (uint128 l) {
        uint256 res = staticcall_0i_1o(pool, IUniswapV3PoolState.liquidity.selector);
        assembly {
            l := res
        }
    }

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

    /// @dev Equivalent to `IUniswapV3Pool.ticks`
    /// @param pool Uniswap v3 pool
    function ticks(V3PoolCallee pool, int24 tick) internal view returns (TickInfo memory info) {
        uint256 _tick;
        uint256 out;
        assembly {
            // Pad int24 to 32 bytes.
            _tick := signextend(2, tick)
            out := info
        }
        // We copy up to 256 bytes of return data at info's pointer.
        staticcall_1i_0o(pool, IUniswapV3PoolState.ticks.selector, _tick, out, 0x100);
    }

    /// @dev Equivalent to `( , int128 liquidityNet, , , , , , ) = pool.ticks(tick)`
    /// @param pool Uniswap v3 pool
    function liquidityNet(V3PoolCallee pool, int24 tick) internal view returns (int128 ln) {
        uint256 _tick;
        assembly {
            // Pad int24 to 32 bytes.
            _tick := signextend(2, tick)
        }
        // We use 0 and 64 to copy up to 64 bytes of return data into the scratch space.
        staticcall_1i_0o(pool, IUniswapV3PoolState.ticks.selector, _tick, 0, 0x40);
        assembly ("memory-safe") {
            ln := mload(0x20)
        }
    }

    /// @dev Equivalent to `IUniswapV3Pool.tickBitmap`
    /// @param pool Uniswap v3 pool
    /// @param wordPos The key in the mapping containing the word in which the bit is stored
    function tickBitmap(V3PoolCallee pool, int16 wordPos) internal view returns (uint256 tickWord) {
        uint256 _wordPos;
        assembly {
            // Pad int16 to 32 bytes.
            _wordPos := signextend(1, wordPos)
        }
        // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
        staticcall_1i_0o(pool, IUniswapV3PoolState.tickBitmap.selector, _wordPos, 0, 0x20);
        assembly ("memory-safe") {
            tickWord := mload(0)
        }
    }

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

    /// @dev Equivalent to `IUniswapV3Pool.positions`
    /// @param pool Uniswap v3 pool
    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
    function positions(V3PoolCallee pool, bytes32 key) internal view returns (PositionInfo memory info) {
        uint256 out;
        assembly {
            out := info
        }
        // We copy up to 160 bytes of return data at info's pointer.
        staticcall_1i_0o(pool, IUniswapV3PoolState.positions.selector, uint256(key), out, 0xa0);
    }

    /// @dev Equivalent to `IUniswapV3Pool.observations`
    /// @param pool Uniswap v3 pool
    /// @param index The element of the observations array to fetch
    /// @return blockTimestamp The timestamp of the observation,
    /// @return tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
    /// @return secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
    /// @return initialized whether the observation has been initialized and the values are safe to use
    function observations(
        V3PoolCallee pool,
        uint256 index
    )
        internal
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        )
    {
        uint256 fmp;
        assembly ("memory-safe") {
            // Get a pointer to some free memory.
            fmp := mload(0x40)
        }
        // We copy up to 128 bytes of return data at the free memory pointer.
        staticcall_1i_0o(pool, IUniswapV3PoolState.observations.selector, index, fmp, 0x80);
        assembly ("memory-safe") {
            blockTimestamp := mload(fmp)
            tickCumulative := mload(add(fmp, 0x20))
            secondsPerLiquidityCumulativeX128 := mload(add(fmp, 0x40))
            initialized := mload(add(fmp, 0x60))
        }
    }

    /// @dev Equivalent to `IUniswapV3Pool.swap`
    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
    /// @param pool Uniswap v3 pool
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        V3PoolCallee pool,
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes memory data
    ) internal returns (int256 amount0, int256 amount1) {
        bytes4 selector = IUniswapV3PoolActions.swap.selector;
        assembly ("memory-safe") {
            // Get a pointer to some free memory.
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 4), recipient)
            mstore(add(fmp, 0x24), zeroForOne)
            mstore(add(fmp, 0x44), amountSpecified)
            mstore(add(fmp, 0x64), sqrtPriceLimitX96)
            // Use 160 for the offset of `data` in calldata.
            mstore(add(fmp, 0x84), 0xa0)
            // length = data.length + 32
            let length := add(mload(data), 0x20)
            // TODO: Use `mcopy`
            // Call the identity precompile 0x04 to copy `data` into calldata.
            pop(staticcall(gas(), 0x04, data, length, add(fmp, 0xa4), length))
            // We use `196 + data.length` for the length of our calldata.
            // We use 0 and 64 to copy up to 64 bytes of return data into the scratch space.
            if iszero(
                and(
                    // The arguments of `and` are evaluated from right to left.
                    eq(returndatasize(), 0x40), // Ensure `returndatasize` is 64.
                    call(gas(), pool, 0, fmp, add(0xa4, length), 0, 0x40)
                )
            ) {
                // It is safe to overwrite the free memory pointer 0x40 and the zero pointer 0x60 here before exiting
                // because a contract obtains a freshly cleared instance of memory for each message call.
                returndatacopy(0, 0, returndatasize())
                // Bubble up the revert reason.
                revert(0, returndatasize())
            }
            // Read the return data.
            amount0 := mload(0)
            amount1 := mload(0x20)
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;

/// @title Safe casting methods
/// @author Aperture Finance
/// @author Modified from Uniswap (https://github.com/uniswap/v3-core/blob/main/contracts/libraries/SafeCast.sol)
/// @notice Contains methods for safely casting between types
library SafeCast {
    /// @notice Cast a uint256 to a uint160, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return The downcasted integer, now type uint160
    function toUint160(uint256 x) internal pure returns (uint160) {
        if (x >= 1 << 160) revert();
        return uint160(x);
    }

    /// @notice Cast a uint256 to a uint128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return The downcasted integer, now type uint128
    function toUint128(uint256 x) internal pure returns (uint128) {
        if (x >= 1 << 128) revert();
        return uint128(x);
    }

    /// @notice Cast a int256 to a int128, revert on overflow or underflow
    /// @param x The int256 to be downcasted
    /// @return The downcasted integer, now type int128
    function toInt128(int256 x) internal pure returns (int128) {
        unchecked {
            if (((1 << 127) + uint256(x)) >> 128 == uint256(0)) return int128(x);
            revert();
        }
    }

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

    /// @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) revert();
        return int128(int256(x));
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;

import "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol";

import "./FullMath.sol";
import "./SafeCast.sol";
import "./TernaryLib.sol";
import "./UnsafeMath.sol";

/// @title Functions based on Q64.96 sqrt price and liquidity
/// @author Aperture Finance
/// @author Modified from Uniswap (https://github.com/uniswap/v3-core/blob/main/contracts/libraries/SqrtPriceMath.sol)
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
    using SafeCast for uint256;

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

        if (add) {
            unchecked {
                uint256 product = amount * _sqrtPX96;
                // checks for overflow
                if (UnsafeMath.div(product, amount) == _sqrtPX96) {
                    uint256 denominator = numerator1 + product;
                    // checks for overflow
                    if (denominator >= numerator1) {
                        // always fits in 160 bits
                        return uint160(FullMath.mulDivRoundingUp(numerator1, _sqrtPX96, denominator));
                    }
                }
            }
            // denominator is checked for overflow
            return uint160(UnsafeMath.divRoundingUp(numerator1, UnsafeMath.div(numerator1, _sqrtPX96) + amount));
        } else {
            uint256 denominator;
            assembly ("memory-safe") {
                // if the product overflows, we know the denominator underflows
                // in addition, we must check that the denominator does not underflow
                let product := mul(amount, _sqrtPX96)
                if iszero(and(eq(div(product, amount), _sqrtPX96), gt(numerator1, product))) {
                    revert(0, 0)
                }
                denominator := sub(numerator1, product)
            }
            return FullMath.mulDivRoundingUp(numerator1, _sqrtPX96, denominator).toUint160();
        }
    }

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

            nextSqrtPrice = (uint256(sqrtPX96) + quotient).toUint160();
        } else {
            uint256 quotient = (
                amount >> 160 == 0
                    ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, _liquidity)
                    : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, _liquidity)
            );
            assembly ("memory-safe") {
                if iszero(gt(sqrtPX96, quotient)) {
                    revert(0, 0)
                }
                // always fits 160 bits
                nextSqrtPrice := sub(sqrtPX96, quotient)
            }
        }
    }

    /// @notice Gets the next sqrt price given an input amount of token0 or token1
    /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
    /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
    /// @param liquidity The amount of usable liquidity
    /// @param amountIn How much of token0, or token1, is being swapped in
    /// @param zeroForOne Whether the amount in is token0 or token1
    /// @return sqrtQX96 The price after adding the input amount to token0 or token1
    function getNextSqrtPriceFromInput(
        uint160 sqrtPX96,
        uint128 liquidity,
        uint256 amountIn,
        bool zeroForOne
    ) internal pure returns (uint160 sqrtQX96) {
        assembly ("memory-safe") {
            if or(iszero(sqrtPX96), iszero(liquidity)) {
                revert(0, 0)
            }
        }
        // round to make sure that we don't pass the target price
        return
            zeroForOne
                ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
                : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
    }

    /// @notice Gets the next sqrt price given an output amount of token0 or token1
    /// @dev Throws if price or liquidity are 0 or the next price is out of bounds
    /// @param sqrtPX96 The starting price before accounting for the output amount
    /// @param liquidity The amount of usable liquidity
    /// @param amountOut How much of token0, or token1, is being swapped out
    /// @param zeroForOne Whether the amount out is token0 or token1
    /// @return sqrtQX96 The price after removing the output amount of token0 or token1
    function getNextSqrtPriceFromOutput(
        uint160 sqrtPX96,
        uint128 liquidity,
        uint256 amountOut,
        bool zeroForOne
    ) internal pure returns (uint160 sqrtQX96) {
        assembly ("memory-safe") {
            if or(iszero(sqrtPX96), iszero(liquidity)) {
                revert(0, 0)
            }
        }
        // round to make sure that we pass the target price
        return
            zeroForOne
                ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
                : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
    }

    /// @notice Gets the amount0 delta between two prices
    /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
    /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
    /// @param sqrtRatioAX96 A sqrt price assumed to be lower otherwise swapped
    /// @param sqrtRatioBX96 Another sqrt price
    /// @param liquidity The amount of usable liquidity
    /// @param roundUp Whether to round the amount up or down
    /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices
    function getAmount0Delta(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity,
        bool roundUp
    ) internal pure returns (uint256 amount0) {
        (sqrtRatioAX96, sqrtRatioBX96) = TernaryLib.sort2U160(sqrtRatioAX96, sqrtRatioBX96);
        assembly ("memory-safe") {
            if iszero(sqrtRatioAX96) {
                revert(0, 0)
            }
        }
        uint256 numerator1;
        uint256 numerator2;
        assembly {
            numerator1 := shl(96, liquidity)
            numerator2 := sub(sqrtRatioBX96, sqrtRatioAX96)
        }
        /**
         * Equivalent to:
         *   roundUp
         *       ? FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96).divRoundingUp(sqrtRatioAX96)
         *       : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;
         * If `md = mulDiv(n1, n2, srb) == mulDivRoundingUp(n1, n2, srb)`, then `mulmod(n1, n2, srb) == 0`.
         * Add `roundUp && md % sra > 0` to `div(md, sra)`.
         * If `md = mulDiv(n1, n2, srb)` and `mulDivRoundingUp(n1, n2, srb)` differs by 1 and `sra > 0`,
         * then `(md + 1).divRoundingUp(sra) == md.div(sra) + 1` whether `sra` fully divides `md` or not.
         */
        uint256 mulDivResult = FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96);
        assembly {
            amount0 := add(
                div(mulDivResult, sqrtRatioAX96),
                and(gt(or(mod(mulDivResult, sqrtRatioAX96), mulmod(numerator1, numerator2, sqrtRatioBX96)), 0), roundUp)
            )
        }
    }

    /// @notice Gets the amount1 delta between two prices
    /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
    /// @param sqrtRatioAX96 A sqrt price assumed to be lower otherwise swapped
    /// @param sqrtRatioBX96 Another sqrt price
    /// @param liquidity The amount of usable liquidity
    /// @param roundUp Whether to round the amount up, or down
    /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices
    function getAmount1Delta(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity,
        bool roundUp
    ) internal pure returns (uint256 amount1) {
        uint256 numerator = TernaryLib.absDiffU160(sqrtRatioAX96, sqrtRatioBX96);
        uint256 denominator = FixedPoint96.Q96;
        uint256 _liquidity;
        assembly {
            // avoid implicit upcasting
            _liquidity := liquidity
        }
        /**
         * Equivalent to:
         *   amount1 = roundUp
         *       ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)
         *       : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
         * Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`.
         */
        amount1 = FullMath.mulDivQ96(_liquidity, numerator);
        assembly {
            amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), roundUp))
        }
    }

    /// @notice Helper that gets signed token0 delta
    /// @param sqrtRatioAX96 A sqrt price
    /// @param sqrtRatioBX96 Another sqrt price
    /// @param liquidity The change in liquidity for which to compute the amount0 delta
    /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices
    function getAmount0Delta(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        int128 liquidity
    ) internal pure returns (int256 amount0) {
        /**
         * Equivalent to:
         *   amount0 = liquidity < 0
         *       ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
         *       : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
         */
        bool roundUp;
        uint256 mask;
        uint128 liquidityAbs;
        assembly {
            // mask = 0 if liquidity >= 0 else -1
            mask := sar(255, liquidity)
            // roundUp = 1 if liquidity >= 0 else 0
            roundUp := iszero(mask)
            liquidityAbs := xor(mask, add(mask, liquidity))
        }
        // amount0Abs = liquidity / sqrt(lower) - liquidity / sqrt(upper) < type(uint224).max
        // always fits in 224 bits, no need for toInt256()
        uint256 amount0Abs = getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, liquidityAbs, roundUp);
        assembly {
            // If liquidity >= 0, amount0 = |amount0| = 0 ^ |amount0|
            // If liquidity < 0, amount0 = -|amount0| = ~|amount0| + 1 = (-1) ^ |amount0| - (-1)
            amount0 := sub(xor(amount0Abs, mask), mask)
        }
    }

    /// @notice Helper that gets signed token1 delta
    /// @param sqrtRatioAX96 A sqrt price
    /// @param sqrtRatioBX96 Another sqrt price
    /// @param liquidity The change in liquidity for which to compute the amount1 delta
    /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices
    function getAmount1Delta(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        int128 liquidity
    ) internal pure returns (int256 amount1) {
        /**
         * Equivalent to:
         *   amount1 = liquidity < 0
         *       ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
         *       : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
         */
        bool roundUp;
        uint256 mask;
        uint128 liquidityAbs;
        assembly {
            // mask = 0 if liquidity >= 0 else -1
            mask := sar(255, liquidity)
            // roundUp = 1 if liquidity >= 0 else 0
            roundUp := iszero(mask)
            liquidityAbs := xor(mask, add(mask, liquidity))
        }
        // amount1Abs = liquidity * (sqrt(upper) - sqrt(lower)) < type(uint192).max
        // always fits in 192 bits, no need for toInt256()
        uint256 amount1Abs = getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, liquidityAbs, roundUp);
        assembly {
            // If liquidity >= 0, amount1 = |amount1| = 0 ^ |amount1|
            // If liquidity < 0, amount1 = -|amount1| = ~|amount1| + 1 = (-1) ^ |amount1| - (-1)
            amount1 := sub(xor(amount1Abs, mask), mask)
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;

import "./SqrtPriceMath.sol";

/// @title Computes the result of a swap within ticks
/// @author Aperture Finance
/// @author Modified from Uniswap (https://github.com/uniswap/v3-core/blob/main/contracts/libraries/SwapMath.sol)
/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.
library SwapMath {
    uint256 internal constant MAX_FEE_PIPS = 1e6;

    /// @notice Computes the sqrt price target for the next swap step
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param sqrtPriceNextX96 The Q64.96 sqrt price for the next initialized tick
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value
    /// after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @return sqrtPriceTargetX96 The price target for the next swap step
    function getSqrtPriceTarget(
        bool zeroForOne,
        uint160 sqrtPriceNextX96,
        uint160 sqrtPriceLimitX96
    ) internal pure returns (uint160 sqrtPriceTargetX96) {
        assembly {
            // a flag to toggle between sqrtPriceNextX96 and sqrtPriceLimitX96
            // when zeroForOne == true, nextOrLimit reduces to sqrtPriceNextX96 >= sqrtPriceLimitX96
            // sqrtPriceTargetX96 = max(sqrtPriceNextX96, sqrtPriceLimitX96)
            // when zeroForOne == false, nextOrLimit reduces to sqrtPriceNextX96 < sqrtPriceLimitX96
            // sqrtPriceTargetX96 = min(sqrtPriceNextX96, sqrtPriceLimitX96)
            let nextOrLimit := xor(lt(sqrtPriceNextX96, sqrtPriceLimitX96), zeroForOne)
            let symDiff := xor(sqrtPriceNextX96, sqrtPriceLimitX96)
            sqrtPriceTargetX96 := xor(sqrtPriceLimitX96, mul(symDiff, nextOrLimit))
        }
    }

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

            if (!exactOut) {
                uint256 amountRemainingLessFee = FullMath.mulDiv(
                    uint256(amountRemaining),
                    MAX_FEE_PIPS - _feePips,
                    MAX_FEE_PIPS
                );
                amountIn = zeroForOne
                    ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)
                    : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);
                if (amountRemainingLessFee >= amountIn) {
                    // `amountIn` is capped by the target price
                    sqrtRatioNextX96 = sqrtRatioTargetX96;
                    feeAmount = FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_FEE_PIPS - _feePips);
                } else {
                    // exhaust the remaining amount
                    amountIn = amountRemainingLessFee;
                    sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(
                        sqrtRatioCurrentX96,
                        liquidity,
                        amountRemainingLessFee,
                        zeroForOne
                    );
                    // we didn't reach the target, so take the remainder of the maximum input as fee
                    feeAmount = uint256(amountRemaining) - amountIn;
                }
                amountOut = zeroForOne
                    ? SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false)
                    : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);
            } else {
                amountOut = zeroForOne
                    ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)
                    : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);
                if (uint256(-amountRemaining) >= amountOut) {
                    // `amountOut` is capped by the target price
                    sqrtRatioNextX96 = sqrtRatioTargetX96;
                } else {
                    // cap the output amount to not exceed the remaining output amount
                    amountOut = uint256(-amountRemaining);
                    sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(
                        sqrtRatioCurrentX96,
                        liquidity,
                        amountOut,
                        zeroForOne
                    );
                }
                amountIn = zeroForOne
                    ? SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true)
                    : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);
                feeAmount = FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_FEE_PIPS - _feePips);
            }
        }
    }

    /// @notice Computes the result of swapping some amount in given the parameters of the swap
    /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive
    /// @param sqrtRatioCurrentX96 The current sqrt price of the pool
    /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred
    /// @param liquidity The usable liquidity
    /// @param amountRemaining How much input amount is remaining to be swapped in
    /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip
    /// @return sqrtRatioNextX96 The price after swapping the amount in, not to exceed the price target
    /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap
    /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap
    function computeSwapStepExactIn(
        uint160 sqrtRatioCurrentX96,
        uint160 sqrtRatioTargetX96,
        uint128 liquidity,
        uint256 amountRemaining,
        uint256 feePips
    ) internal pure returns (uint160 sqrtRatioNextX96, uint256 amountIn, uint256 amountOut) {
        bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;
        uint256 amountRemainingLessFee = FullMath.mulDiv(
            amountRemaining,
            UnsafeMath.sub(MAX_FEE_PIPS, feePips),
            MAX_FEE_PIPS
        );
        amountIn = zeroForOne
            ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)
            : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);
        if (amountRemainingLessFee >= amountIn) {
            // `amountIn` is capped by the target price
            sqrtRatioNextX96 = sqrtRatioTargetX96;
            // add the fee amount
            amountIn = FullMath.mulDivRoundingUp(amountIn, MAX_FEE_PIPS, UnsafeMath.sub(MAX_FEE_PIPS, feePips));
        } else {
            // exhaust the remaining amount
            amountIn = amountRemaining;
            sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(
                sqrtRatioCurrentX96,
                liquidity,
                amountRemainingLessFee,
                zeroForOne
            );
        }
        amountOut = zeroForOne
            ? SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false)
            : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);
    }

    /// @notice Computes the result of swapping some amount out, given the parameters of the swap
    /// @param sqrtRatioCurrentX96 The current sqrt price of the pool
    /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred
    /// @param liquidity The usable liquidity
    /// @param amountRemaining How much output amount is remaining to be swapped out
    /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip
    /// @return sqrtRatioNextX96 The price after swapping the amount out, not to exceed the price target
    /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap
    /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap
    function computeSwapStepExactOut(
        uint160 sqrtRatioCurrentX96,
        uint160 sqrtRatioTargetX96,
        uint128 liquidity,
        uint256 amountRemaining,
        uint256 feePips
    ) internal pure returns (uint160 sqrtRatioNextX96, uint256 amountIn, uint256 amountOut) {
        bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;
        amountOut = zeroForOne
            ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)
            : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);
        if (amountRemaining >= amountOut) {
            // `amountOut` is capped by the target price
            sqrtRatioNextX96 = sqrtRatioTargetX96;
        } else {
            // cap the output amount to not exceed the remaining output amount
            amountOut = amountRemaining;
            sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(
                sqrtRatioCurrentX96,
                liquidity,
                amountRemaining,
                zeroForOne
            );
        }
        amountIn = FullMath.mulDivRoundingUp(
            zeroForOne
                ? SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true)
                : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true),
            MAX_FEE_PIPS,
            UnsafeMath.sub(MAX_FEE_PIPS, feePips)
        );
    }
}

// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;

/// @title Library for efficient ternary operations
/// @author Aperture Finance
library TernaryLib {
    /// @notice Equivalent to the ternary operator: `condition ? a : b`
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256 res) {
        assembly {
            res := xor(b, mul(xor(a, b), condition))
        }
    }

    /// @notice Equivalent to the ternary operator: `condition ? a : b`
    function ternary(bool condition, address a, address b) internal pure returns (address res) {
        assembly {
            res := xor(b, mul(xor(a, b), condition))
        }
    }

    /// @notice Equivalent to: `uint256(x < 0 ? -x : x)`
    function abs(int256 x) internal pure returns (uint256 y) {
        assembly {
            // mask = 0 if x >= 0 else -1
            let mask := sar(255, x)
            // If x >= 0, |x| = x = 0 ^ x
            // If x < 0, |x| = ~~|x| = ~(-|x| - 1) = ~(x - 1) = -1 ^ (x - 1)
            // Either case, |x| = mask ^ (x + mask)
            y := xor(mask, add(mask, x))
        }
    }

    /// @notice Equivalent to: `a > b ? a - b : b - a`
    function absDiff(uint256 a, uint256 b) internal pure returns (uint256 res) {
        assembly {
            // The diff between two `uint256` may overflow `int256`
            let diff0 := sub(a, b)
            let diff1 := sub(b, a)
            res := xor(diff1, mul(xor(diff0, diff1), gt(a, b)))
        }
    }

    /// @notice Equivalent to: `a > b ? a - b : b - a`
    function absDiffU160(uint160 a, uint160 b) internal pure returns (uint256 res) {
        assembly {
            let diff := sub(a, b)
            let mask := sar(255, diff)
            res := xor(mask, add(mask, diff))
        }
    }

    /// @notice Equivalent to: `a < b ? a : b`
    function min(uint256 a, uint256 b) internal pure returns (uint256 res) {
        assembly {
            res := xor(b, mul(xor(a, b), lt(a, b)))
        }
    }

    /// @notice Equivalent to: `a > b ? a : b`
    function max(uint256 a, uint256 b) internal pure returns (uint256 res) {
        assembly {
            res := xor(b, mul(xor(a, b), gt(a, b)))
        }
    }

    /// @notice Equivalent to: `condition ? (b, a) : (a, b)`
    function switchIf(bool condition, uint256 a, uint256 b) internal pure returns (uint256, uint256) {
        assembly {
            let diff := mul(xor(a, b), condition)
            a := xor(a, diff)
            b := xor(b, diff)
        }
        return (a, b);
    }

    /// @notice Equivalent to: `condition ? (b, a) : (a, b)`
    function switchIf(bool condition, address a, address b) internal pure returns (address, address) {
        assembly {
            let diff := mul(xor(a, b), condition)
            a := xor(a, diff)
            b := xor(b, diff)
        }
        return (a, b);
    }

    /// @notice Sorts two addresses and returns them in ascending order
    function sort2(address a, address b) internal pure returns (address, address) {
        assembly {
            let diff := mul(xor(a, b), lt(b, a))
            a := xor(a, diff)
            b := xor(b, diff)
        }
        return (a, b);
    }

    /// @notice Sorts two uint256s and returns them in ascending order
    function sort2(uint256 a, uint256 b) internal pure returns (uint256, uint256) {
        assembly {
            let diff := mul(xor(a, b), lt(b, a))
            a := xor(a, diff)
            b := xor(b, diff)
        }
        return (a, b);
    }

    /// @notice Sorts two uint160s and returns them in ascending order
    function sort2U160(uint160 a, uint160 b) internal pure returns (uint160, uint160) {
        assembly {
            let diff := mul(xor(a, b), lt(b, a))
            a := xor(a, diff)
            b := xor(b, diff)
        }
        return (a, b);
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.8;

import "./BitMath.sol";
import "./PoolCaller.sol";

/// @title Packed tick initialized state library
/// @author Aperture Finance
/// @author Modified from Uniswap (https://github.com/uniswap/v3-core/blob/main/contracts/libraries/TickBitmap.sol)
/// @notice Stores a packed mapping of tick index to its initialized state
/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.
library TickBitmap {
    /// @dev round towards negative infinity
    function compress(int24 tick, int24 tickSpacing) internal pure returns (int24 compressed) {
        // compressed = tick / tickSpacing;
        // if (tick < 0 && tick % tickSpacing != 0) compressed--;
        assembly {
            compressed := sub(
                sdiv(tick, tickSpacing),
                // if (tick < 0 && tick % tickSpacing != 0) then tick % tickSpacing < 0, vice versa
                slt(smod(tick, tickSpacing), 0)
            )
        }
    }

    /// @notice Computes the position in the mapping where the initialized bit for a tick lives
    /// @param tick The tick for which to compute the position
    /// @return wordPos The key in the mapping containing the word in which the bit is stored
    /// @return bitPos The bit position in the word where the flag is stored
    function position(int24 tick) internal pure returns (int16 wordPos, uint8 bitPos) {
        assembly {
            // signed arithmetic shift right
            wordPos := sar(8, tick)
            bitPos := and(tick, 0xff)
        }
    }

    /// @notice Flips the initialized state for a given tick from false to true, or vice versa
    /// @param self The mapping in which to flip the tick
    /// @param tick The tick to flip
    /// @param tickSpacing The spacing between usable ticks
    function flipTick(mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing) internal {
        assembly ("memory-safe") {
            // ensure that the tick is spaced
            if smod(tick, tickSpacing) {
                revert(0, 0)
            }
            tick := sdiv(tick, tickSpacing)
            // calculate the storage slot corresponding to the tick
            // wordPos = tick >> 8
            mstore(0, sar(8, tick))
            mstore(0x20, self.slot)
            // the slot of self[wordPos] is keccak256(abi.encode(wordPos, self.slot))
            let slot := keccak256(0, 0x40)
            // mask = 1 << bitPos = 1 << (tick % 256)
            // self[wordPos] ^= mask
            sstore(slot, xor(sload(slot), shl(and(tick, 0xff), 1)))
        }
    }

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

            if (lte) {
                (int16 wordPos, uint8 bitPos) = position(compressed);
                // all the 1s at or to the right of the current bitPos
                uint256 masked;
                assembly ("memory-safe") {
                    // mask = (1 << (bitPos + 1)) - 1 = (2 << bitPos) - 1
                    // (2 << bitPos) may overflow but fine since 2 << 255 = 0
                    let mask := sub(shl(bitPos, 2), 1)
                    // masked = self[wordPos] & mask
                    mstore(0, wordPos)
                    mstore(0x20, self.slot)
                    masked := and(sload(keccak256(0, 0x40)), mask)
                }

                // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word
                initialized = masked != 0;
                // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
                if (initialized) {
                    uint8 msb = BitMath.mostSignificantBit(masked);
                    assembly {
                        next := mul(add(sub(compressed, bitPos), msb), tickSpacing)
                    }
                } else {
                    assembly {
                        next := mul(sub(compressed, bitPos), tickSpacing)
                    }
                }
            } else {
                // start from the word of the next tick, since the current tick state doesn't matter
                (int16 wordPos, uint8 bitPos) = position(++compressed);
                // all the 1s at or to the left of the bitPos
                uint256 masked;
                assembly ("memory-safe") {
                    // mask = ~((1 << bitPos) - 1) = -((1 << bitPos) - 1) - 1 = -(1 << bitPos)
                    let mask := sub(0, shl(bitPos, 1))
                    // masked = self[wordPos] & mask
                    mstore(0, wordPos)
                    mstore(0x20, self.slot)
                    masked := and(sload(keccak256(0, 0x40)), mask)
                }

                // if there are no initialized ticks to the left of the current tick, return leftmost in the word
                initialized = masked != 0;
                // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
                if (initialized) {
                    uint8 lsb = BitMath.leastSignificantBit(masked);
                    assembly {
                        next := mul(add(sub(compressed, bitPos), lsb), tickSpacing)
                    }
                } else {
                    assembly {
                        next := mul(add(sub(compressed, bitPos), 255), tickSpacing)
                    }
                }
            }
        }
    }

    /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either
    /// to the left (less than or equal to) or right (greater than) of the given tick
    /// @param pool Uniswap v3 pool
    /// @param tick The starting tick
    /// @param tickSpacing The spacing between usable ticks
    /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)
    /// @param lastWordPos The last accessed word position in the Bitmap. Set it to `type(int16).min` for the first call.
    /// @param lastWord The last accessed word in the Bitmap
    /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick
    /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks
    /// @return wordPos The word position of the next initialized tick in the Bitmap
    /// @return tickWord The word of the next initialized tick in the Bitmap
    function nextInitializedTickWithinOneWord(
        V3PoolCallee pool,
        int24 tick,
        int24 tickSpacing,
        bool lte,
        int16 lastWordPos,
        uint256 lastWord
    ) internal view returns (int24 next, bool initialized, int16 wordPos, uint256 tickWord) {
        int24 compressed = compress(tick, tickSpacing);
        uint8 bitPos;
        uint256 masked;

        if (lte) {
            (wordPos, bitPos) = position(compressed);
            // Reuse the same word if the position doesn't change
            tickWord = wordPos == lastWordPos ? lastWord : pool.tickBitmap(wordPos);
            assembly {
                // mask = (1 << (bitPos + 1)) - 1 = (2 << bitPos) - 1
                // (2 << bitPos) may overflow but fine since 2 << 255 = 0
                let mask := sub(shl(bitPos, 2), 1)
                // all the 1s at or to the right of the current bitPos
                masked := and(tickWord, mask)
            }

            // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word
            initialized = masked != 0;
            // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
            if (!initialized) {
                assembly {
                    next := mul(sub(compressed, bitPos), tickSpacing)
                }
            } else {
                uint8 msb = BitMath.mostSignificantBit(masked);
                assembly {
                    next := mul(add(sub(compressed, bitPos), msb), tickSpacing)
                }
            }
        } else {
            // start from the word of the next tick, since the current tick state doesn't matter
            unchecked {
                (wordPos, bitPos) = position(++compressed);
            }
            // Reuse the same word if the position doesn't change
            tickWord = wordPos == lastWordPos ? lastWord : pool.tickBitmap(wordPos);
            assembly {
                // mask = ~((1 << bitPos) - 1) = -((1 << bitPos) - 1) - 1 = -(1 << bitPos)
                let mask := sub(0, shl(bitPos, 1))
                // all the 1s at or to the left of the bitPos
                masked := and(tickWord, mask)
            }

            // if there are no initialized ticks to the left of the current tick, return leftmost in the word
            initialized = masked != 0;
            // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
            if (!initialized) {
                assembly {
                    next := mul(add(sub(compressed, bitPos), 255), tickSpacing)
                }
            } else {
                uint8 lsb = BitMath.leastSignificantBit(masked);
                assembly {
                    next := mul(add(sub(compressed, bitPos), lsb), tickSpacing)
                }
            }
        }
    }

    /// @notice Returns the next initialized tick not limited to the same word as the tick that is either
    /// to the left (less than or equal to) or right (greater than) of the given tick
    /// @dev It is assumed that the next initialized tick exists.
    /// @param pool Uniswap v3 pool
    /// @param tick The starting tick
    /// @param tickSpacing The spacing between usable ticks
    /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)
    /// @param lastWordPos The last accessed word position in the Bitmap. Set it to `type(int16).min` for the first call.
    /// @param lastWord The last accessed word in the Bitmap
    /// @return next The next initialized tick
    /// @return wordPos The word position of the next initialized tick in the Bitmap
    /// @return tickWord The word of the next initialized tick in the Bitmap
    function nextInitializedTick(
        V3PoolCallee pool,
        int24 tick,
        int24 tickSpacing,
        bool lte,
        int16 lastWordPos,
        uint256 lastWord
    ) internal view returns (int24 next, int16 wordPos, uint256 tickWord) {
        unchecked {
            int24 compressed = compress(tick, tickSpacing);
            uint8 bitPos;
            uint256 masked;
            uint8 sb;
            if (lte) {
                (wordPos, bitPos) = position(compressed);
                // Reuse the same word if the position doesn't change
                tickWord = wordPos == lastWordPos ? lastWord : pool.tickBitmap(wordPos);
                assembly {
                    // mask = (1 << (bitPos + 1)) - 1 = (2 << bitPos) - 1
                    // (2 << bitPos) may overflow but fine since 2 << 255 = 0
                    let mask := sub(shl(bitPos, 2), 1)
                    // all the 1s at or to the right of the current bitPos
                    masked := and(tickWord, mask)
                }
                while (masked == 0) {
                    // Always query the next word to the left
                    masked = tickWord = pool.tickBitmap(--wordPos);
                }
                sb = BitMath.mostSignificantBit(masked);
            } else {
                // start from the word of the next tick, since the current tick state doesn't matter
                (wordPos, bitPos) = position(++compressed);
                // Reuse the same word if the position doesn't change
                tickWord = wordPos == lastWordPos ? lastWord : pool.tickBitmap(wordPos);
                assembly {
                    // mask = ~((1 << bitPos) - 1) = -((1 << bitPos) - 1) - 1 = -(1 << bitPos)
                    let mask := sub(0, shl(bitPos, 1))
                    // all the 1s at or to the left of the bitPos
                    masked := and(tickWord, mask)
                }
                while (masked == 0) {
                    // Always query the next word to the right
                    masked = tickWord = pool.tickBitmap(++wordPos);
                }
                sb = BitMath.leastSignificantBit(masked);
            }
            // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
            assembly {
                // next = (wordPos * 256 + sb) * tickSpacing
                next := mul(add(shl(8, wordPos), sb), tickSpacing)
            }
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import "./TernaryLib.sol";

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @author Aperture Finance
/// @author Modified from Uniswap (https://github.com/uniswap/v3-core/blob/main/contracts/libraries/TickMath.sol)
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
    /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
    int24 internal constant MAX_TICK = 887272;

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

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
    /// at the given tick
    function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        unchecked {
            int256 tick256;
            assembly {
                tick256 := tick
            }
            uint256 absTick = TernaryLib.abs(tick256);
            /// @solidity memory-safe-assembly
            assembly {
                // Equivalent: if (absTick > MAX_TICK) revert("T");
                if gt(absTick, MAX_TICK) {
                    // selector "Error(string)", [0x1c, 0x20)
                    mstore(0, 0x08c379a0)
                    // abi encoding offset
                    mstore(0x20, 0x20)
                    // reason string length 1 and 'T', [0x5f, 0x61)
                    mstore(0x41, 0x0154)
                    // 4 byte selector + 32 byte offset + 32 byte length + 1 byte reason
                    revert(0x1c, 0x45)
                }
            }

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

            assembly {
                // if (tick > 0) ratio = type(uint256).max / ratio;
                if sgt(tick, 0) {
                    ratio := div(not(0), ratio)
                }
                // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
                // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
                // we round up in the division so getTickAtSqrtRatio of the output price is always consistent
                sqrtPriceX96 := shr(32, add(ratio, sub(shl(32, 1), 1)))
            }
        }
    }

    /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
    /// ever return.
    /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
    /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
    function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
        // Equivalent: if (sqrtPriceX96 < MIN_SQRT_RATIO || sqrtPriceX96 >= MAX_SQRT_RATIO) revert("R");
        // second inequality must be >= because the price can never reach the price at the max tick
        /// @solidity memory-safe-assembly
        assembly {
            // if sqrtPriceX96 < MIN_SQRT_RATIO, the `sub` underflows and `gt` is true
            // if sqrtPriceX96 >= MAX_SQRT_RATIO, sqrtPriceX96 - MIN_SQRT_RATIO > MAX_SQRT_RATIO - MIN_SQRT_RATIO - 1
            if gt(sub(sqrtPriceX96, MIN_SQRT_RATIO), MAX_SQRT_RATIO_MINUS_MIN_SQRT_RATIO_MINUS_ONE) {
                // selector "Error(string)", [0x1c, 0x20)
                mstore(0, 0x08c379a0)
                // abi encoding offset
                mstore(0x20, 0x20)
                // reason string length 1 and 'R', [0x5f, 0x61)
                mstore(0x41, 0x0152)
                // 4 byte selector + 32 byte offset + 32 byte length + 1 byte reason
                revert(0x1c, 0x45)
            }
        }

        // Find the most significant bit of `sqrtPriceX96`, 160 > msb >= 32.
        uint8 msb;
        assembly {
            let x := sqrtPriceX96
            msb := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            msb := or(msb, shl(6, lt(0xffffffffffffffff, shr(msb, x))))
            msb := or(msb, shl(5, lt(0xffffffff, shr(msb, x))))
            msb := or(msb, shl(4, lt(0xffff, shr(msb, x))))
            msb := or(msb, shl(3, lt(0xff, shr(msb, x))))
            msb := or(
                msb,
                byte(
                    and(0x1f, shr(shr(msb, x), 0x8421084210842108cc6318c6db6d54be)),
                    0x0706060506020504060203020504030106050205030304010505030400000000
                )
            )
        }

        // 2**(msb - 95) > sqrtPrice >= 2**(msb - 96)
        // the integer part of log_2(sqrtPrice) * 2**64 = (msb - 96) << 64, 8.64 number
        int256 log_2X64;
        assembly {
            log_2X64 := shl(64, sub(msb, 96))

            // Get the first 128 significant figures of `sqrtPriceX96`.
            // r = sqrtPriceX96 / 2**(msb - 127), where 2**128 > r >= 2**127
            // sqrtPrice = 2**(msb - 96) * r / 2**127, in floating point math
            // Shift left first because 160 > msb >= 32. If we shift right first, we'll lose precision.
            let r := shr(sub(msb, 31), shl(96, sqrtPriceX96))

            // Approximate `log_2X64` to 14 binary digits after decimal
            // log_2X64 = (msb - 96) * 2**64 + f_0 * 2**63 + f_1 * 2**62 + ......
            // sqrtPrice**2 = 2**(2 * (msb - 96)) * (r / 2**127)**2 = 2**(2 * log_2X64 / 2**64) = 2**(2 * (msb - 96) + f_0)
            // 2**f_0 = (r / 2**127)**2 = r**2 / 2**255 * 2
            // f_0 = 1 if (r**2 >= 2**255) else 0
            // sqrtPrice**2 = 2**(2 * (msb - 96) + f_0) * r**2 / 2**(254 + f_0) = 2**(2 * (msb - 96) + f_0) * r' / 2**127
            // r' = r**2 / 2**(127 + f_0)
            // sqrtPrice**4 = 2**(4 * (msb - 96) + 2 * f_0) * (r' / 2**127)**2
            //     = 2**(4 * log_2X64 / 2**64) = 2**(4 * (msb - 96) + 2 * f_0 + f_1)
            // 2**(f_1) = (r' / 2**127)**2
            // f_1 = 1 if (r'**2 >= 2**255) else 0

            // Check whether r >= sqrt(2) * 2**127
            // 2**256 > r**2 >= 2**254
            let square := mul(r, r)
            // f = (r**2 >= 2**255)
            let f := slt(square, 0)
            // r = r**2 >> 128 if r**2 >= 2**255 else r**2 >> 127
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(63, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(62, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(61, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(60, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(59, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(58, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(57, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(56, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(55, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(54, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(53, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(52, f), log_2X64)

            square := mul(r, r)
            f := slt(square, 0)
            r := shr(127, shr(f, square))
            log_2X64 := or(shl(51, f), log_2X64)

            log_2X64 := or(shl(50, slt(mul(r, r), 0)), log_2X64)
        }

        // sqrtPrice = sqrt(1.0001^tick)
        // tick = log_{sqrt(1.0001)}(sqrtPrice) = log_2(sqrtPrice) / log_2(sqrt(1.0001))
        // 2**64 / log_2(sqrt(1.0001)) = 255738958999603826347141
        int24 tickLow;
        int24 tickHi;
        assembly {
            let log_sqrt10001 := mul(log_2X64, 255738958999603826347141) // 128.128 number
            tickLow := sar(128, sub(log_sqrt10001, 3402992956809132418596140100660247210))
            tickHi := sar(128, add(log_sqrt10001, 291339464771989622907027621153398088495))
        }

        // Equivalent: tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
        if (tickLow != tickHi) {
            uint160 sqrtRatioAtTickHi = getSqrtRatioAtTick(tickHi);
            assembly {
                tick := sub(tickHi, gt(sqrtRatioAtTickHi, sqrtPriceX96))
            }
        } else {
            tick = tickHi;
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Math functions that do not check inputs or outputs
/// @author Aperture Finance
/// @author Modified from Uniswap (https://github.com/uniswap/v3-core/blob/main/contracts/libraries/UnsafeMath.sol)
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
    function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := add(x, y)
        }
    }

    function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := sub(x, y)
        }
    }

    function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := mul(x, y)
        }
    }

    function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := div(x, y)
        }
    }

    /// @notice Returns ceil(x / y)
    /// @dev division by 0 has unspecified behavior, and must be checked externally
    /// @param x The dividend
    /// @param y The divisor
    /// @return z The quotient, ceil(x / y)
    function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := add(div(x, y), gt(mod(x, y), 0))
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

File 13 of 46 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

File 14 of 46 : 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.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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.2.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

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

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    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 Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            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 silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}

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

pragma solidity ^0.8.20;

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

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC-721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC-721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

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

/// @title Callback for IPancakeV3PoolActions#swap
/// @notice Any contract that calls IPancakeV3PoolActions#swap must implement this interface
interface IPancakeV3SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via IPancakeV3Pool#swap.
    /// @dev In the implementation you must pay the pool tokens owed for the swap.
    /// The caller of this method must be checked to be a PancakeV3Pool deployed by the canonical PancakeV3Factory.
    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
    /// @param data Any data passed through by the caller via the IPancakeV3PoolActions#swap call
    function pancakeV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

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

/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
    /// @dev In the implementation you must pay the pool tokens owed for the swap.
    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

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

import {IUniswapV3PoolImmutables} from './pool/IUniswapV3PoolImmutables.sol';
import {IUniswapV3PoolState} from './pool/IUniswapV3PoolState.sol';
import {IUniswapV3PoolDerivedState} from './pool/IUniswapV3PoolDerivedState.sol';
import {IUniswapV3PoolActions} from './pool/IUniswapV3PoolActions.sol';
import {IUniswapV3PoolOwnerActions} from './pool/IUniswapV3PoolOwnerActions.sol';
import {IUniswapV3PoolErrors} from './pool/IUniswapV3PoolErrors.sol';
import {IUniswapV3PoolEvents} from './pool/IUniswapV3PoolEvents.sol';

/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
    IUniswapV3PoolImmutables,
    IUniswapV3PoolState,
    IUniswapV3PoolDerivedState,
    IUniswapV3PoolActions,
    IUniswapV3PoolOwnerActions,
    IUniswapV3PoolErrors,
    IUniswapV3PoolEvents
{

}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

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

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

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

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

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

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

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

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

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

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

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

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

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

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

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
    /// @notice Set the denominator of the protocol's % share of the fees
    /// @param feeProtocol0 new protocol fee for token0 of the pool
    /// @param feeProtocol1 new protocol fee for token1 of the pool
    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;

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

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

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

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

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

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

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

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

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

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

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

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

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

// 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; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(a, b, not(0))
                prod0 := mul(a, b)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

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

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

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

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

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

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

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

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

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

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;

import '@openzeppelin/contracts/token/ERC721/IERC721.sol';

/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
    /// @notice The permit typehash used in the permit signature
    /// @return The typehash for the permit
    function PERMIT_TYPEHASH() external pure returns (bytes32);

    /// @notice The domain separator used in the permit signature
    /// @return The domain seperator used in encoding of permit signature
    function DOMAIN_SEPARATOR() external view returns (bytes32);

    /// @notice Approve of a specific token ID for spending by spender via signature
    /// @param spender The account that is being approved
    /// @param tokenId The ID of the token that is being approved for spending
    /// @param deadline The deadline timestamp by which the call must be mined for the approve to work
    /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
    /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
    /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
    function permit(
        address spender,
        uint256 tokenId,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable;
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';

import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryPayments.sol';
import './IPeripheryImmutableState.sol';
import '../libraries/PoolAddress.sol';

/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
    IPoolInitializer,
    IPeripheryPayments,
    IPeripheryImmutableState,
    IERC721Metadata,
    IERC721Enumerable,
    IERC721Permit
{
    /// @notice Emitted when liquidity is increased for a position NFT
    /// @dev Also emitted when a token is minted
    /// @param tokenId The ID of the token for which liquidity was increased
    /// @param liquidity The amount by which liquidity for the NFT position was increased
    /// @param amount0 The amount of token0 that was paid for the increase in liquidity
    /// @param amount1 The amount of token1 that was paid for the increase in liquidity
    event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
    /// @notice Emitted when liquidity is decreased for a position NFT
    /// @param tokenId The ID of the token for which liquidity was decreased
    /// @param liquidity The amount by which liquidity for the NFT position was decreased
    /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
    /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
    event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
    /// @notice Emitted when tokens are collected for a position NFT
    /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
    /// @param tokenId The ID of the token for which underlying tokens were collected
    /// @param recipient The address of the account that received the collected tokens
    /// @param amount0 The amount of token0 owed to the position that was collected
    /// @param amount1 The amount of token1 owed to the position that was collected
    event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);

    /// @notice Returns the position information associated with a given token ID.
    /// @dev Throws if the token ID is not valid.
    /// @param tokenId The ID of the token that represents the position
    /// @return nonce The nonce for permits
    /// @return operator The address that is approved for spending
    /// @return token0 The address of the token0 for a specific pool
    /// @return token1 The address of the token1 for a specific pool
    /// @return fee The fee associated with the pool
    /// @return tickLower The lower end of the tick range for the position
    /// @return tickUpper The higher end of the tick range for the position
    /// @return liquidity The liquidity of the position
    /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
    /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
    /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
    /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
    function positions(uint256 tokenId)
        external
        view
        returns (
            uint96 nonce,
            address operator,
            address token0,
            address token1,
            uint24 fee,
            int24 tickLower,
            int24 tickUpper,
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    struct MintParams {
        address token0;
        address token1;
        uint24 fee;
        int24 tickLower;
        int24 tickUpper;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        address recipient;
        uint256 deadline;
    }

    /// @notice Creates a new position wrapped in a NFT
    /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
    /// a method does not exist, i.e. the pool is assumed to be initialized.
    /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
    /// @return tokenId The ID of the token that represents the minted position
    /// @return liquidity The amount of liquidity for this position
    /// @return amount0 The amount of token0
    /// @return amount1 The amount of token1
    function mint(MintParams calldata params)
        external
        payable
        returns (
            uint256 tokenId,
            uint128 liquidity,
            uint256 amount0,
            uint256 amount1
        );

    struct IncreaseLiquidityParams {
        uint256 tokenId;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
    /// @param params tokenId The ID of the token for which liquidity is being increased,
    /// amount0Desired The desired amount of token0 to be spent,
    /// amount1Desired The desired amount of token1 to be spent,
    /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
    /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
    /// deadline The time by which the transaction must be included to effect the change
    /// @return liquidity The new liquidity amount as a result of the increase
    /// @return amount0 The amount of token0 to acheive resulting liquidity
    /// @return amount1 The amount of token1 to acheive resulting liquidity
    function increaseLiquidity(IncreaseLiquidityParams calldata params)
        external
        payable
        returns (
            uint128 liquidity,
            uint256 amount0,
            uint256 amount1
        );

    struct DecreaseLiquidityParams {
        uint256 tokenId;
        uint128 liquidity;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    /// @notice Decreases the amount of liquidity in a position and accounts it to the position
    /// @param params tokenId The ID of the token for which liquidity is being decreased,
    /// amount The amount by which liquidity will be decreased,
    /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
    /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
    /// deadline The time by which the transaction must be included to effect the change
    /// @return amount0 The amount of token0 accounted to the position's tokens owed
    /// @return amount1 The amount of token1 accounted to the position's tokens owed
    function decreaseLiquidity(DecreaseLiquidityParams calldata params)
        external
        payable
        returns (uint256 amount0, uint256 amount1);

    struct CollectParams {
        uint256 tokenId;
        address recipient;
        uint128 amount0Max;
        uint128 amount1Max;
    }

    /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
    /// @param params tokenId The ID of the NFT for which tokens are being collected,
    /// recipient The account that should receive the tokens,
    /// amount0Max The maximum amount of token0 to collect,
    /// amount1Max The maximum amount of token1 to collect
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);

    /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
    /// must be collected first.
    /// @param tokenId The ID of the token that is being burned
    function burn(uint256 tokenId) external payable;
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
    /// @return Returns the address of the Uniswap V3 factory
    function factory() external view returns (address);

    /// @return Returns the address of WETH9
    function WETH9() external view returns (address);
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;

/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
    /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
    /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
    /// @param amountMinimum The minimum amount of WETH9 to unwrap
    /// @param recipient The address receiving ETH
    function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;

    /// @notice Refunds any ETH balance held by this contract to the `msg.sender`
    /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
    /// that use ether for the input amount
    function refundETH() external payable;

    /// @notice Transfers the full amount of a token held by this contract to recipient
    /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
    /// @param token The contract address of the token which will be transferred to `recipient`
    /// @param amountMinimum The minimum amount of token required for a transfer
    /// @param recipient The destination address of the token
    function sweepToken(
        address token,
        uint256 amountMinimum,
        address recipient
    ) external payable;
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
    /// @notice Creates a new pool if it does not exist, then initializes if not initialized
    /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
    /// @param token0 The contract address of token0 of the pool
    /// @param token1 The contract address of token1 of the pool
    /// @param fee The fee amount of the v3 pool for the specified token pair
    /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
    /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
    function createAndInitializePoolIfNecessary(
        address token0,
        address token1,
        uint24 fee,
        uint160 sqrtPriceX96
    ) external payable returns (address pool);
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
    bytes32 internal constant POOL_INIT_CODE_HASH = 0xa598dd2fba360510c5a8f02f44423a4468e902df5857dbce3ca162a43a3a31ff;

    /// @notice The identifying key of the pool
    struct PoolKey {
        address token0;
        address token1;
        uint24 fee;
    }

    /// @notice Returns PoolKey: the ordered tokens with the matched fee levels
    /// @param tokenA The first token of a pool, unsorted
    /// @param tokenB The second token of a pool, unsorted
    /// @param fee The fee level of the pool
    /// @return Poolkey The pool details with ordered token0 and token1 assignments
    function getPoolKey(
        address tokenA,
        address tokenB,
        uint24 fee
    ) internal pure returns (PoolKey memory) {
        if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
        return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
    }

    /// @notice Deterministically computes the pool address given the factory and PoolKey
    /// @param factory The Uniswap V3 factory contract address
    /// @param key The PoolKey
    /// @return pool The contract address of the V3 pool
    function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
        require(key.token0 < key.token1);
        pool = address(
            uint160(
                uint256(
                    keccak256(
                        abi.encodePacked(
                            hex'ff',
                            factory,
                            keccak256(abi.encode(key.token0, key.token1, key.fee)),
                            POOL_INIT_CODE_HASH
                        )
                    )
                )
            )
        );
    }
}

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

import { OptimalSwap, V3PoolCallee } from "../libraries/OptimalSwap.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "../interfaces/core/IOptimalSwapper.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol";
import "@pancakeswap/v3-core/contracts/interfaces/callback/IPancakeV3SwapCallback.sol";

/// @title PoolOptimalSwapper
contract PoolOptimalSwapper is IOptimalSwapper, IUniswapV3SwapCallback, IPancakeV3SwapCallback {
  using SafeERC20 for IERC20;

  uint160 internal constant MAX_SQRT_RATIO_LESS_ONE =
    1_461_446_703_485_210_103_287_273_052_203_988_822_378_723_970_342 - 1;
  uint160 internal constant XOR_SQRT_RATIO =
    (4_295_128_739 + 1) ^ (1_461_446_703_485_210_103_287_273_052_203_988_822_378_723_970_342 - 1);

  address private currentPool;

  /// @notice Callback function required by Uniswap V3 to finalize swaps
  /// @param amount0Delta The change in token0 balance
  /// @param amount1Delta The change in token1 balance
  function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata) external override {
    require(msg.sender == currentPool, "Incorrect pool");

    IERC20 token0 = IERC20(IUniswapV3Pool(currentPool).token0());
    IERC20 token1 = IERC20(IUniswapV3Pool(currentPool).token1());

    if (amount0Delta > 0) token0.safeTransfer(msg.sender, uint256(amount0Delta));
    else if (amount1Delta > 0) token1.safeTransfer(msg.sender, uint256(amount1Delta));
  }

  /// @notice Callback function required by Pancake V3 to finalize swaps
  /// @param amount0Delta The change in token0 balance
  /// @param amount1Delta The change in token1 balance
  function pancakeV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata) external override {
    require(msg.sender == currentPool, "Incorrect pool");

    IERC20 token0 = IERC20(IUniswapV3Pool(currentPool).token0());
    IERC20 token1 = IERC20(IUniswapV3Pool(currentPool).token1());

    if (amount0Delta > 0) token0.safeTransfer(msg.sender, uint256(amount0Delta));
    else if (amount1Delta > 0) token1.safeTransfer(msg.sender, uint256(amount1Delta));
  }

  /// @dev Make a direct `exactIn` pool swap
  /// @param pool The address of the Uniswap V3 pool
  /// @param amountIn The amount of token to be swapped
  /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
  /// @return amountOut The amount of token received after swap
  /// @return amountInUsed The amount of token used for swap
  function _poolSwap(address pool, uint256 amountIn, bool zeroForOne)
    internal
    returns (uint256 amountOut, uint256 amountInUsed)
  {
    if (amountIn != 0) {
      currentPool = pool;
      uint160 sqrtPriceLimitX96;
      // Equivalent to `sqrtPriceLimitX96 = zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1`
      assembly {
        sqrtPriceLimitX96 := xor(MAX_SQRT_RATIO_LESS_ONE, mul(XOR_SQRT_RATIO, zeroForOne))
      }
      (int256 amount0Delta, int256 amount1Delta) =
        V3PoolCallee.wrap(pool).swap(address(this), zeroForOne, int256(amountIn), sqrtPriceLimitX96, "");

      unchecked {
        amountOut = zeroForOne ? uint256(-amount1Delta) : uint256(-amount0Delta);
        amountInUsed = zeroForOne ? uint256(amount0Delta) : uint256(amount1Delta);
      }
    }
  }

  /// @notice Swap tokens in a Uniswap V3 pool
  /// @param params The parameters for the optimal swap
  /// @return amount0 The amount of token0 received after swap
  /// @return amount1 The amount of token1 received after swap
  function optimalSwap(OptimalSwapParams calldata params) external override returns (uint256 amount0, uint256 amount1) {
    IERC20 token0 = IERC20(IUniswapV3Pool(params.pool).token0());
    IERC20 token1 = IERC20(IUniswapV3Pool(params.pool).token1());

    token0.safeTransferFrom(msg.sender, address(this), params.amount0Desired);
    token1.safeTransferFrom(msg.sender, address(this), params.amount1Desired);

    (uint256 amountIn,, bool zeroForOne,) = OptimalSwap.getOptimalSwap(
      V3PoolCallee.wrap(params.pool), params.tickLower, params.tickUpper, params.amount0Desired, params.amount1Desired
    );

    (uint256 amountOut, uint256 amountInUsed) = _poolSwap(params.pool, amountIn, zeroForOne);

    // balance0 = balance0 + zeroForOne ? - amountIn : amountOut
    // balance1 = balance1 + zeroForOne ? amountOut : - amountIn
    if (zeroForOne) {
      amount0 = params.amount0Desired - amountInUsed;
      amount1 = params.amount1Desired + amountOut;
    } else {
      amount0 = params.amount0Desired + amountOut;
      amount1 = params.amount1Desired - amountInUsed;
    }

    token0.safeTransfer(msg.sender, amount0);
    token1.safeTransfer(msg.sender, amount1);
  }

  /// @notice Get the optimal swap amounts for a given pool
  /// @param pool The address of the Uniswap V3 pool
  /// @param amount0Desired The desired amount of token0
  /// @param amount1Desired The desired amount of token1
  /// @param tickLower The lower tick of the pool
  /// @param tickUpper The upper tick of the pool
  /// @return amount0 The optimal amount of token0 to swap
  /// @return amount1 The optimal amount of token1 to swap
  function getOptimalSwapAmounts(
    address pool,
    uint256 amount0Desired,
    uint256 amount1Desired,
    int24 tickLower,
    int24 tickUpper,
    bytes calldata
  ) external view returns (uint256 amount0, uint256 amount1) {
    (uint256 amountIn, uint256 amountOut, bool zeroForOne,) =
      OptimalSwap.getOptimalSwap(V3PoolCallee.wrap(pool), tickLower, tickUpper, amount0Desired, amount1Desired);

    // balance0 = balance0 + zeroForOne ? - amountIn : amountOut
    // balance1 = balance1 + zeroForOne ? amountOut : - amountIn
    if (zeroForOne) {
      amount0 = amount0Desired - amountIn;
      amount1 = amount1Desired + amountOut;
    } else {
      amount0 = amount0Desired + amountOut;
      amount1 = amount1Desired - amountIn;
    }
  }

  /// @notice Swap exactIn tokens through an UniswapV3Pool
  /// @param pool The address of the Uniswap V3 pool
  /// @param amountIn The amount of token to be swapped
  /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
  /// @param amountOutMin The minimum amount of token to receive after swap
  /// @return amountOut The amount of token received after swap
  /// @return amountInUsed The amount of token used for swap
  function poolSwap(address pool, uint256 amountIn, bool zeroForOne, uint256 amountOutMin, bytes calldata)
    external
    override
    returns (uint256 amountOut, uint256 amountInUsed)
  {
    IERC20 token0 = IERC20(IUniswapV3Pool(pool).token0());
    IERC20 token1 = IERC20(IUniswapV3Pool(pool).token1());

    IERC20 inputToken = zeroForOne ? token0 : token1;
    IERC20 outputToken = zeroForOne ? token1 : token0;

    inputToken.safeTransferFrom(msg.sender, address(this), amountIn);

    (amountOut, amountInUsed) = _poolSwap(pool, amountIn, zeroForOne);
    require(amountOut >= amountOutMin, "Insufficient output amount");

    outputToken.safeTransfer(msg.sender, amountOut);
    if (amountIn > amountInUsed) inputToken.safeTransfer(msg.sender, amountIn - amountInUsed);
  }
}

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

interface IOptimalSwapper {
  struct OptimalSwapParams {
    address pool;
    uint256 amount0Desired;
    uint256 amount1Desired;
    int24 tickLower;
    int24 tickUpper;
    bytes data;
  }

  function optimalSwap(OptimalSwapParams calldata params)
    external
    returns (uint256 amount0Result, uint256 amount1Result);

  function getOptimalSwapAmounts(
    address pool,
    uint256 amount0Desired,
    uint256 amount1Desired,
    int24 tickLower,
    int24 tickUpper,
    bytes calldata data
  ) external view returns (uint256 amount0, uint256 amount1);

  function poolSwap(address pool, uint256 amountIn, bool zeroToOne, uint256 amountOutMin, bytes calldata data)
    external
    returns (uint256 amountOut, uint256 amountInUsed);
}

File 41 of 46 : ICommon.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

interface ICommon {
  struct VaultConfig {
    bool allowDeposit;
    uint8 rangeStrategyType;
    uint8 tvlStrategyType;
    address principalToken;
    address[] supportedAddresses;
  }

  struct VaultCreateParams {
    string name;
    string symbol;
    uint256 principalTokenAmount;
    VaultConfig config;
  }

  struct FeeConfig {
    uint16 vaultOwnerFeeBasisPoint;
    address vaultOwner;
    uint16 platformFeeBasisPoint;
    address platformFeeRecipient;
    uint64 gasFeeX64;
    address gasFeeRecipient;
  }

  struct Instruction {
    uint8 instructionType;
    bytes params;
  }

  error ZeroAddress();

  error TransferFailed();

  error InvalidVaultConfig();

  error InvalidFeeConfig();

  error InvalidStrategy();

  error InvalidSwapRouter();

  error InvalidInstructionType();
}

File 42 of 46 : IFeeTaker.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

interface IFeeTaker {
  enum FeeType {
    PLATFORM,
    OWNER,
    GAS
  }

  event FeeCollected(address indexed vaultAddress, FeeType indexed feeType, address indexed recipient, address token, uint256 amount);
}

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

import { IFeeTaker } from "./IFeeTaker.sol";
import { ICommon } from "../ICommon.sol";

interface ILpFeeTaker is IFeeTaker, ICommon {
  struct SwapToPrincipalParams {
    address pool;
    address principalToken;
    address token;
    uint256 amount;
    uint256 amountOutMin;
    bytes swapData;
  }

  function takeFees(
    address token0,
    uint256 amount0,
    address token1,
    uint256 amount1,
    FeeConfig memory feeConfig,
    address principalToken,
    address pool,
    address validator
  ) external returns (uint256 fee0, uint256 fee1);
}

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

import { INonfungiblePositionManager as INFPM } from
  "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol";

import "../ICommon.sol";

interface ILpValidator is ICommon {
  struct LpStrategyConfig {
    LpStrategyRangeConfig[] rangeConfigs;
    LpStrategyTvlConfig[] tvlConfigs;
  }

  struct LpStrategyRangeConfig {
    int24 tickWidthMin;
    int24 tickWidthTypedMin;
  }

  struct LpStrategyTvlConfig {
    uint256 principalTokenAmountMin;
  }

  function validateConfig(
    INFPM nfpm,
    uint24 fee,
    address token0,
    address token1,
    int24 tickLower,
    int24 tickUpper,
    VaultConfig calldata config
  ) external view;

  function validateTickWidth(
    address token0,
    address token1,
    int24 tickLower,
    int24 tickUpper,
    VaultConfig calldata config
  ) external view;

  function validateObservationCardinality(INFPM nfpm, uint24 fee, address token0, address token1) external view;

  function validatePriceSanity(address pool) external view;

  error InvalidPool();

  error InvalidPoolAmountMin();

  error InvalidTickWidth();

  error InvalidObservationCardinality();

  error InvalidObservation();

  error PriceSanityCheckFailed();
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.28;

import "@aperture_finance/uni-v3-lib/src/SwapMath.sol";
import "@aperture_finance/uni-v3-lib/src/TickBitmap.sol";
import "@aperture_finance/uni-v3-lib/src/TickMath.sol";

/// @title Optimal Swap Library
/// @author Aperture Finance
/// @notice Optimal library for optimal double-sided Uniswap v3 liquidity provision using closed
/// form solution
library OptimalSwap {
  using TickMath for int24;
  using FullMath for uint256;
  using UnsafeMath for uint256;

  uint256 internal constant MAX_FEE_PIPS = 1e6;

  error Invalid_Pool();
  error Invalid_Tick_Range();
  error Math_Overflow();

  struct SwapState {
    // liquidity in range after swap, accessible by `mload(state)`
    uint128 liquidity;
    // sqrt(price) after swap, accessible by `mload(add(state, 0x20))`
    uint256 sqrtPriceX96;
    // tick after swap, accessible by `mload(add(state, 0x40))`
    int24 tick;
    // The desired amount of token0 to add liquidity, `mload(add(state, 0x60))`
    uint256 amount0Desired;
    // The desired amount of token1 to add liquidity, `mload(add(state, 0x80))`
    uint256 amount1Desired;
    // sqrt(price) at the lower tick, `mload(add(state, 0xa0))`
    uint256 sqrtRatioLowerX96;
    // sqrt(price) at the upper tick, `mload(add(state, 0xc0))`
    uint256 sqrtRatioUpperX96;
    // the fee taken from the input amount, expressed in hundredths of a bip
    // accessible by `mload(add(state, 0xe0))`
    uint256 feePips;
    // the tick spacing of the pool, accessible by `mload(add(state, 0x100))`
    int24 tickSpacing;
  }

  /// @notice Get swap amount, output amount, swap direction for double-sided optimal deposit
  /// @dev Given the elegant analytic solution and custom optimizations to Uniswap libraries,
  /// the amount of gas is at the order of 10k depending on the swap amount and the number of ticks
  /// crossed,
  /// an order of magnitude less than that achieved by binary search, which can be calculated
  /// on-chain.
  /// @param pool Uniswap v3 pool
  /// @param tickLower The lower tick of the position in which to add liquidity
  /// @param tickUpper The upper tick of the position in which to add liquidity
  /// @param amount0Desired The desired amount of token0 to be spent
  /// @param amount1Desired The desired amount of token1 to be spent
  /// @return amountIn The optimal swap amount
  /// @return amountOut Expected output amount
  /// @return zeroForOne The direction of the swap, true for token0 to token1, false for token1 to
  /// token0
  /// @return sqrtPriceX96 The sqrt(price) after the swap
  function getOptimalSwap(
    V3PoolCallee pool,
    int24 tickLower,
    int24 tickUpper,
    uint256 amount0Desired,
    uint256 amount1Desired
  ) internal view returns (uint256 amountIn, uint256 amountOut, bool zeroForOne, uint160 sqrtPriceX96) {
    if (amount0Desired == 0 && amount1Desired == 0) return (0, 0, false, 0);
    if (tickLower >= tickUpper || tickLower < TickMath.MIN_TICK || tickUpper > TickMath.MAX_TICK) {
      revert Invalid_Tick_Range();
    }
    // Ensure the pool exists.
    assembly ("memory-safe") {
      let poolCodeSize := extcodesize(pool)
      if iszero(poolCodeSize) {
        // revert Invalid_Pool()
        mstore(0, 0x01ac05a5)
        revert(0x1c, 0x04)
      }
    }
    // intermediate state cache
    SwapState memory state;
    // Populate `SwapState` with hardcoded offsets.
    {
      int24 tick;
      (sqrtPriceX96, tick) = pool.sqrtPriceX96AndTick();
      assembly ("memory-safe") {
        // state.tick = tick
        mstore(add(state, 0x40), tick)
      }
    }
    {
      uint128 liquidity = pool.liquidity();
      uint256 feePips = pool.fee();
      int24 tickSpacing = pool.tickSpacing();
      assembly ("memory-safe") {
        // state.liquidity = liquidity
        mstore(state, liquidity)
        // state.sqrtPriceX96 = sqrtPriceX96
        mstore(add(state, 0x20), sqrtPriceX96)
        // state.amount0Desired = amount0Desired
        mstore(add(state, 0x60), amount0Desired)
        // state.amount1Desired = amount1Desired
        mstore(add(state, 0x80), amount1Desired)
        // state.feePips = feePips
        mstore(add(state, 0xe0), feePips)
        // state.tickSpacing = tickSpacing
        mstore(add(state, 0x100), tickSpacing)
      }
    }
    uint160 sqrtRatioLowerX96 = tickLower.getSqrtRatioAtTick();
    uint160 sqrtRatioUpperX96 = tickUpper.getSqrtRatioAtTick();
    assembly ("memory-safe") {
      // state.sqrtRatioLowerX96 = sqrtRatioLowerX96
      mstore(add(state, 0xa0), sqrtRatioLowerX96)
      // state.sqrtRatioUpperX96 = sqrtRatioUpperX96
      mstore(add(state, 0xc0), sqrtRatioUpperX96)
    }
    zeroForOne = isZeroForOne(amount0Desired, amount1Desired, sqrtPriceX96, sqrtRatioLowerX96, sqrtRatioUpperX96);
    // Simulate optimal swap by crossing ticks until the direction reverses.
    crossTicks(pool, state, sqrtPriceX96, zeroForOne);
    // Active liquidity at the last tick of optimal swap
    uint128 liquidityLast;
    // sqrt(price) at the last tick of optimal swap
    uint160 sqrtPriceLastTickX96;
    // Remaining amount of token0 to add liquidity at the last tick
    uint256 amount0LastTick;
    // Remaining amount of token1 to add liquidity at the last tick
    uint256 amount1LastTick;
    assembly ("memory-safe") {
      // liquidityLast = state.liquidity
      liquidityLast := mload(state)
      // sqrtPriceLastTickX96 = state.sqrtPriceX96
      sqrtPriceLastTickX96 := mload(add(state, 0x20))
      // amount0LastTick = state.amount0Desired
      amount0LastTick := mload(add(state, 0x60))
      // amount1LastTick = state.amount1Desired
      amount1LastTick := mload(add(state, 0x80))
    }
    unchecked {
      if (!zeroForOne) {
        // The last tick is out of range. There are two cases:
        // 1. There is not enough token1 to swap to reach the lower tick.
        // 2. There is no initialized tick between the last tick and the lower tick.
        if (sqrtPriceLastTickX96 < sqrtRatioLowerX96) {
          sqrtPriceX96 = SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown(
            sqrtPriceLastTickX96,
            liquidityLast,
            amount1LastTick.mulDiv(MAX_FEE_PIPS - state.feePips, MAX_FEE_PIPS),
            true
          );
          // The final price is out of range. Simply consume all token1.
          if (sqrtPriceX96 < sqrtRatioLowerX96) {
            amountIn = amount1Desired;
          }
          // Swap to the lower tick and update the state.
          else {
            amount1LastTick -= SqrtPriceMath.getAmount1Delta(
              sqrtPriceLastTickX96, sqrtRatioLowerX96, liquidityLast, true
            ).mulDiv(MAX_FEE_PIPS, MAX_FEE_PIPS - state.feePips);
            amount0LastTick +=
              SqrtPriceMath.getAmount0Delta(sqrtPriceLastTickX96, sqrtRatioLowerX96, liquidityLast, false);
            sqrtPriceLastTickX96 = sqrtRatioLowerX96;
            state.sqrtPriceX96 = sqrtPriceLastTickX96;
            state.amount0Desired = amount0LastTick;
            state.amount1Desired = amount1LastTick;
          }
        }
        // The final price is in range. Use the closed form solution.
        if (sqrtPriceLastTickX96 >= sqrtRatioLowerX96) {
          sqrtPriceX96 = solveOptimalOneForZero(state);
          amountIn = amount1Desired - amount1LastTick
            + SqrtPriceMath.getAmount1Delta(sqrtPriceX96, sqrtPriceLastTickX96, liquidityLast, true).mulDiv(
              MAX_FEE_PIPS, MAX_FEE_PIPS - state.feePips
            );
        }
        amountOut = amount0LastTick - amount0Desired
          + SqrtPriceMath.getAmount0Delta(sqrtPriceX96, sqrtPriceLastTickX96, liquidityLast, false);
      } else {
        // The last tick is out of range. There are two cases:
        // 1. There is not enough token0 to swap to reach the upper tick.
        // 2. There is no initialized tick between the last tick and the upper tick.
        if (sqrtPriceLastTickX96 > sqrtRatioUpperX96) {
          sqrtPriceX96 = SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp(
            sqrtPriceLastTickX96,
            liquidityLast,
            amount0LastTick.mulDiv(MAX_FEE_PIPS - state.feePips, MAX_FEE_PIPS),
            true
          );
          // The final price is out of range. Simply consume all token0.
          if (sqrtPriceX96 >= sqrtRatioUpperX96) {
            amountIn = amount0Desired;
          }
          // Swap to the upper tick and update the state.
          else {
            amount0LastTick -= SqrtPriceMath.getAmount0Delta(
              sqrtRatioUpperX96, sqrtPriceLastTickX96, liquidityLast, true
            ).mulDiv(MAX_FEE_PIPS, MAX_FEE_PIPS - state.feePips);
            amount1LastTick +=
              SqrtPriceMath.getAmount1Delta(sqrtRatioUpperX96, sqrtPriceLastTickX96, liquidityLast, false);
            sqrtPriceLastTickX96 = sqrtRatioUpperX96;
            state.sqrtPriceX96 = sqrtPriceLastTickX96;
            state.amount0Desired = amount0LastTick;
            state.amount1Desired = amount1LastTick;
          }
        }
        // The final price is in range. Use the closed form solution.
        if (sqrtPriceLastTickX96 <= sqrtRatioUpperX96) {
          sqrtPriceX96 = solveOptimalZeroForOne(state);
          amountIn = amount0Desired - amount0LastTick
            + SqrtPriceMath.getAmount0Delta(sqrtPriceX96, sqrtPriceLastTickX96, liquidityLast, true).mulDiv(
              MAX_FEE_PIPS, MAX_FEE_PIPS - state.feePips
            );
        }
        amountOut = amount1LastTick - amount1Desired
          + SqrtPriceMath.getAmount1Delta(sqrtPriceX96, sqrtPriceLastTickX96, liquidityLast, false);
      }
    }
  }

  /// @dev Check if the remaining amount is enough to cross the next initialized tick.
  // If so, check whether the swap direction changes for optimal deposit. If so, we swap too much
  // and the final sqrt
  // price must be between the current tick and the next tick. Otherwise the next tick must be
  // crossed.
  function crossTicks(V3PoolCallee pool, SwapState memory state, uint160 sqrtPriceX96, bool zeroForOne) private view {
    // the next tick to swap to from the current tick in the swap direction
    int24 tickNext;
    // Ensure the initial `wordPos` doesn't coincide with the starting tick's.
    int16 wordPos = type(int16).min;
    // a word in `pool.tickBitmap`
    uint256 tickWord;

    do {
      (tickNext, wordPos, tickWord) =
        TickBitmap.nextInitializedTick(pool, state.tick, state.tickSpacing, zeroForOne, wordPos, tickWord);
      // sqrt(price) for the next tick (1/0)
      uint160 sqrtPriceNextX96 = tickNext.getSqrtRatioAtTick();
      // The desired amount of token0 to add liquidity after swap
      uint256 amount0Desired;
      // The desired amount of token1 to add liquidity after swap
      uint256 amount1Desired;

      unchecked {
        if (!zeroForOne) {
          // Abuse `amount1Desired` to store `amountIn` to avoid stack too deep errors.
          (sqrtPriceX96, amount1Desired, amount0Desired) = SwapMath.computeSwapStepExactIn(
            uint160(state.sqrtPriceX96), sqrtPriceNextX96, state.liquidity, state.amount1Desired, state.feePips
          );
          amount0Desired = state.amount0Desired + amount0Desired;
          amount1Desired = state.amount1Desired - amount1Desired;
        } else {
          // Abuse `amount0Desired` to store `amountIn` to avoid stack too deep errors.
          (sqrtPriceX96, amount0Desired, amount1Desired) = SwapMath.computeSwapStepExactIn(
            uint160(state.sqrtPriceX96), sqrtPriceNextX96, state.liquidity, state.amount0Desired, state.feePips
          );
          amount0Desired = state.amount0Desired - amount0Desired;
          amount1Desired = state.amount1Desired + amount1Desired;
        }
      }

      // If the remaining amount is large enough to consume the current tick and the optimal swap
      // direction
      // doesn't change, continue crossing ticks.
      if (sqrtPriceX96 != sqrtPriceNextX96) break;
      if (
        isZeroForOne(amount0Desired, amount1Desired, sqrtPriceX96, state.sqrtRatioLowerX96, state.sqrtRatioUpperX96)
          != zeroForOne
      ) {
        break;
      } else {
        int128 liquidityNet = pool.liquidityNet(tickNext);
        assembly ("memory-safe") {
          // If we're moving leftward, we interpret `liquidityNet` as the opposite sign.
          // If zeroForOne, liquidityNet = -liquidityNet = ~liquidityNet + 1 = -1 ^ liquidityNet +
          // 1.
          // Therefore, liquidityNet = -zeroForOne ^ liquidityNet + zeroForOne.
          liquidityNet := add(zeroForOne, xor(sub(0, zeroForOne), liquidityNet))
          // `liquidity` is the first in `SwapState`
          mstore(state, add(mload(state), liquidityNet))
          // state.sqrtPriceX96 = sqrtPriceX96
          mstore(add(state, 0x20), sqrtPriceX96)
          // state.tick = zeroForOne ? tickNext - 1 : tickNext
          mstore(add(state, 0x40), sub(tickNext, zeroForOne))
          // state.amount0Desired = amount0Desired
          mstore(add(state, 0x60), amount0Desired)
          // state.amount1Desired = amount1Desired
          mstore(add(state, 0x80), amount1Desired)
        }
      }
    } while (true);
  }

  /// @dev Analytic solution for optimal swap between two nearest initialized ticks swapping token0
  /// to token1
  /// @param state Pool state at the last tick of optimal swap
  /// @return sqrtPriceFinalX96 sqrt(price) after optimal swap
  function solveOptimalZeroForOne(SwapState memory state) private pure returns (uint160 sqrtPriceFinalX96) {
    /**
     * root = (sqrt(b^2 + 4ac) + b) / 2a
     * `a` is in the order of `amount0Desired`. `b` is in the order of `liquidity`.
     * `c` is in the order of `amount1Desired`.
     * `a`, `b`, `c` are signed integers in two's complement but typed as unsigned to avoid
     * unnecessary casting.
     */
    uint256 a;
    uint256 b;
    uint256 c;
    uint256 sqrtPriceX96;
    unchecked {
      uint256 liquidity;
      uint256 sqrtRatioUpperX96;
      uint256 feePips;
      uint256 feeComplement;
      assembly ("memory-safe") {
        // liquidity = state.liquidity
        liquidity := mload(state)
        // sqrtPriceX96 = state.sqrtPriceX96
        sqrtPriceX96 := mload(add(state, 0x20))
        // sqrtRatioUpperX96 = state.sqrtRatioUpperX96
        sqrtRatioUpperX96 := mload(add(state, 0xc0))
        // feePips = state.feePips
        feePips := mload(add(state, 0xe0))
        // feeComplement = MAX_FEE_PIPS - feePips
        feeComplement := sub(MAX_FEE_PIPS, feePips)
      }
      {
        uint256 a0;
        assembly ("memory-safe") {
          // amount0Desired = state.amount0Desired
          let amount0Desired := mload(add(state, 0x60))
          let liquidityX96 := shl(96, liquidity)
          // a = amount0Desired + liquidity / ((1 - f) * sqrtPrice) - liquidity / sqrtRatioUpper
          a0 := add(amount0Desired, div(mul(MAX_FEE_PIPS, liquidityX96), mul(feeComplement, sqrtPriceX96)))
          a := sub(a0, div(liquidityX96, sqrtRatioUpperX96))
          // `a` is always positive and greater than `amount0Desired`.
          if iszero(gt(a, amount0Desired)) {
            // revert Math_Overflow()
            mstore(0, 0x20236808)
            revert(0x1c, 0x04)
          }
        }
        b = a0.mulDivQ96(state.sqrtRatioLowerX96);
        assembly {
          b := add(div(mul(feePips, liquidity), feeComplement), b)
        }
      }
      {
        // c = amount1Desired + liquidity * sqrtPrice - liquidity * sqrtRatioLower / (1 - f)
        uint256 c0 = liquidity.mulDivQ96(sqrtPriceX96);
        assembly ("memory-safe") {
          // c0 = amount1Desired + liquidity * sqrtPrice
          c0 := add(mload(add(state, 0x80)), c0)
        }
        c = c0 - liquidity.mulDivQ96((MAX_FEE_PIPS * state.sqrtRatioLowerX96) / feeComplement);
        b -= c0.mulDiv(FixedPoint96.Q96, sqrtRatioUpperX96);
      }
      assembly {
        a := shl(1, a)
        c := shl(1, c)
      }
    }
    // Given a root exists, the following calculations cannot realistically overflow/underflow.
    unchecked {
      uint256 numerator = FullMath.sqrt(b * b + a * c) + b;
      assembly {
        // `numerator` and `a` must be positive so use `div`.
        sqrtPriceFinalX96 := div(shl(96, numerator), a)
      }
    }
    // The final price must be less than or equal to the price at the last tick.
    // However the calculated price may increase if the ratio is close to optimal.
    assembly {
      // sqrtPriceFinalX96 = min(sqrtPriceFinalX96, sqrtPriceX96)
      sqrtPriceFinalX96 :=
        xor(sqrtPriceX96, mul(xor(sqrtPriceX96, sqrtPriceFinalX96), lt(sqrtPriceFinalX96, sqrtPriceX96)))
    }
  }

  /// @dev Analytic solution for optimal swap between two nearest initialized ticks swapping token1
  /// to token0
  /// @param state Pool state at the last tick of optimal swap
  /// @return sqrtPriceFinalX96 sqrt(price) after optimal swap
  function solveOptimalOneForZero(SwapState memory state) private pure returns (uint160 sqrtPriceFinalX96) {
    /**
     * root = (sqrt(b^2 + 4ac) + b) / 2a
     * `a` is in the order of `amount0Desired`. `b` is in the order of `liquidity`.
     * `c` is in the order of `amount1Desired`.
     * `a`, `b`, `c` are signed integers in two's complement but typed as unsigned to avoid
     * unnecessary casting.
     */
    uint256 a;
    uint256 b;
    uint256 c;
    uint256 sqrtPriceX96;
    unchecked {
      uint256 liquidity;
      uint256 sqrtRatioUpperX96;
      uint256 feePips;
      uint256 feeComplement;
      assembly ("memory-safe") {
        // liquidity = state.liquidity
        liquidity := mload(state)
        // sqrtPriceX96 = state.sqrtPriceX96
        sqrtPriceX96 := mload(add(state, 0x20))
        // sqrtRatioUpperX96 = state.sqrtRatioUpperX96
        sqrtRatioUpperX96 := mload(add(state, 0xc0))
        // feePips = state.feePips
        feePips := mload(add(state, 0xe0))
        // feeComplement = MAX_FEE_PIPS - feePips
        feeComplement := sub(MAX_FEE_PIPS, feePips)
      }
      {
        // a = state.amount0Desired + liquidity / sqrtPrice - liquidity / ((1 - f) * sqrtRatioUpper)
        uint256 a0;
        assembly ("memory-safe") {
          let liquidityX96 := shl(96, liquidity)
          // a0 = state.amount0Desired + liquidity / sqrtPrice
          a0 := add(mload(add(state, 0x60)), div(liquidityX96, sqrtPriceX96))
          a := sub(a0, div(mul(MAX_FEE_PIPS, liquidityX96), mul(feeComplement, sqrtRatioUpperX96)))
        }
        b = a0.mulDivQ96(state.sqrtRatioLowerX96);
        assembly {
          b := sub(b, div(mul(feePips, liquidity), feeComplement))
        }
      }
      {
        // c = amount1Desired + liquidity * sqrtPrice / (1 - f) - liquidity * sqrtRatioLower
        uint256 c0 = liquidity.mulDivQ96((MAX_FEE_PIPS * sqrtPriceX96) / feeComplement);
        uint256 amount1Desired;
        assembly ("memory-safe") {
          // amount1Desired = state.amount1Desired
          amount1Desired := mload(add(state, 0x80))
          // c0 = amount1Desired + liquidity * sqrtPrice / (1 - f)
          c0 := add(amount1Desired, c0)
        }
        c = c0 - liquidity.mulDivQ96(state.sqrtRatioLowerX96);
        assembly ("memory-safe") {
          // `c` is always positive and greater than `amount1Desired`.
          if iszero(gt(c, amount1Desired)) {
            // revert Math_Overflow()
            mstore(0, 0x20236808)
            revert(0x1c, 0x04)
          }
        }
        b -= c0.mulDiv(FixedPoint96.Q96, sqrtRatioUpperX96);
      }
      assembly {
        a := shl(1, a)
        c := shl(1, c)
      }
    }
    // Given a root exists, the following calculations cannot realistically overflow/underflow.
    unchecked {
      uint256 numerator = FullMath.sqrt(b * b + a * c) + b;
      assembly {
        // `numerator` and `a` may be negative so use `sdiv`.
        sqrtPriceFinalX96 := sdiv(shl(96, numerator), a)
      }
    }
    // The final price must be greater than or equal to the price at the last tick.
    // However the calculated price may decrease if the ratio is close to optimal.
    assembly {
      // sqrtPriceFinalX96 = max(sqrtPriceFinalX96, sqrtPriceX96)
      sqrtPriceFinalX96 :=
        xor(sqrtPriceX96, mul(xor(sqrtPriceX96, sqrtPriceFinalX96), gt(sqrtPriceFinalX96, sqrtPriceX96)))
    }
  }

  /// @dev Swap direction to achieve optimal deposit when the current price is in range
  /// @param amount0Desired The desired amount of token0 to be spent
  /// @param amount1Desired The desired amount of token1 to be spent
  /// @param sqrtPriceX96 sqrt(price) at the last tick of optimal swap
  /// @param sqrtRatioLowerX96 The lower sqrt(price) of the position in which to add liquidity
  /// @param sqrtRatioUpperX96 The upper sqrt(price) of the position in which to add liquidity
  /// @return The direction of the swap, true for token0 to token1, false for token1 to token0
  function isZeroForOneInRange(
    uint256 amount0Desired,
    uint256 amount1Desired,
    uint256 sqrtPriceX96,
    uint256 sqrtRatioLowerX96,
    uint256 sqrtRatioUpperX96
  ) private pure returns (bool) {
    // amount0 = liquidity0 * (sqrt(upper) - sqrt(current)) / (sqrt(upper) * sqrt(current))
    // amount1 = liquidity1 * (sqrt(current) - sqrt(lower))
    // We want to compare liquidity of amount0 with liquidity of amount1
    // ==> compare amount0 * (sqrt(current) - sqrt(lower))
    //    with amount1 * (sqrt(upper) - sqrt(current)) / sqrt(upper) * sqrt(current)

    unchecked {
      return amount0Desired.mulDivQ96(sqrtRatioUpperX96.mulDiv(sqrtPriceX96, sqrtRatioUpperX96 - sqrtPriceX96))
        > amount1Desired.mulDiv(FixedPoint96.Q96, sqrtPriceX96 - sqrtRatioLowerX96);
      // return amount0Desired.mulDivQ96(sqrtPriceX96).mulDivQ96(sqrtPriceX96 - sqrtRatioLowerX96)
      //> amount1Desired.mulDiv(sqrtRatioUpperX96 - sqrtPriceX96, sqrtRatioUpperX96);
    }
  }

  /// @dev Swap direction to achieve optimal deposit
  /// @param amount0Desired The desired amount of token0 to be spent
  /// @param amount1Desired The desired amount of token1 to be spent
  /// @param sqrtPriceX96 sqrt(price) at the last tick of optimal swap
  /// @param sqrtRatioLowerX96 The lower sqrt(price) of the position in which to add liquidity
  /// @param sqrtRatioUpperX96 The upper sqrt(price) of the position in which to add liquidity
  /// @return The direction of the swap, true for token0 to token1, false for token1 to token0
  function isZeroForOne(
    uint256 amount0Desired,
    uint256 amount1Desired,
    uint256 sqrtPriceX96,
    uint256 sqrtRatioLowerX96,
    uint256 sqrtRatioUpperX96
  ) internal pure returns (bool) {
    // If the current price is below `sqrtRatioLowerX96`, only token0 is required.
    if (sqrtPriceX96 <= sqrtRatioLowerX96) return false;
    // If the current tick is above `sqrtRatioUpperX96`, only token1 is required.
    else if (sqrtPriceX96 >= sqrtRatioUpperX96) return true;
    else return isZeroForOneInRange(amount0Desired, amount1Desired, sqrtPriceX96, sqrtRatioLowerX96, sqrtRatioUpperX96);
  }
}

File 46 of 46 : FixedPointMathLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The operation failed, as the output exceeds the maximum value of uint256.
    error ExpOverflow();

    /// @dev The operation failed, as the output exceeds the maximum value of uint256.
    error FactorialOverflow();

    /// @dev The operation failed, due to an overflow.
    error RPowOverflow();

    /// @dev The mantissa is too big to fit.
    error MantissaOverflow();

    /// @dev The operation failed, due to an multiplication overflow.
    error MulWadFailed();

    /// @dev The operation failed, due to an multiplication overflow.
    error SMulWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error DivWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error SDivWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error MulDivFailed();

    /// @dev The division failed, as the denominator is zero.
    error DivFailed();

    /// @dev The full precision multiply-divide operation failed, either due
    /// to the result being larger than 256 bits, or a division by a zero.
    error FullMulDivFailed();

    /// @dev The output is undefined, as the input is less-than-or-equal to zero.
    error LnWadUndefined();

    /// @dev The input outside the acceptable domain.
    error OutOfDomain();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The scalar of ETH and most ERC20s.
    uint256 internal constant WAD = 1e18;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*              SIMPLIFIED FIXED POINT OPERATIONS             */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Equivalent to `(x * y) / WAD` rounded down.
    function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
            if mul(y, gt(x, div(not(0), y))) {
                mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := div(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down.
    function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
            if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
                mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := sdiv(z, WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
    function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
    function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded up.
    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
            if mul(y, gt(x, div(not(0), y))) {
                mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
    function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down.
    function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
            if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
                mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := div(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down.
    function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, WAD)
            // Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
            if iszero(and(iszero(iszero(y)), eq(sdiv(z, WAD), x))) {
                mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := sdiv(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
    function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
    function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded up.
    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
            if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
                mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
    function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
        }
    }

    /// @dev Equivalent to `x` to the power of `y`.
    /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
    function powWad(int256 x, int256 y) internal pure returns (int256) {
        // Using `ln(x)` means `x` must be greater than 0.
        return expWad((lnWad(x) * y) / int256(WAD));
    }

    /// @dev Returns `exp(x)`, denominated in `WAD`.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
    function expWad(int256 x) internal pure returns (int256 r) {
        unchecked {
            // When the result is less than 0.5 we return zero.
            // This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
            if (x <= -41446531673892822313) return r;

            /// @solidity memory-safe-assembly
            assembly {
                // When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
                // an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
                if iszero(slt(x, 135305999368893231589)) {
                    mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
                    revert(0x1c, 0x04)
                }
            }

            // `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
            // for more intermediate precision and a binary basis. This base conversion
            // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
            x = (x << 78) / 5 ** 18;

            // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
            // of two such that exp(x) = exp(x') * 2**k, where k is an integer.
            // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
            int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
            x = x - k * 54916777467707473351141471128;

            // `k` is in the range `[-61, 195]`.

            // Evaluate using a (6, 7)-term rational approximation.
            // `p` is made monic, we'll multiply by a scale factor later.
            int256 y = x + 1346386616545796478920950773328;
            y = ((y * x) >> 96) + 57155421227552351082224309758442;
            int256 p = y + x - 94201549194550492254356042504812;
            p = ((p * y) >> 96) + 28719021644029726153956944680412240;
            p = p * x + (4385272521454847904659076985693276 << 96);

            // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
            int256 q = x - 2855989394907223263936484059900;
            q = ((q * x) >> 96) + 50020603652535783019961831881945;
            q = ((q * x) >> 96) - 533845033583426703283633433725380;
            q = ((q * x) >> 96) + 3604857256930695427073651918091429;
            q = ((q * x) >> 96) - 14423608567350463180887372962807573;
            q = ((q * x) >> 96) + 26449188498355588339934803723976023;

            /// @solidity memory-safe-assembly
            assembly {
                // Div in assembly because solidity adds a zero check despite the unchecked.
                // The q polynomial won't have zeros in the domain as all its roots are complex.
                // No scaling is necessary because p is already `2**96` too large.
                r := sdiv(p, q)
            }

            // r should be in the range `(0.09, 0.25) * 2**96`.

            // We now need to multiply r by:
            // - The scale factor `s ≈ 6.031367120`.
            // - The `2**k` factor from the range reduction.
            // - The `1e18 / 2**96` factor for base conversion.
            // We do this all at once, with an intermediate result in `2**213`
            // basis, so the final right shift is always by a positive amount.
            r = int256(
                (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
            );
        }
    }

    /// @dev Returns `ln(x)`, denominated in `WAD`.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
    function lnWad(int256 x) internal pure returns (int256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            // We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
            // We do this by multiplying by `2**96 / 10**18`. But since
            // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
            // and add `ln(2**96 / 10**18)` at the end.

            // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
            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))))
            // We place the check here for more optimal stack operations.
            if iszero(sgt(x, 0)) {
                mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
                revert(0x1c, 0x04)
            }
            // forgefmt: disable-next-item
            r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))

            // Reduce range of x to (1, 2) * 2**96
            // ln(2^k * x) = k * ln(2) + ln(x)
            x := shr(159, shl(r, x))

            // Evaluate using a (8, 8)-term rational approximation.
            // `p` is made monic, we will multiply by a scale factor later.
            // forgefmt: disable-next-item
            let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
                sar(96, mul(add(43456485725739037958740375743393,
                sar(96, mul(add(24828157081833163892658089445524,
                sar(96, mul(add(3273285459638523848632254066296,
                    x), x))), x))), x)), 11111509109440967052023855526967)
            p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
            p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
            p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
            // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.

            // `q` is monic by convention.
            let q := add(5573035233440673466300451813936, x)
            q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
            q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
            q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
            q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
            q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
            q := add(909429971244387300277376558375, sar(96, mul(x, q)))

            // `p / q` is in the range `(0, 0.125) * 2**96`.

            // Finalization, we need to:
            // - Multiply by the scale factor `s = 5.549…`.
            // - Add `ln(2**96 / 10**18)`.
            // - Add `k * ln(2)`.
            // - Multiply by `10**18 / 2**96 = 5**18 >> 78`.

            // The q polynomial is known not to have zeros in the domain.
            // No scaling required because p is already `2**96` too large.
            p := sdiv(p, q)
            // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
            p := mul(1677202110996718588342820967067443963516166, p)
            // Add `ln(2) * k * 5**18 * 2**192`.
            // forgefmt: disable-next-item
            p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
            // Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
            p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
            // Base conversion: mul `2**18 / 2**192`.
            r := sar(174, p)
        }
    }

    /// @dev Returns `W_0(x)`, denominated in `WAD`.
    /// See: https://en.wikipedia.org/wiki/Lambert_W_function
    /// a.k.a. Product log function. This is an approximation of the principal branch.
    function lambertW0Wad(int256 x) internal pure returns (int256 w) {
        // forgefmt: disable-next-item
        unchecked {
            if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
            int256 wad = int256(WAD);
            int256 p = x;
            uint256 c; // Whether we need to avoid catastrophic cancellation.
            uint256 i = 4; // Number of iterations.
            if (w <= 0x1ffffffffffff) {
                if (-0x4000000000000 <= w) {
                    i = 1; // Inputs near zero only take one step to converge.
                } else if (w <= -0x3ffffffffffffff) {
                    i = 32; // Inputs near `-1/e` take very long to converge.
                }
            } else if (w >> 63 == 0) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Inline log2 for more performance, since the range is small.
                    let v := shr(49, w)
                    let l := shl(3, lt(0xff, v))
                    l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
                        0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
                    w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
                    c := gt(l, 60)
                    i := add(2, add(gt(l, 53), c))
                }
            } else {
                int256 ll = lnWad(w = lnWad(w));
                /// @solidity memory-safe-assembly
                assembly {
                    // `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
                    w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
                    i := add(3, iszero(shr(68, x)))
                    c := iszero(shr(143, x))
                }
                if (c == 0) {
                    do { // If `x` is big, use Newton's so that intermediate values won't overflow.
                        int256 e = expWad(w);
                        /// @solidity memory-safe-assembly
                        assembly {
                            let t := mul(w, div(e, wad))
                            w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
                        }
                        if (p <= w) break;
                        p = w;
                    } while (--i != 0);
                    /// @solidity memory-safe-assembly
                    assembly {
                        w := sub(w, sgt(w, 2))
                    }
                    return w;
                }
            }
            do { // Otherwise, use Halley's for faster convergence.
                int256 e = expWad(w);
                /// @solidity memory-safe-assembly
                assembly {
                    let t := add(w, wad)
                    let s := sub(mul(w, e), mul(x, wad))
                    w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
                }
                if (p <= w) break;
                p = w;
            } while (--i != c);
            /// @solidity memory-safe-assembly
            assembly {
                w := sub(w, sgt(w, 2))
            }
            // For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
            // R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
            if (c != 0) {
                int256 t = w | 1;
                /// @solidity memory-safe-assembly
                assembly {
                    x := sdiv(mul(x, wad), t)
                }
                x = (t * (wad + lnWad(x)));
                /// @solidity memory-safe-assembly
                assembly {
                    w := sdiv(x, add(wad, t))
                }
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  GENERAL NUMBER UTILITIES                  */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Calculates `floor(x * y / d)` with full precision.
    /// Throws if result overflows a uint256 or when `d` is zero.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
    function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            for {} 1 {} {
                // 512-bit multiply `[p1 p0] = x * y`.
                // 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 = p1 * 2**256 + p0`.

                // Least significant 256 bits of the product.
                result := mul(x, y) // Temporarily use `result` as `p0` to save gas.
                let mm := mulmod(x, y, not(0))
                // Most significant 256 bits of the product.
                let p1 := sub(mm, add(result, lt(mm, result)))

                // Handle non-overflow cases, 256 by 256 division.
                if iszero(p1) {
                    if iszero(d) {
                        mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                        revert(0x1c, 0x04)
                    }
                    result := div(result, d)
                    break
                }

                // Make sure the result is less than `2**256`. Also prevents `d == 0`.
                if iszero(gt(d, p1)) {
                    mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                    revert(0x1c, 0x04)
                }

                /*------------------- 512 by 256 division --------------------*/

                // Make division exact by subtracting the remainder from `[p1 p0]`.
                // Compute remainder using mulmod.
                let r := mulmod(x, y, d)
                // `t` is the least significant bit of `d`.
                // Always greater or equal to 1.
                let t := and(d, sub(0, d))
                // Divide `d` by `t`, which is a power of two.
                d := div(d, t)
                // Invert `d mod 2**256`
                // Now that `d` is an odd number, it has an inverse
                // modulo `2**256` such that `d * inv = 1 mod 2**256`.
                // Compute the inverse by starting with a seed that is correct
                // correct for four bits. That is, `d * inv = 1 mod 2**4`.
                let inv := xor(2, mul(3, d))
                // 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 := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
                result :=
                    mul(
                        // Divide [p1 p0] by the factors of two.
                        // Shift in bits from `p1` into `p0`. For this we need
                        // to flip `t` such that it is `2**256 / t`.
                        or(
                            mul(sub(p1, gt(r, result)), add(div(sub(0, t), t), 1)),
                            div(sub(result, r), t)
                        ),
                        // inverse mod 2**256
                        mul(inv, sub(2, mul(d, inv)))
                    )
                break
            }
        }
    }

    /// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
    /// Throws if result overflows a uint256 or when `d` is zero.
    /// Credit to Uniswap-v3-core under MIT license:
    /// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
    function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
        result = fullMulDiv(x, y, d);
        /// @solidity memory-safe-assembly
        assembly {
            if mulmod(x, y, d) {
                result := add(result, 1)
                if iszero(result) {
                    mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                    revert(0x1c, 0x04)
                }
            }
        }
    }

    /// @dev Returns `floor(x * y / d)`.
    /// Reverts if `x * y` overflows, or `d` is zero.
    function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {
                mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                revert(0x1c, 0x04)
            }
            z := div(mul(x, y), d)
        }
    }

    /// @dev Returns `ceil(x * y / d)`.
    /// Reverts if `x * y` overflows, or `d` is zero.
    function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {
                mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(mul(x, y), d))), div(mul(x, y), d))
        }
    }

    /// @dev Returns `ceil(x / d)`.
    /// Reverts if `d` is zero.
    function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(d) {
                mstore(0x00, 0x65244e4e) // `DivFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(x, d))), div(x, d))
        }
    }

    /// @dev Returns `max(0, x - y)`.
    function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(gt(x, y), sub(x, y))
        }
    }

    /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
    /// Reverts if the computation overflows.
    function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
            if x {
                z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
                let half := shr(1, b) // Divide `b` by 2.
                // Divide `y` by 2 every iteration.
                for { y := shr(1, y) } y { y := shr(1, y) } {
                    let xx := mul(x, x) // Store x squared.
                    let xxRound := add(xx, half) // Round to the nearest number.
                    // Revert if `xx + half` overflowed, or if `x ** 2` overflows.
                    if or(lt(xxRound, xx), shr(128, x)) {
                        mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                        revert(0x1c, 0x04)
                    }
                    x := div(xxRound, b) // Set `x` to scaled `xxRound`.
                    // If `y` is odd:
                    if and(y, 1) {
                        let zx := mul(z, x) // Compute `z * x`.
                        let zxRound := add(zx, half) // Round to the nearest number.
                        // If `z * x` overflowed or `zx + half` overflowed:
                        if or(xor(div(zx, x), z), lt(zxRound, zx)) {
                            // Revert if `x` is non-zero.
                            if iszero(iszero(x)) {
                                mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                                revert(0x1c, 0x04)
                            }
                        }
                        z := div(zxRound, b) // Return properly scaled `zxRound`.
                    }
                }
            }
        }
    }

    /// @dev Returns the square root of `x`.
    function sqrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
            z := 181 // The "correct" value is 1, but this saves a multiplication later.

            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.

            // Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
            // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
            let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffffff, shr(r, x))))
            z := shl(shr(1, r), z)

            // Goal was to get `z*z*y` within a small factor of `x`. More iterations could
            // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
            // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
            // That's not possible if `x < 256` but we can just verify those cases exhaustively.

            // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
            // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
            // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.

            // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
            // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
            // with largest error when `s = 1` and when `s = 256` or `1/256`.

            // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
            // Then we can estimate `sqrt(y)` using
            // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.

            // There is no overflow risk here since `y < 2**136` after the first branch above.
            z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.

            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))

            // If `x+1` is a perfect square, the Babylonian method cycles between
            // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
            z := sub(z, lt(div(x, z), z))
        }
    }

    /// @dev Returns the cube root of `x`.
    /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
    /// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy
    function cbrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            let 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))))

            z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))

            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)

            z := sub(z, lt(div(x, mul(z, z)), z))
        }
    }

    /// @dev Returns the square root of `x`, denominated in `WAD`.
    function sqrtWad(uint256 x) internal pure returns (uint256 z) {
        unchecked {
            z = 10 ** 9;
            if (x <= type(uint256).max / 10 ** 36 - 1) {
                x *= 10 ** 18;
                z = 1;
            }
            z *= sqrt(x);
        }
    }

    /// @dev Returns the cube root of `x`, denominated in `WAD`.
    function cbrtWad(uint256 x) internal pure returns (uint256 z) {
        unchecked {
            z = 10 ** 12;
            if (x <= (type(uint256).max / 10 ** 36) * 10 ** 18 - 1) {
                if (x >= type(uint256).max / 10 ** 36) {
                    x *= 10 ** 18;
                    z = 10 ** 6;
                } else {
                    x *= 10 ** 36;
                    z = 1;
                }
            }
            z *= cbrt(x);
        }
    }

    /// @dev Returns the factorial of `x`.
    function factorial(uint256 x) internal pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(lt(x, 58)) {
                mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
                revert(0x1c, 0x04)
            }
            for { result := 1 } x { x := sub(x, 1) } { result := mul(result, x) }
        }
    }

    /// @dev Returns the log2 of `x`.
    /// Equivalent to computing the index of the most significant bit (MSB) of `x`.
    /// Returns 0 if `x` is zero.
    function log2(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            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)),
                0x0706060506020504060203020504030106050205030304010505030400000000))
        }
    }

    /// @dev Returns the log2 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log2Up(uint256 x) internal pure returns (uint256 r) {
        r = log2(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(shl(r, 1), x))
        }
    }

    /// @dev Returns the log10 of `x`.
    /// Returns 0 if `x` is zero.
    function log10(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(lt(x, 100000000000000000000000000000000000000)) {
                x := div(x, 100000000000000000000000000000000000000)
                r := 38
            }
            if iszero(lt(x, 100000000000000000000)) {
                x := div(x, 100000000000000000000)
                r := add(r, 20)
            }
            if iszero(lt(x, 10000000000)) {
                x := div(x, 10000000000)
                r := add(r, 10)
            }
            if iszero(lt(x, 100000)) {
                x := div(x, 100000)
                r := add(r, 5)
            }
            r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
        }
    }

    /// @dev Returns the log10 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log10Up(uint256 x) internal pure returns (uint256 r) {
        r = log10(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(exp(10, r), x))
        }
    }

    /// @dev Returns the log256 of `x`.
    /// Returns 0 if `x` is zero.
    function log256(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            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(shr(3, r), lt(0xff, shr(r, x)))
        }
    }

    /// @dev Returns the log256 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log256Up(uint256 x) internal pure returns (uint256 r) {
        r = log256(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(shl(shl(3, r), 1), x))
        }
    }

    /// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
    /// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
    function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
        /// @solidity memory-safe-assembly
        assembly {
            mantissa := x
            if mantissa {
                if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
                    mantissa := div(mantissa, 1000000000000000000000000000000000)
                    exponent := 33
                }
                if iszero(mod(mantissa, 10000000000000000000)) {
                    mantissa := div(mantissa, 10000000000000000000)
                    exponent := add(exponent, 19)
                }
                if iszero(mod(mantissa, 1000000000000)) {
                    mantissa := div(mantissa, 1000000000000)
                    exponent := add(exponent, 12)
                }
                if iszero(mod(mantissa, 1000000)) {
                    mantissa := div(mantissa, 1000000)
                    exponent := add(exponent, 6)
                }
                if iszero(mod(mantissa, 10000)) {
                    mantissa := div(mantissa, 10000)
                    exponent := add(exponent, 4)
                }
                if iszero(mod(mantissa, 100)) {
                    mantissa := div(mantissa, 100)
                    exponent := add(exponent, 2)
                }
                if iszero(mod(mantissa, 10)) {
                    mantissa := div(mantissa, 10)
                    exponent := add(exponent, 1)
                }
            }
        }
    }

    /// @dev Convenience function for packing `x` into a smaller number using `sci`.
    /// The `mantissa` will be in bits [7..255] (the upper 249 bits).
    /// The `exponent` will be in bits [0..6] (the lower 7 bits).
    /// Use `SafeCastLib` to safely ensure that the `packed` number is small
    /// enough to fit in the desired unsigned integer type:
    /// ```
    ///     uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
    /// ```
    function packSci(uint256 x) internal pure returns (uint256 packed) {
        (x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
        /// @solidity memory-safe-assembly
        assembly {
            if shr(249, x) {
                mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
                revert(0x1c, 0x04)
            }
            packed := or(shl(7, x), packed)
        }
    }

    /// @dev Convenience function for unpacking a packed number from `packSci`.
    function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
        unchecked {
            unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
        }
    }

    /// @dev Returns the average of `x` and `y`.
    function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = (x & y) + ((x ^ y) >> 1);
        }
    }

    /// @dev Returns the average of `x` and `y`.
    function avg(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = (x >> 1) + (y >> 1) + (x & y & 1);
        }
    }

    /// @dev Returns the absolute value of `x`.
    function abs(int256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(sub(0, shr(255, x)), add(sub(0, shr(255, x)), x))
        }
    }

    /// @dev Returns the absolute distance between `x` and `y`.
    function dist(int256 x, int256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(mul(xor(sub(y, x), sub(x, y)), sgt(x, y)), sub(y, x))
        }
    }

    /// @dev Returns the minimum of `x` and `y`.
    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), lt(y, x)))
        }
    }

    /// @dev Returns the minimum of `x` and `y`.
    function min(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), slt(y, x)))
        }
    }

    /// @dev Returns the maximum of `x` and `y`.
    function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), gt(y, x)))
        }
    }

    /// @dev Returns the maximum of `x` and `y`.
    function max(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), sgt(y, x)))
        }
    }

    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
    function clamp(uint256 x, uint256 minValue, uint256 maxValue)
        internal
        pure
        returns (uint256 z)
    {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
            z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
        }
    }

    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
    function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
            z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
        }
    }

    /// @dev Returns greatest common divisor of `x` and `y`.
    function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            for { z := x } y {} {
                let t := y
                y := mod(z, y)
                z := t
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   RAW NUMBER OPERATIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns `x + y`, without checking for overflow.
    function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x + y;
        }
    }

    /// @dev Returns `x + y`, without checking for overflow.
    function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x + y;
        }
    }

    /// @dev Returns `x - y`, without checking for underflow.
    function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x - y;
        }
    }

    /// @dev Returns `x - y`, without checking for underflow.
    function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x - y;
        }
    }

    /// @dev Returns `x * y`, without checking for overflow.
    function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x * y;
        }
    }

    /// @dev Returns `x * y`, without checking for overflow.
    function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x * y;
        }
    }

    /// @dev Returns `x / y`, returning 0 if `y` is zero.
    function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(x, y)
        }
    }

    /// @dev Returns `x / y`, returning 0 if `y` is zero.
    function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(x, y)
        }
    }

    /// @dev Returns `x % y`, returning 0 if `y` is zero.
    function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mod(x, y)
        }
    }

    /// @dev Returns `x % y`, returning 0 if `y` is zero.
    function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := smod(x, y)
        }
    }

    /// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
    function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := addmod(x, y, d)
        }
    }

    /// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
    function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mulmod(x, y, d)
        }
    }
}

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

Contract Security Audit

Contract ABI

API
[{"inputs":[],"name":"InvalidFeeConfig","type":"error"},{"inputs":[],"name":"InvalidInstructionType","type":"error"},{"inputs":[],"name":"InvalidStrategy","type":"error"},{"inputs":[],"name":"InvalidSwapRouter","type":"error"},{"inputs":[],"name":"InvalidVaultConfig","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"TransferFailed","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"vaultAddress","type":"address"},{"indexed":true,"internalType":"enum IFeeTaker.FeeType","name":"feeType","type":"uint8"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"FeeCollected","type":"event"},{"inputs":[{"internalType":"int256","name":"amount0Delta","type":"int256"},{"internalType":"int256","name":"amount1Delta","type":"int256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"pancakeV3SwapCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint256","name":"amount1","type":"uint256"},{"components":[{"internalType":"uint16","name":"vaultOwnerFeeBasisPoint","type":"uint16"},{"internalType":"address","name":"vaultOwner","type":"address"},{"internalType":"uint16","name":"platformFeeBasisPoint","type":"uint16"},{"internalType":"address","name":"platformFeeRecipient","type":"address"},{"internalType":"uint64","name":"gasFeeX64","type":"uint64"},{"internalType":"address","name":"gasFeeRecipient","type":"address"}],"internalType":"struct ICommon.FeeConfig","name":"feeConfig","type":"tuple"},{"internalType":"address","name":"principalToken","type":"address"},{"internalType":"address","name":"pool","type":"address"},{"internalType":"address","name":"validator","type":"address"}],"name":"takeFees","outputs":[{"internalType":"uint256","name":"fee0","type":"uint256"},{"internalType":"uint256","name":"fee1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"int256","name":"amount0Delta","type":"int256"},{"internalType":"int256","name":"amount1Delta","type":"int256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"uniswapV3SwapCallback","outputs":[],"stateMutability":"nonpayable","type":"function"}]

0x60808060405234601557610cac908161001a8239f35b5f80fdfe60806040526004361015610011575f80fd5b5f5f3560e01c90816323a69e75146107d35781635ac6fb9c14610042575063fa461e331461003d575f80fd5b6107d3565b346106ee576101a03660031901126106ee57600435906001600160a01b03821682036106ee57604435906001600160a01b03821682036106ee5760c03660831901126106ee576040519161009583610954565b60843561ffff811681036106ee57835260a4356001600160a01b03811681036106ee57602084015260c43561ffff811681036106ee57604084015260e4356001600160a01b03811681036106ee5760608401526101043567ffffffffffffffff811681036106ee576080840152610124356001600160a01b03811681036106ee5760a084015261014435906001600160a01b03821682036106ee5761016435946001600160a01b03861686036106ee5761018435926001600160a01b03841684036106ee575f955f955f955f915f975f9b5f935f9960243561078f575b60643561074a575b986001600160a01b0389811690821603610737575b506101a4858f61019f908d6109c5565b6109c5565b9182610400575b5050509060409b86928260018060a01b03606089015116948286936103aa575b5050505080610363575b50505060208301516001600160a01b03169182908061031a575b5050806102d1575b505060a001516001600160a01b03169384918161027c575b50505081610227575b50505082519182526020820152f35b6002915f516020610c805f395f51905f52906102719061025181876001600160a01b0387166109f3565b88516001600160a01b039094168452602084015233929081906040820190565b0390a4838080610218565b6002915f516020610c805f395f51905f52906102c6906102a681876001600160a01b0387166109f3565b8b516001600160a01b039094168452602084015233929081906040820190565b0390a482878061020f565b6001906102e881846001600160a01b0389166109f3565b8a516001600160a01b0387168152602081019190915233905f516020610c805f395f51905f5290604090a488806101f7565b60019061033181846001600160a01b038a166109f3565b8c516001600160a01b0388168152602081019190915233905f516020610c805f395f51905f5290604090a4818b6101ef565b61037781846001600160a01b038b166109f3565b8c516001600160a01b0389168152602081019190915233905f516020610c805f395f51905f5290604090a48a80806101d5565b5f516020610c805f395f51905f52906103f4906103d181876001600160a01b0387166109f3565b604080516001600160a01b03909516855260208501919091523393918291820190565b0390a48282885f6101cb565b9a829b60409b979b969394929596519061041982610954565b6001600160a01b0390811682528a81166020808401918252918d166040808501918252606085019889525f608086015251909891926104589082610984565b5f815260a0840152875182516001600160a01b039081169116146106f2576001600160a01b038116610683575b508151955196519051889788976001600160a01b03938416928416929092119288921690806105a3575b5050505060800151841061055e57838f88936104ce8f80938e99610ba2565b6104d7916109c5565b9c6104e3828785610ba2565b6104ec916109c5565b986104f692610ba2565b6104ff916109c5565b9a8085145f149e60409f6105225750505050905081809281985b9192819d6101ab565b8183610552610546846105406105589897610540978d9e9c9d610ba2565b906109e6565b9661054084828d610ba2565b98610ba2565b98610519565b60405162461bcd60e51b815260206004820152601a60248201527f496e73756666696369656e74206f757470757420616d6f756e740000000000006044820152606490fd5b906040949950809293985060018060a01b03198454161783558260c485516105cc602082610984565b5f8152865193630251596160e31b85523060048601528b602486015260448501528a73fffd8963efd1fc6a506488495d951d53639afb810273fffd8963efd1fc6a506488495d951d5263988d2518606485015260a0608485015280519060208201908160a487019160045afa5001925af160403d14161561067a5760808651602051865f14610672578089035b961561066b57505b9590875f806104af565b9050610661565b818903610659565b853d81803e3d90fd5b82516001600160a01b039081169082163b156106ee5760405163c94a521d60e01b81526004810191909152905f90829060249082906001600160a01b03165afa80156106e35715610485576106db9198505f90610984565b5f965f610485565b6040513d5f823e3d90fd5b5f80fd5b60405162461bcd60e51b815260206004820152601a60248201527f746f6b656e20697320616c7265616479207072696e636970616c0000000000006044820152606490fd5b929d999a999298509394936101a461018f565b9d5093509750985061075e84606435610a49565b9b929b99919490949d8c80610774575b5061017a565b6107899030336001600160a01b038516610b0e565b8f61076e565b9c5094509850506107a284602435610a49565b9c929c9a91959095928d806107b8575b50610172565b6107cd9030336001600160a01b038e16610b0e565b8f6107b2565b346106ee5760603660031901126106ee5760243560043560443567ffffffffffffffff81116106ee57366023820112156106ee5780600401359067ffffffffffffffff82116106ee5736602483830101116106ee5750505f546001600160a01b03163381900361091e57604051630dfe168160e01b815292602084600481855afa9182156106e3576004945f936108fc575b506020906040519586809263d21220a760e01b82525afa9384156106e3575f946108cb575b505f8313156108ab57506108a9925033906001600160a01b03166109f3565b005b9150505f81136108b757005b6108a99133906001600160a01b03166109f3565b6108ee91945060203d6020116108f5575b6108e68183610984565b8101906109a6565b925f61088a565b503d6108dc565b602091935061091790823d84116108f5576108e68183610984565b9290610865565b60405162461bcd60e51b815260206004820152600e60248201526d125b98dbdc9c9958dd081c1bdbdb60921b6044820152606490fd5b60c0810190811067ffffffffffffffff82111761097057604052565b634e487b7160e01b5f52604160045260245ffd5b90601f8019910116810190811067ffffffffffffffff82111761097057604052565b908160209103126106ee57516001600160a01b03811681036106ee5790565b919082018092116109d257565b634e487b7160e01b5f52601160045260245ffd5b919082039182116109d257565b60405163a9059cbb60e01b60208201526001600160a01b03929092166024830152604480830193909352918152610a3491610a2f606483610984565b610c27565b565b818102929181159184041417156109d257565b9190915f925f925f925f9261ffff60408201511680610ae7575b5061ffff81511680610aaa575b506080015167ffffffffffffffff169081610a89575050565b610a94929350610b52565b9081610a9c57565b9381610aa7916109c5565b93565b612710919550610aba9083610a36565b049384610ac8575b5f610a70565b956080610ade8667ffffffffffffffff936109c5565b97915050610ac2565b612710919650610af79083610a36565b049485610b05575b5f610a63565b95508495610aff565b6040516323b872dd60e01b60208201526001600160a01b039283166024820152929091166044830152606480830193909352918152610a3491610a2f608483610984565b5f91905f198282099180820293848085109403938085039414610b9857600160401b841015610b955750600160401b910990828211900360c01b910360401c1790565b80fd5b5050505060401c90565b915f198284099282810292838086109503948086039514610c1957848311156106ee5782910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b5050809250156106ee570490565b905f602091828151910182855af1156106e3575f513d610c7657506001600160a01b0381163b155b610c565750565b635274afe760e01b5f9081526001600160a01b0391909116600452602490fd5b60011415610c4f56fe11d90d99368a301484d9d42a2dd11deb18f3cd27ec3d02dd7d52f3a58a2797fca164736f6c634300081c000a

Deployed Bytecode

0x60806040526004361015610011575f80fd5b5f5f3560e01c90816323a69e75146107d35781635ac6fb9c14610042575063fa461e331461003d575f80fd5b6107d3565b346106ee576101a03660031901126106ee57600435906001600160a01b03821682036106ee57604435906001600160a01b03821682036106ee5760c03660831901126106ee576040519161009583610954565b60843561ffff811681036106ee57835260a4356001600160a01b03811681036106ee57602084015260c43561ffff811681036106ee57604084015260e4356001600160a01b03811681036106ee5760608401526101043567ffffffffffffffff811681036106ee576080840152610124356001600160a01b03811681036106ee5760a084015261014435906001600160a01b03821682036106ee5761016435946001600160a01b03861686036106ee5761018435926001600160a01b03841684036106ee575f955f955f955f915f975f9b5f935f9960243561078f575b60643561074a575b986001600160a01b0389811690821603610737575b506101a4858f61019f908d6109c5565b6109c5565b9182610400575b5050509060409b86928260018060a01b03606089015116948286936103aa575b5050505080610363575b50505060208301516001600160a01b03169182908061031a575b5050806102d1575b505060a001516001600160a01b03169384918161027c575b50505081610227575b50505082519182526020820152f35b6002915f516020610c805f395f51905f52906102719061025181876001600160a01b0387166109f3565b88516001600160a01b039094168452602084015233929081906040820190565b0390a4838080610218565b6002915f516020610c805f395f51905f52906102c6906102a681876001600160a01b0387166109f3565b8b516001600160a01b039094168452602084015233929081906040820190565b0390a482878061020f565b6001906102e881846001600160a01b0389166109f3565b8a516001600160a01b0387168152602081019190915233905f516020610c805f395f51905f5290604090a488806101f7565b60019061033181846001600160a01b038a166109f3565b8c516001600160a01b0388168152602081019190915233905f516020610c805f395f51905f5290604090a4818b6101ef565b61037781846001600160a01b038b166109f3565b8c516001600160a01b0389168152602081019190915233905f516020610c805f395f51905f5290604090a48a80806101d5565b5f516020610c805f395f51905f52906103f4906103d181876001600160a01b0387166109f3565b604080516001600160a01b03909516855260208501919091523393918291820190565b0390a48282885f6101cb565b9a829b60409b979b969394929596519061041982610954565b6001600160a01b0390811682528a81166020808401918252918d166040808501918252606085019889525f608086015251909891926104589082610984565b5f815260a0840152875182516001600160a01b039081169116146106f2576001600160a01b038116610683575b508151955196519051889788976001600160a01b03938416928416929092119288921690806105a3575b5050505060800151841061055e57838f88936104ce8f80938e99610ba2565b6104d7916109c5565b9c6104e3828785610ba2565b6104ec916109c5565b986104f692610ba2565b6104ff916109c5565b9a8085145f149e60409f6105225750505050905081809281985b9192819d6101ab565b8183610552610546846105406105589897610540978d9e9c9d610ba2565b906109e6565b9661054084828d610ba2565b98610ba2565b98610519565b60405162461bcd60e51b815260206004820152601a60248201527f496e73756666696369656e74206f757470757420616d6f756e740000000000006044820152606490fd5b906040949950809293985060018060a01b03198454161783558260c485516105cc602082610984565b5f8152865193630251596160e31b85523060048601528b602486015260448501528a73fffd8963efd1fc6a506488495d951d53639afb810273fffd8963efd1fc6a506488495d951d5263988d2518606485015260a0608485015280519060208201908160a487019160045afa5001925af160403d14161561067a5760808651602051865f14610672578089035b961561066b57505b9590875f806104af565b9050610661565b818903610659565b853d81803e3d90fd5b82516001600160a01b039081169082163b156106ee5760405163c94a521d60e01b81526004810191909152905f90829060249082906001600160a01b03165afa80156106e35715610485576106db9198505f90610984565b5f965f610485565b6040513d5f823e3d90fd5b5f80fd5b60405162461bcd60e51b815260206004820152601a60248201527f746f6b656e20697320616c7265616479207072696e636970616c0000000000006044820152606490fd5b929d999a999298509394936101a461018f565b9d5093509750985061075e84606435610a49565b9b929b99919490949d8c80610774575b5061017a565b6107899030336001600160a01b038516610b0e565b8f61076e565b9c5094509850506107a284602435610a49565b9c929c9a91959095928d806107b8575b50610172565b6107cd9030336001600160a01b038e16610b0e565b8f6107b2565b346106ee5760603660031901126106ee5760243560043560443567ffffffffffffffff81116106ee57366023820112156106ee5780600401359067ffffffffffffffff82116106ee5736602483830101116106ee5750505f546001600160a01b03163381900361091e57604051630dfe168160e01b815292602084600481855afa9182156106e3576004945f936108fc575b506020906040519586809263d21220a760e01b82525afa9384156106e3575f946108cb575b505f8313156108ab57506108a9925033906001600160a01b03166109f3565b005b9150505f81136108b757005b6108a99133906001600160a01b03166109f3565b6108ee91945060203d6020116108f5575b6108e68183610984565b8101906109a6565b925f61088a565b503d6108dc565b602091935061091790823d84116108f5576108e68183610984565b9290610865565b60405162461bcd60e51b815260206004820152600e60248201526d125b98dbdc9c9958dd081c1bdbdb60921b6044820152606490fd5b60c0810190811067ffffffffffffffff82111761097057604052565b634e487b7160e01b5f52604160045260245ffd5b90601f8019910116810190811067ffffffffffffffff82111761097057604052565b908160209103126106ee57516001600160a01b03811681036106ee5790565b919082018092116109d257565b634e487b7160e01b5f52601160045260245ffd5b919082039182116109d257565b60405163a9059cbb60e01b60208201526001600160a01b03929092166024830152604480830193909352918152610a3491610a2f606483610984565b610c27565b565b818102929181159184041417156109d257565b9190915f925f925f925f9261ffff60408201511680610ae7575b5061ffff81511680610aaa575b506080015167ffffffffffffffff169081610a89575050565b610a94929350610b52565b9081610a9c57565b9381610aa7916109c5565b93565b612710919550610aba9083610a36565b049384610ac8575b5f610a70565b956080610ade8667ffffffffffffffff936109c5565b97915050610ac2565b612710919650610af79083610a36565b049485610b05575b5f610a63565b95508495610aff565b6040516323b872dd60e01b60208201526001600160a01b039283166024820152929091166044830152606480830193909352918152610a3491610a2f608483610984565b5f91905f198282099180820293848085109403938085039414610b9857600160401b841015610b955750600160401b910990828211900360c01b910360401c1790565b80fd5b5050505060401c90565b915f198284099282810292838086109503948086039514610c1957848311156106ee5782910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b5050809250156106ee570490565b905f602091828151910182855af1156106e3575f513d610c7657506001600160a01b0381163b155b610c565750565b635274afe760e01b5f9081526001600160a01b0391909116600452602490fd5b60011415610c4f56fe11d90d99368a301484d9d42a2dd11deb18f3cd27ec3d02dd7d52f3a58a2797fca164736f6c634300081c000a

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  ]

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.