Skip to content
Verified contractPartialGPL-2.0-or-later

NonfungibleTokenPositionDescriptor

Address0xf17cd3e4fe528a8280e73acdcb03cc56024123e7
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.7.6

 

Same code

Only this contract

 

Details

Compiler
solc 0.7.6+commit.7338295f
Language
solidity
Optimization
Yes, 200 runs
EVM version
istanbul
License
GPL-2.0-or-later
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,238,252
Creation transaction
0xccfd8c666b…7d29dca1d4
Libraries
contracts/periphery/NonfungibleTokenPositionDescriptor.sol:NFTSVG0x933f…33931econtracts/periphery/NonfungibleTokenPositionDescriptor.sol:NFTDescriptor0xea1e…3159fb

41 files

contracts/periphery/NonfungibleTokenPositionDescriptor.sol

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

import '@uniswap/lib/contracts/libraries/SafeERC20Namer.sol';
import 'base64-sol/base64.sol';
import 'contracts/core/interfaces/ICLPool.sol';

import './interfaces/IERC20Metadata.sol';
import './interfaces/INonfungiblePositionManager.sol';
import './interfaces/INonfungibleTokenPositionDescriptor.sol';
import './libraries/ChainId.sol';
import './libraries/NFTDescriptor.sol';
import './libraries/NFTSVG.sol';
import './libraries/PoolAddress.sol';
import './libraries/TokenRatioSortOrder.sol';

/// @title Describes NFT token positions
/// @notice Produces a string containing the data URI for a JSON metadata string
contract NonfungibleTokenPositionDescriptor is INonfungibleTokenPositionDescriptor {
  address private constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
  address private constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
  address private constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
  address private constant TBTC = 0x8dAEBADE922dF735c38C80C7eBD708Af50815fAa;
  address private constant WBTC = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;

  address public immutable WETH9;
  /// @dev A null-terminated string
  bytes32 public immutable nativeCurrencyLabelBytes;

  constructor(address _WETH9, bytes32 _nativeCurrencyLabelBytes) {
    WETH9 = _WETH9;
    nativeCurrencyLabelBytes = _nativeCurrencyLabelBytes;
  }

  /// @notice Returns the native currency label as a string
  function nativeCurrencyLabel() public view returns (string memory) {
    uint256 len = 0;
    while (len < 32 && nativeCurrencyLabelBytes[len] != 0) {
      len++;
    }
    bytes memory b = new bytes(len);
    for (uint256 i = 0; i < len; i++) {
      b[i] = nativeCurrencyLabelBytes[i];
    }
    return string(b);
  }

  /// @inheritdoc INonfungibleTokenPositionDescriptor
  function tokenURI(
    INonfungiblePositionManager positionManager,
    uint256 tokenId
  ) external view override returns (string memory) {
    (,, address token0, address token1, int24 tickSpacing, int24 tickLower, int24 tickUpper,,,,,) =
      positionManager.positions(tokenId);

    ICLPool pool = ICLPool(
      PoolAddress.computeAddress(
        positionManager.factory(), PoolAddress.PoolKey({token0: token0, token1: token1, tickSpacing: tickSpacing})
      )
    );

    bool _flipRatio = flipRatio(token0, token1, ChainId.get());
    address quoteTokenAddress = !_flipRatio ? token1 : token0;
    address baseTokenAddress = !_flipRatio ? token0 : token1;
    NFTDescriptor.ConstructTokenURIParams memory params = NFTDescriptor.ConstructTokenURIParams({
      tokenId: tokenId,
      quoteTokenAddress: quoteTokenAddress,
      baseTokenAddress: baseTokenAddress,
      quoteTokenSymbol: quoteTokenAddress == WETH9
        ? nativeCurrencyLabel()
        : SafeERC20Namer.tokenSymbol(quoteTokenAddress),
      baseTokenSymbol: baseTokenAddress == WETH9 ? nativeCurrencyLabel() : SafeERC20Namer.tokenSymbol(baseTokenAddress),
      quoteTokenDecimals: IERC20Metadata(quoteTokenAddress).decimals(),
      baseTokenDecimals: IERC20Metadata(baseTokenAddress).decimals(),
      flipRatio: _flipRatio,
      tickLower: tickLower,
      tickUpper: tickUpper,
      tickSpacing: tickSpacing,
      poolAddress: address(pool)
    });

    string memory image = Base64.encode(bytes(generateSVG(params)));

    string memory nameAndDescription = NFTDescriptor.constructTokenURI(params);

    return string(
      abi.encodePacked(
        'data:application/json;base64,',
        Base64.encode(
          bytes(abi.encodePacked('{', nameAndDescription, ', "image": "', 'data:image/svg+xml;base64,', image, '"}'))
        )
      )
    );
  }

  function generateSVG(NFTDescriptor.ConstructTokenURIParams memory params) internal pure returns (string memory) {
    (string memory priceLower, string memory priceUpper) = NFTDescriptor.generatePriceRange(params);
    return NFTSVG.generateSVG(
      NFTSVG.SVGParams({
        quoteTokenSymbol: params.quoteTokenSymbol,
        baseTokenSymbol: params.baseTokenSymbol,
        quoteTokenAddress: params.quoteTokenAddress,
        baseTokenAddress: params.baseTokenAddress,
        tokenId: params.tokenId,
        priceLower: priceLower,
        priceUpper: priceUpper,
        tickSpacing: params.tickSpacing,
        chainId: ChainId.get()
      })
    );
  }

  function flipRatio(address token0, address token1, uint256 chainId) public view returns (bool) {
    return tokenRatioPriority(token0, chainId) > tokenRatioPriority(token1, chainId);
  }

  function tokenRatioPriority(address token, uint256 chainId) public view returns (int256) {
    if (token == WETH9) {
      return TokenRatioSortOrder.DENOMINATOR;
    }
    if (chainId == 1) {
      if (token == USDC) {
        return TokenRatioSortOrder.NUMERATOR_MOST;
      } else if (token == USDT) {
        return TokenRatioSortOrder.NUMERATOR_MORE;
      } else if (token == DAI) {
        return TokenRatioSortOrder.NUMERATOR;
      } else if (token == TBTC) {
        return TokenRatioSortOrder.DENOMINATOR_MORE;
      } else if (token == WBTC) {
        return TokenRatioSortOrder.DENOMINATOR_MOST;
      } else {
        return 0;
      }
    }
    return 0;
  }
}

contracts/core/interfaces/ICLFactory.sol

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

import {IFactoryRegistry} from 'contracts/core/interfaces/IFactoryRegistry.sol';
import {ILeafVoter} from 'contracts/gauge/interfaces/ILeafVoter.sol';

/// @title The interface for the CL Factory
/// @notice The CL Factory facilitates creation of CL pools and control over the protocol fees
interface ICLFactory {
  /// @notice An initial tick spacing and its default swap fee, in millionths.
  /// @param tickSpacing Minimum distance between initialized ticks.
  /// @param fee Default swap fee, in millionths.
  struct FeeTier {
    int24 tickSpacing;
    uint24 fee;
  }

  /// @notice Dependencies, initial managers and fee tiers of a newly deployed factory.
  /// @param owner Initial factory owner.
  /// @param swapFeeManager Initial swap fee manager.
  /// @param unstakedFeeManager Initial unstaked fee manager.
  /// @param voter Leaf voter, or zero until configured.
  /// @param poolImplementation Implementation cloned for new pools.
  /// @param positionManager Canonical position manager.
  /// @param factoryRegistry Registry that approves the factory and records its pools.
  /// @param defaultSwapHook Initial swap hook, or zero until configured.
  /// @param discountRegistryManager Initial discount registry manager.
  /// @param clPoolTapeManager Initial pool tape manager.
  /// @param initialFeeTiers Tick spacings and fees enabled during construction.
  struct ConstructorParams {
    address owner;
    address swapFeeManager;
    address unstakedFeeManager;
    address voter;
    address poolImplementation;
    address positionManager;
    address factoryRegistry;
    address defaultSwapHook;
    address discountRegistryManager;
    address clPoolTapeManager;
    FeeTier[] initialFeeTiers;
  }

  /// @notice Emitted when the owner of the factory is changed
  /// @param oldOwner The owner before the owner was changed
  /// @param newOwner The owner after the owner was changed
  event OwnerChanged(address indexed oldOwner, address indexed newOwner);

  /// @notice Emitted when the swapFeeManager of the factory is changed
  /// @param oldFeeManager The swapFeeManager before the swapFeeManager was changed
  /// @param newFeeManager The swapFeeManager after the swapFeeManager was changed
  event SwapFeeManagerChanged(address indexed oldFeeManager, address indexed newFeeManager);

  /// @notice Emitted when the unstakedFeeManager of the factory is changed
  /// @param oldFeeManager The unstakedFeeManager before the unstakedFeeManager was changed
  /// @param newFeeManager The unstakedFeeManager after the unstakedFeeManager was changed
  event UnstakedFeeManagerChanged(address indexed oldFeeManager, address indexed newFeeManager);

  /// @notice Emitted when the default swap hook of the factory is changed
  /// @param swapHook The default swap hook after it was changed
  event DefaultSwapHookChanged(address indexed swapHook);

  /// @notice Emitted when the swap hook of a specific pool is changed
  /// @param pool The pool whose swap hook was changed
  /// @param swapHook The pool swap hook after it was changed
  event PoolSwapHookChanged(address indexed pool, address indexed swapHook);

  /// @notice Emitted when the unstakedFeeModule of the factory is changed
  /// @param oldFeeModule The unstakedFeeModule before the unstakedFeeModule was changed
  /// @param newFeeModule The unstakedFeeModule after the unstakedFeeModule was changed
  event UnstakedFeeModuleChanged(address indexed oldFeeModule, address indexed newFeeModule);

  /// @notice Emitted when the defaultUnstakedFee of the factory is changed
  /// @param oldUnstakedFee The defaultUnstakedFee before the defaultUnstakedFee was changed
  /// @param newUnstakedFee The defaultUnstakedFee after the unstakedFeeModule was changed
  event DefaultUnstakedFeeChanged(uint24 indexed oldUnstakedFee, uint24 indexed newUnstakedFee);

  /// @notice Emitted when the discountRegistryManager of the factory is changed
  /// @param discountRegistryManager The discountRegistryManager after the discountRegistryManager was changed
  event DiscountRegistryManagerChanged(address indexed discountRegistryManager);

  /// @notice Emitted when the discountRegistry of the factory is changed
  /// @param discountRegistry The discountRegistry after the discountRegistry was changed
  event DiscountRegistryChanged(address indexed discountRegistry);

  /// @notice Emitted when the clPoolTape module of the factory is set or cleared
  /// @param clPoolTape The clPoolTape address after the change. The zero address disables tape registration
  event ClPoolTapeChanged(address indexed clPoolTape);

  /// @notice Emitted when the clPoolTapeManager of the factory is changed
  /// @param clPoolTapeManager The clPoolTapeManager after the change
  event ClPoolTapeManagerChanged(address indexed clPoolTapeManager);

