Verified contractExactBUSL-1.1
FluidDexV2D3UserModule
Address0x3347a9cbb12d2fa3130425ee4d52e11f8dca301e
- 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,510
- Creation transaction
- 0x243b28dfc0…b3df95a653
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/userModule.solmain26.69 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/d3/other/commonImport.sol139 B
- contracts/protocols/dexV2/dexTypes/d3/other/helpers.sol4 KB
- contracts/protocols/dexV2/dexTypes/d3/other/structs.sol3.83 KB
- contracts/protocols/dexV2/dexTypes/d3/other/variables.sol1.27 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/d3/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 FluidDexV2D3UserModule
/// @notice User module for D3 (smart collateral) DEX positions
/// @dev Handles deposits (supply), withdrawals, and pool initialization for concentrated liquidity positions.
/// A D3 position is smart collateral: the LP's tokens sit in the dex's own Liquidity supply position and the
/// position is a range of raw-adjusted amounts priced at the tokens' Liquidity SUPPLY exchange prices
/// (`rawAdjusted = amount * 1e12 * numeratorPrecision / (supplyExchangePrice * denominatorPrecision)`; a token
/// never listed at Liquidity is priced at 1e12). Ticks and `sqrtPriceX96` live in that raw-adjusted space, so a
/// range drifts against the market at the differential of the two tokens' supply rates.
/// Stateless implementation delegatecalled by the `FluidDexV2` proxy via `operate(3, 2, data)`. `deposit` and
/// `withdraw` are open to anyone inside an active operation; `initialize` needs the D3 whitelist. 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 FluidDexV2D3UserModule 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 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
/// D3 whitelist, which is per dex type, not per pool, and set through the D3 admin module. Used by
/// `initialize` only; `deposit` and `withdraw` are open to anyone.
modifier _onlyWhitelistedUsers() {
if (_whitelistedUsers[DEX_TYPE_WITH_VERSION / DEX_TYPE_DIVISOR][msg.sender] == 0) {
revert FluidDexV2D3D4Error(ErrorTypes.UserModule__UserNotWhitelisted);
}
_;
}
/// @notice Deposits tokens into a concentrated liquidity position (smart collateral)
/// @dev Delegatecall only (212012); anyone may call it inside an active operation, there is no whitelist on D3
/// liquidity provision. 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. Position id = `keccak256(abi.encode(msg.sender, tickLower, tickUpper, positionSalt))`; a deposit
/// into an existing position first credits the LP fees accrued since its last touch.
/// Pending transfers recorded under msg.sender, per token: pending supply `+= amount - feeAccrued`. The leg
/// is signed: when the accrued fee exceeds the amount used it is negative, i.e. the dex owes the depositor
/// the difference (the fee is paid out of the dex's Liquidity supply, where swaps left it).
/// Emits `LogDeposit(dexType, dexId, msg.sender, tickLower, tickUpper, positionSalt, amount0_, amount1_,
/// feeAccruedToken0_, feeAccruedToken1_, liquidityIncreaseRaw_)`.
/// Amounts: inputs are normal token amounts converted to raw-adjusted units at the SUPPLY exchange price.
/// The liquidity is what both desired amounts support at the current price (`min(L0, L1)` in range, the
/// single in-range leg otherwise), rounded down by 1e-9 and -1; the used amounts are recomputed from it,
/// converted to normal units and rounded up by 1e-9 and +1, fees rounded down. An in-range deposit
/// needs both legs: a single-leg request supports zero liquidity and reverts with 212007. The limits
/// [1e4, 2^86) raw / [1e4, 2^128) normal are applied to the inputs AND to the used amounts, so a deposit
/// into an in-range position whose range boundary lies within about `1e4 * 2^96 / (L_add * sqrtPrice)`
/// (relative, sqrt-price space) of the pool price uses a minor leg below the minimum and reverts with
/// 212005 (or 212004 when a 6-decimal minor leg passes the raw check but its normal amount is below 1e4)
/// whatever the inputs; a proportionally larger deposit narrows the band, a different range avoids it.
/// Reverts with `FluidDexV2D3D4Error(id)`: 210001 pool not initialized; 212004 a non-zero input, or a used
/// amount, outside [1e4, 2^128); 210014 a non-zero input rounds to zero raw-adjusted units, or both round to
/// zero; 212005 a raw-adjusted input or used amount outside [1e4, 2^86); 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 used amount below its minimum. A tick outside +-887272 reverts in
/// TickMath (`T()`) before the range check. Empty revert data from the pool lock.
/// @param params_ DepositParams containing dexKey, tick range, positionSalt, amounts, and minimums
/// @return amount0_ Amount of token0 used by the position, normal units, rounded up (basis of the pending leg)
/// @return amount1_ Amount of token1 used by the position, normal units, rounded up (basis of the pending leg)
/// @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, netted against amount0_ in the pending leg
/// @return feeAccruedToken1_ LP fee in token1 credited since the last touch, normal units, rounded down; netted
/// against amount1_ in the pending leg
/// @return liquidityIncreaseRaw_ Raw liquidity added to the position
function deposit(DepositParams calldata params_) external _onlyDelegateCall
returns (uint256 amount0_, uint256 amount1_, uint256 feeAccruedToken0_, uint256 feeAccruedToken1_, uint256 liquidityIncreaseRaw_) {
unchecked {
DepositVariables 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 amounts to raw adjusted amounts
// NOTE: This calculation is inside unchecked but it wont overflow because params_.amount0 is limited to X128
v_.amount0RawAdjusted = (params_.amount0 * LC.EXCHANGE_PRICES_PRECISION * c_.token0NumeratorPrecision) / (c_.token0SupplyExchangePrice * c_.token0DenominatorPrecision);
// NOTE: This calculation is inside unchecked but it wont overflow because params_.amount1 is limited to X128
v_.amount1RawAdjusted = (params_.amount1 * LC.EXCHANGE_PRICES_PRECISION * c_.token1NumeratorPrecision) / (c_.token1SupplyExchangePrice * c_.token1DenominatorPrecision);
if (
(v_.amount0RawAdjusted == 0 && params_.amount0 > 0) ||
(v_.amount1RawAdjusted == 0 && params_.amount1 > 0) ||
(v_.amount0RawAdjusted == 0 && v_.amount1RawAdjusted == 0)
) {
revert FluidDexV2D3D4Error(ErrorTypes.UserModule__AmountRoundsToZero);
}
if (v_.amount0RawAdjusted > 0) _verifyAdjustedAmountLimits(v_.amount0RawAdjusted);
if (v_.amount1RawAdjusted > 0) _verifyAdjustedAmountLimits(v_.amount1RawAdjusted);
// no matter the user is adding/removing liquidity, the fee is being collected
(
v_.amount0RawAdjusted, // actual amount which got used
v_.amount1RawAdjusted, // actual amount which got used
v_.feeAccruedToken0Adjusted,
v_.feeAccruedToken1Adjusted,
liquidityIncreaseRaw_
) = _addLiquidity(AddLiquidityInternalParams({
dexKey: params_.dexKey,
dexVariables: dexVariables_,
dexVariables2: dexVariables2_,
tickLower: params_.tickLower,
tickUpper: params_.tickUpper,
sqrtPriceLowerX96: TM.getSqrtRatioAtTick(params_.tickLower),
sqrtPriceUpperX96: TM.getSqrtRatioAtTick(params_.tickUpper),
positionSalt: params_.positionSalt,
amount0DesiredRaw: v_.amount0RawAdjusted,
amount1DesiredRaw: v_.amount1RawAdjusted,
dexType: dexType_,
dexId: dexId_,
isSmartCollateral: IS_SMART_COLLATERAL
}));
}
if (v_.amount0RawAdjusted > 0) {
_verifyAdjustedAmountLimits(v_.amount0RawAdjusted);
// Convert raw adjusted amount to normal amount
// NOTE: This calculation is inside unchecked but it wont overflow because v_.amount0RawAdjusted is limited to X86
amount0_ = (v_.amount0RawAdjusted * c_.token0DenominatorPrecision * c_.token0SupplyExchangePrice) / (c_.token0NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION);
}
if (v_.amount1RawAdjusted > 0) {
_verifyAdjustedAmountLimits(v_.amount1RawAdjusted);
// Convert raw adjusted amount to normal amount
// NOTE: This calculation is inside unchecked but it wont overflow because v_.amount1RawAdjusted is limited to X86
amount1_ = (v_.amount1RawAdjusted * c_.token1DenominatorPrecision * c_.token1SupplyExchangePrice) / (c_.token1NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION);
}
if (amount0_ > 0) {
// Explicit Rounding Up of amount0 to be 100% sure that the protocol is on the winning side
amount0_ = ((amount0_ * ROUNDING_FACTOR_PLUS_ONE) / ROUNDING_FACTOR) + 1;
_verifyAmountLimits(amount0_);
}
if (amount1_ > 0) {
// Explicit Rounding Up of amount1 to be 100% sure that the protocol is on the winning side
amount1_ = ((amount1_ * ROUNDING_FACTOR_PLUS_ONE) / ROUNDING_FACTOR) + 1;
_verifyAmountLimits(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
feeAccruedToken0_ = (v_.feeAccruedToken0Adjusted * c_.token0DenominatorPrecision * ROUNDING_FACTOR_MINUS_ONE) / (c_.token0NumeratorPrecision * ROUNDING_FACTOR);
if (feeAccruedToken0_ > 0) feeAccruedToken0_ -= 1; // Just subtracting 1 so protocol remains on the winning side
feeAccruedToken1_ = (v_.feeAccruedToken1Adjusted * c_.token1DenominatorPrecision * ROUNDING_FACTOR_MINUS_ONE) / (c_.token1NumeratorPrecision * ROUNDING_FACTOR);
if (feeAccruedToken1_ > 0) feeAccruedToken1_ -= 1; // Just subtracting 1 so protocol remains on the winning side
// Verify amounts are not less than minimums
if (amount0_ < params_.amount0Min || amount1_ < params_.amount1Min) {
revert FluidDexV2D3D4Error(ErrorTypes.UserModule__AmountsLessThanMinimum);
}
// When user adds liquidity, he/she is supplying tokens to the protocol, hence a positive pending supply
// Subtracting fee accrued because user has to pay net less tokens; the leg is signed and becomes a payout
// (negative) when the accrued fee exceeds the amount used
PT.addPendingSupply(msg.sender, params_.dexKey.token0, SafeCast.toInt256(amount0_) - SafeCast.toInt256(feeAccruedToken0_));
PT.addPendingSupply(msg.sender, params_.dexKey.token1, SafeCast.toInt256(amount1_) - SafeCast.toInt256(feeAccruedToken1_));
emit LogDeposit(
dexType_,
dexId_,
msg.sender,
params_.tickLower,
params_.tickUpper,
params_.positionSalt,
amount0_,
amount1_,
feeAccruedToken0_,
feeAccruedToken1_,
liquidityIncreaseRaw_
);
PL.unlock(dexId_);
return (amount0_, amount1_, feeAccruedToken0_, feeAccruedToken1_, liquidityIncreaseRaw_);
}
}
/// @notice Withdraws tokens from a concentrated liquidity position
/// @dev Delegatecall only (212012); anyone inside an active operation (the position is msg.sender's through the
/// position id). Takes the per-pool transient lock (reentrant call: empty revert data).
/// Liquidity to remove: derived from `amount0` / `amount1` (converted at the SUPPLY exchange price, floored)
/// at the stored pool price, `min(L0, L1)` when in range and the single in-range leg otherwise, then clamped
/// to the position. Amounts above the position therefore remove everything; (0, 0), or a single leg while
/// the position is in range, removes nothing and only credits the accrued fees (the fee-collection call).
/// Two consequences of `min(L0, L1)` for callers that size the request from the pool price (the Money
/// Market liquidation): the smaller leg comes back short from the normal->raw round trip (one or two raw
/// units for a token with 9 or more decimals, up to about 2 * 10^(9 - decimals) raw units for fewer) and
/// the liquidity removed shrinks proportionally, down to zero when the pool price sits a few raw units
/// inside a range boundary and that leg is a token with 10 or more decimals (9 once its supply price is
/// above 1e12; for fewer decimals the Money Market's 1-unit substitution over-requests instead and the
/// partial loss peaks at about 67 %); and since the stored sqrt price is rounded down, a position
/// whose tickUpper is the current tick after a 1->0 swap landed exactly on that tick is treated as in range
/// with a token0 leg of ~0 raw, so a request sized on that view removes nothing.
/// The returned amounts are the pool's own rounded-DOWN figures (raw round-down by 1e-9, then -1), so
/// passing exactly the figures a previous call, or the Money Market's mirror of this rounding, returned
/// leaves about 1e-9 of the liquidity as dust and the position is not deleted; pass amounts above
/// the position to close it. No input limit is enforced so liquidations cannot get stuck, and there is no
/// "max" sentinel: an amount above about 2^256 / (1e12 * numeratorPrecision) (1.16e62 for a 6-decimal
/// token) reverts with Panic(0x11) in the conversion, and very large amounts in narrow ranges revert with
/// empty data in LiquidityAmounts.
/// Pending transfers recorded under msg.sender, per token: pending supply `-= amount + feeAccrued` (the dex
/// owes both to the caller).
/// Emits `LogWithdraw(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
/// deposit); 210007 (guard); 210002 a returned amount below its minimum. 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()`). Empty revert data from the pool lock.
/// @param params_ WithdrawParams containing dexKey, tick range, positionSalt, amounts, and minimums
/// @return amount0_ Amount of token0 released by the removed liquidity, normal units, rounded down
/// @return amount1_ Amount of token1 released by the removed liquidity, normal units, rounded down
/// @return feeAccruedToken0_ LP fee in token0 credited since the last touch, normal units, rounded down
/// @return feeAccruedToken1_ LP fee in token1 credited since the last touch, normal units, rounded down
/// @return liquidityDecreaseRaw_ Raw liquidity removed from the position (0 for a pure fee collection)
function withdraw(WithdrawParams calldata params_) external _onlyDelegateCall
returns (uint256 amount0_, uint256 amount1_, uint256 feeAccruedToken0_, uint256 feeAccruedToken1_, uint256 liquidityDecreaseRaw_) {
// NOTE: No overall unchecked in withdraw because we are not doing amount limit checks
WithdrawVariables 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 withdraw 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 normal amounts to raw adjusted amounts
v_.amount0RawAdjusted = (params_.amount0 * LC.EXCHANGE_PRICES_PRECISION * c_.token0NumeratorPrecision) / (c_.token0SupplyExchangePrice * c_.token0DenominatorPrecision);
v_.amount1RawAdjusted = (params_.amount1 * LC.EXCHANGE_PRICES_PRECISION * c_.token1NumeratorPrecision) / (c_.token1SupplyExchangePrice * c_.token1DenominatorPrecision);
// NOTE: no checks in withdraw so liquidations dont get stuck
// if (
// (v_.amount0RawAdjusted == 0 && params_.amount0 > 0) ||
// (v_.amount1RawAdjusted == 0 && params_.amount1 > 0)
// ) {
// revert FluidDexV2D3D4Error(ErrorTypes.UserModule__AmountRoundsToZero);
// }
// NOTE: no checks in withdraw so liquidations dont get stuck
// if (v_.amount0RawAdjusted > 0) _verifyAdjustedAmountLimits(v_.amount0RawAdjusted);
// if (v_.amount1RawAdjusted > 0) _verifyAdjustedAmountLimits(v_.amount1RawAdjusted);
// no matter the user is adding/removing liquidity, the fee is being collected
(
v_.amount0RawAdjusted,
v_.amount1RawAdjusted,
v_.feeAccruedToken0Adjusted,
v_.feeAccruedToken1Adjusted,
liquidityDecreaseRaw_
) = _removeLiquidity(RemoveLiquidityInternalParams({
dexKey: params_.dexKey,
dexVariables: dexVariables_,
dexVariables2: dexVariables2_,
tickLower: params_.tickLower,
tickUpper: params_.tickUpper,
sqrtPriceLowerX96: TM.getSqrtRatioAtTick(params_.tickLower),
sqrtPriceUpperX96: TM.getSqrtRatioAtTick(params_.tickUpper),
positionSalt: params_.positionSalt,
amount0DesiredRaw: v_.amount0RawAdjusted,
amount1DesiredRaw: v_.amount1RawAdjusted,
dexType: dexType_,
dexId: dexId_
}));
}
// NOTE: no checks in withdraw so liquidations dont get stuck
// if (v_.amount0RawAdjusted > 0) _verifyAdjustedAmountLimits(v_.amount0RawAdjusted);
// if (v_.amount1RawAdjusted > 0) _verifyAdjustedAmountLimits(v_.amount1RawAdjusted);
// Convert raw adjusted amounts to normal amounts
// Also explicitly rounding down to be 100% sure that the protocol is on the winning side
amount0_ = (v_.amount0RawAdjusted * c_.token0DenominatorPrecision * c_.token0SupplyExchangePrice * ROUNDING_FACTOR_MINUS_ONE) /
(c_.token0NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION * ROUNDING_FACTOR);
if (amount0_ > 0) {
amount0_ -= 1; // Just subtracting 1 so protocol remains on the winning side
// _verifyAmountLimits(amount0_); // NOTE: no checks in withdraw so liquidations dont get stuck
}
amount1_ = (v_.amount1RawAdjusted * c_.token1DenominatorPrecision * c_.token1SupplyExchangePrice * ROUNDING_FACTOR_MINUS_ONE) /
(c_.token1NumeratorPrecision * LC.EXCHANGE_PRICES_PRECISION * ROUNDING_FACTOR);
if (amount1_ > 0) {
amount1_ -= 1; // Just subtracting 1 so protocol remains on the winning side
// _verifyAmountLimits(amount1_); // NOTE: no checks in withdraw 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
feeAccruedToken0_ = (v_.feeAccruedToken0Adjusted * c_.token0DenominatorPrecision * ROUNDING_FACTOR_MINUS_ONE) / (c_.token0NumeratorPrecision * ROUNDING_FACTOR);
if (feeAccruedToken0_ > 0) feeAccruedToken0_ -= 1; // Just subtracting 1 so protocol remains on the winning side
feeAccruedToken1_ = (v_.feeAccruedToken1Adjusted * c_.token1DenominatorPrecision * ROUNDING_FACTOR_MINUS_ONE) / (c_.token1NumeratorPrecision * ROUNDING_FACTOR);
if (feeAccruedToken1_ > 0) feeAccruedToken1_ -= 1; // Just subtracting 1 so protocol remains on the winning side
// Verify amounts are not less than minimums
if (amount0_ < params_.amount0Min || amount1_ < params_.amount1Min) {
revert FluidDexV2D3D4Error(ErrorTypes.UserModule__AmountsLessThanMinimum);
}
// Add user pending supply
PT.addPendingSupply(msg.sender, params_.dexKey.token0, -SafeCast.toInt256(amount0_ + feeAccruedToken0_));
PT.addPendingSupply(msg.sender, params_.dexKey.token1, -SafeCast.toInt256(amount1_ + feeAccruedToken1_));
emit LogWithdraw(
dexType_,
dexId_,
msg.sender,
params_.tickLower,
params_.tickUpper,
params_.positionSalt,
amount0_,
amount1_,
feeAccruedToken0_,
feeAccruedToken1_,
liquidityDecreaseRaw_
);
PL.unlock(dexId_);
return (amount0_, amount1_, feeAccruedToken0_, feeAccruedToken1_, liquidityDecreaseRaw_);
}
/// @notice Initializes a new D3 pool with initial price
/// @dev Delegatecall only (212012); only a D3-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) / supplyExchangePrice`, i.e. both tokens normalised to 9
/// decimals and divided by their live Liquidity supply exchange prices (1e12 for a token never listed at
/// Liquidity). 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' supply 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 or that `dexKey.controller` is usable (address(0) makes the controller
/// functions permanently uncallable for the pool, so a dynamic-fee pool stays at 0 % LP fee).
/// 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.