Skip to content
Verified contractExactBUSL-1.1

FluidDexV2D4UserModule

Address0x609a72d609614284a1db941b5e2845fc9493dbbb
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,271,531
Creation transaction
0x6ee3ba88a3…773d7e0eb1

38 files

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

contracts/protocols/dexV2/dexTypes/d4/core/userModule.sol

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

import "../other/commonImport.sol";
import { PendingTransfers as PT } from "../../../../../libraries/pendingTransfers.sol";

/// @title FluidDexV2D4UserModule
/// @notice User module for D4 (smart debt) DEX positions
/// @dev Handles borrows, paybacks, and pool initialization for concentrated liquidity debt positions.
///      A D4 position is smart debt: a range of debt whose composition swaps can move, priced at the tokens'
///      Liquidity BORROW exchange prices (`rawAdjusted = amount * 1e12 * numeratorPrecision / (borrowExchangePrice *
///      denominatorPrecision)`; a token never listed at Liquidity makes every `borrow` and `payback` revert with
///      `FluidLiquidityCalcsError(70001)`, `initialize` reads no price). Ticks and `sqrtPriceX96` live in that
///      raw-adjusted space, so a range drifts against the market at the differential of the two tokens' borrow
///      rates. Debt amounts and position reserves are linked by the quadratic in helpers.sol; the position's
///      liquidity is debt liquidity.
///      Stateless implementation delegatecalled by the `FluidDexV2` proxy via `operate(4, 2, data)`. Every function
///      needs the D4 whitelist (the Money Market is the intended user; it performs the collateral check the dex
///      does not). No function moves tokens: each records signed pending-transfer legs under msg.sender that the
///      base's `settle` executes. Model, accepted behaviours and open items: docs/internal-dev/dexv2-d3d4-notes.md.
contract FluidDexV2D4UserModule is CommonImportD4Other {
    /// @dev Dex type 4, version 0; every use divides by `DEX_TYPE_DIVISOR`, discarding the version digits, so all
    ///      versions of a type share one storage namespace. Re-declared in each of the four D4 modules.
    uint256 internal constant DEX_TYPE_WITH_VERSION = 40_000;

    /// @notice Initializes the D4 User Module
    /// @param liquidityAddress_ The FluidLiquidity contract address
    constructor(address liquidityAddress_) {
        THIS_CONTRACT = address(this);
        LIQUIDITY = IFluidLiquidity(liquidityAddress_);
    }

    /// @dev Reverts with `UserModule__UserNotWhitelisted` (210003) unless msg.sender (the `operate` caller) is on the
    ///      D4 whitelist, which is per dex type, not per pool, and set through the D4 admin module. One bit gates
    ///      `initialize`, `borrow` AND `payback`: removing an address from the whitelist also blocks its paybacks
    ///      and, for the Money Market, its D4 liquidations.
    modifier _onlyWhitelistedUsers() {
        if (_whitelistedUsers[DEX_TYPE_WITH_VERSION / DEX_TYPE_DIVISOR][msg.sender] == 0) {
            revert FluidDexV2D3D4Error(ErrorTypes.UserModule__UserNotWhitelisted);
        }
        _;
    }

    /// @notice Borrows tokens by creating or increasing a concentrated liquidity debt position (smart debt)
    /// @dev Delegatecall only (212012); D4-whitelisted callers only (210003), inside an active operation. Takes the
    ///      per-pool transient lock keyed by `keccak256(abi.encode(dexKey))` (shared with the D3 pool of the same
    ///      key; a reentrant call reverts with empty revert data) and releases it at the end. Position id =
    ///      `keccak256(abi.encode(msg.sender, tickLower, tickUpper, positionSalt))`; a top-up first credits the LP
    ///      fees accrued since the position's last touch.
    ///      Amounts: `amount0` / `amount1` are the desired debt amounts (normal units, converted at the BORROW
    ///      exchange price). They are mapped to position reserves by the price-independent debt -> reserve quadratic
    ///      (`_getReservesFromDebtAmounts`), the reserves are added as liquidity (rounded UP by 1e-9 and +1 for
    ///      smart debt, `min(L0, L1)` in range), the reserves actually used are mapped back to debt amounts, and
    ///      those are returned rounded down (raw round-down by 1e-9, then -1); fees are rounded down. An in-range
    ///      request needs both legs: a single leg maps to a single-sided reserve and to zero liquidity and reverts
    ///      with 212007. `_verifyReserveAndDebtLimits` runs on the requested and on the resulting amounts, so
    ///      an in-range borrow or top-up while the pool price sits within about 1/101 of the range width of either
    ///      range edge reverts with 212013 whatever the amounts, as does a request whose legs differ by more than
    ///      100x in reserve terms.
    ///      Pending transfers recorded under msg.sender, per token: pending borrow `+= amount` (the dex owes the
    ///      borrower) and pending supply `-= feeAccrued` (the accrued LP fee is paid by withdrawing the dex's
    ///      Liquidity supply, where swaps parked it).
    ///      Emits `LogBorrow(dexType, dexId, msg.sender, tickLower, tickUpper, positionSalt, amount0, amount1,
    ///      feeAccruedToken0, feeAccruedToken1, liquidityIncreaseRaw)`.
    ///      Reverts with `FluidDexV2D3D4Error(id)`: 210001 pool not initialized; 212004 a non-zero input, or a
    ///      returned amount, outside [1e4, 2^128); 210014 a non-zero input rounds to zero raw-adjusted units, or both
    ///      round to zero; 212005 a reserve or debt amount outside [1e4, 2^86); 212013 reserve / debt ratio of a
    ///      token above 100x; 210004 invalid range (tickLower >= tickUpper, a tick not a multiple of tickSpacing or
    ///      not strictly inside (-524287, 524287), or more than 8000 ticks apart, i.e. a price band above 2.2254x);
    ///      212007 liquidity to add outside [1e4, 2^86); 212008 liquidity change at a tick below gross / 1e9 or above
    ///      gross * 1e9 (a small first position at a fresh tick caps the next add there at 1e9x its size; two adds
    ///      get through); 210005 tick gross liquidity above 2^102 / numTicks; 210006 (guard); 210013 per-pool
    ///      reserve counter above 2^128; 210002 a returned amount below its minimum. `FluidLiquidityCalcsError(70001)`
    ///      for a token never listed at Liquidity. Panic(0x11) or an empty SafeCast revert from the quadratic for
    ///      inputs far above the limits, before 212005 can report them. A tick outside +-887272 reverts in
    ///      TickMath (`T()`); a range far below -524287 can revert earlier in the quadratic (Panic(0x12) or a
    ///      Helpers__ id) because its X96 prices round to zero. Empty revert data from the pool lock.
    /// @param params_ BorrowParams containing dexKey, tick range, positionSalt, amounts, and minimums
    /// @return amount0 Debt taken in token0, normal units, rounded down; recorded as a positive pending borrow
    /// @return amount1 Debt taken in token1, normal units, rounded down; recorded as a positive pending borrow
    /// @return feeAccruedToken0 LP fee in token0 credited to the position since its last touch, normal units,
    ///         rounded down; a nominal amount fixed at swap time, recorded as a negative pending supply
    /// @return feeAccruedToken1 LP fee in token1 credited since the last touch, normal units, rounded down;
    ///         recorded as a negative pending supply
    /// @return liquidityIncreaseRaw Raw debt liquidity added to the position
    function borrow(BorrowParams calldata params_) external _onlyDelegateCall _onlyWhitelistedUsers 
        returns (uint256, uint256, uint256, uint256, uint256) {
        unchecked {
            BorrowVariables memory v_;

            bytes32 dexId_ = keccak256(abi.encode(params_.dexKey));
            PL.lock(dexId_);

            uint256 dexType_ = DEX_TYPE_WITH_VERSION / DEX_TYPE_DIVISOR;

            CalculatedVars memory c_;
            {
                DexVariables memory dexVariables_ = _getDexVariables(dexType_, dexId_);
                uint256 dexVariables2_ = _dexVariables2[dexType_][dexId_];

                if (dexVariables_.sqrtPriceX96 == 0) {
                    revert FluidDexV2D3D4Error(ErrorTypes.UserModule__DexNotInitialized);
                }

                if (params_.amount0 > 0) _verifyAmountLimits(params_.amount0);
                if (params_.amount1 > 0) _verifyAmountLimits(params_.amount1);

                c_ = _calculateVars(params_.dexKey.token0, params_.dexKey.token1, dexVariables2_);

                // Convert normal amounts to raw adjusted amounts
                // NOTE: This calculation is inside unchecked but it wont overflow because params_.amount0 is limited to X128
                v_.token0DebtAmountRawAdjusted = (params_.amount0 * LC.EXCHANGE_PRICES_PRECISION * c_.token0NumeratorPrecision) / (c_.token0BorrowExchangePrice * c_.token0DenominatorPrecision);
                // NOTE: This calculation is inside unchecked but it wont overflow because params_.amount1 is limited to X128
                v_.token1DebtAmountRawAdjusted = (params_.amount1 * LC.EXCHANGE_PRICES_PRECISION * c_.token1NumeratorPrecision) / (c_.token1BorrowExchangePrice * c_.token1DenominatorPrecision);

                if (
                    (v_.token0DebtAmountRawAdjusted == 0 && params_.amount0 > 0) ||
                    (v_.token1DebtAmountRawAdjusted == 0 && params_.amount1 > 0) ||
                    (v_.token0DebtAmountRawAdjusted == 0 && v_.token1DebtAmountRawAdjusted == 0)
                ) {
                    revert FluidDexV2D3D4Error(ErrorTypes.UserModule__AmountRoundsToZero);
                }

                v_.sqrtPriceLowerX96 = TM.getSqrtRatioAtTick(params_.tickLower);
                v_.sqrtPriceUpperX96 = TM.getSqrtRatioAtTick(params_.tickUpper);

                v_.geometricMeanPriceX96 = FM.mulDiv(v_.sqrtPriceLowerX96, v_.sqrtPriceUpperX96, Q96);
                v_.priceLowerX96 = FM.mulDiv(v_.sqrtPriceLowerX96, v_.sqrtPriceLowerX96, Q96);
                v_.priceUpperX96 = FM.mulDiv(v_.sqrtPriceUpperX96, v_.sqrtPriceUpperX96, Q96);

                (v_.token0ReserveAmountRawAdjusted, v_.token1ReserveAmountRawAdjusted) = _getReservesFromDebtAmounts(
                    v_.geometricMeanPriceX96,
                    v_.priceUpperX96,
                    v_.priceLowerX96,
                    v_.token0DebtAmountRawAdjusted,
                    v_.token1DebtAmountRawAdjusted
                );

                _verifyReserveAndDebtLimits(v_.token0ReserveAmountRawAdjusted, v_.token0DebtAmountRawAdjusted);
                _verifyReserveAndDebtLimits(v_.token1ReserveAmountRawAdjusted, v_.token1DebtAmountRawAdjusted);

                // no matter the user is adding/removing liquidity, the fee is being collected
                (
                    v_.token0ReserveAmountRawAdjusted,
                    v_.token1ReserveAmountRawAdjusted,
                    v_.feeAccruedToken0Adjusted,
                    v_.feeAccruedToken1Adjusted,
                    v_.liquidityIncreaseRaw
                ) = _addLiquidity(AddLiquidityInternalParams({
                    dexKey: params_.dexKey,
                    dexVariables: dexVariables_,
                    dexVariables2: dexVariables2_,
                    tickLower: params_.tickLower,
                    tickUpper: params_.tickUpper,
                    sqrtPriceLowerX96: v_.sqrtPriceLowerX96,
                    sqrtPriceUpperX96: v_.sqrtPriceUpperX96,
                    positionSalt: params_.positionSalt,
                    amount0DesiredRaw: v_.token0ReserveAmountRawAdjusted,
                    amount1DesiredRaw: v_.token1ReserveAmountRawAdjusted,
                    dexType: dexType_,
                    dexId: dexId_,
                    isSmartCollateral: IS_SMART_DEBT
                }));
            }

            (v_.token0DebtAmountRawAdjusted, v_.token1DebtAmountRawAdjusted) = _getDebtAmountsFromReserves(
                v_.geometricMeanPriceX96,
                v_.priceUpperX96,
                v_.priceLowerX96,
                v_.token0ReserveAmountRawAdjusted,
                v_.token1ReserveAmountRawAdjusted
            );

            _verifyReserveAndDebtLimits(v_.token0ReserveAmountRawAdjusted, v_.token0DebtAmountRawAdjusted);
            _verifyReserveAndDebtLimits(v_.token1ReserveAmountRawAdjusted, v_.token1DebtAmountRawAdjusted);

            // Convert raw adjusted amounts to normal amounts
            // Also explicitly rounding down to be 100% sure that the protocol is on the winning side (user gets less when borrowing)
            // NOTE: This calculation is inside unchecked but it wont overflow because v_.token0DebtAmountRawAdjusted is limited to X86
            v_.amount0 = (v_.token0DebtAmountRawAdjusted * c_.token0DenominatorPrecision * c_.token0BorrowExchangePrice * ROUNDING_FACTOR_MINUS_ONE) / 
                (c_.token0NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION * ROUNDING_FACTOR);
            if (v_.amount0 > 0) {
                v_.amount0 -= 1; // Just subtracting 1 so protocol remains on the winning side
                _verifyAmountLimits(v_.amount0);
            }

            // NOTE: This calculation is inside unchecked but it wont overflow because v_.token1DebtAmountRawAdjusted is limited to X86
            v_.amount1 = (v_.token1DebtAmountRawAdjusted * c_.token1DenominatorPrecision * c_.token1BorrowExchangePrice * ROUNDING_FACTOR_MINUS_ONE) / 
                (c_.token1NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION * ROUNDING_FACTOR);
            if (v_.amount1 > 0) {
                v_.amount1 -= 1; // Just subtracting 1 so protocol remains on the winning side
                _verifyAmountLimits(v_.amount1);
            }

            // Convert adjusted fee amounts to normal fee amounts
            // Also explicitly rounding down to be 100% sure that the protocol is on the winning side
            v_.feeAccruedToken0 = (v_.feeAccruedToken0Adjusted * c_.token0DenominatorPrecision * ROUNDING_FACTOR_MINUS_ONE) / (c_.token0NumeratorPrecision * ROUNDING_FACTOR);
            if (v_.feeAccruedToken0 > 0) v_.feeAccruedToken0 -= 1; // Just subtracting 1 so protocol remains on the winning side

            v_.feeAccruedToken1 = (v_.feeAccruedToken1Adjusted * c_.token1DenominatorPrecision * ROUNDING_FACTOR_MINUS_ONE) / (c_.token1NumeratorPrecision * ROUNDING_FACTOR);
            if (v_.feeAccruedToken1 > 0) v_.feeAccruedToken1 -= 1; // Just subtracting 1 so protocol remains on the winning side

            // Verify amounts are not less than minimums
            if (v_.amount0 < params_.amount0Min || v_.amount1 < params_.amount1Min) {
                revert FluidDexV2D3D4Error(ErrorTypes.UserModule__AmountsLessThanMinimum);
            }

            // Update Pending Transfers for token 0
            PT.addPendingBorrow(msg.sender, params_.dexKey.token0, SafeCast.toInt256(v_.amount0)); // When user adds liquidity, he/she is borrowing tokens from the protocol, hence a positive pending borrow 
            PT.addPendingSupply(msg.sender, params_.dexKey.token0, -SafeCast.toInt256(v_.feeAccruedToken0)); // when fee was accrued during swap we made it +ve supply, hence now we make it -ve.

            // Update Pending Transfers for token 1
            PT.addPendingBorrow(msg.sender, params_.dexKey.token1, SafeCast.toInt256(v_.amount1)); // When user adds liquidity, he/she is borrowing tokens from the protocol, hence a positive pending borrow 
            PT.addPendingSupply(msg.sender, params_.dexKey.token1, -SafeCast.toInt256(v_.feeAccruedToken1)); // when fee was accrued during swap we made it +ve supply, hence now we make it -ve.

            emit LogBorrow(
                dexType_, 
                dexId_,
                msg.sender, 
                params_.tickLower, 
                params_.tickUpper, 
                params_.positionSalt, 
                v_.amount0, 
                v_.amount1,
                v_.feeAccruedToken0, 
                v_.feeAccruedToken1, 
                v_.liquidityIncreaseRaw
            );

            PL.unlock(dexId_);

            return (v_.amount0, v_.amount1, v_.feeAccruedToken0, v_.feeAccruedToken1, v_.liquidityIncreaseRaw);
        }
    }

    /// @notice Pays back debt to reduce or close a concentrated liquidity debt position
    /// @dev Delegatecall only (212012); D4-whitelisted callers only (210003): the same whitelist bit gates borrow,
    ///      payback and initialize, so de-whitelisting an address also blocks its paybacks and, for the Money
    ///      Market, D4 liquidations. Takes the per-pool transient lock (reentrant call: empty revert data).
    ///      Amounts: `amount0` / `amount1` are the debt amounts to pay back (normal units, converted at the BORROW
    ///      exchange price). They are mapped to reserves by the price-independent debt -> reserve quadratic, i.e.
    ///      interpreted at the price their ratio implies; the liquidity to remove is derived from those reserves at
    ///      the CURRENT pool price (`min(L0, L1)` in range, the single in-range leg otherwise) and clamped to the
    ///      position. Consequences: amounts above the position remove everything; (0, 0) removes nothing and only
    ///      credits fees (the fee-collection call); a single leg while the position is in range yields zero
    ///      liquidity and is a fee-only no-op that still emits `LogPayback`; a two-leg figure derived at any
    ///      price other than the pool's closes only part of the position; paying back exactly the amounts
    ///      `borrow` returned, or the rounded-up debt figure, does not necessarily close the position: the liquidity
    ///      was rounded up at borrow and the reserve -> liquidity round trip floors, so a few raw units of margin
    ///      are missing and dust liquidity keeps the position alive; close by over-requesting both legs
    ///      proportionally, the clamp absorbs the excess.
    ///      The returned amounts are rounded UP (raw round-up by 1e-9, then +1), so they can exceed the request by up
    ///      to `amount / 1e9 + 1` per leg; a native-token payback must send, and an ERC20 payback must approve, that
    ///      slack. No input limit is enforced so liquidations cannot get stuck, and there is no "max"
    ///      sentinel: amounts far above the position revert in the quadratic (Panic(0x11) or an empty SafeCast
    ///      revert) or in the conversion.
    ///      Pending transfers recorded under msg.sender, per token: pending borrow `-= amount` (the caller owes the
    ///      dex) and pending supply `-= feeAccrued` (the dex owes the accrued LP fee, paid from its Liquidity supply).
    ///      Emits `LogPayback(dexType, dexId, msg.sender, tickLower, tickUpper, positionSalt, amount0, amount1,
    ///      feeAccruedToken0, feeAccruedToken1, liquidityDecreaseRaw)`.
    ///      Reverts with `FluidDexV2D3D4Error(id)`: 210001 pool not initialized; 210004 invalid range (same rules as
    ///      borrow); 210007 (guard); 210002 a returned amount below its minimum. `FluidLiquidityCalcsError(70001)`
    ///      for a token never listed at Liquidity. Panic(0x11) from the checked per-pool reserve subtraction when
    ///      per-pool accounting is on and the counter is understated. A tick outside +-887272 reverts in
    ///      TickMath (`T()`); a range far below -524287 can revert earlier in the quadratic (Panic(0x12) or a
    ///      Helpers__ id) because its X96 prices round to zero. Empty revert data from the pool lock.
    /// @param params_ PaybackParams containing dexKey, tick range, positionSalt, amounts, and minimums
    /// @return amount0 Debt paid back in token0, normal units, rounded up; recorded as a negative pending borrow
    /// @return amount1 Debt paid back in token1, normal units, rounded up; recorded as a negative pending borrow
    /// @return feeAccruedToken0 LP fee in token0 credited since the last touch, normal units, rounded down;
    ///         recorded as a negative pending supply
    /// @return feeAccruedToken1 LP fee in token1 credited since the last touch, normal units, rounded down;
    ///         recorded as a negative pending supply
    /// @return liquidityDecreaseRaw Raw debt liquidity removed from the position (0 for a fee-only call)
    function payback(PaybackParams calldata params_) external _onlyDelegateCall _onlyWhitelistedUsers 
        returns (uint256, uint256, uint256, uint256, uint256) {
        // NOTE: No overall unchecked in payback because we are not doing amount limit checks
        PaybackVariables memory v_;

        bytes32 dexId_ = keccak256(abi.encode(params_.dexKey));
        PL.lock(dexId_);

        uint256 dexType_ = DEX_TYPE_WITH_VERSION / DEX_TYPE_DIVISOR;

        CalculatedVars memory c_;
        {
            DexVariables memory dexVariables_ = _getDexVariables(dexType_, dexId_);
            uint256 dexVariables2_ = _dexVariables2[dexType_][dexId_];

            if (dexVariables_.sqrtPriceX96 == 0) revert FluidDexV2D3D4Error(ErrorTypes.UserModule__DexNotInitialized);

            // NOTE: no checks in payback so liquidations dont get stuck
            // if (params_.amount0 > 0) _verifyAmountLimits(params_.amount0);
            // if (params_.amount1 > 0) _verifyAmountLimits(params_.amount1);

            c_ = _calculateVars(params_.dexKey.token0, params_.dexKey.token1, dexVariables2_);

            // Convert amounts to raw adjusted amounts using exchange prices
            v_.token0DebtAmountRawAdjusted = (params_.amount0 * LC.EXCHANGE_PRICES_PRECISION * c_.token0NumeratorPrecision) / (c_.token0BorrowExchangePrice * c_.token0DenominatorPrecision);
            v_.token1DebtAmountRawAdjusted = (params_.amount1 * LC.EXCHANGE_PRICES_PRECISION * c_.token1NumeratorPrecision) / (c_.token1BorrowExchangePrice * c_.token1DenominatorPrecision);

            // NOTE: no checks in payback so liquidations dont get stuck
            // if (
            //     (v_.token0DebtAmountRawAdjusted == 0 && params_.amount0 > 0) ||
            //     (v_.token1DebtAmountRawAdjusted == 0 && params_.amount1 > 0)
            // ) {
            //     revert FluidDexV2D3D4Error(ErrorTypes.UserModule__AmountRoundsToZero);
            // }

            v_.sqrtPriceLowerX96 = TM.getSqrtRatioAtTick(params_.tickLower);
            v_.sqrtPriceUpperX96 = TM.getSqrtRatioAtTick(params_.tickUpper);

            v_.geometricMeanPriceX96 = FM.mulDiv(v_.sqrtPriceLowerX96, v_.sqrtPriceUpperX96, Q96);
            v_.priceLowerX96 = FM.mulDiv(v_.sqrtPriceLowerX96, v_.sqrtPriceLowerX96, Q96);
            v_.priceUpperX96 = FM.mulDiv(v_.sqrtPriceUpperX96, v_.sqrtPriceUpperX96, Q96);

            (v_.token0ReserveAmountRawAdjusted, v_.token1ReserveAmountRawAdjusted) = _getReservesFromDebtAmounts(
                v_.geometricMeanPriceX96,
                v_.priceUpperX96,
                v_.priceLowerX96,
                v_.token0DebtAmountRawAdjusted,
                v_.token1DebtAmountRawAdjusted
            );

            // NOTE: no checks in payback so liquidations dont get stuck
            // _verifyReserveAndDebtLimits(v_.token0ReserveAmountRawAdjusted, v_.token0DebtAmountRawAdjusted);
            // _verifyReserveAndDebtLimits(v_.token1ReserveAmountRawAdjusted, v_.token1DebtAmountRawAdjusted);

            // no matter the user is adding/removing liquidity, the fee is being collected
            (
                v_.token0ReserveAmountRawAdjusted,
                v_.token1ReserveAmountRawAdjusted,
                v_.feeAccruedToken0Adjusted,
                v_.feeAccruedToken1Adjusted,
                v_.liquidityDecreaseRaw
            ) = _removeLiquidity(RemoveLiquidityInternalParams({
                dexKey: params_.dexKey,
                dexVariables: dexVariables_,
                dexVariables2: dexVariables2_,
                tickLower: params_.tickLower,
                tickUpper: params_.tickUpper,
                sqrtPriceLowerX96: v_.sqrtPriceLowerX96,
                sqrtPriceUpperX96: v_.sqrtPriceUpperX96,
                positionSalt: params_.positionSalt,
                amount0DesiredRaw: v_.token0ReserveAmountRawAdjusted,
                amount1DesiredRaw: v_.token1ReserveAmountRawAdjusted,
                dexType: dexType_,
                dexId: dexId_
            }));
        }

        (v_.token0DebtAmountRawAdjusted, v_.token1DebtAmountRawAdjusted) = _getDebtAmountsFromReserves(
            v_.geometricMeanPriceX96,
            v_.priceUpperX96,
            v_.priceLowerX96,
            v_.token0ReserveAmountRawAdjusted,
            v_.token1ReserveAmountRawAdjusted
        );

        // NOTE: no checks in payback so liquidations dont get stuck
        // _verifyReserveAndDebtLimits(v_.token0ReserveAmountRawAdjusted, v_.token0DebtAmountRawAdjusted);
        // _verifyReserveAndDebtLimits(v_.token1ReserveAmountRawAdjusted, v_.token1DebtAmountRawAdjusted);

        // Convert raw adjusted amounts to normal amounts
        // Also explicitly rounding up to be 100% sure that the protocol is on the winning side (user pays more when paying back)
        v_.amount0 = (v_.token0DebtAmountRawAdjusted * c_.token0DenominatorPrecision * c_.token0BorrowExchangePrice * ROUNDING_FACTOR_PLUS_ONE) / 
            (c_.token0NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION * ROUNDING_FACTOR);
        if (v_.amount0 > 0) {
            v_.amount0 += 1; // Just adding 1 so protocol remains on the winning side
            // _verifyAmountLimits(v_.amount0); // NOTE: no checks in payback so liquidations dont get stuck   
        }

        v_.amount1 = (v_.token1DebtAmountRawAdjusted * c_.token1DenominatorPrecision * c_.token1BorrowExchangePrice * ROUNDING_FACTOR_PLUS_ONE) / 
            (c_.token1NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION * ROUNDING_FACTOR);
        if (v_.amount1 > 0) {
            v_.amount1 += 1; // Just adding 1 so protocol remains on the winning side
            // _verifyAmountLimits(v_.amount1); // NOTE: no checks in payback so liquidations dont get stuck
        }

        // Convert adjusted fee amounts to normal fee amounts
        // Also explicitly rounding down to be 100% sure that the protocol is on the winning side
        v_.feeAccruedToken0 = (v_.feeAccruedToken0Adjusted * c_.token0DenominatorPrecision * ROUNDING_FACTOR_MINUS_ONE) / (c_.token0NumeratorPrecision * ROUNDING_FACTOR);
        if (v_.feeAccruedToken0 > 0) v_.feeAccruedToken0 -= 1; // Just subtracting 1 so protocol remains on the winning side

        v_.feeAccruedToken1 = (v_.feeAccruedToken1Adjusted * c_.token1DenominatorPrecision * ROUNDING_FACTOR_MINUS_ONE) / (c_.token1NumeratorPrecision * ROUNDING_FACTOR);
        if (v_.feeAccruedToken1 > 0) v_.feeAccruedToken1 -= 1; // Just subtracting 1 so protocol remains on the winning side

        // Verify amounts are not less than minimums
        if (v_.amount0 < params_.amount0Min || v_.amount1 < params_.amount1Min) {
            revert FluidDexV2D3D4Error(ErrorTypes.UserModule__AmountsLessThanMinimum);
        }

        // Update Pending Transfers for token 0
        PT.addPendingBorrow(msg.sender, params_.dexKey.token0, -SafeCast.toInt256(v_.amount0)); // When user removes liquidity, he/she is paying back tokens to the protocol, hence a negative pending borrow 
        PT.addPendingSupply(msg.sender, params_.dexKey.token0, -SafeCast.toInt256(v_.feeAccruedToken0)); // when fee was accrued during swap we made it +ve supply, hence now we make it -ve

        // Update Pending Transfers for token 1
        PT.addPendingBorrow(msg.sender, params_.dexKey.token1, -SafeCast.toInt256(v_.amount1)); // When user removes liquidity, he/she is paying back tokens to the protocol, hence a negative pending borrow 
        PT.addPendingSupply(msg.sender, params_.dexKey.token1, -SafeCast.toInt256(v_.feeAccruedToken1)); // when fee was accrued during swap we made it +ve supply, hence now we make it -ve

        emit LogPayback(
            dexType_, 
            dexId_,
            msg.sender, 
            params_.tickLower, 
            params_.tickUpper, 
            params_.positionSalt, 
            v_.amount0, 
            v_.amount1, 
            v_.feeAccruedToken0, 
            v_.feeAccruedToken1, 
            v_.liquidityDecreaseRaw
        );

        PL.unlock(dexId_);

        return (v_.amount0, v_.amount1, v_.feeAccruedToken0, v_.feeAccruedToken1, v_.liquidityDecreaseRaw);
    }

    /// @notice Initializes a new D4 pool with initial price
    /// @dev Delegatecall only (212012); only a D4-whitelisted caller (210003). No pool lock.
    ///      `sqrtPriceX96` is in the pool's raw-adjusted price space: `sqrt(rawAdjusted1 / rawAdjusted0) * 2^96` with
    ///      `rawAdjusted = amount * 1e12 * 10^(9 - decimals) / borrowExchangePrice`, i.e. both tokens normalised to 9
    ///      decimals and divided by their live Liquidity borrow exchange prices. A Uniswap-convention price is off by
    ///      the decimals and exchange-price factors, and the fair raw price of a pair drifts with the differential of
    ///      the two tokens' borrow rates.
    ///      Validation (`_initialize`): tickSpacing in [1, 500] (210008); token0 < token1 by address (210009; the
    ///      native token sentinel sorts as token1 for nearly every pair); `dexKey.fee` <= 65535 (1e6 base, max
    ///      6.5535 %) or exactly `type(uint24).max` for a dynamic-fee pool, whose LP fee is 0 until the controller
    ///      sets it (212011); sqrtPriceX96 strictly inside (MIN_SQRT_PRICE_X96, MAX_SQRT_PRICE_X96), i.e. ticks
    ///      +-524287 (210010); pool not yet initialized for this dex type (210011); `decimals()` read by external
    ///      call from each non-native token, 6..18 allowed, 15, 16 and 17 rejected (210012). Nothing checks that the
    ///      tokens are listed at Liquidity (a pool with an unlisted token initializes, but every borrow, payback and
    ///      swap on it reverts with `FluidLiquidityCalcsError(70001)`) or that `dexKey.controller` is usable
    ///      (address(0) makes the controller functions permanently uncallable for the pool).
    ///      Writes `_dexVariables` (tick, sqrt price rounded down into a 64|8 big number, fee growth 0),
    ///      `_dexVariables2` (decimals, static LP fee) and `_dexKey` (which no module reads); emits
    ///      `LogInitialize(dexType, dexId, dexKey, sqrtPriceX96)` with the caller's un-rounded price.
    /// @param params_ InitializeParams containing dexKey and initial sqrtPriceX96
    function initialize(InitializeParams calldata params_) external _onlyDelegateCall _onlyWhitelistedUsers {
        _initialize(InitializeInternalParams({
            dexKey: params_.dexKey,
            sqrtPriceX96: params_.sqrtPriceX96,
            dexType: DEX_TYPE_WITH_VERSION / DEX_TYPE_DIVISOR
        }));

        // NOTE: LogInitialize event is emitted in the internal _initialize function
    }
}
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.