  /// @notice Emitted when the voter of the factory is set
  /// @param voter The voter after it was set
  event VoterSet(address indexed voter);

  /// @notice Emitted when a pool is created
  /// @param token0 The first token of the pool by address sort order
  /// @param token1 The second token of the pool by address sort order
  /// @param tickSpacing The minimum number of ticks between initialized ticks
  /// @param pool The address of the created pool
  event PoolCreated(address indexed token0, address indexed token1, int24 indexed tickSpacing, address pool);

  /// @notice Emitted when a new tick spacing is enabled for pool creation via the factory
  /// @param tickSpacing The minimum number of ticks between initialized ticks for pools
  /// @param fee The default fee for a pool created with a given tickSpacing
  event TickSpacingEnabled(int24 indexed tickSpacing, uint24 indexed fee);

  /// @notice The LeafVoter contract, used to check gauge activation for unstaked fees
  /// @dev May be the zero address until set via setVoter, as the voter can be deployed
  ///      after the factory. Unstaked fees are zero until it is set
  /// @return The address of the LeafVoter contract
  function voter() external view returns (ILeafVoter);

  /// @notice The address of the pool implementation contract used to deploy proxies / clones
  /// @return The address of the pool implementation contract
  function poolImplementation() external view returns (address);

  /// @notice The canonical position manager for pools created by this factory
  /// @return The address of the nonfungible position manager
  function positionManager() external view returns (address);

  /// @notice Factory registry that records pools as gauge targets
  /// @dev Set at construction. Every created pool is registered as a target;
  ///      pool creation reverts until this factory is an approved target factory
  ///      in the registry
  /// @return The address of the factory registry
  function factoryRegistry() external view returns (IFactoryRegistry);

  /// @notice Returns the current owner of the factory
  /// @dev Can be changed by the current owner via setOwner
  /// @return The address of the factory owner
  function owner() external view returns (address);

  /// @notice Returns the current swapFeeManager of the factory
  /// @dev Can be changed by the current swap fee manager via setSwapFeeManager
  /// @return The address of the factory swapFeeManager
  function swapFeeManager() external view returns (address);

  /// @notice Returns the current unstakedFeeManager of the factory
  /// @dev Can be changed by the current unstaked fee manager via setUnstakedFeeManager
  /// @return The address of the factory unstakedFeeManager
  function unstakedFeeManager() external view returns (address);

  /// @notice Returns the factory-wide default swap hook used when a pool has no hook set
  /// @dev Can be changed by the current swap fee manager via setDefaultSwapHook
  /// @return The address of the factory defaultSwapHook
  function defaultSwapHook() external view returns (address);

  /// @notice Returns the swap hook override set for a specific pool.
  /// @param pool The pool to query
  /// @return The pool swap hook override, or address(0) if unset
  function poolSwapHook(address pool) external view returns (address);

  /// @notice Resolves the swap hook address for a pool. If the pool doesn't have a swap hook specified,
  ///         then the default hook address is returned.
  /// @param pool The pool to resolve the swap hook for
  /// @return The swap hook address for the pool
  function getPoolSwapHook(address pool) external view returns (address);

  /// @notice Returns the current unstakedFeeModule of the factory
  /// @dev Can be changed by the current unstaked fee manager via setUnstakedFeeModule
  /// @return The address of the factory unstakedFeeModule
  function unstakedFeeModule() external view returns (address);

  /// @notice Returns the current defaultUnstakedFee of the factory
  /// @dev Can be changed by the current unstaked fee manager via setDefaultUnstakedFee
  /// @return The default Unstaked Fee of the factory
  function defaultUnstakedFee() external view returns (uint24);

  /// @notice The current manager of {discountRegistry} of the factory
  /// @return The address of the discount registry manager
  function discountRegistryManager() external view returns (address);

  /// @notice Discount registry for swap fee discounts
  /// @return The address of the discount registry
  function discountRegistry() external view returns (address);

  /// @notice The clPoolTape module new pools are registered with. The zero address means registration is disabled
  /// @return The address of the clPoolTape module
  function clPoolTape() external view returns (address);

  /// @notice The current clPoolTapeManager of the factory
  /// @dev Can be changed by the current clPoolTapeManager via setClPoolTapeManager
  /// @return The address of the clPoolTapeManager
  function clPoolTapeManager() external view returns (address);

  /// @notice Returns a default fee for a tick spacing.
  /// @dev Use getFee for the most up to date fee for a given pool.
  /// A tick spacing can never be removed, so this value should be hard coded or cached in the calling context
  /// @param tickSpacing The enabled tick spacing. Returns 0 if not enabled
  /// @return fee The default fee for the given tick spacing
  function tickSpacingToFee(int24 tickSpacing) external view returns (uint24 fee);

  /// @notice Returns a list of enabled tick spacings. Used to iterate through pools created by the factory
  /// @dev Tick spacings cannot be removed. Tick spacings are not ordered
  /// @return List of enabled tick spacings
  function tickSpacings() external view returns (int24[] memory);

  /// @notice Returns the pool address for a given pair of tokens and a tick spacing, or address 0 if it does not exist
  /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
  /// @param tokenA The contract address of either token0 or token1
  /// @param tokenB The contract address of the other token
  /// @param tickSpacing The tick spacing of the pool in uint24
  /// @return pool The pool address
  function getPool(address tokenA, address tokenB, uint24 tickSpacing) external view returns (address pool);

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

  /// @notice Return address of pool created by this factory given its `index`
  /// @param index Index of the pool
  /// @return The pool address in the given index
  function allPools(uint256 index) external view returns (address);

  /// @notice Returns the number of pools created from this factory
  /// @return Number of pools created from this factory
  function allPoolsLength() external view returns (uint256);

  /// @notice Used in VotingEscrow to determine if a contract is a valid pool of the factory
  /// @param pool The address of the pool to check
  /// @return Whether the pool is a valid pool of the factory
  function isPool(address pool) external view returns (bool);

  /// @notice Get unstaked fee for a given pool. Accounts for default and dynamic fees
  /// @dev Unstaked fee is denominated in pips. i.e. 1e-6
  /// @param pool The pool to get the unstaked fee for
  /// @return The unstaked fee for the given pool
  function getUnstakedFee(address pool) external view returns (uint24);

  /// @notice Creates a pool for the given two tokens and tick spacing
  /// @param tokenA One of the two tokens in the desired pool
  /// @param tokenB The other of the two tokens in the desired pool
  /// @param tickSpacing The desired tick spacing for the pool
  /// @dev Use encodeSqrtPrice(1,1) as price
  /// @dev Used to programmatically create pools in case one does not exist
  /// @dev Invalid tickSpacing will revert the transaction
  /// @return pool The address of the newly created pool
  function createPool(address tokenA, address tokenB, uint24 tickSpacing) external returns (address pool);

  /// @notice Creates a pool for the given two tokens and tick spacing
  /// @param tokenA One of the two tokens in the desired pool
  /// @param tokenB The other of the two tokens in the desired pool
  /// @param tickSpacing The desired tick spacing for the pool
  /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
  /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. The call will
  /// revert if the pool already exists, the tick spacing is invalid, or the token arguments are invalid
  /// @return pool The address of the newly created pool
  function createPool(
    address tokenA,
    address tokenB,
    int24 tickSpacing,
    uint160 sqrtPriceX96
  ) external returns (address pool);

  /// @notice Updates the owner of the factory
  /// @dev Must be called by the current owner
  /// @param _owner The new owner of the factory
  function setOwner(address _owner) external;

  /// @notice Sets the voter of the factory
  /// @dev Must be called by the current owner. Callable only while the voter is unset,
  ///      so once set the voter is immutable. Used when the factory is deployed before the voter
  /// @param _voter The voter of the factory
  function setVoter(address _voter) external;

  /// @notice Updates the swapFeeManager of the factory
  /// @dev Must be called by the current swap fee manager
  /// @param _swapFeeManager The new swapFeeManager of the factory
  function setSwapFeeManager(address _swapFeeManager) external;

  /// @notice Updates the unstakedFeeManager of the factory
  /// @dev Must be called by the current unstaked fee manager
  /// @param _unstakedFeeManager The new unstakedFeeManager of the factory
  function setUnstakedFeeManager(address _unstakedFeeManager) external;

  /// @notice Updates the discountRegistryManager of the factory
  /// @dev Must be called by the current discount registry manager
  /// @param _discountRegistryManager The new discountRegistryManager of the factory
  function setDiscountRegistryManager(address _discountRegistryManager) external;

  /// @notice Updates the unstakedFeeModule of the factory
  /// @dev Must be called by the current unstaked fee manager
  /// @param _unstakedFeeModule The new unstakedFeeModule of the factory
  function setUnstakedFeeModule(address _unstakedFeeModule) external;

  /// @notice Updates the defaultUnstakedFee of the factory
  /// @dev Must be called by the current unstaked fee manager
  /// @param _defaultUnstakedFee The new defaultUnstakedFee of the factory
  function setDefaultUnstakedFee(uint24 _defaultUnstakedFee) external;

  /// @notice Updates the factory-wide default swap hook
  /// @dev Must be called by the current swap fee manager
  /// @param _swapHook The new default swap hook of the factory
  function setDefaultSwapHook(address _swapHook) external;

  /// @notice Sets the swap hook override for a batch of pools
  /// @dev Must be called by the current swap fee manager. Reverts with 'LMM' if the array lengths differ.
  ///      For each pool, passing address(0) clears its override back to the default.
  /// @param _pools The pools to set swap hooks for
  /// @param _swapHooks The new swapHook for each corresponding pool
  function setPoolSwapHook(address[] calldata _pools, address[] calldata _swapHooks) external;

  /// @notice Updates the discountRegistry of the factory
  /// @dev Must be called by the current discount registry manager
  /// @param _discountRegistry The new discountRegistry of the factory
  function setDiscountRegistry(address _discountRegistry) external;

  /// @notice Updates the clPoolTapeManager of the factory
  /// @dev Must be called by the current clPoolTapeManager
  /// @param _clPoolTapeManager The new clPoolTapeManager of the factory
  function setClPoolTapeManager(address _clPoolTapeManager) external;

  /// @notice Sets or clears the clPoolTape module new pools are registered with
  /// @dev Must be called by the clPoolTapeManager. The zero address disables tape registration
  /// @param _clPoolTape The new clPoolTape module address
  function setClPoolTape(address _clPoolTape) external;

  /// @notice Enables a certain tickSpacing
  /// @dev Tick spacings may never be removed once enabled
  /// @param tickSpacing The spacing between ticks to be enforced in the pool
  /// @param fee The default fee associated with a given tick spacing
  function enableTickSpacing(int24 tickSpacing, uint24 fee) external;
}

contracts/core/interfaces/ICLPool.sol

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

import './pool/ICLPoolActions.sol';
import './pool/ICLPoolConstants.sol';
import './pool/ICLPoolDerivedState.sol';
import './pool/ICLPoolEvents.sol';
import './pool/ICLPoolOwnerActions.sol';
import './pool/ICLPoolState.sol';

