Skip to content
Verified contractExactBUSL-1.1

FluidMoneyMarketD3D4ValuationModule

Address0x0e478d9cfecf36f1d3555c1b7f2d20d93a2d17bd
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.36

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.36+commit.8a079791
Language
solidity
Optimization
Yes, 10,000,000 runs
EVM version
cancun
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,280,092
Creation transaction
0x7ad018fc4e…dc96e73a92

56 files

The source code is large: one file is shown at a time. Choose a file in the list.

contracts/protocols/moneyMarket/core/d3d4Module/valuation.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;

import "./valuationHelpers.sol";

import { LiquidateVariables } from "../liquidateModule/structs.sol";

/// @title FluidMoneyMarketD3D4ValuationModule
/// @notice Valuation-side module of the D3 / D4 position types: their health-factor contribution (`valuePositions`),
///         their `changeEmode` class checks (`validateEmodeChange`), the D4 payback leg (`liquidatePayback`) and the
///         D3 withdraw / D4 fee-store legs (`liquidateWithdraw`) of a liquidation, and the range gate of the ops module
///         evaluated against the oracle-implied price (`verifyRangeWithinOracleBand`). See SPEC.md §7.1.2, §7.2, §9.
/// @dev Reached only by `delegatecall` through `_spell` (`IFluidMoneyMarketDexValuationModule`): `valuePositions`
///      from the shared `_getHfInfo` (one hop per `_checkHf` / `getHfInfo` of an NFT holding a D3 / D4 position),
///      `validateEmodeChange` from the base, the two liquidation legs from the liquidate module. Runs in the proxy's
///      storage with the outer `msg.sender` / `msg.value`; `_onlyDelegateCall` rejects a direct call with empty data.
///      Every function is `payable` because the delegatecall carries the outer `msg.value` of the payable `operate` /
///      `liquidate` / `changeEmode` (a non-payable function would reject it), none of them reads it; `validateEmodeChange`
///      is therefore not `view` although it writes nothing. Never calls `_checkHf` / `_getHfInfo` itself. Every body is the former inline code of the base, the shared
///      helpers and the liquidate module, unchanged: the reverts are the same (empty data for a price outside the
///      band, `_calculateSqrtPriceX96` overflow and the D3 / D4 helper checks; `Base__InvalidParams` from the emode
///      checks; `LiquidateModule__InvalidParams` from the legs, including a position type the leg does not serve;
///      bubbled Liquidity, DexV2 and oracle errors) and `_spell` re-raises them unchanged.
///      Trust assumptions: as the shared helpers — the oracle of `_moneyMarketVariables`, Liquidity's exchange prices
///      and DexV2's storage layout (`DexV2D3D4CommonSlotsLink`) are interfaces of this module; `DEX_V2` is this
///      module's own immutable (the D4 payback and fee-collection legs call DexV2 `payback`, which requires the proxy
///      on DexV2's D4 user whitelist).
contract FluidMoneyMarketD3D4ValuationModule is D3D4ValuationHelpers {
    /// @dev Address of this module contract, captured at construction; under delegatecall `address(this)` is the proxy
    address internal immutable THIS_ADDRESS;

    /// @dev Ensures function is called via delegatecall, not directly
    ///      (a direct call, i.e. `address(this) == THIS_ADDRESS`, reverts with empty data)
    modifier _onlyDelegateCall() {
        if (address(this) == THIS_ADDRESS) {
            revert();
        }
        _;
    }

    /// @notice Initializes the D3 / D4 valuation module
    /// @dev Dereferences no other module, so none is checked; `LIQUIDITY` / `DEX_V2` are this module's own copies
    ///      under delegatecall and are what the other constructors compare against through `liquidityAndDexV2()`.
    /// @param liquidity_ The FluidLiquidity contract address
    /// @param dexV2_ The FluidDexV2 contract address
    /// @param modules_ The deployed module addresses (all fields ignored, may be zero)
    constructor(
        address liquidity_,
        address dexV2_,
        ModuleAddresses memory modules_
    ) ImmutableVariables(liquidity_, dexV2_, modules_, 0) {
        THIS_ADDRESS = address(this);
    }

    /// @notice Values the D3 / D4 positions of an NFT for `_getHfInfo` (SPEC.md §9.2); the D3 / D4 branch of the
    ///         former loop, unchanged, applied to every type-3 / type-4 word of `p_.positionData` in index order.
    /// @dev Per position: rebuild the `DexKey`, read the fee store at `(positionId, dexV2PositionId)` and value the
    ///      range at the oracle-implied `sqrtPriceX96`, never at the pool price: D3 amounts plus stored and accrued
    ///      fees are collateral, both legs at the lower of the two tokens' CF / LT (`_dexCollateralTokenConfigs`); D4
    ///      debt goes to the debt value and its stored plus accrued fees are collateral at freshly fetched
    ///      collateral-side prices and each token's own CF / LT, so a D4 position contributes to both sides. Two
    ///      oracle calls per D3, four per D4, plus Liquidity and DexV2 storage reads per leg; nothing is cached. Zero
    ///      words and other types are skipped. Reverts with empty data for a price outside the band and when the
    ///      oracle price ratio overflows `_calculateSqrtPriceX96`; oracle and `FluidLiquidityCalcsError` errors
    ///      bubble unchanged.
    /// @param p_ `ValuePositionsParams`: the NFT, its emode, the valuation basis, the oracle and the position words
    /// @return collateralValue_ The sum of the unweighted collateral legs, `1e27` units
    /// @return normalizedCollateralValue_ The sum of the CF- (operate) or LT- (liquidate) weighted collateral legs
    /// @return debtValue_ The sum of the D4 debt legs, `1e27` units
    function valuePositions(
        ValuePositionsParams calldata p_
    )
        external
        payable
        _onlyDelegateCall
        returns (uint256 collateralValue_, uint256 normalizedCollateralValue_, uint256 debtValue_)
    {
        GetHfVariables memory v_;
        v_.oracle = p_.oracle;
        v_.emode = p_.emode;
        v_.dexPositions = p_.positionData;

        HfInfo memory hfInfo_ = _valuePositions(p_.nftId, p_.isOperate, v_);
        return (hfInfo_.collateralValue, hfInfo_.normalizedCollateralValue, hfInfo_.debtValue);
    }

    /// @dev The loop of `valuePositions` over `v_.dexPositions`, in its own frame with the locals of the former
    ///      `_getHfInfo` (`nftId_`, `isOperate_`, `v_`, `hfInfo_`, the index, the word and its type) so that the moved
    ///      branch compiles unchanged within the stack limit.
    function _valuePositions(
        uint256 nftId_,
        bool isOperate_,
        GetHfVariables memory v_
    ) internal returns (HfInfo memory hfInfo_) {
        for (uint256 i_ = 0; i_ < v_.dexPositions.length; i_++) {
            uint256 positionData_ = v_.dexPositions[i_];
            uint256 positionType_ = (positionData_ >> MSL.BITS_POSITION_DATA_POSITION_TYPE) & X5;
            if (positionType_ == D3_POSITION_TYPE || positionType_ == D4_POSITION_TYPE) {
                // Build the dex key
                DexKey memory dexKey_;
                GetHfD3D4Variables memory vhf_;

                vhf_.token0Configs = _getTokenConfigs(
                    v_.emode,
                    (positionData_ >> MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_TOKEN_0_INDEX) & X12
                );
                vhf_.token1Configs = _getTokenConfigs(
                    v_.emode,
                    (positionData_ >> MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_TOKEN_1_INDEX) & X12
                );

                (dexKey_, vhf_.tickLower, vhf_.tickUpper) = _decodeD3D4PositionData(
                    positionData_,
                    vhf_.token0Configs,
                    vhf_.token1Configs
                );

                vhf_.positionSalt = keccak256(abi.encode(nftId_));

                vhf_.positionFeeStored = _positionFeeStored[nftId_][keccak256(abi.encode(positionType_, dexKey_))][
                    keccak256(abi.encode(address(this), vhf_.tickLower, vhf_.tickUpper, vhf_.positionSalt))
                ];

                if (positionType_ == D3_POSITION_TYPE) {
                    vhf_.token0Price = _getPrice(
                        v_.oracle,
                        dexKey_.token0,
                        (vhf_.token0Configs >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) & X5,
                        v_.emode,
                        isOperate_,
                        IS_COLLATERAL
                    );

                    vhf_.token1Price = _getPrice(
                        v_.oracle,
                        dexKey_.token1,
                        (vhf_.token1Configs >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) & X5,
                        v_.emode,
                        isOperate_,
                        IS_COLLATERAL
                    );

                    uint256 token0SupplyAmount_;
                    uint256 token1SupplyAmount_;
                    {
                        uint256 feeAccruedToken0_;
                        uint256 feeAccruedToken1_;
                        {
                            (uint256 token0SupplyExchangePrice_, ) = _getExchangePrices(dexKey_.token0);
                            (uint256 token1SupplyExchangePrice_, ) = _getExchangePrices(dexKey_.token1);

                            uint256 token0Decimals_ = (vhf_.token0Configs >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) &
                                X5;
                            uint256 token1Decimals_ = (vhf_.token1Configs >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) &
                                X5;

                            uint256 sqrtPriceX96_ = _calculateSqrtPriceX96(
                                vhf_.token0Price,
                                vhf_.token1Price,
                                token0SupplyExchangePrice_,
                                token1SupplyExchangePrice_,
                                token0Decimals_,
                                token1Decimals_
                            );

                            (
                                token0SupplyAmount_,
                                token1SupplyAmount_,
                                feeAccruedToken0_,
                                feeAccruedToken1_
                            ) = _getD3SupplyAmounts(
                                _getDexId(dexKey_),
                                GetD3D4AmountsParams({
                                    tickLower: vhf_.tickLower,
                                    tickUpper: vhf_.tickUpper,
                                    positionSalt: vhf_.positionSalt,
                                    token0Decimals: token0Decimals_,
                                    token1Decimals: token1Decimals_,
                                    token0ExchangePrice: token0SupplyExchangePrice_,
                                    token1ExchangePrice: token1SupplyExchangePrice_,
                                    sqrtPriceX96: sqrtPriceX96_
                                })
                            );
                        }

                        // Now we need add fee stored and fees accrued to this amount also
                        token0SupplyAmount_ +=
                            ((vhf_.positionFeeStored >> MSL.BITS_POSITION_FEE_STORED_FEE_STORED_TOKEN_0) & X128) +
                            feeAccruedToken0_;
                        token1SupplyAmount_ +=
                            ((vhf_.positionFeeStored >> MSL.BITS_POSITION_FEE_STORED_FEE_STORED_TOKEN_1) & X128) +
                            feeAccruedToken1_;
                    }

                    // Both legs at the lower of the two tokens' CF / LT: the pool is one collateral
                    uint256 configs_ = _dexCollateralTokenConfigs(vhf_.token0Configs, vhf_.token1Configs);
                    (hfInfo_.collateralValue, hfInfo_.normalizedCollateralValue) = _calculateCollateralValues(
                        isOperate_,
                        token0SupplyAmount_,
                        vhf_.token0Price,
                        configs_,
                        hfInfo_.collateralValue,
                        hfInfo_.normalizedCollateralValue
                    );
                    (hfInfo_.collateralValue, hfInfo_.normalizedCollateralValue) = _calculateCollateralValues(
                        isOperate_,
                        token1SupplyAmount_,
                        vhf_.token1Price,
                        configs_,
                        hfInfo_.collateralValue,
                        hfInfo_.normalizedCollateralValue
                    );
                } else {
                    vhf_.token0Price = _getPrice(
                        v_.oracle,
                        dexKey_.token0,
                        (vhf_.token0Configs >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) & X5,
                        v_.emode,
                        isOperate_,
                        IS_DEBT
                    );
                    vhf_.token1Price = _getPrice(
                        v_.oracle,
                        dexKey_.token1,
                        (vhf_.token1Configs >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) & X5,
                        v_.emode,
                        isOperate_,
                        IS_DEBT
                    );

                    uint256 token0FeeAmount_;
                    uint256 token1FeeAmount_;
                    {
                        uint256 token0DebtAmount_;
                        uint256 token1DebtAmount_;
                        {
                            (, uint256 token0BorrowExchangePrice_) = _getExchangePrices(dexKey_.token0);
                            (, uint256 token1BorrowExchangePrice_) = _getExchangePrices(dexKey_.token1);

                            uint256 token0Decimals_ = (vhf_.token0Configs >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) &
                                X5;
                            uint256 token1Decimals_ = (vhf_.token1Configs >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) &
                                X5;

                            uint256 sqrtPriceX96_ = _calculateSqrtPriceX96(
                                vhf_.token0Price,
                                vhf_.token1Price,
                                token0BorrowExchangePrice_,
                                token1BorrowExchangePrice_,
                                token0Decimals_,
                                token1Decimals_
                            );

                            uint256 feeAccruedToken0_;
                            uint256 feeAccruedToken1_;
                            (
                                token0DebtAmount_,
                                token1DebtAmount_,
                                feeAccruedToken0_,
                                feeAccruedToken1_
                            ) = _getD4DebtAmounts(
                                _getDexId(dexKey_),
                                GetD3D4AmountsParams({
                                    tickLower: vhf_.tickLower,
                                    tickUpper: vhf_.tickUpper,
                                    positionSalt: vhf_.positionSalt,
                                    token0Decimals: token0Decimals_,
                                    token1Decimals: token1Decimals_,
                                    token0ExchangePrice: token0BorrowExchangePrice_,
                                    token1ExchangePrice: token1BorrowExchangePrice_,
                                    sqrtPriceX96: sqrtPriceX96_
                                })
                            );
                            // Now we also need to add fee on the collateral side
                            token0FeeAmount_ =
                                ((vhf_.positionFeeStored >> MSL.BITS_POSITION_FEE_STORED_FEE_STORED_TOKEN_0) & X128) +
                                feeAccruedToken0_;
                            token1FeeAmount_ =
                                ((vhf_.positionFeeStored >> MSL.BITS_POSITION_FEE_STORED_FEE_STORED_TOKEN_1) & X128) +
                                feeAccruedToken1_;
                        }

                        if (token0DebtAmount_ > 0) {
                            hfInfo_.debtValue += (((token0DebtAmount_ * vhf_.token0Price) + 1) / EIGHTEEN_DECIMALS) + 1; // rounded up so protocol is on the winning side
                        }
                        if (token1DebtAmount_ > 0) {
                            hfInfo_.debtValue += (((token1DebtAmount_ * vhf_.token1Price) + 1) / EIGHTEEN_DECIMALS) + 1; // rounded up so protocol is on the winning side
                        }
                    }

                    // We will need to update to collateral side prices for this
                    vhf_.token0Price = _getPrice(
                        v_.oracle,
                        dexKey_.token0,
                        (vhf_.token0Configs >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) & X5,
                        v_.emode,
                        isOperate_,
                        IS_COLLATERAL
                    );
                    vhf_.token1Price = _getPrice(
                        v_.oracle,
                        dexKey_.token1,
                        (vhf_.token1Configs >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) & X5,
                        v_.emode,
                        isOperate_,
                        IS_COLLATERAL
                    );

                    (hfInfo_.collateralValue, hfInfo_.normalizedCollateralValue) = _calculateCollateralValues(
                        isOperate_,
                        token0FeeAmount_,
                        vhf_.token0Price,
                        vhf_.token0Configs,
                        hfInfo_.collateralValue,
                        hfInfo_.normalizedCollateralValue
                    );
                    (hfInfo_.collateralValue, hfInfo_.normalizedCollateralValue) = _calculateCollateralValues(
                        isOperate_,
                        token1FeeAmount_,
                        vhf_.token1Price,
                        vhf_.token1Configs,
                        hfInfo_.collateralValue,
                        hfInfo_.normalizedCollateralValue
                    );
                }
            }
        }
    }

    /// @notice The range gate of the D3 / D4 ops module (SPEC.md §7.1.2 step 6, §7.1.3), evaluated against the
    ///         oracle-implied price: both bounds of the range must lie within `p_.maxTickDistance` ticks of the tick of
    ///         `_calculateSqrtPriceX96` over the Money Market oracle's operate-side prices of the two tokens (collateral
    ///         prices and supply exchange prices for a D3, debt prices and borrow exchange prices for a D4, the inputs
    ///         `valuePositions` values the position with), else
    ///         `FluidMoneyMarketError(ErrorTypes.D3D4Module__RangeTooFarFromPrice)`.
    /// @dev Reached by `delegatecall` from the ops module (`_verifyD3D4RangeWithinOracleBand`) before
    ///      `DEX_V2.startOperation` on a creation and on a D3 deposit / D4 borrow; never on withdraws, paybacks, fee
    ///      collections or the liquidation legs. The pool's own price is not consulted, so a swap cannot move the band.
    ///      Reverts as the health-factor valuation of the pair would: the oracle's own revert bubbles unchanged, a price
    ///      outside the `_getPrice` operate bounds `[1e9, 1e39]` reverts with empty data, an oracle price ratio of
    ///      `2^64` or more reverts with empty data in `_calculateSqrtPriceX96` (§16); the sqrt price of every ratio the
    ///      bounds admit lies inside `TickMath`'s range, so `getTickAtSqrtRatio` does not revert. Two oracle calls, two
    ///      Liquidity reads, no storage write.
    /// @param p_ `VerifyD3D4RangeBandParams`: the position type, the NFT's emode, the two token indices, the range and
    ///        the distance
    function verifyRangeWithinOracleBand(VerifyD3D4RangeBandParams calldata p_) external payable _onlyDelegateCall {
        bool isCollateral_ = p_.positionType == D3_POSITION_TYPE;
        uint256 token0Configs_ = _getTokenConfigs(p_.emode, p_.token0Index);
        uint256 token1Configs_ = _getTokenConfigs(p_.emode, p_.token1Index);

        uint256 sqrtPriceX96_;
        {
            // The first 160 bits of _moneyMarketVariables are the oracle address (as _getHfInfo reads it)
            IMMOracle oracle_ = IMMOracle(address(uint160(_moneyMarketVariables)));
            uint256 token0Price_ = _getPrice(
                oracle_,
                address(uint160(token0Configs_)),
                (token0Configs_ >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) & X5,
                p_.emode,
                IS_OPERATE,
                isCollateral_
            );
            uint256 token1Price_ = _getPrice(
                oracle_,
                address(uint160(token1Configs_)),
                (token1Configs_ >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) & X5,
                p_.emode,
                IS_OPERATE,
                isCollateral_
            );
            sqrtPriceX96_ = _calculateSqrtPriceX96(
                token0Price_,
                token1Price_,
                _operateExchangePrice(address(uint160(token0Configs_)), isCollateral_),
                _operateExchangePrice(address(uint160(token1Configs_)), isCollateral_),
                (token0Configs_ >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) & X5,
                (token1Configs_ >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) & X5
            );
        }

        int256 oracleTick_ = int256(TM.getTickAtSqrtRatio(uint160(sqrtPriceX96_)));
        if (
            oracleTick_ - int256(p_.tickLower) > int256(p_.maxTickDistance) ||
            int256(p_.tickUpper) - oracleTick_ > int256(p_.maxTickDistance)
        ) revert FluidMoneyMarketError(ErrorTypes.D3D4Module__RangeTooFarFromPrice);
    }

    /// @dev the Liquidity exchange price the range gate scales a token's oracle price with: the supply exchange price
    ///      for a D3 (collateral), the borrow exchange price for a D4 (debt), as `valuePositions` does
    function _operateExchangePrice(address token_, bool isCollateral_) internal view returns (uint256) {
        (uint256 supplyExchangePrice_, uint256 borrowExchangePrice_) = _getExchangePrices(token_);
        return isCollateral_ ? supplyExchangePrice_ : borrowExchangePrice_;
    }

    /// @notice The `changeEmode` checks of one D3 / D4 position (SPEC.md §7.2); the former base branches, unchanged.
    /// @dev Type 3: the collateral class of both tokens must be equal in the current and the new emode. Type 4: the
    ///      debt class and the collateral class of both tokens must be equal, and `_validateDebtForEmode(newEmode_,
    ///      idx)` must pass for both (empty revert when the new emode's "debt allowed" bit is clear). Reverts with
    ///      `FluidMoneyMarketError(ErrorTypes.Base__InvalidParams)` on a class mismatch and for a position type other
    ///      than 3 / 4.
    /// @param positionData_ The `_positionData` word of the position
    /// @param currentEmode_ The NFT's current emode
    /// @param newEmode_ The emode being switched to
    function validateEmodeChange(
        uint256 positionData_,
        uint256 currentEmode_,
        uint256 newEmode_
    ) external payable _onlyDelegateCall {
        uint256 positionType_ = (positionData_ >> MSL.BITS_POSITION_DATA_POSITION_TYPE) & X5;

        if (positionType_ == D3_POSITION_TYPE) {
            uint256 token0Index_ = (positionData_ >> MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_TOKEN_0_INDEX) & X12;
            if (
                ((_getTokenConfigs(currentEmode_, token0Index_) >> MSL.BITS_TOKEN_CONFIGS_COLLATERAL_CLASS) & X3) !=
                ((_getTokenConfigs(newEmode_, token0Index_) >> MSL.BITS_TOKEN_CONFIGS_COLLATERAL_CLASS) & X3)
            ) {
                revert FluidMoneyMarketError(ErrorTypes.Base__InvalidParams);
            }

            uint256 token1Index_ = (positionData_ >> MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_TOKEN_1_INDEX) & X12;
            if (
                ((_getTokenConfigs(currentEmode_, token1Index_) >> MSL.BITS_TOKEN_CONFIGS_COLLATERAL_CLASS) & X3) !=
                ((_getTokenConfigs(newEmode_, token1Index_) >> MSL.BITS_TOKEN_CONFIGS_COLLATERAL_CLASS) & X3)
            ) {
                revert FluidMoneyMarketError(ErrorTypes.Base__InvalidParams);
            }
        } else if (positionType_ == D4_POSITION_TYPE) {
            // NOTE: Checking both debt class and collateral class because D4 positions are used as both debt and collateral (fees)

            uint256 token0Index_ = (positionData_ >> MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_TOKEN_0_INDEX) & X12;
            if (
                (((_getTokenConfigs(currentEmode_, token0Index_) >> MSL.BITS_TOKEN_CONFIGS_DEBT_CLASS) & X3) !=
                    ((_getTokenConfigs(newEmode_, token0Index_) >> MSL.BITS_TOKEN_CONFIGS_DEBT_CLASS) & X3)) ||
                (((_getTokenConfigs(currentEmode_, token0Index_) >> MSL.BITS_TOKEN_CONFIGS_COLLATERAL_CLASS) & X3) !=
                    ((_getTokenConfigs(newEmode_, token0Index_) >> MSL.BITS_TOKEN_CONFIGS_COLLATERAL_CLASS) & X3))
            ) {
                revert FluidMoneyMarketError(ErrorTypes.Base__InvalidParams);
            }
            _validateDebtForEmode(newEmode_, token0Index_);

            uint256 token1Index_ = (positionData_ >> MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_TOKEN_1_INDEX) & X12;
            if (
                (((_getTokenConfigs(currentEmode_, token1Index_) >> MSL.BITS_TOKEN_CONFIGS_DEBT_CLASS) & X3) !=
                    ((_getTokenConfigs(newEmode_, token1Index_) >> MSL.BITS_TOKEN_CONFIGS_DEBT_CLASS) & X3)) ||
                (((_getTokenConfigs(currentEmode_, token1Index_) >> MSL.BITS_TOKEN_CONFIGS_COLLATERAL_CLASS) & X3) !=
                    ((_getTokenConfigs(newEmode_, token1Index_) >> MSL.BITS_TOKEN_CONFIGS_COLLATERAL_CLASS) & X3))
            ) {
                revert FluidMoneyMarketError(ErrorTypes.Base__InvalidParams);
            }
            _validateDebtForEmode(newEmode_, token1Index_);
        } else {
            revert FluidMoneyMarketError(ErrorTypes.Base__InvalidParams);
        }
    }

    /// @notice The D4 payback leg of `liquidate` (SPEC.md §9.4); the former liquidate-module branch, unchanged.
    /// @dev `paybackData` is `abi.encode(amount0, amount1, amount0Min, amount1Min)`; both amounts zero reverts
    ///      `LiquidateModule__InvalidParams`, as does a position type other than 4 (a type-3 position is never a debt
    ///      leg). The DexV2 round trip runs the ops module's payback branch with `isOperate = false` (no `1e4` floor;
    ///      settles skipped in estimate mode, the leg's storage writes then unwound by `PendingTransfersNotCleared`);
    ///      the payback value is the DexV2-reported amounts at the liquidate debt prices, rounded down.
    /// @param p_ `LiquidatePaybackParams`
    /// @return positionDeleted_ Whether the leg deleted its position (DexV2 liquidity and fee store both zero)
    /// @return paybackValue_ Value of what the liquidator paid, `1e27` units
    /// @return paybackData_ `abi.encode(uint256 amount0, uint256 amount1)` as reported by DexV2 `payback`
    function liquidatePayback(
        LiquidatePaybackParams calldata p_
    )
        external
        payable
        _onlyDelegateCall
        returns (bool positionDeleted_, uint256 paybackValue_, bytes memory paybackData_)
    {
        // Locals named as in the liquidate module so that the moved leg (`_liquidatePayback`) is unchanged
        LiquidateParams memory params_;
        params_.nftId = p_.nftId;
        params_.paybackPositionIndex = p_.positionIndex;
        params_.estimate = p_.estimate;
        params_.paybackData = p_.paybackData;

        LiquidateVariables memory v_;
        v_.oracle = p_.oracle;
        v_.nftConfig = p_.nftConfig;
        v_.emode = p_.emode;
        v_.paybackPositionData = p_.positionData;
        v_.paybackPositionType = (v_.paybackPositionData >> MSL.BITS_POSITION_DATA_POSITION_TYPE) & X5;

        _liquidatePayback(params_, v_, keccak256(abi.encode(params_.nftId)));

        return (v_.positionDeleted, v_.paybackValue, params_.paybackData);
    }

    /// @dev The D4 payback leg in its own frame (the former branch of `liquidate` had fewer locals above it than the
    ///      external wrapper has); writes `v_.positionDeleted`, `v_.paybackValue` and `params_.paybackData`.
    function _liquidatePayback(
        LiquidateParams memory params_,
        LiquidateVariables memory v_,
        bytes32 positionSalt_
    ) internal {
        if (v_.paybackPositionType == D4_POSITION_TYPE) {
            // D4 leg: `abi.encode(amount0, amount1, amount0Min, amount1Min)`; the DexV2 round trip runs the callback's payback
            // branch, which pulls the amounts DexV2 reports from `_msgSender` (native: from `_msgValue`) and skips the `1e4`
            // amount floor because `isOperate` is false. Requires the proxy to be whitelisted at DexV2 as a D4 user.
            (
                uint256 paybackAmount0_,
                uint256 paybackAmount1_,
                uint256 paybackAmount0Min_,
                uint256 paybackAmount1Min_
            ) = abi.decode(params_.paybackData, (uint256, uint256, uint256, uint256));

            // Make sure that this is not a fee collection operation (both amounts zero would select that callback branch)
            if (paybackAmount0_ == 0 && paybackAmount1_ == 0)
                revert FluidMoneyMarketError(ErrorTypes.LiquidateModule__InvalidParams);

            DexKey memory dexKey_;
            StartOperationParams memory s_ = StartOperationParams({
                isOperate: IS_LIQUIDATE,
                estimate: params_.estimate,
                positionType: v_.paybackPositionType,
                nftId: params_.nftId,
                nftConfig: v_.nftConfig,
                token0Index: (v_.paybackPositionData >> MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_TOKEN_0_INDEX) &
                    X12,
                token1Index: (v_.paybackPositionData >> MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_TOKEN_1_INDEX) &
                    X12,
                positionIndex: params_.paybackPositionIndex,
                tickLower: 0,
                tickUpper: 0,
                positionSalt: positionSalt_,
                emode: v_.emode,
                permissionlessTokens: false, // passing permissionless tokens as false because it doesn't matter because its a payback operation
                actionData: abi.encode(
                    -SafeCast.toInt256(paybackAmount0_),
                    -SafeCast.toInt256(paybackAmount1_),
                    paybackAmount0Min_,
                    paybackAmount1Min_,
                    address(0)
                )
            });

            uint256 token0Configs_ = _getTokenConfigs(v_.emode, s_.token0Index);
            uint256 token1Configs_ = _getTokenConfigs(v_.emode, s_.token1Index);

            (dexKey_, s_.tickLower, s_.tickUpper) = _decodeD3D4PositionData(
                v_.paybackPositionData,
                token0Configs_,
                token1Configs_
            );

            // The callback returns `(positionDeleted, amount0Paid, amount1Paid)` with DexV2's rounded-up amounts, clamped to
            // the position; the position is deleted only when its DexV2 liquidity and its fee store are both zero. In estimate
            // mode the Money Market writes made inside the DexV2 frame are unwound, while `positionDeleted` still reports what
            // the real call would do.
            (v_.positionDeleted, paybackAmount0_, paybackAmount1_) = abi.decode(
                _startOperationWithEstimate(abi.encode(dexKey_, s_), params_.estimate),
                (bool, uint256, uint256)
            );

            params_.paybackData = abi.encode(paybackAmount0_, paybackAmount1_);

            uint256 token0Price_ = _getPrice(
                v_.oracle,
                dexKey_.token0,
                (token0Configs_ >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) & X5,
                v_.emode,
                IS_LIQUIDATE,
                IS_DEBT
            );
            uint256 token1Price_ = _getPrice(
                v_.oracle,
                dexKey_.token1,
                (token1Configs_ >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) & X5,
                v_.emode,
                IS_LIQUIDATE,
                IS_DEBT
            );

            {
                // rounded down so protocol is on the winning side
                uint256 paybackValue0_;
                if (paybackAmount0_ > 0) {
                    paybackValue0_ = ((paybackAmount0_ * token0Price_) - 1) / EIGHTEEN_DECIMALS;
                    if (paybackValue0_ > 0) paybackValue0_ -= 1;
                }
                uint256 paybackValue1_;
                if (paybackAmount1_ > 0) {
                    paybackValue1_ = ((paybackAmount1_ * token1Price_) - 1) / EIGHTEEN_DECIMALS;
                    if (paybackValue1_ > 0) paybackValue1_ -= 1;
                }

                v_.paybackValue = paybackValue0_ + paybackValue1_;
            }
        } else {
            revert FluidMoneyMarketError(ErrorTypes.LiquidateModule__InvalidParams);
        }
    }

    /// @notice The D3 withdraw leg and the D4 fee-store leg of `liquidate` (SPEC.md §9.4, §9.5); the former
    ///         liquidate-module branches, unchanged.
    /// @dev Type 3: range liquidity is sized and removed at the pool's own price (`AT_POOL_PRICE`) scaled by the
    ///      average of the two capped penalties, then the fee store (stored plus accrued) covers a remainder above
    ///      `1e25` through `_useFeeStoredForLiquidation` and a fee-collection round trip. Type 4: the fee store is the
    ///      only seizable part, through a DexV2 `payback(0, 0)` round trip. Both re-read `_nftConfigs[nftId]` because
    ///      the payback leg may have rewritten it. Reverts `LiquidateModule__InvalidParams` where the legs did (no fee
    ///      to cover the remainder, the fee-store cases) and for a position type other than 3 / 4; DexV2 reverts
    ///      bubble unchanged; the settles are skipped in estimate mode.
    /// @param p_ `LiquidateWithdrawParams`
    /// @return withdrawData_ `abi.encode(uint256 amount0, uint256 amount1)`: type 3 the amounts DexV2 `withdraw`
    ///         released plus any fee-store amounts collected; type 4 the fee-store amounts collected
    function liquidateWithdraw(
        LiquidateWithdrawParams calldata p_
    ) external payable _onlyDelegateCall returns (bytes memory withdrawData_) {
        // Locals named as in the liquidate module so that the moved legs below are unchanged
        LiquidateParams memory params_;
        params_.nftId = p_.nftId;
        params_.withdrawPositionIndex = p_.positionIndex;
        params_.to = p_.to;
        params_.estimate = p_.estimate;

        LiquidateVariables memory v_;
        v_.oracle = p_.oracle;
        v_.emode = p_.emode;
        v_.withdrawPositionData = p_.positionData;
        v_.withdrawPositionType = (v_.withdrawPositionData >> MSL.BITS_POSITION_DATA_POSITION_TYPE) & X5;
        v_.withdrawValue = p_.withdrawValue;
        v_.maxLiquidationPenalty = p_.maxLiquidationPenalty;

        bytes32 positionSalt_ = keccak256(abi.encode(params_.nftId));

        if (v_.withdrawPositionType == D3_POSITION_TYPE) {
            // D3 leg: range liquidity is sized and removed at the pool's own price, then the fee store covers any remainder.
            // `isOperate = false`: the callback skips `_verifyAmountLimits` and its own health-factor check.
            DexKey memory dexKey_;
            StartOperationParams memory s_ = StartOperationParams({
                isOperate: IS_LIQUIDATE,
                estimate: params_.estimate,
                positionType: D3_POSITION_TYPE,
                nftId: params_.nftId,
                nftConfig: _nftConfigs[params_.nftId], // using directly from storage because payback might have changed it
                token0Index: (v_.withdrawPositionData >> MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_TOKEN_0_INDEX) &
                    X12,
                token1Index: (v_.withdrawPositionData >> MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_TOKEN_1_INDEX) &
                    X12,
                positionIndex: params_.withdrawPositionIndex,
                tickLower: 0,
                tickUpper: 0,
                positionSalt: positionSalt_,
                emode: v_.emode,
                permissionlessTokens: false, // passing permissionless tokens as false because it doesn't matter because its a withdraw operation
                actionData: "" // will be set when needed
            });

            LiquidateD3WithdrawVariables memory vl_;

            {
                uint256 token0Configs_ = _getTokenConfigs(v_.emode, s_.token0Index);
                uint256 token1Configs_ = _getTokenConfigs(v_.emode, s_.token1Index);

                (dexKey_, s_.tickLower, s_.tickUpper) = _decodeD3D4PositionData(
                    v_.withdrawPositionData,
                    token0Configs_,
                    token1Configs_
                );

                vl_.token0Decimals = (token0Configs_ >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) & X5;
                vl_.token1Decimals = (token1Configs_ >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) & X5;

                vl_.token0LiquidationPenalty = (token0Configs_ >> MSL.BITS_TOKEN_CONFIGS_LIQUIDATION_PENALTY) & X10;
                if (vl_.token0LiquidationPenalty > v_.maxLiquidationPenalty)
                    vl_.token0LiquidationPenalty = v_.maxLiquidationPenalty;

                vl_.token1LiquidationPenalty = (token1Configs_ >> MSL.BITS_TOKEN_CONFIGS_LIQUIDATION_PENALTY) & X10;
                if (vl_.token1LiquidationPenalty > v_.maxLiquidationPenalty)
                    vl_.token1LiquidationPenalty = v_.maxLiquidationPenalty;
            }

            {
                // Fee store of the position (normal token units, SPEC.md §6.3.9); the inner key equals the DexV2 positionId
                // because `address(this)` is the proxy. Newly accrued fees are added below.
                uint256 positionFeeStored_ = _positionFeeStored[params_.nftId][
                    keccak256(abi.encode(D3_POSITION_TYPE, dexKey_))
                ][keccak256(abi.encode(address(this), s_.tickLower, s_.tickUpper, s_.positionSalt))];

                vl_.feeAmountToken0 = (positionFeeStored_ >> MSL.BITS_POSITION_FEE_STORED_FEE_STORED_TOKEN_0) & X128;
                vl_.feeAmountToken1 = (positionFeeStored_ >> MSL.BITS_POSITION_FEE_STORED_FEE_STORED_TOKEN_1) & X128;
            }

            {
                (uint256 token0SupplyExchangePrice_, ) = _getExchangePrices(dexKey_.token0);
                (uint256 token1SupplyExchangePrice_, ) = _getExchangePrices(dexKey_.token1);

                uint256 feeAccruedToken0_;
                uint256 feeAccruedToken1_;

                // Range amounts at the pool's stored `sqrtPriceX96` (`AT_POOL_PRICE` sentinel), not at the oracle-implied
                // price the health factor used: DexV2 removes liquidity at its own price, so the seizure is sized where it is
                // executed. Read from DexV2 storage; a position with zero DexV2 liquidity yields four zeros.
                (
                    vl_.token0SupplyAmount,
                    vl_.token1SupplyAmount,
                    feeAccruedToken0_,
                    feeAccruedToken1_
                ) = _getD3SupplyAmounts(
                    _getDexId(dexKey_),
                    GetD3D4AmountsParams({
                        tickLower: s_.tickLower,
                        tickUpper: s_.tickUpper,
                        positionSalt: s_.positionSalt,
                        token0Decimals: vl_.token0Decimals,
                        token1Decimals: vl_.token1Decimals,
                        token0ExchangePrice: token0SupplyExchangePrice_,
                        token1ExchangePrice: token1SupplyExchangePrice_,
                        sqrtPriceX96: AT_POOL_PRICE
                    })
                );

                vl_.feeAmountToken0 += feeAccruedToken0_;
                vl_.feeAmountToken1 += feeAccruedToken1_;
            }

            vl_.token0Price = _getPrice(
                v_.oracle,
                dexKey_.token0,
                vl_.token0Decimals,
                v_.emode,
                IS_LIQUIDATE,
                IS_COLLATERAL
            );
            vl_.token1Price = _getPrice(
                v_.oracle,
                dexKey_.token1,
                vl_.token1Decimals,
                v_.emode,
                IS_LIQUIDATE,
                IS_COLLATERAL
            );

            // Only when the position holds range liquidity; a fee-only position goes straight to the fee store below with the
            // unscaled value
            if (!(vl_.token0SupplyAmount == 0 && vl_.token1SupplyAmount == 0)) {
                uint256 supplyValue_;
                uint256 averageLiquidationPenalty_;

                {
                    uint256 supplyValue0_ = (((vl_.token0SupplyAmount * vl_.token0Price) + 1) / EIGHTEEN_DECIMALS) + 1; // rounded up so protocol is on the winning side
                    uint256 supplyValue1_ = (((vl_.token1SupplyAmount * vl_.token1Price) + 1) / EIGHTEEN_DECIMALS) + 1; // rounded up so protocol is on the winning side

                    supplyValue_ = supplyValue0_ + supplyValue1_;
                    // Simple average of the two capped penalties (integer division), so the penalty does not depend on
                    // the pool price. It is not bounded by the per-token listing rule `LT * (1000 + LP) / 1000 <= 990`:
                    // seizing a single-sided leg whose in-range token carries a high LT while its out-of-range partner
                    // carries a larger LP (the average then exceeds the in-range token's own LP, so
                    // `LT * (1000 + average) / 1000` can pass 1000) can increase the shortfall and fail the check at
                    // the end of this function.
                    averageLiquidationPenalty_ = (vl_.token0LiquidationPenalty + vl_.token1LiquidationPenalty) / 2;
                }

                // Scaling up the withdraw value by the average liquidation penalty
                // rounded down so protocol is on the winning side
                v_.withdrawValue =
                    ((v_.withdrawValue * (THREE_DECIMALS + averageLiquidationPenalty_)) - 1) /
                    THREE_DECIMALS;
                if (v_.withdrawValue > 0) v_.withdrawValue -= 1;

                if (supplyValue_ < v_.withdrawValue) {
                    // Position value below the scaled target: request the whole position and keep the uncovered remainder
                    // for the fee store
                    // if one of the amounts is very small that it rounds to 0, then adding 1 here makes sure that the withdraw is actually happening
                    if (vl_.token0SupplyAmount == 0) vl_.token0SupplyAmount = 1;
                    if (vl_.token1SupplyAmount == 0) vl_.token1SupplyAmount = 1;

                    v_.withdrawValue -= supplyValue_;

                    // This withdraw value was scaled up, hence now the remaining portion needs to be scaled down
                    // rounded down so protocol is on the winning side
                    v_.withdrawValue =
                        ((v_.withdrawValue * THREE_DECIMALS) - 1) /
                        (THREE_DECIMALS + averageLiquidationPenalty_);
                    if (v_.withdrawValue > 0) v_.withdrawValue -= 1;
                } else {
                    // Position covers the target: request the proportional share of each token, rounded down, at least 1 unit
                    if (vl_.token0SupplyAmount == 0) {
                        // if one of the amounts is very small that it rounds to 0, then adding 1 here makes sure that the withdraw is actually happening
                        vl_.token0SupplyAmount = 1;
                    } else {
                        // rounded down so protocol is on the winning side
                        vl_.token0SupplyAmount = ((vl_.token0SupplyAmount * v_.withdrawValue) - 1) / supplyValue_;

                        // ensure at least 1 for withdraw
                        if (vl_.token0SupplyAmount > 1) {
                            vl_.token0SupplyAmount -= 1;
                        } else {
                            vl_.token0SupplyAmount = 1;
                        }
                    }

                    if (vl_.token1SupplyAmount == 0) {
                        // if one of the amounts is very small that it rounds to 0, then adding 1 here makes sure that the withdraw is actually happening
                        vl_.token1SupplyAmount = 1;
                    } else {
                        // rounded down so protocol is on the winning side
                        vl_.token1SupplyAmount = ((vl_.token1SupplyAmount * v_.withdrawValue) - 1) / supplyValue_;

                        // ensure at least 1 for withdraw
                        if (vl_.token1SupplyAmount > 1) {
                            vl_.token1SupplyAmount -= 1;
                        } else {
                            vl_.token1SupplyAmount = 1;
                        }
                    }

                    // The entire withdraw value was consumed
                    v_.withdrawValue = 0;
                }

                // `amount0Min = amount1Min = 0`. DexV2 converts the requested pair to a liquidity decrease (`min(L0, L1)` at the
                // pool price), clamps it to the position and returns what it released; the returned amounts are not compared
                // with the request. DexV2 pays `to` directly (settle skipped in estimate mode).
                s_.actionData = abi.encode(
                    -SafeCast.toInt256(vl_.token0SupplyAmount),
                    -SafeCast.toInt256(vl_.token1SupplyAmount),
                    0,
                    0,
                    params_.to
                );

                (, vl_.withdrawAmount0, vl_.withdrawAmount1) = abi.decode(
                    _startOperationWithEstimate(abi.encode(dexKey_, s_), params_.estimate),
                    (bool, uint256, uint256)
                );
            }

            // NOTE: We will process further withdrawal using fee stored only if the withdraw value is greater than $0.01 i.e. 1 cent (1e25 in 27 decimals)
            // A remainder of at most 1e25 is dropped.
            if (v_.withdrawValue > 1e25) {
                if (!(vl_.feeAmountToken0 == 0 && vl_.feeAmountToken1 == 0)) {
                    (vl_.feeAmountToken0, vl_.feeAmountToken1) = _useFeeStoredForLiquidation(
                        vl_.feeAmountToken0,
                        vl_.feeAmountToken1,
                        v_.withdrawValue,
                        vl_.token0Price,
                        vl_.token1Price,
                        vl_.token0LiquidationPenalty,
                        vl_.token1LiquidationPenalty
                    );

                    // Fee-collection round trip (a DexV2 `withdraw(0, 0)` followed by `_feeSettle` paying the store to `to`, no
                    // amount floor); its return data is ignored and the computed collection amounts are reported instead
                    s_.actionData = abi.encode(0, 0, vl_.feeAmountToken0, vl_.feeAmountToken1, params_.to);
                    _startOperationWithEstimate(abi.encode(dexKey_, s_), params_.estimate);

                    vl_.withdrawAmount0 += vl_.feeAmountToken0;
                    vl_.withdrawAmount1 += vl_.feeAmountToken1;
                } else {
                    // Reverting here because withdrawValue_ was non zero, but there is no fee stored to fill it
                    revert FluidMoneyMarketError(ErrorTypes.LiquidateModule__InvalidParams);
                }
            }

            withdrawData_ = abi.encode(vl_.withdrawAmount0, vl_.withdrawAmount1);
        } else if (v_.withdrawPositionType == D4_POSITION_TYPE) {
            // D4 leg: the fee store (stored + newly accrued) is the only seizable part; the D4 debt itself is untouched here.
            // Routed through a DexV2 `payback(0, 0)`, which DexV2 gates with its D4 whitelist.
            DexKey memory dexKey_;
            StartOperationParams memory s_ = StartOperationParams({
                isOperate: IS_LIQUIDATE,
                estimate: params_.estimate,
                positionType: D4_POSITION_TYPE,
                nftId: params_.nftId,
                nftConfig: _nftConfigs[params_.nftId], // using directly from storage because payback might have changed it
                token0Index: (v_.withdrawPositionData >> MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_TOKEN_0_INDEX) &
                    X12,
                token1Index: (v_.withdrawPositionData >> MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_TOKEN_1_INDEX) &
                    X12,
                positionIndex: params_.withdrawPositionIndex,
                tickLower: 0,
                tickUpper: 0,
                positionSalt: positionSalt_,
                emode: v_.emode,
                permissionlessTokens: false, // passing permissionless tokens as false because it doesn't matter because its a fee collection operation
                actionData: "" // will be set when needed
            });

            LiquidateD4WithdrawVariables memory vl_;

            {
                uint256 token0Configs_ = _getTokenConfigs(v_.emode, s_.token0Index);
                uint256 token1Configs_ = _getTokenConfigs(v_.emode, s_.token1Index);

                (dexKey_, s_.tickLower, s_.tickUpper) = _decodeD3D4PositionData(
                    v_.withdrawPositionData,
                    token0Configs_,
                    token1Configs_
                );

                vl_.token0Decimals = (token0Configs_ >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) & X5;
                vl_.token1Decimals = (token1Configs_ >> MSL.BITS_TOKEN_CONFIGS_TOKEN_DECIMALS) & X5;
                vl_.token0LiquidationPenalty = (token0Configs_ >> MSL.BITS_TOKEN_CONFIGS_LIQUIDATION_PENALTY) & X10;
                if (vl_.token0LiquidationPenalty > v_.maxLiquidationPenalty)
                    vl_.token0LiquidationPenalty = v_.maxLiquidationPenalty;

                vl_.token1LiquidationPenalty = (token1Configs_ >> MSL.BITS_TOKEN_CONFIGS_LIQUIDATION_PENALTY) & X10;
                if (vl_.token1LiquidationPenalty > v_.maxLiquidationPenalty)
                    vl_.token1LiquidationPenalty = v_.maxLiquidationPenalty;
            }

            uint256 feeAmountToken0_;
            uint256 feeAmountToken1_;
            {
                uint256 positionFeeStored_ = _positionFeeStored[params_.nftId][
                    keccak256(abi.encode(D4_POSITION_TYPE, dexKey_))
                ][keccak256(abi.encode(address(this), s_.tickLower, s_.tickUpper, s_.positionSalt))];

                feeAmountToken0_ = (positionFeeStored_ >> MSL.BITS_POSITION_FEE_STORED_FEE_STORED_TOKEN_0) & X128;
                feeAmountToken1_ = (positionFeeStored_ >> MSL.BITS_POSITION_FEE_STORED_FEE_STORED_TOKEN_1) & X128;
            }

            {
                (, uint256 token0BorrowExchangePrice_) = _getExchangePrices(dexKey_.token0);
                (, uint256 token1BorrowExchangePrice_) = _getExchangePrices(dexKey_.token1);

                uint256 feeAccruedToken0_;
                uint256 feeAccruedToken1_;

                // Only the accrued fees are used; the debt amounts are discarded. Zero DexV2 liquidity yields zeros.
                (, , feeAccruedToken0_, feeAccruedToken1_) = _getD4DebtAmounts(
                    _getDexId(dexKey_),
                    GetD3D4AmountsParams({
                        tickLower: s_.tickLower,
                        tickUpper: s_.tickUpper,
                        positionSalt: s_.positionSalt,
                        token0Decimals: vl_.token0Decimals,
                        token1Decimals: vl_.token1Decimals,
                        token0ExchangePrice: token0BorrowExchangePrice_,
                        token1ExchangePrice: token1BorrowExchangePrice_,
                        sqrtPriceX96: AT_POOL_PRICE
                    })
                );

                feeAmountToken0_ += feeAccruedToken0_;
                feeAmountToken1_ += feeAccruedToken1_;
            }

            if (!(feeAmountToken0_ == 0 && feeAmountToken1_ == 0)) {
                // The unscaled value goes in; the helper applies each token's capped penalty to the part it covers
                {
                    uint256 token0Price_ = _getPrice(
                        v_.oracle,
                        dexKey_.token0,
                        vl_.token0Decimals,
                        v_.emode,
                        IS_LIQUIDATE,
                        IS_COLLATERAL
                    );
                    uint256 token1Price_ = _getPrice(
                        v_.oracle,
                        dexKey_.token1,
                        vl_.token1Decimals,
                        v_.emode,
                        IS_LIQUIDATE,
                        IS_COLLATERAL
                    );
                    (feeAmountToken0_, feeAmountToken1_) = _useFeeStoredForLiquidation(
                        feeAmountToken0_,
                        feeAmountToken1_,
                        v_.withdrawValue,
                        token0Price_,
                        token1Price_,
                        vl_.token0LiquidationPenalty,
                        vl_.token1LiquidationPenalty
                    );
                }

                // Fee-collection round trip (DexV2 `payback(0, 0)` followed by `_feeSettle` paying the store to `to`, no amount
                // floor); its return data is ignored and the computed collection amounts are reported
                s_.actionData = abi.encode(0, 0, feeAmountToken0_, feeAmountToken1_, params_.to);
                _startOperationWithEstimate(abi.encode(dexKey_, s_), params_.estimate);

                withdrawData_ = abi.encode(feeAmountToken0_, feeAmountToken1_);
            } else {
                // Reverting here because withdrawValue_ was non zero, but there is no fee stored to fill it
                revert FluidMoneyMarketError(ErrorTypes.LiquidateModule__InvalidParams);
            }
        } else {
            // Any other type, including type 0 read from an emptied slot
            revert FluidMoneyMarketError(ErrorTypes.LiquidateModule__InvalidParams);
        }
    }
}
Compiler settingsShow
{
  "metadata": {
    "useLiteralContent": true
  },
  "optimizer": {
    "runs": 10000000,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.