Skip to content
Verified contractExactBUSL-1.1

FluidDexV2D3SwapModule

Address0x2d0e4fb14b614e4c6b8b3965d848a3f7f0c4fbe3
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,505
Creation transaction
0x9f5dfb417d…17676a6612

38 files

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

contracts/protocols/dexV2/dexTypes/d3/core/swapModule.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 FluidDexV2D3SwapModule
/// @notice Swap module for D3 (smart collateral) DEX pools
/// @dev Implements concentrated liquidity swaps in raw-adjusted units priced at the tokens' Liquidity SUPPLY exchange
///      prices: every normal amount is converted with `amount * 1e12 * numeratorPrecision / (supplyExchangePrice *
///      denominatorPrecision)` before the pool math and back afterwards (a token never listed at Liquidity is priced
///      at 1e12). The pool's ticks and `sqrtPriceX96` therefore express ratios of raw-adjusted amounts, not market
///      prices, and a range drifts against the market at the differential of the two tokens' supply rates.
///      D3 liquidity is smart collateral held in the dex's own Liquidity supply position, so a swap is a pair of
///      pending SUPPLY legs under the swapper (input positive, output negative) and both fee parts stay inside that
///      supply position: the LP part is claimable through fee growth, the protocol part is untracked surplus.
///      Stateless implementation delegatecalled by the `FluidDexV2` proxy via `operate(3, 1, data)`; callable by
///      anyone inside an active operation. Model, accepted behaviours and open items:
///      docs/internal-dev/dexv2-d3d4-notes.md.
contract FluidDexV2D3SwapModule is CommonImportD3Other {
    /// @dev Dex type 3, 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 D3 modules.
    uint256 internal constant DEX_TYPE_WITH_VERSION = 30_000;

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

    /// @notice Executes a swap with exact input amount
    /// @dev Delegatecall only (212012); anyone may call it inside an active operation. Takes the per-pool transient
    ///      lock keyed by `keccak256(abi.encode(dexKey))` (shared with the D4 pool of the same key; a reentrant call
    ///      reverts with empty revert data) and releases it at the end. Nothing is transferred by this call.
    ///      Pending transfers recorded under msg.sender (to be settled through the base before the operation ends):
    ///      pending supply of the input token `+= amountIn` (the swapper owes it to the dex) and pending supply of
    ///      the output token `-= amountOut_` (the dex owes it to the swapper). The fees are not a separate leg: they
    ///      remain in the dex's Liquidity supply position.
    ///      Fee model: the protocol fee of the direction (1e6 base) is cut from each step's output first, then the LP
    ///      fee (static, controller-fetched or version-1 dynamic, 1e6 base) from the remainder; a protocol cut
    ///      (whole percent) moves part of the LP fee to the protocol. LP fee growth is credited in adjusted units
    ///      (`lpFeeRaw * exchangePrice / 1e12` per raw liquidity) only while active liquidity is non-zero, so an LP's
    ///      claim is a nominal amount fixed at swap time that earns no Liquidity interest until collected.
    ///      Emits `LogSwapIn(dexType, dexId, msg.sender, swap0To1, amountIn, amountOut_, protocolFeeAccrued_,
    ///      lpFeeAccrued_)`.
    ///      Reverts with `FluidDexV2D3D4Error(id)`: 211001 pool not initialized; 212004 `amountIn` or `amountOut_`
    ///      outside [1e4, 2^128); 212005 raw-adjusted input or output outside [1e4, 2^86); 211012 `controllerData`
    ///      longer than 10000 bytes on a pool with the fetch flag set (not checked when the controller itself swaps);
    ///      211004 the swap needs liquidity beyond the last initialized tick in its direction (the next tick reaches
    ///      +-524287; there is no partial fill); 212006 relative sqrt price move outside [5e-10, 0.2], i.e. at
    ///      most 20 % and at least 5e-10 (a minimum trade size on deep pools), measured from the start price
    ///      or, for a swap that started in an empty region, from the price at which liquidity was first found (a
    ///      swap that starts inside liquidity has every empty region it crosses counted); 211008 fee version 1
    ///      and the final price is at least 2x the zero-impact anchor (1->0 swaps only; also hit, whatever the size,
    ///      by a swap that starts in an empty region and finds liquidity at >= 2x the start price); 211010
    ///      per-pool reserve counter above 2^128; 211002 `amountOut_ < amountOutMin`; guards not expected to fire:
    ///      211005, 212009, 211007, 211009, 211011. Other reverts: 212012 direct call; empty revert data from the
    ///      pool lock; Panic(0x11) from the checked per-pool reserve subtraction when per-pool accounting is on and
    ///      the counter is understated; a revert of `abi.decode` when the pool controller returns 64 bytes
    ///      whose second word is not a valid bool.
    /// @param params_ SwapInParams containing dexKey, swap direction, amountIn, amountOutMin, and controllerData
    /// @return amountOut_ Net output amount in normal units after both fees, rounded down (raw round-down, then -1);
    ///         recorded as a negative pending supply of the output token
    /// @return protocolFeeAccrued_ Protocol fee cut from the output, in normal units of the output token
    /// @return lpFeeAccrued_ LP fee cut from the output, in normal units of the output token
    function swapIn(SwapInParams calldata params_) external _onlyDelegateCall returns (uint256 amountOut_, uint256 protocolFeeAccrued_, uint256 lpFeeAccrued_) {
        unchecked {
            bytes32 dexId_ = keccak256(abi.encode(params_.dexKey));
            PL.lock(dexId_);

            uint256 dexType_ = DEX_TYPE_WITH_VERSION / DEX_TYPE_DIVISOR;

            CalculatedVars memory c_;
            uint256 amountOutRawAdjusted_;
            uint256 protocolFeeAccruedRawAdjusted_;
            uint256 lpFeeAccruedRawAdjusted_;

            {
                uint256 dexVariables_ = _dexVariables[dexType_][dexId_];
                uint256 dexVariables2_ = _dexVariables2[dexType_][dexId_];

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

                _verifyAmountLimits(params_.amountIn);

                c_ = _calculateVars(params_.dexKey.token0, params_.dexKey.token1, dexVariables2_);
                
                {
                    uint256 amountInRawAdjusted_;
                    if (params_.swap0To1) {
                        // NOTE: This calculation is inside unchecked but it wont overflow because params_.amountIn is limited to X128
                        amountInRawAdjusted_ = (params_.amountIn * LC.EXCHANGE_PRICES_PRECISION * c_.token0NumeratorPrecision) / (c_.token0SupplyExchangePrice * c_.token0DenominatorPrecision);
                    } else {
                        // NOTE: This calculation is inside unchecked but it wont overflow because params_.amountIn is limited to X128
                        amountInRawAdjusted_ = (params_.amountIn * LC.EXCHANGE_PRICES_PRECISION * c_.token1NumeratorPrecision) / (c_.token1SupplyExchangePrice * c_.token1DenominatorPrecision);
                    }

                    // Explicit Rounding Down of amountInRawAdjusted to be 100% sure that the protocol is on the winning side
                    amountInRawAdjusted_ = (amountInRawAdjusted_ * ROUNDING_FACTOR_MINUS_ONE) / ROUNDING_FACTOR; 
                    if (amountInRawAdjusted_ > 0) amountInRawAdjusted_ -= 1;

                    _verifyAdjustedAmountLimits(amountInRawAdjusted_);

                    (amountOutRawAdjusted_, protocolFeeAccruedRawAdjusted_, lpFeeAccruedRawAdjusted_) = _swapIn(SwapInInternalParams({
                        dexKey: params_.dexKey,
                        dexVariables: dexVariables_,
                        dexVariables2: dexVariables2_,
                        swap0To1: params_.swap0To1,
                        amountInRaw: amountInRawAdjusted_,
                        controllerData: params_.controllerData,
                        token0ExchangePrice: c_.token0SupplyExchangePrice,
                        token1ExchangePrice: c_.token1SupplyExchangePrice,
                        dexType: dexType_,
                        dexId: dexId_
                    }));
                }
            }

            // Explicit Rounding Down of amountOutRawAdjusted to be 100% sure that the protocol is on the winning side
            amountOutRawAdjusted_ = (amountOutRawAdjusted_ * ROUNDING_FACTOR_MINUS_ONE) / ROUNDING_FACTOR; 
            if (amountOutRawAdjusted_ > 0) amountOutRawAdjusted_ -= 1;

            _verifyAdjustedAmountLimits(amountOutRawAdjusted_);

            if (params_.swap0To1) {
                // NOTE: This calculation is inside unchecked but it wont overflow because amountOutRawAdjusted_ is limited to X86
                amountOut_ = ((amountOutRawAdjusted_ * c_.token1DenominatorPrecision * c_.token1SupplyExchangePrice) / (c_.token1NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION));
                if (amountOut_ > 0) amountOut_ -= 1; // Just subtracting 1 so protocol remains on the winning side
                _verifyAmountLimits(amountOut_);

                if (amountOut_ < params_.amountOutMin) {
                    revert FluidDexV2D3D4Error(ErrorTypes.SwapModule__AmountOutLessThanMin);
                }

                // NOTE: Fee is cut from tokenOut in swap in
                // NOTE: Inside unchecked but it wont overflow: amountOutRawAdjusted_ (the net output) is limited to X86
                //       and the fees are capped fractions of each step's gross output (protocol fee <= X12 / 1e6,
                //       LP fee <= X16 / 1e6; a step's gross output is itself limited to X86 by 211005 / 212009), so
                //       protocolFeeAccruedRawAdjusted_ is far below X86 and the product below 2^180
                protocolFeeAccrued_ = (protocolFeeAccruedRawAdjusted_ * c_.token1DenominatorPrecision * c_.token1SupplyExchangePrice) / (c_.token1NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION);
                // NOTE: Same bound as above: lpFeeAccruedRawAdjusted_ is far below X86
                lpFeeAccrued_ = (lpFeeAccruedRawAdjusted_ * c_.token1DenominatorPrecision * c_.token1SupplyExchangePrice) / (c_.token1NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION);

                PT.addPendingSupply(msg.sender, params_.dexKey.token0, SafeCast.toInt256(params_.amountIn));
                PT.addPendingSupply(msg.sender, params_.dexKey.token1, -SafeCast.toInt256(amountOut_));
            } else {
                // NOTE: This calculation is inside unchecked but it wont overflow because amountOutRawAdjusted_ is limited to X86
                amountOut_ = ((amountOutRawAdjusted_ * c_.token0DenominatorPrecision * c_.token0SupplyExchangePrice) / (c_.token0NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION));
                if (amountOut_ > 0) amountOut_ -= 1; // Just subtracting 1 so protocol remains on the winning side
                _verifyAmountLimits(amountOut_);

                if (amountOut_ < params_.amountOutMin) {
                    revert FluidDexV2D3D4Error(ErrorTypes.SwapModule__AmountOutLessThanMin);
                }

                // NOTE: Fee is cut from tokenOut in swap in
                // NOTE: Inside unchecked but it wont overflow: amountOutRawAdjusted_ (the net output) is limited to X86
                //       and the fees are capped fractions of each step's gross output (protocol fee <= X12 / 1e6,
                //       LP fee <= X16 / 1e6; a step's gross output is itself limited to X86 by 211005 / 212009), so
                //       protocolFeeAccruedRawAdjusted_ is far below X86 and the product below 2^180
                protocolFeeAccrued_ = (protocolFeeAccruedRawAdjusted_ * c_.token0DenominatorPrecision * c_.token0SupplyExchangePrice) / (c_.token0NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION);
                // NOTE: Same bound as above: lpFeeAccruedRawAdjusted_ is far below X86
                lpFeeAccrued_ = (lpFeeAccruedRawAdjusted_ * c_.token0DenominatorPrecision * c_.token0SupplyExchangePrice) / (c_.token0NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION);

                PT.addPendingSupply(msg.sender, params_.dexKey.token1, SafeCast.toInt256(params_.amountIn));
                PT.addPendingSupply(msg.sender, params_.dexKey.token0, -SafeCast.toInt256(amountOut_));
            }

            emit LogSwapIn(dexType_, dexId_, msg.sender, params_.swap0To1, params_.amountIn, amountOut_, protocolFeeAccrued_, lpFeeAccrued_);

            PL.unlock(dexId_);
        }
    }

    /// @notice Executes a swap with exact output amount
    /// @dev Delegatecall only (212012); anyone may call it inside an active operation. Takes the per-pool transient
    ///      lock keyed by `keccak256(abi.encode(dexKey))` (shared with the D4 pool of the same key; a reentrant call
    ///      reverts with empty revert data) and releases it at the end. Nothing is transferred by this call.
    ///      Pending transfers recorded under msg.sender (to be settled through the base before the operation ends):
    ///      pending supply of the input token `+= amountIn_` (fees included, the swapper owes it to the dex) and
    ///      pending supply of the output token `-= amountOut` (exactly the requested amount, the dex owes it to the
    ///      swapper). The fees are not a separate leg: they remain in the dex's Liquidity supply position.
    ///      Fee model: each step's input is inflated by the LP fee (static, controller-fetched or version-1 dynamic,
    ///      1e6 base) first and then by the protocol fee of the direction (1e6 base); a protocol cut (whole percent)
    ///      moves part of the LP fee to the protocol. `amountIn_` includes both fees. LP fee growth is credited in
    ///      adjusted units (`lpFeeRaw * exchangePrice / 1e12` per raw liquidity) only while active liquidity is
    ///      non-zero, so an LP's claim is a nominal amount fixed at swap time.
    ///      Emits `LogSwapOut(dexType, dexId, msg.sender, swap0To1, amountIn_, amountOut, protocolFeeAccrued_,
    ///      lpFeeAccrued_)`.
    ///      Reverts with `FluidDexV2D3D4Error(id)`: 211001 pool not initialized; 212004 `amountOut` or `amountIn_`
    ///      outside [1e4, 2^128); 212005 raw-adjusted output or input outside [1e4, 2^86); 211012 `controllerData`
    ///      longer than 10000 bytes on a pool with the fetch flag set (not checked when the controller itself swaps);
    ///      211004 the swap needs liquidity beyond the last initialized tick in its direction (the next tick reaches
    ///      +-524287; there is no partial fill); 212006 relative sqrt price move outside [5e-10, 0.2], i.e. at
    ///      most 20 % and at least 5e-10 (a minimum trade size on deep pools), measured from the start price
    ///      or, for a swap that started in an empty region, from the price at which liquidity was first found (a
    ///      swap that starts inside liquidity has every empty region it crosses counted); 211008 fee version 1
    ///      and the final price is at least 2x the zero-impact anchor (1->0 swaps only; also hit, whatever the size,
    ///      by a swap that starts in an empty region and finds liquidity at >= 2x the start price); 211010
    ///      per-pool reserve counter above 2^128; 211003 `amountIn_ > amountInMax`; guards not expected to fire:
    ///      211006, 212010, 211007, 211009, 211011. Other reverts: 212012 direct call; empty revert data from the
    ///      pool lock; Panic(0x11) from the checked per-pool reserve subtraction when per-pool accounting is on and
    ///      the counter is understated; a revert of `abi.decode` when the pool controller returns 64 bytes
    ///      whose second word is not a valid bool.
    /// @param params_ SwapOutParams containing dexKey, swap direction, amountOut, amountInMax, and controllerData
    /// @return amountIn_ Input amount in normal units including both fees, rounded up (raw round-up, then +1);
    ///         recorded as a positive pending supply of the input token
    /// @return protocolFeeAccrued_ Protocol fee contained in `amountIn_`, in normal units of the input token
    /// @return lpFeeAccrued_ LP fee contained in `amountIn_`, in normal units of the input token
    function swapOut(SwapOutParams calldata params_) external _onlyDelegateCall returns (uint256 amountIn_, uint256 protocolFeeAccrued_, uint256 lpFeeAccrued_) {
        unchecked {
            bytes32 dexId_ = keccak256(abi.encode(params_.dexKey));
            PL.lock(dexId_);

            uint256 dexType_ = DEX_TYPE_WITH_VERSION / DEX_TYPE_DIVISOR;

            CalculatedVars memory c_;
            uint256 amountInRawAdjusted_;
            uint256 protocolFeeAccruedRawAdjusted_;
            uint256 lpFeeAccruedRawAdjusted_;

            {
                uint256 dexVariables_ = _dexVariables[dexType_][dexId_];
                uint256 dexVariables2_ = _dexVariables2[dexType_][dexId_];

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

                _verifyAmountLimits(params_.amountOut);

                c_ = _calculateVars(params_.dexKey.token0, params_.dexKey.token1, dexVariables2_);
                
                {
                    uint256 amountOutRawAdjusted_;
                    if (params_.swap0To1) {
                        // NOTE: This calculation is inside unchecked but it wont overflow because params_.amountOut is limited to X128
                        amountOutRawAdjusted_ = (params_.amountOut * LC.EXCHANGE_PRICES_PRECISION * c_.token1NumeratorPrecision) / (c_.token1SupplyExchangePrice * c_.token1DenominatorPrecision);
                    } else {
                        // NOTE: This calculation is inside unchecked but it wont overflow because params_.amountOut is limited to X128
                        amountOutRawAdjusted_ = (params_.amountOut * LC.EXCHANGE_PRICES_PRECISION * c_.token0NumeratorPrecision) / (c_.token0SupplyExchangePrice * c_.token0DenominatorPrecision);
                    }

                    // Explicit Rounding Up of amountOutRawAdjusted to be 100% sure that the protocol is on the winning side
                    amountOutRawAdjusted_ = ((amountOutRawAdjusted_ * ROUNDING_FACTOR_PLUS_ONE) / ROUNDING_FACTOR) + 1;

                    _verifyAdjustedAmountLimits(amountOutRawAdjusted_);

                    (amountInRawAdjusted_, protocolFeeAccruedRawAdjusted_, lpFeeAccruedRawAdjusted_) = _swapOut(SwapOutInternalParams({
                        dexKey: params_.dexKey,
                        dexVariables: dexVariables_,
                        dexVariables2: dexVariables2_,
                        swap0To1: params_.swap0To1,
                        amountOutRaw: amountOutRawAdjusted_,
                        controllerData: params_.controllerData,
                        token0ExchangePrice: c_.token0SupplyExchangePrice,
                        token1ExchangePrice: c_.token1SupplyExchangePrice,
                        dexType: dexType_,
                        dexId: dexId_
                    }));
                }
            }

            // Explicit Rounding Up of amountInRawAdjusted to be 100% sure that the protocol is on the winning side
            amountInRawAdjusted_ = ((amountInRawAdjusted_ * ROUNDING_FACTOR_PLUS_ONE) / ROUNDING_FACTOR) + 1;

            _verifyAdjustedAmountLimits(amountInRawAdjusted_);

            if (params_.swap0To1) {
                // NOTE: This calculation is inside unchecked but it wont overflow because amountInRawAdjusted_ is limited to X86
                amountIn_ = ((amountInRawAdjusted_ * c_.token0DenominatorPrecision * c_.token0SupplyExchangePrice) / (c_.token0NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION)) + 1; // Just adding 1 so protocol remains on the winning side
                _verifyAmountLimits(amountIn_);

                if (amountIn_ > params_.amountInMax) {
                    revert FluidDexV2D3D4Error(ErrorTypes.SwapModule__AmountInMoreThanMax);
                }

                // NOTE: Fee is cut from tokenIn in swap out
                // NOTE: This calculation is inside unchecked but it wont overflow because amountInRawAdjusted_ is limited to X86, hence protocolFeeAccruedRawAdjusted_ will be surely less than that
                protocolFeeAccrued_ = (protocolFeeAccruedRawAdjusted_ * c_.token0DenominatorPrecision * c_.token0SupplyExchangePrice) / (c_.token0NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION);
                // NOTE: This calculation is inside unchecked but it wont overflow because amountInRawAdjusted_ is limited to X86, hence lpFeeAccruedRawAdjusted_ will be surely less than that
                lpFeeAccrued_ = (lpFeeAccruedRawAdjusted_ * c_.token0DenominatorPrecision * c_.token0SupplyExchangePrice) / (c_.token0NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION);

                PT.addPendingSupply(msg.sender, params_.dexKey.token0, SafeCast.toInt256(amountIn_));
                PT.addPendingSupply(msg.sender, params_.dexKey.token1, -SafeCast.toInt256(params_.amountOut));
            } else {
                // NOTE: This calculation is inside unchecked but it wont overflow because amountInRawAdjusted_ is limited to X86
                amountIn_ = ((amountInRawAdjusted_ * c_.token1DenominatorPrecision * c_.token1SupplyExchangePrice) / (c_.token1NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION)) + 1; // Just adding 1 so protocol remains on the winning side
                _verifyAmountLimits(amountIn_);
                
                if (amountIn_ > params_.amountInMax) {
                    revert FluidDexV2D3D4Error(ErrorTypes.SwapModule__AmountInMoreThanMax);
                }

                // NOTE: Fee is cut from tokenIn in swap out
                // NOTE: This calculation is inside unchecked but it wont overflow because amountInRawAdjusted_ is limited to X86, hence protocolFeeAccruedRawAdjusted_ will be surely less than that
                protocolFeeAccrued_ = (protocolFeeAccruedRawAdjusted_ * c_.token1DenominatorPrecision * c_.token1SupplyExchangePrice) / (c_.token1NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION);
                // NOTE: This calculation is inside unchecked but it wont overflow because amountInRawAdjusted_ is limited to X86, hence lpFeeAccruedRawAdjusted_ will be surely less than that
                lpFeeAccrued_ = (lpFeeAccruedRawAdjusted_ * c_.token1DenominatorPrecision * c_.token1SupplyExchangePrice) / (c_.token1NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION);

                PT.addPendingSupply(msg.sender, params_.dexKey.token1, SafeCast.toInt256(amountIn_));
                PT.addPendingSupply(msg.sender, params_.dexKey.token0, -SafeCast.toInt256(params_.amountOut));
            }

            emit LogSwapOut(dexType_, dexId_, msg.sender, params_.swap0To1, amountIn_, params_.amountOut, protocolFeeAccrued_, lpFeeAccrued_);

            PL.unlock(dexId_);
        }
    }
}
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.