/// @title The interface for a CL Pool
/// @notice A CL pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface ICLPool is
  ICLPoolConstants,
  ICLPoolState,
  ICLPoolDerivedState,
  ICLPoolActions,
  ICLPoolEvents,
  ICLPoolOwnerActions
{}

contracts/core/interfaces/IFactoryRegistry.sol

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

/**
 * @title IFactoryRegistry
 * @notice Surface of the metadex `FactoryRegistry` the CL stack calls.
 * @dev A pool is a "target" and a pool factory a "target factory". The periphery keeps its own read-only mirror in
 *      `contracts/periphery/interfaces/IV3FactoryRegistry.sol` for the quoters.
 */
interface IFactoryRegistry {
  /**
   * @notice Registers a gauge factory and the target factory it serves as a pair, writing their permanent link.
   * @param gaugeFactory The gauge factory to register.
   * @param targetFactory The target (pool) factory the gauge factory serves.
   */
  function registerFactories(address gaugeFactory, address targetFactory) external;

  /**
   * @notice Records a freshly deployed target. Called by the target factory inside its own creation function.
   * @param target The deployed target (pool).
   */
  function registerTarget(address target) external;

  /**
   * @notice True when a target (pool) factory is in the approval set.
   * @param targetFactory The target factory to check.
   * @return Whether the factory is approved.
   */
  function isTargetFactoryApproved(address targetFactory) external view returns (bool);

  /**
   * @notice The gauge factory serving a target factory.
   * @param targetFactory The target factory to resolve.
   * @return The linked gauge factory, zero for an unlinked factory.
   */
  function targetFactoryToGaugeFactory(address targetFactory) external view returns (address);

  /**
   * @notice The gauge over a target (pool).
   * @param target The target to resolve.
   * @return The gauge for `target`, zero when none is recorded.
   */
  function targetToGauge(address target) external view returns (address);

  /**
   * @notice Effective emission cap for a gauge, resolved through the factory that deployed it.
   * @dev Returns zero when the gauge is unknown or the factory call reverts.
   * @param gauge The gauge to resolve.
   * @return The effective cap in tokens per second.
   */
  function emissionCap(address gauge) external view returns (uint128);
}

contracts/core/interfaces/hook/ISwapHook.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma abicoder v2;

/// @notice Interface for CLPool swap hooks that can override pre-swap fees and/or apply post-swap fees.
interface ISwapHook {
  /*////////////////////////////////////////////////////////////
                              STRUCTS
  ////////////////////////////////////////////////////////////*/

  /// @notice Swap context passed to hook entry points.
  /// @param caller `msg.sender` address that initiated the swap.
  /// @param recipient Recipient of the swap output.
  /// @param zeroForOne True for token0 -> token1 swaps, false otherwise.
  /// @param amountSpecified The exact amount specified by the swapper (either input or output).
  /// @param sqrtPriceLimitX96 Swap price limit.
  /// @param data Optional calldata supplied to the swap call.
  /// @param sqrtPriceX96 Square root price of the pool:
  ///        In {beforeSwap} represents a PRE-SWAP sqrt price.
  ///        In {afterSwap} represents a POST-SWAP sqrt price.
  /// @param tick Tick of the pool:
  ///        In {beforeSwap} represents a PRE-SWAP tick.
  ///        In {afterSwap} represents a POST-SWAP tick.
  struct SwapParams {
    address caller;
    address recipient;
    bool zeroForOne;
    int256 amountSpecified;
    uint160 sqrtPriceLimitX96;
    bytes data;
    uint160 sqrtPriceX96;
    int24 tick;
  }

  /// @notice Post-swap state passed to the {afterSwap} entry-point.
  /// @param amountSpecifiedRemaining Remaining specified amount after the swap loop conclusion.
  /// @param amountCalculated Amount computed by the swap loop before any post-swap fee adjustment.
  /// @param fee The fee applied during the swap loop.
  /// @param hasUpdatedFees Whether swap fees were updated during execution.
  /// @param feeGrowthGlobalX128 The global fee growth of the input token after the swap loop.
  /// @param gaugeFee Fee amount paid to staked liquidity.
  /// @param liquidity In-range liquidity at the end of the swap loop.
  /// @param stakedLiquidity In-range staked liquidity at the end of the swap loop.
  /// @param tickCumulative The post-swap value of the tick accumulator, computed only if an initialized tick is crossed.
  /// @param secondsPerLiquidityCumulativeX128 The post-swap value of the seconds per liquidity
  ///        accumulator, computed only if an initialized tick is crossed.
  /// @param computedLatestObservation Whether the latest observation was computed during the swap.
  struct AfterSwapParams {
    int256 amountSpecifiedRemaining;
    int256 amountCalculated;
    uint24 fee;
    bool hasUpdatedFees;
    uint256 feeGrowthGlobalX128;
    uint128 gaugeFee;
    uint128 liquidity;
    uint128 stakedLiquidity;
    int56 tickCumulative;
    uint160 secondsPerLiquidityCumulativeX128;
    bool computedLatestObservation;
  }

  /// @notice Call context of `flash` function.
  /// @param caller `msg.sender` address that initiated flash execution.
  /// @param recipient Recipient of the flash loaned tokens.
  /// @param amount0 Amount of token0 to flash loan.
  /// @param amount1 Amount of token1 to flash loan.
  /// @param data Optional calldata supplied to the flash call.
  struct FlashParams {
    address caller;
    address recipient;
    uint256 amount0;
    uint256 amount1;
    bytes data;
  }

  /*////////////////////////////////////////////////////////////
                              VIEW FUNCTIONS
  ////////////////////////////////////////////////////////////*/

  /// @notice Queries the swap fee that the hook would charge in the swap loop.
  /// @param _pool Address of the pool making the query.
  /// @param _swapParams Swap context and pre-swap pool state.
  /// @return _fee The fee that would be applied in the swap loop, in pips.
  function getBeforeSwapFee(address _pool, SwapParams memory _swapParams) external view returns (uint24 _fee);

  /// @notice Queries the swap fee that the hook would charge after the swap loop.
  /// @param _pool Address of the pool making the query.
  /// @param _swapParams Swap context and post-swap pool state.
  /// @param _afterSwapParams Post-swap execution state and oracle/liquidity context.
  /// @return _fee The fee that would be applied after the swap loop, in pips.
  function getAfterSwapFee(
    address _pool,
    SwapParams memory _swapParams,
    AfterSwapParams memory _afterSwapParams
  ) external view returns (uint24 _fee);

  /// @notice Queries the flash loan fee that the hook would charge for a given flash context.
  /// @param _pool Address of the pool making the query.
  /// @param _flashParams Arguments passed to the flash function.
  /// @return _fee The fee that would be applied to flash loaned amounts, in pips.
  function getFlashFee(address _pool, FlashParams memory _flashParams) external view returns (uint24 _fee);

  /*////////////////////////////////////////////////////////////
                              WRITE FUNCTIONS
  ////////////////////////////////////////////////////////////*/

  /// @notice Returns the fee to apply inside the swap loop.
  /// @param _swapParams Swap context and PRE-SWAP pool state.
  /// @return _fee The fee to apply throughout the swap loop.
  function beforeSwap(SwapParams memory _swapParams) external returns (uint24 _fee);

  /// @notice Returns the pips fee to apply after the swap loop conclusion.
  /// @dev The fee is redirected exclusively to the Gauge.
  /// @param _swapParams Swap context and POST-SWAP pool state.
  /// @param _afterSwapParams POST-SWAP execution state and oracle/liquidity context.
  /// @return _fee A post-swap fee to apply to the non-exact input/output part
  ///         of the swap that's credited to the gauge.
  function afterSwap(
    SwapParams memory _swapParams,
    AfterSwapParams memory _afterSwapParams
  ) external returns (uint24 _fee);

  /// @notice Returns the fee to apply to `amount0/1` in `flash` function.
  /// @param _flashParams Arguments passed to the `flash` function.
  /// @return _fee Fee to apply to flash loaned amounts.
  function beforeFlash(FlashParams memory _flashParams) external returns (uint24 _fee);
}

contracts/core/interfaces/pool/ICLPoolActions.sol

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

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface ICLPoolActions {
  /// @notice Initialize function used in proxy deployment
  /// @dev Can be called once only
  /// Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
  /// @dev not locked because it initializes unlocked
  /// @param _factory The CL factory contract address
  /// @param _token0 The first token of the pool by address sort order
  /// @param _token1 The second token of the pool by address sort order
  /// @param _tickSpacing The pool tick spacing
  /// @param _factoryRegistry The address of the factory registry managing the pool factory
  /// @param _sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
  function initialize(
    address _factory,
    address _token0,
    address _token1,
    int24 _tickSpacing,
    address _factoryRegistry,
    uint160 _sqrtPriceX96
  ) external;

  /// @notice Initialize gauge and nft manager
  /// @dev Callable only once, by the gauge factory
  /// @param _gauge The gauge corresponding to this pool
  /// @param _nft The position manager used for position management
  function setGaugeAndPositionManager(address _gauge, address _nft) external;

  /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
  /// @dev The caller of this method receives a callback in the form of ICLMintCallback#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 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
  /// @param owner Owner of the position in the pool (nft manager or gauge)
  /// @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,
    address owner
  ) 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 Burn liquidity from the supplied owner 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
  /// @param owner Owner of the position in the pool (nft manager or gauge)
  /// @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,
    address owner
  ) external returns (uint256 amount0, uint256 amount1);

  /// @notice Convert existing liquidity into staked liquidity
  /// @notice Only callable by the gauge associated with this pool
  /// @param stakedLiquidityDelta The amount by which to increase or decrease the staked liquidity
  /// @param tickLower The lower tick of the position for which to stake liquidity
  /// @param tickUpper The upper tick of the position for which to stake liquidity
  function stake(int128 stakedLiquidityDelta, int24 tickLower, int24 tickUpper) external;

  /// @notice Swap token0 for token1, or token1 for token0
  /// @dev The caller of this method receives a callback in the form of ICLSwapCallback#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 ICLFlashCallback#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;

  /// @notice Settles the pool's reward growth to the current block timestamp and returns the accrued rollover
  /// @dev Only callable by the gauge. Pulls the emissions accrued since the last settlement through the gauge.
  /// @return _rollover the emissions accumulated while no staked liquidity was in range. Reset to 0 after this call.
  function settleToBlock() external returns (uint256 _rollover);
}

contracts/core/interfaces/pool/ICLPoolConstants.sol

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

/// @title Pool state that never changes
/// @notice These parameters are not defined as immutable (due to proxy pattern) but are effectively immutable.
/// @notice i.e., the methods will always return the same values
interface ICLPoolConstants {
  /// @notice The contract that deployed the pool, which must adhere to the ICLFactory 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 gauge corresponding to this pool
  /// @return The gauge contract address
  function gauge() external view returns (address);

  /// @notice The nft manager
  /// @return The nft manager contract address
  function nft() external view returns (address);

  /// @notice The factory registry that manages pool <> gauge <> reward factory relationships
  /// @return The factory registry contract address
  function factoryRegistry() external view returns (address);

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

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

