{
    "Function": "slitherConstructorConstantVariables",
    "File": "src/LBPair.sol",
    "Parent Contracts": [
        "src/interfaces/ILBPair.sol",
        "src/libraries/ReentrancyGuardUpgradeable.sol",
        "src/LBToken.sol",
        "src/interfaces/ILBToken.sol"
    ],
    "High-Level Calls": [],
    "Internal Calls": [],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "contract LBPair is LBToken, ReentrancyGuardUpgradeable, ILBPair {\n    /** Libraries **/\n\n    using Math512Bits for uint256;\n    using TreeMath for mapping(uint256 => uint256)[3];\n    using SafeCast for uint256;\n    using SafeMath for uint256;\n    using TokenHelper for IERC20;\n    using FeeHelper for FeeHelper.FeeParameters;\n    using SwapHelper for Bin;\n    using Decoder for bytes32;\n    using FeeDistributionHelper for FeeHelper.FeesDistribution;\n    using Oracle for bytes32[65_535];\n\n    /** Modifiers **/\n\n    modifier onlyFactory() {\n        if (msg.sender != address(factory)) revert LBPair__OnlyFactory();\n        _;\n    }\n\n    /** Public immutable variables **/\n\n    ILBFactory public immutable override factory;\n\n    /** Public variables **/\n\n    IERC20 public override tokenX;\n    IERC20 public override tokenY;\n\n    /** Private variables **/\n\n    PairInformation private _pairInformation;\n    FeeHelper.FeeParameters private _feeParameters;\n    /// @dev The reserves of tokens for every bin. This is the amount\n    /// of tokenY if `id < _pairInformation.activeId`; of tokenX if `id > _pairInformation.activeId`\n    /// and a mix of both if `id == _pairInformation.activeId`\n    mapping(uint256 => Bin) private _bins;\n    /// @dev Tree to find bins with non zero liquidity\n    mapping(uint256 => uint256)[3] private _tree;\n    /// @dev Mapping from account to user's unclaimed fees. The first 128 bits are tokenX and the last are for tokenY\n    mapping(address => bytes32) private _unclaimedFees;\n    /// @dev Mapping from account to id to user's accruedDebt.\n    mapping(address => mapping(uint256 => Debts)) private _accruedDebts;\n    /// @dev Oracle array\n    bytes32[65_535] private _oracle;\n\n    /** OffSets */\n\n    uint256 private constant _OFFSET_PAIR_RESERVE_X = 24;\n    uint256 private constant _OFFSET_PROTOCOL_FEE = 128;\n    uint256 private constant _OFFSET_BIN_RESERVE_Y = 112;\n    uint256 private constant _OFFSET_VARIABLE_FEE_PARAMETERS = 144;\n    uint256 private constant _OFFSET_ORACLE_SAMPLE_LIFETIME = 136;\n    uint256 private constant _OFFSET_ORACLE_SIZE = 152;\n    uint256 private constant _OFFSET_ORACLE_ACTIVE_SIZE = 168;\n    uint256 private constant _OFFSET_ORACLE_LAST_TIMESTAMP = 184;\n    uint256 private constant _OFFSET_ORACLE_ID = 224;\n\n    /** Constructor **/\n\n    /// @notice Set the factory address\n    /// @param _factory The address of the factory\n    constructor(ILBFactory _factory) LBToken() {\n        if (address(_factory) == address(0)) revert LBPair__AddressZero();\n        factory = _factory;\n    }\n\n    /// @notice Initialize the parameters of the LBPair\n    /// @dev The different parameters needs to be validated very cautiously.\n    /// It is highly recommended to never call this function directly, use the factory\n    /// as it validates the different parameters\n    /// @param _tokenX The address of the tokenX. Can't be address 0\n    /// @param _tokenY The address of the tokenY. Can't be address 0\n    /// @param _activeId The active id of the pair\n    /// @param _sampleLifetime The lifetime of a sample. It's the min time between 2 oracle's sample\n    /// @param _packedFeeParameters The fee parameters packed in a single 256 bits slot\n    function initialize(\n        IERC20 _tokenX,\n        IERC20 _tokenY,\n        uint24 _activeId,\n        uint16 _sampleLifetime,\n        bytes32 _packedFeeParameters\n    ) external override onlyFactory {\n        if (address(_tokenX) == address(0) || address(_tokenY) == address(0)) revert LBPair__AddressZero();\n        if (address(tokenX) != address(0)) revert LBPair__AlreadyInitialized();\n\n        __ReentrancyGuard_init();\n\n        tokenX = _tokenX;\n        tokenY = _tokenY;\n\n        _pairInformation.activeId = _activeId;\n        _pairInformation.oracleSampleLifetime = _sampleLifetime;\n\n        _setFeesParameters(_packedFeeParameters);\n        _increaseOracle(2);\n    }\n\n    /** External View Functions **/\n\n    /// @notice View function to get the reserves and active id\n    /// @return reserveX The reserve of asset X\n    /// @return reserveY The reserve of asset Y\n    /// @return activeId The active id of the pair\n    function getReservesAndId()\n        external\n        view\n        override\n        returns (\n            uint256 reserveX,\n            uint256 reserveY,\n            uint256 activeId\n        )\n    {\n        return _getReservesAndId();\n    }\n\n    /// @notice View function to get the global fees information, the total fees and those for protocol\n    /// @dev The fees for users are `total - protocol`\n    /// @return feesXTotal The total fees of asset X\n    /// @return feesYTotal The total fees of asset Y\n    /// @return feesXProtocol The protocol fees of asset X\n    /// @return feesYProtocol The protocol fees of asset Y\n    function getGlobalFees()\n        external\n        view\n        override\n        returns (\n            uint256 feesXTotal,\n            uint256 feesYTotal,\n            uint256 feesXProtocol,\n            uint256 feesYProtocol\n        )\n    {\n        return _getGlobalFees();\n    }\n\n    /// @notice View function to get the oracle parameters\n    /// @return oracleSampleLifetime The lifetime of a sample, it accumulates information for up to this timestamp\n    /// @return oracleSize The size of the oracle (last ids can be empty)\n    /// @return oracleActiveSize The active size of the oracle (no empty data)\n    /// @return oracleLastTimestamp The timestamp of the creation of the oracle's latest sample\n    /// @return oracleId The index of the oracle's latest sample\n    /// @return min The min delta time of two samples\n    /// @return max The safe max delta time of two samples\n    function getOracleParameters()\n        external\n        view\n        override\n        returns (\n            uint256 oracleSampleLifetime,\n            uint256 oracleSize,\n            uint256 oracleActiveSize,\n            uint256 oracleLastTimestamp,\n            uint256 oracleId,\n            uint256 min,\n            uint256 max\n        )\n    {\n        (oracleSampleLifetime, oracleSize, oracleActiveSize, oracleLastTimestamp, oracleId) = _getOracleParameters();\n        min = oracleActiveSize == 0 ? 0 : oracleSampleLifetime;\n        max = oracleSampleLifetime * oracleActiveSize;\n    }\n\n    /// @notice View function to get the oracle's sample at `_timeDelta` seconds\n    /// @dev Return a linearized sample, the weighted average of 2 neighboring samples\n    /// @param _timeDelta The number of seconds before the current timestamp\n    /// @return cumulativeId The weighted average cumulative id\n    /// @return cumulativeVolatilityAccumulated The weighted average cumulative volatility accumulated\n    /// @return cumulativeBinCrossed The weighted average cumulative bin crossed\n    function getOracleSampleFrom(uint256 _timeDelta)\n        external\n        view\n        override\n        returns (\n            uint256 cumulativeId,\n            uint256 cumulativeVolatilityAccumulated,\n            uint256 cumulativeBinCrossed\n        )\n    {\n        uint256 _lookUpTimestamp = block.timestamp - _timeDelta;\n\n        (, , uint256 _oracleActiveSize, , uint256 _oracleId) = _getOracleParameters();\n\n        uint256 timestamp;\n        (timestamp, cumulativeId, cumulativeVolatilityAccumulated, cumulativeBinCrossed) = _oracle.getSampleAt(\n            _oracleActiveSize,\n            _oracleId,\n            _lookUpTimestamp\n        );\n\n        if (timestamp < _lookUpTimestamp) {\n            FeeHelper.FeeParameters memory _fp = _feeParameters;\n            uint256 _activeId = _pairInformation.activeId;\n            _fp.updateVariableFeeParameters(_activeId);\n\n            unchecked {\n                uint256 _deltaT = _lookUpTimestamp - timestamp;\n\n                cumulativeId += _activeId * _deltaT;\n                cumulativeVolatilityAccumulated += uint256(_fp.volatilityAccumulated) * _deltaT;\n            }\n        }\n    }\n\n    /// @notice View function to get the fee parameters\n    /// @return The fee parameters\n    function feeParameters() external view override returns (FeeHelper.FeeParameters memory) {\n        return _feeParameters;\n    }\n\n    /// @notice View function to get the first bin that isn't empty, will not be `_id` itself\n    /// @param _id The bin id\n    /// @param _swapForY Whether you've swapping token X for token Y (true) or token Y for token X (false)\n    /// @return The id of the non empty bin\n    function findFirstNonEmptyBinId(uint24 _id, bool _swapForY) external view override returns (uint24) {\n        return _tree.findFirstBin(_id, _swapForY);\n    }\n\n    /// @notice View function to get the bin at `id`\n    /// @param _id The bin id\n    /// @return reserveX The reserve of tokenX of the bin\n    /// @return reserveY The reserve of tokenY of the bin\n    function getBin(uint24 _id) external view override returns (uint256 reserveX, uint256 reserveY) {\n        return _getBin(_id);\n    }\n\n    /// @notice View function to get the pending fees of a user\n    /// @dev The array must be strictly increasing to ensure uniqueness\n    /// @param _account The address of the user\n    /// @param _ids The list of ids\n    /// @return amountX The amount of tokenX pending\n    /// @return amountY The amount of tokenY pending\n    function pendingFees(address _account, uint256[] memory _ids)\n        external\n        view\n        override\n        returns (uint256 amountX, uint256 amountY)\n    {\n        bytes32 _unclaimedData = _unclaimedFees[_account];\n\n        amountX = _unclaimedData.decode(type(uint128).max, 0);\n        amountY = _unclaimedData.decode(type(uint128).max, 128);\n\n        uint256 _lastId;\n        unchecked {\n            for (uint256 i; i < _ids.length; ++i) {\n                uint256 _id = _ids[i];\n\n                // Ensures uniqueness of ids\n                if (_lastId >= _id && i != 0) revert LBPair__OnlyStrictlyIncreasingId();\n\n                uint256 _balance = balanceOf(_account, _id);\n\n                if (_balance != 0) {\n                    Bin memory _bin = _bins[_id];\n\n                    (uint256 _amountX, uint256 _amountY) = _getPendingFees(_bin, _account, _id, _balance);\n\n                    amountX += _amountX;\n                    amountY += _amountY;\n                }\n\n                _lastId = _id;\n            }\n        }\n    }\n\n    /** External Functions **/\n\n    /// @notice Performs a low level swap, this needs to be called from a contract which performs important safety checks\n    /// @dev Will swap the full amount that this contract received of token X or Y\n    /// @param _swapForY whether the token sent was Y (true) or X (false)\n    /// @param _to The address of the recipient\n    /// @return amountXOut The amount of token X sent to `_to`\n    /// @return amountYOut The amount of token Y sent to `_to`\n    function swap(bool _swapForY, address _to)\n        external\n        override\n        nonReentrant\n        returns (uint256 amountXOut, uint256 amountYOut)\n    {\n        PairInformation memory _pair = _pairInformation;\n\n        uint256 _amountIn = _swapForY\n            ? tokenX.received(_pair.reserveX, _pair.feesX.total)\n            : tokenY.received(_pair.reserveY, _pair.feesY.total);\n\n        if (_amountIn == 0) revert LBPair__InsufficientAmounts();\n\n        FeeHelper.FeeParameters memory _fp = _feeParameters;\n        _fp.updateVariableFeeParameters(_pair.activeId);\n        uint256 _startId = _pair.activeId;\n\n        uint256 _amountOut;\n        // Performs the actual swap, bin per bin\n        // It uses the findFirstBin function to make sure the bin we're currently looking at\n        // has liquidity in it.\n        while (true) {\n            Bin memory _bin = _bins[_pair.activeId];\n            if ((!_swapForY && _bin.reserveX != 0) || (_swapForY && _bin.reserveY != 0)) {\n                (uint256 _amountInToBin, uint256 _amountOutOfBin, FeeHelper.FeesDistribution memory _fees) = _bin\n                    .getAmounts(_fp, _pair.activeId, _swapForY, _amountIn);\n\n                _bin.updateFees(_swapForY ? _pair.feesX : _pair.feesY, _fees, _swapForY, totalSupply(_pair.activeId));\n\n                _bin.updateReserves(_pair, _swapForY, _amountInToBin.safe112(), _amountOutOfBin.safe112());\n\n                _amountIn -= _amountInToBin + _fees.total;\n                _amountOut += _amountOutOfBin;\n\n                _bins[_pair.activeId] = _bin;\n\n                if (_swapForY) {\n                    emit Swap(\n                        msg.sender,\n                        _to,\n                        _pair.activeId,\n                        _amountInToBin,\n                        0,\n                        0,\n                        _amountOutOfBin,\n                        _fp.volatilityAccumulated,\n                        _fees.total,\n                        0\n                    );\n                } else {\n                    emit Swap(\n                        msg.sender,\n                        _to,\n                        _pair.activeId,\n                        0,\n                        _amountInToBin,\n                        _amountOutOfBin,\n                        0,\n                        _fp.volatilityAccumulated,\n                        0,\n                        _fees.total\n                    );\n                }\n            }\n\n            if (_amountIn != 0) {\n                _pair.activeId = _tree.findFirstBin(_pair.activeId, _swapForY);\n            } else {\n                break;\n            }\n        }\n\n        if (_amountOut == 0) revert LBPair__BrokenSwapSafetyCheck(); // Safety check\n\n        // We use oracleSize so it can start filling empty slot that were added recently\n        uint256 _updatedOracleId = _oracle.update(\n            _pair.oracleSize,\n            _pair.oracleSampleLifetime,\n            _pair.oracleLastTimestamp,\n            _pair.oracleId,\n            _pair.activeId,\n            _fp.volatilityAccumulated,\n            _startId.absSub(_pair.activeId)\n        );\n\n        // We update the oracleId and lastTimestamp if the sample write on another slot\n        if (_updatedOracleId != _pair.oracleId || _pair.oracleLastTimestamp == 0) {\n            // Can't overflow as the updatedOracleId < oracleSize\n            _pair.oracleId = uint16(_updatedOracleId);\n            _pair.oracleLastTimestamp = block.timestamp.safe40();\n\n            // We increase the activeSize if the updated sample is written in a new slot\n            // Can't overflow as _updatedOracleId < maxSize = 2**16-1\n            unchecked {\n                if (_updatedOracleId == _pair.oracleActiveSize) ++_pair.oracleActiveSize;\n            }\n        }\n\n        _feeParameters = _fp;\n        _pairInformation = _pair;\n\n        if (_swapForY) {\n            amountYOut = _amountOut;\n            tokenY.safeTransfer(_to, _amountOut);\n        } else {\n            amountXOut = _amountOut;\n            tokenX.safeTransfer(_to, _amountOut);\n        }\n    }\n\n    /// @notice Performs a flash loan\n    /// @param _to the address that will execute the external call\n    /// @param _amountXOut The amount of tokenX\n    /// @param _amountYOut The amount of tokenY\n    /// @param _data The bytes data that will be forwarded to _to\n    function flashLoan(\n        address _to,\n        uint256 _amountXOut,\n        uint256 _amountYOut,\n        bytes calldata _data\n    ) external override nonReentrant {\n        FeeHelper.FeeParameters memory _fp = _feeParameters;\n\n        uint256 _fee = factory.flashLoanFee();\n\n        FeeHelper.FeesDistribution memory _feesX = _fp.getFeeAmountDistribution(_getFlashLoanFee(_amountXOut, _fee));\n        FeeHelper.FeesDistribution memory _feesY = _fp.getFeeAmountDistribution(_getFlashLoanFee(_amountYOut, _fee));\n\n        (uint256 _reserveX, uint256 _reserveY, uint256 _id) = _getReservesAndId();\n\n        tokenX.safeTransfer(_to, _amountXOut);\n        tokenY.safeTransfer(_to, _amountYOut);\n\n        ILBFlashLoanCallback(_to).LBFlashLoanCallback(\n            msg.sender,\n            _amountXOut,\n            _amountYOut,\n            _feesX.total,\n            _feesY.total,\n            _data\n        );\n\n        _feesX.flashLoanHelper(_pairInformation.feesX, tokenX, _reserveX);\n        _feesY.flashLoanHelper(_pairInformation.feesY, tokenY, _reserveY);\n\n        uint256 _totalSupply = totalSupply(_id);\n\n        _bins[_id].accTokenXPerShare += _feesX.getTokenPerShare(_totalSupply);\n        _bins[_id].accTokenYPerShare += _feesY.getTokenPerShare(_totalSupply);\n\n        emit FlashLoan(msg.sender, _to, _amountXOut, _amountYOut, _feesX.total, _feesY.total);\n    }\n\n    /// @notice Performs a low level add, this needs to be called from a contract which performs important safety checks.\n    /// @param _ids The list of ids to add liquidity\n    /// @param _distributionX The distribution of tokenX with sum(_distributionX) = 1e18 (100%) or 0 (0%)\n    /// @param _distributionY The distribution of tokenY with sum(_distributionY) = 1e18 (100%) or 0 (0%)\n    /// @param _to The address of the recipient\n    /// @return The amount of token X that was added to the pair\n    /// @return The amount of token Y that was added to the pair\n    /// @return liquidityMinted Amount of LBToken minted\n    function mint(\n        uint256[] memory _ids,\n        uint256[] memory _distributionX,\n        uint256[] memory _distributionY,\n        address _to\n    )\n        external\n        override\n        nonReentrant\n        returns (\n            uint256,\n            uint256,\n            uint256[] memory liquidityMinted\n        )\n    {\n        if (_ids.length == 0 || _ids.length != _distributionX.length || _ids.length != _distributionY.length)\n            revert LBPair__WrongLengths();\n\n        PairInformation memory _pair = _pairInformation;\n\n        FeeHelper.FeeParameters memory _fp = _feeParameters;\n\n        MintInfo memory _mintInfo;\n\n        _mintInfo.amountXIn = tokenX.received(_pair.reserveX, _pair.feesX.total).safe128();\n        _mintInfo.amountYIn = tokenY.received(_pair.reserveY, _pair.feesY.total).safe128();\n\n        liquidityMinted = new uint256[](_ids.length);\n\n        unchecked {\n            for (uint256 i; i < _ids.length; ++i) {\n                _mintInfo.id = _ids[i].safe24();\n                Bin memory _bin = _bins[_mintInfo.id];\n\n                if (_bin.reserveX == 0 && _bin.reserveY == 0) _tree.addToTree(_mintInfo.id);\n\n                _mintInfo.distributionX = _distributionX[i];\n                _mintInfo.distributionY = _distributionY[i];\n\n                if (\n                    _mintInfo.distributionX > Constants.PRECISION ||\n                    _mintInfo.distributionY > Constants.PRECISION ||\n                    (_mintInfo.totalDistributionX += _mintInfo.distributionX) > Constants.PRECISION ||\n                    (_mintInfo.totalDistributionY += _mintInfo.distributionY) > Constants.PRECISION\n                ) revert LBPair__DistributionsOverflow();\n\n                // Can't overflow as amounts are uint128 and distributions are smaller or equal to 1e18\n                _mintInfo.amountX = (_mintInfo.amountXIn * _mintInfo.distributionX) / Constants.PRECISION;\n                _mintInfo.amountY = (_mintInfo.amountYIn * _mintInfo.distributionY) / Constants.PRECISION;\n\n                uint256 _price = BinHelper.getPriceFromId(_mintInfo.id, _fp.binStep);\n                if (_mintInfo.id >= _pair.activeId) {\n                    if (_mintInfo.id == _pair.activeId) {\n                        uint256 _totalSupply = totalSupply(_mintInfo.id);\n\n                        uint256 _userL = _price.mulShiftRoundDown(_mintInfo.amountX, Constants.SCALE_OFFSET) +\n                            _mintInfo.amountY;\n\n                        uint256 _receivedX;\n                        uint256 _receivedY;\n                        {\n                            uint256 _supply = _totalSupply + _userL;\n                            _receivedX = (_userL * (uint256(_bin.reserveX) + _mintInfo.amountX)) / _supply;\n                            _receivedY = (_userL * (uint256(_bin.reserveY) + _mintInfo.amountY)) / _supply;\n                        }\n\n                        _fp.updateVariableFeeParameters(_mintInfo.id);\n\n                        if (_mintInfo.amountX > _receivedX) {\n                            FeeHelper.FeesDistribution memory _fees = _fp.getFeeAmountDistribution(\n                                _fp.getFeeAmountForC(_mintInfo.amountX - _receivedX)\n                            );\n\n                            _mintInfo.amountX -= _fees.total;\n                            _mintInfo.activeFeeX += _fees.total;\n\n                            _bin.updateFees(_pair.feesX, _fees, true, _totalSupply);\n\n                            emit CompositionFee(msg.sender, _to, _mintInfo.id, _fees.total, 0);\n                        } else if (_mintInfo.amountY > _receivedY) {\n                            FeeHelper.FeesDistribution memory _fees = _fp.getFeeAmountDistribution(\n                                _fp.getFeeAmountForC(_mintInfo.amountY - _receivedY)\n                            );\n\n                            _mintInfo.amountY -= _fees.total;\n                            _mintInfo.activeFeeY += _fees.total;\n\n                            _bin.updateFees(_pair.feesY, _fees, false, _totalSupply);\n\n                            emit CompositionFee(msg.sender, _to, _mintInfo.id, 0, _fees.total);\n                        }\n                    } else if (_mintInfo.amountY != 0) revert LBPair__CompositionFactorFlawed(_mintInfo.id);\n                } else if (_mintInfo.amountX != 0) revert LBPair__CompositionFactorFlawed(_mintInfo.id);\n\n                uint256 _liquidity = _price.mulShiftRoundDown(_mintInfo.amountX, Constants.SCALE_OFFSET) +\n                    _mintInfo.amountY;\n\n                if (_liquidity == 0) revert LBPair__InsufficientLiquidityMinted(_mintInfo.id);\n\n                liquidityMinted[i] = _liquidity;\n\n                // The addition can't overflow as the amounts are checked to be uint128 and the reserves are uint112\n                _bin.reserveX = (_mintInfo.amountX + _bin.reserveX).safe112();\n                _bin.reserveY = (_mintInfo.amountY + _bin.reserveY).safe112();\n\n                // The addition or the cast can't overflow as it would have reverted during the L568 and L569 if amounts were greater than uint112\n                _pair.reserveX += uint112(_mintInfo.amountX);\n                _pair.reserveY += uint112(_mintInfo.amountY);\n\n                _mintInfo.amountXAddedToPair += _mintInfo.amountX;\n                _mintInfo.amountYAddedToPair += _mintInfo.amountY;\n\n                _bins[_mintInfo.id] = _bin;\n                _mint(_to, _mintInfo.id, _liquidity);\n\n                emit LiquidityAdded(\n                    msg.sender,\n                    _to,\n                    _mintInfo.id,\n                    _liquidity,\n                    _mintInfo.amountX,\n                    _mintInfo.amountY,\n                    _mintInfo.distributionX,\n                    _mintInfo.distributionY\n                );\n            }\n\n            _pairInformation = _pair;\n\n            uint256 _amountAddedPlusFee = _mintInfo.amountXAddedToPair + _mintInfo.activeFeeX;\n            // If user sent too much tokens, We send them back the excess\n            if (_mintInfo.amountXIn > _amountAddedPlusFee) {\n                tokenX.safeTransfer(_to, _mintInfo.amountXIn - _amountAddedPlusFee);\n            }\n\n            _amountAddedPlusFee = _mintInfo.amountYAddedToPair + _mintInfo.activeFeeY;\n            if (_mintInfo.amountYIn > _amountAddedPlusFee) {\n                tokenY.safeTransfer(_to, _mintInfo.amountYIn - _amountAddedPlusFee);\n            }\n        }\n\n        return (_mintInfo.amountXAddedToPair, _mintInfo.amountYAddedToPair, liquidityMinted);\n    }\n\n    /// @notice Performs a low level remove, this needs to be called from a contract which performs important safety checks\n    /// @param _ids The ids the user want to remove its liquidity\n    /// @param _amounts The amount of token to burn\n    /// @param _to The address of the recipient\n    /// @return amountX The amount of token X sent to `_to`\n    /// @return amountY The amount of token Y sent to `_to`\n    function burn(\n        uint256[] memory _ids,\n        uint256[] memory _amounts,\n        address _to\n    ) external override nonReentrant returns (uint256 amountX, uint256 amountY) {\n        (uint256 _pairReserveX, uint256 _pairReserveY, uint256 _activeId) = _getReservesAndId();\n        unchecked {\n            for (uint256 i; i < _ids.length; ++i) {\n                uint24 _id = _ids[i].safe24();\n                uint256 _amountToBurn = _amounts[i];\n\n                if (_amountToBurn == 0) revert LBPair__InsufficientLiquidityBurned(_id);\n\n                (uint256 _reserveX, uint256 _reserveY) = _getBin(_id);\n\n                uint256 _totalSupply = totalSupply(_id);\n\n                uint256 _amountX;\n                uint256 _amountY;\n\n                if (_id <= _activeId) {\n                    _amountY = _amountToBurn.mulDivRoundDown(_reserveY, _totalSupply);\n\n                    amountY += _amountY;\n                    _reserveY -= _amountY;\n                    _pairReserveY -= _amountY;\n                }\n                if (_id >= _activeId) {\n                    _amountX = _amountToBurn.mulDivRoundDown(_reserveX, _totalSupply);\n\n                    amountX += _amountX;\n                    _reserveX -= _amountX;\n                    _pairReserveX -= _amountX;\n                }\n\n                if (_reserveX == 0 && _reserveY == 0) _tree.removeFromTree(_id);\n\n                // Optimized `_bins[_id] = _bin` to do only 1 sstore\n                assembly {\n                    mstore(0, _id)\n                    mstore(32, _bins.slot)\n                    let slot := keccak256(0, 64)\n\n                    let reserves := add(shl(_OFFSET_BIN_RESERVE_Y, _reserveY), _reserveX)\n                    sstore(slot, reserves)\n                }\n\n                _burn(address(this), _id, _amountToBurn);\n\n                emit LiquidityRemoved(msg.sender, _to, _id, _amountToBurn, _amountX, _amountY);\n            }\n        }\n\n        // Optimization to do only 2 sstore\n        _pairInformation.reserveX = uint136(_pairReserveX);\n        _pairInformation.reserveY = uint136(_pairReserveY);\n\n        tokenX.safeTransfer(_to, amountX);\n        tokenY.safeTransfer(_to, amountY);\n    }\n\n    /// @notice Increase the length of the oracle\n    /// @param _newSize The new size of the oracle. Needs to be bigger than current one\n    function increaseOracleLength(uint16 _newSize) external override {\n        _increaseOracle(_newSize);\n    }\n\n    /// @notice Collect fees of an user\n    /// @param _account The address of the user\n    /// @param _ids The list of bin ids to collect fees in\n    /// @return amountX The amount of tokenX claimed\n    /// @return amountY The amount of tokenY claimed\n    function collectFees(address _account, uint256[] memory _ids)\n        external\n        override\n        nonReentrant\n        returns (uint256 amountX, uint256 amountY)\n    {\n        unchecked {\n            bytes32 _unclaimedData = _unclaimedFees[_account];\n            delete _unclaimedFees[_account];\n\n            amountX = _unclaimedData.decode(type(uint128).max, 0);\n            amountY = _unclaimedData.decode(type(uint128).max, 128);\n\n            for (uint256 i; i < _ids.length; ++i) {\n                uint256 _id = _ids[i];\n                uint256 _balance = balanceOf(_account, _id);\n\n                if (_balance != 0) {\n                    Bin memory _bin = _bins[_id];\n\n                    (uint256 _amountX, uint256 _amountY) = _getPendingFees(_bin, _account, _id, _balance);\n                    _updateUserDebts(_bin, _account, _id, _balance);\n\n                    amountX += _amountX;\n                    amountY += _amountY;\n                }\n            }\n\n            if (amountX != 0) {\n                _pairInformation.feesX.total -= uint128(amountX);\n            }\n            if (amountY != 0) {\n                _pairInformation.feesY.total -= uint128(amountY);\n            }\n\n            tokenX.safeTransfer(_account, amountX);\n            tokenY.safeTransfer(_account, amountY);\n\n            emit FeesCollected(msg.sender, _account, amountX, amountY);\n        }\n    }\n\n    /// @notice Collect the protocol fees and send them to the feeRecipient\n    /// @dev The balances are not zeroed to save gas by not resetting the storage slot\n    /// Only callable by the fee recipient\n    /// @return amountX The amount of tokenX claimed\n    /// @return amountY The amount of tokenY claimed\n    function collectProtocolFees() external override nonReentrant returns (uint256 amountX, uint256 amountY) {\n        unchecked {\n            address _feeRecipient = factory.feeRecipient();\n\n            if (msg.sender != _feeRecipient) revert LBPair__OnlyFeeRecipient(_feeRecipient, msg.sender);\n\n            // The fees returned can't be greater than uint128, so the assembly blocks are safe\n            (\n                uint256 _feesXTotal,\n                uint256 _feesYTotal,\n                uint256 _feesXProtocol,\n                uint256 _feesYProtocol\n            ) = _getGlobalFees();\n\n            if (_feesXProtocol > 1) {\n                amountX = _feesXProtocol - 1;\n                _feesXTotal -= amountX;\n\n                // Assembly block that does:\n                // _pairInformation.feesX = FeeHelper.FeesDistribution({total: _feesXTotal, protocol: 1});\n                assembly {\n                    let _slotX := add(_pairInformation.slot, 2)\n\n                    sstore(_slotX, add(shl(_OFFSET_PROTOCOL_FEE, 1), _feesXTotal))\n                }\n\n                tokenX.safeTransfer(_feeRecipient, amountX);\n            }\n\n            if (_feesYProtocol > 1) {\n                amountY = _feesYProtocol - 1;\n                _feesYTotal -= amountY;\n\n                // Assembly block that does:\n                // _pairInformation.feesY = FeeHelper.FeesDistribution({total: _feesYTotal, protocol: 1});\n                assembly {\n                    let _slotY := add(_pairInformation.slot, 3)\n\n                    sstore(_slotY, add(shl(_OFFSET_PROTOCOL_FEE, 1), _feesYTotal))\n                }\n\n                tokenY.safeTransfer(_feeRecipient, amountY);\n            }\n\n            emit ProtocolFeesCollected(msg.sender, _feeRecipient, amountX, amountY);\n        }\n    }\n\n    /// @notice Set the fees parameters\n    /// @dev Needs to be called by the factory that will validate the values\n    /// The bin step will not change\n    /// Only callable by the factory\n    /// @param _packedFeeParameters The packed fee parameters\n    function setFeesParameters(bytes32 _packedFeeParameters) external override onlyFactory {\n        _setFeesParameters(_packedFeeParameters);\n    }\n\n    function forceDecay() external override onlyFactory {\n        unchecked {\n            _feeParameters.volatilityReference = uint24(\n                (uint256(_feeParameters.reductionFactor) * _feeParameters.volatilityReference) /\n                    Constants.BASIS_POINT_MAX\n            );\n        }\n    }\n\n    /** Internal Functions **/\n\n    /// @notice Collect and update fees before any token transfer, mint or burn\n    /// @param _from The address of the owner of the token\n    /// @param _to The address of the recipient of the  token\n    /// @param _id The id of the token\n    /// @param _amount The amount of token of type `id`\n    function _beforeTokenTransfer(\n        address _from,\n        address _to,\n        uint256 _id,\n        uint256 _amount\n    ) internal override(LBToken) {\n        unchecked {\n            super._beforeTokenTransfer(_from, _to, _id, _amount);\n\n            Bin memory _bin = _bins[_id];\n\n            if (_from != _to) {\n                if (_from != address(0) && _from != address(this)) {\n                    uint256 _balanceFrom = balanceOf(_from, _id);\n\n                    _cacheFees(_bin, _from, _id, _balanceFrom, _balanceFrom - _amount);\n                }\n\n                if (_to != address(0) && _to != address(this)) {\n                    uint256 _balanceTo = balanceOf(_to, _id);\n\n                    _cacheFees(_bin, _to, _id, _balanceTo, _balanceTo + _amount);\n                }\n            }\n        }\n    }\n\n    /** Private Functions **/\n\n    /// @notice View function to get the pending fees of an account on a given bin\n    /// @param _bin  The bin where the user is collecting fees\n    /// @param _account The address of the user\n    /// @param _id The id where the user is collecting fees\n    /// @param _balance The previous balance of the user\n    /// @return amountX The amount of tokenX pending for the account\n    /// @return amountY The amount of tokenY pending for the account\n    function _getPendingFees(\n        Bin memory _bin,\n        address _account,\n        uint256 _id,\n        uint256 _balance\n    ) private view returns (uint256 amountX, uint256 amountY) {\n        Debts memory _debts = _accruedDebts[_account][_id];\n\n        amountX = _bin.accTokenXPerShare.mulShiftRoundDown(_balance, Constants.SCALE_OFFSET) - _debts.debtX;\n        amountY = _bin.accTokenYPerShare.mulShiftRoundDown(_balance, Constants.SCALE_OFFSET) - _debts.debtY;\n    }\n\n    /// @notice Update fees of a given user\n    /// @param _bin The bin where the user has collected fees\n    /// @param _account The address of the user\n    /// @param _id The id where the user has collected fees\n    /// @param _balance The new balance of the user\n    function _updateUserDebts(\n        Bin memory _bin,\n        address _account,\n        uint256 _id,\n        uint256 _balance\n    ) private {\n        uint256 _debtX = _bin.accTokenXPerShare.mulShiftRoundDown(_balance, Constants.SCALE_OFFSET);\n        uint256 _debtY = _bin.accTokenYPerShare.mulShiftRoundDown(_balance, Constants.SCALE_OFFSET);\n\n        _accruedDebts[_account][_id].debtX = _debtX;\n        _accruedDebts[_account][_id].debtY = _debtY;\n    }\n\n    /// @notice Update the unclaimed fees of a given user before a transfer\n    /// @param _bin The bin where the user has collected fees\n    /// @param _user The address of the user\n    /// @param _id The id where the user has collected fees\n    /// @param _previousBalance The previous balance of the user\n    /// @param _newBalance The new balance of the user\n    function _cacheFees(\n        Bin memory _bin,\n        address _user,\n        uint256 _id,\n        uint256 _previousBalance,\n        uint256 _newBalance\n    ) private {\n        unchecked {\n            bytes32 _unclaimedData = _unclaimedFees[_user];\n\n            uint256 amountX = _unclaimedData.decode(type(uint128).max, 0);\n            uint256 amountY = _unclaimedData.decode(type(uint128).max, 128);\n\n            (uint256 _amountX, uint256 _amountY) = _getPendingFees(_bin, _user, _id, _previousBalance);\n            _updateUserDebts(_bin, _user, _id, _newBalance);\n\n            (amountX += _amountX).safe128();\n            (amountY += _amountY).safe128();\n\n            _unclaimedFees[_user] = bytes32((amountY << 128) | amountX);\n        }\n    }\n\n    /// @notice Internal function to set the fee parameters of the pair\n    /// @param _packedFeeParameters The packed fee parameters\n    function _setFeesParameters(bytes32 _packedFeeParameters) internal {\n        bytes32 _feeStorageSlot;\n        assembly {\n            _feeStorageSlot := sload(_feeParameters.slot)\n        }\n\n        uint256 _varParameters = _feeStorageSlot.decode(type(uint112).max, _OFFSET_VARIABLE_FEE_PARAMETERS);\n        uint256 _newFeeParameters = _packedFeeParameters.decode(type(uint144).max, 0);\n\n        assembly {\n            sstore(_feeParameters.slot, or(_newFeeParameters, _varParameters))\n        }\n    }\n\n    /// @notice Private function to increase the oracle's number of sample\n    /// @param _newSize The new size of the oracle. Needs to be bigger than current one\n    function _increaseOracle(uint16 _newSize) private {\n        uint256 _oracleSize = _pairInformation.oracleSize;\n\n        if (_oracleSize >= _newSize) revert LBPair__NewSizeTooSmall(_newSize, _oracleSize);\n\n        _pairInformation.oracleSize = _newSize;\n\n        unchecked {\n            for (uint256 _id = _oracleSize; _id < _newSize; ++_id) {\n                _oracle.initialize(_id);\n            }\n        }\n\n        emit OracleSizeIncreased(_oracleSize, _newSize);\n    }\n\n    /// @notice Private view function to return the oracle's parameters\n    /// @return oracleSampleLifetime The lifetime of a sample, it accumulates information for up to this timestamp\n    /// @return oracleSize The size of the oracle (last ids can be empty)\n    /// @return oracleActiveSize The active size of the oracle (no empty data)\n    /// @return oracleLastTimestamp The timestamp of the creation of the oracle's latest sample\n    /// @return oracleId The index of the oracle's latest sample\n    function _getOracleParameters()\n        internal\n        view\n        returns (\n            uint256 oracleSampleLifetime,\n            uint256 oracleSize,\n            uint256 oracleActiveSize,\n            uint256 oracleLastTimestamp,\n            uint256 oracleId\n        )\n    {\n        bytes32 _slot;\n        assembly {\n            _slot := sload(add(_pairInformation.slot, 1))\n        }\n        oracleSampleLifetime = _slot.decode(type(uint16).max, _OFFSET_ORACLE_SAMPLE_LIFETIME);\n        oracleSize = _slot.decode(type(uint16).max, _OFFSET_ORACLE_SIZE);\n        oracleActiveSize = _slot.decode(type(uint16).max, _OFFSET_ORACLE_ACTIVE_SIZE);\n        oracleLastTimestamp = _slot.decode(type(uint40).max, _OFFSET_ORACLE_LAST_TIMESTAMP);\n        oracleId = _slot.decode(type(uint24).max, _OFFSET_ORACLE_ID);\n    }\n\n    /// @notice Internal view function to get the reserves and active id\n    /// @return reserveX The reserve of asset X\n    /// @return reserveY The reserve of asset Y\n    /// @return activeId The active id of the pair\n    function _getReservesAndId()\n        internal\n        view\n        returns (\n            uint256 reserveX,\n            uint256 reserveY,\n            uint256 activeId\n        )\n    {\n        uint256 _mask24 = type(uint24).max;\n        uint256 _mask136 = type(uint136).max;\n        assembly {\n            let slot := sload(add(_pairInformation.slot, 1))\n            reserveY := and(slot, _mask136)\n\n            slot := sload(_pairInformation.slot)\n            activeId := and(slot, _mask24)\n            reserveX := and(shr(_OFFSET_PAIR_RESERVE_X, slot), _mask136)\n        }\n    }\n\n    /// @notice Internal view function to get the bin at `id`\n    /// @param _id The bin id\n    /// @return reserveX The reserve of tokenX of the bin\n    /// @return reserveY The reserve of tokenY of the bin\n    function _getBin(uint24 _id) internal view returns (uint256 reserveX, uint256 reserveY) {\n        bytes32 _data;\n        uint256 _mask112 = type(uint112).max;\n        // low level read of mapping to only load 1 storage slot\n        assembly {\n            mstore(0, _id)\n            mstore(32, _bins.slot)\n            _data := sload(keccak256(0, 64))\n\n            reserveX := and(_data, _mask112)\n            reserveY := shr(_OFFSET_BIN_RESERVE_Y, _data)\n        }\n\n        return (reserveX.safe112(), reserveY.safe112());\n    }\n\n    /// @notice Internal view function to get the global fees information, the total fees and those for protocol\n    /// @dev The fees for users are `total - protocol`\n    /// @return feesXTotal The total fees of asset X\n    /// @return feesYTotal The total fees of asset Y\n    /// @return feesXProtocol The protocol fees of asset X\n    /// @return feesYProtocol The protocol fees of asset Y\n    function _getGlobalFees()\n        internal\n        view\n        returns (\n            uint256 feesXTotal,\n            uint256 feesYTotal,\n            uint256 feesXProtocol,\n            uint256 feesYProtocol\n        )\n    {\n        bytes32 _slotX;\n        bytes32 _slotY;\n        assembly {\n            _slotX := sload(add(_pairInformation.slot, 2))\n            _slotY := sload(add(_pairInformation.slot, 3))\n        }\n\n        feesXTotal = _slotX.decode(type(uint128).max, 0);\n        feesYTotal = _slotY.decode(type(uint128).max, 0);\n\n        feesXProtocol = _slotX.decode(type(uint128).max, _OFFSET_PROTOCOL_FEE);\n        feesYProtocol = _slotY.decode(type(uint128).max, _OFFSET_PROTOCOL_FEE);\n    }\n\n    /// @notice Internal pure function to return the flashloan fee amount\n    /// @param _amount The amount to flashloan\n    /// @param _fee the fee percentage, in basis point\n    /// @return The fee amount\n    function _getFlashLoanFee(uint256 _amount, uint256 _fee) internal pure returns (uint256) {\n        return (_amount * _fee) / Constants.PRECISION;\n    }\n}"
}