Verified contractExactBUSL-1.1
FluidDexResolver
Address0x11d80cff056cef4f9e6d23da8672fe9873e5cc07
- Balance
0 ETH
- Transactions
2
- Compiler
solc 0.8.21
- Same code
Only this contract
Details
- Compiler
- solc 0.8.21+commit.d9974bed
- Language
- solidity
- Optimization
- Yes, 1,000 runs
- EVM version
- paris
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 23,881,747
- Creation transaction
- 0xedff376e67…b3a8b698fa
13 files
- contracts/periphery/resolvers/dex/main.solmain47.96 KB
- contracts/libraries/addressCalcs.sol1.76 KB
- contracts/libraries/bigMathMinified.sol9.82 KB
- contracts/libraries/bytesSliceAndConcat.sol6.05 KB
- contracts/libraries/dexCalcs.sol15.7 KB
- contracts/libraries/dexSlotsLink.sol3.35 KB
- contracts/liquidity/adminModule/structs.sol6.62 KB
- contracts/periphery/resolvers/dex/structs.sol7.26 KB
- contracts/periphery/resolvers/dex/variables.sol2.17 KB
- contracts/periphery/resolvers/liquidity/iLiquidityResolver.sol6.82 KB
- contracts/periphery/resolvers/liquidity/structs.sol2.92 KB
- contracts/protocols/dex/interfaces/iDexFactory.sol707 B
- contracts/protocols/dex/interfaces/iDexT1.sol15.14 KB
contracts/periphery/resolvers/dex/main.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;
import { AddressCalcs } from "../../../libraries/addressCalcs.sol";
import { DexSlotsLink } from "../../../libraries/dexSlotsLink.sol";
import { DexCalcs } from "../../../libraries/dexCalcs.sol";
import { BigMathMinified } from "../../../libraries/bigMathMinified.sol";
import { BytesSliceAndConcat } from "../../../libraries/bytesSliceAndConcat.sol";
import { IFluidDexT1 } from "../../../protocols/dex/interfaces/iDexT1.sol";
import { Structs as FluidLiquidityResolverStructs } from "../liquidity/structs.sol";
import { Structs } from "./structs.sol";
import { Variables } from "./variables.sol";
/// @title DexFactoryViews
/// @notice Abstract contract providing view functions for DEX factory-related operations
abstract contract DexFactoryViews is Variables {
/// @notice Get the address of a DEX given its ID
/// @param dexId_ The ID of the DEX
/// @return dex_ The address of the DEX
function getDexAddress(uint256 dexId_) public view returns (address dex_) {
return AddressCalcs.addressCalc(address(FACTORY), dexId_);
}
/// @notice Get the ID of a DEX given its address
/// @param dex_ The address of the DEX
/// @return id_ The ID of the DEX
function getDexId(address dex_) public view returns (uint id_) {
id_ = IFluidDexT1(dex_).DEX_ID();
}
/// @notice Get the total number of DEXes
/// @return The total number of DEXes
function getTotalDexes() public view returns (uint) {
return FACTORY.totalDexes();
}
/// @notice Get an array of all DEX addresses
/// @return dexes_ An array containing all DEX addresses
function getAllDexAddresses() public view returns (address[] memory dexes_) {
uint totalDexes_ = getTotalDexes();
dexes_ = new address[](totalDexes_);
for (uint i = 0; i < totalDexes_; i++) {
dexes_[i] = getDexAddress((i + 1));
}
}
}
/// @title DexStorageVars
/// @notice Abstract contract providing view functions for DEX storage variables
abstract contract DexStorageVars is Variables {
/// @notice Get the raw DEX variables
/// @param dex_ The address of the DEX
/// @return The raw DEX variables
function getDexVariablesRaw(address dex_) public view returns (uint) {
return IFluidDexT1(dex_).readFromStorage(bytes32(DexSlotsLink.DEX_VARIABLES_SLOT));
}
/// @notice Get the raw DEX variables2
/// @param dex_ The address of the DEX
/// @return The raw DEX variables2
function getDexVariables2Raw(address dex_) public view returns (uint) {
return IFluidDexT1(dex_).readFromStorage(bytes32(DexSlotsLink.DEX_VARIABLES2_SLOT));
}
/// @notice Get the total supply shares slot data of a DEX
/// @param dex_ The address of the DEX
/// @return The total supply shares
function getTotalSupplySharesRaw(address dex_) public view returns (uint) {
return IFluidDexT1(dex_).readFromStorage(bytes32(DexSlotsLink.DEX_TOTAL_SUPPLY_SHARES_SLOT));
}
/// @notice Get the raw user supply data for a specific user and DEX
/// @param dex_ The address of the DEX
/// @param user_ The address of the user
/// @return The raw user supply data
function getUserSupplyDataRaw(address dex_, address user_) public view returns (uint) {
return
IFluidDexT1(dex_).readFromStorage(
DexSlotsLink.calculateMappingStorageSlot(DexSlotsLink.DEX_USER_SUPPLY_MAPPING_SLOT, user_)
);
}
/// @notice Get the total borrow shares slot data of a DEX
/// @param dex_ The address of the DEX
/// @return The total borrow shares
function getTotalBorrowSharesRaw(address dex_) public view returns (uint) {
return IFluidDexT1(dex_).readFromStorage(bytes32(DexSlotsLink.DEX_TOTAL_BORROW_SHARES_SLOT));
}
/// @notice Get the raw user borrow data for a specific user and DEX
/// @param dex_ The address of the DEX
/// @param user_ The address of the user
/// @return The raw user borrow data
function getUserBorrowDataRaw(address dex_, address user_) public view returns (uint) {
return
IFluidDexT1(dex_).readFromStorage(
DexSlotsLink.calculateMappingStorageSlot(DexSlotsLink.DEX_USER_BORROW_MAPPING_SLOT, user_)
);
}
/// @notice Get the raw oracle data for a specific DEX and index
/// @param dex_ The address of the DEX
/// @param index_ The index of the oracle data
/// @return The raw oracle data
function getOracleRaw(address dex_, uint index_) public view returns (uint) {
return
IFluidDexT1(dex_).readFromStorage(
_calculateStorageSlotUintMapping(DexSlotsLink.DEX_ORACLE_MAPPING_SLOT, index_)
);
}
/// @notice Get the raw range shift for a DEX
/// @param dex_ The address of the DEX
/// @return The raw range shift
function getRangeShiftRaw(address dex_) public view returns (uint) {
return
IFluidDexT1(dex_).readFromStorage(bytes32(DexSlotsLink.DEX_RANGE_THRESHOLD_SHIFTS_SLOT)) &
type(uint128).max;
}
/// @notice Get the raw threshold shift for a DEX
/// @param dex_ The address of the DEX
/// @return The raw threshold shift
function getThresholdShiftRaw(address dex_) public view returns (uint) {
return IFluidDexT1(dex_).readFromStorage(bytes32(DexSlotsLink.DEX_RANGE_THRESHOLD_SHIFTS_SLOT)) >> 128;
}
/// @notice Get the raw center price shift for a DEX
/// @param dex_ The address of the DEX
/// @return The raw center price shift
function getCenterPriceShiftRaw(address dex_) public view returns (uint) {
return IFluidDexT1(dex_).readFromStorage(bytes32(DexSlotsLink.DEX_CENTER_PRICE_SHIFT_SLOT));
}
/// @dev Calculate the storage slot for a uint mapping
/// @param slot_ The base slot of the mapping
/// @param key_ The key of the mapping
/// @return The calculated storage slot
function _calculateStorageSlotUintMapping(uint256 slot_, uint key_) internal pure returns (bytes32) {
return keccak256(abi.encode(key_, slot_));
}
}
abstract contract DexActionEstimates {
address private constant ADDRESS_DEAD = 0x000000000000000000000000000000000000dEaD;
/// @notice estimates swap IN tokens execution
/// @param dex_ Dex pool
/// @param swap0to1_ Direction of swap. If true, swaps token0 for token1; if false, swaps token1 for token0
/// @param amountIn_ The exact amount of input tokens to swap
/// @param amountOutMin_ The minimum amount of output tokens the user is willing to accept
/// @return amountOut_ The amount of output tokens received from the swap
function estimateSwapIn(
address dex_,
bool swap0to1_,
uint256 amountIn_,
uint256 amountOutMin_
) public payable returns (uint256 amountOut_) {
try IFluidDexT1(dex_).swapIn{ value: msg.value }(swap0to1_, amountIn_, amountOutMin_, ADDRESS_DEAD) {} catch (
bytes memory lowLevelData_
) {
(amountOut_) = _decodeLowLevelUint1x(lowLevelData_, IFluidDexT1.FluidDexSwapResult.selector);
}
}
/// @notice estimates swap OUT tokens execution
/// @param dex_ Dex pool
/// @param swap0to1_ Direction of swap. If true, swaps token0 for token1; if false, swaps token1 for token0
/// @param amountOut_ The exact amount of tokens to receive after swap
/// @param amountInMax_ Maximum amount of tokens to swap in
/// @return amountIn_ The amount of input tokens used for the swap
function estimateSwapOut(
address dex_,
bool swap0to1_,
uint256 amountOut_,
uint256 amountInMax_
) public payable returns (uint256 amountIn_) {
try IFluidDexT1(dex_).swapOut{ value: msg.value }(swap0to1_, amountOut_, amountInMax_, ADDRESS_DEAD) {} catch (
bytes memory lowLevelData_
) {
(amountIn_) = _decodeLowLevelUint1x(lowLevelData_, IFluidDexT1.FluidDexSwapResult.selector);
}
}
/// @dev Estimate deposit tokens in equal proportion to the current pool ratio
/// @param dex_ The address of the DEX contract
/// @param shares_ The number of shares to mint
/// @param maxToken0Deposit_ Maximum amount of token0 to deposit
/// @param maxToken1Deposit_ Maximum amount of token1 to deposit
/// @return token0Amt_ Estimated amount of token0 to deposit
/// @return token1Amt_ Estimated amount of token1 to deposit
function estimateDepositPerfect(
address dex_,
uint shares_,
uint maxToken0Deposit_,
uint maxToken1Deposit_
) public payable returns (uint token0Amt_, uint token1Amt_) {
try
IFluidDexT1(dex_).depositPerfect{ value: msg.value }(shares_, maxToken0Deposit_, maxToken1Deposit_, true)
{} catch (bytes memory lowLevelData_) {
(token0Amt_, token1Amt_) = _decodeLowLevelUint2x(
lowLevelData_,
IFluidDexT1.FluidDexPerfectLiquidityOutput.selector
);
}
}
/// @dev Estimate withdrawal of a perfect amount of collateral liquidity
/// @param dex_ The address of the DEX contract
/// @param shares_ The number of shares to withdraw
/// @param minToken0Withdraw_ The minimum amount of token0 the user is willing to accept
/// @param minToken1Withdraw_ The minimum amount of token1 the user is willing to accept
/// @return token0Amt_ Estimated amount of token0 to be withdrawn
/// @return token1Amt_ Estimated amount of token1 to be withdrawn
function estimateWithdrawPerfect(
address dex_,
uint shares_,
uint minToken0Withdraw_,
uint minToken1Withdraw_
) public returns (uint token0Amt_, uint token1Amt_) {
try IFluidDexT1(dex_).withdrawPerfect(shares_, minToken0Withdraw_, minToken1Withdraw_, ADDRESS_DEAD) {} catch (
bytes memory lowLevelData_
) {
(token0Amt_, token1Amt_) = _decodeLowLevelUint2x(
lowLevelData_,
IFluidDexT1.FluidDexPerfectLiquidityOutput.selector
);
}
}
/// @dev Estimate borrowing tokens in equal proportion to the current debt pool ratio
/// @param dex_ The address of the DEX contract
/// @param shares_ The number of shares to borrow
/// @param minToken0Borrow_ Minimum amount of token0 to borrow
/// @param minToken1Borrow_ Minimum amount of token1 to borrow
/// @return token0Amt_ Estimated amount of token0 to be borrowed
/// @return token1Amt_ Estimated amount of token1 to be borrowed
function estimateBorrowPerfect(
address dex_,
uint shares_,
uint minToken0Borrow_,
uint minToken1Borrow_
) public returns (uint token0Amt_, uint token1Amt_) {
try IFluidDexT1(dex_).borrowPerfect(shares_, minToken0Borrow_, minToken1Borrow_, ADDRESS_DEAD) {} catch (
bytes memory lowLevelData_
) {
(token0Amt_, token1Amt_) = _decodeLowLevelUint2x(
lowLevelData_,
IFluidDexT1.FluidDexPerfectLiquidityOutput.selector
);
}
}
/// @dev Estimate paying back borrowed tokens in equal proportion to the current debt pool ratio
/// @param dex_ The address of the DEX contract
/// @param shares_ The number of shares to pay back
/// @param maxToken0Payback_ Maximum amount of token0 to pay back
/// @param maxToken1Payback_ Maximum amount of token1 to pay back
/// @return token0Amt_ Estimated amount of token0 to be paid back
/// @return token1Amt_ Estimated amount of token1 to be paid back
function estimatePaybackPerfect(
address dex_,
uint shares_,
uint maxToken0Payback_,
uint maxToken1Payback_
) public payable returns (uint token0Amt_, uint token1Amt_) {
try
IFluidDexT1(dex_).paybackPerfect{ value: msg.value }(shares_, maxToken0Payback_, maxToken1Payback_, true)
{} catch (bytes memory lowLevelData_) {
(token0Amt_, token1Amt_) = _decodeLowLevelUint2x(
lowLevelData_,
IFluidDexT1.FluidDexPerfectLiquidityOutput.selector
);
}
}
/// @dev Estimate deposit of tokens
/// @param dex_ The address of the DEX contract
/// @param token0Amt_ Amount of token0 to deposit
/// @param token1Amt_ Amount of token1 to deposit
/// @param minSharesAmt_ Minimum amount of shares to receive
/// @return shares_ Estimated amount of shares to be minted
function estimateDeposit(
address dex_,
uint token0Amt_,
uint token1Amt_,
uint minSharesAmt_
) public payable returns (uint shares_) {
try IFluidDexT1(dex_).deposit{ value: msg.value }(token0Amt_, token1Amt_, minSharesAmt_, true) {} catch (
bytes memory lowLevelData_
) {
(shares_) = _decodeLowLevelUint1x(lowLevelData_, IFluidDexT1.FluidDexLiquidityOutput.selector);
}
}
/// @dev Estimate withdrawal of tokens
/// @param dex_ The address of the DEX contract
/// @param token0Amt_ Amount of token0 to withdraw
/// @param token1Amt_ Amount of token1 to withdraw
/// @param maxSharesAmt_ Maximum amount of shares to burn
/// @return shares_ Estimated amount of shares to be burned
function estimateWithdraw(
address dex_,
uint token0Amt_,
uint token1Amt_,
uint maxSharesAmt_
) public returns (uint shares_) {
try IFluidDexT1(dex_).withdraw(token0Amt_, token1Amt_, maxSharesAmt_, ADDRESS_DEAD) {} catch (
bytes memory lowLevelData_
) {
(shares_) = _decodeLowLevelUint1x(lowLevelData_, IFluidDexT1.FluidDexLiquidityOutput.selector);
}
}
/// @dev Estimate borrowing of tokens
/// @param dex_ The address of the DEX contract
/// @param token0Amt_ Amount of token0 to borrow
/// @param token1Amt_ Amount of token1 to borrow
/// @param maxSharesAmt_ Maximum amount of shares to mint
/// @return shares_ Estimated amount of shares to be minted
function estimateBorrow(
address dex_,
uint token0Amt_,
uint token1Amt_,
uint maxSharesAmt_
) public returns (uint shares_) {
try IFluidDexT1(dex_).borrow(token0Amt_, token1Amt_, maxSharesAmt_, ADDRESS_DEAD) {} catch (
bytes memory lowLevelData_
) {
(shares_) = _decodeLowLevelUint1x(lowLevelData_, IFluidDexT1.FluidDexLiquidityOutput.selector);
}
}
/// @dev Estimate paying back of borrowed tokens
/// @param dex_ The address of the DEX contract
/// @param token0Amt_ Amount of token0 to pay back
/// @param token1Amt_ Amount of token1 to pay back
/// @param minSharesAmt_ Minimum amount of shares to burn
/// @return shares_ Estimated amount of shares to be burned
function estimatePayback(
address dex_,
uint token0Amt_,
uint token1Amt_,
uint minSharesAmt_
) public payable returns (uint shares_) {
try IFluidDexT1(dex_).payback{ value: msg.value }(token0Amt_, token1Amt_, minSharesAmt_, true) {} catch (
bytes memory lowLevelData_
) {
(shares_) = _decodeLowLevelUint1x(lowLevelData_, IFluidDexT1.FluidDexLiquidityOutput.selector);
}
}
/// @dev Estimate withdrawal of a perfect amount of collateral liquidity in one token
/// @param dex_ The address of the DEX contract
/// @param shares_ The number of shares to withdraw
/// @param minToken0_ The minimum amount of token0 the user is willing to accept
/// @param minToken1_ The minimum amount of token1 the user is willing to accept
/// @return withdrawAmt_ Estimated amount of tokens to be withdrawn
function estimateWithdrawPerfectInOneToken(
address dex_,
uint shares_,
uint minToken0_,
uint minToken1_
) public returns (uint withdrawAmt_) {
try IFluidDexT1(dex_).withdrawPerfectInOneToken(shares_, minToken0_, minToken1_, ADDRESS_DEAD) {} catch (
bytes memory lowLevelData_
) {
(withdrawAmt_) = _decodeLowLevelUint1x(lowLevelData_, IFluidDexT1.FluidDexLiquidityOutput.selector);
}
}
/// @dev Estimate paying back of a perfect amount of borrowed tokens in one token
/// @param dex_ The address of the DEX contract
/// @param shares_ The number of shares to pay back
/// @param maxToken0_ Maximum amount of token0 to pay back
/// @param maxToken1_ Maximum amount of token1 to pay back
/// @return paybackAmt_ Estimated amount of tokens to be paid back
function estimatePaybackPerfectInOneToken(
address dex_,
uint shares_,
uint maxToken0_,
uint maxToken1_
) public payable returns (uint paybackAmt_) {
try
IFluidDexT1(dex_).paybackPerfectInOneToken{ value: msg.value }(shares_, maxToken0_, maxToken1_, true)
{} catch (bytes memory lowLevelData_) {
(paybackAmt_) = _decodeLowLevelUint1x(lowLevelData_, IFluidDexT1.FluidDexSingleTokenOutput.selector);
}
}
function _decodeLowLevelUint2x(
bytes memory lowLevelData_,
bytes4 targetErrorSelector_
) internal pure returns (uint value1_, uint value2_) {
if (lowLevelData_.length < 68) {
return (0, 0);
}
bytes4 errorSelector_;
assembly {
// Extract the selector from the error data
errorSelector_ := mload(add(lowLevelData_, 0x20))
}
if (errorSelector_ == targetErrorSelector_) {
assembly {
value1_ := mload(add(lowLevelData_, 36))
value2_ := mload(add(lowLevelData_, 68))
}
}
// else => values remain 0
}
function _decodeLowLevelUint1x(
bytes memory lowLevelData_,
bytes4 targetErrorSelector_
) internal pure returns (uint value1_) {
if (lowLevelData_.length < 36) {
return 0;
}
bytes4 errorSelector_;
assembly {
// Extract the selector from the error data
errorSelector_ := mload(add(lowLevelData_, 0x20))
}
if (errorSelector_ == targetErrorSelector_) {
assembly {
value1_ := mload(add(lowLevelData_, 36))
}
}
// else => values remain 0
}
}
abstract contract DexConstantsViews {
/// @notice returns all Dex constants
function getDexConstantsView(address dex_) public view returns (IFluidDexT1.ConstantViews memory constantsView_) {
return IFluidDexT1(dex_).constantsView();
}
/// @notice returns all Dex constants 2
function getDexConstantsView2(
address dex_
) public view returns (IFluidDexT1.ConstantViews2 memory constantsView2_) {
return IFluidDexT1(dex_).constantsView2();
}
/// @notice Get the addresses of the tokens in a DEX
/// @param dex_ The address of the DEX
/// @return token0_ The address of token0 in the DEX
/// @return token1_ The address of token1 in the DEX
function getDexTokens(address dex_) public view returns (address token0_, address token1_) {
IFluidDexT1.ConstantViews memory constantsView_ = IFluidDexT1(dex_).constantsView();
return (constantsView_.token0, constantsView_.token1);
}
}
abstract contract DexPublicViews is DexStorageVars, DexConstantsViews {
/// @notice Get the prices and exchange prices for a DEX
/// @param dex_ The address of the DEX
/// @return pex_ A struct containing prices and exchange prices
/// @dev expected to be called via callStatic
function getDexPricesAndExchangePrices(
address dex_
) public returns (IFluidDexT1.PricesAndExchangePrice memory pex_) {
try IFluidDexT1(dex_).getPricesAndExchangePrices() {} catch (bytes memory lowLevelData_) {
bytes4 errorSelector_;
assembly {
// Extract the selector from the error data
errorSelector_ := mload(add(lowLevelData_, 0x20))
}
if (errorSelector_ == IFluidDexT1.FluidDexPricesAndExchangeRates.selector) {
pex_ = abi.decode(
BytesSliceAndConcat.bytesSlice(lowLevelData_, 4, lowLevelData_.length - 4),
(IFluidDexT1.PricesAndExchangePrice)
);
}
}
}
/// @notice Get the collateral reserves for a DEX
/// @param dex_ The address of the DEX
/// @return reserves_ A struct containing collateral reserve information
/// @dev expected to be called via callStatic
function getDexCollateralReserves(address dex_) public returns (IFluidDexT1.CollateralReserves memory reserves_) {
return _getDexCollateralReserves(dex_, getDexConstantsView2(dex_));
}
/// @notice Get the debt reserves for a DEX
/// @param dex_ The address of the DEX
/// @return reserves_ A struct containing debt reserve information
/// @dev expected to be called via callStatic
function getDexDebtReserves(address dex_) public returns (IFluidDexT1.DebtReserves memory reserves_) {
return _getDexDebtReserves(dex_, getDexConstantsView2(dex_));
}
/// @notice get Dex oracle price TWAP data
/// @param secondsAgos_ array of seconds ago for which TWAP is needed. If user sends [10, 30, 60] then twaps_ will return [10-0, 30-10, 60-30]
/// @return twaps_ twap price, lowest price (aka minima) & highest price (aka maxima) between secondsAgo checkpoints
/// @return currentPrice_ price of pool after the most recent swap
function getDexOraclePrice(
address dex_,
uint[] memory secondsAgos_
) external view returns (IFluidDexT1.Oracle[] memory twaps_, uint currentPrice_) {
return IFluidDexT1(dex_).oraclePrice(secondsAgos_);
}
/// @dev Get the collateral reserves for a DEX scaled to token decimals
function _getDexCollateralReserves(
address dex_,
IFluidDexT1.ConstantViews2 memory constantsView2_
) internal returns (IFluidDexT1.CollateralReserves memory reserves_) {
uint256 dexVariables2_ = getDexVariables2Raw(dex_);
if ((dexVariables2_ & 1) != 1) {
// smart col not enabled
return IFluidDexT1.CollateralReserves(0, 0, 0, 0);
}
try this.getDexPricesAndExchangePrices(dex_) returns (IFluidDexT1.PricesAndExchangePrice memory pex_) {
try
IFluidDexT1(dex_).getCollateralReserves(
pex_.geometricMean,
pex_.upperRange,
pex_.lowerRange,
pex_.supplyToken0ExchangePrice,
pex_.supplyToken1ExchangePrice
)
returns (IFluidDexT1.CollateralReserves memory colReserves_) {
// returned reserves are in 1e12 decimals -> normalize to token decimals
reserves_.token0RealReserves =
(colReserves_.token0RealReserves * constantsView2_.token0DenominatorPrecision) /
constantsView2_.token0NumeratorPrecision;
reserves_.token0ImaginaryReserves =
(colReserves_.token0ImaginaryReserves * constantsView2_.token0DenominatorPrecision) /
constantsView2_.token0NumeratorPrecision;
reserves_.token1RealReserves =
(colReserves_.token1RealReserves * constantsView2_.token1DenominatorPrecision) /
constantsView2_.token1NumeratorPrecision;
reserves_.token1ImaginaryReserves =
(colReserves_.token1ImaginaryReserves * constantsView2_.token1DenominatorPrecision) /
constantsView2_.token1NumeratorPrecision;
} catch {
reserves_ = IFluidDexT1.CollateralReserves(0, 0, 0, 0);
}
} catch {
reserves_ = IFluidDexT1.CollateralReserves(0, 0, 0, 0);
}
}
/// @dev Get the debt reserves for a DEX scaled to token decimals
function _getDexDebtReserves(
address dex_,
IFluidDexT1.ConstantViews2 memory constantsView2_
) internal returns (IFluidDexT1.DebtReserves memory reserves_) {
uint256 dexVariables2_ = getDexVariables2Raw(dex_);
if ((dexVariables2_ & 2) != 2) {
// smart debt not enabled
return IFluidDexT1.DebtReserves(0, 0, 0, 0, 0, 0);
}
try this.getDexPricesAndExchangePrices(dex_) returns (IFluidDexT1.PricesAndExchangePrice memory pex_) {
try
IFluidDexT1(dex_).getDebtReserves(
pex_.geometricMean,
pex_.upperRange,
pex_.lowerRange,
pex_.borrowToken0ExchangePrice,
pex_.borrowToken1ExchangePrice
)
returns (IFluidDexT1.DebtReserves memory debtReserves_) {
// returned reserves are in 1e12 decimals -> normalize to token decimals
reserves_.token0Debt =
(debtReserves_.token0Debt * constantsView2_.token0DenominatorPrecision) /
constantsView2_.token0NumeratorPrecision;
reserves_.token0RealReserves =
(debtReserves_.token0RealReserves * constantsView2_.token0DenominatorPrecision) /
constantsView2_.token0NumeratorPrecision;
reserves_.token0ImaginaryReserves =
(debtReserves_.token0ImaginaryReserves * constantsView2_.token0DenominatorPrecision) /
constantsView2_.token0NumeratorPrecision;
reserves_.token1Debt =
(debtReserves_.token1Debt * constantsView2_.token1DenominatorPrecision) /
constantsView2_.token1NumeratorPrecision;
reserves_.token1RealReserves =
(debtReserves_.token1RealReserves * constantsView2_.token1DenominatorPrecision) /
constantsView2_.token1NumeratorPrecision;
reserves_.token1ImaginaryReserves =
(debtReserves_.token1ImaginaryReserves * constantsView2_.token1DenominatorPrecision) /
constantsView2_.token1NumeratorPrecision;
} catch {
reserves_ = IFluidDexT1.DebtReserves(0, 0, 0, 0, 0, 0);
}
} catch {
reserves_ = IFluidDexT1.DebtReserves(0, 0, 0, 0, 0, 0);
}
}
}
abstract contract DexUserViews is Variables, Structs, DexConstantsViews, DexPublicViews {
/// @notice Get user supply data for a specific DEX and user
/// @param dex_ The address of the DEX
/// @param user_ The address of the user
/// @return userSupplyData_ Struct containing user supply data
function getUserSupplyData(
address dex_,
address user_
) public view returns (UserSupplyData memory userSupplyData_) {
uint256 userSupply_ = getUserSupplyDataRaw(dex_, user_);
if (userSupply_ > 0) {
// if userSupply_ == 0 -> user not configured yet
userSupplyData_.isAllowed = userSupply_ & 1 == 1;
userSupplyData_.supply = BigMathMinified.fromBigNumber(
(userSupply_ >> DexSlotsLink.BITS_USER_SUPPLY_AMOUNT) & DexCalcs.X64,
DexCalcs.DEFAULT_EXPONENT_SIZE,
DexCalcs.DEFAULT_EXPONENT_MASK
);
// get updated expanded withdrawal limit
userSupplyData_.withdrawalLimit = DexCalcs.calcWithdrawalLimitBeforeOperate(
userSupply_,
userSupplyData_.supply
);
userSupplyData_.lastUpdateTimestamp =
(userSupply_ >> DexSlotsLink.BITS_USER_SUPPLY_LAST_UPDATE_TIMESTAMP) &
DexCalcs.X33;
userSupplyData_.expandPercent =
(userSupply_ >> DexSlotsLink.BITS_USER_SUPPLY_EXPAND_PERCENT) &
DexCalcs.X14;
userSupplyData_.expandDuration =
(userSupply_ >> DexSlotsLink.BITS_USER_SUPPLY_EXPAND_DURATION) &
DexCalcs.X24;
userSupplyData_.baseWithdrawalLimit = BigMathMinified.fromBigNumber(
(userSupply_ >> DexSlotsLink.BITS_USER_SUPPLY_BASE_WITHDRAWAL_LIMIT) & DexCalcs.X18,
DexCalcs.DEFAULT_EXPONENT_SIZE,
DexCalcs.DEFAULT_EXPONENT_MASK
);
userSupplyData_.withdrawableUntilLimit = userSupplyData_.supply > userSupplyData_.withdrawalLimit
? userSupplyData_.supply - userSupplyData_.withdrawalLimit
: 0;
userSupplyData_.withdrawable = userSupplyData_.withdrawableUntilLimit;
(address token0_, address token1_) = getDexTokens(dex_);
(userSupplyData_.liquidityUserSupplyDataToken0, userSupplyData_.liquidityTokenData0) = LIQUIDITY_RESOLVER
.getUserSupplyData(dex_, token0_);
(userSupplyData_.liquidityUserSupplyDataToken1, userSupplyData_.liquidityTokenData1) = LIQUIDITY_RESOLVER
.getUserSupplyData(dex_, token1_);
}
}
/// @notice Get user supply data for multiple users in a specific DEX
/// @param dex_ The address of the DEX
/// @param users_ Array of user addresses
/// @return userSuppliesData_ Array of UserSupplyData structs for each user
function getUserSupplyDatas(
address dex_,
address[] calldata users_
) public view returns (UserSupplyData[] memory userSuppliesData_) {
uint256 length_ = users_.length;
userSuppliesData_ = new UserSupplyData[](length_);
for (uint256 i; i < length_; i++) {
(userSuppliesData_[i]) = getUserSupplyData(dex_, users_[i]);
}
}
/// @notice Get user borrow data for a specific DEX and user
/// @param dex_ The address of the DEX
/// @param user_ The address of the user
/// @return userBorrowData_ Struct containing user borrow data
function getUserBorrowData(
address dex_,
address user_
) public view returns (UserBorrowData memory userBorrowData_) {
uint256 userBorrow_ = getUserBorrowDataRaw(dex_, user_);
if (userBorrow_ > 0) {
// if userBorrow_ == 0 -> user not configured yet
userBorrowData_.isAllowed = userBorrow_ & 1 == 1;
userBorrowData_.borrow = BigMathMinified.fromBigNumber(
(userBorrow_ >> DexSlotsLink.BITS_USER_BORROW_AMOUNT) & DexCalcs.X64,
DexCalcs.DEFAULT_EXPONENT_SIZE,
DexCalcs.DEFAULT_EXPONENT_MASK
);
// get updated expanded borrow limit
userBorrowData_.borrowLimit = DexCalcs.calcBorrowLimitBeforeOperate(userBorrow_, userBorrowData_.borrow);
userBorrowData_.lastUpdateTimestamp =
(userBorrow_ >> DexSlotsLink.BITS_USER_BORROW_LAST_UPDATE_TIMESTAMP) &
DexCalcs.X33;
userBorrowData_.expandPercent =
(userBorrow_ >> DexSlotsLink.BITS_USER_BORROW_EXPAND_PERCENT) &
DexCalcs.X14;
userBorrowData_.expandDuration =
(userBorrow_ >> DexSlotsLink.BITS_USER_BORROW_EXPAND_DURATION) &
DexCalcs.X24;
userBorrowData_.baseBorrowLimit = BigMathMinified.fromBigNumber(
(userBorrow_ >> DexSlotsLink.BITS_USER_BORROW_BASE_BORROW_LIMIT) & DexCalcs.X18,
DexCalcs.DEFAULT_EXPONENT_SIZE,
DexCalcs.DEFAULT_EXPONENT_MASK
);
userBorrowData_.maxBorrowLimit = BigMathMinified.fromBigNumber(
(userBorrow_ >> DexSlotsLink.BITS_USER_BORROW_MAX_BORROW_LIMIT) & DexCalcs.X18,
DexCalcs.DEFAULT_EXPONENT_SIZE,
DexCalcs.DEFAULT_EXPONENT_MASK
);
userBorrowData_.borrowableUntilLimit = userBorrowData_.borrowLimit > userBorrowData_.borrow
? userBorrowData_.borrowLimit - userBorrowData_.borrow
: 0;
userBorrowData_.borrowable = userBorrowData_.borrowableUntilLimit;
(address token0_, address token1_) = getDexTokens(dex_);
(userBorrowData_.liquidityUserBorrowDataToken0, userBorrowData_.liquidityTokenData0) = LIQUIDITY_RESOLVER
.getUserBorrowData(dex_, token0_);
(userBorrowData_.liquidityUserBorrowDataToken1, userBorrowData_.liquidityTokenData1) = LIQUIDITY_RESOLVER
.getUserBorrowData(dex_, token1_);
}
}
/// @notice Get user borrow data for multiple users in a specific DEX
/// @param dex_ The address of the DEX
/// @param users_ Array of user addresses
/// @return userBorrowingsData_ Array of UserBorrowData structs for each user
function getUserBorrowDatas(
address dex_,
address[] calldata users_
) public view returns (UserBorrowData[] memory userBorrowingsData_) {
uint256 length_ = users_.length;
userBorrowingsData_ = new UserBorrowData[](length_);
for (uint256 i; i < length_; i++) {
(userBorrowingsData_[i]) = getUserBorrowData(dex_, users_[i]);
}
}
/// @notice Get both user supply and borrow data for multiple users in a specific DEX
/// @param dex_ The address of the DEX
/// @param users_ Array of user addresses
/// @return userSuppliesData_ Array of UserSupplyData structs for each user
/// @return userBorrowingsData_ Array of UserBorrowData structs for each user
function getUserBorrowSupplyDatas(
address dex_,
address[] calldata users_
) public view returns (UserSupplyData[] memory userSuppliesData_, UserBorrowData[] memory userBorrowingsData_) {
uint256 length_ = users_.length;
userSuppliesData_ = new UserSupplyData[](length_);
userBorrowingsData_ = new UserBorrowData[](length_);
for (uint256 i; i < length_; i++) {
(userSuppliesData_[i]) = getUserSupplyData(dex_, users_[i]);
(userBorrowingsData_[i]) = getUserBorrowData(dex_, users_[i]);
}
}
}
/// @notice Fluid Dex protocol resolver
/// Implements various view-only methods to give easy access to Dex protocol data.
contract FluidDexResolver is Variables, DexFactoryViews, DexActionEstimates, DexUserViews {
constructor(
address factory_,
address liquidity_,
address liquidityResolver_,
address deployer_
) Variables(factory_, liquidity_, liquidityResolver_, deployer_) {}
/// @notice Get the current state of a DEX
/// @param dex_ The address of the DEX
/// @return state_ A struct containing the current state of the DEX
/// @dev expected to be called via callStatic
function getDexState(address dex_) public returns (DexState memory state_) {
return _getDexState(dex_, getDexCollateralReserves(dex_), getDexDebtReserves(dex_));
}
/// @notice Get the current configurations of a DEX
/// @param dex_ The address of the DEX
/// @return configs_ A struct containing the current configurations of the DEX
function getDexConfigs(address dex_) public view returns (Configs memory configs_) {
uint256 dexVariables2_ = getDexVariables2Raw(dex_);
configs_.isSmartCollateralEnabled = (dexVariables2_ & 1) == 1;
configs_.isSmartDebtEnabled = (dexVariables2_ & 2) == 2;
configs_.fee = (dexVariables2_ >> 2) & X17;
configs_.revenueCut = (dexVariables2_ >> 19) & X7;
configs_.upperRange = (dexVariables2_ >> 27) & X20;
configs_.lowerRange = (dexVariables2_ >> 47) & X20;
configs_.upperShiftThreshold = (dexVariables2_ >> 68) & X10;
configs_.lowerShiftThreshold = (dexVariables2_ >> 78) & X10;
configs_.shiftingTime = (dexVariables2_ >> 88) & X24;
configs_.maxSupplyShares = getTotalSupplySharesRaw(dex_) >> 128;
configs_.maxBorrowShares = getTotalBorrowSharesRaw(dex_) >> 128;
uint256 addressNonce_ = (dexVariables2_ >> 112) & X30;
if (addressNonce_ > 0) {
configs_.centerPriceAddress = AddressCalcs.addressCalc(DEPLOYER_CONTRACT, addressNonce_);
}
addressNonce_ = (dexVariables2_ >> 142) & X30;
if (addressNonce_ > 0) {
configs_.hookAddress = AddressCalcs.addressCalc(DEPLOYER_CONTRACT, addressNonce_);
}
configs_.maxCenterPrice = BigMathMinified.fromBigNumber(
(dexVariables2_ >> 172) & X28,
DexCalcs.DEFAULT_EXPONENT_SIZE,
DexCalcs.DEFAULT_EXPONENT_MASK
);
configs_.minCenterPrice = BigMathMinified.fromBigNumber(
(dexVariables2_ >> 200) & X28,
DexCalcs.DEFAULT_EXPONENT_SIZE,
DexCalcs.DEFAULT_EXPONENT_MASK
);
configs_.utilizationLimitToken0 = (dexVariables2_ >> 228) & X10;
configs_.utilizationLimitToken1 = (dexVariables2_ >> 238) & X10;
}
/// @notice Get the swap limits and availability for a DEX
/// @param dex_ The address of the DEX
/// @return limitsAndAvailability_ A struct containing the swap limits and availability for the DEX
function getDexSwapLimitsAndAvailability(
address dex_
) public view returns (SwapLimitsAndAvailability memory limitsAndAvailability_) {
(address token0_, address token1_) = getDexTokens(dex_);
uint256 dexVariables2_ = getDexVariables2Raw(dex_);
uint256 utilizationLimitToken0_ = (dexVariables2_ >> 228) & X10;
uint256 utilizationLimitToken1_ = (dexVariables2_ >> 238) & X10;
return
_getDexSwapLimitsAndAvailability(dex_, token0_, token1_, utilizationLimitToken0_, utilizationLimitToken1_);
}
/// @notice Get the entire data for a DEX
/// @param dex_ The address of the DEX
/// @return data_ A struct containing all the data for the DEX
/// @dev expected to be called via callStatic
function getDexEntireData(address dex_) public returns (DexEntireData memory data_) {
data_.dex = dex_;
data_.constantViews = getDexConstantsView(dex_);
data_.constantViews2 = getDexConstantsView2(dex_);
data_.configs = getDexConfigs(dex_);
data_.pex = getDexPricesAndExchangePrices(dex_);
data_.colReserves = _getDexCollateralReserves(dex_, data_.constantViews2);
data_.debtReserves = _getDexDebtReserves(dex_, data_.constantViews2);
data_.dexState = _getDexState(dex_, data_.colReserves, data_.debtReserves);
data_.limitsAndAvailability = _getDexSwapLimitsAndAvailability(
dex_,
data_.constantViews.token0,
data_.constantViews.token1,
data_.configs.utilizationLimitToken0,
data_.configs.utilizationLimitToken1
);
}
/// @notice Get the entire data for multiple DEXes
/// @param dexes_ An array of DEX addresses
/// @return datas_ An array of structs containing all the data for each DEX
/// @dev expected to be called via callStatic
function getDexEntireDatas(address[] memory dexes_) public returns (DexEntireData[] memory datas_) {
uint256 length_ = dexes_.length;
datas_ = new DexEntireData[](length_);
for (uint256 i; i < length_; i++) {
datas_[i] = getDexEntireData(dexes_[i]);
}
}
/// @notice Get the entire data for all DEXes
/// @return datas_ An array of structs containing all the data for all DEXes
/// @dev expected to be called via callStatic
function getAllDexEntireDatas() external returns (DexEntireData[] memory datas_) {
return getDexEntireDatas(getAllDexAddresses());
}
/// @dev get the swap limits and availability for a DEX
/// @param dex_ The address of the DEX
/// @param token0_ The address of token0
/// @param token1_ The address of token1
/// @param utilizationLimitToken0Percent_ The utilization limit percentage for token0
/// @param utilizationLimitToken1Percent_ The utilization limit percentage for token1
/// @return limitsAndAvailability_ A struct containing the swap limits and availability for the DEX
function _getDexSwapLimitsAndAvailability(
address dex_,
address token0_,
address token1_,
uint256 utilizationLimitToken0Percent_,
uint256 utilizationLimitToken1Percent_
) internal view returns (SwapLimitsAndAvailability memory limitsAndAvailability_) {
(
limitsAndAvailability_.liquidityUserSupplyDataToken0,
limitsAndAvailability_.liquidityTokenData0
) = LIQUIDITY_RESOLVER.getUserSupplyData(dex_, token0_);
(
limitsAndAvailability_.liquidityUserSupplyDataToken1,
limitsAndAvailability_.liquidityTokenData1
) = LIQUIDITY_RESOLVER.getUserSupplyData(dex_, token1_);
(limitsAndAvailability_.liquidityUserBorrowDataToken0, ) = LIQUIDITY_RESOLVER.getUserBorrowData(dex_, token0_);
(limitsAndAvailability_.liquidityUserBorrowDataToken1, ) = LIQUIDITY_RESOLVER.getUserBorrowData(dex_, token1_);
limitsAndAvailability_.liquiditySupplyToken0 = limitsAndAvailability_.liquidityTokenData0.totalSupply;
limitsAndAvailability_.liquiditySupplyToken1 = limitsAndAvailability_.liquidityTokenData1.totalSupply;
limitsAndAvailability_.liquidityBorrowToken0 = limitsAndAvailability_.liquidityTokenData0.totalBorrow;
limitsAndAvailability_.liquidityBorrowToken1 = limitsAndAvailability_.liquidityTokenData1.totalBorrow;
limitsAndAvailability_.liquidityWithdrawableToken0 = limitsAndAvailability_
.liquidityUserSupplyDataToken0
.withdrawable;
limitsAndAvailability_.liquidityWithdrawableToken1 = limitsAndAvailability_
.liquidityUserSupplyDataToken1
.withdrawable;
limitsAndAvailability_.liquidityBorrowableToken0 = limitsAndAvailability_
.liquidityUserBorrowDataToken0
.borrowable;
limitsAndAvailability_.liquidityBorrowableToken1 = limitsAndAvailability_
.liquidityUserBorrowDataToken1
.borrowable;
limitsAndAvailability_.utilizationLimitToken0 =
(limitsAndAvailability_.liquiditySupplyToken0 * utilizationLimitToken0Percent_) /
1e3;
limitsAndAvailability_.utilizationLimitToken1 =
(limitsAndAvailability_.liquiditySupplyToken1 * utilizationLimitToken1Percent_) /
1e3;
if (limitsAndAvailability_.liquidityBorrowToken0 < limitsAndAvailability_.utilizationLimitToken0) {
limitsAndAvailability_.withdrawableUntilUtilizationLimitToken0 =
(1e3 * limitsAndAvailability_.liquidityBorrowToken0) /
utilizationLimitToken0Percent_;
limitsAndAvailability_.withdrawableUntilUtilizationLimitToken0 = limitsAndAvailability_
.liquiditySupplyToken0 > limitsAndAvailability_.withdrawableUntilUtilizationLimitToken0
? limitsAndAvailability_.liquiditySupplyToken0 -
limitsAndAvailability_.withdrawableUntilUtilizationLimitToken0
: 0;
limitsAndAvailability_.borrowableUntilUtilizationLimitToken0 =
limitsAndAvailability_.utilizationLimitToken0 -
limitsAndAvailability_.liquidityBorrowToken0;
}
if (limitsAndAvailability_.liquidityBorrowToken1 < limitsAndAvailability_.utilizationLimitToken1) {
limitsAndAvailability_.withdrawableUntilUtilizationLimitToken1 =
(1e3 * limitsAndAvailability_.liquidityBorrowToken1) /
utilizationLimitToken1Percent_;
limitsAndAvailability_.withdrawableUntilUtilizationLimitToken1 = limitsAndAvailability_
.liquiditySupplyToken1 > limitsAndAvailability_.withdrawableUntilUtilizationLimitToken1
? limitsAndAvailability_.liquiditySupplyToken1 -
limitsAndAvailability_.withdrawableUntilUtilizationLimitToken1
: 0;
limitsAndAvailability_.borrowableUntilUtilizationLimitToken1 =
limitsAndAvailability_.utilizationLimitToken1 -
limitsAndAvailability_.liquidityBorrowToken1;
}
}
/// @dev Get the current state of a DEX
function _getDexState(
address dex_,
IFluidDexT1.CollateralReserves memory colReserves_,
IFluidDexT1.DebtReserves memory debtReserves_
) internal view returns (DexState memory state_) {
uint256 storageVar_ = getDexVariablesRaw(dex_);
/// Next 40 bits => 1-40 => last to last stored price. BigNumber (32 bits precision, 8 bits exponent)
/// Next 40 bits => 41-80 => last stored price of pool. BigNumber (32 bits precision, 8 bits exponent)
/// Next 40 bits => 81-120 => center price. Center price from where the ranges will be calculated. BigNumber (32 bits precision, 8 bits exponent)
state_.lastToLastStoredPrice = (storageVar_ >> 1) & X40;
state_.lastToLastStoredPrice = (state_.lastToLastStoredPrice >> 8) << (state_.lastToLastStoredPrice & X8);
state_.lastStoredPrice = (storageVar_ >> 41) & X40;
state_.lastStoredPrice = (state_.lastStoredPrice >> 8) << (state_.lastStoredPrice & X8);
state_.centerPrice = (storageVar_ >> 81) & X40;
state_.centerPrice = (state_.centerPrice >> 8) << (state_.centerPrice & X8);
state_.lastUpdateTimestamp = (storageVar_ >> 121) & X33;
state_.lastPricesTimeDiff = (storageVar_ >> 154) & X22;
state_.oracleCheckPoint = (storageVar_ >> 176) & X3;
state_.oracleMapping = (storageVar_ >> 179) & X16;
state_.totalSupplyShares = getTotalSupplySharesRaw(dex_) & X128;
state_.totalBorrowShares = getTotalBorrowSharesRaw(dex_) & X128;
storageVar_ = getDexVariables2Raw(dex_);
state_.isSwapAndArbitragePaused = storageVar_ >> 255 == 1;
state_.shifts.isRangeChangeActive = (storageVar_ >> 26) & 1 == 1;
state_.shifts.isThresholdChangeActive = (storageVar_ >> 67) & 1 == 1;
state_.shifts.isCenterPriceShiftActive = (storageVar_ >> 248) & 1 == 1;
storageVar_ = getRangeShiftRaw(dex_);
state_.shifts.rangeShift.oldUpper = storageVar_ & X20;
state_.shifts.rangeShift.oldLower = (storageVar_ >> 20) & X20;
state_.shifts.rangeShift.duration = (storageVar_ >> 40) & X20;
state_.shifts.rangeShift.startTimestamp = (storageVar_ >> 60) & X33;
storageVar_ = getThresholdShiftRaw(dex_);
state_.shifts.thresholdShift.oldUpper = storageVar_ & X10;
state_.shifts.thresholdShift.oldLower = (storageVar_ >> 20) & X10;
state_.shifts.thresholdShift.duration = (storageVar_ >> 40) & X20;
state_.shifts.thresholdShift.startTimestamp = (storageVar_ >> 60) & X33;
state_.shifts.thresholdShift.oldTime = (storageVar_ >> 93) & X24;
storageVar_ = getCenterPriceShiftRaw(dex_);
state_.shifts.centerPriceShift.startTimestamp = storageVar_ & X33;
state_.shifts.centerPriceShift.shiftPercentage = (storageVar_ >> 33) & X20;
state_.shifts.centerPriceShift.duration = (storageVar_ >> 53) & X20;
if (state_.totalSupplyShares > 0) {
state_.token0PerSupplyShare = (colReserves_.token0RealReserves * 1e18) / state_.totalSupplyShares;
state_.token1PerSupplyShare = (colReserves_.token1RealReserves * 1e18) / state_.totalSupplyShares;
}
if (state_.totalBorrowShares > 0) {
state_.token0PerBorrowShare = (debtReserves_.token0Debt * 1e18) / state_.totalBorrowShares;
state_.token1PerBorrowShare = (debtReserves_.token1Debt * 1e18) / state_.totalBorrowShares;
}
}
}
contracts/libraries/addressCalcs.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.21 <=0.8.29;
/// @notice implements calculation of address for contracts deployed through CREATE.
/// Accepts contract deployed from which address & nonce
library AddressCalcs {
/// @notice Computes the address of a contract based
/// @param deployedFrom_ Address from which the contract was deployed
/// @param nonce_ Nonce at which the contract was deployed
/// @return contract_ Address of deployed contract
function addressCalc(address deployedFrom_, uint nonce_) internal pure returns (address contract_) {
// @dev based on https://ethereum.stackexchange.com/a/61413
// nonce of smart contract always starts with 1. so, with nonce 0 there won't be any deployment
// hence, nonce of vault deployment starts with 1.
bytes memory data;
if (nonce_ == 0x00) {
return address(0);
} else if (nonce_ <= 0x7f) {
data = abi.encodePacked(bytes1(0xd6), bytes1(0x94), deployedFrom_, uint8(nonce_));
} else if (nonce_ <= 0xff) {
data = abi.encodePacked(bytes1(0xd7), bytes1(0x94), deployedFrom_, bytes1(0x81), uint8(nonce_));
} else if (nonce_ <= 0xffff) {
data = abi.encodePacked(bytes1(0xd8), bytes1(0x94), deployedFrom_, bytes1(0x82), uint16(nonce_));
} else if (nonce_ <= 0xffffff) {
data = abi.encodePacked(bytes1(0xd9), bytes1(0x94), deployedFrom_, bytes1(0x83), uint24(nonce_));
} else {
data = abi.encodePacked(bytes1(0xda), bytes1(0x94), deployedFrom_, bytes1(0x84), uint32(nonce_));
}
return address(uint160(uint256(keccak256(data))));
}
}contracts/libraries/bigMathMinified.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.21 <=0.8.29;
/// @title library that represents a number in BigNumber(coefficient and exponent) format to store in smaller bits.
/// @notice the number is divided into two parts: a coefficient and an exponent. This comes at a cost of losing some precision
/// at the end of the number because the exponent simply fills it with zeroes. This precision is oftentimes negligible and can
/// result in significant gas cost reduction due to storage space reduction.
/// Also note, a valid big number is as follows: if the exponent is > 0, then coefficient last bits should be occupied to have max precision.
/// @dev roundUp is more like a increase 1, which happens everytime for the same number.
/// roundDown simply sets trailing digits after coefficientSize to zero (floor), only once for the same number.
library BigMathMinified {
/// @dev constants to use for `roundUp` input param to increase readability
bool internal constant ROUND_DOWN = false;
bool internal constant ROUND_UP = true;
/// @dev converts `normal` number to BigNumber with `exponent` and `coefficient` (or precision).
/// e.g.:
/// 5035703444687813576399599 (normal) = (coefficient[32bits], exponent[8bits])[40bits]
/// 5035703444687813576399599 (decimal) => 10000101010010110100000011111011110010100110100000000011100101001101001101011101111 (binary)
/// => 10000101010010110100000011111011000000000000000000000000000000000000000000000000000
/// ^-------------------- 51(exponent) -------------- ^
/// coefficient = 1000,0101,0100,1011,0100,0000,1111,1011 (2236301563)
/// exponent = 0011,0011 (51)
/// bigNumber = 1000,0101,0100,1011,0100,0000,1111,1011,0011,0011 (572493200179)
///
/// @param normal number which needs to be converted into Big Number
/// @param coefficientSize at max how many bits of precision there should be (64 = uint64 (64 bits precision))
/// @param exponentSize at max how many bits of exponent there should be (8 = uint8 (8 bits exponent))
/// @param roundUp signals if result should be rounded down or up
/// @return bigNumber converted bigNumber (coefficient << exponent)
function toBigNumber(
uint256 normal,
uint256 coefficientSize,
uint256 exponentSize,
bool roundUp
) internal pure returns (uint256 bigNumber) {
assembly {
let lastBit_
let number_ := normal
if gt(number_, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
number_ := shr(0x80, number_)
lastBit_ := 0x80
}
if gt(number_, 0xFFFFFFFFFFFFFFFF) {
number_ := shr(0x40, number_)
lastBit_ := add(lastBit_, 0x40)
}
if gt(number_, 0xFFFFFFFF) {
number_ := shr(0x20, number_)
lastBit_ := add(lastBit_, 0x20)
}
if gt(number_, 0xFFFF) {
number_ := shr(0x10, number_)
lastBit_ := add(lastBit_, 0x10)
}
if gt(number_, 0xFF) {
number_ := shr(0x8, number_)
lastBit_ := add(lastBit_, 0x8)
}
if gt(number_, 0xF) {
number_ := shr(0x4, number_)
lastBit_ := add(lastBit_, 0x4)
}
if gt(number_, 0x3) {
number_ := shr(0x2, number_)
lastBit_ := add(lastBit_, 0x2)
}
if gt(number_, 0x1) {
lastBit_ := add(lastBit_, 1)
}
if gt(number_, 0) {
lastBit_ := add(lastBit_, 1)
}
if lt(lastBit_, coefficientSize) {
// for throw exception
lastBit_ := coefficientSize
}
let exponent := sub(lastBit_, coefficientSize)
let coefficient := shr(exponent, normal)
if and(roundUp, gt(exponent, 0)) {
// rounding up is only needed if exponent is > 0, as otherwise the coefficient fully holds the original number
coefficient := add(coefficient, 1)
if eq(shl(coefficientSize, 1), coefficient) {
// case were coefficient was e.g. 111, with adding 1 it became 1000 (in binary) and coefficientSize 3 bits
// final coefficient would exceed it's size. -> reduce coefficent to 100 and increase exponent by 1.
coefficient := shl(sub(coefficientSize, 1), 1)
exponent := add(exponent, 1)
}
}
if iszero(lt(exponent, shl(exponentSize, 1))) {
// if exponent is >= exponentSize, the normal number is too big to fit within
// BigNumber with too small sizes for coefficient and exponent
revert(0, 0)
}
bigNumber := shl(exponentSize, coefficient)
bigNumber := add(bigNumber, exponent)
}
}
/// @dev get `normal` number from `bigNumber`, `exponentSize` and `exponentMask`
function fromBigNumber(
uint256 bigNumber,
uint256 exponentSize,
uint256 exponentMask
) internal pure returns (uint256 normal) {
assembly {
let coefficient := shr(exponentSize, bigNumber)
let exponent := and(bigNumber, exponentMask)
normal := shl(exponent, coefficient)
}
}
/// @dev gets the most significant bit `lastBit` of a `normal` number (length of given number of binary format).
/// e.g.
/// 5035703444687813576399584 = 10000101010010110100000011111011110010100110100000000011100101001101001101011100000
/// lastBit = ^--------------------------------- 83 ----------------------------------------^
function mostSignificantBit(uint256 normal) internal pure returns (uint lastBit) {
assembly {
let number_ := normal
if gt(normal, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
number_ := shr(0x80, number_)
lastBit := 0x80
}
if gt(number_, 0xFFFFFFFFFFFFFFFF) {
number_ := shr(0x40, number_)
lastBit := add(lastBit, 0x40)
}
if gt(number_, 0xFFFFFFFF) {
number_ := shr(0x20, number_)
lastBit := add(lastBit, 0x20)
}
if gt(number_, 0xFFFF) {
number_ := shr(0x10, number_)
lastBit := add(lastBit, 0x10)
}
if gt(number_, 0xFF) {
number_ := shr(0x8, number_)
lastBit := add(lastBit, 0x8)
}
if gt(number_, 0xF) {
number_ := shr(0x4, number_)
lastBit := add(lastBit, 0x4)
}
if gt(number_, 0x3) {
number_ := shr(0x2, number_)
lastBit := add(lastBit, 0x2)
}
if gt(number_, 0x1) {
lastBit := add(lastBit, 1)
}
if gt(number_, 0) {
lastBit := add(lastBit, 1)
}
}
}
/// @dev gets the least significant bit `firstBit` of a `normal` number (position of rightmost 1 in binary format).
/// e.g.
/// 5035703444687813576399584 = 10000101010010110100000011111011110010100110100000000011100101001101001101011100000
/// firstBit = ^-6--^
function leastSignificantBit(uint256 normal) internal pure returns (uint firstBit) {
assembly {
// If number is 0, revert as there is no least significant bit
if iszero(normal) {
revert(0, 0)
}
// Find first set bit using binary search
let number_ := normal
firstBit := 0
// Check if lower 128 bits are all zero
if iszero(and(number_, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) {
number_ := shr(0x80, number_)
firstBit := 0x80
}
// Check if lower 64 bits are all zero
if iszero(and(number_, 0xFFFFFFFFFFFFFFFF)) {
number_ := shr(0x40, number_)
firstBit := add(firstBit, 0x40)
}
// Check if lower 32 bits are all zero
if iszero(and(number_, 0xFFFFFFFF)) {
number_ := shr(0x20, number_)
firstBit := add(firstBit, 0x20)
}
// Check if lower 16 bits are all zero
if iszero(and(number_, 0xFFFF)) {
number_ := shr(0x10, number_)
firstBit := add(firstBit, 0x10)
}
// Check if lower 8 bits are all zero
if iszero(and(number_, 0xFF)) {
number_ := shr(0x8, number_)
firstBit := add(firstBit, 0x8)
}
// Check if lower 4 bits are all zero
if iszero(and(number_, 0xF)) {
number_ := shr(0x4, number_)
firstBit := add(firstBit, 0x4)
}
// Check if lower 2 bits are all zero
if iszero(and(number_, 0x3)) {
number_ := shr(0x2, number_)
firstBit := add(firstBit, 0x2)
}
// Check if lowest bit is zero
if iszero(and(number_, 0x1)) {
firstBit := add(firstBit, 1)
}
// Add 1 to match the 1-based position counting
firstBit := add(firstBit, 1)
}
}
}
contracts/libraries/bytesSliceAndConcat.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.21 <=0.8.29;
library BytesSliceAndConcat {
// @dev taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
function bytesConcat(
bytes memory _preBytes,
bytes memory _postBytes
) internal pure returns (bytes memory tempBytes) {
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(
0x40,
and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
)
)
}
return tempBytes;
}
// @dev taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
function bytesSlice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory tempBytes) {
require(_length + 31 >= _length, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
}
contracts/libraries/dexCalcs.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.21 <=0.8.29;
import { BigMathMinified } from "./bigMathMinified.sol";
import { DexSlotsLink } from "./dexSlotsLink.sol";
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// @DEV ATTENTION: ON ANY CHANGES HERE, MAKE SURE THAT LOGIC IN VAULTS WILL STILL BE VALID.
// SOME CODE THERE ASSUMES DEXCALCS == LIQUIDITYCALCS.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/// @notice implements calculation methods used for Fluid Dex such as updated withdrawal / borrow limits.
library DexCalcs {
// constants used for BigMath conversion from and to storage
uint256 internal constant DEFAULT_EXPONENT_SIZE = 8;
uint256 internal constant DEFAULT_EXPONENT_MASK = 0xFF;
uint256 internal constant FOUR_DECIMALS = 1e4;
uint256 internal constant X14 = 0x3fff;
uint256 internal constant X18 = 0x3ffff;
uint256 internal constant X24 = 0xffffff;
uint256 internal constant X33 = 0x1ffffffff;
uint256 internal constant X64 = 0xffffffffffffffff;
///////////////////////////////////////////////////////////////////////////
////////// CALC LIMITS /////////
///////////////////////////////////////////////////////////////////////////
/// @dev calculates withdrawal limit before an operate execution:
/// amount of user supply that must stay supplied (not amount that can be withdrawn).
/// i.e. if user has supplied 100m and can withdraw 5M, this method returns the 95M, not the withdrawable amount 5M
/// @param userSupplyData_ user supply data packed uint256 from storage
/// @param userSupply_ current user supply amount already extracted from `userSupplyData_` and converted from BigMath
/// @return currentWithdrawalLimit_ current withdrawal limit updated for expansion since last interaction.
/// returned value is in raw for with interest mode, normal amount for interest free mode!
function calcWithdrawalLimitBeforeOperate(
uint256 userSupplyData_,
uint256 userSupply_
) internal view returns (uint256 currentWithdrawalLimit_) {
// @dev must support handling the case where timestamp is 0 (config is set but no interactions yet).
// first tx where timestamp is 0 will enter `if (lastWithdrawalLimit_ == 0)` because lastWithdrawalLimit_ is not set yet.
// returning max withdrawal allowed, which is not exactly right but doesn't matter because the first interaction must be
// a deposit anyway. Important is that it would not revert.
// Note the first time a deposit brings the user supply amount to above the base withdrawal limit, the active limit
// is the fully expanded limit immediately.
// extract last set withdrawal limit
uint256 lastWithdrawalLimit_ = (userSupplyData_ >> DexSlotsLink.BITS_USER_SUPPLY_PREVIOUS_WITHDRAWAL_LIMIT) &
X64;
lastWithdrawalLimit_ =
(lastWithdrawalLimit_ >> DEFAULT_EXPONENT_SIZE) <<
(lastWithdrawalLimit_ & DEFAULT_EXPONENT_MASK);
if (lastWithdrawalLimit_ == 0) {
// withdrawal limit is not activated. Max withdrawal allowed
return 0;
}
uint256 maxWithdrawableLimit_;
uint256 temp_;
unchecked {
// extract max withdrawable percent of user supply and
// calculate maximum withdrawable amount expandPercentage of user supply at full expansion duration elapsed
// e.g.: if 10% expandPercentage, meaning 10% is withdrawable after full expandDuration has elapsed.
// userSupply_ needs to be at least 1e73 to overflow max limit of ~1e77 in uint256 (no token in existence where this is possible).
maxWithdrawableLimit_ =
(((userSupplyData_ >> DexSlotsLink.BITS_USER_SUPPLY_EXPAND_PERCENT) & X14) * userSupply_) /
FOUR_DECIMALS;
// time elapsed since last withdrawal limit was set (in seconds)
// @dev last process timestamp is guaranteed to exist for withdrawal, as a supply must have happened before.
// last timestamp can not be > current timestamp
temp_ = block.timestamp - ((userSupplyData_ >> DexSlotsLink.BITS_USER_SUPPLY_LAST_UPDATE_TIMESTAMP) & X33);
}
// calculate withdrawable amount of expandPercent that is elapsed of expandDuration.
// e.g. if 60% of expandDuration has elapsed, then user should be able to withdraw 6% of user supply, down to 94%.
// Note: no explicit check for this needed, it is covered by setting minWithdrawalLimit_ if needed.
temp_ =
(maxWithdrawableLimit_ * temp_) /
// extract expand duration: After this, decrement won't happen (user can withdraw 100% of withdraw limit)
((userSupplyData_ >> DexSlotsLink.BITS_USER_SUPPLY_EXPAND_DURATION) & X24); // expand duration can never be 0
// calculate expanded withdrawal limit: last withdrawal limit - withdrawable amount.
// Note: withdrawable amount here can grow bigger than userSupply if timeElapsed is a lot bigger than expandDuration,
// which would cause the subtraction `lastWithdrawalLimit_ - withdrawableAmount_` to revert. In that case, set 0
// which will cause minimum (fully expanded) withdrawal limit to be set in lines below.
unchecked {
// underflow explicitly checked & handled
currentWithdrawalLimit_ = lastWithdrawalLimit_ > temp_ ? lastWithdrawalLimit_ - temp_ : 0;
// calculate minimum withdrawal limit: minimum amount of user supply that must stay supplied at full expansion.
// subtraction can not underflow as maxWithdrawableLimit_ is a percentage amount (<=100%) of userSupply_
temp_ = userSupply_ - maxWithdrawableLimit_;
}
// if withdrawal limit is decreased below minimum then set minimum
// (e.g. when more than expandDuration time has elapsed)
if (temp_ > currentWithdrawalLimit_) {
currentWithdrawalLimit_ = temp_;
}
}
/// @dev calculates withdrawal limit after an operate execution:
/// amount of user supply that must stay supplied (not amount that can be withdrawn).
/// i.e. if user has supplied 100m and can withdraw 5M, this method returns the 95M, not the withdrawable amount 5M
/// @param userSupplyData_ user supply data packed uint256 from storage
/// @param userSupply_ current user supply amount already extracted from `userSupplyData_` and added / subtracted with the executed operate amount
/// @param newWithdrawalLimit_ current withdrawal limit updated for expansion since last interaction, result from `calcWithdrawalLimitBeforeOperate`
/// @return withdrawalLimit_ updated withdrawal limit that should be written to storage. returned value is in
/// raw for with interest mode, normal amount for interest free mode!
function calcWithdrawalLimitAfterOperate(
uint256 userSupplyData_,
uint256 userSupply_,
uint256 newWithdrawalLimit_
) internal pure returns (uint256) {
// temp_ => base withdrawal limit. below this, maximum withdrawals are allowed
uint256 temp_ = (userSupplyData_ >> DexSlotsLink.BITS_USER_SUPPLY_BASE_WITHDRAWAL_LIMIT) & X18;
temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK);
// if user supply is below base limit then max withdrawals are allowed
if (userSupply_ < temp_) {
return 0;
}
// temp_ => withdrawal limit expandPercent (is in 1e2 decimals)
temp_ = (userSupplyData_ >> DexSlotsLink.BITS_USER_SUPPLY_EXPAND_PERCENT) & X14;
unchecked {
// temp_ => minimum withdrawal limit: userSupply - max withdrawable limit (userSupply * expandPercent))
// userSupply_ needs to be at least 1e73 to overflow max limit of ~1e77 in uint256 (no token in existence where this is possible).
// subtraction can not underflow as maxWithdrawableLimit_ is a percentage amount (<=100%) of userSupply_
temp_ = userSupply_ - ((userSupply_ * temp_) / FOUR_DECIMALS);
}
// if new (before operation) withdrawal limit is less than minimum limit then set minimum limit.
// e.g. can happen on new deposits. withdrawal limit is instantly fully expanded in a scenario where
// increased deposit amount outpaces withrawals.
if (temp_ > newWithdrawalLimit_) {
return temp_;
}
return newWithdrawalLimit_;
}
/// @dev calculates borrow limit before an operate execution:
/// total amount user borrow can reach (not borrowable amount in current operation).
/// i.e. if user has borrowed 50M and can still borrow 5M, this method returns the total 55M, not the borrowable amount 5M
/// @param userBorrowData_ user borrow data packed uint256 from storage
/// @param userBorrow_ current user borrow amount already extracted from `userBorrowData_`
/// @return currentBorrowLimit_ current borrow limit updated for expansion since last interaction. returned value is in
/// raw for with interest mode, normal amount for interest free mode!
function calcBorrowLimitBeforeOperate(
uint256 userBorrowData_,
uint256 userBorrow_
) internal view returns (uint256 currentBorrowLimit_) {
// @dev must support handling the case where timestamp is 0 (config is set but no interactions yet) -> base limit.
// first tx where timestamp is 0 will end up with maxExpansionLimit_ = 0 because userBorrow = 0, so maxExpandedBorrowLimit_ = 0,
// so currentBorrowLimit_ = 0, so it will enter currentBorrowLimit_ < temp_ when checking against base limit as expected.
// temp_ = extract borrow expand percent (is in 1e2 decimals)
uint256 temp_ = (userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_EXPAND_PERCENT) & X14;
uint256 maxExpansionLimit_;
uint256 maxExpandedBorrowLimit_;
unchecked {
// calculate max expansion limit: Max amount limit can expand to since last interaction
// userBorrow_ needs to be at least 1e73 to overflow max limit of ~1e77 in uint256 (no token in existence where this is possible).
maxExpansionLimit_ = ((userBorrow_ * temp_) / FOUR_DECIMALS);
// calculate max borrow limit: Max point limit can increase to since last interaction
maxExpandedBorrowLimit_ = userBorrow_ + maxExpansionLimit_;
}
// time elapsed since last borrow limit was set (in seconds)
unchecked {
// temp_ = timeElapsed_ (last timestamp can not be > current timestamp)
temp_ = block.timestamp - ((userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_LAST_UPDATE_TIMESTAMP) & X33); // extract last update timestamp
}
// currentBorrowLimit_ = expandedBorrowableAmount + extract last set borrow limit
currentBorrowLimit_ =
// calculate borrow limit expansion since last interaction for `expandPercent` that is elapsed of `expandDuration`.
// divisor is extract expand duration (after this, full expansion to expandPercentage happened).
((maxExpansionLimit_ * temp_) /
((userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_EXPAND_DURATION) & X24)) + // expand duration can never be 0
// extract last set borrow limit
BigMathMinified.fromBigNumber(
(userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_PREVIOUS_BORROW_LIMIT) & X64,
DEFAULT_EXPONENT_SIZE,
DEFAULT_EXPONENT_MASK
);
// if timeElapsed is bigger than expandDuration, new borrow limit would be > max expansion,
// so set to `maxExpandedBorrowLimit_` in that case.
// also covers the case where last process timestamp = 0 (timeElapsed would simply be very big)
if (currentBorrowLimit_ > maxExpandedBorrowLimit_) {
currentBorrowLimit_ = maxExpandedBorrowLimit_;
}
// temp_ = extract base borrow limit, if current limit is below this, then set base limit as current limit
temp_ = (userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_BASE_BORROW_LIMIT) & X18;
temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK);
if (currentBorrowLimit_ < temp_) {
return temp_;
}
// temp_ = extract hard max borrow limit. Above this user can never borrow (not expandable above)
temp_ = (userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_MAX_BORROW_LIMIT) & X18;
temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK);
if (currentBorrowLimit_ > temp_) {
return temp_;
}
}
/// @dev calculates borrow limit after an operate execution:
/// total amount user borrow can reach (not borrowable amount in current operation).
/// i.e. if user has borrowed 50M and can still borrow 5M, this method returns the total 55M, not the borrowable amount 5M
/// @param userBorrowData_ user borrow data packed uint256 from storage
/// @param userBorrow_ current user borrow amount already extracted from `userBorrowData_` and added / subtracted with the executed operate amount
/// @param newBorrowLimit_ current borrow limit updated for expansion since last interaction, result from `calcBorrowLimitBeforeOperate`
/// @return borrowLimit_ updated borrow limit that should be written to storage.
/// returned value is in raw for with interest mode, normal amount for interest free mode!
function calcBorrowLimitAfterOperate(
uint256 userBorrowData_,
uint256 userBorrow_,
uint256 newBorrowLimit_
) internal pure returns (uint256 borrowLimit_) {
// temp_ = extract borrow expand percent
uint256 temp_ = (userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_EXPAND_PERCENT) & X14; // (is in 1e2 decimals)
unchecked {
// borrowLimit_ = calculate maximum borrow limit at full expansion.
// userBorrow_ needs to be at least 1e73 to overflow max limit of ~1e77 in uint256 (no token in existence where this is possible).
borrowLimit_ = userBorrow_ + ((userBorrow_ * temp_) / FOUR_DECIMALS);
}
// temp_ = extract base borrow limit
temp_ = (userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_BASE_BORROW_LIMIT) & X18;
temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK);
if (borrowLimit_ < temp_) {
// below base limit, borrow limit is always base limit
return temp_;
}
// temp_ = extract hard max borrow limit. Above this user can never borrow (not expandable above)
temp_ = (userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_MAX_BORROW_LIMIT) & X18;
temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK);
// make sure fully expanded borrow limit is not above hard max borrow limit
if (borrowLimit_ > temp_) {
borrowLimit_ = temp_;
}
// if new borrow limit (from before operate) is > max borrow limit, set max borrow limit.
// (e.g. on a repay shrinking instantly to fully expanded borrow limit from new borrow amount. shrinking is instant)
if (newBorrowLimit_ > borrowLimit_) {
return borrowLimit_;
}
return newBorrowLimit_;
}
}
contracts/libraries/dexSlotsLink.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.21 <=0.8.29;
/// @notice library that helps in reading / working with storage slot data of Fluid Dex.
/// @dev as all data for Fluid Dex is internal, any data must be fetched directly through manual
/// slot reading through this library or, if gas usage is less important, through the FluidDexResolver.
library DexSlotsLink {
/// @dev storage slot for variables at Dex
uint256 internal constant DEX_VARIABLES_SLOT = 0;
/// @dev storage slot for variables2 at Dex
uint256 internal constant DEX_VARIABLES2_SLOT = 1;
/// @dev storage slot for total supply shares at Dex
uint256 internal constant DEX_TOTAL_SUPPLY_SHARES_SLOT = 2;
/// @dev storage slot for user supply mapping at Dex
uint256 internal constant DEX_USER_SUPPLY_MAPPING_SLOT = 3;
/// @dev storage slot for total borrow shares at Dex
uint256 internal constant DEX_TOTAL_BORROW_SHARES_SLOT = 4;
/// @dev storage slot for user borrow mapping at Dex
uint256 internal constant DEX_USER_BORROW_MAPPING_SLOT = 5;
/// @dev storage slot for oracle mapping at Dex
uint256 internal constant DEX_ORACLE_MAPPING_SLOT = 6;
/// @dev storage slot for range and threshold shifts at Dex
uint256 internal constant DEX_RANGE_THRESHOLD_SHIFTS_SLOT = 7;
/// @dev storage slot for center price shift at Dex
uint256 internal constant DEX_CENTER_PRICE_SHIFT_SLOT = 8;
// --------------------------------
// @dev stacked uint256 storage slots bits position data for each:
// UserSupplyData
uint256 internal constant BITS_USER_SUPPLY_ALLOWED = 0;
uint256 internal constant BITS_USER_SUPPLY_AMOUNT = 1;
uint256 internal constant BITS_USER_SUPPLY_PREVIOUS_WITHDRAWAL_LIMIT = 65;
uint256 internal constant BITS_USER_SUPPLY_LAST_UPDATE_TIMESTAMP = 129;
uint256 internal constant BITS_USER_SUPPLY_EXPAND_PERCENT = 162;
uint256 internal constant BITS_USER_SUPPLY_EXPAND_DURATION = 176;
uint256 internal constant BITS_USER_SUPPLY_BASE_WITHDRAWAL_LIMIT = 200;
// UserBorrowData
uint256 internal constant BITS_USER_BORROW_ALLOWED = 0;
uint256 internal constant BITS_USER_BORROW_AMOUNT = 1;
uint256 internal constant BITS_USER_BORROW_PREVIOUS_BORROW_LIMIT = 65;
uint256 internal constant BITS_USER_BORROW_LAST_UPDATE_TIMESTAMP = 129;
uint256 internal constant BITS_USER_BORROW_EXPAND_PERCENT = 162;
uint256 internal constant BITS_USER_BORROW_EXPAND_DURATION = 176;
uint256 internal constant BITS_USER_BORROW_BASE_BORROW_LIMIT = 200;
uint256 internal constant BITS_USER_BORROW_MAX_BORROW_LIMIT = 218;
// --------------------------------
/// @notice Calculating the slot ID for Dex contract for single mapping at `slot_` for `key_`
function calculateMappingStorageSlot(uint256 slot_, address key_) internal pure returns (bytes32) {
return keccak256(abi.encode(key_, slot_));
}
/// @notice Calculating the slot ID for Dex contract for double mapping at `slot_` for `key1_` and `key2_`
function calculateDoubleMappingStorageSlot(
uint256 slot_,
address key1_,
address key2_
) internal pure returns (bytes32) {
bytes32 intermediateSlot_ = keccak256(abi.encode(key1_, slot_));
return keccak256(abi.encode(key2_, intermediateSlot_));
}
}
contracts/liquidity/adminModule/structs.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.21 <=0.8.29;
abstract contract Structs {
struct AddressBool {
address addr;
bool value;
}
struct AddressUint256 {
address addr;
uint256 value;
}
/// @notice struct to set borrow rate data for version 1
struct RateDataV1Params {
///
/// @param token for rate data
address token;
///
/// @param kink in borrow rate. in 1e2: 100% = 10_000; 1% = 100
/// utilization below kink usually means slow increase in rate, once utilization is above kink borrow rate increases fast
uint256 kink;
///
/// @param rateAtUtilizationZero desired borrow rate when utilization is zero. in 1e2: 100% = 10_000; 1% = 100
/// i.e. constant minimum borrow rate
/// e.g. at utilization = 0.01% rate could still be at least 4% (rateAtUtilizationZero would be 400 then)
uint256 rateAtUtilizationZero;
///
/// @param rateAtUtilizationKink borrow rate when utilization is at kink. in 1e2: 100% = 10_000; 1% = 100
/// e.g. when rate should be 7% at kink then rateAtUtilizationKink would be 700
uint256 rateAtUtilizationKink;
///
/// @param rateAtUtilizationMax borrow rate when utilization is maximum at 100%. in 1e2: 100% = 10_000; 1% = 100
/// e.g. when rate should be 125% at 100% then rateAtUtilizationMax would be 12_500
uint256 rateAtUtilizationMax;
}
/// @notice struct to set borrow rate data for version 2
struct RateDataV2Params {
///
/// @param token for rate data
address token;
///
/// @param kink1 first kink in borrow rate. in 1e2: 100% = 10_000; 1% = 100
/// utilization below kink 1 usually means slow increase in rate, once utilization is above kink 1 borrow rate increases faster
uint256 kink1;
///
/// @param kink2 second kink in borrow rate. in 1e2: 100% = 10_000; 1% = 100
/// utilization below kink 2 usually means slow / medium increase in rate, once utilization is above kink 2 borrow rate increases fast
uint256 kink2;
///
/// @param rateAtUtilizationZero desired borrow rate when utilization is zero. in 1e2: 100% = 10_000; 1% = 100
/// i.e. constant minimum borrow rate
/// e.g. at utilization = 0.01% rate could still be at least 4% (rateAtUtilizationZero would be 400 then)
uint256 rateAtUtilizationZero;
///
/// @param rateAtUtilizationKink1 desired borrow rate when utilization is at first kink. in 1e2: 100% = 10_000; 1% = 100
/// e.g. when rate should be 7% at first kink then rateAtUtilizationKink would be 700
uint256 rateAtUtilizationKink1;
///
/// @param rateAtUtilizationKink2 desired borrow rate when utilization is at second kink. in 1e2: 100% = 10_000; 1% = 100
/// e.g. when rate should be 7% at second kink then rateAtUtilizationKink would be 1_200
uint256 rateAtUtilizationKink2;
///
/// @param rateAtUtilizationMax desired borrow rate when utilization is maximum at 100%. in 1e2: 100% = 10_000; 1% = 100
/// e.g. when rate should be 125% at 100% then rateAtUtilizationMax would be 12_500
uint256 rateAtUtilizationMax;
}
/// @notice struct to set token config
struct TokenConfig {
///
/// @param token address
address token;
///
/// @param fee charges on borrower's interest. in 1e2: 100% = 10_000; 1% = 100
uint256 fee;
///
/// @param threshold on when to update the storage slot. in 1e2: 100% = 10_000; 1% = 100
uint256 threshold;
///
/// @param maxUtilization maximum allowed utilization. in 1e2: 100% = 10_000; 1% = 100
/// set to 100% to disable and have default limit of 100% (avoiding SLOAD).
uint256 maxUtilization;
}
/// @notice struct to set user supply & withdrawal config
struct UserSupplyConfig {
///
/// @param user address
address user;
///
/// @param token address
address token;
///
/// @param mode: 0 = without interest. 1 = with interest
uint8 mode;
///
/// @param expandPercent withdrawal limit expand percent. in 1e2: 100% = 10_000; 1% = 100
/// Also used to calculate rate at which withdrawal limit should decrease (instant).
uint256 expandPercent;
///
/// @param expandDuration withdrawal limit expand duration in seconds.
/// used to calculate rate together with expandPercent
uint256 expandDuration;
///
/// @param baseWithdrawalLimit base limit, below this, user can withdraw the entire amount.
/// amount in raw (to be multiplied with exchange price) or normal depends on configured mode in user config for the token:
/// with interest -> raw, without interest -> normal
uint256 baseWithdrawalLimit;
}
/// @notice struct to set user borrow & payback config
struct UserBorrowConfig {
///
/// @param user address
address user;
///
/// @param token address
address token;
///
/// @param mode: 0 = without interest. 1 = with interest
uint8 mode;
///
/// @param expandPercent debt limit expand percent. in 1e2: 100% = 10_000; 1% = 100
/// Also used to calculate rate at which debt limit should decrease (instant).
uint256 expandPercent;
///
/// @param expandDuration debt limit expand duration in seconds.
/// used to calculate rate together with expandPercent
uint256 expandDuration;
///
/// @param baseDebtCeiling base borrow limit. until here, borrow limit remains as baseDebtCeiling
/// (user can borrow until this point at once without stepped expansion). Above this, automated limit comes in place.
/// amount in raw (to be multiplied with exchange price) or normal depends on configured mode in user config for the token:
/// with interest -> raw, without interest -> normal
uint256 baseDebtCeiling;
///
/// @param maxDebtCeiling max borrow ceiling, maximum amount the user can borrow.
/// amount in raw (to be multiplied with exchange price) or normal depends on configured mode in user config for the token:
/// with interest -> raw, without interest -> normal
uint256 maxDebtCeiling;
}
}
contracts/periphery/resolvers/dex/structs.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;
import { IFluidDexT1 } from "../../../protocols/dex/interfaces/iDexT1.sol";
import { Structs as FluidLiquidityResolverStructs } from "../liquidity/structs.sol";
abstract contract Structs {
struct DexState {
uint256 lastToLastStoredPrice;
uint256 lastStoredPrice; // price of pool after the most recent swap
uint256 centerPrice;
uint256 lastUpdateTimestamp;
uint256 lastPricesTimeDiff;
uint256 oracleCheckPoint;
uint256 oracleMapping;
uint256 totalSupplyShares;
uint256 totalBorrowShares;
bool isSwapAndArbitragePaused; // if true, only perfect functions will be usable
ShiftChanges shifts;
// below values have to be combined with Oracle price data at the VaultResolver
uint256 token0PerSupplyShare; // token0 amount per 1e18 supply shares
uint256 token1PerSupplyShare; // token1 amount per 1e18 supply shares
uint256 token0PerBorrowShare; // token0 amount per 1e18 borrow shares
uint256 token1PerBorrowShare; // token1 amount per 1e18 borrow shares
}
struct ShiftData {
uint256 oldUpper;
uint256 oldLower;
uint256 duration;
uint256 startTimestamp;
uint256 oldTime; // only for thresholdShift
}
struct CenterPriceShift {
uint256 shiftPercentage;
uint256 duration;
uint256 startTimestamp;
}
struct ShiftChanges {
bool isRangeChangeActive;
bool isThresholdChangeActive;
bool isCenterPriceShiftActive;
ShiftData rangeShift;
ShiftData thresholdShift;
CenterPriceShift centerPriceShift;
}
struct Configs {
bool isSmartCollateralEnabled;
bool isSmartDebtEnabled;
uint256 fee;
uint256 revenueCut;
uint256 upperRange;
uint256 lowerRange;
uint256 upperShiftThreshold;
uint256 lowerShiftThreshold;
uint256 shiftingTime;
address centerPriceAddress;
address hookAddress;
uint256 maxCenterPrice;
uint256 minCenterPrice;
uint256 utilizationLimitToken0;
uint256 utilizationLimitToken1;
uint256 maxSupplyShares;
uint256 maxBorrowShares;
}
// @dev note there might be other things that act as effective limits which are not fully considered here.
// e.g. such as maximum 5% oracle shift in one swap, withdraws & borrowing together affecting each other,
// shares being below max supply / borrow shares etc.
struct SwapLimitsAndAvailability {
// liquidity total amounts
uint liquiditySupplyToken0;
uint liquiditySupplyToken1;
uint liquidityBorrowToken0;
uint liquidityBorrowToken1;
// liquidity limits
uint liquidityWithdrawableToken0;
uint liquidityWithdrawableToken1;
uint liquidityBorrowableToken0;
uint liquidityBorrowableToken1;
// utilization limits based on config at Dex. (e.g. liquiditySupplyToken0 * Configs.utilizationLimitToken0 / 1e3)
uint utilizationLimitToken0;
uint utilizationLimitToken1;
// swappable amounts until utilization limit.
// In a swap that does both withdraw and borrow, the effective amounts might be less because withdraw / borrow affect each other
// (both increase utilization).
uint withdrawableUntilUtilizationLimitToken0; // x = totalSupply - totalBorrow / maxUtilizationPercentage
uint withdrawableUntilUtilizationLimitToken1;
uint borrowableUntilUtilizationLimitToken0; // x = maxUtilizationPercentage * totalSupply - totalBorrow.
uint borrowableUntilUtilizationLimitToken1;
// additional liquidity related data such as supply amount, limits, expansion etc.
FluidLiquidityResolverStructs.UserSupplyData liquidityUserSupplyDataToken0;
FluidLiquidityResolverStructs.UserSupplyData liquidityUserSupplyDataToken1;
// additional liquidity related data such as borrow amount, limits, expansion etc.
FluidLiquidityResolverStructs.UserBorrowData liquidityUserBorrowDataToken0;
FluidLiquidityResolverStructs.UserBorrowData liquidityUserBorrowDataToken1;
// liquidity token related data
FluidLiquidityResolverStructs.OverallTokenData liquidityTokenData0;
FluidLiquidityResolverStructs.OverallTokenData liquidityTokenData1;
}
struct DexEntireData {
address dex;
IFluidDexT1.ConstantViews constantViews;
IFluidDexT1.ConstantViews2 constantViews2;
Configs configs;
IFluidDexT1.PricesAndExchangePrice pex;
IFluidDexT1.CollateralReserves colReserves;
IFluidDexT1.DebtReserves debtReserves;
DexState dexState;
SwapLimitsAndAvailability limitsAndAvailability;
}
// amounts are always in normal (for withInterest already multiplied with exchange price)
struct UserSupplyData {
bool isAllowed;
uint256 supply; // user supply amount/shares
// the withdrawal limit (e.g. if 10% is the limit, and 100M is supplied, it would be 90M)
uint256 withdrawalLimit;
uint256 lastUpdateTimestamp;
uint256 expandPercent; // withdrawal limit expand percent in 1e2
uint256 expandDuration; // withdrawal limit expand duration in seconds
uint256 baseWithdrawalLimit;
// the current actual max withdrawable amount (e.g. if 10% is the limit, and 100M is supplied, it would be 10M)
uint256 withdrawableUntilLimit;
uint256 withdrawable; // actual currently withdrawable amount (supply - withdrawal Limit) & considering balance
// liquidity related data such as supply amount, limits, expansion etc.
FluidLiquidityResolverStructs.UserSupplyData liquidityUserSupplyDataToken0;
FluidLiquidityResolverStructs.UserSupplyData liquidityUserSupplyDataToken1;
// liquidity token related data
FluidLiquidityResolverStructs.OverallTokenData liquidityTokenData0;
FluidLiquidityResolverStructs.OverallTokenData liquidityTokenData1;
}
// amounts are always in normal (for withInterest already multiplied with exchange price)
struct UserBorrowData {
bool isAllowed;
uint256 borrow; // user borrow amount/shares
uint256 borrowLimit;
uint256 lastUpdateTimestamp;
uint256 expandPercent;
uint256 expandDuration;
uint256 baseBorrowLimit;
uint256 maxBorrowLimit;
uint256 borrowableUntilLimit; // borrowable amount until any borrow limit (incl. max utilization limit)
uint256 borrowable; // actual currently borrowable amount (borrow limit - already borrowed) & considering balance, max utilization
// liquidity related data such as borrow amount, limits, expansion etc.
FluidLiquidityResolverStructs.UserBorrowData liquidityUserBorrowDataToken0;
FluidLiquidityResolverStructs.UserBorrowData liquidityUserBorrowDataToken1;
// liquidity token related data
FluidLiquidityResolverStructs.OverallTokenData liquidityTokenData0;
FluidLiquidityResolverStructs.OverallTokenData liquidityTokenData1;
}
}
contracts/periphery/resolvers/dex/variables.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;
import { IFluidLiquidityResolver } from "../liquidity/iLiquidityResolver.sol";
import { IFluidDexFactory } from "../../../protocols/dex/interfaces/iDexFactory.sol";
interface IFluidLiquidity {
function readFromStorage(bytes32 slot_) external view returns (uint256 result_);
}
abstract contract Variables {
IFluidDexFactory public immutable FACTORY;
IFluidLiquidity public immutable LIQUIDITY;
IFluidLiquidityResolver public immutable LIQUIDITY_RESOLVER;
/// @dev Address of contract used for deploying center price & hook related contract
address public immutable DEPLOYER_CONTRACT;
uint256 internal constant X2 = 0x3;
uint256 internal constant X3 = 0x7;
uint256 internal constant X5 = 0x1f;
uint256 internal constant X7 = 0x7f;
uint256 internal constant X8 = 0xff;
uint256 internal constant X9 = 0x1ff;
uint256 internal constant X10 = 0x3ff;
uint256 internal constant X11 = 0x7ff;
uint256 internal constant X14 = 0x3fff;
uint256 internal constant X16 = 0xffff;
uint256 internal constant X17 = 0x1ffff;
uint256 internal constant X20 = 0xfffff;
uint256 internal constant X22 = 0x3fffff;
uint256 internal constant X23 = 0x7fffff;
uint256 internal constant X24 = 0xffffff;
uint256 internal constant X28 = 0xfffffff;
uint256 internal constant X30 = 0x3fffffff;
uint256 internal constant X32 = 0xffffffff;
uint256 internal constant X33 = 0x1ffffffff;
uint256 internal constant X40 = 0xffffffffff;
uint256 internal constant X64 = 0xffffffffffffffff;
uint256 internal constant X128 = 0xffffffffffffffffffffffffffffffff;
/// @dev address that is mapped to the chain native token
address internal constant NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
constructor(address factory_, address liquidity_, address liquidityResolver_, address deployer_) {
FACTORY = IFluidDexFactory(factory_);
LIQUIDITY = IFluidLiquidity(liquidity_);
LIQUIDITY_RESOLVER = IFluidLiquidityResolver(liquidityResolver_);
DEPLOYER_CONTRACT = deployer_;
}
}
contracts/periphery/resolvers/liquidity/iLiquidityResolver.sol
//SPDX-License-Identifier: MIT
pragma solidity >=0.8.21 <=0.8.29;
import { Structs as LiquidityStructs } from "../../../periphery/resolvers/liquidity/structs.sol";
interface IFluidLiquidityResolver {
/// @notice gets the `revenueAmount_` for a `token_`.
function getRevenue(address token_) external view returns (uint256 revenueAmount_);
/// @notice address of contract that gets sent the revenue. Configurable by governance
function getRevenueCollector() external view returns (address);
/// @notice Liquidity contract paused status: status = 1 -> normal. status = 2 -> paused.
function getStatus() external view returns (uint256);
/// @notice checks if `auth_` is an allowed auth on Liquidity.
/// Auths can set most config values. E.g. contracts that automate certain flows like e.g. adding a new fToken.
/// Governance can add/remove auths. Governance is auth by default.
function isAuth(address auth_) external view returns (uint256);
/// @notice checks if `guardian_` is an allowed Guardian on Liquidity.
/// Guardians can pause lower class users.
/// Governance can add/remove guardians. Governance is guardian by default.
function isGuardian(address guardian_) external view returns (uint256);
/// @notice gets user class for `user_`. Class defines which protocols can be paused by guardians.
/// Currently there are 2 classes: 0 can be paused by guardians. 1 cannot be paused by guardians.
/// New protocols are added as class 0 and will be upgraded to 1 over time.
function getUserClass(address user_) external view returns (uint256);
/// @notice gets exchangePricesAndConfig packed uint256 storage slot for `token_`.
function getExchangePricesAndConfig(address token_) external view returns (uint256);
/// @notice gets rateConfig packed uint256 storage slot for `token_`.
function getRateConfig(address token_) external view returns (uint256);
/// @notice gets totalAmounts packed uint256 storage slot for `token_`.
function getTotalAmounts(address token_) external view returns (uint256);
/// @notice gets configs2 packed uint256 storage slot for `token_`.
function getConfigs2(address token_) external view returns (uint256);
/// @notice gets userSupply data packed uint256 storage slot for `user_` and `token_`.
function getUserSupply(address user_, address token_) external view returns (uint256);
/// @notice gets userBorrow data packed uint256 storage slot for `user_` and `token_`.
function getUserBorrow(address user_, address token_) external view returns (uint256);
/// @notice returns all `listedTokens_` at the Liquidity contract. Once configured, a token can never be removed.
function listedTokens() external view returns (address[] memory listedTokens_);
/// @notice get the Rate config data `rateData_` for a `token_` compiled from the packed uint256 rateConfig storage slot
function getTokenRateData(address token_) external view returns (LiquidityStructs.RateData memory rateData_);
/// @notice get the Rate config datas `rateDatas_` for multiple `tokens_` compiled from the packed uint256 rateConfig storage slot
function getTokensRateData(
address[] calldata tokens_
) external view returns (LiquidityStructs.RateData[] memory rateDatas_);
/// @notice returns general data for `token_` such as rates, exchange prices, utilization, fee, total amounts etc.
function getOverallTokenData(
address token_
) external view returns (LiquidityStructs.OverallTokenData memory overallTokenData_);
/// @notice returns general data for multiple `tokens_` such as rates, exchange prices, utilization, fee, total amounts etc.
function getOverallTokensData(
address[] calldata tokens_
) external view returns (LiquidityStructs.OverallTokenData[] memory overallTokensData_);
/// @notice returns general data for all `listedTokens()` such as rates, exchange prices, utilization, fee, total amounts etc.
function getAllOverallTokensData()
external
view
returns (LiquidityStructs.OverallTokenData[] memory overallTokensData_);
/// @notice returns `user_` supply data and general data (such as rates, exchange prices, utilization, fee, total amounts etc.) for `token_`
function getUserSupplyData(
address user_,
address token_
)
external
view
returns (
LiquidityStructs.UserSupplyData memory userSupplyData_,
LiquidityStructs.OverallTokenData memory overallTokenData_
);
/// @notice returns `user_` supply data and general data (such as rates, exchange prices, utilization, fee, total amounts etc.) for multiple `tokens_`
function getUserMultipleSupplyData(
address user_,
address[] calldata tokens_
)
external
view
returns (
LiquidityStructs.UserSupplyData[] memory userSuppliesData_,
LiquidityStructs.OverallTokenData[] memory overallTokensData_
);
/// @notice returns `user_` borrow data and general data (such as rates, exchange prices, utilization, fee, total amounts etc.) for `token_`
function getUserBorrowData(
address user_,
address token_
)
external
view
returns (
LiquidityStructs.UserBorrowData memory userBorrowData_,
LiquidityStructs.OverallTokenData memory overallTokenData_
);
/// @notice returns `user_` borrow data and general data (such as rates, exchange prices, utilization, fee, total amounts etc.) for multiple `tokens_`
function getUserMultipleBorrowData(
address user_,
address[] calldata tokens_
)
external
view
returns (
LiquidityStructs.UserBorrowData[] memory userBorrowingsData_,
LiquidityStructs.OverallTokenData[] memory overallTokensData_
);
/// @notice returns `user_` supply data and general data (such as rates, exchange prices, utilization, fee, total amounts etc.) for multiple `supplyTokens_`
/// and returns `user_` borrow data and general data (such as rates, exchange prices, utilization, fee, total amounts etc.) for multiple `borrowTokens_`
function getUserMultipleBorrowSupplyData(
address user_,
address[] calldata supplyTokens_,
address[] calldata borrowTokens_
)
external
view
returns (
LiquidityStructs.UserSupplyData[] memory userSuppliesData_,
LiquidityStructs.OverallTokenData[] memory overallSupplyTokensData_,
LiquidityStructs.UserBorrowData[] memory userBorrowingsData_,
LiquidityStructs.OverallTokenData[] memory overallBorrowTokensData_
);
}
contracts/periphery/resolvers/liquidity/structs.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.21 <=0.8.29;
import { Structs as AdminModuleStructs } from "../../../liquidity/adminModule/structs.sol";
abstract contract Structs {
struct RateData {
uint256 version;
AdminModuleStructs.RateDataV1Params rateDataV1;
AdminModuleStructs.RateDataV2Params rateDataV2;
}
struct OverallTokenData {
uint256 borrowRate;
uint256 supplyRate;
uint256 fee; // revenue fee
uint256 lastStoredUtilization;
uint256 storageUpdateThreshold;
uint256 lastUpdateTimestamp;
uint256 supplyExchangePrice;
uint256 borrowExchangePrice;
uint256 supplyRawInterest;
uint256 supplyInterestFree;
uint256 borrowRawInterest;
uint256 borrowInterestFree;
uint256 totalSupply;
uint256 totalBorrow;
uint256 revenue;
uint256 maxUtilization; // maximum allowed utilization
RateData rateData;
}
// amounts are always in normal (for withInterest already multiplied with exchange price)
struct UserSupplyData {
bool modeWithInterest; // true if mode = with interest, false = without interest
uint256 supply; // user supply amount
// the withdrawal limit (e.g. if 10% is the limit, and 100M is supplied, it would be 90M)
uint256 withdrawalLimit;
uint256 lastUpdateTimestamp;
uint256 expandPercent; // withdrawal limit expand percent in 1e2
uint256 expandDuration; // withdrawal limit expand duration in seconds
uint256 baseWithdrawalLimit;
// the current actual max withdrawable amount (e.g. if 10% is the limit, and 100M is supplied, it would be 10M)
uint256 withdrawableUntilLimit;
uint256 withdrawable; // actual currently withdrawable amount (supply - withdrawal Limit) & considering balance
// internal decay limit values
uint256 decayEndTimestamp; // computed from last update timestamp + decay duration. when decay will fully end.
uint256 decayAmount; // as in storage adjusted for decayed time leftover
}
// amounts are always in normal (for withInterest already multiplied with exchange price)
struct UserBorrowData {
bool modeWithInterest; // true if mode = with interest, false = without interest
uint256 borrow; // user borrow amount
uint256 borrowLimit;
uint256 lastUpdateTimestamp;
uint256 expandPercent;
uint256 expandDuration;
uint256 baseBorrowLimit;
uint256 maxBorrowLimit;
uint256 borrowableUntilLimit; // borrowable amount until any borrow limit (incl. max utilization limit)
uint256 borrowable; // actual currently borrowable amount (borrow limit - already borrowed) & considering balance, max utilization
uint256 borrowLimitUtilization; // borrow limit for `maxUtilization`
}
}
contracts/protocols/dex/interfaces/iDexFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
interface IFluidDexFactory {
/// @notice Global auth is auth for all dexes
function isGlobalAuth(address auth_) external view returns (bool);
/// @notice Dex auth is auth for a specific dex
function isDexAuth(address vault_, address auth_) external view returns (bool);
/// @notice Total dexes deployed.
function totalDexes() external view returns (uint256);
/// @notice Compute dexAddress
function getDexAddress(uint256 dexId_) external view returns (address);
/// @notice read uint256 `result_` for a storage `slot_` key
function readFromStorage(bytes32 slot_) external view returns (uint256 result_);
}
contracts/protocols/dex/interfaces/iDexT1.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
interface IFluidDexT1 {
error FluidDexError(uint256 errorId);
/// @notice used to simulate swap to find the output amount
error FluidDexSwapResult(uint256 amountOut);
error FluidDexPerfectLiquidityOutput(uint256 token0Amt, uint token1Amt);
error FluidDexSingleTokenOutput(uint256 tokenAmt);
error FluidDexLiquidityOutput(uint256 shares);
error FluidDexPricesAndExchangeRates(PricesAndExchangePrice pex_);
/// @notice returns the dex id
function DEX_ID() external view returns (uint256);
/// @notice reads uint256 data `result_` from storage at a bytes32 storage `slot_` key.
function readFromStorage(bytes32 slot_) external view returns (uint256 result_);
struct Implementations {
address shift;
address admin;
address colOperations;
address debtOperations;
address perfectOperationsAndOracle;
}
struct ConstantViews {
uint256 dexId;
address liquidity;
address factory;
Implementations implementations;
address deployerContract;
address token0;
address token1;
bytes32 supplyToken0Slot;
bytes32 borrowToken0Slot;
bytes32 supplyToken1Slot;
bytes32 borrowToken1Slot;
bytes32 exchangePriceToken0Slot;
bytes32 exchangePriceToken1Slot;
uint256 oracleMapping;
}
struct ConstantViews2 {
uint token0NumeratorPrecision;
uint token0DenominatorPrecision;
uint token1NumeratorPrecision;
uint token1DenominatorPrecision;
}
struct PricesAndExchangePrice {
uint lastStoredPrice; // last stored price in 1e27 decimals
uint centerPrice; // last stored price in 1e27 decimals
uint upperRange; // price at upper range in 1e27 decimals
uint lowerRange; // price at lower range in 1e27 decimals
uint geometricMean; // geometric mean of upper range & lower range in 1e27 decimals
uint supplyToken0ExchangePrice;
uint borrowToken0ExchangePrice;
uint supplyToken1ExchangePrice;
uint borrowToken1ExchangePrice;
}
struct CollateralReserves {
uint token0RealReserves;
uint token1RealReserves;
uint token0ImaginaryReserves;
uint token1ImaginaryReserves;
}
struct DebtReserves {
uint token0Debt;
uint token1Debt;
uint token0RealReserves;
uint token1RealReserves;
uint token0ImaginaryReserves;
uint token1ImaginaryReserves;
}
function getCollateralReserves(
uint geometricMean_,
uint upperRange_,
uint lowerRange_,
uint token0SupplyExchangePrice_,
uint token1SupplyExchangePrice_
) external view returns (CollateralReserves memory c_);
function getDebtReserves(
uint geometricMean_,
uint upperRange_,
uint lowerRange_,
uint token0BorrowExchangePrice_,
uint token1BorrowExchangePrice_
) external view returns (DebtReserves memory d_);
// reverts with FluidDexPricesAndExchangeRates(pex_);
function getPricesAndExchangePrices() external;
function constantsView() external view returns (ConstantViews memory constantsView_);
function constantsView2() external view returns (ConstantViews2 memory constantsView2_);
struct Oracle {
uint twap1by0; // TWAP price
uint lowestPrice1by0; // lowest price point
uint highestPrice1by0; // highest price point
uint twap0by1; // TWAP price
uint lowestPrice0by1; // lowest price point
uint highestPrice0by1; // highest price point
}
/// @dev This function allows users to swap a specific amount of input tokens for output tokens
/// @param swap0to1_ Direction of swap. If true, swaps token0 for token1; if false, swaps token1 for token0
/// @param amountIn_ The exact amount of input tokens to swap
/// @param amountOutMin_ The minimum amount of output tokens the user is willing to accept
/// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with amountOut_
/// @return amountOut_ The amount of output tokens received from the swap
function swapIn(
bool swap0to1_,
uint256 amountIn_,
uint256 amountOutMin_,
address to_
) external payable returns (uint256 amountOut_);
/// @dev Swap tokens with perfect amount in and callback functionality
/// @param swap0to1_ Direction of swap. If true, swaps token0 for token1; if false, swaps token1 for token0
/// @param amountIn_ The exact amount of tokens to swap in
/// @param amountOutMin_ The minimum amount of tokens to receive after swap
/// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with amountOut_
/// @return amountOut_ The amount of output tokens received from the swap
function swapInWithCallback(
bool swap0to1_,
uint256 amountIn_,
uint256 amountOutMin_,
address to_
) external payable returns (uint256 amountOut_);
/// @dev Swap tokens with perfect amount out
/// @param swap0to1_ Direction of swap. If true, swaps token0 for token1; if false, swaps token1 for token0
/// @param amountOut_ The exact amount of tokens to receive after swap
/// @param amountInMax_ Maximum amount of tokens to swap in
/// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with amountIn_
/// @return amountIn_ The amount of input tokens used for the swap
function swapOut(
bool swap0to1_,
uint256 amountOut_,
uint256 amountInMax_,
address to_
) external payable returns (uint256 amountIn_);
/// @dev Swap tokens with perfect amount out and callback functionality
/// @param swap0to1_ Direction of swap. If true, swaps token0 for token1; if false, swaps token1 for token0
/// @param amountOut_ The exact amount of tokens to receive after swap
/// @param amountInMax_ Maximum amount of tokens to swap in
/// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with amountIn_
/// @return amountIn_ The amount of input tokens used for the swap
function swapOutWithCallback(
bool swap0to1_,
uint256 amountOut_,
uint256 amountInMax_,
address to_
) external payable returns (uint256 amountIn_);
/// @dev Deposit tokens in equal proportion to the current pool ratio
/// @param shares_ The number of shares to mint
/// @param maxToken0Deposit_ Maximum amount of token0 to deposit
/// @param maxToken1Deposit_ Maximum amount of token1 to deposit
/// @param estimate_ If true, function will revert with estimated deposit amounts without executing the deposit
/// @return token0Amt_ Amount of token0 deposited
/// @return token1Amt_ Amount of token1 deposited
function depositPerfect(
uint shares_,
uint maxToken0Deposit_,
uint maxToken1Deposit_,
bool estimate_
) external payable returns (uint token0Amt_, uint token1Amt_);
/// @dev This function allows users to withdraw a perfect amount of collateral liquidity
/// @param shares_ The number of shares to withdraw
/// @param minToken0Withdraw_ The minimum amount of token0 the user is willing to accept
/// @param minToken1Withdraw_ The minimum amount of token1 the user is willing to accept
/// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with token0Amt_ & token1Amt_
/// @return token0Amt_ The amount of token0 withdrawn
/// @return token1Amt_ The amount of token1 withdrawn
function withdrawPerfect(
uint shares_,
uint minToken0Withdraw_,
uint minToken1Withdraw_,
address to_
) external returns (uint token0Amt_, uint token1Amt_);
/// @dev This function allows users to borrow tokens in equal proportion to the current debt pool ratio
/// @param shares_ The number of shares to borrow
/// @param minToken0Borrow_ Minimum amount of token0 to borrow
/// @param minToken1Borrow_ Minimum amount of token1 to borrow
/// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with token0Amt_ & token1Amt_
/// @return token0Amt_ Amount of token0 borrowed
/// @return token1Amt_ Amount of token1 borrowed
function borrowPerfect(
uint shares_,
uint minToken0Borrow_,
uint minToken1Borrow_,
address to_
) external returns (uint token0Amt_, uint token1Amt_);
/// @dev This function allows users to pay back borrowed tokens in equal proportion to the current debt pool ratio
/// @param shares_ The number of shares to pay back
/// @param maxToken0Payback_ Maximum amount of token0 to pay back
/// @param maxToken1Payback_ Maximum amount of token1 to pay back
/// @param estimate_ If true, function will revert with estimated payback amounts without executing the payback
/// @return token0Amt_ Amount of token0 paid back
/// @return token1Amt_ Amount of token1 paid back
function paybackPerfect(
uint shares_,
uint maxToken0Payback_,
uint maxToken1Payback_,
bool estimate_
) external payable returns (uint token0Amt_, uint token1Amt_);
/// @dev This function allows users to deposit tokens in any proportion into the col pool
/// @param token0Amt_ The amount of token0 to deposit
/// @param token1Amt_ The amount of token1 to deposit
/// @param minSharesAmt_ The minimum amount of shares the user expects to receive
/// @param estimate_ If true, function will revert with estimated shares without executing the deposit
/// @return shares_ The amount of shares minted for the deposit
function deposit(
uint token0Amt_,
uint token1Amt_,
uint minSharesAmt_,
bool estimate_
) external payable returns (uint shares_);
/// @dev This function allows users to withdraw tokens in any proportion from the col pool
/// @param token0Amt_ The amount of token0 to withdraw
/// @param token1Amt_ The amount of token1 to withdraw
/// @param maxSharesAmt_ The maximum number of shares the user is willing to burn
/// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with shares_
/// @return shares_ The number of shares burned for the withdrawal
function withdraw(
uint token0Amt_,
uint token1Amt_,
uint maxSharesAmt_,
address to_
) external returns (uint shares_);
/// @dev This function allows users to borrow tokens in any proportion from the debt pool
/// @param token0Amt_ The amount of token0 to borrow
/// @param token1Amt_ The amount of token1 to borrow
/// @param maxSharesAmt_ The maximum amount of shares the user is willing to receive
/// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with shares_
/// @return shares_ The amount of borrow shares minted to represent the borrowed amount
function borrow(uint token0Amt_, uint token1Amt_, uint maxSharesAmt_, address to_) external returns (uint shares_);
/// @dev This function allows users to payback tokens in any proportion to the debt pool
/// @param token0Amt_ The amount of token0 to payback
/// @param token1Amt_ The amount of token1 to payback
/// @param minSharesAmt_ The minimum amount of shares the user expects to burn
/// @param estimate_ If true, function will revert with estimated shares without executing the payback
/// @return shares_ The amount of borrow shares burned for the payback
function payback(
uint token0Amt_,
uint token1Amt_,
uint minSharesAmt_,
bool estimate_
) external payable returns (uint shares_);
/// @dev This function allows users to withdraw their collateral with perfect shares in one token
/// @param shares_ The number of shares to burn for withdrawal
/// @param minToken0_ The minimum amount of token0 the user expects to receive (set to 0 if withdrawing in token1)
/// @param minToken1_ The minimum amount of token1 the user expects to receive (set to 0 if withdrawing in token0)
/// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with withdrawAmt_
/// @return withdrawAmt_ The amount of tokens withdrawn in the chosen token
function withdrawPerfectInOneToken(
uint shares_,
uint minToken0_,
uint minToken1_,
address to_
) external returns (uint withdrawAmt_);
/// @dev This function allows users to payback their debt with perfect shares in one token
/// @param shares_ The number of shares to burn for payback
/// @param maxToken0_ The maximum amount of token0 the user is willing to pay (set to 0 if paying back in token1)
/// @param maxToken1_ The maximum amount of token1 the user is willing to pay (set to 0 if paying back in token0)
/// @param estimate_ If true, the function will revert with the estimated payback amount without executing the payback
/// @return paybackAmt_ The amount of tokens paid back in the chosen token
function paybackPerfectInOneToken(
uint shares_,
uint maxToken0_,
uint maxToken1_,
bool estimate_
) external payable returns (uint paybackAmt_);
/// @dev the oracle assumes last set price of pool till the next swap happens.
/// There's a possibility that during that time some interest is generated hence the last stored price is not the 100% correct price for the whole duration
/// but the difference due to interest will be super low so this difference is ignored
/// For example 2 swaps happened 10min (600 seconds) apart and 1 token has 10% higher interest than other.
/// then that token will accrue about 10% * 600 / secondsInAYear = ~0.0002%
/// @param secondsAgos_ array of seconds ago for which TWAP is needed. If user sends [10, 30, 60] then twaps_ will return [10-0, 30-10, 60-30]
/// @return twaps_ twap price, lowest price (aka minima) & highest price (aka maxima) between secondsAgo checkpoints
/// @return currentPrice_ price of pool after the most recent swap
function oraclePrice(uint[] memory secondsAgos_) external view returns (Oracle[] memory twaps_, uint currentPrice_);
}
Compiler settingsShow
{
"optimizer": {
"runs": 1000,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.