  /// @notice The ceiling applied to the before/after swap fee.
  /// @return The swap fee ceiling value in pips.
  function SWAP_FEE_CEIL() external view returns (uint256);

  /// @notice The denominator used for fees computation.
  /// @return The denominator value in pips.
  function DENOMINATOR() external view returns (uint256);

  /// @notice The pool type identifier
  /// @return The pool type label to be able to identify the type of pool
  function POOL_TYPE() external view returns (bytes32);
}

contracts/core/interfaces/pool/ICLPoolDerivedState.sol

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

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

  /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
  /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
  /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
  /// snapshot is taken and the second snapshot is taken.
  /// @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);

  /// @notice The seconds per staked liquidity cumulative projected to the current block timestamp
  /// @return The Q128.128 seconds per staked liquidity cumulative as of the current block
  function getSecondsPerStakedLiquidityCumulativeX128() external view returns (uint160);
}

contracts/core/interfaces/pool/ICLPoolEvents.sol

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

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

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

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

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

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

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

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

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

  /// @notice Emitted when the collected protocol fees are withdrawn by the gauge
  /// @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 CollectFees(address indexed recipient, uint128 amount0, uint128 amount1);
}

contracts/core/interfaces/pool/ICLPoolOwnerActions.sol

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

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface ICLPoolOwnerActions {
  /// @notice Collect the gauge fee accrued to the pool
  /// @param recipient The address that receives the claimed gauge fees
  /// @return amount0 The gauge fee collected in token0
  /// @return amount1 The gauge fee collected in token1
  function collectFees(address recipient) external returns (uint128 amount0, uint128 amount1);
}

contracts/core/interfaces/pool/ICLPoolState.sol

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

import {ISwapHook} from '../hook/ISwapHook.sol';

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

  /// @notice The pool's pre-swap swap fee in pips, i.e. 1e-6
  /// @param _swapParams Swap context and pre-swap pool state.
  /// @return The pre-swap fee.
  function beforeSwapFee(ISwapHook.SwapParams memory _swapParams) external view returns (uint24);

  /// @notice The pool's post-swap swap fee in pips, i.e. 1e-6
  /// @param _swapParams Swap context and post-swap pool state.
  /// @param _afterSwapParams Post-swap execution state and oracle/liquidity context.
  /// @return The post-swap fee.
  function afterSwapFee(
    ISwapHook.SwapParams memory _swapParams,
    ISwapHook.AfterSwapParams memory _afterSwapParams
  ) external view returns (uint24);

  /// @notice The pool's flash fee in pips, i.e. 1e-6
  /// @param _flashParams Arguments passed to the flash function.
  /// @return The flash fee.
  function flashFee(ISwapHook.FlashParams memory _flashParams) external view returns (uint24);

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

  /// @notice The pool's unstaked fee in pips, i.e. 1e-6
  /// @dev Can be modified in PoolFactory on a pool basis or upgraded to be dynamic.
  /// @return The unstaked fee
  function unstakedFee() external view returns (uint24);

  /// @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 reward growth as a Q128.128 rewards of emission collected per unit of liquidity for the entire life of the pool
  /// @dev This value can overflow the uint256
  function rewardGrowthGlobalX128() external view returns (uint256);

  /// @notice The cumulative seconds per unit of in-range staked liquidity as of lastUpdated
  /// @return The Q128.128 stored seconds per staked liquidity cumulative
  function secondsPerStakedLiquidityCumulativeX128() external view returns (uint160);

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

  /// @notice Last time the pool reward growth was advanced
  function lastUpdated() external view returns (uint48);

  /// @notice Emissions accrued while no staked liquidity was in range
  function rollover() external view returns (uint256);

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

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

  /// @notice Look up information about a specific tick in the pool
  /// @param tick The tick to look up
  /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
  /// tick upper,
  /// liquidityNet how much liquidity changes when the pool price crosses the tick,
  /// stakedLiquidityNet how much staked liquidity changes when the pool price crosses the tick,
  /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
  /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
  /// rewardGrowthOutsideX128 the reward growth on the other side of the tick from the current tick in emission token
  /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
  /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
  /// secondsOutside the seconds spent on the other side of the tick from the current tick,
  /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
  /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
  /// In addition, these values are only relative and must be used only in comparison to previous snapshots for
  /// a specific position.
  function ticks(int24 tick)
    external
    view
    returns (
      uint128 liquidityGross,
      int128 liquidityNet,
      int128 stakedLiquidityNet,
      uint256 feeGrowthOutside0X128,
      uint256 feeGrowthOutside1X128,
      uint256 rewardGrowthOutsideX128,
      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,
  /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
  /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
  /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
  /// Returns 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,
  /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
  /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
  /// Returns initialized whether the observation has been initialized and the values are safe to use
  function observations(uint256 index)
    external
    view
    returns (uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized);

  /// @notice Returns data about reward growth within a tick range.
  /// RewardGrowthGlobalX128 can be supplied as a parameter for claimable reward calculations.
  /// @dev Used in gauge reward/earned calculations
  /// @param tickLower The lower tick of the range
  /// @param tickUpper The upper tick of the range
  /// @param _rewardGrowthGlobalX128 a calculated rewardGrowthGlobalX128 or 0 (in case of 0 it means we use the rewardGrowthGlobalX128 from state)
  /// @return rewardGrowthInsideX128 The reward growth in the range
  function getRewardGrowthInside(
    int24 tickLower,
    int24 tickUpper,
    uint256 _rewardGrowthGlobalX128
  ) external view returns (uint256 rewardGrowthInsideX128);

  /// @notice Returns data about fee growth within a tick range.
  /// @param tickLower The lower tick of the range
  /// @param tickUpper The upper tick of the range
  /// @return feeGrowthInside0X128 The token0 fee growth in range.
  /// @return feeGrowthInside1X128 The token1 fee growth in range.
  function getFeeGrowthInside(
    int24 tickLower,
    int24 tickUpper
  ) external view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128);
}

contracts/core/libraries/BitMath.sol

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

/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
library BitMath {
  /// @notice Returns the index of the most significant bit of the number,
  ///     where the least significant bit is at index 0 and the most significant bit is at index 255
  /// @dev The function satisfies the property:
  ///     x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)
  /// @param x the value for which to compute the most significant bit, must be greater than 0
  /// @return r the index of the most significant bit
  function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
    require(x > 0);

    if (x >= 0x100000000000000000000000000000000) {
      x >>= 128;
      r += 128;
    }
    if (x >= 0x10000000000000000) {
      x >>= 64;
      r += 64;
    }
    if (x >= 0x100000000) {
      x >>= 32;
      r += 32;
    }
    if (x >= 0x10000) {
      x >>= 16;
      r += 16;
    }
    if (x >= 0x100) {
      x >>= 8;
      r += 8;
    }
    if (x >= 0x10) {
      x >>= 4;
      r += 4;
    }
    if (x >= 0x4) {
      x >>= 2;
      r += 2;
    }
    if (x >= 0x2) r += 1;
  }

  /// @notice Returns the index of the least significant bit of the number,
  ///     where the least significant bit is at index 0 and the most significant bit is at index 255
  /// @dev The function satisfies the property:
  ///     (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)
  /// @param x the value for which to compute the least significant bit, must be greater than 0
  /// @return r the index of the least significant bit
  function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
    require(x > 0);

    r = 255;
    if (x & type(uint128).max > 0) {
      r -= 128;
    } else {
      x >>= 128;
    }
    if (x & type(uint64).max > 0) {
      r -= 64;
    } else {
      x >>= 64;
    }
    if (x & type(uint32).max > 0) {
      r -= 32;
    } else {
      x >>= 32;
    }
    if (x & type(uint16).max > 0) {
      r -= 16;
    } else {
      x >>= 16;
    }
    if (x & type(uint8).max > 0) {
      r -= 8;
    } else {
      x >>= 8;
    }
    if (x & 0xf > 0) {
      r -= 4;
    } else {
      x >>= 4;
    }
    if (x & 0x3 > 0) {
      r -= 2;
    } else {
      x >>= 2;
    }
    if (x & 0x1 > 0) r -= 1;
  }
}

contracts/core/libraries/FullMath.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0 <0.8.0;

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

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

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

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

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

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

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

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

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

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

contracts/core/libraries/TickMath.sol

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

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

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

  /// @notice Calculates sqrt(1.0001^tick) * 2^96
  /// @dev Throws if |tick| > max tick
  /// @param tick The input tick for the above formula
  /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
  /// at the given tick
  function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
    uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
    require(absTick <= uint256(MAX_TICK), 'T');

    uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
    if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
    if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
    if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
    if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
    if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
    if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
    if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
    if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
    if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
    if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
    if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
    if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
    if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
    if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
    if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
    if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
    if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
    if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
    if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;

    if (tick > 0) ratio = type(uint256).max / ratio;

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

  /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
  /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
  /// ever return.
  /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
  /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
  function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
    // second inequality must be < because the price can never reach the price at the max tick
    require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
    uint256 ratio = uint256(sqrtPriceX96) << 32;

    uint256 r = ratio;
    uint256 msb = 0;

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

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

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

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

    int256 log_sqrt10001 = log_2 * 255_738_958_999_603_826_347_141; // 128.128 number

    int24 tickLow = int24((log_sqrt10001 - 3_402_992_956_809_132_418_596_140_100_660_247_210) >> 128);
    int24 tickHi = int24((log_sqrt10001 + 291_339_464_771_989_622_907_027_621_153_398_088_495) >> 128);

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

contracts/gauge/interfaces/IAccessControl.sol

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

interface IAccessControl {
  function hasRole(bytes32 _role, address _account) external view returns (bool);
  function getRoleAdmin(bytes32 _role) external view returns (bytes32);
  function getRoleMemberCount(bytes32 _role) external view returns (uint256);
  function getRoleMember(bytes32 _role, uint256 _index) external view returns (address);
  function grantRole(bytes32 _role, address _account) external;
  function revokeRole(bytes32 _role, address _account) external;
  function renounceRole(bytes32 _role, address _account) external;
}

contracts/gauge/interfaces/ILeafVoter.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma abicoder v2;

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

interface ILeafVoter is IAccessControl {
  /**
   * @notice Aggregated voting power of a gauge at a point in time.
   * @param bias Decaying voting power at `ts`.
   * @param slope Per-second decay of `bias`.
   * @param ts Timestamp the point was resolved at.
   * @param permanentStakeBalance Non-decaying voting power from permanent stakes.
   */
  struct Point {
    int128 bias;
    int128 slope;
    uint48 ts;
    uint128 permanentStakeBalance;
  }

  /**
   * @notice Permissionless settle entrypoint for a registered gauge.
   *         Settles the chain index to `block.timestamp`, settles `_gauge`, and
   *         returns the gauge's cumulative reward share. The return value is
   *         monotonically increasing; a call against an unregistered gauge
   *         returns 0 without settling, so the function never reverts for any
   *         input address.
   * @param _gauge The gauge to settle.
   * @return _cumulativeRewardShare The gauge's settled cumulative reward share.
   */
  function settleGauge(address _gauge) external returns (uint256 _cumulativeRewardShare);

