Skip to content
Verified contractExactBUSL-1.1

FluidMoneyMarketD3D4Module

Address0xe1cabe92b24f3f407ea9bd1e7f41470db1714bdb
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,097
Creation transaction
0x0b7e0b9290…67a46bcdf6

53 files

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

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

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

import "./helpers.sol";

/// @title FluidMoneyMarketD3D4Module
/// @notice Operate-side module of the D3 (smart collateral) and D4 (smart debt) position types: creation and
///         modification of a position (both open the DexV2 round trip) and the DexV2 callback that performs the D3
///         `deposit` / `withdraw` and D4 `borrow` / `payback` calls, fee collection, per-token settlement, fee-store
///         and cap accounting, position deletion and the health-factor check. See SPEC.md §7.1.2, §10.
/// @dev Reached only by `delegatecall` through `_spell`: `createPosition` and `modifyPosition` from the operate module
///      (`IFluidMoneyMarketDexModule`), `startOperationCallback` from the base's router, which reads the position
///      type at word 8 of the callback data and forwards `msg.data` unchanged. This code runs in the proxy's storage
///      while the outer `_handleMsgDetails` is active (`_msgSender` = the user or liquidator, `_msgValue` = remaining
///      native value); `_onlyDelegateCall` rejects a direct call with empty data. `createPosition` and `modifyPosition`
///      are `payable` because the delegatecall carries the outer `msg.value` of the payable `operate`; the native legs
///      draw on the transient `_msgValue`, never on `msg.value` directly.
///      Round trip: `createPosition` / `modifyPosition` / the liquidate legs call
///      `DEX_V2.startOperation(abi.encode(DexKey, StartOperationParams))`; DexV2 calls `startOperationCallback(data)`
///      on the proxy, whose base forwards it here (`_dexModule(positionType)`).
///      Trust assumptions: `DEX_V2` and `LIQUIDITY` are this module's own immutables (checked against the valuation
///      module's at construction); DexV2 is relied on to return the amounts it moved, to clamp withdraws / paybacks to
///      the position and to settle exactly the pending legs the module call created; `_isD3D4PositionEmpty` reads
///      DexV2's position storage by slot (`DexV2D3D4CommonSlotsLink`), so the DexV2 storage layout is an interface of
///      this module (SPEC.md §10.8); every D4 call (`borrow`, `payback` and the zero-amount `payback` used for fee
///      collection) requires the Money Market proxy on DexV2's D4 user whitelist (`UserModule__UserNotWhitelisted`
///      otherwise). Every check of this module reverts with empty data except the range gate
///      (`FluidMoneyMarketError(ErrorTypes.D3D4Module__RangeTooFarFromPrice)`, raised inside the D3 / D4 valuation
///      module through one `_spell` hop: a bound of the range more than `D3D4_CREATE_MAX_TICK_DISTANCE` ticks (a price
///      ratio of 100) from the tick of the oracle-implied price on a position being created, or more than
///      `D3D4_INCREASE_MAX_TICK_DISTANCE` ticks (a ratio of 200) on a position receiving a deposit / borrow; the hop
///      also surfaces the oracle's revert and the `_getPrice` bounds' empty revert for a pair that cannot be priced);
///      `_checkHf` reverts with `FluidMoneyMarketError(ErrorTypes.Helpers__HealthFactorFailed)` after one
///      `valuePositions` hop per dex family; DexV2 wraps the returned bytes in `PendingTransfersNotCleared(bytes)`
///      when any pending amount remains after the callback.
contract FluidMoneyMarketD3D4Module is Helpers {
    // NOTE: All functions in this contract are only callable by specific addresses

    /// @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 ops module
    /// @dev Checks both valuation modules (reached by `_checkHf` -> `_getHfInfo`: an NFT can hold a D3 and a D1 position
    ///      at once); every other module address is ignored here. `LIQUIDITY` / `DEX_V2` are this module's own copies
    ///      under delegatecall.
    /// @param liquidity_ The FluidLiquidity contract address
    /// @param dexV2_ The FluidDexV2 contract address
    /// @param modules_ The deployed module addresses (`d3d4Valuation` and `d1d2Valuation` must be set)
    constructor(
        address liquidity_,
        address dexV2_,
        ModuleAddresses memory modules_
    ) ImmutableVariables(liquidity_, dexV2_, modules_, CHECK_D3D4_VALUATION_MODULE | CHECK_D1D2_VALUATION_MODULE) {
        THIS_ADDRESS = address(this);
    }

    /// @notice Creates a D3 / D4 position for the operate module (SPEC.md §7.1.2); the body of the former
    ///         `_createPosition` types 3 / 4 branch, unchanged.
    /// @dev Token indices validated; both amounts 0 reverts (fee collection is not a creation); class and isolated
    ///      rules of §7.1.2; fee and tick bounds; `DexKey` built from the two token configs of the NFT's emode; the
    ///      range gate (`_verifyD3D4RangeWithinOracleBand` with `D3D4_CREATE_MAX_TICK_DISTANCE`, a hop into the
    ///      valuation module and the one typed revert of this module, `D3D4Module__RangeTooFarFromPrice`);
    ///      `_isD3D4PositionEmpty` must hold; the position word is stored (`_addPosition`, which also persists the
    ///      isolated-collateral bits `_beforeCreatingIsolatedCollateralPosition` set in the memory `nftConfig_`) before
    ///      `DEX_V2.startOperation`, whose callback performs the deposit / borrow, settles, applies the caps and (D4)
    ///      the health-factor check and checks the per-leg `[1e4, X128]` limits. A revert anywhere in the round trip
    ///      unwinds the stored word. Every check reverts with empty data; a position type other than 3 / 4 as well.
    /// @param params_ `CreateDexPositionParams`: the NFT, its config word and emode, the position type and the action
    ///        data `abi.encode(3 | 4, CreateD3D4PositionParams)`
    /// @return positionIndex_ The index of the new position
    /// @return actionData_ `abi.encode(positionType, p)` with `p.amount0` / `p.amount1` replaced by the amounts DexV2
    ///         used and `fee = 0` reported for a dynamic-fee pool
    function createPosition(
        CreateDexPositionParams calldata params_
    ) external payable _onlyDelegateCall returns (uint256 positionIndex_, bytes memory actionData_) {
        uint256 nftId_ = params_.nftId;
        uint256 nftConfig_ = params_.nftConfig;
        uint256 emode_ = params_.emode;
        uint256 positionType_ = params_.positionType;
        actionData_ = params_.actionData;

        if (positionType_ == D3_POSITION_TYPE || positionType_ == D4_POSITION_TYPE) {
            (, CreateD3D4PositionParams memory p_) = abi.decode(actionData_, (uint256, CreateD3D4PositionParams));

            _validateTokenIndex(p_.token0Index);
            _validateTokenIndex(p_.token1Index);

            // Make sure that this is not a fee collection operation
            if (p_.amount0 == 0 && p_.amount1 == 0) revert();

            // NOTE: This is checked in the start operation callback
            // Verify the amounts are within the limits
            // if (p_.amount0 > 0) _verifyAmountLimits(p_.amount0);
            // if (p_.amount1 > 0) _verifyAmountLimits(p_.amount1);

            CreateD3D4PositionVariables memory v_;

            v_.token0Configs = _getTokenConfigs(emode_, p_.token0Index);
            v_.token1Configs = _getTokenConfigs(emode_, p_.token1Index);

            if (positionType_ == D3_POSITION_TYPE) {
                uint256 token0CollateralClass_ = (v_.token0Configs >> MSL.BITS_TOKEN_CONFIGS_COLLATERAL_CLASS) & X3;
                uint256 token1CollateralClass_ = (v_.token1Configs >> MSL.BITS_TOKEN_CONFIGS_COLLATERAL_CLASS) & X3;

                // We need to check the following:
                // 1. If any of the tokens is not enabled as collateral, then revert
                // 2. If both the tokens are of isolated collateral class, then revert
                // 3. If any one of the tokens is of isolated collateral class, then we need to update the nft config and _isolatedCapConfigs
                if (
                    token0CollateralClass_ == COLLATERAL_CLASS_NOT_ENABLED ||
                    token1CollateralClass_ == COLLATERAL_CLASS_NOT_ENABLED
                ) {
                    revert();
                } else if (
                    token0CollateralClass_ == COLLATERAL_CLASS_ISOLATED &&
                    token1CollateralClass_ == COLLATERAL_CLASS_ISOLATED
                ) {
                    // Both the tokens cannot be of isolated collateral class because 2 isolated collaterals are not allowed
                    revert();
                } else if (token0CollateralClass_ == COLLATERAL_CLASS_ISOLATED) {
                    nftConfig_ = _beforeCreatingIsolatedCollateralPosition(nftId_, nftConfig_, p_.token0Index);
                } else if (token1CollateralClass_ == COLLATERAL_CLASS_ISOLATED) {
                    nftConfig_ = _beforeCreatingIsolatedCollateralPosition(nftId_, nftConfig_, p_.token1Index);
                }

                // If both of the tokens are of permissionless collateral class then its a permissionless deposit, otherwise its a permissioned deposit
                // The start operation callback consults this flag only while the pool's _positionCapConfigs word is zero: a
                // permissionless deposit then copies the per-pair (else the per-dex-type global) default cap word into the pool's
                // own word, a permissioned deposit reverts. Once the pool's word is set (by the admin or by an earlier permissionless
                // deposit) the callback applies that word's window and caps to every caller and does not read this flag again.
                if (
                    token0CollateralClass_ == COLLATERAL_CLASS_PERMISSIONLESS &&
                    token1CollateralClass_ == COLLATERAL_CLASS_PERMISSIONLESS
                ) {
                    v_.permissionlessTokens = true;
                }
            } else if (positionType_ == D4_POSITION_TYPE) {
                // Check if the nft has isolated collateral flag as ON, if it is then we need to update revert because if there is an isolated collateral we cannot have smart debt
                if ((nftConfig_ >> MSL.BITS_NFT_CONFIGS_ISOLATED_COLLATERAL_FLAG) & X1 == 1) {
                    revert();
                }

                {
                    uint256 token0DebtClass_ = (v_.token0Configs >> MSL.BITS_TOKEN_CONFIGS_DEBT_CLASS) & X3;
                    uint256 token1DebtClass_ = (v_.token1Configs >> MSL.BITS_TOKEN_CONFIGS_DEBT_CLASS) & X3;

                    if (token0DebtClass_ == DEBT_CLASS_NOT_ENABLED || token1DebtClass_ == DEBT_CLASS_NOT_ENABLED) {
                        revert();
                    }

                    // If both of the tokens are of permissionless debt class then its a permissionless borrow, otherwise its a permissioned borrow
                    // The start operation callback consults this flag only while the pool's _positionCapConfigs word is zero: a
                    // permissionless borrow then copies the per-pair (else the per-dex-type global) default cap word into the pool's
                    // own word, a permissioned borrow reverts. Once the pool's word is set (by the admin or by an earlier permissionless
                    // borrow) the callback applies that word's window and caps to every caller and does not read this flag again.
                    if (
                        token0DebtClass_ == DEBT_CLASS_PERMISSIONLESS && token1DebtClass_ == DEBT_CLASS_PERMISSIONLESS
                    ) {
                        v_.permissionlessTokens = true;
                    }
                }

                // NOTE: These checks are added in the start operation callback
                // _validateDebtForEmode(emode_, p_.token0Index);
                // _validateDebtForEmode(emode_, p_.token1Index);

                // NOTE: We dont allow creating D4 positions for tokens who are not enabled as collateral or are isolated collateral class
                // because the fee accrued is counted on the collateral side
                {
                    uint256 token0CollateralClass_ = (v_.token0Configs >> MSL.BITS_TOKEN_CONFIGS_COLLATERAL_CLASS) & X3;
                    uint256 token1CollateralClass_ = (v_.token1Configs >> MSL.BITS_TOKEN_CONFIGS_COLLATERAL_CLASS) & X3;
                    if (
                        token0CollateralClass_ == COLLATERAL_CLASS_NOT_ENABLED ||
                        token1CollateralClass_ == COLLATERAL_CLASS_NOT_ENABLED ||
                        token0CollateralClass_ == COLLATERAL_CLASS_ISOLATED ||
                        token1CollateralClass_ == COLLATERAL_CLASS_ISOLATED
                    ) revert();
                }
            } else {
                // This wont ever happen
                revert(); // Invalid position type
            }

            // Fee: DYNAMIC_FEE_FLAG (0xFFFFFF) sets the dynamic-fee bit and stores fee 0; p_.fee is zeroed in memory, so
            // the returned / emitted action data of a dynamic-fee creation reports fee = 0 (the DexKey sent to DexV2 and
            // the stored word are correct). Any other fee up to X17 (131071) is accepted here although DexV2 initializes
            // static-fee pools only up to 65535; a fee in [65536, 131071] addresses a pool that cannot exist and the
            // DexV2 call reverts with UserModule__DexNotInitialized.
            if (p_.fee == DYNAMIC_FEE_FLAG) {
                v_.isDynamicFeeFlag = 1;
                p_.fee = 0;
            } else if (p_.fee > X17) revert();

            // Not checked here: tickSpacing == 0, tick alignment to tickSpacing, the 8000-tick maximum width,
            // token0 < token1, token0Index != token1Index and pool existence; DexV2 rejects these with its own ids.
            if (
                p_.tickSpacing > MAX_TICK_SPACING ||
                p_.tickLower >= p_.tickUpper ||
                p_.tickLower <= MIN_TICK ||
                p_.tickUpper >= MAX_TICK
                // NOTE: The below 3 checks are on the dex v2 side
                // (p_.tickLower % int24(p_.tickSpacing) != 0) ||
                // (p_.tickUpper % int24(p_.tickSpacing) != 0)
                // (p_.tickUpper - p_.tickLower > int24(MAX_TICK_RANGE))
            ) revert();

            // Build the dex key
            DexKey memory dexKey_ = DexKey({
                token0: address(uint160(v_.token0Configs)), // The first 160 bits of the token configs are the token address
                token1: address(uint160(v_.token1Configs)), // The first 160 bits of the token configs are the token address
                fee: v_.isDynamicFeeFlag == 1 ? DYNAMIC_FEE_FLAG : p_.fee,
                tickSpacing: p_.tickSpacing,
                controller: p_.controller
            });

            // Range gate (SPEC.md §7.1.2 step 6): both bounds within D3D4_CREATE_MAX_TICK_DISTANCE ticks (a price ratio
            // of 100) of the tick of the oracle-implied price (D3D4Module__RangeTooFarFromPrice), checked by the
            // valuation module through one hop; the pool's own price plays no part
            _verifyD3D4RangeWithinOracleBand(
                positionType_,
                emode_,
                p_.token0Index,
                p_.token1Index,
                p_.tickLower,
                p_.tickUpper,
                D3D4_CREATE_MAX_TICK_DISTANCE
            );

            // Build the position salt
            v_.positionSalt = keccak256(abi.encode(nftId_));

            // One NFT holds at most one position per (type, DexKey, tickLower, tickUpper): the DexV2 liquidity word (read
            // from DexV2 storage) and this NFT's fee store for that position must both be zero
            if (!_isD3D4PositionEmpty(nftId_, positionType_, dexKey_, p_.tickLower, p_.tickUpper, v_.positionSalt))
                revert(); // Position already exists

            {
                uint256 positionData_ = (positionType_ << MSL.BITS_POSITION_DATA_POSITION_TYPE) |
                    (p_.token0Index << MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_TOKEN_0_INDEX) |
                    (p_.token1Index << MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_TOKEN_1_INDEX) |
                    (v_.isDynamicFeeFlag << MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_IS_DYNAMIC_FEE_POOL) |
                    (uint256(p_.fee) << MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_FEE) |
                    (uint256(p_.tickSpacing) << MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_TICK_SPACING) |
                    (uint256(uint160(p_.controller)) <<
                        MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_CONTROLLER_ADDRESS) |
                    ((p_.tickLower < 0 ? uint256(0) : uint256(1)) <<
                        MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_LOWER_TICK_SIGN) |
                    ((p_.tickLower < 0 ? uint256(uint24(-p_.tickLower)) : uint256(uint24(p_.tickLower))) <<
                        MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_ABSOLUTE_LOWER_TICK) |
                    ((p_.tickUpper < 0 ? uint256(0) : uint256(1)) <<
                        MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_UPPER_TICK_SIGN) |
                    ((p_.tickUpper < 0 ? uint256(uint24(-p_.tickUpper)) : uint256(uint24(p_.tickUpper))) <<
                        MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_ABSOLUTE_UPPER_TICK);

                // The position word is written before the DexV2 round trip; a revert anywhere in the round trip unwinds it
                // Store the position data on storage
                positionIndex_ = _addPosition(nftId_, nftConfig_, positionData_);
            }

            // NOTE: nftConfig_ passed below is the memory word from before _addPosition wrote the incremented position
            // count (its isolated-collateral bits are current, its count is one behind storage). The callback's deposit
            // and borrow branches never delete a position, so the stale count is not read on this path; a deletion from
            // it would revert in _deletePosition's index check rather than corrupt storage.
            {
                bytes memory result_ = DEX_V2.startOperation(
                    abi.encode(
                        dexKey_,
                        StartOperationParams({
                            isOperate: IS_OPERATE,
                            estimate: IS_NOT_ESTIMATE, // estimate is only for liquidate
                            positionType: positionType_,
                            nftId: nftId_,
                            nftConfig: nftConfig_,
                            token0Index: p_.token0Index,
                            token1Index: p_.token1Index,
                            positionIndex: positionIndex_,
                            tickLower: p_.tickLower,
                            tickUpper: p_.tickUpper,
                            positionSalt: v_.positionSalt,
                            emode: emode_,
                            permissionlessTokens: v_.permissionlessTokens,
                            actionData: abi.encode(
                                SafeCast.toInt256(p_.amount0),
                                SafeCast.toInt256(p_.amount1),
                                p_.amount0Min,
                                p_.amount1Min,
                                p_.to
                            )
                        })
                    )
                );
                (, uint256 actualAmount0_, uint256 actualAmount1_) = abi.decode(result_, (bool, uint256, uint256));
                p_.amount0 = actualAmount0_;
                p_.amount1 = actualAmount1_;
            }
            actionData_ = abi.encode(positionType_, p_);
        } else {
            revert(); // Invalid position type
        }

        return (positionIndex_, actionData_);
    }

    /// @notice Runs an action on an existing D3 / D4 position for the operate module (SPEC.md §7.1.3); the body of
    ///         the former `operate` types 3 / 4 branch, unchanged.
    /// @dev The `DexKey` and ticks are rebuilt from the stored word plus the token addresses of the current emode's
    ///      token configs; `actionData` is forwarded verbatim and the callback selects deposit / withdraw / borrow /
    ///      payback / fee collection from its signs (SPEC.md §10.4). `permissionlessTokens` is recomputed from the
    ///      current emode's classes on every call. A deposit / borrow (both amounts `>= 0`, not both 0) first passes
    ///      the range gate (`_verifyD3D4RangeWithinOracleBand` with `D3D4_INCREASE_MAX_TICK_DISTANCE`,
    ///      `D3D4Module__RangeTooFarFromPrice`); withdraws, paybacks and fee collections are not gated. Reverts with
    ///      empty data for a position type other than 3 / 4; DexV2 reverts, `PendingTransfersNotCleared(bytes)`
    ///      included, bubble unchanged.
    /// @param params_ `ModifyDexPositionParams`: the NFT, its config word and emode, the position index and word, and
    ///        the user's `abi.encode(int256 amount0, int256 amount1, uint256 amount0Min, uint256 amount1Min, address to)`
    /// @return actualActionData_ The five-word action data with the DexV2-used amounts (`_reconstructD3D4ActionData`)
    function modifyPosition(
        ModifyDexPositionParams calldata params_
    ) external payable _onlyDelegateCall returns (bytes memory actualActionData_) {
        uint256 nftId_ = params_.nftId;
        uint256 nftConfig_ = params_.nftConfig;
        uint256 emode_ = params_.emode;
        uint256 positionIndex_ = params_.positionIndex;
        uint256 positionData_ = params_.positionData;
        uint256 positionType_ = (positionData_ >> MSL.BITS_POSITION_DATA_POSITION_TYPE) & X5;
        bytes calldata actionData_ = params_.actionData;

        if (positionType_ == D3_POSITION_TYPE || positionType_ == D4_POSITION_TYPE) {
            // Existing D3 / D4 position: the DexKey and ticks are rebuilt from the stored word plus the token
            // addresses of the current emode's token configs; actionData_ is forwarded verbatim and the callback
            // module selects deposit / withdraw / borrow / payback / fee collection from its signs (SPEC.md §10.4).
            DexKey memory dexKey_;
            StartOperationParams memory s_ = StartOperationParams({
                isOperate: IS_OPERATE,
                estimate: IS_NOT_ESTIMATE, // estimate is only for liquidate
                positionType: positionType_,
                nftId: nftId_,
                nftConfig: nftConfig_,
                token0Index: (positionData_ >> MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_TOKEN_0_INDEX) & X12,
                token1Index: (positionData_ >> MSL.BITS_POSITION_DATA_POSITION_TYPE_3_AND_4_TOKEN_1_INDEX) & X12,
                positionIndex: positionIndex_,
                tickLower: 0,
                tickUpper: 0,
                positionSalt: keccak256(abi.encode(nftId_)),
                emode: emode_,
                permissionlessTokens: false,
                actionData: actionData_
            });

            // permissionlessTokens is recomputed from the current emode's classes on every call, but the
            // callback consults it only while the pool's _positionCapConfigs word is zero (first liquidity
            // increase); once that word is set every caller is admitted regardless of this flag.
            {
                uint256 token0Configs_ = _getTokenConfigs(emode_, s_.token0Index);
                uint256 token1Configs_ = _getTokenConfigs(emode_, s_.token1Index);

                if (positionType_ == D3_POSITION_TYPE) {
                    if (
                        (token0Configs_ >> MSL.BITS_TOKEN_CONFIGS_COLLATERAL_CLASS) & X3 ==
                        COLLATERAL_CLASS_PERMISSIONLESS &&
                        (token1Configs_ >> MSL.BITS_TOKEN_CONFIGS_COLLATERAL_CLASS) & X3 ==
                        COLLATERAL_CLASS_PERMISSIONLESS
                    ) {
                        s_.permissionlessTokens = true;
                    }
                } else if (positionType_ == D4_POSITION_TYPE) {
                    if (
                        (token0Configs_ >> MSL.BITS_TOKEN_CONFIGS_DEBT_CLASS) & X3 == DEBT_CLASS_PERMISSIONLESS &&
                        (token1Configs_ >> MSL.BITS_TOKEN_CONFIGS_DEBT_CLASS) & X3 == DEBT_CLASS_PERMISSIONLESS
                    ) {
                        s_.permissionlessTokens = true;
                    }
                } else {
                    revert(); // This shouldn't ever happen
                }

                (dexKey_, s_.tickLower, s_.tickUpper) = _decodeD3D4PositionData(
                    positionData_,
                    token0Configs_,
                    token1Configs_
                );
            }

            // NOTE: No need to check these here because this must be checked while creating the position
            // if (dexKey_.tickSpacing > MAX_TICK_SPACING ||
            //     s_.tickLower >= s_.tickUpper ||
            //     s_.tickLower <= MIN_TICK ||
            //     s_.tickUpper >= MAX_TICK
            // ) revert();

            // Range gate (SPEC.md §7.1.3) on the liquidity increases only (D3 deposit / D4 borrow: both amounts >= 0,
            // not both 0): both bounds within D3D4_INCREASE_MAX_TICK_DISTANCE ticks (a price ratio of 200) of the tick
            // of the oracle-implied price (D3D4Module__RangeTooFarFromPrice). Withdraws, paybacks and fee collections
            // are not gated so a position the price has moved away from can always be reduced or closed.
            if (_isD3D4LiquidityIncrease(actionData_)) {
                _verifyD3D4RangeWithinOracleBand(
                    positionType_,
                    emode_,
                    s_.token0Index,
                    s_.token1Index,
                    s_.tickLower,
                    s_.tickUpper,
                    D3D4_INCREASE_MAX_TICK_DISTANCE
                );
            }

            // DexV2 calls startOperationCallback on the proxy with these bytes and returns the callback's
            // abi.encode(bool positionDeleted, uint256 amount0, uint256 amount1); any revert inside bubbles
            // unchanged, as PendingTransfersNotCleared(bytes) when a settle left pending amounts.
            bytes memory result_ = DEX_V2.startOperation(abi.encode(dexKey_, s_));
            actualActionData_ = _reconstructD3D4ActionData(actionData_, result_);
        } else revert(); // This shouldn't ever happen
    }

    /// @notice Handles DexV2 callbacks for D3/D4 position operations
    /// @dev Processes:
    ///      - Fee collection (amount0=0 && amount1=0)
    ///      - D3 deposits/withdrawals (smart collateral)
    ///      - D4 borrows/paybacks (smart debt)
    ///      Updates position caps, fee storage, and validates health factor where applicable.
    ///      Preconditions (empty revert otherwise): reached by delegatecall, `msg.sender == DEX_V2`, an operation is
    ///      active (`_msgSender != 0`), so it runs only inside a `startOperation` the Money Market itself opened.
    ///      `s_.actionData` is decoded as `(int256 amount0, int256 amount1)` to pick the branch and then fully as
    ///      `(int256, int256, uint256, uint256, address to)` (shorter data reverts with empty data in `abi.decode`):
    ///      both `>= 0` and not both 0: D3 deposit / D4 borrow; both `<= 0` and not both 0: D3 withdraw / D4 payback;
    ///      both 0: fee collection with words 3-4 as the collection amounts; mixed signs or a position type other than
    ///      3 / 4: empty revert. Branch table in SPEC.md §10.4.
    ///      `isOperate` (true from `operate`, false from `liquidate`) gates `_verifyAmountLimits` on withdraw / payback
    ///      / fee-collection legs and the health-factor check after withdraws and fee collections; the D4 borrow check
    ///      is unconditional. Settlement (`DEX_V2.settle` per token, SPEC.md §10.5) runs when `isOperate || !estimate`;
    ///      in liquidation estimate mode it is skipped, the module call's pending legs stay open and DexV2 reverts the
    ///      outer `startOperation` with `PendingTransfersNotCleared(returnData_)`, which unwinds every storage write
    ///      made here and hands the liquidate module the return bytes.
    ///      Ordering: in the four position-changing branches the settles, and with them the token or native transfer
    ///      to `to` and the `dexCallback` pull from `_msgSender`, run before the fee-store, cap and health-factor
    ///      updates; in the fee-collection branch the store update and the deletion run first. Health factor:
    ///      `_checkHf(nftId, IS_OPERATE)` after a D3 withdraw and a fee collection (operate only) and after every D4
    ///      borrow; never after a D3 deposit or D4 payback. Deletion: a withdraw, payback or fee collection that leaves
    ///      DexV2 liquidity 0 and an empty fee store deletes the position (swap-and-pop, SPEC.md §7.1.5) from the
    ///      `nftConfig` snapshot in `s_`. `to != 0` is required on withdraw, borrow and fee collection; `address(this)`
    ///      is not rejected. Typed reverts: `FluidMoneyMarketError(ErrorTypes.Helpers__HealthFactorFailed)`;
    ///      `Panic(0x11)` (native value short in `_depositSettle` / `_paybackSettle`, fee collection above stored plus
    ///      accrued, cap counters); DexV2, Liquidity and oracle errors bubbled unchanged. No event of its own.
    /// @param data_ Encoded (DexKey, StartOperationParams) containing position and action details
    /// @return returnData_ Encoded result indicating position deletion status and amounts:
    ///         `abi.encode(bool positionDeleted, uint256 amount0, uint256 amount1)` (96 bytes in every branch), the
    ///         amounts being the ones DexV2 used (deposit / borrow), paid out (withdraw / borrow), pulled (payback) or
    ///         collected (fee collection), in normal token units
    function startOperationCallback(
        bytes calldata data_
    ) external _onlyDelegateCall returns (bytes memory returnData_) {
        // Only DexV2, and only while an operation opened by operate / liquidate is active (both empty reverts)
        if (msg.sender != address(DEX_V2)) revert();
        if (_msgSender == address(0)) revert();

        (DexKey memory dexKey_, StartOperationParams memory s_) = abi.decode(data_, (DexKey, StartOperationParams));

        // For it the action data can either be add or remove liquidity, hence action data will be decoded accordingly
        (int256 amount0_, int256 amount1_) = abi.decode(s_.actionData, (int256, int256));

        if (amount0_ == 0 && amount1_ == 0) {
            // This means that the user is trying to collect fees
            (, , uint256 feeCollectionAmount0_, uint256 feeCollectionAmount1_, address to_) = abi.decode(
                s_.actionData,
                (int256, int256, uint256, uint256, address)
            );
            if (to_ == address(0)) revert();

            // First we will collect the accrued fees
            if (s_.positionType == D3_POSITION_TYPE) {
                // Collecting the accrued fees by passing zero withdraw amounts
                returnData_ = DEX_V2.operate(
                    D3_DEX_TYPE,
                    D3_USER_MODULE_IMPLEMENTATION_ID,
                    abi.encodeWithSelector(
                        DEX_V2_WITHDRAW_SELECTOR,
                        WithdrawParams({
                            dexKey: dexKey_,
                            tickLower: s_.tickLower,
                            tickUpper: s_.tickUpper,
                            positionSalt: s_.positionSalt,
                            amount0: uint256(0),
                            amount1: uint256(0),
                            amount0Min: 0,
                            amount1Min: 0
                        })
                    )
                );

                uint256 feeAccruedToken0_;
                uint256 feeAccruedToken1_;

                {
                    uint256 amount0Withdrawn_;
                    uint256 amount1Withdrawn_;
                    uint256 liquidityDecrease_;
                    (
                        amount0Withdrawn_,
                        amount1Withdrawn_,
                        feeAccruedToken0_,
                        feeAccruedToken1_,
                        liquidityDecrease_
                    ) = abi.decode(returnData_, (uint256, uint256, uint256, uint256, uint256));
                    // a zero-amount withdraw must move nothing; it only realises the accrued fees
                    if (!(amount0Withdrawn_ == 0 && amount1Withdrawn_ == 0 && liquidityDecrease_ == 0)) revert();
                }

                (feeCollectionAmount0_, feeCollectionAmount1_) = _updateAndCollectFees(
                    FeeCollectionParams({
                        nftId: s_.nftId,
                        positionId: _encodePositionId(D3_POSITION_TYPE, dexKey_),
                        dexV2PositionId: _encodeDexV2PositionId(s_.tickLower, s_.tickUpper, s_.positionSalt),
                        feeAccruedToken0: feeAccruedToken0_,
                        feeAccruedToken1: feeAccruedToken1_,
                        feeCollectionAmount0: feeCollectionAmount0_,
                        feeCollectionAmount1: feeCollectionAmount1_,
                        isOperate: s_.isOperate
                    })
                );

                if (
                    _isD3D4PositionEmpty(
                        s_.nftId,
                        D3_POSITION_TYPE,
                        dexKey_,
                        s_.tickLower,
                        s_.tickUpper,
                        s_.positionSalt
                    )
                ) {
                    _handleD3PositionDeletion(s_);
                    returnData_ = abi.encode(POSITION_DELETED, feeCollectionAmount0_, feeCollectionAmount1_);
                } else {
                    returnData_ = abi.encode(POSITION_NOT_DELETED, feeCollectionAmount0_, feeCollectionAmount1_);
                }

                // Settlement is skipped only in liquidation estimate mode (!isOperate && estimate): the pending legs then
                // stay open and DexV2 reverts the outer startOperation with PendingTransfersNotCleared(returnData_). In
                // this branch the fee-store update and the deletion run before the settle (unlike the other branches).
                if (s_.isOperate || !s_.estimate) {
                    _feeSettle(dexKey_.token0, feeAccruedToken0_, feeCollectionAmount0_, to_);
                    _feeSettle(dexKey_.token1, feeAccruedToken1_, feeCollectionAmount1_, to_);
                }
            } else if (s_.positionType == D4_POSITION_TYPE) {
                // Collecting the accrued fees by passing zero payback amounts
                // DexV2 gates payback, this zero-amount call included, with its D4 user whitelist: D4 fee collection and
                // fee-store seizure need the Money Market proxy whitelisted just like borrow / payback.
                returnData_ = DEX_V2.operate(
                    D4_DEX_TYPE,
                    D4_USER_MODULE_IMPLEMENTATION_ID,
                    abi.encodeWithSelector(
                        DEX_V2_PAYBACK_SELECTOR,
                        PaybackParams({
                            dexKey: dexKey_,
                            tickLower: s_.tickLower,
                            tickUpper: s_.tickUpper,
                            positionSalt: s_.positionSalt,
                            amount0: uint256(0),
                            amount1: uint256(0),
                            amount0Min: 0,
                            amount1Min: 0
                        })
                    )
                );

                uint256 feeAccruedToken0_;
                uint256 feeAccruedToken1_;
                {
                    uint256 amount0Payedback_;
                    uint256 amount1Payedback_;
                    uint256 liquidityDecrease_;
                    (
                        amount0Payedback_,
                        amount1Payedback_,
                        feeAccruedToken0_,
                        feeAccruedToken1_,
                        liquidityDecrease_
                    ) = abi.decode(returnData_, (uint256, uint256, uint256, uint256, uint256));
                    // a zero-amount payback must move nothing; it only realises the accrued fees
                    if (!(amount0Payedback_ == 0 && amount1Payedback_ == 0 && liquidityDecrease_ == 0)) revert();
                }

                (feeCollectionAmount0_, feeCollectionAmount1_) = _updateAndCollectFees(
                    FeeCollectionParams({
                        nftId: s_.nftId,
                        positionId: _encodePositionId(D4_POSITION_TYPE, dexKey_),
                        dexV2PositionId: _encodeDexV2PositionId(s_.tickLower, s_.tickUpper, s_.positionSalt),
                        feeAccruedToken0: feeAccruedToken0_,
                        feeAccruedToken1: feeAccruedToken1_,
                        feeCollectionAmount0: feeCollectionAmount0_,
                        feeCollectionAmount1: feeCollectionAmount1_,
                        isOperate: s_.isOperate
                    })
                );

                if (
                    _isD3D4PositionEmpty(
                        s_.nftId,
                        D4_POSITION_TYPE,
                        dexKey_,
                        s_.tickLower,
                        s_.tickUpper,
                        s_.positionSalt
                    )
                ) {
                    _deletePosition(s_.nftId, s_.nftConfig, s_.positionIndex);
                    returnData_ = abi.encode(POSITION_DELETED, feeCollectionAmount0_, feeCollectionAmount1_);
                } else {
                    returnData_ = abi.encode(POSITION_NOT_DELETED, feeCollectionAmount0_, feeCollectionAmount1_);
                }

                if (s_.isOperate || !s_.estimate) {
                    _feeSettle(dexKey_.token0, feeAccruedToken0_, feeCollectionAmount0_, to_);
                    _feeSettle(dexKey_.token1, feeAccruedToken1_, feeCollectionAmount1_, to_);
                }
            } else {
                revert();
            }

            // We check hf after fee collection
            // (operate only: the liquidate module runs its own post-check with IS_LIQUIDATE after startOperation returns)
            if (s_.isOperate) {
                _checkHf(s_.nftId, IS_OPERATE);
            }
        } else {
            (, , uint256 amount0Min_, uint256 amount1Min_, address to_) = abi.decode(
                s_.actionData,
                (int256, int256, uint256, uint256, address)
            );

            if (s_.positionType == D3_POSITION_TYPE) {
                if (amount0_ >= 0 && amount1_ >= 0) {
                    // Deposit
                    // Each non-zero leg must be in [1e4, X128] (this is also the creation path's amount check). The amounts
                    // settled below are the ones DexV2 reports as used, not the request.
                    if (amount0_ > 0) _verifyAmountLimits(amount0_);
                    if (amount1_ > 0) _verifyAmountLimits(amount1_);

                    returnData_ = DEX_V2.operate(
                        D3_DEX_TYPE,
                        D3_USER_MODULE_IMPLEMENTATION_ID,
                        abi.encodeWithSelector(
                            DEX_V2_DEPOSIT_SELECTOR,
                            DepositParams({
                                dexKey: dexKey_,
                                tickLower: s_.tickLower,
                                tickUpper: s_.tickUpper,
                                positionSalt: s_.positionSalt,
                                amount0: uint256(amount0_),
                                amount1: uint256(amount1_),
                                amount0Min: amount0Min_,
                                amount1Min: amount1Min_
                            })
                        )
                    );

                    uint256 liquidityIncrease_;
                    bytes32 positionId_ = _encodePositionId(D3_POSITION_TYPE, dexKey_);
                    {
                        uint256 feeAccruedToken0_;
                        uint256 feeAccruedToken1_;
                        {
                            uint256 amount0Supplied_;
                            uint256 amount1Supplied_;
                            (
                                amount0Supplied_,
                                amount1Supplied_,
                                feeAccruedToken0_,
                                feeAccruedToken1_,
                                liquidityIncrease_
                            ) = abi.decode(returnData_, (uint256, uint256, uint256, uint256, uint256));

                            if (s_.isOperate || !s_.estimate) {
                                _depositSettle(dexKey_.token0, amount0Supplied_, feeAccruedToken0_, to_);
                                _depositSettle(dexKey_.token1, amount1Supplied_, feeAccruedToken1_, to_);
                            }
                        }

                        _updateFeeStoredWithNewFeeAccrued(
                            s_.nftId,
                            positionId_,
                            _encodeDexV2PositionId(s_.tickLower, s_.tickUpper, s_.positionSalt),
                            feeAccruedToken0_,
                            feeAccruedToken1_
                        );
                    }

                    _checkAndUpdateCapsForD3D4LiquidityIncrease(
                        positionId_,
                        D3_DEX_TYPE,
                        dexKey_,
                        s_.tickLower,
                        s_.tickUpper,
                        liquidityIncrease_,
                        s_.permissionlessTokens
                    );

                    (uint256 amount0Supplied_, uint256 amount1Supplied_) = abi.decode(returnData_, (uint256, uint256));
                    returnData_ = abi.encode(POSITION_NOT_DELETED, amount0Supplied_, amount1Supplied_);

                    // NOTE: We dont check hf after deposits
                } else if (amount0_ <= 0 && amount1_ <= 0) {
                    // Withdraw

                    // to_ == address(this) is not rejected (SPEC.md §16). The [1e4, X128] bound applies to operate only;
                    // liquidation withdraws pass the module's own figures. DexV2 clamps amounts above the position to the
                    // position (an over-request withdraws everything); a full exit can revert with Panic(0x11) inside DexV2
                    // when the pool's per-pool reserve counter is below the claim (SPEC.md §16).
                    if (to_ == address(0)) revert();

                    if (s_.isOperate) {
                        if (amount0_ < 0) _verifyAmountLimits(amount0_);
                        if (amount1_ < 0) _verifyAmountLimits(amount1_);
                    }

                    returnData_ = DEX_V2.operate(
                        D3_DEX_TYPE,
                        D3_USER_MODULE_IMPLEMENTATION_ID,
                        abi.encodeWithSelector(
                            DEX_V2_WITHDRAW_SELECTOR,
                            WithdrawParams({
                                dexKey: dexKey_,
                                tickLower: s_.tickLower,
                                tickUpper: s_.tickUpper,
                                positionSalt: s_.positionSalt,
                                amount0: uint256(-amount0_),
                                amount1: uint256(-amount1_),
                                amount0Min: amount0Min_,
                                amount1Min: amount1Min_
                            })
                        )
                    );

                    {
                        uint256 feeAccruedToken0_;
                        uint256 feeAccruedToken1_;
                        uint256 liquidityDecrease_;
                        {
                            uint256 amount0Withdrawn_;
                            uint256 amount1Withdrawn_;
                            (
                                amount0Withdrawn_,
                                amount1Withdrawn_,
                                feeAccruedToken0_,
                                feeAccruedToken1_,
                                liquidityDecrease_
                            ) = abi.decode(returnData_, (uint256, uint256, uint256, uint256, uint256));

                            if (s_.isOperate || !s_.estimate) {
                                _withdrawSettle(dexKey_.token0, amount0Withdrawn_, feeAccruedToken0_, to_);
                                _withdrawSettle(dexKey_.token1, amount1Withdrawn_, feeAccruedToken1_, to_);
                            }
                        }

                        bytes32 positionId_ = _encodePositionId(D3_POSITION_TYPE, dexKey_);
                        _updateFeeStoredWithNewFeeAccrued(
                            s_.nftId,
                            positionId_,
                            _encodeDexV2PositionId(s_.tickLower, s_.tickUpper, s_.positionSalt),
                            feeAccruedToken0_,
                            feeAccruedToken1_
                        );

                        _updatePositionCapsForD3D4LiquidityDecrease(
                            positionId_,
                            s_.tickLower,
                            s_.tickUpper,
                            liquidityDecrease_
                        );
                    }

                    // Decoding here to get amount0Withdrawn_ and amount1Withdrawn_ because doing it above was giving stack too deep
                    (uint256 amount0Withdrawn_, uint256 amount1Withdrawn_) = abi.decode(
                        returnData_,
                        (uint256, uint256)
                    );

                    if (
                        _isD3D4PositionEmpty(
                            s_.nftId,
                            D3_POSITION_TYPE,
                            dexKey_,
                            s_.tickLower,
                            s_.tickUpper,
                            s_.positionSalt
                        )
                    ) {
                        _handleD3PositionDeletion(s_);
                        returnData_ = abi.encode(POSITION_DELETED, amount0Withdrawn_, amount1Withdrawn_);
                    } else {
                        returnData_ = abi.encode(POSITION_NOT_DELETED, amount0Withdrawn_, amount1Withdrawn_);
                    }

                    // We check hf after withdrawals
                    if (s_.isOperate) {
                        _checkHf(s_.nftId, IS_OPERATE);
                    }
                } else {
                    revert();
                }
            } else if (s_.positionType == D4_POSITION_TYPE) {
                if (amount0_ >= 0 && amount1_ >= 0) {
                    // Borrow

                    // to_ == address(this) is not rejected (SPEC.md §16). DexV2 performs no collateral check for a
                    // whitelisted D4 user; the health-factor check at the end of this branch is the only one.
                    if (to_ == address(0)) revert();

                    if (amount0_ > 0) _verifyAmountLimits(amount0_);
                    if (amount1_ > 0) _verifyAmountLimits(amount1_);

                    // Check if the position's emode allows taking debt of both the tokens
                    _validateDebtForEmode(s_.emode, s_.token0Index);
                    _validateDebtForEmode(s_.emode, s_.token1Index);

                    returnData_ = DEX_V2.operate(
                        D4_DEX_TYPE,
                        D4_USER_MODULE_IMPLEMENTATION_ID,
                        abi.encodeWithSelector(
                            DEX_V2_BORROW_SELECTOR,
                            BorrowParams({
                                dexKey: dexKey_,
                                tickLower: s_.tickLower,
                                tickUpper: s_.tickUpper,
                                positionSalt: s_.positionSalt,
                                amount0: uint256(amount0_),
                                amount1: uint256(amount1_),
                                amount0Min: amount0Min_,
                                amount1Min: amount1Min_
                            })
                        )
                    );

                    uint256 liquidityIncrease_;
                    bytes32 positionId_ = _encodePositionId(D4_POSITION_TYPE, dexKey_);
                    {
                        uint256 feeAccruedToken0_;
                        uint256 feeAccruedToken1_;
                        {
                            uint256 amount0Borrowed_;
                            uint256 amount1Borrowed_;
                            (
                                amount0Borrowed_,
                                amount1Borrowed_,
                                feeAccruedToken0_,
                                feeAccruedToken1_,
                                liquidityIncrease_
                            ) = abi.decode(returnData_, (uint256, uint256, uint256, uint256, uint256));

                            // Settle runs before the storage updates below (fee store, caps, health factor) because of
                            // stack-too-deep. The settle is not callback-free: for the native token DexV2 (or
                            // Liquidity, when DexV2 routes the outflow there) sends the value to to_ with a 50 000 gas
                            // stipend, an external call into a caller-chosen contract. Nothing can persist from that
                            // call: the transient _msgSender is set, so operate / liquidate / changeEmode revert with
                            // Base__ValidationFailed and the ERC-721 mutators with ERC721__InvalidOperation; DexV2
                            // holds its reentrancy lock during settle; a DexV2 operation started from the hook leaves
                            // pending amounts that make the outer startOperation revert; and the stipend is not enough
                            // for a DexV2 swap. The admin fallback is not under the guard. A change to any of these
                            // guards must revisit this ordering. A D4 borrow leg served from the dex balance can also
                            // make DexV2 sync its own position with Liquidity inside the settle (LogRebalance); that
                            // Liquidity call runs under DexV2's settle lock, Liquidity's callback targets DexV2 only,
                            // and any Liquidity revert of the dex user reverts this call.
                            if (s_.isOperate || !s_.estimate) {
                                _borrowSettle(dexKey_.token0, amount0Borrowed_, feeAccruedToken0_, to_);
                                _borrowSettle(dexKey_.token1, amount1Borrowed_, feeAccruedToken1_, to_);
                            }
                        }

                        _updateFeeStoredWithNewFeeAccrued(
                            s_.nftId,
                            positionId_,
                            _encodeDexV2PositionId(s_.tickLower, s_.tickUpper, s_.positionSalt),
                            feeAccruedToken0_,
                            feeAccruedToken1_
                        );
                    }

                    _checkAndUpdateCapsForD3D4LiquidityIncrease(
                        positionId_,
                        D4_DEX_TYPE,
                        dexKey_,
                        s_.tickLower,
                        s_.tickUpper,
                        liquidityIncrease_,
                        s_.permissionlessTokens
                    );

                    // We check hf after borrows
                    // NOTE: Borrow happens during operate only, hence skipping the check
                    // if (s_.isOperate) {
                    _checkHf(s_.nftId, IS_OPERATE);
                    // }

                    (uint256 amount0Borrowed_, uint256 amount1Borrowed_) = abi.decode(returnData_, (uint256, uint256));
                    returnData_ = abi.encode(POSITION_NOT_DELETED, amount0Borrowed_, amount1Borrowed_);
                } else if (amount0_ <= 0 && amount1_ <= 0) {
                    // Payback
                    // The [1e4, X128] bound applies to operate only. DexV2 clamps amounts above the position to the position
                    // and rounds the paid-back amounts up, so the amount pulled (or the native value consumed in
                    // _paybackSettle) can exceed the request; a native payback needs that margin as msg.value.

                    if (s_.isOperate) {
                        if (amount0_ < 0) _verifyAmountLimits(amount0_);
                        if (amount1_ < 0) _verifyAmountLimits(amount1_);
                    }

                    returnData_ = DEX_V2.operate(
                        D4_DEX_TYPE,
                        D4_USER_MODULE_IMPLEMENTATION_ID,
                        abi.encodeWithSelector(
                            DEX_V2_PAYBACK_SELECTOR,
                            PaybackParams({
                                dexKey: dexKey_,
                                tickLower: s_.tickLower,
                                tickUpper: s_.tickUpper,
                                positionSalt: s_.positionSalt,
                                amount0: uint256(-amount0_),
                                amount1: uint256(-amount1_),
                                amount0Min: amount0Min_,
                                amount1Min: amount1Min_
                            })
                        )
                    );

                    {
                        uint256 feeAccruedToken0_;
                        uint256 feeAccruedToken1_;
                        uint256 liquidityDecrease_;
                        {
                            uint256 amount0Payedback_;
                            uint256 amount1Payedback_;
                            (
                                amount0Payedback_,
                                amount1Payedback_,
                                feeAccruedToken0_,
                                feeAccruedToken1_,
                                liquidityDecrease_
                            ) = abi.decode(returnData_, (uint256, uint256, uint256, uint256, uint256));

                            if (s_.isOperate || !s_.estimate) {
                                _paybackSettle(dexKey_.token0, amount0Payedback_, feeAccruedToken0_, to_);
                                _paybackSettle(dexKey_.token1, amount1Payedback_, feeAccruedToken1_, to_);
                            }
                        }
                        bytes32 positionId_ = _encodePositionId(D4_POSITION_TYPE, dexKey_);
                        _updateFeeStoredWithNewFeeAccrued(
                            s_.nftId,
                            positionId_,
                            _encodeDexV2PositionId(s_.tickLower, s_.tickUpper, s_.positionSalt),
                            feeAccruedToken0_,
                            feeAccruedToken1_
                        );

                        _updatePositionCapsForD3D4LiquidityDecrease(
                            positionId_,
                            s_.tickLower,
                            s_.tickUpper,
                            liquidityDecrease_
                        );
                    }

                    // Decoding here again to get amount0Payedback_ and amount1Payedback_ because doing it above was giving stack too deep
                    (uint256 amount0Payedback_, uint256 amount1Payedback_) = abi.decode(
                        returnData_,
                        (uint256, uint256)
                    );

                    if (
                        _isD3D4PositionEmpty(
                            s_.nftId,
                            D4_POSITION_TYPE,
                            dexKey_,
                            s_.tickLower,
                            s_.tickUpper,
                            s_.positionSalt
                        )
                    ) {
                        _deletePosition(s_.nftId, s_.nftConfig, s_.positionIndex);
                        returnData_ = abi.encode(POSITION_DELETED, amount0Payedback_, amount1Payedback_);
                    } else {
                        returnData_ = abi.encode(POSITION_NOT_DELETED, amount0Payedback_, amount1Payedback_);
                    }
                    // NOTE: We dont check hf after paybacks
                } else {
                    revert();
                }
            } else {
                revert();
            }
        }
    }
}
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.