creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@pancakeswap/v3-lm-pool/contracts/interfaces/IPancakeV3LmPool.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\ninterface IPancakeV3LmPool {\n  function accumulateReward(uint32 currTimestamp) external;\n\n  function crossLmTick(int24 tick, bool zeroForOne) external;\n}\n"
      },
      "contracts/interfaces/callback/IPancakeV3FlashCallback.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IPancakeV3PoolActions#flash\n/// @notice Any contract that calls IPancakeV3PoolActions#flash must implement this interface\ninterface IPancakeV3FlashCallback {\n    /// @notice Called to `msg.sender` after transferring to the recipient from IPancakeV3Pool#flash.\n    /// @dev In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts.\n    /// The caller of this method must be checked to be a PancakeV3Pool deployed by the canonical PancakeV3Factory.\n    /// @param fee0 The fee amount in token0 due to the pool by the end of the flash\n    /// @param fee1 The fee amount in token1 due to the pool by the end of the flash\n    /// @param data Any data passed through by the caller via the IPancakeV3PoolActions#flash call\n    function pancakeV3FlashCallback(\n        uint256 fee0,\n        uint256 fee1,\n        bytes calldata data\n    ) external;\n}\n"
      },
      "contracts/interfaces/callback/IPancakeV3MintCallback.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IPancakeV3PoolActions#mint\n/// @notice Any contract that calls IPancakeV3PoolActions#mint must implement this interface\ninterface IPancakeV3MintCallback {\n    /// @notice Called to `msg.sender` after minting liquidity to a position from IPancakeV3Pool#mint.\n    /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.\n    /// The caller of this method must be checked to be a PancakeV3Pool deployed by the canonical PancakeV3Factory.\n    /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity\n    /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity\n    /// @param data Any data passed through by the caller via the IPancakeV3PoolActions#mint call\n    function pancakeV3MintCallback(\n        uint256 amount0Owed,\n        uint256 amount1Owed,\n        bytes calldata data\n    ) external;\n}\n"
      },
      "contracts/interfaces/callback/IPancakeV3SwapCallback.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IPancakeV3PoolActions#swap\n/// @notice Any contract that calls IPancakeV3PoolActions#swap must implement this interface\ninterface IPancakeV3SwapCallback {\n    /// @notice Called to `msg.sender` after executing a swap via IPancakeV3Pool#swap.\n    /// @dev In the implementation you must pay the pool tokens owed for the swap.\n    /// The caller of this method must be checked to be a PancakeV3Pool deployed by the canonical PancakeV3Factory.\n    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.\n    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by\n    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.\n    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by\n    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.\n    /// @param data Any data passed through by the caller via the IPancakeV3PoolActions#swap call\n    function pancakeV3SwapCallback(\n        int256 amount0Delta,\n        int256 amount1Delta,\n        bytes calldata data\n    ) external;\n}\n"
      },
      "contracts/interfaces/IERC20Minimal.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Minimal ERC20 interface for PancakeSwap\n/// @notice Contains a subset of the full ERC20 interface that is used in PancakeSwap V3\ninterface IERC20Minimal {\n    /// @notice Returns the balance of a token\n    /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n    /// @return The number of tokens held by the account\n    function balanceOf(address account) external view returns (uint256);\n\n    /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n    /// @param recipient The account that will receive the amount transferred\n    /// @param amount The number of tokens to send from the sender to the recipient\n    /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n    function transfer(address recipient, uint256 amount) external returns (bool);\n\n    /// @notice Returns the current allowance given to a spender by an owner\n    /// @param owner The account of the token owner\n    /// @param spender The account of the token spender\n    /// @return The current allowance granted by `owner` to `spender`\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n    /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n    /// @param amount The amount of tokens allowed to be used by `spender`\n    /// @return Returns true for a successful approval, false for unsuccessful\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n    /// @param sender The account from which the transfer will be initiated\n    /// @param recipient The recipient of the transfer\n    /// @param amount The amount of the transfer\n    /// @return Returns true for a successful transfer, false for unsuccessful\n    function transferFrom(\n        address sender,\n        address recipient,\n        uint256 amount\n    ) external returns (bool);\n\n    /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n    /// @param from The account from which the tokens were sent, i.e. the balance decreased\n    /// @param to The account to which the tokens were sent, i.e. the balance increased\n    /// @param value The amount of tokens that were transferred\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n    /// @param owner The account that approved spending of its tokens\n    /// @param spender The account for which the spending allowance was modified\n    /// @param value The new allowance from the owner to the spender\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
      },
      "contracts/interfaces/IPancakeV3Factory.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title The interface for the PancakeSwap V3 Factory\n/// @notice The PancakeSwap V3 Factory facilitates creation of PancakeSwap V3 pools and control over the protocol fees\ninterface IPancakeV3Factory {\n    struct TickSpacingExtraInfo {\n        bool whitelistRequested;\n        bool enabled;\n    }\n\n    /// @notice Emitted when the owner of the factory is changed\n    /// @param oldOwner The owner before the owner was changed\n    /// @param newOwner The owner after the owner was changed\n    event OwnerChanged(address indexed oldOwner, address indexed newOwner);\n\n    /// @notice Emitted when a pool is created\n    /// @param token0 The first token of the pool by address sort order\n    /// @param token1 The second token of the pool by address sort order\n    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n    /// @param tickSpacing The minimum number of ticks between initialized ticks\n    /// @param pool The address of the created pool\n    event PoolCreated(\n        address indexed token0,\n        address indexed token1,\n        uint24 indexed fee,\n        int24 tickSpacing,\n        address pool\n    );\n\n    /// @notice Emitted when a new fee amount is enabled for pool creation via the factory\n    /// @param fee The enabled fee, denominated in hundredths of a bip\n    /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee\n    event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);\n\n    event FeeAmountExtraInfoUpdated(uint24 indexed fee, bool whitelistRequested, bool enabled);\n\n    event WhiteListAdded(address indexed user, bool verified);\n\n    /// @notice Emitted when LM pool deployer is set\n    event SetLmPoolDeployer(address indexed lmPoolDeployer);\n\n    /// @notice Returns the current owner of the factory\n    /// @dev Can be changed by the current owner via setOwner\n    /// @return The address of the factory owner\n    function owner() external view returns (address);\n\n    /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled\n    /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context\n    /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee\n    /// @return The tick spacing\n    function feeAmountTickSpacing(uint24 fee) external view returns (int24);\n\n    /// @notice Returns the tick spacing extra info\n    /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context\n    /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee\n    /// @return whitelistRequested The flag whether should be created by white list users only\n    function feeAmountTickSpacingExtraInfo(uint24 fee) external view returns (bool whitelistRequested, bool enabled);\n\n    /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist\n    /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order\n    /// @param tokenA The contract address of either token0 or token1\n    /// @param tokenB The contract address of the other token\n    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n    /// @return pool The pool address\n    function getPool(\n        address tokenA,\n        address tokenB,\n        uint24 fee\n    ) external view returns (address pool);\n\n    /// @notice Creates a pool for the given two tokens and fee\n    /// @param tokenA One of the two tokens in the desired pool\n    /// @param tokenB The other of the two tokens in the desired pool\n    /// @param fee The desired fee for the pool\n    /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved\n    /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments\n    /// are invalid.\n    /// @return pool The address of the newly created pool\n    function createPool(\n        address tokenA,\n        address tokenB,\n        uint24 fee\n    ) external returns (address pool);\n\n    /// @notice Updates the owner of the factory\n    /// @dev Must be called by the current owner\n    /// @param _owner The new owner of the factory\n    function setOwner(address _owner) external;\n\n    /// @notice Enables a fee amount with the given tickSpacing\n    /// @dev Fee amounts may never be removed once enabled\n    /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)\n    /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount\n    function enableFeeAmount(uint24 fee, int24 tickSpacing) external;\n\n    /// @notice Set an address into white list\n    /// @dev Address can be updated by owner with boolean value false\n    /// @param user The user address that add into white list\n    function setWhiteListAddress(address user, bool verified) external;\n\n    /// @notice Set a fee amount extra info\n    /// @dev Fee amounts can be updated by owner with extra info\n    /// @param whitelistRequested The flag whether should be created by owner only\n    /// @param enabled The flag is the fee is enabled or not\n    function setFeeAmountExtraInfo(\n        uint24 fee,\n        bool whitelistRequested,\n        bool enabled\n    ) external;\n\n    function setLmPoolDeployer(address _lmPoolDeployer) external;\n\n    function setFeeProtocol(address pool, uint32 feeProtocol0, uint32 feeProtocol1) external;\n\n    function collectProtocol(\n        address pool,\n        address recipient,\n        uint128 amount0Requested,\n        uint128 amount1Requested\n    ) external returns (uint128 amount0, uint128 amount1);\n\n    function setLmPool(address pool, address lmPool) external;\n}\n"
      },
      "contracts/interfaces/IPancakeV3Pool.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport './pool/IPancakeV3PoolImmutables.sol';\nimport './pool/IPancakeV3PoolState.sol';\nimport './pool/IPancakeV3PoolDerivedState.sol';\nimport './pool/IPancakeV3PoolActions.sol';\nimport './pool/IPancakeV3PoolOwnerActions.sol';\nimport './pool/IPancakeV3PoolEvents.sol';\n\n/// @title The interface for a PancakeSwap V3 Pool\n/// @notice A PancakeSwap pool facilitates swapping and automated market making between any two assets that strictly conform\n/// to the ERC20 specification\n/// @dev The pool interface is broken up into many smaller pieces\ninterface IPancakeV3Pool is\n    IPancakeV3PoolImmutables,\n    IPancakeV3PoolState,\n    IPancakeV3PoolDerivedState,\n    IPancakeV3PoolActions,\n    IPancakeV3PoolOwnerActions,\n    IPancakeV3PoolEvents\n{\n\n}\n"
      },
      "contracts/interfaces/IPancakeV3PoolDeployer.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title An interface for a contract that is capable of deploying PancakeSwap V3 Pools\n/// @notice A contract that constructs a pool must implement this to pass arguments to the pool\n/// @dev This is used to avoid having constructor arguments in the pool contract, which results in the init code hash\n/// of the pool being constant allowing the CREATE2 address of the pool to be cheaply computed on-chain\ninterface IPancakeV3PoolDeployer {\n    /// @notice Get the parameters to be used in constructing the pool, set transiently during pool creation.\n    /// @dev Called by the pool constructor to fetch the parameters of the pool\n    /// Returns factory The factory address\n    /// Returns token0 The first token of the pool by address sort order\n    /// Returns token1 The second token of the pool by address sort order\n    /// Returns fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n    /// Returns tickSpacing The minimum number of ticks between initialized ticks\n    function parameters()\n        external\n        view\n        returns (\n            address factory,\n            address token0,\n            address token1,\n            uint24 fee,\n            int24 tickSpacing\n        );\n\n    function deploy(\n        address factory,\n        address token0,\n        address token1,\n        uint24 fee,\n        int24 tickSpacing\n    ) external returns (address pool);\n}\n"
      },
      "contracts/interfaces/pool/IPancakeV3PoolActions.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissionless pool actions\n/// @notice Contains pool methods that can be called by anyone\ninterface IPancakeV3PoolActions {\n    /// @notice Sets the initial price for the pool\n    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value\n    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96\n    function initialize(uint160 sqrtPriceX96) external;\n\n    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position\n    /// @dev The caller of this method receives a callback in the form of IPancakeV3MintCallback#pancakeV3MintCallback\n    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends\n    /// on tickLower, tickUpper, the amount of liquidity, and the current price.\n    /// @param recipient The address for which the liquidity will be created\n    /// @param tickLower The lower tick of the position in which to add liquidity\n    /// @param tickUpper The upper tick of the position in which to add liquidity\n    /// @param amount The amount of liquidity to mint\n    /// @param data Any data that should be passed through to the callback\n    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback\n    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback\n    function mint(\n        address recipient,\n        int24 tickLower,\n        int24 tickUpper,\n        uint128 amount,\n        bytes calldata data\n    ) external returns (uint256 amount0, uint256 amount1);\n\n    /// @notice Collects tokens owed to a position\n    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.\n    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or\n    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the\n    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.\n    /// @param recipient The address which should receive the fees collected\n    /// @param tickLower The lower tick of the position for which to collect fees\n    /// @param tickUpper The upper tick of the position for which to collect fees\n    /// @param amount0Requested How much token0 should be withdrawn from the fees owed\n    /// @param amount1Requested How much token1 should be withdrawn from the fees owed\n    /// @return amount0 The amount of fees collected in token0\n    /// @return amount1 The amount of fees collected in token1\n    function collect(\n        address recipient,\n        int24 tickLower,\n        int24 tickUpper,\n        uint128 amount0Requested,\n        uint128 amount1Requested\n    ) external returns (uint128 amount0, uint128 amount1);\n\n    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position\n    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0\n    /// @dev Fees must be collected separately via a call to #collect\n    /// @param tickLower The lower tick of the position for which to burn liquidity\n    /// @param tickUpper The upper tick of the position for which to burn liquidity\n    /// @param amount How much liquidity to burn\n    /// @return amount0 The amount of token0 sent to the recipient\n    /// @return amount1 The amount of token1 sent to the recipient\n    function burn(\n        int24 tickLower,\n        int24 tickUpper,\n        uint128 amount\n    ) external returns (uint256 amount0, uint256 amount1);\n\n    /// @notice Swap token0 for token1, or token1 for token0\n    /// @dev The caller of this method receives a callback in the form of IPancakeV3SwapCallback#pancakeV3SwapCallback\n    /// @param recipient The address to receive the output of the swap\n    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0\n    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)\n    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this\n    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap\n    /// @param data Any data to be passed through to the callback\n    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive\n    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive\n    function swap(\n        address recipient,\n        bool zeroForOne,\n        int256 amountSpecified,\n        uint160 sqrtPriceLimitX96,\n        bytes calldata data\n    ) external returns (int256 amount0, int256 amount1);\n\n    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback\n    /// @dev The caller of this method receives a callback in the form of IPancakeV3FlashCallback#pancakeV3FlashCallback\n    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling\n    /// with 0 amount{0,1} and sending the donation amount(s) from the callback\n    /// @param recipient The address which will receive the token0 and token1 amounts\n    /// @param amount0 The amount of token0 to send\n    /// @param amount1 The amount of token1 to send\n    /// @param data Any data to be passed through to the callback\n    function flash(\n        address recipient,\n        uint256 amount0,\n        uint256 amount1,\n        bytes calldata data\n    ) external;\n\n    /// @notice Increase the maximum number of price and liquidity observations that this pool will store\n    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to\n    /// the input observationCardinalityNext.\n    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store\n    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;\n}\n"
      },
      "contracts/interfaces/pool/IPancakeV3PoolDerivedState.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that is not stored\n/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the\n/// blockchain. The functions here may have variable gas costs.\ninterface IPancakeV3PoolDerivedState {\n    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp\n    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing\n    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,\n    /// you must call it with secondsAgos = [3600, 0].\n    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in\n    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.\n    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned\n    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp\n    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block\n    /// timestamp\n    function observe(uint32[] calldata secondsAgos)\n        external\n        view\n        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);\n\n    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range\n    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.\n    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first\n    /// snapshot is taken and the second snapshot is taken.\n    /// @param tickLower The lower tick of the range\n    /// @param tickUpper The upper tick of the range\n    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range\n    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range\n    /// @return secondsInside The snapshot of seconds per liquidity for the range\n    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)\n        external\n        view\n        returns (\n            int56 tickCumulativeInside,\n            uint160 secondsPerLiquidityInsideX128,\n            uint32 secondsInside\n        );\n}\n"
      },
      "contracts/interfaces/pool/IPancakeV3PoolEvents.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Events emitted by a pool\n/// @notice Contains all events emitted by the pool\ninterface IPancakeV3PoolEvents {\n    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool\n    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize\n    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96\n    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool\n    event Initialize(uint160 sqrtPriceX96, int24 tick);\n\n    /// @notice Emitted when liquidity is minted for a given position\n    /// @param sender The address that minted the liquidity\n    /// @param owner The owner of the position and recipient of any minted liquidity\n    /// @param tickLower The lower tick of the position\n    /// @param tickUpper The upper tick of the position\n    /// @param amount The amount of liquidity minted to the position range\n    /// @param amount0 How much token0 was required for the minted liquidity\n    /// @param amount1 How much token1 was required for the minted liquidity\n    event Mint(\n        address sender,\n        address indexed owner,\n        int24 indexed tickLower,\n        int24 indexed tickUpper,\n        uint128 amount,\n        uint256 amount0,\n        uint256 amount1\n    );\n\n    /// @notice Emitted when fees are collected by the owner of a position\n    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees\n    /// @param owner The owner of the position for which fees are collected\n    /// @param tickLower The lower tick of the position\n    /// @param tickUpper The upper tick of the position\n    /// @param amount0 The amount of token0 fees collected\n    /// @param amount1 The amount of token1 fees collected\n    event Collect(\n        address indexed owner,\n        address recipient,\n        int24 indexed tickLower,\n        int24 indexed tickUpper,\n        uint128 amount0,\n        uint128 amount1\n    );\n\n    /// @notice Emitted when a position's liquidity is removed\n    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect\n    /// @param owner The owner of the position for which liquidity is removed\n    /// @param tickLower The lower tick of the position\n    /// @param tickUpper The upper tick of the position\n    /// @param amount The amount of liquidity to remove\n    /// @param amount0 The amount of token0 withdrawn\n    /// @param amount1 The amount of token1 withdrawn\n    event Burn(\n        address indexed owner,\n        int24 indexed tickLower,\n        int24 indexed tickUpper,\n        uint128 amount,\n        uint256 amount0,\n        uint256 amount1\n    );\n\n    /// @notice Emitted by the pool for any swaps between token0 and token1\n    /// @param sender The address that initiated the swap call, and that received the callback\n    /// @param recipient The address that received the output of the swap\n    /// @param amount0 The delta of the token0 balance of the pool\n    /// @param amount1 The delta of the token1 balance of the pool\n    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96\n    /// @param liquidity The liquidity of the pool after the swap\n    /// @param tick The log base 1.0001 of price of the pool after the swap\n    /// @param protocolFeesToken0 The protocol fee of token0 in the swap\n    /// @param protocolFeesToken1 The protocol fee of token1 in the swap\n    event Swap(\n        address indexed sender,\n        address indexed recipient,\n        int256 amount0,\n        int256 amount1,\n        uint160 sqrtPriceX96,\n        uint128 liquidity,\n        int24 tick,\n        uint128 protocolFeesToken0,\n        uint128 protocolFeesToken1\n    );\n\n    /// @notice Emitted by the pool for any flashes of token0/token1\n    /// @param sender The address that initiated the swap call, and that received the callback\n    /// @param recipient The address that received the tokens from flash\n    /// @param amount0 The amount of token0 that was flashed\n    /// @param amount1 The amount of token1 that was flashed\n    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee\n    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee\n    event Flash(\n        address indexed sender,\n        address indexed recipient,\n        uint256 amount0,\n        uint256 amount1,\n        uint256 paid0,\n        uint256 paid1\n    );\n\n    /// @notice Emitted by the pool for increases to the number of observations that can be stored\n    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index\n    /// just before a mint/swap/burn.\n    /// @param observationCardinalityNextOld The previous value of the next observation cardinality\n    /// @param observationCardinalityNextNew The updated value of the next observation cardinality\n    event IncreaseObservationCardinalityNext(\n        uint16 observationCardinalityNextOld,\n        uint16 observationCardinalityNextNew\n    );\n\n    /// @notice Emitted when the protocol fee is changed by the pool\n    /// @param feeProtocol0Old The previous value of the token0 protocol fee\n    /// @param feeProtocol1Old The previous value of the token1 protocol fee\n    /// @param feeProtocol0New The updated value of the token0 protocol fee\n    /// @param feeProtocol1New The updated value of the token1 protocol fee\n    event SetFeeProtocol(\n        uint32 feeProtocol0Old,\n        uint32 feeProtocol1Old,\n        uint32 feeProtocol0New,\n        uint32 feeProtocol1New\n    );\n\n    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner\n    /// @param sender The address that collects the protocol fees\n    /// @param recipient The address that receives the collected protocol fees\n    /// @param amount0 The amount of token0 protocol fees that is withdrawn\n    /// @param amount0 The amount of token1 protocol fees that is withdrawn\n    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);\n}\n"
      },
      "contracts/interfaces/pool/IPancakeV3PoolImmutables.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that never changes\n/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values\ninterface IPancakeV3PoolImmutables {\n    /// @notice The contract that deployed the pool, which must adhere to the IPancakeV3Factory interface\n    /// @return The contract address\n    function factory() external view returns (address);\n\n    /// @notice The first of the two tokens of the pool, sorted by address\n    /// @return The token contract address\n    function token0() external view returns (address);\n\n    /// @notice The second of the two tokens of the pool, sorted by address\n    /// @return The token contract address\n    function token1() external view returns (address);\n\n    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6\n    /// @return The fee\n    function fee() external view returns (uint24);\n\n    /// @notice The pool tick spacing\n    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive\n    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...\n    /// This value is an int24 to avoid casting even though it is always positive.\n    /// @return The tick spacing\n    function tickSpacing() external view returns (int24);\n\n    /// @notice The maximum amount of position liquidity that can use any tick in the range\n    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and\n    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool\n    /// @return The max amount of liquidity per tick\n    function maxLiquidityPerTick() external view returns (uint128);\n}\n"
      },
      "contracts/interfaces/pool/IPancakeV3PoolOwnerActions.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissioned pool actions\n/// @notice Contains pool methods that may only be called by the factory owner\ninterface IPancakeV3PoolOwnerActions {\n    /// @notice Set the denominator of the protocol's % share of the fees\n    /// @param feeProtocol0 new protocol fee for token0 of the pool\n    /// @param feeProtocol1 new protocol fee for token1 of the pool\n    function setFeeProtocol(uint32 feeProtocol0, uint32 feeProtocol1) external;\n\n    /// @notice Collect the protocol fee accrued to the pool\n    /// @param recipient The address to which collected protocol fees should be sent\n    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1\n    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0\n    /// @return amount0 The protocol fee collected in token0\n    /// @return amount1 The protocol fee collected in token1\n    function collectProtocol(\n        address recipient,\n        uint128 amount0Requested,\n        uint128 amount1Requested\n    ) external returns (uint128 amount0, uint128 amount1);\n\n    /// @notice Set the LM pool to enable liquidity mining\n    function setLmPool(address lmPool) external;\n}\n"
      },
      "contracts/interfaces/pool/IPancakeV3PoolState.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that can change\n/// @notice These methods compose the pool's state, and can change with any frequency including multiple times\n/// per transaction\ninterface IPancakeV3PoolState {\n    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas\n    /// when accessed externally.\n    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value\n    /// tick The current tick of the pool, i.e. according to the last tick transition that was run.\n    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick\n    /// boundary.\n    /// observationIndex The index of the last oracle observation that was written,\n    /// observationCardinality The current maximum number of observations stored in the pool,\n    /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.\n    /// feeProtocol The protocol fee for both tokens of the pool.\n    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0\n    /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.\n    /// unlocked Whether the pool is currently locked to reentrancy\n    function slot0()\n        external\n        view\n        returns (\n            uint160 sqrtPriceX96,\n            int24 tick,\n            uint16 observationIndex,\n            uint16 observationCardinality,\n            uint16 observationCardinalityNext,\n            uint32 feeProtocol,\n            bool unlocked\n        );\n\n    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool\n    /// @dev This value can overflow the uint256\n    function feeGrowthGlobal0X128() external view returns (uint256);\n\n    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool\n    /// @dev This value can overflow the uint256\n    function feeGrowthGlobal1X128() external view returns (uint256);\n\n    /// @notice The amounts of token0 and token1 that are owed to the protocol\n    /// @dev Protocol fees will never exceed uint128 max in either token\n    function protocolFees() external view returns (uint128 token0, uint128 token1);\n\n    /// @notice The currently in range liquidity available to the pool\n    /// @dev This value has no relationship to the total liquidity across all ticks\n    function liquidity() external view returns (uint128);\n\n    /// @notice Look up information about a specific tick in the pool\n    /// @param tick The tick to look up\n    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or\n    /// tick upper,\n    /// liquidityNet how much liquidity changes when the pool price crosses the tick,\n    /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,\n    /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,\n    /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick\n    /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,\n    /// secondsOutside the seconds spent on the other side of the tick from the current tick,\n    /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.\n    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.\n    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for\n    /// a specific position.\n    function ticks(int24 tick)\n        external\n        view\n        returns (\n            uint128 liquidityGross,\n            int128 liquidityNet,\n            uint256 feeGrowthOutside0X128,\n            uint256 feeGrowthOutside1X128,\n            int56 tickCumulativeOutside,\n            uint160 secondsPerLiquidityOutsideX128,\n            uint32 secondsOutside,\n            bool initialized\n        );\n\n    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information\n    function tickBitmap(int16 wordPosition) external view returns (uint256);\n\n    /// @notice Returns the information about a position by the position's key\n    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper\n    /// @return _liquidity The amount of liquidity in the position,\n    /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,\n    /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,\n    /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,\n    /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke\n    function positions(bytes32 key)\n        external\n        view\n        returns (\n            uint128 _liquidity,\n            uint256 feeGrowthInside0LastX128,\n            uint256 feeGrowthInside1LastX128,\n            uint128 tokensOwed0,\n            uint128 tokensOwed1\n        );\n\n    /// @notice Returns data about a specific observation index\n    /// @param index The element of the observations array to fetch\n    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time\n    /// ago, rather than at a specific index in the array.\n    /// @return blockTimestamp The timestamp of the observation,\n    /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,\n    /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,\n    /// Returns initialized whether the observation has been initialized and the values are safe to use\n    function observations(uint256 index)\n        external\n        view\n        returns (\n            uint32 blockTimestamp,\n            int56 tickCumulative,\n            uint160 secondsPerLiquidityCumulativeX128,\n            bool initialized\n        );\n}\n"
      },
      "contracts/libraries/BitMath.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title BitMath\n/// @dev This library provides functionality for computing bit properties of an unsigned integer\nlibrary BitMath {\n    /// @notice Returns the index of the most significant bit of the number,\n    ///     where the least significant bit is at index 0 and the most significant bit is at index 255\n    /// @dev The function satisfies the property:\n    ///     x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)\n    /// @param x the value for which to compute the most significant bit, must be greater than 0\n    /// @return r the index of the most significant bit\n    function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {\n        require(x > 0);\n\n        if (x >= 0x100000000000000000000000000000000) {\n            x >>= 128;\n            r += 128;\n        }\n        if (x >= 0x10000000000000000) {\n            x >>= 64;\n            r += 64;\n        }\n        if (x >= 0x100000000) {\n            x >>= 32;\n            r += 32;\n        }\n        if (x >= 0x10000) {\n            x >>= 16;\n            r += 16;\n        }\n        if (x >= 0x100) {\n            x >>= 8;\n            r += 8;\n        }\n        if (x >= 0x10) {\n            x >>= 4;\n            r += 4;\n        }\n        if (x >= 0x4) {\n            x >>= 2;\n            r += 2;\n        }\n        if (x >= 0x2) r += 1;\n    }\n\n    /// @notice Returns the index of the least significant bit of the number,\n    ///     where the least significant bit is at index 0 and the most significant bit is at index 255\n    /// @dev The function satisfies the property:\n    ///     (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)\n    /// @param x the value for which to compute the least significant bit, must be greater than 0\n    /// @return r the index of the least significant bit\n    function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {\n        require(x > 0);\n\n        r = 255;\n        if (x & type(uint128).max > 0) {\n            r -= 128;\n        } else {\n            x >>= 128;\n        }\n        if (x & type(uint64).max > 0) {\n            r -= 64;\n        } else {\n            x >>= 64;\n        }\n        if (x & type(uint32).max > 0) {\n            r -= 32;\n        } else {\n            x >>= 32;\n        }\n        if (x & type(uint16).max > 0) {\n            r -= 16;\n        } else {\n            x >>= 16;\n        }\n        if (x & type(uint8).max > 0) {\n            r -= 8;\n        } else {\n            x >>= 8;\n        }\n        if (x & 0xf > 0) {\n            r -= 4;\n        } else {\n            x >>= 4;\n        }\n        if (x & 0x3 > 0) {\n            r -= 2;\n        } else {\n            x >>= 2;\n        }\n        if (x & 0x1 > 0) r -= 1;\n    }\n}\n"
      },
      "contracts/libraries/FixedPoint128.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.4.0;\n\n/// @title FixedPoint128\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\nlibrary FixedPoint128 {\n    uint256 internal constant Q128 = 0x100000000000000000000000000000000;\n}\n"
      },
      "contracts/libraries/FixedPoint96.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.4.0;\n\n/// @title FixedPoint96\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\n/// @dev Used in SqrtPriceMath.sol\nlibrary FixedPoint96 {\n    uint8 internal constant RESOLUTION = 96;\n    uint256 internal constant Q96 = 0x1000000000000000000000000;\n}\n"
      },
      "contracts/libraries/FullMath.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.4.0 <0.8.0;\n\n/// @title Contains 512-bit math functions\n/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision\n/// @dev Handles \"phantom overflow\" i.e., allows multiplication and division where an intermediate value overflows 256 bits\nlibrary FullMath {\n    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n    /// @param a The multiplicand\n    /// @param b The multiplier\n    /// @param denominator The divisor\n    /// @return result The 256-bit result\n    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv\n    function mulDiv(\n        uint256 a,\n        uint256 b,\n        uint256 denominator\n    ) internal pure returns (uint256 result) {\n        // 512-bit multiply [prod1 prod0] = a * b\n        // Compute the product mod 2**256 and mod 2**256 - 1\n        // then use the Chinese Remainder Theorem to reconstruct\n        // the 512 bit result. The result is stored in two 256\n        // variables such that product = prod1 * 2**256 + prod0\n        uint256 prod0; // Least significant 256 bits of the product\n        uint256 prod1; // Most significant 256 bits of the product\n        assembly {\n            let mm := mulmod(a, b, not(0))\n            prod0 := mul(a, b)\n            prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n        }\n\n        // Handle non-overflow cases, 256 by 256 division\n        if (prod1 == 0) {\n            require(denominator > 0);\n            assembly {\n                result := div(prod0, denominator)\n            }\n            return result;\n        }\n\n        // Make sure the result is less than 2**256.\n        // Also prevents denominator == 0\n        require(denominator > prod1);\n\n        ///////////////////////////////////////////////\n        // 512 by 256 division.\n        ///////////////////////////////////////////////\n\n        // Make division exact by subtracting the remainder from [prod1 prod0]\n        // Compute remainder using mulmod\n        uint256 remainder;\n        assembly {\n            remainder := mulmod(a, b, denominator)\n        }\n        // Subtract 256 bit number from 512 bit number\n        assembly {\n            prod1 := sub(prod1, gt(remainder, prod0))\n            prod0 := sub(prod0, remainder)\n        }\n\n        // Factor powers of two out of denominator\n        // Compute largest power of two divisor of denominator.\n        // Always >= 1.\n        uint256 twos = -denominator & denominator;\n        // Divide denominator by power of two\n        assembly {\n            denominator := div(denominator, twos)\n        }\n\n        // Divide [prod1 prod0] by the factors of two\n        assembly {\n            prod0 := div(prod0, twos)\n        }\n        // Shift in bits from prod1 into prod0. For this we need\n        // to flip `twos` such that it is 2**256 / twos.\n        // If twos is zero, then it becomes one\n        assembly {\n            twos := add(div(sub(0, twos), twos), 1)\n        }\n        prod0 |= prod1 * twos;\n\n        // Invert denominator mod 2**256\n        // Now that denominator is an odd number, it has an inverse\n        // modulo 2**256 such that denominator * inv = 1 mod 2**256.\n        // Compute the inverse by starting with a seed that is correct\n        // correct for four bits. That is, denominator * inv = 1 mod 2**4\n        uint256 inv = (3 * denominator) ^ 2;\n        // Now use Newton-Raphson iteration to improve the precision.\n        // Thanks to Hensel's lifting lemma, this also works in modular\n        // arithmetic, doubling the correct bits in each step.\n        inv *= 2 - denominator * inv; // inverse mod 2**8\n        inv *= 2 - denominator * inv; // inverse mod 2**16\n        inv *= 2 - denominator * inv; // inverse mod 2**32\n        inv *= 2 - denominator * inv; // inverse mod 2**64\n        inv *= 2 - denominator * inv; // inverse mod 2**128\n        inv *= 2 - denominator * inv; // inverse mod 2**256\n\n        // Because the division is now exact we can divide by multiplying\n        // with the modular inverse of denominator. This will give us the\n        // correct result modulo 2**256. Since the precoditions guarantee\n        // that the outcome is less than 2**256, this is the final result.\n        // We don't need to compute the high bits of the result and prod1\n        // is no longer required.\n        result = prod0 * inv;\n        return result;\n    }\n\n    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n    /// @param a The multiplicand\n    /// @param b The multiplier\n    /// @param denominator The divisor\n    /// @return result The 256-bit result\n    function mulDivRoundingUp(\n        uint256 a,\n        uint256 b,\n        uint256 denominator\n    ) internal pure returns (uint256 result) {\n        result = mulDiv(a, b, denominator);\n        if (mulmod(a, b, denominator) > 0) {\n            require(result < type(uint256).max);\n            result++;\n        }\n    }\n}\n"
      },
      "contracts/libraries/LiquidityMath.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n    /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n    /// @param x The liquidity before change\n    /// @param y The delta by which liquidity should be changed\n    /// @return z The liquidity delta\n    function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n        if (y < 0) {\n            require((z = x - uint128(-y)) < x, 'LS');\n        } else {\n            require((z = x + uint128(y)) >= x, 'LA');\n        }\n    }\n}\n"
      },
      "contracts/libraries/LowGasSafeMath.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.0;\n\n/// @title Optimized overflow and underflow safe math operations\n/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost\nlibrary LowGasSafeMath {\n    /// @notice Returns x + y, reverts if sum overflows uint256\n    /// @param x The augend\n    /// @param y The addend\n    /// @return z The sum of x and y\n    function add(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        require((z = x + y) >= x);\n    }\n\n    /// @notice Returns x - y, reverts if underflows\n    /// @param x The minuend\n    /// @param y The subtrahend\n    /// @return z The difference of x and y\n    function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        require((z = x - y) <= x);\n    }\n\n    /// @notice Returns x * y, reverts if overflows\n    /// @param x The multiplicand\n    /// @param y The multiplier\n    /// @return z The product of x and y\n    function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        require(x == 0 || (z = x * y) / x == y);\n    }\n\n    /// @notice Returns x + y, reverts if overflows or underflows\n    /// @param x The augend\n    /// @param y The addend\n    /// @return z The sum of x and y\n    function add(int256 x, int256 y) internal pure returns (int256 z) {\n        require((z = x + y) >= x == (y >= 0));\n    }\n\n    /// @notice Returns x - y, reverts if overflows or underflows\n    /// @param x The minuend\n    /// @param y The subtrahend\n    /// @return z The difference of x and y\n    function sub(int256 x, int256 y) internal pure returns (int256 z) {\n        require((z = x - y) <= x == (y >= 0));\n    }\n}\n"
      },
      "contracts/libraries/Oracle.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0 <0.8.0;\n\n/// @title Oracle\n/// @notice Provides price and liquidity data useful for a wide variety of system designs\n/// @dev Instances of stored oracle data, \"observations\", are collected in the oracle array\n/// Every pool is initialized with an oracle array length of 1. Anyone can pay the SSTOREs to increase the\n/// maximum length of the oracle array. New slots will be added when the array is fully populated.\n/// Observations are overwritten when the full length of the oracle array is populated.\n/// The most recent observation is available, independent of the length of the oracle array, by passing 0 to observe()\nlibrary Oracle {\n    struct Observation {\n        // the block timestamp of the observation\n        uint32 blockTimestamp;\n        // the tick accumulator, i.e. tick * time elapsed since the pool was first initialized\n        int56 tickCumulative;\n        // the seconds per liquidity, i.e. seconds elapsed / max(1, liquidity) since the pool was first initialized\n        uint160 secondsPerLiquidityCumulativeX128;\n        // whether or not the observation is initialized\n        bool initialized;\n    }\n\n    /// @notice Transforms a previous observation into a new observation, given the passage of time and the current tick and liquidity values\n    /// @dev blockTimestamp _must_ be chronologically equal to or greater than last.blockTimestamp, safe for 0 or 1 overflows\n    /// @param last The specified observation to be transformed\n    /// @param blockTimestamp The timestamp of the new observation\n    /// @param tick The active tick at the time of the new observation\n    /// @param liquidity The total in-range liquidity at the time of the new observation\n    /// @return Observation The newly populated observation\n    function transform(\n        Observation memory last,\n        uint32 blockTimestamp,\n        int24 tick,\n        uint128 liquidity\n    ) private pure returns (Observation memory) {\n        uint32 delta = blockTimestamp - last.blockTimestamp;\n        return\n            Observation({\n                blockTimestamp: blockTimestamp,\n                tickCumulative: last.tickCumulative + int56(tick) * delta,\n                secondsPerLiquidityCumulativeX128: last.secondsPerLiquidityCumulativeX128 +\n                    ((uint160(delta) << 128) / (liquidity > 0 ? liquidity : 1)),\n                initialized: true\n            });\n    }\n\n    /// @notice Initialize the oracle array by writing the first slot. Called once for the lifecycle of the observations array\n    /// @param self The stored oracle array\n    /// @param time The time of the oracle initialization, via block.timestamp truncated to uint32\n    /// @return cardinality The number of populated elements in the oracle array\n    /// @return cardinalityNext The new length of the oracle array, independent of population\n    function initialize(Observation[65535] storage self, uint32 time)\n        internal\n        returns (uint16 cardinality, uint16 cardinalityNext)\n    {\n        self[0] = Observation({\n            blockTimestamp: time,\n            tickCumulative: 0,\n            secondsPerLiquidityCumulativeX128: 0,\n            initialized: true\n        });\n        return (1, 1);\n    }\n\n    /// @notice Writes an oracle observation to the array\n    /// @dev Writable at most once per block. Index represents the most recently written element. cardinality and index must be tracked externally.\n    /// If the index is at the end of the allowable array length (according to cardinality), and the next cardinality\n    /// is greater than the current one, cardinality may be increased. This restriction is created to preserve ordering.\n    /// @param self The stored oracle array\n    /// @param index The index of the observation that was most recently written to the observations array\n    /// @param blockTimestamp The timestamp of the new observation\n    /// @param tick The active tick at the time of the new observation\n    /// @param liquidity The total in-range liquidity at the time of the new observation\n    /// @param cardinality The number of populated elements in the oracle array\n    /// @param cardinalityNext The new length of the oracle array, independent of population\n    /// @return indexUpdated The new index of the most recently written element in the oracle array\n    /// @return cardinalityUpdated The new cardinality of the oracle array\n    function write(\n        Observation[65535] storage self,\n        uint16 index,\n        uint32 blockTimestamp,\n        int24 tick,\n        uint128 liquidity,\n        uint16 cardinality,\n        uint16 cardinalityNext\n    ) internal returns (uint16 indexUpdated, uint16 cardinalityUpdated) {\n        Observation memory last = self[index];\n\n        // early return if we've already written an observation this block\n        if (last.blockTimestamp == blockTimestamp) return (index, cardinality);\n\n        // if the conditions are right, we can bump the cardinality\n        if (cardinalityNext > cardinality && index == (cardinality - 1)) {\n            cardinalityUpdated = cardinalityNext;\n        } else {\n            cardinalityUpdated = cardinality;\n        }\n\n        indexUpdated = (index + 1) % cardinalityUpdated;\n        self[indexUpdated] = transform(last, blockTimestamp, tick, liquidity);\n    }\n\n    /// @notice Prepares the oracle array to store up to `next` observations\n    /// @param self The stored oracle array\n    /// @param current The current next cardinality of the oracle array\n    /// @param next The proposed next cardinality which will be populated in the oracle array\n    /// @return next The next cardinality which will be populated in the oracle array\n    function grow(\n        Observation[65535] storage self,\n        uint16 current,\n        uint16 next\n    ) internal returns (uint16) {\n        require(current > 0, 'I');\n        // no-op if the passed next value isn't greater than the current next value\n        if (next <= current) return current;\n        // store in each slot to prevent fresh SSTOREs in swaps\n        // this data will not be used because the initialized boolean is still false\n        for (uint16 i = current; i < next; i++) self[i].blockTimestamp = 1;\n        return next;\n    }\n\n    /// @notice comparator for 32-bit timestamps\n    /// @dev safe for 0 or 1 overflows, a and b _must_ be chronologically before or equal to time\n    /// @param time A timestamp truncated to 32 bits\n    /// @param a A comparison timestamp from which to determine the relative position of `time`\n    /// @param b From which to determine the relative position of `time`\n    /// @return bool Whether `a` is chronologically <= `b`\n    function lte(\n        uint32 time,\n        uint32 a,\n        uint32 b\n    ) private pure returns (bool) {\n        // if there hasn't been overflow, no need to adjust\n        if (a <= time && b <= time) return a <= b;\n\n        uint256 aAdjusted = a > time ? a : a + 2**32;\n        uint256 bAdjusted = b > time ? b : b + 2**32;\n\n        return aAdjusted <= bAdjusted;\n    }\n\n    /// @notice Fetches the observations beforeOrAt and atOrAfter a target, i.e. where [beforeOrAt, atOrAfter] is satisfied.\n    /// The result may be the same observation, or adjacent observations.\n    /// @dev The answer must be contained in the array, used when the target is located within the stored observation\n    /// boundaries: older than the most recent observation and younger, or the same age as, the oldest observation\n    /// @param self The stored oracle array\n    /// @param time The current block.timestamp\n    /// @param target The timestamp at which the reserved observation should be for\n    /// @param index The index of the observation that was most recently written to the observations array\n    /// @param cardinality The number of populated elements in the oracle array\n    /// @return beforeOrAt The observation recorded before, or at, the target\n    /// @return atOrAfter The observation recorded at, or after, the target\n    function binarySearch(\n        Observation[65535] storage self,\n        uint32 time,\n        uint32 target,\n        uint16 index,\n        uint16 cardinality\n    ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {\n        uint256 l = (index + 1) % cardinality; // oldest observation\n        uint256 r = l + cardinality - 1; // newest observation\n        uint256 i;\n        while (true) {\n            i = (l + r) / 2;\n\n            beforeOrAt = self[i % cardinality];\n\n            // we've landed on an uninitialized tick, keep searching higher (more recently)\n            if (!beforeOrAt.initialized) {\n                l = i + 1;\n                continue;\n            }\n\n            atOrAfter = self[(i + 1) % cardinality];\n\n            bool targetAtOrAfter = lte(time, beforeOrAt.blockTimestamp, target);\n\n            // check if we've found the answer!\n            if (targetAtOrAfter && lte(time, target, atOrAfter.blockTimestamp)) break;\n\n            if (!targetAtOrAfter) r = i - 1;\n            else l = i + 1;\n        }\n    }\n\n    /// @notice Fetches the observations beforeOrAt and atOrAfter a given target, i.e. where [beforeOrAt, atOrAfter] is satisfied\n    /// @dev Assumes there is at least 1 initialized observation.\n    /// Used by observeSingle() to compute the counterfactual accumulator values as of a given block timestamp.\n    /// @param self The stored oracle array\n    /// @param time The current block.timestamp\n    /// @param target The timestamp at which the reserved observation should be for\n    /// @param tick The active tick at the time of the returned or simulated observation\n    /// @param index The index of the observation that was most recently written to the observations array\n    /// @param liquidity The total pool liquidity at the time of the call\n    /// @param cardinality The number of populated elements in the oracle array\n    /// @return beforeOrAt The observation which occurred at, or before, the given timestamp\n    /// @return atOrAfter The observation which occurred at, or after, the given timestamp\n    function getSurroundingObservations(\n        Observation[65535] storage self,\n        uint32 time,\n        uint32 target,\n        int24 tick,\n        uint16 index,\n        uint128 liquidity,\n        uint16 cardinality\n    ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {\n        // optimistically set before to the newest observation\n        beforeOrAt = self[index];\n\n        // if the target is chronologically at or after the newest observation, we can early return\n        if (lte(time, beforeOrAt.blockTimestamp, target)) {\n            if (beforeOrAt.blockTimestamp == target) {\n                // if newest observation equals target, we're in the same block, so we can ignore atOrAfter\n                return (beforeOrAt, atOrAfter);\n            } else {\n                // otherwise, we need to transform\n                return (beforeOrAt, transform(beforeOrAt, target, tick, liquidity));\n            }\n        }\n\n        // now, set before to the oldest observation\n        beforeOrAt = self[(index + 1) % cardinality];\n        if (!beforeOrAt.initialized) beforeOrAt = self[0];\n\n        // ensure that the target is chronologically at or after the oldest observation\n        require(lte(time, beforeOrAt.blockTimestamp, target), 'OLD');\n\n        // if we've reached this point, we have to binary search\n        return binarySearch(self, time, target, index, cardinality);\n    }\n\n    /// @dev Reverts if an observation at or before the desired observation timestamp does not exist.\n    /// 0 may be passed as `secondsAgo' to return the current cumulative values.\n    /// If called with a timestamp falling between two observations, returns the counterfactual accumulator values\n    /// at exactly the timestamp between the two observations.\n    /// @param self The stored oracle array\n    /// @param time The current block timestamp\n    /// @param secondsAgo The amount of time to look back, in seconds, at which point to return an observation\n    /// @param tick The current tick\n    /// @param index The index of the observation that was most recently written to the observations array\n    /// @param liquidity The current in-range pool liquidity\n    /// @param cardinality The number of populated elements in the oracle array\n    /// @return tickCumulative The tick * time elapsed since the pool was first initialized, as of `secondsAgo`\n    /// @return secondsPerLiquidityCumulativeX128 The time elapsed / max(1, liquidity) since the pool was first initialized, as of `secondsAgo`\n    function observeSingle(\n        Observation[65535] storage self,\n        uint32 time,\n        uint32 secondsAgo,\n        int24 tick,\n        uint16 index,\n        uint128 liquidity,\n        uint16 cardinality\n    ) internal view returns (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) {\n        if (secondsAgo == 0) {\n            Observation memory last = self[index];\n            if (last.blockTimestamp != time) last = transform(last, time, tick, liquidity);\n            return (last.tickCumulative, last.secondsPerLiquidityCumulativeX128);\n        }\n\n        uint32 target = time - secondsAgo;\n\n        (Observation memory beforeOrAt, Observation memory atOrAfter) = getSurroundingObservations(\n            self,\n            time,\n            target,\n            tick,\n            index,\n            liquidity,\n            cardinality\n        );\n\n        if (target == beforeOrAt.blockTimestamp) {\n            // we're at the left boundary\n            return (beforeOrAt.tickCumulative, beforeOrAt.secondsPerLiquidityCumulativeX128);\n        } else if (target == atOrAfter.blockTimestamp) {\n            // we're at the right boundary\n            return (atOrAfter.tickCumulative, atOrAfter.secondsPerLiquidityCumulativeX128);\n        } else {\n            // we're in the middle\n            uint32 observationTimeDelta = atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp;\n            uint32 targetDelta = target - beforeOrAt.blockTimestamp;\n            return (\n                beforeOrAt.tickCumulative +\n                    ((atOrAfter.tickCumulative - beforeOrAt.tickCumulative) / observationTimeDelta) *\n                    targetDelta,\n                beforeOrAt.secondsPerLiquidityCumulativeX128 +\n                    uint160(\n                        (uint256(\n                            atOrAfter.secondsPerLiquidityCumulativeX128 - beforeOrAt.secondsPerLiquidityCumulativeX128\n                        ) * targetDelta) / observationTimeDelta\n                    )\n            );\n        }\n    }\n\n    /// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos`\n    /// @dev Reverts if `secondsAgos` > oldest observation\n    /// @param self The stored oracle array\n    /// @param time The current block.timestamp\n    /// @param secondsAgos Each amount of time to look back, in seconds, at which point to return an observation\n    /// @param tick The current tick\n    /// @param index The index of the observation that was most recently written to the observations array\n    /// @param liquidity The current in-range pool liquidity\n    /// @param cardinality The number of populated elements in the oracle array\n    /// @return tickCumulatives The tick * time elapsed since the pool was first initialized, as of each `secondsAgo`\n    /// @return secondsPerLiquidityCumulativeX128s The cumulative seconds / max(1, liquidity) since the pool was first initialized, as of each `secondsAgo`\n    function observe(\n        Observation[65535] storage self,\n        uint32 time,\n        uint32[] memory secondsAgos,\n        int24 tick,\n        uint16 index,\n        uint128 liquidity,\n        uint16 cardinality\n    ) internal view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) {\n        require(cardinality > 0, 'I');\n\n        tickCumulatives = new int56[](secondsAgos.length);\n        secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length);\n        for (uint256 i = 0; i < secondsAgos.length; i++) {\n            (tickCumulatives[i], secondsPerLiquidityCumulativeX128s[i]) = observeSingle(\n                self,\n                time,\n                secondsAgos[i],\n                tick,\n                index,\n                liquidity,\n                cardinality\n            );\n        }\n    }\n}\n"
      },
      "contracts/libraries/Position.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0 <0.8.0;\n\nimport './FullMath.sol';\nimport './FixedPoint128.sol';\nimport './LiquidityMath.sol';\n\n/// @title Position\n/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary\n/// @dev Positions store additional state for tracking fees owed to the position\nlibrary Position {\n    // info stored for each user's position\n    struct Info {\n        // the amount of liquidity owned by this position\n        uint128 liquidity;\n        // fee growth per unit of liquidity as of the last update to liquidity or fees owed\n        uint256 feeGrowthInside0LastX128;\n        uint256 feeGrowthInside1LastX128;\n        // the fees owed to the position owner in token0/token1\n        uint128 tokensOwed0;\n        uint128 tokensOwed1;\n    }\n\n    /// @notice Returns the Info struct of a position, given an owner and position boundaries\n    /// @param self The mapping containing all user positions\n    /// @param owner The address of the position owner\n    /// @param tickLower The lower tick boundary of the position\n    /// @param tickUpper The upper tick boundary of the position\n    /// @return position The position info struct of the given owners' position\n    function get(\n        mapping(bytes32 => Info) storage self,\n        address owner,\n        int24 tickLower,\n        int24 tickUpper\n    ) internal view returns (Position.Info storage position) {\n        position = self[keccak256(abi.encodePacked(owner, tickLower, tickUpper))];\n    }\n\n    /// @notice Credits accumulated fees to a user's position\n    /// @param self The individual position to update\n    /// @param liquidityDelta The change in pool liquidity as a result of the position update\n    /// @param feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries\n    /// @param feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries\n    function update(\n        Info storage self,\n        int128 liquidityDelta,\n        uint256 feeGrowthInside0X128,\n        uint256 feeGrowthInside1X128\n    ) internal {\n        Info memory _self = self;\n\n        uint128 liquidityNext;\n        if (liquidityDelta == 0) {\n            require(_self.liquidity > 0, 'NP'); // disallow pokes for 0 liquidity positions\n            liquidityNext = _self.liquidity;\n        } else {\n            liquidityNext = LiquidityMath.addDelta(_self.liquidity, liquidityDelta);\n        }\n\n        // calculate accumulated fees\n        uint128 tokensOwed0 = uint128(\n            FullMath.mulDiv(feeGrowthInside0X128 - _self.feeGrowthInside0LastX128, _self.liquidity, FixedPoint128.Q128)\n        );\n        uint128 tokensOwed1 = uint128(\n            FullMath.mulDiv(feeGrowthInside1X128 - _self.feeGrowthInside1LastX128, _self.liquidity, FixedPoint128.Q128)\n        );\n\n        // update the position\n        if (liquidityDelta != 0) self.liquidity = liquidityNext;\n        self.feeGrowthInside0LastX128 = feeGrowthInside0X128;\n        self.feeGrowthInside1LastX128 = feeGrowthInside1X128;\n        if (tokensOwed0 > 0 || tokensOwed1 > 0) {\n            // overflow is acceptable, have to withdraw before you hit type(uint128).max fees\n            self.tokensOwed0 += tokensOwed0;\n            self.tokensOwed1 += tokensOwed1;\n        }\n    }\n}\n"
      },
      "contracts/libraries/SafeCast.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n    /// @notice Cast a uint256 to a uint160, revert on overflow\n    /// @param y The uint256 to be downcasted\n    /// @return z The downcasted integer, now type uint160\n    function toUint160(uint256 y) internal pure returns (uint160 z) {\n        require((z = uint160(y)) == y);\n    }\n\n    /// @notice Cast a int256 to a int128, revert on overflow or underflow\n    /// @param y The int256 to be downcasted\n    /// @return z The downcasted integer, now type int128\n    function toInt128(int256 y) internal pure returns (int128 z) {\n        require((z = int128(y)) == y);\n    }\n\n    /// @notice Cast a uint256 to a int256, revert on overflow\n    /// @param y The uint256 to be casted\n    /// @return z The casted integer, now type int256\n    function toInt256(uint256 y) internal pure returns (int256 z) {\n        require(y < 2**255);\n        z = int256(y);\n    }\n}\n"
      },
      "contracts/libraries/SqrtPriceMath.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport './LowGasSafeMath.sol';\nimport './SafeCast.sol';\n\nimport './FullMath.sol';\nimport './UnsafeMath.sol';\nimport './FixedPoint96.sol';\n\n/// @title Functions based on Q64.96 sqrt price and liquidity\n/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas\nlibrary SqrtPriceMath {\n    using LowGasSafeMath for uint256;\n    using SafeCast for uint256;\n\n    /// @notice Gets the next sqrt price given a delta of token0\n    /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least\n    /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the\n    /// price less in order to not send too much output.\n    /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),\n    /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).\n    /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta\n    /// @param liquidity The amount of usable liquidity\n    /// @param amount How much of token0 to add or remove from virtual reserves\n    /// @param add Whether to add or remove the amount of token0\n    /// @return The price after adding or removing amount, depending on add\n    function getNextSqrtPriceFromAmount0RoundingUp(\n        uint160 sqrtPX96,\n        uint128 liquidity,\n        uint256 amount,\n        bool add\n    ) internal pure returns (uint160) {\n        // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price\n        if (amount == 0) return sqrtPX96;\n        uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n\n        if (add) {\n            uint256 product;\n            if ((product = amount * sqrtPX96) / amount == sqrtPX96) {\n                uint256 denominator = numerator1 + product;\n                if (denominator >= numerator1)\n                    // always fits in 160 bits\n                    return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));\n            }\n\n            return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));\n        } else {\n            uint256 product;\n            // if the product overflows, we know the denominator underflows\n            // in addition, we must check that the denominator does not underflow\n            require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);\n            uint256 denominator = numerator1 - product;\n            return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();\n        }\n    }\n\n    /// @notice Gets the next sqrt price given a delta of token1\n    /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least\n    /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the\n    /// price less in order to not send too much output.\n    /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity\n    /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta\n    /// @param liquidity The amount of usable liquidity\n    /// @param amount How much of token1 to add, or remove, from virtual reserves\n    /// @param add Whether to add, or remove, the amount of token1\n    /// @return The price after adding or removing `amount`\n    function getNextSqrtPriceFromAmount1RoundingDown(\n        uint160 sqrtPX96,\n        uint128 liquidity,\n        uint256 amount,\n        bool add\n    ) internal pure returns (uint160) {\n        // if we're adding (subtracting), rounding down requires rounding the quotient down (up)\n        // in both cases, avoid a mulDiv for most inputs\n        if (add) {\n            uint256 quotient = (\n                amount <= type(uint160).max\n                    ? (amount << FixedPoint96.RESOLUTION) / liquidity\n                    : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)\n            );\n\n            return uint256(sqrtPX96).add(quotient).toUint160();\n        } else {\n            uint256 quotient = (\n                amount <= type(uint160).max\n                    ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)\n                    : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)\n            );\n\n            require(sqrtPX96 > quotient);\n            // always fits 160 bits\n            return uint160(sqrtPX96 - quotient);\n        }\n    }\n\n    /// @notice Gets the next sqrt price given an input amount of token0 or token1\n    /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds\n    /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount\n    /// @param liquidity The amount of usable liquidity\n    /// @param amountIn How much of token0, or token1, is being swapped in\n    /// @param zeroForOne Whether the amount in is token0 or token1\n    /// @return sqrtQX96 The price after adding the input amount to token0 or token1\n    function getNextSqrtPriceFromInput(\n        uint160 sqrtPX96,\n        uint128 liquidity,\n        uint256 amountIn,\n        bool zeroForOne\n    ) internal pure returns (uint160 sqrtQX96) {\n        require(sqrtPX96 > 0);\n        require(liquidity > 0);\n\n        // round to make sure that we don't pass the target price\n        return\n            zeroForOne\n                ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)\n                : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);\n    }\n\n    /// @notice Gets the next sqrt price given an output amount of token0 or token1\n    /// @dev Throws if price or liquidity are 0 or the next price is out of bounds\n    /// @param sqrtPX96 The starting price before accounting for the output amount\n    /// @param liquidity The amount of usable liquidity\n    /// @param amountOut How much of token0, or token1, is being swapped out\n    /// @param zeroForOne Whether the amount out is token0 or token1\n    /// @return sqrtQX96 The price after removing the output amount of token0 or token1\n    function getNextSqrtPriceFromOutput(\n        uint160 sqrtPX96,\n        uint128 liquidity,\n        uint256 amountOut,\n        bool zeroForOne\n    ) internal pure returns (uint160 sqrtQX96) {\n        require(sqrtPX96 > 0);\n        require(liquidity > 0);\n\n        // round to make sure that we pass the target price\n        return\n            zeroForOne\n                ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)\n                : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);\n    }\n\n    /// @notice Gets the amount0 delta between two prices\n    /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),\n    /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))\n    /// @param sqrtRatioAX96 A sqrt price\n    /// @param sqrtRatioBX96 Another sqrt price\n    /// @param liquidity The amount of usable liquidity\n    /// @param roundUp Whether to round the amount up or down\n    /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices\n    function getAmount0Delta(\n        uint160 sqrtRatioAX96,\n        uint160 sqrtRatioBX96,\n        uint128 liquidity,\n        bool roundUp\n    ) internal pure returns (uint256 amount0) {\n        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n        uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n        uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;\n\n        require(sqrtRatioAX96 > 0);\n\n        return\n            roundUp\n                ? UnsafeMath.divRoundingUp(\n                    FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),\n                    sqrtRatioAX96\n                )\n                : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;\n    }\n\n    /// @notice Gets the amount1 delta between two prices\n    /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))\n    /// @param sqrtRatioAX96 A sqrt price\n    /// @param sqrtRatioBX96 Another sqrt price\n    /// @param liquidity The amount of usable liquidity\n    /// @param roundUp Whether to round the amount up, or down\n    /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices\n    function getAmount1Delta(\n        uint160 sqrtRatioAX96,\n        uint160 sqrtRatioBX96,\n        uint128 liquidity,\n        bool roundUp\n    ) internal pure returns (uint256 amount1) {\n        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n        return\n            roundUp\n                ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)\n                : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n    }\n\n    /// @notice Helper that gets signed token0 delta\n    /// @param sqrtRatioAX96 A sqrt price\n    /// @param sqrtRatioBX96 Another sqrt price\n    /// @param liquidity The change in liquidity for which to compute the amount0 delta\n    /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices\n    function getAmount0Delta(\n        uint160 sqrtRatioAX96,\n        uint160 sqrtRatioBX96,\n        int128 liquidity\n    ) internal pure returns (int256 amount0) {\n        return\n            liquidity < 0\n                ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n                : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n    }\n\n    /// @notice Helper that gets signed token1 delta\n    /// @param sqrtRatioAX96 A sqrt price\n    /// @param sqrtRatioBX96 Another sqrt price\n    /// @param liquidity The change in liquidity for which to compute the amount1 delta\n    /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices\n    function getAmount1Delta(\n        uint160 sqrtRatioAX96,\n        uint160 sqrtRatioBX96,\n        int128 liquidity\n    ) internal pure returns (int256 amount1) {\n        return\n            liquidity < 0\n                ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n                : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n    }\n}\n"
      },
      "contracts/libraries/SwapMath.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport './FullMath.sol';\nimport './SqrtPriceMath.sol';\n\n/// @title Computes the result of a swap within ticks\n/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.\nlibrary SwapMath {\n    /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap\n    /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive\n    /// @param sqrtRatioCurrentX96 The current sqrt price of the pool\n    /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred\n    /// @param liquidity The usable liquidity\n    /// @param amountRemaining How much input or output amount is remaining to be swapped in/out\n    /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip\n    /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target\n    /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap\n    /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap\n    /// @return feeAmount The amount of input that will be taken as a fee\n    function computeSwapStep(\n        uint160 sqrtRatioCurrentX96,\n        uint160 sqrtRatioTargetX96,\n        uint128 liquidity,\n        int256 amountRemaining,\n        uint24 feePips\n    )\n        internal\n        pure\n        returns (\n            uint160 sqrtRatioNextX96,\n            uint256 amountIn,\n            uint256 amountOut,\n            uint256 feeAmount\n        )\n    {\n        bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;\n        bool exactIn = amountRemaining >= 0;\n\n        if (exactIn) {\n            uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6);\n            amountIn = zeroForOne\n                ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)\n                : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);\n            if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96;\n            else\n                sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(\n                    sqrtRatioCurrentX96,\n                    liquidity,\n                    amountRemainingLessFee,\n                    zeroForOne\n                );\n        } else {\n            amountOut = zeroForOne\n                ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)\n                : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);\n            if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96;\n            else\n                sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(\n                    sqrtRatioCurrentX96,\n                    liquidity,\n                    uint256(-amountRemaining),\n                    zeroForOne\n                );\n        }\n\n        bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;\n\n        // get the input/output amounts\n        if (zeroForOne) {\n            amountIn = max && exactIn\n                ? amountIn\n                : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);\n            amountOut = max && !exactIn\n                ? amountOut\n                : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);\n        } else {\n            amountIn = max && exactIn\n                ? amountIn\n                : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);\n            amountOut = max && !exactIn\n                ? amountOut\n                : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);\n        }\n\n        // cap the output amount to not exceed the remaining output amount\n        if (!exactIn && amountOut > uint256(-amountRemaining)) {\n            amountOut = uint256(-amountRemaining);\n        }\n\n        if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {\n            // we didn't reach the target, so take the remainder of the maximum input as fee\n            feeAmount = uint256(amountRemaining) - amountIn;\n        } else {\n            feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips);\n        }\n    }\n}\n"
      },
      "contracts/libraries/Tick.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0 <0.8.0;\n\nimport './LowGasSafeMath.sol';\nimport './SafeCast.sol';\n\nimport './TickMath.sol';\nimport './LiquidityMath.sol';\n\n/// @title Tick\n/// @notice Contains functions for managing tick processes and relevant calculations\nlibrary Tick {\n    using LowGasSafeMath for int256;\n    using SafeCast for int256;\n\n    // info stored for each initialized individual tick\n    struct Info {\n        // the total position liquidity that references this tick\n        uint128 liquidityGross;\n        // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left),\n        int128 liquidityNet;\n        // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n        // only has relative meaning, not absolute — the value depends on when the tick is initialized\n        uint256 feeGrowthOutside0X128;\n        uint256 feeGrowthOutside1X128;\n        // the cumulative tick value on the other side of the tick\n        int56 tickCumulativeOutside;\n        // the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n        // only has relative meaning, not absolute — the value depends on when the tick is initialized\n        uint160 secondsPerLiquidityOutsideX128;\n        // the seconds spent on the other side of the tick (relative to the current tick)\n        // only has relative meaning, not absolute — the value depends on when the tick is initialized\n        uint32 secondsOutside;\n        // true iff the tick is initialized, i.e. the value is exactly equivalent to the expression liquidityGross != 0\n        // these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks\n        bool initialized;\n    }\n\n    /// @notice Derives max liquidity per tick from given tick spacing\n    /// @dev Executed within the pool constructor\n    /// @param tickSpacing The amount of required tick separation, realized in multiples of `tickSpacing`\n    ///     e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ...\n    /// @return The max liquidity per tick\n    function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) internal pure returns (uint128) {\n        int24 minTick = (TickMath.MIN_TICK / tickSpacing) * tickSpacing;\n        int24 maxTick = (TickMath.MAX_TICK / tickSpacing) * tickSpacing;\n        uint24 numTicks = uint24((maxTick - minTick) / tickSpacing) + 1;\n        return type(uint128).max / numTicks;\n    }\n\n    /// @notice Retrieves fee growth data\n    /// @param self The mapping containing all tick information for initialized ticks\n    /// @param tickLower The lower tick boundary of the position\n    /// @param tickUpper The upper tick boundary of the position\n    /// @param tickCurrent The current tick\n    /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0\n    /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1\n    /// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries\n    /// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries\n    function getFeeGrowthInside(\n        mapping(int24 => Tick.Info) storage self,\n        int24 tickLower,\n        int24 tickUpper,\n        int24 tickCurrent,\n        uint256 feeGrowthGlobal0X128,\n        uint256 feeGrowthGlobal1X128\n    ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) {\n        Info storage lower = self[tickLower];\n        Info storage upper = self[tickUpper];\n\n        // calculate fee growth below\n        uint256 feeGrowthBelow0X128;\n        uint256 feeGrowthBelow1X128;\n        if (tickCurrent >= tickLower) {\n            feeGrowthBelow0X128 = lower.feeGrowthOutside0X128;\n            feeGrowthBelow1X128 = lower.feeGrowthOutside1X128;\n        } else {\n            feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lower.feeGrowthOutside0X128;\n            feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lower.feeGrowthOutside1X128;\n        }\n\n        // calculate fee growth above\n        uint256 feeGrowthAbove0X128;\n        uint256 feeGrowthAbove1X128;\n        if (tickCurrent < tickUpper) {\n            feeGrowthAbove0X128 = upper.feeGrowthOutside0X128;\n            feeGrowthAbove1X128 = upper.feeGrowthOutside1X128;\n        } else {\n            feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upper.feeGrowthOutside0X128;\n            feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upper.feeGrowthOutside1X128;\n        }\n\n        feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128;\n        feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128;\n    }\n\n    /// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa\n    /// @param self The mapping containing all tick information for initialized ticks\n    /// @param tick The tick that will be updated\n    /// @param tickCurrent The current tick\n    /// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left)\n    /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0\n    /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1\n    /// @param secondsPerLiquidityCumulativeX128 The all-time seconds per max(1, liquidity) of the pool\n    /// @param tickCumulative The tick * time elapsed since the pool was first initialized\n    /// @param time The current block timestamp cast to a uint32\n    /// @param upper true for updating a position's upper tick, or false for updating a position's lower tick\n    /// @param maxLiquidity The maximum liquidity allocation for a single tick\n    /// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa\n    function update(\n        mapping(int24 => Tick.Info) storage self,\n        int24 tick,\n        int24 tickCurrent,\n        int128 liquidityDelta,\n        uint256 feeGrowthGlobal0X128,\n        uint256 feeGrowthGlobal1X128,\n        uint160 secondsPerLiquidityCumulativeX128,\n        int56 tickCumulative,\n        uint32 time,\n        bool upper,\n        uint128 maxLiquidity\n    ) internal returns (bool flipped) {\n        Tick.Info storage info = self[tick];\n\n        uint128 liquidityGrossBefore = info.liquidityGross;\n        uint128 liquidityGrossAfter = LiquidityMath.addDelta(liquidityGrossBefore, liquidityDelta);\n\n        require(liquidityGrossAfter <= maxLiquidity, 'LO');\n\n        flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0);\n\n        if (liquidityGrossBefore == 0) {\n            // by convention, we assume that all growth before a tick was initialized happened _below_ the tick\n            if (tick <= tickCurrent) {\n                info.feeGrowthOutside0X128 = feeGrowthGlobal0X128;\n                info.feeGrowthOutside1X128 = feeGrowthGlobal1X128;\n                info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128;\n                info.tickCumulativeOutside = tickCumulative;\n                info.secondsOutside = time;\n            }\n            info.initialized = true;\n        }\n\n        info.liquidityGross = liquidityGrossAfter;\n\n        // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed)\n        info.liquidityNet = upper\n            ? int256(info.liquidityNet).sub(liquidityDelta).toInt128()\n            : int256(info.liquidityNet).add(liquidityDelta).toInt128();\n    }\n\n    /// @notice Clears tick data\n    /// @param self The mapping containing all initialized tick information for initialized ticks\n    /// @param tick The tick that will be cleared\n    function clear(mapping(int24 => Tick.Info) storage self, int24 tick) internal {\n        delete self[tick];\n    }\n\n    /// @notice Transitions to next tick as needed by price movement\n    /// @param self The mapping containing all tick information for initialized ticks\n    /// @param tick The destination tick of the transition\n    /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0\n    /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1\n    /// @param secondsPerLiquidityCumulativeX128 The current seconds per liquidity\n    /// @param tickCumulative The tick * time elapsed since the pool was first initialized\n    /// @param time The current block.timestamp\n    /// @return liquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left)\n    function cross(\n        mapping(int24 => Tick.Info) storage self,\n        int24 tick,\n        uint256 feeGrowthGlobal0X128,\n        uint256 feeGrowthGlobal1X128,\n        uint160 secondsPerLiquidityCumulativeX128,\n        int56 tickCumulative,\n        uint32 time\n    ) internal returns (int128 liquidityNet) {\n        Tick.Info storage info = self[tick];\n        info.feeGrowthOutside0X128 = feeGrowthGlobal0X128 - info.feeGrowthOutside0X128;\n        info.feeGrowthOutside1X128 = feeGrowthGlobal1X128 - info.feeGrowthOutside1X128;\n        info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128 - info.secondsPerLiquidityOutsideX128;\n        info.tickCumulativeOutside = tickCumulative - info.tickCumulativeOutside;\n        info.secondsOutside = time - info.secondsOutside;\n        liquidityNet = info.liquidityNet;\n    }\n}\n"
      },
      "contracts/libraries/TickBitmap.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport './BitMath.sol';\n\n/// @title Packed tick initialized state library\n/// @notice Stores a packed mapping of tick index to its initialized state\n/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.\nlibrary TickBitmap {\n    /// @notice Computes the position in the mapping where the initialized bit for a tick lives\n    /// @param tick The tick for which to compute the position\n    /// @return wordPos The key in the mapping containing the word in which the bit is stored\n    /// @return bitPos The bit position in the word where the flag is stored\n    function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {\n        wordPos = int16(tick >> 8);\n        bitPos = uint8(tick % 256);\n    }\n\n    /// @notice Flips the initialized state for a given tick from false to true, or vice versa\n    /// @param self The mapping in which to flip the tick\n    /// @param tick The tick to flip\n    /// @param tickSpacing The spacing between usable ticks\n    function flipTick(\n        mapping(int16 => uint256) storage self,\n        int24 tick,\n        int24 tickSpacing\n    ) internal {\n        require(tick % tickSpacing == 0); // ensure that the tick is spaced\n        (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing);\n        uint256 mask = 1 << bitPos;\n        self[wordPos] ^= mask;\n    }\n\n    /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either\n    /// to the left (less than or equal to) or right (greater than) of the given tick\n    /// @param self The mapping in which to compute the next initialized tick\n    /// @param tick The starting tick\n    /// @param tickSpacing The spacing between usable ticks\n    /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)\n    /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick\n    /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks\n    function nextInitializedTickWithinOneWord(\n        mapping(int16 => uint256) storage self,\n        int24 tick,\n        int24 tickSpacing,\n        bool lte\n    ) internal view returns (int24 next, bool initialized) {\n        int24 compressed = tick / tickSpacing;\n        if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity\n\n        if (lte) {\n            (int16 wordPos, uint8 bitPos) = position(compressed);\n            // all the 1s at or to the right of the current bitPos\n            uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);\n            uint256 masked = self[wordPos] & mask;\n\n            // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word\n            initialized = masked != 0;\n            // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n            next = initialized\n                ? (compressed - int24(bitPos - BitMath.mostSignificantBit(masked))) * tickSpacing\n                : (compressed - int24(bitPos)) * tickSpacing;\n        } else {\n            // start from the word of the next tick, since the current tick state doesn't matter\n            (int16 wordPos, uint8 bitPos) = position(compressed + 1);\n            // all the 1s at or to the left of the bitPos\n            uint256 mask = ~((1 << bitPos) - 1);\n            uint256 masked = self[wordPos] & mask;\n\n            // if there are no initialized ticks to the left of the current tick, return leftmost in the word\n            initialized = masked != 0;\n            // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n            next = initialized\n                ? (compressed + 1 + int24(BitMath.leastSignificantBit(masked) - bitPos)) * tickSpacing\n                : (compressed + 1 + int24(type(uint8).max - bitPos)) * tickSpacing;\n        }\n    }\n}\n"
      },
      "contracts/libraries/TickMath.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0 <0.8.0;\n\n/// @title Math library for computing sqrt prices from ticks and vice versa\n/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports\n/// prices between 2**-128 and 2**128\nlibrary TickMath {\n    /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128\n    int24 internal constant MIN_TICK = -887272;\n    /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128\n    int24 internal constant MAX_TICK = -MIN_TICK;\n\n    /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)\n    uint160 internal constant MIN_SQRT_RATIO = 4295128739;\n    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)\n    uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;\n\n    /// @notice Calculates sqrt(1.0001^tick) * 2^96\n    /// @dev Throws if |tick| > max tick\n    /// @param tick The input tick for the above formula\n    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)\n    /// at the given tick\n    function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {\n        uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));\n        require(absTick <= uint256(MAX_TICK), 'T');\n\n        uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;\n        if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;\n        if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;\n        if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;\n        if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;\n        if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;\n        if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;\n        if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;\n        if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;\n        if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;\n        if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;\n        if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;\n        if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;\n        if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;\n        if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;\n        if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;\n        if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;\n        if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;\n        if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;\n        if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;\n\n        if (tick > 0) ratio = type(uint256).max / ratio;\n\n        // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.\n        // we then downcast because we know the result always fits within 160 bits due to our tick input constraint\n        // we round up in the division so getTickAtSqrtRatio of the output price is always consistent\n        sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));\n    }\n\n    /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio\n    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may\n    /// ever return.\n    /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96\n    /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio\n    function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {\n        // second inequality must be < because the price can never reach the price at the max tick\n        require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');\n        uint256 ratio = uint256(sqrtPriceX96) << 32;\n\n        uint256 r = ratio;\n        uint256 msb = 0;\n\n        assembly {\n            let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))\n            msb := or(msb, f)\n            r := shr(f, r)\n        }\n        assembly {\n            let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))\n            msb := or(msb, f)\n            r := shr(f, r)\n        }\n        assembly {\n            let f := shl(5, gt(r, 0xFFFFFFFF))\n            msb := or(msb, f)\n            r := shr(f, r)\n        }\n        assembly {\n            let f := shl(4, gt(r, 0xFFFF))\n            msb := or(msb, f)\n            r := shr(f, r)\n        }\n        assembly {\n            let f := shl(3, gt(r, 0xFF))\n            msb := or(msb, f)\n            r := shr(f, r)\n        }\n        assembly {\n            let f := shl(2, gt(r, 0xF))\n            msb := or(msb, f)\n            r := shr(f, r)\n        }\n        assembly {\n            let f := shl(1, gt(r, 0x3))\n            msb := or(msb, f)\n            r := shr(f, r)\n        }\n        assembly {\n            let f := gt(r, 0x1)\n            msb := or(msb, f)\n        }\n\n        if (msb >= 128) r = ratio >> (msb - 127);\n        else r = ratio << (127 - msb);\n\n        int256 log_2 = (int256(msb) - 128) << 64;\n\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(63, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(62, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(61, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(60, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(59, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(58, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(57, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(56, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(55, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(54, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(53, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(52, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(51, f))\n            r := shr(f, r)\n        }\n        assembly {\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(50, f))\n        }\n\n        int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number\n\n        int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);\n        int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);\n\n        tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;\n    }\n}\n"
      },
      "contracts/libraries/TransferHelper.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport '../interfaces/IERC20Minimal.sol';\n\n/// @title TransferHelper\n/// @notice Contains helper methods for interacting with ERC20 tokens that do not consistently return true/false\nlibrary TransferHelper {\n    /// @notice Transfers tokens from msg.sender to a recipient\n    /// @dev Calls transfer on token contract, errors with TF if transfer fails\n    /// @param token The contract address of the token which will be transferred\n    /// @param to The recipient of the transfer\n    /// @param value The value of the transfer\n    function safeTransfer(\n        address token,\n        address to,\n        uint256 value\n    ) internal {\n        (bool success, bytes memory data) = token.call(\n            abi.encodeWithSelector(IERC20Minimal.transfer.selector, to, value)\n        );\n        require(success && (data.length == 0 || abi.decode(data, (bool))), 'TF');\n    }\n}\n"
      },
      "contracts/libraries/UnsafeMath.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Math functions that do not check inputs or outputs\n/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks\nlibrary UnsafeMath {\n    /// @notice Returns ceil(x / y)\n    /// @dev division by 0 has unspecified behavior, and must be checked externally\n    /// @param x The dividend\n    /// @param y The divisor\n    /// @return z The quotient, ceil(x / y)\n    function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        assembly {\n            z := add(div(x, y), gt(mod(x, y), 0))\n        }\n    }\n}\n"
      },
      "contracts/PancakeV3Pool.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity =0.7.6;\n\nimport './interfaces/IPancakeV3Pool.sol';\n\nimport './libraries/LowGasSafeMath.sol';\nimport './libraries/SafeCast.sol';\nimport './libraries/Tick.sol';\nimport './libraries/TickBitmap.sol';\nimport './libraries/Position.sol';\nimport './libraries/Oracle.sol';\n\nimport './libraries/FullMath.sol';\nimport './libraries/FixedPoint128.sol';\nimport './libraries/TransferHelper.sol';\nimport './libraries/TickMath.sol';\nimport './libraries/LiquidityMath.sol';\nimport './libraries/SqrtPriceMath.sol';\nimport './libraries/SwapMath.sol';\n\nimport './interfaces/IPancakeV3PoolDeployer.sol';\nimport './interfaces/IPancakeV3Factory.sol';\nimport './interfaces/IERC20Minimal.sol';\nimport './interfaces/callback/IPancakeV3MintCallback.sol';\nimport './interfaces/callback/IPancakeV3SwapCallback.sol';\nimport './interfaces/callback/IPancakeV3FlashCallback.sol';\n\nimport '@pancakeswap/v3-lm-pool/contracts/interfaces/IPancakeV3LmPool.sol';\n\ncontract PancakeV3Pool is IPancakeV3Pool {\n    using LowGasSafeMath for uint256;\n    using LowGasSafeMath for int256;\n    using SafeCast for uint256;\n    using SafeCast for int256;\n    using Tick for mapping(int24 => Tick.Info);\n    using TickBitmap for mapping(int16 => uint256);\n    using Position for mapping(bytes32 => Position.Info);\n    using Position for Position.Info;\n    using Oracle for Oracle.Observation[65535];\n\n    /// @inheritdoc IPancakeV3PoolImmutables\n    address public immutable override factory;\n    /// @inheritdoc IPancakeV3PoolImmutables\n    address public immutable override token0;\n    /// @inheritdoc IPancakeV3PoolImmutables\n    address public immutable override token1;\n    /// @inheritdoc IPancakeV3PoolImmutables\n    uint24 public immutable override fee;\n\n    /// @inheritdoc IPancakeV3PoolImmutables\n    int24 public immutable override tickSpacing;\n\n    /// @inheritdoc IPancakeV3PoolImmutables\n    uint128 public immutable override maxLiquidityPerTick;\n\n    uint32  internal constant PROTOCOL_FEE_SP = 65536;\n\n    uint256 internal constant PROTOCOL_FEE_DENOMINATOR = 10000;\n\n    struct Slot0 {\n        // the current price\n        uint160 sqrtPriceX96;\n        // the current tick\n        int24 tick;\n        // the most-recently updated index of the observations array\n        uint16 observationIndex;\n        // the current maximum number of observations that are being stored\n        uint16 observationCardinality;\n        // the next maximum number of observations to store, triggered in observations.write\n        uint16 observationCardinalityNext;\n        // the current protocol fee for token0 and token1,\n        // 2 uint32 values store in a uint32 variable (fee/PROTOCOL_FEE_DENOMINATOR)\n        uint32 feeProtocol;\n        // whether the pool is locked\n        bool unlocked;\n    }\n    /// @inheritdoc IPancakeV3PoolState\n    Slot0 public override slot0;\n\n    /// @inheritdoc IPancakeV3PoolState\n    uint256 public override feeGrowthGlobal0X128;\n    /// @inheritdoc IPancakeV3PoolState\n    uint256 public override feeGrowthGlobal1X128;\n\n    // accumulated protocol fees in token0/token1 units\n    struct ProtocolFees {\n        uint128 token0;\n        uint128 token1;\n    }\n    /// @inheritdoc IPancakeV3PoolState\n    ProtocolFees public override protocolFees;\n\n    /// @inheritdoc IPancakeV3PoolState\n    uint128 public override liquidity;\n\n    /// @inheritdoc IPancakeV3PoolState\n    mapping(int24 => Tick.Info) public override ticks;\n    /// @inheritdoc IPancakeV3PoolState\n    mapping(int16 => uint256) public override tickBitmap;\n    /// @inheritdoc IPancakeV3PoolState\n    mapping(bytes32 => Position.Info) public override positions;\n    /// @inheritdoc IPancakeV3PoolState\n    Oracle.Observation[65535] public override observations;\n\n    // liquidity mining\n    IPancakeV3LmPool public lmPool;\n\n    event SetLmPoolEvent(address addr);\n\n    /// @dev Mutually exclusive reentrancy protection into the pool to/from a method. This method also prevents entrance\n    /// to a function before the pool is initialized. The reentrancy guard is required throughout the contract because\n    /// we use balance checks to determine the payment status of interactions such as mint, swap and flash.\n    modifier lock() {\n        require(slot0.unlocked, 'LOK');\n        slot0.unlocked = false;\n        _;\n        slot0.unlocked = true;\n    }\n\n    /// @dev Prevents calling a function from anyone except the factory or its\n    /// owner\n    modifier onlyFactoryOrFactoryOwner() {\n        require(msg.sender == factory || msg.sender == IPancakeV3Factory(factory).owner());\n        _;\n    }\n\n    constructor() {\n        int24 _tickSpacing;\n        (factory, token0, token1, fee, _tickSpacing) = IPancakeV3PoolDeployer(msg.sender).parameters();\n        tickSpacing = _tickSpacing;\n\n        maxLiquidityPerTick = Tick.tickSpacingToMaxLiquidityPerTick(_tickSpacing);\n    }\n\n    /// @dev Common checks for valid tick inputs.\n    function checkTicks(int24 tickLower, int24 tickUpper) private pure {\n        require(tickLower < tickUpper, 'TLU');\n        require(tickLower >= TickMath.MIN_TICK, 'TLM');\n        require(tickUpper <= TickMath.MAX_TICK, 'TUM');\n    }\n\n    /// @dev Returns the block timestamp truncated to 32 bits, i.e. mod 2**32. This method is overridden in tests.\n    function _blockTimestamp() internal view virtual returns (uint32) {\n        return uint32(block.timestamp); // truncation is desired\n    }\n\n    /// @dev Get the pool's balance of token0\n    /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize\n    /// check\n    function balance0() private view returns (uint256) {\n        (bool success, bytes memory data) = token0.staticcall(\n            abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this))\n        );\n        require(success && data.length >= 32);\n        return abi.decode(data, (uint256));\n    }\n\n    /// @dev Get the pool's balance of token1\n    /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize\n    /// check\n    function balance1() private view returns (uint256) {\n        (bool success, bytes memory data) = token1.staticcall(\n            abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this))\n        );\n        require(success && data.length >= 32);\n        return abi.decode(data, (uint256));\n    }\n\n    /// @inheritdoc IPancakeV3PoolDerivedState\n    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)\n        external\n        view\n        override\n        returns (\n            int56 tickCumulativeInside,\n            uint160 secondsPerLiquidityInsideX128,\n            uint32 secondsInside\n        )\n    {\n        checkTicks(tickLower, tickUpper);\n\n        int56 tickCumulativeLower;\n        int56 tickCumulativeUpper;\n        uint160 secondsPerLiquidityOutsideLowerX128;\n        uint160 secondsPerLiquidityOutsideUpperX128;\n        uint32 secondsOutsideLower;\n        uint32 secondsOutsideUpper;\n\n        {\n            Tick.Info storage lower = ticks[tickLower];\n            Tick.Info storage upper = ticks[tickUpper];\n            bool initializedLower;\n            (tickCumulativeLower, secondsPerLiquidityOutsideLowerX128, secondsOutsideLower, initializedLower) = (\n                lower.tickCumulativeOutside,\n                lower.secondsPerLiquidityOutsideX128,\n                lower.secondsOutside,\n                lower.initialized\n            );\n            require(initializedLower);\n\n            bool initializedUpper;\n            (tickCumulativeUpper, secondsPerLiquidityOutsideUpperX128, secondsOutsideUpper, initializedUpper) = (\n                upper.tickCumulativeOutside,\n                upper.secondsPerLiquidityOutsideX128,\n                upper.secondsOutside,\n                upper.initialized\n            );\n            require(initializedUpper);\n        }\n\n        Slot0 memory _slot0 = slot0;\n\n        if (_slot0.tick < tickLower) {\n            return (\n                tickCumulativeLower - tickCumulativeUpper,\n                secondsPerLiquidityOutsideLowerX128 - secondsPerLiquidityOutsideUpperX128,\n                secondsOutsideLower - secondsOutsideUpper\n            );\n        } else if (_slot0.tick < tickUpper) {\n            uint32 time = _blockTimestamp();\n            (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) = observations.observeSingle(\n                time,\n                0,\n                _slot0.tick,\n                _slot0.observationIndex,\n                liquidity,\n                _slot0.observationCardinality\n            );\n            return (\n                tickCumulative - tickCumulativeLower - tickCumulativeUpper,\n                secondsPerLiquidityCumulativeX128 -\n                    secondsPerLiquidityOutsideLowerX128 -\n                    secondsPerLiquidityOutsideUpperX128,\n                time - secondsOutsideLower - secondsOutsideUpper\n            );\n        } else {\n            return (\n                tickCumulativeUpper - tickCumulativeLower,\n                secondsPerLiquidityOutsideUpperX128 - secondsPerLiquidityOutsideLowerX128,\n                secondsOutsideUpper - secondsOutsideLower\n            );\n        }\n    }\n\n    /// @inheritdoc IPancakeV3PoolDerivedState\n    function observe(uint32[] calldata secondsAgos)\n        external\n        view\n        override\n        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)\n    {\n        return\n            observations.observe(\n                _blockTimestamp(),\n                secondsAgos,\n                slot0.tick,\n                slot0.observationIndex,\n                liquidity,\n                slot0.observationCardinality\n            );\n    }\n\n    /// @inheritdoc IPancakeV3PoolActions\n    function increaseObservationCardinalityNext(uint16 observationCardinalityNext)\n        external\n        override\n        lock\n    {\n        uint16 observationCardinalityNextOld = slot0.observationCardinalityNext; // for the event\n        uint16 observationCardinalityNextNew = observations.grow(\n            observationCardinalityNextOld,\n            observationCardinalityNext\n        );\n        slot0.observationCardinalityNext = observationCardinalityNextNew;\n        if (observationCardinalityNextOld != observationCardinalityNextNew)\n            emit IncreaseObservationCardinalityNext(observationCardinalityNextOld, observationCardinalityNextNew);\n    }\n\n    /// @inheritdoc IPancakeV3PoolActions\n    /// @dev not locked because it initializes unlocked\n    function initialize(uint160 sqrtPriceX96) external override {\n        require(slot0.sqrtPriceX96 == 0, 'AI');\n\n        int24 tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96);\n\n        (uint16 cardinality, uint16 cardinalityNext) = observations.initialize(_blockTimestamp());\n\n        slot0 = Slot0({\n            sqrtPriceX96: sqrtPriceX96,\n            tick: tick,\n            observationIndex: 0,\n            observationCardinality: cardinality,\n            observationCardinalityNext: cardinalityNext,\n            feeProtocol: 209718400, // default value for all pools, 3200:3200, store 2 uint32 inside\n            unlocked: true\n        });\n\n        if (fee == 100) {\n            slot0.feeProtocol = 216272100; // value for 3300:3300, store 2 uint32 inside\n        } else if (fee == 500) {\n            slot0.feeProtocol = 222825800; // value for 3400:3400, store 2 uint32 inside\n        } else if (fee == 2500) {\n            slot0.feeProtocol = 209718400; // value for 3200:3200, store 2 uint32 inside\n        } else if (fee == 10000) {\n            slot0.feeProtocol = 209718400; // value for 3200:3200, store 2 uint32 inside\n        }\n\n        emit Initialize(sqrtPriceX96, tick);\n    }\n\n    struct ModifyPositionParams {\n        // the address that owns the position\n        address owner;\n        // the lower and upper tick of the position\n        int24 tickLower;\n        int24 tickUpper;\n        // any change in liquidity\n        int128 liquidityDelta;\n    }\n\n    /// @dev Effect some changes to a position\n    /// @param params the position details and the change to the position's liquidity to effect\n    /// @return position a storage pointer referencing the position with the given owner and tick range\n    /// @return amount0 the amount of token0 owed to the pool, negative if the pool should pay the recipient\n    /// @return amount1 the amount of token1 owed to the pool, negative if the pool should pay the recipient\n    function _modifyPosition(ModifyPositionParams memory params)\n        private\n        returns (\n            Position.Info storage position,\n            int256 amount0,\n            int256 amount1\n        )\n    {\n        checkTicks(params.tickLower, params.tickUpper);\n\n        Slot0 memory _slot0 = slot0; // SLOAD for gas optimization\n\n        position = _updatePosition(\n            params.owner,\n            params.tickLower,\n            params.tickUpper,\n            params.liquidityDelta,\n            _slot0.tick\n        );\n\n        if (params.liquidityDelta != 0) {\n            if (_slot0.tick < params.tickLower) {\n                // current tick is below the passed range; liquidity can only become in range by crossing from left to\n                // right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it\n                amount0 = SqrtPriceMath.getAmount0Delta(\n                    TickMath.getSqrtRatioAtTick(params.tickLower),\n                    TickMath.getSqrtRatioAtTick(params.tickUpper),\n                    params.liquidityDelta\n                );\n            } else if (_slot0.tick < params.tickUpper) {\n                // current tick is inside the passed range\n                uint128 liquidityBefore = liquidity; // SLOAD for gas optimization\n\n                // write an oracle entry\n                (slot0.observationIndex, slot0.observationCardinality) = observations.write(\n                    _slot0.observationIndex,\n                    _blockTimestamp(),\n                    _slot0.tick,\n                    liquidityBefore,\n                    _slot0.observationCardinality,\n                    _slot0.observationCardinalityNext\n                );\n\n                amount0 = SqrtPriceMath.getAmount0Delta(\n                    _slot0.sqrtPriceX96,\n                    TickMath.getSqrtRatioAtTick(params.tickUpper),\n                    params.liquidityDelta\n                );\n                amount1 = SqrtPriceMath.getAmount1Delta(\n                    TickMath.getSqrtRatioAtTick(params.tickLower),\n                    _slot0.sqrtPriceX96,\n                    params.liquidityDelta\n                );\n\n                liquidity = LiquidityMath.addDelta(liquidityBefore, params.liquidityDelta);\n            } else {\n                // current tick is above the passed range; liquidity can only become in range by crossing from right to\n                // left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it\n                amount1 = SqrtPriceMath.getAmount1Delta(\n                    TickMath.getSqrtRatioAtTick(params.tickLower),\n                    TickMath.getSqrtRatioAtTick(params.tickUpper),\n                    params.liquidityDelta\n                );\n            }\n        }\n    }\n\n    /// @dev Gets and updates a position with the given liquidity delta\n    /// @param owner the owner of the position\n    /// @param tickLower the lower tick of the position's tick range\n    /// @param tickUpper the upper tick of the position's tick range\n    /// @param tick the current tick, passed to avoid sloads\n    function _updatePosition(\n        address owner,\n        int24 tickLower,\n        int24 tickUpper,\n        int128 liquidityDelta,\n        int24 tick\n    ) private returns (Position.Info storage position) {\n        position = positions.get(owner, tickLower, tickUpper);\n\n        uint256 _feeGrowthGlobal0X128 = feeGrowthGlobal0X128; // SLOAD for gas optimization\n        uint256 _feeGrowthGlobal1X128 = feeGrowthGlobal1X128; // SLOAD for gas optimization\n\n        // if we need to update the ticks, do it\n        bool flippedLower;\n        bool flippedUpper;\n        if (liquidityDelta != 0) {\n            uint32 time = _blockTimestamp();\n            (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) = observations.observeSingle(\n                time,\n                0,\n                slot0.tick,\n                slot0.observationIndex,\n                liquidity,\n                slot0.observationCardinality\n            );\n\n            flippedLower = ticks.update(\n                tickLower,\n                tick,\n                liquidityDelta,\n                _feeGrowthGlobal0X128,\n                _feeGrowthGlobal1X128,\n                secondsPerLiquidityCumulativeX128,\n                tickCumulative,\n                time,\n                false,\n                maxLiquidityPerTick\n            );\n            flippedUpper = ticks.update(\n                tickUpper,\n                tick,\n                liquidityDelta,\n                _feeGrowthGlobal0X128,\n                _feeGrowthGlobal1X128,\n                secondsPerLiquidityCumulativeX128,\n                tickCumulative,\n                time,\n                true,\n                maxLiquidityPerTick\n            );\n\n            if (flippedLower) {\n                tickBitmap.flipTick(tickLower, tickSpacing);\n            }\n            if (flippedUpper) {\n                tickBitmap.flipTick(tickUpper, tickSpacing);\n            }\n        }\n\n        (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = ticks.getFeeGrowthInside(\n            tickLower,\n            tickUpper,\n            tick,\n            _feeGrowthGlobal0X128,\n            _feeGrowthGlobal1X128\n        );\n\n        position.update(liquidityDelta, feeGrowthInside0X128, feeGrowthInside1X128);\n\n        // clear any tick data that is no longer needed\n        if (liquidityDelta < 0) {\n            if (flippedLower) {\n                ticks.clear(tickLower);\n            }\n            if (flippedUpper) {\n                ticks.clear(tickUpper);\n            }\n        }\n    }\n\n    /// @inheritdoc IPancakeV3PoolActions\n    /// @dev noDelegateCall is applied indirectly via _modifyPosition\n    function mint(\n        address recipient,\n        int24 tickLower,\n        int24 tickUpper,\n        uint128 amount,\n        bytes calldata data\n    ) external override lock returns (uint256 amount0, uint256 amount1) {\n        require(amount > 0);\n        (, int256 amount0Int, int256 amount1Int) = _modifyPosition(\n            ModifyPositionParams({\n                owner: recipient,\n                tickLower: tickLower,\n                tickUpper: tickUpper,\n                liquidityDelta: int256(amount).toInt128()\n            })\n        );\n\n        amount0 = uint256(amount0Int);\n        amount1 = uint256(amount1Int);\n\n        uint256 balance0Before;\n        uint256 balance1Before;\n        if (amount0 > 0) balance0Before = balance0();\n        if (amount1 > 0) balance1Before = balance1();\n        IPancakeV3MintCallback(msg.sender).pancakeV3MintCallback(amount0, amount1, data);\n        if (amount0 > 0) require(balance0Before.add(amount0) <= balance0(), 'M0');\n        if (amount1 > 0) require(balance1Before.add(amount1) <= balance1(), 'M1');\n\n        emit Mint(msg.sender, recipient, tickLower, tickUpper, amount, amount0, amount1);\n    }\n\n    /// @inheritdoc IPancakeV3PoolActions\n    function collect(\n        address recipient,\n        int24 tickLower,\n        int24 tickUpper,\n        uint128 amount0Requested,\n        uint128 amount1Requested\n    ) external override lock returns (uint128 amount0, uint128 amount1) {\n        // we don't need to checkTicks here, because invalid positions will never have non-zero tokensOwed{0,1}\n        Position.Info storage position = positions.get(msg.sender, tickLower, tickUpper);\n\n        amount0 = amount0Requested > position.tokensOwed0 ? position.tokensOwed0 : amount0Requested;\n        amount1 = amount1Requested > position.tokensOwed1 ? position.tokensOwed1 : amount1Requested;\n\n        if (amount0 > 0) {\n            position.tokensOwed0 -= amount0;\n            TransferHelper.safeTransfer(token0, recipient, amount0);\n        }\n        if (amount1 > 0) {\n            position.tokensOwed1 -= amount1;\n            TransferHelper.safeTransfer(token1, recipient, amount1);\n        }\n\n        emit Collect(msg.sender, recipient, tickLower, tickUpper, amount0, amount1);\n    }\n\n    /// @inheritdoc IPancakeV3PoolActions\n    /// @dev noDelegateCall is applied indirectly via _modifyPosition\n    function burn(\n        int24 tickLower,\n        int24 tickUpper,\n        uint128 amount\n    ) external override lock returns (uint256 amount0, uint256 amount1) {\n        (Position.Info storage position, int256 amount0Int, int256 amount1Int) = _modifyPosition(\n            ModifyPositionParams({\n                owner: msg.sender,\n                tickLower: tickLower,\n                tickUpper: tickUpper,\n                liquidityDelta: -int256(amount).toInt128()\n            })\n        );\n\n        amount0 = uint256(-amount0Int);\n        amount1 = uint256(-amount1Int);\n\n        if (amount0 > 0 || amount1 > 0) {\n            (position.tokensOwed0, position.tokensOwed1) = (\n                position.tokensOwed0 + uint128(amount0),\n                position.tokensOwed1 + uint128(amount1)\n            );\n        }\n\n        emit Burn(msg.sender, tickLower, tickUpper, amount, amount0, amount1);\n    }\n\n    struct SwapCache {\n        // the protocol fee for the input token\n        uint32 feeProtocol;\n        // liquidity at the beginning of the swap\n        uint128 liquidityStart;\n        // the timestamp of the current block\n        uint32 blockTimestamp;\n        // the current value of the tick accumulator, computed only if we cross an initialized tick\n        int56 tickCumulative;\n        // the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick\n        uint160 secondsPerLiquidityCumulativeX128;\n        // whether we've computed and cached the above two accumulators\n        bool computedLatestObservation;\n    }\n\n    // the top level state of the swap, the results of which are recorded in storage at the end\n    struct SwapState {\n        // the amount remaining to be swapped in/out of the input/output asset\n        int256 amountSpecifiedRemaining;\n        // the amount already swapped out/in of the output/input asset\n        int256 amountCalculated;\n        // current sqrt(price)\n        uint160 sqrtPriceX96;\n        // the tick associated with the current price\n        int24 tick;\n        // the global fee growth of the input token\n        uint256 feeGrowthGlobalX128;\n        // amount of input token paid as protocol fee\n        uint128 protocolFee;\n        // the current liquidity in range\n        uint128 liquidity;\n    }\n\n    struct StepComputations {\n        // the price at the beginning of the step\n        uint160 sqrtPriceStartX96;\n        // the next tick to swap to from the current tick in the swap direction\n        int24 tickNext;\n        // whether tickNext is initialized or not\n        bool initialized;\n        // sqrt(price) for the next tick (1/0)\n        uint160 sqrtPriceNextX96;\n        // how much is being swapped in in this step\n        uint256 amountIn;\n        // how much is being swapped out\n        uint256 amountOut;\n        // how much fee is being paid in\n        uint256 feeAmount;\n    }\n\n    /// @inheritdoc IPancakeV3PoolActions\n    function swap(\n        address recipient,\n        bool zeroForOne,\n        int256 amountSpecified,\n        uint160 sqrtPriceLimitX96,\n        bytes calldata data\n    ) external override returns (int256 amount0, int256 amount1) {\n        require(amountSpecified != 0, 'AS');\n\n        Slot0 memory slot0Start = slot0;\n\n        require(slot0Start.unlocked, 'LOK');\n        require(\n            zeroForOne\n                ? sqrtPriceLimitX96 < slot0Start.sqrtPriceX96 && sqrtPriceLimitX96 > TickMath.MIN_SQRT_RATIO\n                : sqrtPriceLimitX96 > slot0Start.sqrtPriceX96 && sqrtPriceLimitX96 < TickMath.MAX_SQRT_RATIO,\n            'SPL'\n        );\n\n        slot0.unlocked = false;\n\n        SwapCache memory cache = SwapCache({\n            liquidityStart: liquidity,\n            blockTimestamp: _blockTimestamp(),\n            feeProtocol: zeroForOne ? (slot0Start.feeProtocol % PROTOCOL_FEE_SP) : (slot0Start.feeProtocol >> 16),\n            secondsPerLiquidityCumulativeX128: 0,\n            tickCumulative: 0,\n            computedLatestObservation: false\n        });\n\n        if (address(lmPool) != address(0)) {\n          lmPool.accumulateReward(cache.blockTimestamp);\n        }\n\n        bool exactInput = amountSpecified > 0;\n\n        SwapState memory state = SwapState({\n            amountSpecifiedRemaining: amountSpecified,\n            amountCalculated: 0,\n            sqrtPriceX96: slot0Start.sqrtPriceX96,\n            tick: slot0Start.tick,\n            feeGrowthGlobalX128: zeroForOne ? feeGrowthGlobal0X128 : feeGrowthGlobal1X128,\n            protocolFee: 0,\n            liquidity: cache.liquidityStart\n        });\n\n        // continue swapping as long as we haven't used the entire input/output and haven't reached the price limit\n        while (state.amountSpecifiedRemaining != 0 && state.sqrtPriceX96 != sqrtPriceLimitX96) {\n            StepComputations memory step;\n\n            step.sqrtPriceStartX96 = state.sqrtPriceX96;\n\n            (step.tickNext, step.initialized) = tickBitmap.nextInitializedTickWithinOneWord(\n                state.tick,\n                tickSpacing,\n                zeroForOne\n            );\n\n            // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds\n            if (step.tickNext < TickMath.MIN_TICK) {\n                step.tickNext = TickMath.MIN_TICK;\n            } else if (step.tickNext > TickMath.MAX_TICK) {\n                step.tickNext = TickMath.MAX_TICK;\n            }\n\n            // get the price for the next tick\n            step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);\n\n            // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted\n            (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(\n                state.sqrtPriceX96,\n                (zeroForOne ? step.sqrtPriceNextX96 < sqrtPriceLimitX96 : step.sqrtPriceNextX96 > sqrtPriceLimitX96)\n                    ? sqrtPriceLimitX96\n                    : step.sqrtPriceNextX96,\n                state.liquidity,\n                state.amountSpecifiedRemaining,\n                fee\n            );\n\n            if (exactInput) {\n                state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256();\n                state.amountCalculated = state.amountCalculated.sub(step.amountOut.toInt256());\n            } else {\n                state.amountSpecifiedRemaining += step.amountOut.toInt256();\n                state.amountCalculated = state.amountCalculated.add((step.amountIn + step.feeAmount).toInt256());\n            }\n\n            // if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee\n            if (cache.feeProtocol > 0) {\n                uint256 delta = (step.feeAmount.mul(cache.feeProtocol)) / PROTOCOL_FEE_DENOMINATOR;\n                step.feeAmount -= delta;\n                state.protocolFee += uint128(delta);\n            }\n\n            // update global fee tracker\n            if (state.liquidity > 0)\n                state.feeGrowthGlobalX128 += FullMath.mulDiv(step.feeAmount, FixedPoint128.Q128, state.liquidity);\n\n            // shift tick if we reached the next price\n            if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {\n                // if the tick is initialized, run the tick transition\n                if (step.initialized) {\n                    // check for the placeholder value, which we replace with the actual value the first time the swap\n                    // crosses an initialized tick\n                    if (!cache.computedLatestObservation) {\n                        (cache.tickCumulative, cache.secondsPerLiquidityCumulativeX128) = observations.observeSingle(\n                            cache.blockTimestamp,\n                            0,\n                            slot0Start.tick,\n                            slot0Start.observationIndex,\n                            cache.liquidityStart,\n                            slot0Start.observationCardinality\n                        );\n                        cache.computedLatestObservation = true;\n                    }\n\n                    if (address(lmPool) != address(0)) {\n                      lmPool.crossLmTick(step.tickNext, zeroForOne);\n                    }\n\n                    int128 liquidityNet = ticks.cross(\n                        step.tickNext,\n                        (zeroForOne ? state.feeGrowthGlobalX128 : feeGrowthGlobal0X128),\n                        (zeroForOne ? feeGrowthGlobal1X128 : state.feeGrowthGlobalX128),\n                        cache.secondsPerLiquidityCumulativeX128,\n                        cache.tickCumulative,\n                        cache.blockTimestamp\n                    );\n                    // if we're moving leftward, we interpret liquidityNet as the opposite sign\n                    // safe because liquidityNet cannot be type(int128).min\n                    if (zeroForOne) liquidityNet = -liquidityNet;\n\n                    state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);\n                }\n\n                state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;\n            } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {\n                // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved\n                state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);\n            }\n        }\n\n        // update tick and write an oracle entry if the tick change\n        if (state.tick != slot0Start.tick) {\n            (uint16 observationIndex, uint16 observationCardinality) = observations.write(\n                slot0Start.observationIndex,\n                cache.blockTimestamp,\n                slot0Start.tick,\n                cache.liquidityStart,\n                slot0Start.observationCardinality,\n                slot0Start.observationCardinalityNext\n            );\n            (slot0.sqrtPriceX96, slot0.tick, slot0.observationIndex, slot0.observationCardinality) = (\n                state.sqrtPriceX96,\n                state.tick,\n                observationIndex,\n                observationCardinality\n            );\n        } else {\n            // otherwise just update the price\n            slot0.sqrtPriceX96 = state.sqrtPriceX96;\n        }\n\n        // update liquidity if it changed\n        if (cache.liquidityStart != state.liquidity) liquidity = state.liquidity;\n\n        uint128 protocolFeesToken0 = 0;\n        uint128 protocolFeesToken1 = 0;\n\n        // update fee growth global and, if necessary, protocol fees\n        // overflow is acceptable, protocol has to withdraw before it hits type(uint128).max fees\n        if (zeroForOne) {\n            feeGrowthGlobal0X128 = state.feeGrowthGlobalX128;\n            if (state.protocolFee > 0) protocolFees.token0 += state.protocolFee;\n            protocolFeesToken0 = state.protocolFee;\n        } else {\n            feeGrowthGlobal1X128 = state.feeGrowthGlobalX128;\n            if (state.protocolFee > 0) protocolFees.token1 += state.protocolFee;\n            protocolFeesToken1 = state.protocolFee;\n        }\n\n        (amount0, amount1) = zeroForOne == exactInput\n            ? (amountSpecified - state.amountSpecifiedRemaining, state.amountCalculated)\n            : (state.amountCalculated, amountSpecified - state.amountSpecifiedRemaining);\n\n        // do the transfers and collect payment\n        if (zeroForOne) {\n            if (amount1 < 0) TransferHelper.safeTransfer(token1, recipient, uint256(-amount1));\n\n            uint256 balance0Before = balance0();\n            IPancakeV3SwapCallback(msg.sender).pancakeV3SwapCallback(amount0, amount1, data);\n            require(balance0Before.add(uint256(amount0)) <= balance0(), 'IIA');\n        } else {\n            if (amount0 < 0) TransferHelper.safeTransfer(token0, recipient, uint256(-amount0));\n\n            uint256 balance1Before = balance1();\n            IPancakeV3SwapCallback(msg.sender).pancakeV3SwapCallback(amount0, amount1, data);\n            require(balance1Before.add(uint256(amount1)) <= balance1(), 'IIA');\n        }\n\n        emit Swap(msg.sender, recipient, amount0, amount1, state.sqrtPriceX96, state.liquidity, state.tick, protocolFeesToken0, protocolFeesToken1);\n        slot0.unlocked = true;\n    }\n\n    /// @inheritdoc IPancakeV3PoolActions\n    function flash(\n        address recipient,\n        uint256 amount0,\n        uint256 amount1,\n        bytes calldata data\n    ) external override lock {\n        uint128 _liquidity = liquidity;\n        require(_liquidity > 0, 'L');\n\n        uint256 fee0 = FullMath.mulDivRoundingUp(amount0, fee, 1e6);\n        uint256 fee1 = FullMath.mulDivRoundingUp(amount1, fee, 1e6);\n        uint256 balance0Before = balance0();\n        uint256 balance1Before = balance1();\n\n        if (amount0 > 0) TransferHelper.safeTransfer(token0, recipient, amount0);\n        if (amount1 > 0) TransferHelper.safeTransfer(token1, recipient, amount1);\n\n        IPancakeV3FlashCallback(msg.sender).pancakeV3FlashCallback(fee0, fee1, data);\n\n        uint256 balance0After = balance0();\n        uint256 balance1After = balance1();\n\n        require(balance0Before.add(fee0) <= balance0After, 'F0');\n        require(balance1Before.add(fee1) <= balance1After, 'F1');\n\n        // sub is safe because we know balanceAfter is gt balanceBefore by at least fee\n        uint256 paid0 = balance0After - balance0Before;\n        uint256 paid1 = balance1After - balance1Before;\n\n        if (paid0 > 0) {\n            uint32 feeProtocol0 = slot0.feeProtocol % PROTOCOL_FEE_SP;\n            uint256 fees0 = feeProtocol0 == 0 ? 0 : (paid0 * feeProtocol0) / PROTOCOL_FEE_DENOMINATOR;\n            if (uint128(fees0) > 0) protocolFees.token0 += uint128(fees0);\n            feeGrowthGlobal0X128 += FullMath.mulDiv(paid0 - fees0, FixedPoint128.Q128, _liquidity);\n        }\n        if (paid1 > 0) {\n            uint32 feeProtocol1 = slot0.feeProtocol >> 16;\n            uint256 fees1 = feeProtocol1 == 0 ? 0 : (paid1 * feeProtocol1) / PROTOCOL_FEE_DENOMINATOR;\n            if (uint128(fees1) > 0) protocolFees.token1 += uint128(fees1);\n            feeGrowthGlobal1X128 += FullMath.mulDiv(paid1 - fees1, FixedPoint128.Q128, _liquidity);\n        }\n\n        emit Flash(msg.sender, recipient, amount0, amount1, paid0, paid1);\n    }\n\n    /// @inheritdoc IPancakeV3PoolOwnerActions\n    function setFeeProtocol(uint32 feeProtocol0, uint32 feeProtocol1) external override lock onlyFactoryOrFactoryOwner {\n        require(\n            (feeProtocol0 == 0 || (feeProtocol0 >= 1000 && feeProtocol0 <= 4000)) &&\n            (feeProtocol1 == 0 || (feeProtocol1 >= 1000 && feeProtocol1 <= 4000))\n        );\n\n        uint32 feeProtocolOld = slot0.feeProtocol;\n        slot0.feeProtocol = feeProtocol0 + (feeProtocol1 << 16);\n        emit SetFeeProtocol(feeProtocolOld % PROTOCOL_FEE_SP, feeProtocolOld >> 16, feeProtocol0, feeProtocol1);\n    }\n\n    /// @inheritdoc IPancakeV3PoolOwnerActions\n    function collectProtocol(\n        address recipient,\n        uint128 amount0Requested,\n        uint128 amount1Requested\n    ) external override lock onlyFactoryOrFactoryOwner returns (uint128 amount0, uint128 amount1) {\n        amount0 = amount0Requested > protocolFees.token0 ? protocolFees.token0 : amount0Requested;\n        amount1 = amount1Requested > protocolFees.token1 ? protocolFees.token1 : amount1Requested;\n\n        if (amount0 > 0) {\n            if (amount0 == protocolFees.token0) amount0--; // ensure that the slot is not cleared, for gas savings\n            protocolFees.token0 -= amount0;\n            TransferHelper.safeTransfer(token0, recipient, amount0);\n        }\n        if (amount1 > 0) {\n            if (amount1 == protocolFees.token1) amount1--; // ensure that the slot is not cleared, for gas savings\n            protocolFees.token1 -= amount1;\n            TransferHelper.safeTransfer(token1, recipient, amount1);\n        }\n\n        emit CollectProtocol(msg.sender, recipient, amount0, amount1);\n    }\n\n    function setLmPool(address _lmPool) external override onlyFactoryOrFactoryOwner {\n      lmPool = IPancakeV3LmPool(_lmPool);\n      emit SetLmPoolEvent(address(_lmPool));\n    }\n}\n"
      }
    },
    "settings": {
      "evmVersion": "istanbul",
      "optimizer": {
        "enabled": true,
        "runs": 400
      },
      "metadata": {
        "bytecodeHash": "none"
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}