  /**
   * @notice Read-only twin of `settleGauge`. Projects the gauge's cumulative
   *         reward share at the current timestamp without writing state.
   *         `projectedCumulativeRewardShare(_gauge)` equals the value a
   *         `settleGauge(_gauge)` in this block would return.
   * @param _gauge The gauge to project.
   * @return _cumulativeRewardShare The gauge's projected cumulative reward share.
   */
  function projectedCumulativeRewardShare(address _gauge) external view returns (uint256 _cumulativeRewardShare);

  /**
   * @notice Mints `ReceiptToken` to the registered `EmissionsHandler` and calls it back per recipient.
   * @dev Reverts with `GaugeNotRegistered` for an unregistered caller and `CeilingExceeded` when the claim exceeds the
   * gauge's claimable headroom, `ceiling - claimed - surplus`. The claim is added to the gauge's `claimed` before the
   * mint, so all state effects complete before the handler callback fires. Callbacks MUST NOT rely on further
   * `LeafVoter` state changes. Emits `EmissionsMinted`.
   * @param _recipients Recipients for the per-leg delivery (LP, referral).
   * @param _amounts Per-leg amounts of `ReceiptToken`.
   */
  function mintEmissions(address[] calldata _recipients, uint128[] calldata _amounts) external;

  /**
   * @notice Gauge-only entrypoint for forfeiting surplus emissions the gauge
   *         cannot distribute, covering the Idle Gauge and Early Exit cases.
   *         Clamps `_amount` to the gauge's claimable headroom
   *         (`ceiling - claimed - surplus`), flushes the clamped amount into
   *         the gauge's `surplus` and the chain-level `surplusAccrued`, and
   *         emits `EmissionsForfeited` with the accrued amount. Reverts with
   *         `GaugeNotRegistered` when the caller is not a registered gauge.
   * @param _amount The surplus the calling gauge is forfeiting.
   */
  function forfeitEmissions(uint128 _amount) external;

  /**
   * @notice Whether a gauge is activated for direct allocation routing.
   * @param _gauge Gauge address to query.
   * @return Whether the gauge is activated.
   */
  function isActivated(address _gauge) external view returns (bool);

  /**
   * @notice Canonical per-gauge settlement state.
   * @param _gauge Gauge address to query.
   * @return _ceiling Cumulative effective share credited to the gauge.
   * @return _claimed Cumulative emissions minted to recipients by the claim flow.
   * @return _lastSettlement Timestamp of the gauge's last settlement.
   * @return _isRegistered Whether the gauge was produced by an approved factory.
   * @return _isActivated Whether the gauge is activated for direct allocation routing.
   * @return _surplus Cumulative surplus attributed to the gauge.
   * @return _lastIndex Snapshot of the chain index at the gauge's last settlement.
   * @return _lastTimeIndex Snapshot of the chain time index at the gauge's last settlement.
   * @return _point Decaying weight of the gauge.
   */
  function gaugeStates(address _gauge)
    external
    view
    returns (
      uint128 _ceiling,
      uint128 _claimed,
      uint48 _lastSettlement,
      bool _isRegistered,
      bool _isActivated,
      uint128 _surplus,
      uint256 _lastIndex,
      uint256 _lastTimeIndex,
      Point memory _point
    );
}

contracts/periphery/interfaces/IERC20Metadata.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.0;

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

/// @title IERC20Metadata
/// @title Interface for ERC20 Metadata
/// @notice Extension to IERC20 that includes token metadata
interface IERC20Metadata is IERC20 {
  /// @return The name of the token
  function name() external view returns (string memory);

  /// @return The symbol of the token
  function symbol() external view returns (string memory);

  /// @return The number of decimal places the token has
  function decimals() external view returns (uint8);
}

contracts/periphery/interfaces/IERC4906.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.5;

/// @title EIP-721 Metadata Update Extension
interface IERC4906 {
  /// @dev This event emits when the metadata of a token is changed.
  /// So that the third-party platforms such as NFT market could
  /// timely update the images and related attributes of the NFT.
  event MetadataUpdate(uint256 _tokenId);

  /// @dev This event emits when the metadata of a range of tokens is changed.
  /// So that the third-party platforms such as NFT market could
  /// timely update the images and related attributes of the NFTs.
  event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
}

contracts/periphery/interfaces/IERC721Permit.sol

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

contracts/periphery/interfaces/INonfungiblePositionManager.sol

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

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

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

/// @title Non-fungible token for positions
/// @notice Wraps CL positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
  IPeripheryPayments,
  IPeripheryImmutableState,
  IERC721Metadata,
  IERC721Enumerable,
  IERC721Permit,
  IERC4906
{
  /// @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
  /// @param tickLower The lower end of the tick range for the position
  /// @param tickUpper The upper end of the tick range for the position
  event IncreaseLiquidity(
    uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1, int24 tickLower, int24 tickUpper
  );
  /// @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 Emitted when a new Token Descriptor is set
  /// @param tokenDescriptor Address of the new Token Descriptor
  event TokenDescriptorChanged(address indexed tokenDescriptor);
  /// @notice Emitted when a new Owner is set
  /// @param owner Address of the new Owner
  event TransferOwnership(address indexed owner);

  /// @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 tickSpacing The tick spacing 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.
  ///         If the position is staked this value represents the total unstaked fee growth within the given tick range
  /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
  ///         If the position is staked this value represents the total unstaked fee growth within the given tick range
  /// @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,
      int24 tickSpacing,
      int24 tickLower,
      int24 tickUpper,
      uint128 liquidity,
      uint256 feeGrowthInside0LastX128,
      uint256 feeGrowthInside1LastX128,
      uint128 tokensOwed0,
      uint128 tokensOwed1
    );

  /// @notice Returns the address of the Token Descriptor, that handles generating token URIs for Positions
  function tokenDescriptor() external view returns (address);

  /// @notice Returns the address of the Owner, that is allowed to set a new TokenDescriptor
  function owner() external view returns (address);

  struct MintParams {
    address token0;
    address token1;
    int24 tickSpacing;
    int24 tickLower;
    int24 tickUpper;
    uint256 amount0Desired;
    uint256 amount1Desired;
    uint256 amount0Min;
    uint256 amount1Min;
    address recipient;
    uint256 deadline;
    uint160 sqrtPriceX96;
  }

  /// @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
  /// @dev The use of this function can cause a loss to users of the NonfungiblePositionManager
  /// @dev for tokens that have very high decimals.
  /// @dev The amount of tokens necessary for the loss is: 3.4028237e+38.
  /// @dev This is equivalent to 1e20 value with 18 decimals.
  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
  /// @notice Used to update staked positions before deposit and withdraw
  /// @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;

  /// @notice Sets a new Token Descriptor
  /// @param _tokenDescriptor Address of the new Token Descriptor to be chosen
  function setTokenDescriptor(address _tokenDescriptor) external;

  /// @notice Sets a new Owner address
  /// @param _owner Address of the new Owner to be chosen
  function setOwner(address _owner) external;
}

contracts/periphery/interfaces/INonfungibleTokenPositionDescriptor.sol

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

import './INonfungiblePositionManager.sol';

/// @title Describes position NFT tokens via URI
interface INonfungibleTokenPositionDescriptor {
  /// @notice Produces the URI describing a particular token ID for a position manager
  /// @dev Note this URI may be a data: URI with the JSON contents directly inlined
  /// @param positionManager The position manager for which to describe the token
  /// @param tokenId The ID of the token for which to produce a description, which may not be valid
  /// @return The URI of the ERC721-compliant metadata
  function tokenURI(INonfungiblePositionManager positionManager, uint256 tokenId) external view returns (string memory);
}

contracts/periphery/interfaces/IPeripheryImmutableState.sol

// 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 CL factory
  function factory() external view returns (address);

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

contracts/periphery/interfaces/IPeripheryPayments.sol

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

contracts/periphery/libraries/ChainId.sol

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

/// @title Function for getting the current chain ID
library ChainId {
  /// @dev Gets the current chain ID
  /// @return chainId The current chain ID
  function get() internal pure returns (uint256 chainId) {
    assembly {
      chainId := chainid()
    }
  }
}

contracts/periphery/libraries/HexStrings.sol

// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;

library HexStrings {
  bytes16 internal constant ALPHABET = '0123456789abcdef';

  /// @notice Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
  /// @dev Credit to Open Zeppelin under MIT license https://github.com/OpenZeppelin/openzeppelin-contracts/blob/243adff49ce1700e0ecb99fe522fb16cff1d1ddc/contracts/utils/Strings.sol#L55
  function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
    bytes memory buffer = new bytes(2 * length + 2);
    buffer[0] = '0';
    buffer[1] = 'x';
    for (uint256 i = 2 * length + 1; i > 1; --i) {
      buffer[i] = ALPHABET[value & 0xf];
      value >>= 4;
    }
    require(value == 0, 'HLI'); // hex length insufficient
    return string(buffer);
  }

  function toHexStringNoPrefix(uint256 value, uint256 length) internal pure returns (string memory) {
    bytes memory buffer = new bytes(2 * length);
    for (uint256 i = buffer.length; i > 0; i--) {
      buffer[i - 1] = ALPHABET[value & 0xf];
      value >>= 4;
    }
    return string(buffer);
  }
}

contracts/periphery/libraries/NFTDescriptor.sol

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

import './HexStrings.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/math/SignedSafeMath.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import 'contracts/core/interfaces/ICLPool.sol';
import 'contracts/core/libraries/BitMath.sol';
import 'contracts/core/libraries/FullMath.sol';
import 'contracts/core/libraries/TickMath.sol';

