{
    "Function": "slitherConstructorConstantVariables",
    "File": "contracts/SemiFungiblePositionManager.sol",
    "Parent Contracts": [
        "contracts/multicall/Multicall.sol",
        "contracts/tokens/ERC1155Minimal.sol"
    ],
    "High-Level Calls": [],
    "Internal Calls": [],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "contract SemiFungiblePositionManager is ERC1155, Multicall {\n    /*//////////////////////////////////////////////////////////////\n                                EVENTS\n    //////////////////////////////////////////////////////////////*/\n\n    /// @notice Emitted when a UniswapV3Pool is initialized.\n    /// @param uniswapPool Address of the underlying Uniswap v3 pool\n    event PoolInitialized(address indexed uniswapPool);\n\n    /// @notice Emitted when a position is destroyed/burned\n    /// @dev Recipient is used to track whether it was burned directly by the user or through an option contract\n    /// @param recipient The address of the user who burned the position\n    /// @param tokenId The tokenId of the burned position\n    /// @param positionSize The number of contracts burnt, expressed in terms of the asset\n    event TokenizedPositionBurnt(\n        address indexed recipient,\n        uint256 indexed tokenId,\n        uint128 positionSize\n    );\n\n    /// @notice Emitted when a position is created/minted\n    /// @dev Recipient is used to track whether it was minted directly by the user or through an option contract\n    /// @param caller the caller who created the position. In 99% of cases `caller` == `recipient`.\n    /// @param tokenId The tokenId of the minted position\n    /// @param positionSize The number of contracts minted, expressed in terms of the asset\n    event TokenizedPositionMinted(\n        address indexed caller,\n        uint256 indexed tokenId,\n        uint128 positionSize\n    );\n\n    /*//////////////////////////////////////////////////////////////\n                                TYPES \n    //////////////////////////////////////////////////////////////*/\n\n    /// @dev Uses the LeftRight packaging methods for uint256/int256 to store 128bit values\n    using LeftRight for int256;\n    using LeftRight for uint256;\n\n    using TokenId for uint256; // an option position\n    using LiquidityChunk for uint256; // a leg within an option position `tokenId`\n\n    // Packs the pool address and reentrancy lock into a single slot\n    // `locked` can be initialized to false because the pool address makes the slot nonzero\n    // false = unlocked, true = locked\n    struct PoolAddressAndLock {\n        IUniswapV3Pool pool;\n        bool locked;\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                            IMMUTABLES \n    //////////////////////////////////////////////////////////////*/\n\n    /// @dev flag for mint/burn\n    bool internal constant MINT = false;\n    bool internal constant BURN = true;\n\n    // \u03bd = 2**VEGOID = multiplicative factor for long premium (Eqns 1-5)\n    // Similar to vega in options because the liquidity utilization is somewhat reflective of the implied volatility (IV),\n    // and vegoid modifies the sensitivity of the stremia to changes in that utilization,\n    // much like vega measures the sensitivity of traditional option prices to IV.\n    // The effect of vegoid on the long premium multiplier can be explored here: https://www.desmos.com/calculator/mdeqob2m04\n    uint128 private constant VEGOID = 2;\n\n    /// @dev Uniswap V3 Factory address. Initialized in the constructor.\n    /// @dev used to verify callbacks and to query for the pool address\n    IUniswapV3Factory internal immutable FACTORY;\n\n    /*//////////////////////////////////////////////////////////////\n                            STORAGE \n    //////////////////////////////////////////////////////////////*/\n\n    /// Store the mapping between the poolId and the Uniswap v3 pool - intent is to be 1:1 for all pools\n    /// @dev pool address => pool id + 2 ** 255 (initialization bit for `poolId == 0`, set if the pool exists)\n    mapping(address univ3pool => uint256 poolIdData) internal s_AddrToPoolIdData;\n\n    /// @dev also contains a boolean which is used for the reentrancy lock - saves gas since this slot is often warmed\n    // pool ids are used instead of addresses to save bits in the token id\n    // (there will never be a collision because it's infeasible to mine an address with 8 consecutive bytes)\n    mapping(uint64 poolId => PoolAddressAndLock contextData) internal s_poolContext;\n\n    /** \n        We're tracking the amount of net and removed liquidity for the specific region:\n\n             net amount    \n           received minted  \n          \u25b2 for isLong=0     amount           \n          \u2502                 moved out      actual amount \n          \u2502  \u250c\u2500\u2500\u2500\u2500\u2510-T      due isLong=1   in the UniswapV3Pool \n          \u2502  \u2502    \u2502          mints      \n          \u2502  \u2502    \u2502                        \u250c\u2500\u2500\u2500\u2500\u2510-(T-R)  \n          \u2502  \u2502    \u2502         \u250c\u2500\u2500\u2500\u2500\u2510-R       \u2502    \u2502          \n          \u2502  \u2502    \u2502         \u2502    \u2502         \u2502    \u2502     \n          \u2514\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u25ba                     \n             total=T       removed=R      net=(T-R)\n\n\n     *       removed liquidity r          net liquidity N=(T-R)\n     * |<------- 128 bits ------->|<------- 128 bits ------->|\n     * |<---------------------- 256 bits ------------------->|\n     */\n    ///\n    /// @dev mapping that stores the liquidity data of keccak256(abi.encodePacked(address poolAddress, address owner, int24 tickLower, int24 tickUpper))\n    // liquidityData is a LeftRight. The right slot represents the liquidity currently sold (added) in the AMM owned by the user\n    // the left slot represents the amount of liquidity currently bought (removed) that has been removed from the AMM - the user owes it to a seller\n    // the reason why it is called \"removedLiquidity\" is because long options are created by removed liquidity -ie. short selling LP positions\n    mapping(bytes32 positionKey => uint256 removedAndNetLiquidity) internal s_accountLiquidity;\n\n    /**\n        Any liquidity that has been deposited in the AMM using the SFPM will collect fees over \n        time, we call this the gross premia. If that liquidity has been removed, we also need to\n        keep track of the amount of fees that *would have been collected*, we call this the owed\n        premia. The gross and owed premia are tracked per unit of liquidity by the \n        s_accountPremiumGross and s_accountPremiumOwed accumulators.\n        \n        Here is how we can use the accumulators to compute the Gross, Net, and Owed fees collected\n        by any position.\n\n        Let`s say Charlie the smart contract deposited T into the AMM and later removed R from that\n        same tick using a tokenId with a isLong=1 parameter. Because the netLiquidity is only (T-R),\n        the AMM will collect fees equal to:\n\n              net_feesCollectedX128 = feeGrowthX128 * (T - R)\n                                    = feeGrowthX128 * N                                     \n        \n        where N = netLiquidity = T-R. Had that liquidity never been removed, we want the gross\n        premia to be given by:\n\n              gross_feesCollectedX128 = feeGrowthX128 * T\n\n        So we must keep track of fees for the removed liquidity R so that the long premia exactly\n        compensates for the fees that would have been collected from the initial liquidity.\n\n        In addition to tracking, we also want to track those fees plus a small spread. Specifically,\n        we want:\n\n              gross_feesCollectedX128 = net_feesCollectedX128 + owed_feesCollectedX128\n\n       where \n\n              owed_feesCollectedX128 = feeGrowthX128 * R * (1 + spread)                      (Eqn 1)\n\n        A very opinionated definition for the spread is: \n              \n              spread = \u03bd*(liquidity removed from that strike)/(netLiquidity remaining at that strike)\n                     = \u03bd*R/N\n\n        For an arbitrary parameter 0 <= \u03bd <= 1. This way, the gross_feesCollectedX128 will be given by: \n\n              gross_feesCollectedX128 = feeGrowthX128 * N + feeGrowthX128*R*(1 + \u03bd*R/N) \n                                      = feeGrowthX128 * T + feesGrowthX128*\u03bd*R^2/N         \n                                      = feeGrowthX128 * T * (1 + \u03bd*R^2/(N*T))                (Eqn 2)\n        \n        The s_accountPremiumOwed accumulator tracks the feeGrowthX128 * R * (1 + spread) term\n        per unit of removed liquidity R every time the position touched:\n\n              s_accountPremiumOwed += feeGrowthX128 * R * (1 + \u03bd*R/N) / R\n                                   += feeGrowthX128 * (T - R + \u03bd*R)/N\n                                   += feeGrowthX128 * T/N * (1 - R/T + \u03bd*R/T)\n         \n        Note that the value of feeGrowthX128 can be extracted from the amount of fees collected by\n        the smart contract since the amount of feesCollected is related to feeGrowthX128 according\n        to:\n\n             feesCollected = feesGrowthX128 * (T-R)\n\n        So that we get:\n             \n             feesGrowthX128 = feesCollected/N\n\n        And the accumulator is computed from the amount of collected fees according to:\n             \n             s_accountPremiumOwed += feesCollected * T/N^2 * (1 - R/T + \u03bd*R/T)          (Eqn 3)     \n\n        So, the amount of owed premia for a position of size r minted at time t1 and burnt at \n        time t2 is:\n\n             owedPremia(t1, t2) = (s_accountPremiumOwed_t2-s_accountPremiumOwed_t1) * r\n                                = \u2206feesGrowthX128 * r * T/N * (1 - R/T + \u03bd*R/T)\n                                = \u2206feesGrowthX128 * r * (T - R + \u03bd*R)/N\n                                = \u2206feesGrowthX128 * r * (N + \u03bd*R)/N\n                                = \u2206feesGrowthX128 * r * (1 + \u03bd*R/N)             (same as Eqn 1)\n\n        This way, the amount of premia owed for a position will match Eqn 1 exactly.\n\n        Similarly, the amount of gross fees for the total liquidity is tracked in a similar manner\n        by the s_accountPremiumGross accumulator. \n\n        However, since we require that Eqn 2 holds up-- ie. the gross fees collected should be equal\n        to the net fees collected plus the ower fees plus the small spread, the expression for the\n        s_accountPremiumGross accumulator has to be given by (you`ll see why in a minute): \n\n            s_accountPremiumGross += feesCollected * T/N^2 * (1 - R/T + \u03bd*R^2/T^2)       (Eqn 4) \n\n        This expression can be used to calculate the fees collected by a position of size t between times\n        t1 and t2 according to:\n             \n            grossPremia(t1, t2) = \u2206(s_accountPremiumGross) * t\n                                = \u2206feeGrowthX128 * t * T/N * (1 - R/T + \u03bd*R^2/T^2) \n                                = \u2206feeGrowthX128 * t * (T - R + \u03bd*R^2/T) / N \n                                = \u2206feeGrowthX128 * t * (N + \u03bd*R^2/T) / N\n                                = \u2206feeGrowthX128 * t * (1  + \u03bd*R^2/(N*T))   (same as Eqn 2)\n            \n        where the last expression matches Eqn 2 exactly.\n\n        In summary, the s_accountPremium accumulators allow smart contracts that need to handle \n        long+short liquidity to guarantee that liquidity deposited always receives the correct\n        premia, whether that liquidity has been removed from the AMM or not.\n\n        Note that the expression for the spread is extremely opinionated, and may not fit the\n        specific risk management profile of every smart contract. And simply setting the \u03bd parameter\n        to zero would get rid of the \"spread logic\".\n    */\n\n    // tracking account premia for the added liquidity (isLong=0 legs) and removed liquidity (isLong=1 legs) separately\n    mapping(bytes32 positionKey => uint256 accountPremium) private s_accountPremiumOwed;\n\n    mapping(bytes32 positionKey => uint256 accountPremium) private s_accountPremiumGross;\n\n    /// @dev mapping that stores a LeftRight packing of feesBase of  keccak256(abi.encodePacked(address poolAddress, address owner, int24 tickLower, int24 tickUpper))\n    /// @dev Base fees is stored as int128((feeGrowthInside0LastX128 * liquidity) / 2**128), which allows us to store the accumulated fees as int128 instead of uint256\n    /// @dev Right slot: int128 token0 base fees, Left slot: int128 token1 base fees.\n    /// feesBase represents the baseline fees collected by the position last time it was updated - this is recalculated every time the position is collected from with the new value\n    mapping(bytes32 positionKey => int256 baseFees0And1) internal s_accountFeesBase;\n\n    /*//////////////////////////////////////////////////////////////\n                           REENTRANCY LOCK\n    //////////////////////////////////////////////////////////////*/\n\n    /// @notice Modifier that prohibits reentrant calls for a specific pool\n    /// @dev We piggyback the reentrancy lock on the (pool id => pool) mapping to save gas\n    /// @dev (there's an extra 96 bits of storage available in the mapping slot and it's almost always warm)\n    /// @param poolId The poolId of the pool to activate the reentrancy lock on\n    modifier ReentrancyLock(uint64 poolId) {\n        // check if the pool is already locked\n        // init lock if not\n        beginReentrancyLock(poolId);\n\n        // execute function\n        _;\n\n        // remove lock\n        endReentrancyLock(poolId);\n    }\n\n    /// @notice Add reentrancy lock on pool\n    /// @dev reverts if the pool is already locked\n    /// @param poolId The poolId of the pool to add the reentrancy lock to\n    function beginReentrancyLock(uint64 poolId) internal {\n        // check if the pool is already locked, if so, revert\n        if (s_poolContext[poolId].locked) revert Errors.ReentrantCall();\n\n        // activate lock\n        s_poolContext[poolId].locked = true;\n    }\n\n    /// @notice Remove reentrancy lock on pool\n    /// @param poolId The poolId of the pool to remove the reentrancy lock from\n    function endReentrancyLock(uint64 poolId) internal {\n        // gas refund is triggered here by returning the slot to its original value\n        s_poolContext[poolId].locked = false;\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                            INITIALIZATION\n    //////////////////////////////////////////////////////////////*/\n\n    /// @notice Construct the Semi-Fungible Position Manager (SFPM)\n    /// @param _factory the Uniswap v3 Factory used to retrieve registered Uniswap pools\n    constructor(IUniswapV3Factory _factory) {\n        FACTORY = _factory;\n    }\n\n    /// @notice Initialize a Uniswap v3 pool in the SemifungiblePositionManager contract\n    /// @dev Revert if already initialized.\n    /// @param token0 The contract address of token0 of the pool\n    /// @param token1 The contract address of token1 of the pool\n    /// @param fee The fee level of the of the underlying Uniswap v3 pool, denominated in hundredths of bips\n    function initializeAMMPool(address token0, address token1, uint24 fee) external {\n        // compute the address of the Uniswap v3 pool for the given token0, token1, and fee tier\n        address univ3pool = FACTORY.getPool(token0, token1, fee);\n\n        // reverts if the Uni v3 pool has not been initialized\n        if (address(univ3pool) == address(0)) revert Errors.UniswapPoolNotInitialized();\n\n        // return if the pool has already been initialized in SFPM\n        // @dev pools can be initialized from a Panoptic pool or by calling initializeAMMPool directly, reverting\n        // would prevent any PanopticPool from being deployed\n        // @dev some pools may not be deployable if the poolId has a collision (since we take only 8 bytes)\n        // if poolId == 0, we have a bit on the left set if it was initialized, so this will still return properly\n        if (s_AddrToPoolIdData[univ3pool] != 0) return;\n\n        // Set the base poolId as last 8 bytes of the address (the first 16 hex characters)\n        // @dev in the unlikely case that there is a collision between the first 8 bytes of two different Uni v3 pools\n        // @dev increase the poolId by a pseudo-random number\n        uint64 poolId = PanopticMath.getPoolId(univ3pool);\n\n        while (address(s_poolContext[poolId].pool) != address(0)) {\n            poolId = PanopticMath.getFinalPoolId(poolId, token0, token1, fee);\n        }\n        // store the poolId => UniswapV3Pool information in a mapping\n        // `locked` can be initialized to false because the pool address makes the slot nonzero\n        s_poolContext[poolId] = PoolAddressAndLock({\n            pool: IUniswapV3Pool(univ3pool),\n            locked: false\n        });\n\n        // store the UniswapV3Pool => poolId information in a mapping\n        // add a bit on the end to indicate that the pool is initialized\n        // (this is for the case that poolId == 0, so we can make a distinction between zero and uninitialized)\n        unchecked {\n            s_AddrToPoolIdData[univ3pool] = uint256(poolId) + 2 ** 255;\n        }\n        emit PoolInitialized(univ3pool);\n\n        return;\n\n        // this disables `memoryguard` when compiling this contract via IR\n        // it is classed as a potentially unsafe assembly block by the compiler, but is in fact safe\n        // we need this because enabling `memoryguard` and therefore StackLimitEvader increases the size of the contract significantly beyond the size limit\n        assembly {\n            mstore(0, 0xFA20F71C)\n        }\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                          CALLBACK HANDLERS\n    //////////////////////////////////////////////////////////////*/\n\n    /// @notice Called after minting liquidity to a position\n    /// @dev Pays the pool tokens owed for the minted liquidity from the payer (always the caller)\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 Contains the payer address and the pool features required to validate the callback\n    function uniswapV3MintCallback(\n        uint256 amount0Owed,\n        uint256 amount1Owed,\n        bytes calldata data\n    ) external {\n        // Decode the mint callback data\n        CallbackLib.CallbackData memory decoded = abi.decode(data, (CallbackLib.CallbackData));\n        // Validate caller to ensure we got called from the AMM pool\n        CallbackLib.validateCallback(msg.sender, address(FACTORY), decoded.poolFeatures);\n        // Sends the amount0Owed and amount1Owed quantities provided\n        if (amount0Owed > 0)\n            SafeTransferLib.safeTransferFrom(\n                decoded.poolFeatures.token0,\n                decoded.payer,\n                msg.sender,\n                amount0Owed\n            );\n        if (amount1Owed > 0)\n            SafeTransferLib.safeTransferFrom(\n                decoded.poolFeatures.token1,\n                decoded.payer,\n                msg.sender,\n                amount1Owed\n            );\n    }\n\n    /// @notice Called by the pool after executing a swap during an ITM option mint/burn.\n    /// @dev Pays the pool tokens owed for the swap from the payer (always the caller)\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 Contains the payer address and the pool features required to validate the callback\n    function uniswapV3SwapCallback(\n        int256 amount0Delta,\n        int256 amount1Delta,\n        bytes calldata data\n    ) external {\n        // Decode the swap callback data, checks that the UniswapV3Pool has the correct address.\n        CallbackLib.CallbackData memory decoded = abi.decode(data, (CallbackLib.CallbackData));\n        // Validate caller to ensure we got called from the AMM pool\n        CallbackLib.validateCallback(msg.sender, address(FACTORY), decoded.poolFeatures);\n\n        // Extract the address of the token to be sent (amount0 -> token0, amount1 -> token1)\n        address token = amount0Delta > 0\n            ? address(decoded.poolFeatures.token0)\n            : address(decoded.poolFeatures.token1);\n\n        // Transform the amount to pay to uint256 (take positive one from amount0 and amount1)\n        uint256 amountToPay = amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta);\n\n        // Pay the required token from the payer to the caller of this contract\n        SafeTransferLib.safeTransferFrom(token, decoded.payer, msg.sender, amountToPay);\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                       PUBLIC MINT/BURN FUNCTIONS\n    //////////////////////////////////////////////////////////////*/\n\n    /// @notice Burn a new position containing up to 4 legs wrapped in a ERC1155 token.\n    /// @dev Auto-collect all accumulated fees.\n    /// @param tokenId The tokenId of the minted position, which encodes information about up to 4 legs\n    /// @param positionSize The number of contracts minted, expressed in terms of the asset\n    /// @param slippageTickLimitLow The lower price slippage limit when minting an ITM position (set to larger than slippageTickLimitHigh for swapping when minting)\n    /// @param slippageTickLimitHigh The higher slippage limit when minting an ITM position (set to lower than slippageTickLimitLow for swapping when minting)\n    /// @return totalCollected A LeftRight encoded word containing the total amount of token0 and token1 collected as fees\n    /// @return totalSwapped A LeftRight encoded word containing the total amount of token0 and token1 swapped if minting ITM\n    /// @return newTick the current tick in the pool after all the mints and swaps\n    function burnTokenizedPosition(\n        uint256 tokenId,\n        uint128 positionSize,\n        int24 slippageTickLimitLow,\n        int24 slippageTickLimitHigh\n    )\n        external\n        ReentrancyLock(tokenId.univ3pool())\n        returns (int256 totalCollected, int256 totalSwapped, int24 newTick)\n    {\n        // burn this ERC1155 token id\n        _burn(msg.sender, tokenId, positionSize);\n\n        // emit event\n        emit TokenizedPositionBurnt(msg.sender, tokenId, positionSize);\n\n        // Call a function that contains other functions to mint/burn position, collect amounts, swap if necessary\n        (totalCollected, totalSwapped, newTick) = _validateAndForwardToAMM(\n            tokenId,\n            positionSize,\n            slippageTickLimitLow,\n            slippageTickLimitHigh,\n            BURN\n        );\n    }\n\n    /// @notice Create a new position `tokenId` containing up to 4 legs.\n    /// @param tokenId The tokenId of the minted position, which encodes information for up to 4 legs\n    /// @param positionSize The number of contracts minted, expressed in terms of the asset\n    /// @param slippageTickLimitLow The lower price slippage limit when minting an ITM position (set to larger than slippageTickLimitHigh for swapping when minting)\n    /// @param slippageTickLimitHigh The higher slippage limit when minting an ITM position (set to lower than slippageTickLimitLow for swapping when minting)\n    /// @return totalCollected A LeftRight encoded word containing the total amount of token0 and token1 collected as fees\n    /// @return totalSwapped A LeftRight encoded word containing the total amount of token0 and token1 swapped if minting ITM\n    /// @return newTick the current tick in the pool after all the mints and swaps\n    function mintTokenizedPosition(\n        uint256 tokenId,\n        uint128 positionSize,\n        int24 slippageTickLimitLow,\n        int24 slippageTickLimitHigh\n    )\n        external\n        ReentrancyLock(tokenId.univ3pool())\n        returns (int256 totalCollected, int256 totalSwapped, int24 newTick)\n    {\n        // create the option position via its ID in this erc1155\n        _mint(msg.sender, tokenId, positionSize);\n\n        emit TokenizedPositionMinted(msg.sender, tokenId, positionSize);\n\n        // validate the incoming option position, then forward to the AMM for minting/burning required liquidity chunks\n        (totalCollected, totalSwapped, newTick) = _validateAndForwardToAMM(\n            tokenId,\n            positionSize,\n            slippageTickLimitLow,\n            slippageTickLimitHigh,\n            MINT\n        );\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                    TRANSFER HOOK IMPLEMENTATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    /// @notice called after batch transfers (NOT mints or burns)\n    /// @param from The address of the sender\n    /// @param to The address of the recipient\n    /// @param ids The tokenIds being transferred\n    /// @param amounts The amounts of each token being transferred\n    function afterTokenTransfer(\n        address from,\n        address to,\n        uint256[] memory ids,\n        uint256[] memory amounts\n    ) internal override {\n        for (uint256 i = 0; i < ids.length; ) {\n            registerTokenTransfer(from, to, ids[i], amounts[i]);\n            unchecked {\n                ++i;\n            }\n        }\n    }\n\n    /// @notice called after single transfers (NOT mints or burns)\n    /// @param from The address of the sender\n    /// @param to The address of the recipient\n    /// @param id The tokenId being transferred\n    /// @param amount The amount of the token being transferred\n    function afterTokenTransfer(\n        address from,\n        address to,\n        uint256 id,\n        uint256 amount\n    ) internal override {\n        registerTokenTransfer(from, to, id, amount);\n    }\n\n    /// @notice update user position data following a token transfer\n    /// @dev token transfers are only allowed if you transfer your entire balance of a given tokenId and the recipient has none\n    /// @param from The address of the sender\n    /// @param to The address of the recipient\n    /// @param id The tokenId being transferred'\n    /// @param amount The amount of the token being transferred\n    function registerTokenTransfer(address from, address to, uint256 id, uint256 amount) internal {\n        // Extract univ3pool from the poolId map to Uniswap Pool\n        IUniswapV3Pool univ3pool = s_poolContext[id.validate()].pool;\n\n        uint256 numLegs = id.countLegs();\n        for (uint256 leg = 0; leg < numLegs; ) {\n            // for this leg index: extract the liquidity chunk: a 256bit word containing the liquidity amount and upper/lower tick\n            // @dev see `contracts/types/LiquidityChunk.sol`\n            uint256 liquidityChunk = PanopticMath.getLiquidityChunk(\n                id,\n                leg,\n                uint128(amount),\n                univ3pool.tickSpacing()\n            );\n\n            //construct the positionKey for the from and to addresses\n            bytes32 positionKey_from = keccak256(\n                abi.encodePacked(\n                    address(univ3pool),\n                    from,\n                    id.tokenType(leg),\n                    liquidityChunk.tickLower(),\n                    liquidityChunk.tickUpper()\n                )\n            );\n            bytes32 positionKey_to = keccak256(\n                abi.encodePacked(\n                    address(univ3pool),\n                    to,\n                    id.tokenType(leg),\n                    liquidityChunk.tickLower(),\n                    liquidityChunk.tickUpper()\n                )\n            );\n\n            // Revert if recipient already has that position\n            if (\n                (s_accountLiquidity[positionKey_to] != 0) ||\n                (s_accountFeesBase[positionKey_to] != 0)\n            ) revert Errors.TransferFailed();\n\n            // Revert if not all balance is transferred\n            uint256 fromLiq = s_accountLiquidity[positionKey_from];\n            if (fromLiq.rightSlot() != liquidityChunk.liquidity()) revert Errors.TransferFailed();\n\n            int256 fromBase = s_accountFeesBase[positionKey_from];\n\n            //update+store liquidity and fee values between accounts\n            s_accountLiquidity[positionKey_to] = fromLiq;\n            s_accountLiquidity[positionKey_from] = 0;\n\n            s_accountFeesBase[positionKey_to] = fromBase;\n            s_accountFeesBase[positionKey_from] = 0;\n            unchecked {\n                ++leg;\n            }\n        }\n    }\n\n    /*//////////////////////////////////////////////////////////////\n              AMM INTERACTION AND POSITION UPDATE HELPERS\n    //////////////////////////////////////////////////////////////*/\n\n    /// @notice Helper that checks the proposed option position and size and forwards the minting and potential swapping tasks.\n    /// @notice This helper function checks:\n    /// @notice  - that the `tokenId` is valid\n    /// @notice  - confirms that the Uniswap pool exists\n    /// @notice  - retrieves Uniswap pool info\n    /// @notice and then forwards the minting/burning/swapping to another internal helper functions which perform the AMM pool actions.\n    ///   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    ///   \u2502mintTokenizedPosition()\u251c\u2500\u2500\u2500\u2510\n    ///   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2502\n    ///                               \u2502\n    ///   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u2502   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    ///   \u2502burnTokenizedPosition()\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25ba _validateAndForwardToAMM(...) \u251c\u2500 (...) --> (mint/burn in AMM)\n    ///   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518       \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\n    /// @param tokenId the option position\n    /// @param positionSize the size of the position to create\n    /// @param tickLimitLow lower limits on potential slippage\n    /// @param tickLimitHigh upper limits on potential slippage\n    /// @param isBurn is equal to false for mints and true for burns\n    /// @return totalCollectedFromAMM the total amount of funds collected from Uniswap\n    /// @return totalMoved the total amount of funds swapped in Uniswap as part of building potential ITM positions\n    /// @return newTick the tick *after* the mint+swap\n    function _validateAndForwardToAMM(\n        uint256 tokenId,\n        uint128 positionSize,\n        int24 tickLimitLow,\n        int24 tickLimitHigh,\n        bool isBurn\n    ) internal returns (int256 totalCollectedFromAMM, int256 totalMoved, int24 newTick) {\n        // Reverts if positionSize is 0 and user did not own the position before minting/burning\n        if (positionSize == 0) revert Errors.OptionsBalanceZero();\n\n        /// @dev the flipToBurnToken() function flips the isLong bits\n        if (isBurn) {\n            tokenId = tokenId.flipToBurnToken();\n        }\n\n        // Validate tokenId\n        // Extract univ3pool from the poolId map to Uniswap Pool\n        IUniswapV3Pool univ3pool = s_poolContext[tokenId.validate()].pool;\n\n        // Revert if the pool not been previously initialized\n        if (univ3pool == IUniswapV3Pool(address(0))) revert Errors.UniswapPoolNotInitialized();\n\n        bool swapAtMint;\n        {\n            if (tickLimitLow > tickLimitHigh) {\n                swapAtMint = true;\n                (tickLimitLow, tickLimitHigh) = (tickLimitHigh, tickLimitLow);\n            }\n        }\n        // initialize some variables returned by the _createPositionInAMM function\n        int256 itmAmounts;\n\n        {\n            // calls a function that loops through each leg of tokenId and mints/burns liquidity in Uni v3 pool\n            (totalMoved, totalCollectedFromAMM, itmAmounts) = _createPositionInAMM(\n                univ3pool,\n                tokenId,\n                positionSize,\n                isBurn\n            );\n        }\n\n        // if the in-the-money amount is not zero (i.e. positions were minted ITM) and the user did provide tick limits LOW > HIGH, then swap necessary amounts\n        if ((itmAmounts != 0) && (swapAtMint)) {\n            totalMoved = swapInAMM(univ3pool, itmAmounts).add(totalMoved);\n        }\n\n        // Get the current tick of the Uniswap pool, check slippage\n        (, newTick, , , , , ) = univ3pool.slot0();\n\n        if ((newTick >= tickLimitHigh) || (newTick <= tickLimitLow)) revert Errors.PriceBoundFail();\n\n        return (totalCollectedFromAMM, totalMoved, newTick);\n    }\n\n    /// @notice When a position is minted or burnt in-the-money (ITM) we are *not* 100% token0 or 100% token1: we have a mix of both tokens.\n    /// @notice The swapping for ITM options is needed because only one of the tokens are \"borrowed\" by a user to create the position.\n    /// @notice This is an ITM situation below (price within the range of the chunk):\n    ///\n    ///        AMM       strike\n    ///     liquidity   price tick\n    ///        \u25b2           \u2502\n    ///        \u2502       \u250c\u2500\u2500\u2500\u25bc\u2500\u2500\u2500\u2510\n    ///        \u2502       \u2502       \u2502liquidity chunk\n    ///        \u2502 \u250c\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u25b2\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2510\n    ///        \u2502 \u2502       \u2502           \u2502\n    ///        \u2502 \u2502       :           \u2502\n    ///        \u2502 \u2502       :           \u2502\n    ///        \u2502 \u2502       :           \u2502\n    ///        \u2514\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25b2\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u25ba price\n    ///                  \u2502\n    ///             current price\n    ///             in-the-money: mix of tokens 0 and 1 within the chunk\n    ///\n    ///   If we take token0 as an example, we deploy it to the AMM pool and *then* swap to get the right mix of token0 and token1\n    ///   to be correctly in the money at that strike.\n    ///   It that position is burnt, then we remove a mix of the two tokens and swap one of them so that the user receives only one.\n    /// @param univ3pool the uniswap pool in which to swap.\n    /// @param itmAmounts how much to swap - how much is ITM\n    /// @return totalSwapped the amount swapped in the AMM\n    function swapInAMM(\n        IUniswapV3Pool univ3pool,\n        int256 itmAmounts\n    ) internal returns (int256 totalSwapped) {\n        // Initialize variables\n        bool zeroForOne; // The direction of the swap, true for token0 to token1, false for token1 to token0\n        int256 swapAmount; // The amount of token0 or token1 to swap\n        bytes memory data;\n\n        IUniswapV3Pool _univ3pool = univ3pool;\n\n        unchecked {\n            // unpack the in-the-money amounts\n            int128 itm0 = itmAmounts.rightSlot();\n            int128 itm1 = itmAmounts.leftSlot();\n\n            // construct the swap callback struct\n            data = abi.encode(\n                CallbackLib.CallbackData({\n                    poolFeatures: CallbackLib.PoolFeatures({\n                        token0: _univ3pool.token0(),\n                        token1: _univ3pool.token1(),\n                        fee: _univ3pool.fee()\n                    }),\n                    payer: msg.sender\n                })\n            );\n\n            // note: upstream users of this function such as the Panoptic Pool should ensure users always compensate for the ITM amount delta\n            // the netting swap is not perfectly accurate, and it is possible for swaps to run out of liquidity, so we do not want to rely on it\n            // this is simply a convenience feature, and should be treated as such\n            if ((itm0 != 0) && (itm1 != 0)) {\n                (uint160 sqrtPriceX96, , , , , , ) = _univ3pool.slot0();\n\n                // implement a single \"netting\" swap. Thank you @danrobinson for this puzzle/idea\n                // note: negative ITM amounts denote a surplus of tokens (burning liquidity), while positive amounts denote a shortage of tokens (minting liquidity)\n                // compute the approximate delta of token0 that should be resolved in the swap at the current tick\n                // we do this by flipping the signs on the token1 ITM amount converting+deducting it against the token0 ITM amount\n                // couple examples (price = 2 1/0):\n                //  - 100 surplus 0, 100 surplus 1 (itm0 = -100, itm1 = -100)\n                //    normal swap 0: 100 0 => 200 1\n                //    normal swap 1: 100 1 => 50 0\n                //    final swap amounts: 50 0 => 100 1\n                //    netting swap: net0 = -100 - (-100/2) = -50, ZF1 = true, 50 0 => 100 1\n                // - 100 surplus 0, 100 shortage 1 (itm0 = -100, itm1 = 100)\n                //    normal swap 0: 100 0 => 200 1\n                //    normal swap 1: 50 0 => 100 1\n                //    final swap amounts: 150 0 => 300 1\n                //    netting swap: net0 = -100 - (100/2) = -150, ZF1 = true, 150 0 => 300 1\n                // - 100 shortage 0, 100 surplus 1 (itm0 = 100, itm1 = -100)\n                //    normal swap 0: 200 1 => 100 0\n                //    normal swap 1: 100 1 => 50 0\n                //    final swap amounts: 300 1 => 150 0\n                //    netting swap: net0 = 100 - (-100/2) = 150, ZF1 = false, 300 1 => 150 0\n                // - 100 shortage 0, 100 shortage 1 (itm0 = 100, itm1 = 100)\n                //    normal swap 0: 200 1 => 100 0\n                //    normal swap 1: 50 0 => 100 1\n                //    final swap amounts: 100 1 => 50 0\n                //    netting swap: net0 = 100 - (100/2) = 50, ZF1 = false, 100 1 => 50 0\n                // - = Net surplus of token0\n                // + = Net shortage of token0\n                int256 net0 = itm0 - PanopticMath.convert1to0(itm1, sqrtPriceX96);\n\n                zeroForOne = net0 < 0;\n\n                //compute the swap amount, set as positive (exact input)\n                swapAmount = -net0;\n            } else if (itm0 != 0) {\n                zeroForOne = itm0 < 0;\n                swapAmount = -itm0;\n            } else {\n                zeroForOne = itm1 > 0;\n                swapAmount = -itm1;\n            }\n\n            // note - can occur if itm0 and itm1 have the same value\n            // in that case, swapping would be pointless so skip\n            if (swapAmount == 0) return int256(0);\n\n            // swap tokens in the Uniswap pool\n            // @dev note this triggers our swap callback function\n            (int256 swap0, int256 swap1) = _univ3pool.swap(\n                msg.sender,\n                zeroForOne,\n                swapAmount,\n                zeroForOne\n                    ? Constants.MIN_V3POOL_SQRT_RATIO + 1\n                    : Constants.MAX_V3POOL_SQRT_RATIO - 1,\n                data\n            );\n\n            // Add amounts swapped to totalSwapped variable\n            totalSwapped = int256(0).toRightSlot(swap0.toInt128()).toLeftSlot(swap1.toInt128());\n        }\n    }\n\n    /// @notice Create the position in the AMM given in the tokenId.\n    /// @dev Loops over each leg in the tokenId and calls _createLegInAMM for each, which does the mint/burn in the AMM.\n    /// @param univ3pool the Uniswap pool.\n    /// @param tokenId the option position\n    /// @param positionSize the size of the option position\n    /// @param isBurn is true if the position is burnt\n    /// @return totalMoved the total amount of liquidity moved from the msg.sender to Uniswap\n    /// @return totalCollected the total amount of liquidity collected from Uniswap to msg.sender\n    /// @return itmAmounts the amount of tokens swapped due to legs being in-the-money\n    function _createPositionInAMM(\n        IUniswapV3Pool univ3pool,\n        uint256 tokenId,\n        uint128 positionSize,\n        bool isBurn\n    ) internal returns (int256 totalMoved, int256 totalCollected, int256 itmAmounts) {\n        // upper bound on amount of tokens contained across all legs of the position at any given tick\n        uint256 amount0;\n        uint256 amount1;\n\n        uint256 numLegs = tokenId.countLegs();\n        // loop through up to the 4 potential legs in the tokenId\n        for (uint256 leg = 0; leg < numLegs; ) {\n            int256 _moved;\n            int256 _itmAmounts;\n            int256 _totalCollected;\n\n            {\n                // cache the univ3pool, tokenId, isBurn, and _positionSize variables to get rid of stack too deep error\n                IUniswapV3Pool _univ3pool = univ3pool;\n                uint256 _tokenId = tokenId;\n                bool _isBurn = isBurn;\n                uint128 _positionSize = positionSize;\n                uint256 _leg;\n\n                unchecked {\n                    // Reverse the order of the legs if this call is burning a position (LIFO)\n                    // We loop in reverse order if burning a position so that any dependent long liquidity is returned to the pool first,\n                    // allowing the corresponding short liquidity to be removed\n                    _leg = _isBurn ? numLegs - leg - 1 : leg;\n                }\n\n                // for this _leg index: extract the liquidity chunk: a 256bit word containing the liquidity amount and upper/lower tick\n                // @dev see `contracts/types/LiquidityChunk.sol`\n                uint256 liquidityChunk = PanopticMath.getLiquidityChunk(\n                    _tokenId,\n                    _leg,\n                    _positionSize,\n                    _univ3pool.tickSpacing()\n                );\n\n                (_moved, _itmAmounts, _totalCollected) = _createLegInAMM(\n                    _univ3pool,\n                    _tokenId,\n                    _leg,\n                    liquidityChunk,\n                    _isBurn\n                );\n\n                unchecked {\n                    // increment accumulators of the upper bound on tokens contained across all legs of the position at any given tick\n                    amount0 += Math.getAmount0ForLiquidity(liquidityChunk);\n\n                    amount1 += Math.getAmount1ForLiquidity(liquidityChunk);\n                }\n            }\n\n            totalMoved = totalMoved.add(_moved);\n            itmAmounts = itmAmounts.add(_itmAmounts);\n            totalCollected = totalCollected.add(_totalCollected);\n\n            unchecked {\n                ++leg;\n            }\n        }\n\n        // Ensure upper bound on amount of tokens contained across all legs of the position on any given tick does not exceed a maximum of (2**127-1).\n        // This is the maximum value of the `int128` type we frequently use to hold token amounts, so a given position's size should be guaranteed to\n        // fit within that limit at all times.\n        if (amount0 > uint128(type(int128).max) || amount1 > uint128(type(int128).max))\n            revert Errors.PositionTooLarge();\n    }\n\n    /// @notice Create the position in the AMM for a specific leg in the tokenId.\n    /// @dev For the leg specified by the _leg input:\n    /// @dev  - mints any new liquidity in the AMM needed (via _mintLiquidity)\n    /// @dev  - burns any new liquidity in the AMM needed (via _burnLiquidity)\n    /// @dev  - tracks all amounts minted and burned\n    /// @dev to burn a position, the opposing position is \"created\" through this function\n    /// but we need to pass in a flag to indicate that so the shortLiquidity is updated.\n    /// @param _univ3pool the Uniswap pool.\n    /// @param _tokenId the option position\n    /// @param _leg the leg index that needs to be modified\n    /// @param _liquidityChunk has lower tick, upper tick, and liquidity amount to mint\n    /// @param _isBurn is true if the position is burnt\n    /// @return _moved the total amount of liquidity moved from the msg.sender to Uniswap\n    /// @return _itmAmounts the amount of tokens swapped due to legs being in-the-money\n    /// @return _totalCollected the total amount of liquidity collected from Uniswap to msg.sender\n    function _createLegInAMM(\n        IUniswapV3Pool _univ3pool,\n        uint256 _tokenId,\n        uint256 _leg,\n        uint256 _liquidityChunk,\n        bool _isBurn\n    ) internal returns (int256 _moved, int256 _itmAmounts, int256 _totalCollected) {\n        uint256 _tokenType = TokenId.tokenType(_tokenId, _leg);\n        // unique key to identify the liquidity chunk in this uniswap pool\n        bytes32 positionKey = keccak256(\n            abi.encodePacked(\n                address(_univ3pool),\n                msg.sender,\n                _tokenType,\n                _liquidityChunk.tickLower(),\n                _liquidityChunk.tickUpper()\n            )\n        );\n\n        // update our internal bookkeeping of how much liquidity we have deployed in the AMM\n        // for example: if this _leg is short, we add liquidity to the amm, make sure to add that to our tracking\n        uint128 updatedLiquidity;\n        uint256 isLong = TokenId.isLong(_tokenId, _leg);\n        uint256 currentLiquidity = s_accountLiquidity[positionKey]; //cache\n\n        unchecked {\n            // did we have liquidity already deployed in Uniswap for this chunk range from some past mint?\n\n            // s_accountLiquidity is a LeftRight. The right slot represents the liquidity currently sold (added) in the AMM owned by the user\n            // the left slot represents the amount of liquidity currently bought (removed) that has been removed from the AMM - the user owes it to a seller\n            // the reason why it is called \"removedLiquidity\" is because long options are created by removing -ie.short selling LP positions\n            uint128 startingLiquidity = currentLiquidity.rightSlot();\n            uint128 removedLiquidity = currentLiquidity.leftSlot();\n            uint128 chunkLiquidity = _liquidityChunk.liquidity();\n\n            if (isLong == 0) {\n                // selling/short: so move from msg.sender *to* uniswap\n                // we're minting more liquidity in uniswap: so add the incoming liquidity chunk to the existing liquidity chunk\n                updatedLiquidity = startingLiquidity + chunkLiquidity;\n\n                /// @dev If the isLong flag is 0=short but the position was burnt, then this is closing a long position\n                /// @dev so the amount of short liquidity should decrease.\n                if (_isBurn) {\n                    removedLiquidity -= chunkLiquidity;\n                }\n            } else {\n                // the _leg is long (buying: moving *from* uniswap to msg.sender)\n                // so we seek to move the incoming liquidity chunk *out* of uniswap - but was there sufficient liquidity sitting in uniswap\n                // in the first place?\n                if (startingLiquidity < chunkLiquidity) {\n                    // the amount we want to move (liquidityChunk.legLiquidity()) out of uniswap is greater than\n                    // what the account that owns the liquidity in uniswap has (startingLiquidity)\n                    // we must ensure that an account can only move its own liquidity out of uniswap\n                    // so we revert in this case\n                    revert Errors.NotEnoughLiquidity();\n                } else {\n                    // we want to move less than what already sits in uniswap, no problem:\n                    updatedLiquidity = startingLiquidity - chunkLiquidity;\n                }\n\n                /// @dev If the isLong flag is 1=long and the position is minted, then this is opening a long position\n                /// @dev so the amount of short liquidity should increase.\n                if (!_isBurn) {\n                    removedLiquidity += chunkLiquidity;\n                }\n            }\n\n            // update the starting liquidity for this position for next time around\n            s_accountLiquidity[positionKey] = uint256(0).toLeftSlot(removedLiquidity).toRightSlot(\n                updatedLiquidity\n            );\n        }\n\n        // track how much liquidity we need to collect from uniswap\n        // add the fees that accumulated in uniswap within the liquidityChunk:\n        {\n            /** if the position is NOT long (selling a put or a call), then _mintLiquidity to move liquidity\n                from the msg.sender to the uniswap v3 pool:\n                Selling(isLong=0): Mint chunk of liquidity in Uniswap (defined by upper tick, lower tick, and amount)\n                       \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n                \u25b2     \u250c\u25bc\u2510 liquidityChunk                 \u2502\n                \u2502  \u250c\u2500\u2500\u2534\u2500\u2534\u2500\u2500\u2510                         \u250c\u2500\u2500\u2500\u2534\u2500\u2500\u2510\n                \u2502  \u2502       \u2502                         \u2502      \u2502\n                \u2514\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u25ba                      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n                   Uniswap v3                      msg.sender\n            \n             else: the position is long (buying a put or a call), then _burnLiquidity to remove liquidity from univ3\n                Buying(isLong=1): Burn in Uniswap\n                       \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n                \u25b2     \u250c\u253c\u2510                \u2502\n                \u2502  \u250c\u2500\u2500\u2534\u2500\u2534\u2500\u2500\u2510         \u250c\u2500\u2500\u2500\u25bc\u2500\u2500\u2510\n                \u2502  \u2502       \u2502         \u2502      \u2502\n                \u2514\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u25ba      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n                    Uniswap v3      msg.sender \n            */\n            _moved = isLong == 0\n                ? _mintLiquidity(_liquidityChunk, _univ3pool)\n                : _burnLiquidity(_liquidityChunk, _univ3pool); // from msg.sender to Uniswap\n            // add the moved liquidity chunk to amount we need to collect from uniswap:\n\n            // Is this _leg ITM?\n            // if tokenType is 1, and we transacted some token0: then this leg is ITM!\n            if (_tokenType == 1) {\n                // extract amount moved out of UniswapV3 pool\n                _itmAmounts = _itmAmounts.toRightSlot(_moved.rightSlot());\n            }\n            // if tokenType is 0, and we transacted some token1: then this leg is ITM\n            if (_tokenType == 0) {\n                // Add this in-the-money amount transacted.\n                _itmAmounts = _itmAmounts.toLeftSlot(_moved.leftSlot());\n            }\n        }\n\n        // if there was liquidity at that tick before the transaction, collect any accumulated fees\n        if (currentLiquidity.rightSlot() > 0) {\n            _totalCollected = _collectAndWritePositionData(\n                _liquidityChunk,\n                _univ3pool,\n                currentLiquidity,\n                positionKey,\n                _moved,\n                isLong\n            );\n        }\n\n        // position has been touched, update s_accountFeesBase with the latest values from the pool.positions\n        s_accountFeesBase[positionKey] = _getFeesBase(\n            _univ3pool,\n            updatedLiquidity,\n            _liquidityChunk\n        );\n    }\n\n    /// @notice caches/stores the accumulated premia values for the specified postion.\n    /// @param positionKey the hashed data which represents the underlying position in the Uniswap pool\n    /// @param currentLiquidity the total amount of liquidity in the AMM for the specific position\n    /// @param collectedAmounts amount of tokens (token0 and token1) collected from Uniswap\n    function _updateStoredPremia(\n        bytes32 positionKey,\n        uint256 currentLiquidity,\n        int256 collectedAmounts\n    ) private {\n        (uint256 deltaPremiumOwed, uint256 deltaPremiumGross) = _getPremiaDeltas(\n            currentLiquidity,\n            collectedAmounts\n        );\n\n        s_accountPremiumOwed[positionKey] = s_accountPremiumOwed[positionKey].add(deltaPremiumOwed);\n        s_accountPremiumGross[positionKey] = s_accountPremiumGross[positionKey].add(\n            deltaPremiumGross\n        );\n    }\n\n    /// @notice Compute the feesGrowth * liquidity / 2**128 by reading feeGrowthInside0LastX128 and feeGrowthInside1LastX128 from univ3pool.positions.\n    /// @param univ3pool the Uniswap pool.\n    /// @param liquidity the total amount of liquidity in the AMM for the specific position\n    /// @param liquidityChunk has lower tick, upper tick, and liquidity amount to mint\n    function _getFeesBase(\n        IUniswapV3Pool univ3pool,\n        uint128 liquidity,\n        uint256 liquidityChunk\n    ) private view returns (int256 feesBase) {\n        // now collect fee growth within the liquidity chunk in `liquidityChunk`\n        // this is the fee accumulated in Uniswap for this chunk of liquidity\n\n        // read the latest feeGrowth directly from the Uniswap pool\n        (, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = univ3pool\n            .positions(\n                keccak256(\n                    abi.encodePacked(\n                        address(this),\n                        liquidityChunk.tickLower(),\n                        liquidityChunk.tickUpper()\n                    )\n                )\n            );\n\n        // (feegrowth * liquidity) / 2 ** 128\n        /// @dev here we're converting the value to an int128 even though all values (feeGrowth, liquidity, Q128) are strictly positive.\n        /// That's because of the way feeGrowthInside works in Uniswap v3, where it can underflow when stored for the first time.\n        /// This is not a problem in Uniswap v3 because the fees are always calculated by taking the difference of the feeGrowths,\n        /// so that the net different is always positive.\n        /// So by using int128 instead of uint128, we remove the need to handle extremely large underflows and simply allow it to be negative\n        feesBase = int256(0)\n            .toRightSlot(int128(int256(Math.mulDiv128(feeGrowthInside0LastX128, liquidity))))\n            .toLeftSlot(int128(int256(Math.mulDiv128(feeGrowthInside1LastX128, liquidity))));\n    }\n\n    /// @notice Mint a chunk of liquidity (`liquidityChunk`) in the Uniswap v3 pool; return the amount moved.\n    /// @dev note that \"moved\" means: mint in Uniswap and move tokens from msg.sender.\n    /// @param liquidityChunk the chunk of liquidity to mint given by tick upper, tick lower, and its size\n    /// @param univ3pool the Uniswap v3 pool to mint liquidity in/to\n    /// @return movedAmounts how many tokens were moved from msg.sender to Uniswap\n    function _mintLiquidity(\n        uint256 liquidityChunk,\n        IUniswapV3Pool univ3pool\n    ) internal returns (int256 movedAmounts) {\n        // build callback data\n        bytes memory mintdata = abi.encode(\n            CallbackLib.CallbackData({ // compute by reading values from univ3pool every time\n                    poolFeatures: CallbackLib.PoolFeatures({\n                        token0: univ3pool.token0(),\n                        token1: univ3pool.token1(),\n                        fee: univ3pool.fee()\n                    }),\n                    payer: msg.sender\n                })\n        );\n\n        /// mint the required amount in the Uniswap pool\n        /// @dev this triggers the uniswap mint callback function\n        (uint256 amount0, uint256 amount1) = univ3pool.mint(\n            address(this),\n            liquidityChunk.tickLower(),\n            liquidityChunk.tickUpper(),\n            liquidityChunk.liquidity(),\n            mintdata\n        );\n\n        // amount0 The amount of token0 that was paid to mint the given amount of liquidity\n        // amount1 The amount of token1 that was paid to mint the given amount of liquidity\n        // no need to safecast to int from uint here as the max position size is int128\n        // from msg.sender to the uniswap pool, stored as negative value to represent amount debited\n        movedAmounts = int256(0).toRightSlot(int128(int256(amount0))).toLeftSlot(\n            int128(int256(amount1))\n        );\n    }\n\n    /// @notice Burn a chunk of liquidity (`liquidityChunk`) in the Uniswap v3 pool and send to msg.sender; return the amount moved.\n    /// @dev note that \"moved\" means: burn position in Uniswap and send tokens to msg.sender.\n    /// @param liquidityChunk the chunk of liquidity to burn given by tick upper, tick lower, and its size\n    /// @param univ3pool the Uniswap v3 pool to burn liquidity in/from\n    /// @return movedAmounts how many tokens were moved from Uniswap to msg.sender\n    function _burnLiquidity(\n        uint256 liquidityChunk,\n        IUniswapV3Pool univ3pool\n    ) internal returns (int256 movedAmounts) {\n        // burn that option's liquidity in the Uniswap Pool.\n        // This will send the underlying tokens back to the Panoptic Pool (msg.sender)\n        (uint256 amount0, uint256 amount1) = univ3pool.burn(\n            liquidityChunk.tickLower(),\n            liquidityChunk.tickUpper(),\n            liquidityChunk.liquidity()\n        );\n\n        // amount0 The amount of token0 that was sent back to the Panoptic Pool\n        // amount1 The amount of token1 that was sent back to the Panoptic Pool\n        // no need to safecast to int from uint here as the max position size is int128\n        // decrement the amountsOut with burnt amounts. amountsOut = notional value of tokens moved\n        unchecked {\n            movedAmounts = int256(0).toRightSlot(-int128(int256(amount0))).toLeftSlot(\n                -int128(int256(amount1))\n            );\n        }\n    }\n\n    /// @notice Helper to collect amounts between msg.sender and Uniswap and also to update the Uniswap fees collected to date from the AMM.\n    /// @param liquidityChunk the liquidity chunk representing the option position/leg\n    /// @param univ3pool the Uniswap pool where the position is deployed\n    /// @param currentLiquidity the existing liquidity msg.sender owns in the AMM for this chunk before the SFPM was called\n    /// @param positionKey the unique key to identify the liquidity chunk/tokenType pairing in this uniswap pool\n    /// @param movedInLeg how much liquidity has been moved between msg.sender and Uniswap before this function call\n    /// @param isLong whether the leg in question is long (=1) or short (=0)\n    /// @return collectedOut the incoming totalCollected with potentially whatever is collected in this function added to it\n    function _collectAndWritePositionData(\n        uint256 liquidityChunk,\n        IUniswapV3Pool univ3pool,\n        uint256 currentLiquidity,\n        bytes32 positionKey,\n        int256 movedInLeg,\n        uint256 isLong\n    ) internal returns (int256 collectedOut) {\n        uint128 startingLiquidity = currentLiquidity.rightSlot();\n        int256 amountToCollect = _getFeesBase(univ3pool, startingLiquidity, liquidityChunk).sub(\n            s_accountFeesBase[positionKey]\n        );\n\n        if (isLong == 1) {\n            amountToCollect = amountToCollect.sub(movedInLeg);\n        }\n\n        if (amountToCollect != 0) {\n            // first collect amounts from Uniswap corresponding to this position\n            // Collect only if there was existing startingLiquidity=liquidities.rightSlot() at that position: collect all fees\n\n            // Collects tokens owed to a liquidity chunk\n            (uint128 receivedAmount0, uint128 receivedAmount1) = univ3pool.collect(\n                msg.sender,\n                liquidityChunk.tickLower(),\n                liquidityChunk.tickUpper(),\n                uint128(amountToCollect.rightSlot()),\n                uint128(amountToCollect.leftSlot())\n            );\n\n            // moved will be negative if the leg was long (funds left the caller, don't count it in collected fees)\n            uint128 collected0;\n            uint128 collected1;\n            unchecked {\n                collected0 = movedInLeg.rightSlot() < 0\n                    ? receivedAmount0 - uint128(-movedInLeg.rightSlot())\n                    : receivedAmount0;\n                collected1 = movedInLeg.leftSlot() < 0\n                    ? receivedAmount1 - uint128(-movedInLeg.leftSlot())\n                    : receivedAmount1;\n            }\n\n            // CollectedOut is the amount of fees accumulated+collected (received - burnt)\n            // That's because receivedAmount contains the burnt tokens and whatever amount of fees collected\n            collectedOut = int256(0).toRightSlot(collected0).toLeftSlot(collected1);\n\n            _updateStoredPremia(positionKey, currentLiquidity, collectedOut);\n        }\n    }\n\n    /// @notice Function that updates the Owed and Gross account liquidities.\n    /// @param currentLiquidity netLiquidity (right) and removedLiquidity (left) at the start of the transaction\n    /// @param collectedAmounts total amount of tokens (token0 and token1) collected from Uniswap.\n    /// @return deltaPremiumOwed The extra premium (per liquidity X64) to be added to the owed accumulator for token0 (right) and token1 (right)\n    /// @return deltaPremiumGross The extra premium (per liquidity X64) to be added to the gross accumulator for token0 (right) and token1 (right)\n    function _getPremiaDeltas(\n        uint256 currentLiquidity,\n        int256 collectedAmounts\n    ) private pure returns (uint256 deltaPremiumOwed, uint256 deltaPremiumGross) {\n        // extract liquidity values\n        uint256 removedLiquidity = currentLiquidity.leftSlot();\n        uint256 netLiquidity = currentLiquidity.rightSlot();\n\n        // premia spread equations are graphed and documented here: https://www.desmos.com/calculator/mdeqob2m04\n        // explains how we get from the premium per liquidity (calculated here) to the total premia collected and the multiplier\n        // as well as how the value of VEGOID affects the premia\n        // note that the \"base\" premium is just a common factor shared between the owed (long) and gross (short)\n        // premia, and is only seperated to simplify the calculation\n        // (the graphed equations include this factor without separating it)\n        unchecked {\n            uint256 totalLiquidity = netLiquidity + removedLiquidity;\n\n            uint128 premium0X64_base;\n            uint128 premium1X64_base;\n\n            {\n                uint128 collected0 = uint128(collectedAmounts.rightSlot());\n                uint128 collected1 = uint128(collectedAmounts.leftSlot());\n\n                // compute the base premium as collected * total / net^2 (from Eqn 3)\n                premium0X64_base = Math\n                    .mulDiv(collected0, totalLiquidity * 2 ** 64, netLiquidity ** 2)\n                    .toUint128();\n                premium1X64_base = Math\n                    .mulDiv(collected1, totalLiquidity * 2 ** 64, netLiquidity ** 2)\n                    .toUint128();\n            }\n\n            {\n                uint128 premium0X64_owed;\n                uint128 premium1X64_owed;\n                {\n                    // compute the owed premium (from Eqn 3)\n                    uint256 numerator = netLiquidity + (removedLiquidity / 2 ** VEGOID);\n\n                    premium0X64_owed = Math\n                        .mulDiv(premium0X64_base, numerator, totalLiquidity)\n                        .toUint128();\n                    premium1X64_owed = Math\n                        .mulDiv(premium1X64_base, numerator, totalLiquidity)\n                        .toUint128();\n\n                    deltaPremiumOwed = uint256(0).toRightSlot(premium0X64_owed).toLeftSlot(\n                        premium1X64_owed\n                    );\n                }\n            }\n\n            {\n                uint128 premium0X64_gross;\n                uint128 premium1X64_gross;\n                {\n                    // compute the gross premium (from Eqn 4)\n                    uint256 numerator = totalLiquidity ** 2 -\n                        totalLiquidity *\n                        removedLiquidity +\n                        ((removedLiquidity ** 2) / 2 ** (VEGOID));\n                    premium0X64_gross = Math\n                        .mulDiv(premium0X64_base, numerator, totalLiquidity ** 2)\n                        .toUint128();\n                    premium1X64_gross = Math\n                        .mulDiv(premium1X64_base, numerator, totalLiquidity ** 2)\n                        .toUint128();\n                    deltaPremiumGross = uint256(0).toRightSlot(premium0X64_gross).toLeftSlot(\n                        premium1X64_gross\n                    );\n                }\n            }\n        }\n    }\n\n    /*///////////////////////////////////////////////////////////////////////////\n                                    SFPM PROPERTIES\n    ///////////////////////////////////////////////////////////////////////////*/\n\n    /// @notice Return the liquidity associated with a given position.\n    /// @dev Computes accountLiquidity[keccak256(abi.encodePacked(univ3pool, owner, tokenType, tickLower, tickUpper))]\n    /// @param univ3pool The address of the Uniswap v3 Pool\n    /// @param owner The address of the account that is queried\n    /// @param tokenType The tokenType of the position (the token it started as)\n    /// @param tickLower The lower end of the tick range for the position (int24)\n    /// @param tickUpper The upper end of the tick range for the position (int24)\n    /// @return accountLiquidities The amount of liquidity that has been shorted/added to the Uniswap contract (removedLiquidity:netLiquidity -> rightSlot:leftSlot)\n    function getAccountLiquidity(\n        address univ3pool,\n        address owner,\n        uint256 tokenType,\n        int24 tickLower,\n        int24 tickUpper\n    ) external view returns (uint256 accountLiquidities) {\n        /// Extract the account liquidity for a given uniswap pool, owner, token type, and ticks\n        /// @dev tokenType input here is the asset of the positions minted, this avoids put liquidity to be used for call, and vice-versa\n        accountLiquidities = s_accountLiquidity[\n            keccak256(abi.encodePacked(univ3pool, owner, tokenType, tickLower, tickUpper))\n        ];\n    }\n\n    /// @notice Return the premium associated with a given position, where Premium is an accumulator of feeGrowth for the touched position.\n    /// @dev Computes s_accountPremium{isLong ? Owed : Gross}[keccak256(abi.encodePacked(univ3pool, owner, tokenType, tickLower, tickUpper))]\n    /// @dev if an atTick parameter is provided that is different from type(int24).max, then it will update the premium up to the current\n    /// @dev block at the provided atTick value. We do this because this may be called immediately after the Uni v3 pool has been touched\n    /// @dev so no need to read the feeGrowths from the Uni v3 pool.\n    /// @param univ3pool The address of the Uniswap v3 Pool\n    /// @param owner The address of the account that is queried\n    /// @param tokenType The tokenType of the position (the token it started as)\n    /// @param tickLower The lower end of the tick range for the position (int24)\n    /// @param tickUpper The upper end of the tick range for the position (int24)\n    /// @param atTick The current tick. Set atTick < type(int24).max = 8388608 to get latest premium up to the current block\n    /// @param isLong whether the position is long (=1) or short (=0)\n    /// @return premiumToken0 The amount of premium (per liquidity X64) for token0 = sum (feeGrowthLast0X128) over every block where the position has been touched\n    /// @return premiumToken1 The amount of premium (per liquidity X64) for token1 = sum (feeGrowthLast0X128) over every block where the position has been touched\n    function getAccountPremium(\n        address univ3pool,\n        address owner,\n        uint256 tokenType,\n        int24 tickLower,\n        int24 tickUpper,\n        int24 atTick,\n        uint256 isLong\n    ) external view returns (uint128 premiumToken0, uint128 premiumToken1) {\n        bytes32 positionKey = keccak256(\n            abi.encodePacked(address(univ3pool), owner, tokenType, tickLower, tickUpper)\n        );\n\n        // Extract the account liquidity for a given uniswap pool, owner, token type, and ticks\n        uint256 acctPremia = isLong == 1\n            ? s_accountPremiumOwed[positionKey]\n            : s_accountPremiumGross[positionKey];\n\n        // Compute the premium up to the current block (ie. after last touch until now). Do not proceed if atTick == type(int24).max = 8388608\n        if (atTick < type(int24).max) {\n            // unique key to identify the liquidity chunk in this uniswap pool\n            uint256 accountLiquidities = s_accountLiquidity[positionKey];\n            uint128 netLiquidity = accountLiquidities.rightSlot();\n            if (netLiquidity != 0) {\n                int256 amountToCollect;\n                {\n                    IUniswapV3Pool _univ3pool = IUniswapV3Pool(univ3pool);\n                    uint256 tempChunk = uint256(0).createChunk(tickLower, tickUpper, 0);\n                    // how much fees have been accumulated within the liquidity chunk since last time we updated this chunk?\n                    // Compute (currentFeesGrowth - oldFeesGrowth), the amount to collect\n                    // currentFeesGrowth (calculated from FeesCalc.calculateAMMSwapFeesLiquidityChunk) is (ammFeesCollectedPerLiquidity * liquidityChunk.liquidity())\n                    // oldFeesGrowth is the last stored update of fee growth within the position range in the past (feeGrowthRange*liquidityChunk.liquidity()) (s_accountFeesBase[positionKey])\n                    int256 feesBase = FeesCalc.calculateAMMSwapFeesLiquidityChunk(\n                        _univ3pool,\n                        atTick,\n                        netLiquidity,\n                        tempChunk\n                    );\n                    amountToCollect = feesBase.sub(s_accountFeesBase[positionKey]);\n                }\n\n                (uint256 deltaPremiumOwed, uint256 deltaPremiumGross) = _getPremiaDeltas(\n                    accountLiquidities,\n                    amountToCollect\n                );\n                // Extract the account liquidity for a given uniswap pool, owner, token type, and ticks\n                acctPremia = isLong == 1\n                    ? acctPremia.add(deltaPremiumOwed)\n                    : acctPremia.add(deltaPremiumGross);\n            }\n        }\n\n        premiumToken0 = acctPremia.rightSlot();\n        premiumToken1 = acctPremia.leftSlot();\n    }\n\n    /// @notice Return the feesBase associated with a given position.\n    /// @dev Computes accountFeesBase[keccak256(abi.encodePacked(univ3pool, owner, tickLower, tickUpper))]\n    /// @dev feesBase0 is computed as Math.mulDiv128(feeGrowthInside0X128, legLiquidity)\n    /// @param univ3pool The address of the Uniswap v3 Pool\n    /// @param owner The address of the account that is queried\n    /// @param tokenType The tokenType of the position (the token it started as)\n    /// @param tickLower The lower end of the tick range for the position (int24)\n    /// @param tickUpper The upper end of the tick range for the position (int24)\n    /// @return feesBase0 The feesBase of the position for token0\n    /// @return feesBase1 The feesBase of the position for token1\n    function getAccountFeesBase(\n        address univ3pool,\n        address owner,\n        uint256 tokenType,\n        int24 tickLower,\n        int24 tickUpper\n    ) external view returns (int128 feesBase0, int128 feesBase1) {\n        // Get accumulated fees for token0 (rightSlot) and token1 (leftSlot)\n        int256 feesBase = s_accountFeesBase[\n            keccak256(abi.encodePacked(univ3pool, owner, tokenType, tickLower, tickUpper))\n        ];\n        feesBase0 = feesBase.rightSlot();\n        feesBase1 = feesBase.leftSlot();\n    }\n\n    /// @notice Returns the Uniswap v3 pool for a given poolId.\n    /// @dev poolId is typically the first 8 bytes of the uni v3 pool address\n    /// @dev But poolId can be different for first 8 bytes if there is a collision between Uni v3 pool addresses\n    /// @param poolId The poolId for a Uni v3 pool\n    /// @return UniswapV3Pool The unique poolId for that Uni v3 pool\n    function getUniswapV3PoolFromId(\n        uint64 poolId\n    ) external view returns (IUniswapV3Pool UniswapV3Pool) {\n        return s_poolContext[poolId].pool;\n    }\n\n    /// @notice Returns the poolId for a given Uniswap v3 pool.\n    /// @dev poolId is typically the first 8 bytes of the uni v3 pool address\n    /// @dev But poolId can be different for first 8 bytes if there is a collision between Uni v3 pool addresses\n    /// @param univ3pool The address of the Uniswap v3 Pool\n    /// @return poolId The unique poolId for that Uni v3 pool\n    function getPoolId(address univ3pool) external view returns (uint64 poolId) {\n        poolId = uint64(s_AddrToPoolIdData[univ3pool]);\n    }\n}"
}