Verified contractExactBUSL-1.1
FluidDexV2D4SwapModule
Address0x2cd0a02e4ec14a2328a72d580d29b5007ca98444
- 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,525
- Creation transaction
- 0x6e46a20a59…1c1678904e
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/swapModule.solmain26.48 KB
- @uniswap/v3-core/contracts/libraries/FixedPoint96.sol380 B
- @uniswap/v3-core/contracts/libraries/FullMath.sol5.52 KB
- @uniswap/v3-core/contracts/libraries/SafeCast.sol1.05 KB
- @uniswap/v3-core/contracts/libraries/SqrtPriceMath.sol11.14 KB
- @uniswap/v3-core/contracts/libraries/UnsafeMath.sol660 B
- contracts/infiniteProxy/interfaces/iProxy.sol772 B
- contracts/libraries/bigMathMinified.sol9.82 KB
- contracts/libraries/dexV2D3D4CommonSlotsLink.sol9.48 KB
- contracts/libraries/dexV2PoolLock.sol1.7 KB
- contracts/libraries/errorTypes.sol1.67 KB
- contracts/libraries/liquidityCalcs.sol43.04 KB
- contracts/libraries/liquiditySlotsLink.sol6.83 KB
- contracts/libraries/pendingTransfers.sol9.77 KB
- contracts/libraries/safeCast.sol493 B
- contracts/liquidity/adminModule/structs.sol6.62 KB
- contracts/liquidity/interfaces/iLiquidity.sol15.42 KB
- contracts/protocols/dexV2/dexTypes/common/d3d4common/adminModuleInternals.sol6.74 KB
- contracts/protocols/dexV2/dexTypes/common/d3d4common/commonImport.sol171 B
- contracts/protocols/dexV2/dexTypes/common/d3d4common/constantVariables.sol11.5 KB
- contracts/protocols/dexV2/dexTypes/common/d3d4common/controllerModuleInternals.sol8.95 KB
- contracts/protocols/dexV2/dexTypes/common/d3d4common/error.sol136 B
- contracts/protocols/dexV2/dexTypes/common/d3d4common/errorTypes.sol15.47 KB
- contracts/protocols/dexV2/dexTypes/common/d3d4common/events.sol10.74 KB
- contracts/protocols/dexV2/dexTypes/common/d3d4common/helpers.sol53.21 KB
- contracts/protocols/dexV2/dexTypes/common/d3d4common/interfaces.sol4.97 KB
- contracts/protocols/dexV2/dexTypes/common/d3d4common/structs.sol13.29 KB
- contracts/protocols/dexV2/dexTypes/common/d3d4common/swapModuleInternals.sol61.17 KB
- contracts/protocols/dexV2/dexTypes/common/d3d4common/userModuleInternals.sol41.9 KB
- contracts/protocols/dexV2/dexTypes/common/d3d4common/variables.sol16.64 KB
- contracts/protocols/dexV2/dexTypes/d4/other/commonImport.sol139 B
- contracts/protocols/dexV2/dexTypes/d4/other/helpers.sol17.4 KB
- contracts/protocols/dexV2/dexTypes/d4/other/structs.sol5.48 KB
- contracts/protocols/dexV2/dexTypes/d4/other/variables.sol1.7 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.77 KB
- lib/v3-core/contracts/libraries/TickMath.sol9.42 KB
- lib/v3-periphery/contracts/libraries/LiquidityAmounts.sol6.98 KB
- solmate/src/utils/FixedPointMathLib.sol10.05 KB
contracts/protocols/dexV2/dexTypes/d4/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 FluidDexV2D4SwapModule
/// @notice Swap module for D4 (smart debt) DEX pools
/// @dev Implements concentrated liquidity swaps in raw-adjusted units priced at the tokens' Liquidity BORROW exchange
/// prices: every normal amount is converted with `amount * 1e12 * numeratorPrecision / (borrowExchangePrice *
/// denominatorPrecision)` before the pool math and back afterwards (a token never listed at Liquidity makes
/// every call revert with `FluidLiquidityCalcsError(70001)`). 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' borrow rates. D4 liquidity is smart debt: a swap that sends token X
/// into the pool pays back X debt and creates Y debt for the debt positions, so the swapper's input is a
/// negative pending BORROW leg (a payback) and the output a positive one.
/// Fee routing: the output plus both fees is borrowed from the debt pool and the fees are supplied to the dex's
/// own Liquidity SUPPLY position (positive pending supply leg); debt positions later collect their LP share by
/// withdrawing that supply (negative pending supply in `borrow` / `payback`), the protocol part stays there as
/// untracked surplus. A D4 pool therefore needs the dex to be a Liquidity supply user of both tokens, not only
/// a borrow user (deployment requirement, see the base notes).
/// Stateless implementation delegatecalled by the `FluidDexV2` proxy via `operate(4, 1, data)`; callable by
/// anyone inside an active operation. Model, accepted behaviours and open items:
/// docs/internal-dev/dexv2-d3d4-notes.md.
contract FluidDexV2D4SwapModule 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 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 D3 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 borrow of the input token `-= amountIn` (a payback: the swapper owes it to the dex); pending
/// borrow of the output token `+= amountOut_ + protocolFeeAccrued_ + lpFeeAccrued_` (borrowed from the
/// debt pool); pending supply of the output token `+= protocolFeeAccrued_ + lpFeeAccrued_` (the fee is
/// supplied to the dex's Liquidity supply position). Net to the swapper: `amountOut_` of the output token.
/// `lpFeeAccrued_` is floored to token units while the LP fee growth is credited at 9-decimal adjusted
/// precision, so for a token with fewer than 9 decimals the sum of LP claims can exceed the fee supplied by
/// less than one token unit per swap.
/// 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; `FluidLiquidityCalcsError(70001)` for a token never listed at
/// Liquidity.
/// @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, together with the fees, as a positive pending borrow 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_.token0BorrowExchangePrice * 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_.token1BorrowExchangePrice * 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_.token0BorrowExchangePrice,
token1ExchangePrice: c_.token1BorrowExchangePrice,
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_.token1BorrowExchangePrice) / (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_.token1BorrowExchangePrice) / (c_.token1NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION);
// NOTE: Same bound as above: lpFeeAccruedRawAdjusted_ is far below X86
lpFeeAccrued_ = (lpFeeAccruedRawAdjusted_ * c_.token1DenominatorPrecision * c_.token1BorrowExchangePrice) / (c_.token1NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION);
// Update Pending Transfers for token in
PT.addPendingBorrow(msg.sender, params_.dexKey.token0, -SafeCast.toInt256(params_.amountIn));
// Update Pending Transfers for token out
PT.addPendingBorrow(msg.sender, params_.dexKey.token1, SafeCast.toInt256(amountOut_ + protocolFeeAccrued_ + lpFeeAccrued_)); // amount out is borrowed with fee
PT.addPendingSupply(msg.sender, params_.dexKey.token1, SafeCast.toInt256(protocolFeeAccrued_ + lpFeeAccrued_)); // Fee gets supplied to liquidity
} else {
// NOTE: This calculation is inside unchecked but it wont overflow because amountOutRawAdjusted_ is limited to X86
amountOut_ = ((amountOutRawAdjusted_ * c_.token0DenominatorPrecision * c_.token0BorrowExchangePrice) / (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_.token0BorrowExchangePrice) / (c_.token0NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION);
// NOTE: Same bound as above: lpFeeAccruedRawAdjusted_ is far below X86
lpFeeAccrued_ = (lpFeeAccruedRawAdjusted_ * c_.token0DenominatorPrecision * c_.token0BorrowExchangePrice) / (c_.token0NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION);
// Update Pending Transfers for token in
PT.addPendingBorrow(msg.sender, params_.dexKey.token1, -SafeCast.toInt256(params_.amountIn));
// Update Pending Transfers for token out
PT.addPendingBorrow(msg.sender, params_.dexKey.token0, SafeCast.toInt256(amountOut_ + protocolFeeAccrued_ + lpFeeAccrued_)); // amount out is borrowed with fee
PT.addPendingSupply(msg.sender, params_.dexKey.token0, SafeCast.toInt256(protocolFeeAccrued_ + lpFeeAccrued_)); // Fee gets supplied to liquidity
}
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 D3 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 borrow of the input token `-= amountIn_ - protocolFeeAccrued_ - lpFeeAccrued_` (the payback part,
/// the swapper owes it to the dex); pending supply of the input token `+= protocolFeeAccrued_ +
/// lpFeeAccrued_` (the fee is supplied to the dex's Liquidity supply position, also owed by the swapper);
/// pending borrow of the output token `+= amountOut` (exactly the requested amount, borrowed from the debt
/// pool for the swapper). `lpFeeAccrued_` is floored to token units while the LP fee growth is credited at
/// 9-decimal adjusted precision, so for a token with fewer than 9 decimals the sum of LP claims can exceed
/// the fee supplied by less than one token unit per swap.
/// 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; `FluidLiquidityCalcsError(70001)` for a token never listed at
/// Liquidity.
/// @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);
/// its fee part is recorded as a positive pending supply and the rest as a negative pending borrow 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_.token1BorrowExchangePrice * 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_.token0BorrowExchangePrice * 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_.token0BorrowExchangePrice,
token1ExchangePrice: c_.token1BorrowExchangePrice,
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_.token0BorrowExchangePrice) / (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_.token0BorrowExchangePrice) / (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_.token0BorrowExchangePrice) / (c_.token0NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION);
// Update Pending Transfers for token in
PT.addPendingBorrow(msg.sender, params_.dexKey.token0, -SafeCast.toInt256(amountIn_ - protocolFeeAccrued_ - lpFeeAccrued_)); // payback happens without fee
PT.addPendingSupply(msg.sender, params_.dexKey.token0, SafeCast.toInt256(protocolFeeAccrued_ + lpFeeAccrued_)); // fee gets supplied to liquidity
// Update Pending Transfers for token out
PT.addPendingBorrow(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_.token1BorrowExchangePrice) / (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_.token1BorrowExchangePrice) / (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_.token1BorrowExchangePrice) / (c_.token1NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION);
// Update Pending Transfers for token in
PT.addPendingBorrow(msg.sender, params_.dexKey.token1, -SafeCast.toInt256(amountIn_ - protocolFeeAccrued_ - lpFeeAccrued_)); // payback happens without fee
PT.addPendingSupply(msg.sender, params_.dexKey.token1, SafeCast.toInt256(protocolFeeAccrued_ + lpFeeAccrued_)); // fee gets supplied to liquidity
// Update Pending Transfers for token out
PT.addPendingBorrow(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.