library NFTDescriptor {
  using TickMath for int24;
  using Strings for uint256;
  using SafeMath for uint256;
  using SafeMath for uint160;
  using SafeMath for uint8;
  using SignedSafeMath for int256;
  using HexStrings for uint256;

  uint256 constant sqrt10X128 = 1_076_067_327_063_303_206_878_105_757_264_492_625_226;

  struct ConstructTokenURIParams {
    uint256 tokenId;
    address quoteTokenAddress;
    address baseTokenAddress;
    string quoteTokenSymbol;
    string baseTokenSymbol;
    uint8 quoteTokenDecimals;
    uint8 baseTokenDecimals;
    bool flipRatio;
    int24 tickLower;
    int24 tickUpper;
    int24 tickSpacing;
    address poolAddress;
  }

  function constructTokenURI(ConstructTokenURIParams memory params) public pure returns (string memory) {
    string memory name = generateName(params);
    string memory descriptionPartOne = generateDescriptionPartOne(
      escapeQuotes(params.quoteTokenSymbol), escapeQuotes(params.baseTokenSymbol), addressToString(params.poolAddress)
    );
    string memory descriptionPartTwo = generateDescriptionPartTwo(
      params.tokenId.toString(),
      escapeQuotes(params.baseTokenSymbol),
      addressToString(params.quoteTokenAddress),
      addressToString(params.baseTokenAddress),
      (uint256(params.tickSpacing)).toString()
    );

    return string(abi.encodePacked('"name":"', name, '", "description":"', descriptionPartOne, descriptionPartTwo, '"'));
  }

  function escapeQuotes(string memory symbol) internal pure returns (string memory) {
    bytes memory symbolBytes = bytes(symbol);
    uint8 quotesCount = 0;
    for (uint8 i = 0; i < symbolBytes.length; i++) {
      if (symbolBytes[i] == '"') {
        quotesCount++;
      }
    }
    if (quotesCount > 0) {
      bytes memory escapedBytes = new bytes(symbolBytes.length + (quotesCount));
      uint256 index;
      for (uint8 i = 0; i < symbolBytes.length; i++) {
        if (symbolBytes[i] == '"') {
          escapedBytes[index++] = '\\';
        }
        escapedBytes[index++] = symbolBytes[i];
      }
      return string(escapedBytes);
    }
    return symbol;
  }

  function generateDescriptionPartOne(
    string memory quoteTokenSymbol,
    string memory baseTokenSymbol,
    string memory poolAddress
  ) private pure returns (string memory) {
    return string(
      abi.encodePacked(
        'This NFT represents a liquidity position in a Velodrome Finance ',
        quoteTokenSymbol,
        '-',
        baseTokenSymbol,
        ' pool. ',
        'The owner of this NFT can modify or redeem the position.\\n',
        '\\nPool Address: ',
        poolAddress,
        '\\n',
        quoteTokenSymbol
      )
    );
  }

  function generateDescriptionPartTwo(
    string memory tokenId,
    string memory baseTokenSymbol,
    string memory quoteTokenAddress,
    string memory baseTokenAddress,
    string memory tickSpacing
  ) private pure returns (string memory) {
    return string(
      abi.encodePacked(
        ' Address: ',
        quoteTokenAddress,
        '\\n',
        baseTokenSymbol,
        ' Address: ',
        baseTokenAddress,
        '\\nTick Spacing: ',
        tickSpacing,
        '\\nToken ID: ',
        tokenId,
        '\\n\\n',
        unicode'⚠️ DISCLAIMER: Due diligence is imperative when assessing this NFT. Make sure token addresses match the expected tokens, as token symbols may be imitated.'
      )
    );
  }

  function generateName(ConstructTokenURIParams memory params) private pure returns (string memory) {
    return string(
      abi.encodePacked(
        'CL - ',
        escapeQuotes(params.quoteTokenSymbol),
        '/',
        escapeQuotes(params.baseTokenSymbol),
        ' - ',
        tickToDecimalString(
          !params.flipRatio ? params.tickLower : params.tickUpper,
          params.tickSpacing,
          params.baseTokenDecimals,
          params.quoteTokenDecimals,
          params.flipRatio
        ),
        '<>',
        tickToDecimalString(
          !params.flipRatio ? params.tickUpper : params.tickLower,
          params.tickSpacing,
          params.baseTokenDecimals,
          params.quoteTokenDecimals,
          params.flipRatio
        )
      )
    );
  }

  /// @dev Returns the lower and upper prices for a position in quote token per base token
  function generatePriceRange(ConstructTokenURIParams memory params)
    internal
    pure
    returns (string memory priceLower, string memory priceUpper)
  {
    priceLower = tickToDecimalString(
      !params.flipRatio ? params.tickLower : params.tickUpper,
      params.tickSpacing,
      params.baseTokenDecimals,
      params.quoteTokenDecimals,
      params.flipRatio
    );
    priceUpper = tickToDecimalString(
      !params.flipRatio ? params.tickUpper : params.tickLower,
      params.tickSpacing,
      params.baseTokenDecimals,
      params.quoteTokenDecimals,
      params.flipRatio
    );
  }

  struct DecimalStringParams {
    // significant figures of decimal
    uint256 sigfigs;
    // length of decimal string
    uint8 bufferLength;
    // ending index for significant figures (funtion works backwards when copying sigfigs)
    uint8 sigfigIndex;
    // index of decimal place (0 if no decimal)
    uint8 decimalIndex;
    // start index for trailing/leading 0's for very small/large numbers
    uint8 zerosStartIndex;
    // end index for trailing/leading 0's for very small/large numbers
    uint8 zerosEndIndex;
    // true if decimal number is less than one
    bool isLessThanOne;
  }

  function generateDecimalString(DecimalStringParams memory params) private pure returns (string memory) {
    bytes memory buffer = new bytes(params.bufferLength);
    if (params.isLessThanOne) {
      buffer[0] = '0';
      buffer[1] = '.';
    }

    // add leading/trailing 0's
    for (uint256 zerosCursor = params.zerosStartIndex; zerosCursor < params.zerosEndIndex.add(1); zerosCursor++) {
      buffer[zerosCursor] = bytes1(uint8(48));
    }
    // add sigfigs
    while (params.sigfigs > 0) {
      if (params.decimalIndex > 0 && params.sigfigIndex == params.decimalIndex) {
        buffer[params.sigfigIndex--] = '.';
      }
      buffer[params.sigfigIndex--] = bytes1(uint8(uint256(48).add(params.sigfigs % 10)));
      params.sigfigs /= 10;
    }
    return string(buffer);
  }

  function tickToDecimalString(
    int24 tick,
    int24 tickSpacing,
    uint8 baseTokenDecimals,
    uint8 quoteTokenDecimals,
    bool flipRatio
  ) internal pure returns (string memory) {
    if (tick == (TickMath.MIN_TICK / tickSpacing) * tickSpacing) {
      return !flipRatio ? 'MIN' : 'MAX';
    } else if (tick == (TickMath.MAX_TICK / tickSpacing) * tickSpacing) {
      return !flipRatio ? 'MAX' : 'MIN';
    } else {
      uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
      if (flipRatio) {
        sqrtRatioX96 = uint160(uint256(1 << 192).div(sqrtRatioX96));
      }
      return fixedPointToDecimalString(sqrtRatioX96, baseTokenDecimals, quoteTokenDecimals);
    }
  }

  function sigfigsRounded(uint256 value, uint8 digits) private pure returns (uint256, bool) {
    bool extraDigit;
    if (digits > 5) {
      value = value.div((10 ** (digits - 5)));
    }
    bool roundUp = value % 10 > 4;
    value = value.div(10);
    if (roundUp) {
      value = value + 1;
    }
    // 99999 -> 100000 gives an extra sigfig
    if (value == 100_000) {
      value /= 10;
      extraDigit = true;
    }
    return (value, extraDigit);
  }

  function adjustForDecimalPrecision(
    uint160 sqrtRatioX96,
    uint8 baseTokenDecimals,
    uint8 quoteTokenDecimals
  ) private pure returns (uint256 adjustedSqrtRatioX96) {
    uint256 difference = abs(int256(baseTokenDecimals).sub(int256(quoteTokenDecimals)));
    if (difference > 0 && difference <= 18) {
      if (baseTokenDecimals > quoteTokenDecimals) {
        adjustedSqrtRatioX96 = sqrtRatioX96.mul(10 ** (difference.div(2)));
        if (difference % 2 == 1) {
          adjustedSqrtRatioX96 = FullMath.mulDiv(adjustedSqrtRatioX96, sqrt10X128, 1 << 128);
        }
      } else {
        adjustedSqrtRatioX96 = sqrtRatioX96.div(10 ** (difference.div(2)));
        if (difference % 2 == 1) {
          adjustedSqrtRatioX96 = FullMath.mulDiv(adjustedSqrtRatioX96, 1 << 128, sqrt10X128);
        }
      }
    } else {
      adjustedSqrtRatioX96 = uint256(sqrtRatioX96);
    }
  }

  function abs(int256 x) private pure returns (uint256) {
    return uint256(x >= 0 ? x : -x);
  }

  // @notice Returns string that includes first 5 significant figures of a decimal number
  // @param sqrtRatioX96 a sqrt price
  function fixedPointToDecimalString(
    uint160 sqrtRatioX96,
    uint8 baseTokenDecimals,
    uint8 quoteTokenDecimals
  ) internal pure returns (string memory) {
    uint256 adjustedSqrtRatioX96 = adjustForDecimalPrecision(sqrtRatioX96, baseTokenDecimals, quoteTokenDecimals);
    uint256 value = FullMath.mulDiv(adjustedSqrtRatioX96, adjustedSqrtRatioX96, 1 << 64);

    bool priceBelow1 = adjustedSqrtRatioX96 < 2 ** 96;
    if (priceBelow1) {
      // 10 ** 43 is precision needed to retreive 5 sigfigs of smallest possible price + 1 for rounding
      value = FullMath.mulDiv(value, 10 ** 44, 1 << 128);
    } else {
      // leave precision for 4 decimal places + 1 place for rounding
      value = FullMath.mulDiv(value, 10 ** 5, 1 << 128);
    }

    // get digit count
    uint256 temp = value;
    uint8 digits;
    while (temp != 0) {
      digits++;
      temp /= 10;
    }
    // don't count extra digit kept for rounding
    digits = digits - 1;

    // address rounding
    (uint256 sigfigs, bool extraDigit) = sigfigsRounded(value, digits);
    if (extraDigit) {
      digits++;
    }

    DecimalStringParams memory params;
    if (priceBelow1) {
      // 7 bytes ( "0." and 5 sigfigs) + leading 0's bytes
      params.bufferLength = uint8(uint8(7).add(uint8(43).sub(digits)));
      params.zerosStartIndex = 2;
      params.zerosEndIndex = uint8(uint256(43).sub(digits).add(1));
      params.sigfigIndex = uint8(params.bufferLength.sub(1));
    } else if (digits >= 9) {
      // no decimal in price string
      params.bufferLength = uint8(digits.sub(4));
      params.zerosStartIndex = 5;
      params.zerosEndIndex = uint8(params.bufferLength.sub(1));
      params.sigfigIndex = 4;
    } else {
      // 5 sigfigs surround decimal
      params.bufferLength = 6;
      params.sigfigIndex = 5;
      params.decimalIndex = uint8(digits.sub(5).add(1));
    }
    params.sigfigs = sigfigs;
    params.isLessThanOne = priceBelow1;

    return generateDecimalString(params);
  }

  function addressToString(address addr) internal pure returns (string memory) {
    return (uint256(addr)).toHexString(20);
  }
}

contracts/periphery/libraries/NFTSVG.sol

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

import '@openzeppelin/contracts/utils/Strings.sol';

/// @title NFTSVG
/// @notice Provides a function for generating an SVG associated with a CL NFT
library NFTSVG {
  using Strings for uint256;

  struct SVGParams {
    string quoteTokenSymbol;
    string baseTokenSymbol;
    address quoteTokenAddress;
    address baseTokenAddress;
    uint256 tokenId;
    string priceLower;
    string priceUpper;
    int24 tickSpacing;
    uint256 chainId;
  }

  /// @dev Base URI token logos are fetched from, keyed by chain id and EIP-55 checksummed token address
  string internal constant LOGO_BASE_URI = 'https://assets.smold.app/token/';

  function generateSVG(SVGParams memory params) public pure returns (string memory svg) {
    return string(
      abi.encodePacked(
        '<svg width="400" height="400" viewBox="0 0 400 400" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n',
        '<rect width="400" height="400" fill="white"/>\n',
        '<rect width="400" height="400" fill="#090E1F"/>\n',
        '<rect x="61.5" y="109.5" width="277" height="181" rx="90.5" stroke="url(#ringGrad)" stroke-width="3"/>\n',
        generateArt(params),
        generateText(params),
        '<path d="M368 20L377.75 20.0004L380 22.2504L380 32" stroke="#EAEAEC" stroke-width="1.5" stroke-miterlimit="16"/>\n\n',
        generateSVGDefs(),
        '</svg>\n'
      )
    );
  }

  /// @dev `{LOGO_BASE_URI}{chainId}/{checksummedTokenAddress}/logo-128.png`
  function logoURI(address token, uint256 chainId) internal pure returns (string memory) {
    // smoldapp keys token assets by the EIP-55 checksummed address, so the casing must match for the logo to resolve.
    return string(abi.encodePacked(LOGO_BASE_URI, chainId.toString(), '/', toChecksumString(token), '/logo-128.png'));
  }

  /// @dev EIP-55 checksummed hex string of an address, `0x` prefixed
  function toChecksumString(address addr) internal pure returns (string memory) {
    bytes memory lower = new bytes(40);
    bytes memory hexChars = '0123456789abcdef';
    uint160 value = uint160(addr);
    for (uint256 i = 40; i > 0; i--) {
      lower[i - 1] = hexChars[value & 0xf];
      value >>= 4;
    }
    bytes32 hash = keccak256(lower);
    bytes memory checksummed = new bytes(42);
    checksummed[0] = '0';
    checksummed[1] = 'x';
    for (uint256 i = 0; i < 40; i++) {
      uint8 nibble = uint8(hash[i / 2]);
      nibble = i % 2 == 0 ? nibble >> 4 : nibble & 0xf;
      bytes1 char = lower[i];
      // letters a-f are uppercased when the matching hash nibble is 8 or above
      if (char >= 'a' && nibble >= 8) char = bytes1(uint8(char) - 32);
      checksummed[i + 2] = char;
    }
    return string(checksummed);
  }

  /// @dev Escapes `&`, `<`, `>`, `"` and `'` so a token symbol cannot inject markup into the SVG
  function escapeHTML(string memory input) internal pure returns (string memory) {
    bytes memory raw = bytes(input);
    bytes memory escaped;
    for (uint256 i = 0; i < raw.length; i++) {
      bytes1 char = raw[i];
      if (char == '&') escaped = abi.encodePacked(escaped, '&amp;');
      else if (char == '<') escaped = abi.encodePacked(escaped, '&lt;');
      else if (char == '>') escaped = abi.encodePacked(escaped, '&gt;');
      else if (char == '"') escaped = abi.encodePacked(escaped, '&quot;');
      else if (char == "'") escaped = abi.encodePacked(escaped, '&#39;');
      else escaped = abi.encodePacked(escaped, char);
    }
    return string(escaped);
  }

  /// @dev Quote token on the left, base token on the right, each logo layered over a placeholder shown when the
  ///      logo is missing
  function generateArt(SVGParams memory params) private pure returns (string memory svg) {
    string memory quoteLogo = logoURI(params.quoteTokenAddress, params.chainId);
    string memory baseLogo = logoURI(params.baseTokenAddress, params.chainId);
    svg = string(
      abi.encodePacked(
        '<path opacity="0.55" d="M152 272C191.764 272 224 239.764 224 200C224 160.236 191.764 128 152 128C112.236 128 80 160.236 80 200C80 239.764 112.236 272 152 272Z" fill="#22294B"/>\n',
        '<path d="M152 176.6L159.446 192.554L175.4 200L159.446 207.446L152 223.4L144.554 207.446L128.6 200L144.554 192.554L152 176.6Z" fill="#8C9FFF"/>\n',
        '<image x="80" y="128" width="144" height="144" clip-path="url(#quoteClip)" href="',
        quoteLogo,
        '"/>\n',
        '<path opacity="0.55" d="M248 272C287.764 272 320 239.764 320 200C320 160.236 287.764 128 248 128C208.236 128 176 160.236 176 200C176 239.764 208.236 272 248 272Z" fill="#22294B"/>\n',
        '<path d="M248 176.6L255.446 192.554L271.4 200L255.446 207.446L248 223.4L240.554 207.446L224.6 200L240.554 192.554L248 176.6Z" fill="#8C9FFF"/>\n',
        '<image x="176" y="128" width="144" height="144" clip-path="url(#baseClip)" href="',
        baseLogo,
        '"/>\n',
        '<path d="M32 380L22.25 380L20 377.75L20 368" stroke="#EAEAEC" stroke-width="1.5" stroke-miterlimit="16"/>\n',
        '<path d="M380 368L380 377.75L377.75 380L368 380" stroke="#EAEAEC" stroke-width="1.5" stroke-miterlimit="16"/>\n'
      )
    );
  }

  function generateText(SVGParams memory params) private pure returns (string memory svg) {
    string memory pool = string(
      abi.encodePacked(
        escapeHTML(params.quoteTokenSymbol),
        '/',
        escapeHTML(params.baseTokenSymbol),
        ' CL ',
        tickToString(params.tickSpacing)
      )
    );
    string memory range =
      string(abi.encodePacked(escapeHTML(params.priceLower), '&#8211;', escapeHTML(params.priceUpper)));
    svg = string(
      abi.encodePacked(
        '<g font-family="\'Roobert Mono\', ui-monospace, \'SF Mono\', Menlo, monospace" font-size="10" letter-spacing="0.2" fill="#EAEAEC">\n',
        textLine('32', 'POOL:', pool),
        textLine('48', 'RANGE:', range),
        textLine('64', 'ID:', string(abi.encodePacked('#', params.tokenId.toString()))),
        '</g>\n'
      )
    );
  }

  function textLine(string memory y, string memory label, string memory value) private pure returns (string memory) {
    return string(
      abi.encodePacked(
        '<text x="20" y="', y, '"><tspan fill-opacity="0.5">', label, '</tspan><tspan> ', value, '</tspan></text>\n'
      )
    );
  }

  function generateSVGDefs() private pure returns (string memory svg) {
    svg = string(
      abi.encodePacked(
        '<defs>\n',
        '<clipPath id="quoteClip"><circle cx="152" cy="200" r="72"/></clipPath>\n',
        '<clipPath id="baseClip"><circle cx="248" cy="200" r="72"/></clipPath>\n',
        '<linearGradient id="ringGrad" gradientUnits="objectBoundingBox" x1="0" y1="0" x2="1" y2="1">\n',
        '<stop offset="0" stop-color="#0B1233"/>\n',
        '<stop offset="0.20" stop-color="#1446EA"/>\n',
        '<stop offset="0.45" stop-color="#FF2D12"/>\n',
        '<stop offset="0.62" stop-color="#FF6A3D"/>\n',
        '<stop offset="0.80" stop-color="#DCEBFF"/>\n',
        '<stop offset="1" stop-color="#0B1233"/>\n',
        '<animateTransform attributeName="gradientTransform" type="rotate" from="0 0.5 0.5" to="360 0.5 0.5" dur="7s" repeatCount="indefinite"/>\n',
        '</linearGradient>\n',
        '</defs>\n'
      )
    );
  }

  function tickToString(int24 tick) private pure returns (string memory) {
    string memory sign = '';
    if (tick < 0) {
      tick = tick * -1;
      sign = '-';
    }
    return string(abi.encodePacked(sign, uint256(tick).toString()));
  }
}

contracts/periphery/libraries/PoolAddress.sol

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

import '@openzeppelin/contracts/proxy/Clones.sol';
import 'contracts/core/interfaces/ICLFactory.sol';

/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
  /// @notice The identifying key of the pool
  struct PoolKey {
    address token0;
    address token1;
    int24 tickSpacing;
  }

  /// @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 tickSpacing The tick spacing of the pool
  /// @return Poolkey The pool details with ordered token0 and token1 assignments
  function getPoolKey(address tokenA, address tokenB, int24 tickSpacing) internal pure returns (PoolKey memory) {
    if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
    return PoolKey({token0: tokenA, token1: tokenB, tickSpacing: tickSpacing});
  }

  /// @notice Deterministically computes the pool address given the factory and PoolKey
  /// @param factory The CL factory contract address
  /// @param key The PoolKey
  /// @return pool The contract address of the V3 pool
  function computeAddress(address factory, PoolKey memory key) internal view returns (address pool) {
    require(key.token0 < key.token1);
    pool = Clones.predictDeterministicAddress({
      master: ICLFactory(factory).poolImplementation(),
      salt: keccak256(abi.encode(key.token0, key.token1, key.tickSpacing)),
      deployer: factory
    });
  }
}

contracts/periphery/libraries/TokenRatioSortOrder.sol

// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;

library TokenRatioSortOrder {
  int256 constant NUMERATOR_MOST = 300;
  int256 constant NUMERATOR_MORE = 200;
  int256 constant NUMERATOR = 100;

  int256 constant DENOMINATOR_MOST = -300;
  int256 constant DENOMINATOR_MORE = -200;
  int256 constant DENOMINATOR = -100;
}

node_modules/@openzeppelin/contracts/introspection/IERC165.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * 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[EIP 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);
}

node_modules/@openzeppelin/contracts/math/SafeMath.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        uint256 c = a + b;
        if (c < a) return (false, 0);
        return (true, c);
    }

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

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

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

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

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");
        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b <= a, "SafeMath: subtraction overflow");
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        if (a == 0) return 0;
        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");
        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b > 0, "SafeMath: division by zero");
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b > 0, "SafeMath: modulo by zero");
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        return a - b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryDiv}.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        return a % b;
    }
}

node_modules/@openzeppelin/contracts/math/SignedSafeMath.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @title SignedSafeMath
 * @dev Signed math operations with safety checks that revert on error.
 */
library SignedSafeMath {
    int256 constant private _INT256_MIN = -2**255;

    /**
     * @dev Returns the multiplication of two signed integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(int256 a, int256 b) internal pure returns (int256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");

        int256 c = a * b;
        require(c / a == b, "SignedSafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two signed integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(int256 a, int256 b) internal pure returns (int256) {
        require(b != 0, "SignedSafeMath: division by zero");
        require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");

        int256 c = a / b;

        return c;
    }

    /**
     * @dev Returns the subtraction of two signed integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(int256 a, int256 b) internal pure returns (int256) {
        int256 c = a - b;
        require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");

        return c;
    }

    /**
     * @dev Returns the addition of two signed integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(int256 a, int256 b) internal pure returns (int256) {
        int256 c = a + b;
        require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");

        return c;
    }
}

node_modules/@openzeppelin/contracts/proxy/Clones.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

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

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

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

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

node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

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

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

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

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

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

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

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

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

node_modules/@openzeppelin/contracts/token/ERC721/IERC721.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "../../introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 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`, checking first that contract recipients
     * are aware of the ERC721 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 be 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: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * 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 Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @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 caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

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

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

node_modules/@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "./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 tokenId);

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

node_modules/@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "./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);
}

node_modules/@openzeppelin/contracts/utils/Strings.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev String operations.
 */
library Strings {
    /**
     * @dev Converts a `uint256` to its ASCII `string` representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        uint256 index = digits - 1;
        temp = value;
        while (temp != 0) {
            buffer[index--] = bytes1(uint8(48 + temp % 10));
            temp /= 10;
        }
        return string(buffer);
    }
}

node_modules/@uniswap/lib/contracts/libraries/AddressStringUtil.sol

// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.5.0;

library AddressStringUtil {
    // converts an address to the uppercase hex string, extracting only len bytes (up to 20, multiple of 2)
    function toAsciiString(address addr, uint256 len) internal pure returns (string memory) {
        require(len % 2 == 0 && len > 0 && len <= 40, 'AddressStringUtil: INVALID_LEN');

        bytes memory s = new bytes(len);
        uint256 addrNum = uint256(addr);
        for (uint256 i = 0; i < len / 2; i++) {
            // shift right and truncate all but the least significant byte to extract the byte at position 19-i
            uint8 b = uint8(addrNum >> (8 * (19 - i)));
            // first hex character is the most significant 4 bits
            uint8 hi = b >> 4;
            // second hex character is the least significant 4 bits
            uint8 lo = b - (hi << 4);
            s[2 * i] = char(hi);
            s[2 * i + 1] = char(lo);
        }
        return string(s);
    }

    // hi and lo are only 4 bits and between 0 and 16
    // this method converts those values to the unicode/ascii code point for the hex representation
    // uses upper case for the characters
    function char(uint8 b) private pure returns (bytes1 c) {
        if (b < 10) {
            return bytes1(b + 0x30);
        } else {
            return bytes1(b + 0x37);
        }
    }
}

node_modules/@uniswap/lib/contracts/libraries/SafeERC20Namer.sol

// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.5.0;

import './AddressStringUtil.sol';

// produces token descriptors from inconsistent or absent ERC20 symbol implementations that can return string or bytes32
// this library will always produce a string symbol to represent the token
library SafeERC20Namer {
    function bytes32ToString(bytes32 x) private pure returns (string memory) {
        bytes memory bytesString = new bytes(32);
        uint256 charCount = 0;
        for (uint256 j = 0; j < 32; j++) {
            bytes1 char = x[j];
            if (char != 0) {
                bytesString[charCount] = char;
                charCount++;
            }
        }
        bytes memory bytesStringTrimmed = new bytes(charCount);
        for (uint256 j = 0; j < charCount; j++) {
            bytesStringTrimmed[j] = bytesString[j];
        }
        return string(bytesStringTrimmed);
    }

    // assumes the data is in position 2
    function parseStringData(bytes memory b) private pure returns (string memory) {
        uint256 charCount = 0;
        // first parse the charCount out of the data
        for (uint256 i = 32; i < 64; i++) {
            charCount <<= 8;
            charCount += uint8(b[i]);
        }

        bytes memory bytesStringTrimmed = new bytes(charCount);
        for (uint256 i = 0; i < charCount; i++) {
            bytesStringTrimmed[i] = b[i + 64];
        }

        return string(bytesStringTrimmed);
    }

    // uses a heuristic to produce a token name from the address
    // the heuristic returns the full hex of the address string in upper case
    function addressToName(address token) private pure returns (string memory) {
        return AddressStringUtil.toAsciiString(token, 40);
    }

    // uses a heuristic to produce a token symbol from the address
    // the heuristic returns the first 6 hex of the address string in upper case
    function addressToSymbol(address token) private pure returns (string memory) {
        return AddressStringUtil.toAsciiString(token, 6);
    }

    // calls an external view token contract method that returns a symbol or name, and parses the output into a string
    function callAndParseStringReturn(address token, bytes4 selector) private view returns (string memory) {
        (bool success, bytes memory data) = token.staticcall(abi.encodeWithSelector(selector));
        // if not implemented, or returns empty data, return empty string
        if (!success || data.length == 0) {
            return '';
        }
        // bytes32 data always has length 32
        if (data.length == 32) {
            bytes32 decoded = abi.decode(data, (bytes32));
            return bytes32ToString(decoded);
        } else if (data.length > 64) {
            return abi.decode(data, (string));
        }
        return '';
    }

    // attempts to extract the token symbol. if it does not implement symbol, returns a symbol derived from the address
    function tokenSymbol(address token) internal view returns (string memory) {
        // 0x95d89b41 = bytes4(keccak256("symbol()"))
        string memory symbol = callAndParseStringReturn(token, 0x95d89b41);
        if (bytes(symbol).length == 0) {
            // fallback to 6 uppercase hex of address
            return addressToSymbol(token);
        }
        return symbol;
    }

    // attempts to extract the token name. if it does not implement name, returns a name derived from the address
    function tokenName(address token) internal view returns (string memory) {
        // 0x06fdde03 = bytes4(keccak256("name()"))
        string memory name = callAndParseStringReturn(token, 0x06fdde03);
        if (bytes(name).length == 0) {
            // fallback to full hex of address
            return addressToName(token);
        }
        return name;
    }
}

node_modules/base64-sol/base64.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0;

/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides functions for encoding/decoding base64
library Base64 {
    string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    bytes  internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000"
                                            hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000"
                                            hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000"
                                            hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000";

    function encode(bytes memory data) internal pure returns (string memory) {
        if (data.length == 0) return '';

        // load the table into memory
        string memory table = TABLE_ENCODE;

        // multiply by 4/3 rounded up
        uint256 encodedLen = 4 * ((data.length + 2) / 3);

        // add some extra buffer at the end required for the writing
        string memory result = new string(encodedLen + 32);

        assembly {
            // set the actual output length
            mstore(result, encodedLen)

            // prepare the lookup table
            let tablePtr := add(table, 1)

            // input ptr
            let dataPtr := data
            let endPtr := add(dataPtr, mload(data))

            // result ptr, jump over length
            let resultPtr := add(result, 32)

            // run over the input, 3 bytes at a time
            for {} lt(dataPtr, endPtr) {}
            {
                // read 3 bytes
                dataPtr := add(dataPtr, 3)
                let input := mload(dataPtr)

                // write 4 characters
                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(        input,  0x3F))))
                resultPtr := add(resultPtr, 1)
            }

            // padding with '='
            switch mod(mload(data), 3)
            case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
            case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
        }

        return result;
    }

    function decode(string memory _data) internal pure returns (bytes memory) {
        bytes memory data = bytes(_data);

        if (data.length == 0) return new bytes(0);
        require(data.length % 4 == 0, "invalid base64 decoder input");

        // load the table into memory
        bytes memory table = TABLE_DECODE;

        // every 4 characters represent 3 bytes
        uint256 decodedLen = (data.length / 4) * 3;

        // add some extra buffer at the end required for the writing
        bytes memory result = new bytes(decodedLen + 32);

        assembly {
            // padding with '='
            let lastBytes := mload(add(data, mload(data)))
            if eq(and(lastBytes, 0xFF), 0x3d) {
                decodedLen := sub(decodedLen, 1)
                if eq(and(lastBytes, 0xFFFF), 0x3d3d) {
                    decodedLen := sub(decodedLen, 1)
                }
            }

            // set the actual output length
            mstore(result, decodedLen)

            // prepare the lookup table
            let tablePtr := add(table, 1)

            // input ptr
            let dataPtr := data
            let endPtr := add(dataPtr, mload(data))

            // result ptr, jump over length
            let resultPtr := add(result, 32)

            // run over the input, 4 characters at a time
            for {} lt(dataPtr, endPtr) {}
            {
               // read 4 characters
               dataPtr := add(dataPtr, 4)
               let input := mload(dataPtr)

               // write 3 bytes
               let output := add(
                   add(
                       shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)),
                       shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))),
                   add(
                       shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)),
                               and(mload(add(tablePtr, and(        input , 0xFF))), 0xFF)
                    )
                )
                mstore(resultPtr, shl(232, output))
                resultPtr := add(resultPtr, 3)
            }
        }

        return result;
    }
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {
    "contracts/periphery/NonfungibleTokenPositionDescriptor.sol": {
      "NFTSVG": "0x933f7c94f165143daf9ca82e763cfd6fa233931e",
      "NFTDescriptor": "0xea1eaf9b4a4f93626b890975a0293627a33159fb"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "istanbul",
  "remappings": [
    "/Users/acx/code/dromos/metadex-slipstream/node_modules/@hyperlane-xyz/:@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable-v4/",
    "/Users/acx/code/dromos/metadex-slipstream/node_modules/@hyperlane-xyz/:@openzeppelin/contracts/=node_modules/@openzeppelin/contracts-v4/",
    "/Users/acx/code/dromos/metadex-slipstream/node_modules/metadex/:@hyperlane/contracts/=node_modules/@hyperlane-xyz/core/contracts/",
    "/Users/acx/code/dromos/metadex-slipstream/node_modules/metadex/:@nomad-xyz/src/=node_modules/metadex/node_modules/@nomad-xyz/excessively-safe-call/src/",
    "/Users/acx/code/dromos/metadex-slipstream/node_modules/metadex/:@openzeppelin/contracts/=node_modules/metadex/node_modules/@openzeppelin/contracts/",
    "/Users/acx/code/dromos/metadex-slipstream/node_modules/metadex/:@solady/=node_modules/solady/src/",
    "/Users/acx/code/dromos/metadex-slipstream/test/invariants/fuzz/:@openzeppelin/contracts/=node_modules/metadex/node_modules/@openzeppelin/contracts/",
    ":@hyperlane-v11/contracts/=node_modules/@hyperlane-xyz/core-v11/contracts/",
    ":@hyperlane/contracts/=node_modules/@hyperlane-xyz/core/contracts/",
    ":@nomad-xyz/excessively-safe-call/=node_modules/@nomad-xyz/excessively-safe-call/",
    ":@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
    ":@solady/=node_modules/solady/src/",
    ":@uniswap/lib/=node_modules/@uniswap/lib/",
    ":V3-script/=node_modules/metadex/V3/script/",
    ":V3-test/=node_modules/metadex/V3/test/",
    ":V3/=node_modules/metadex/V3/src/",
    ":base64-sol/=node_modules/base64-sol/",
    ":forge-std/=node_modules/forge-std/src/",
    "node_modules/@hyperlane-xyz/:@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable-v4/",
    "node_modules/@hyperlane-xyz/:@openzeppelin/contracts/=node_modules/@openzeppelin/contracts-v4/",
    "node_modules/metadex/:@hyperlane/contracts/=node_modules/@hyperlane-xyz/core/contracts/",
    "node_modules/metadex/:@nomad-xyz/src/=node_modules/metadex/node_modules/@nomad-xyz/excessively-safe-call/src/",
    "node_modules/metadex/:@openzeppelin/contracts/=node_modules/metadex/node_modules/@openzeppelin/contracts/",
    "node_modules/metadex/:@solady/=node_modules/solady/src/",
    "test/invariants/fuzz/:@openzeppelin/contracts/=node_modules/metadex/node_modules/@openzeppelin/contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.