Verified contractExactBUSL-1.1
FluidDexV2Router
Address0xf10ef09d71ef87cc2a63de6b130cc150ae3c56b4
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.36
- Same code
Only this contract
Details
- Compiler
- solc 0.8.36+commit.8a079791
- Language
- solidity
- Optimization
- Yes, 10,000,000 runs
- EVM version
- cancun
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,425,715
- Creation transaction
- 0x239d4d9638…e651ee8b87
15 files
- contracts/periphery/dexV2/router/main.solmain8.69 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.77 KB
- contracts/libraries/access/liquidityGovernanceAuth.sol1.79 KB
- contracts/libraries/errorTypes.sol1.67 KB
- contracts/libraries/pendingTransfers.sol9.77 KB
- contracts/libraries/safeTransfer.sol4.08 KB
- contracts/periphery/dexV2/router/error.sol141 B
- contracts/periphery/dexV2/router/errorTypes.sol2.54 KB
- contracts/periphery/dexV2/router/events.sol649 B
- contracts/periphery/dexV2/router/helpers.sol15.35 KB
- contracts/periphery/dexV2/router/interfaces.sol844 B
- contracts/periphery/dexV2/router/structs.sol649 B
- contracts/periphery/dexV2/router/variables.sol3.03 KB
- contracts/protocols/dexV2/dexTypes/common/d3d4common/structs.sol13.29 KB
- contracts/protocols/dexV2/interfaces/iDexV2.sol4.31 KB
contracts/periphery/dexV2/router/main.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./helpers.sol";
/// @title FluidDexV2Router
/// @notice Stateless swap router for the FluidDexV2 singleton: exact-input and exact-output swaps along a path of D3
/// and D4 pools in one transaction, paid by the caller and delivered to a recipient, plus the matching quotes.
/// Opens the DexV2 operation, runs the hops through `operate`, settles every pending leg and refunds unused
/// native value. Holds no funds between transactions and is replaced by redeploy.
/// @dev Implements `IDexV2Callbacks`. ERC20 inputs are pulled from the caller with `transferFrom` inside `dexCallback`
/// (approve the router, not the dex); native inputs are sent as `msg.value` and the unused part is refunded.
/// Native outputs are paid to `to_` by the dex, which must accept them. Standard ERC20 tokens only (DexV2 base
/// notes). See SPEC.md in this folder.
contract FluidDexV2Router is Helpers {
constructor(address dexV2_, address liquidity_) ImmutableVariables(dexV2_, liquidity_) {}
/// @notice Swaps exactly `amountIn_` of `path_[0]` into at least `amountOutMin_` of the last token of the path.
/// @param path_ tokens of the route, `path_[i]` swapped into `path_[i + 1]`; `0xEeee…EEeE` for the native token
/// @param hops_ the pool of each neighbouring pair of the path, `hops_.length == path_.length - 1`
/// @param amountIn_ exact input, in token units; for a native input send it as `msg.value`
/// @param amountOutMin_ floor for the output of the last hop, in token units
/// @param to_ receives the output (the dex pays it directly); must accept native tokens for a native output
/// @param deadline_ last `block.timestamp` at which the swap may execute
/// @return amountOut_ output of the last hop, delivered to `to_`
function swapIn(
address[] calldata path_,
Hop[] calldata hops_,
uint256 amountIn_,
uint256 amountOutMin_,
address to_,
uint256 deadline_
) external payable _handleMsgDetails returns (uint256 amountOut_) {
_validateSwap(path_, hops_, to_, deadline_);
amountOut_ = _startSwap(abi.encode(OPERATION_SWAP_IN, path_, hops_, amountIn_, amountOutMin_, to_));
}
/// @notice Swaps at most `amountInMax_` of `path_[0]` into exactly `amountOut_` of the last token of the path.
/// @param path_ tokens of the route, `path_[i]` swapped into `path_[i + 1]`; `0xEeee…EEeE` for the native token
/// @param hops_ the pool of each neighbouring pair of the path, `hops_.length == path_.length - 1`
/// @param amountOut_ exact output, in token units
/// @param amountInMax_ cap for the input of the first hop, in token units; for a native input send at least the cap
/// as `msg.value`, the unused part is refunded
/// @param to_ receives the output (the dex pays it directly); must accept native tokens for a native output
/// @param deadline_ last `block.timestamp` at which the swap may execute
/// @return amountIn_ input of the first hop, taken from the caller
function swapOut(
address[] calldata path_,
Hop[] calldata hops_,
uint256 amountOut_,
uint256 amountInMax_,
address to_,
uint256 deadline_
) external payable _handleMsgDetails returns (uint256 amountIn_) {
_validateSwap(path_, hops_, to_, deadline_);
amountIn_ = _startSwap(abi.encode(OPERATION_SWAP_OUT, path_, hops_, amountOut_, amountInMax_, to_));
}
/// @notice Output `swapIn` would deliver for `amountIn_` along the path at the current state, with the real swap
/// engine (dynamic fees, controller fees, every limit of the swap modules).
/// @dev Not a view: the hops run inside an operation that is then reverted (`PendingTransfersNotCleared` carries
/// the result). Call through `eth_call` with a non-zero `from` (the zero address is refused, 220007); a
/// transaction would only pay gas. A swap the modules refuse reverts with their error. Only the hops run:
/// nothing of the settle is checked (the caller's balance and allowance, the native value, the Liquidity
/// limits a settle can meet, pending left by a third party), so a quote can return where the swap reverts.
function quoteSwapIn(
address[] calldata path_,
Hop[] calldata hops_,
uint256 amountIn_
) external _handleQuoteDetails returns (uint256 amountOut_) {
_validatePath(path_, hops_);
amountOut_ = _startQuote(abi.encode(OPERATION_QUOTE_IN, path_, hops_, amountIn_));
}
/// @notice Input `swapOut` would take for `amountOut_` along the path at the current state; see `quoteSwapIn`.
function quoteSwapOut(
address[] calldata path_,
Hop[] calldata hops_,
uint256 amountOut_
) external _handleQuoteDetails returns (uint256 amountIn_) {
_validatePath(path_, hops_);
amountIn_ = _startQuote(abi.encode(OPERATION_QUOTE_OUT, path_, hops_, amountOut_));
}
/// @notice Called by the dex inside `startOperation`: runs the hops of the operation the router opened and, for a
/// swap, settles every pending leg. Quotes return without settling (see `quoteSwapIn`).
function startOperationCallback(bytes calldata data_) external returns (bytes memory) {
if (msg.sender != address(DEX_V2) || _msgSender() == address(0)) {
revert FluidDexV2RouterError(ErrorTypes.DexV2Router__UnauthorizedCallback);
}
// the data is the operation id followed by its parameters, as the entry point encoded them: the id is the
// first word, the operation decodes the whole data once
uint256 operation_ = uint256(bytes32(data_[:32]));
if (operation_ == OPERATION_SWAP_IN) return _operationSwapIn(data_);
if (operation_ == OPERATION_SWAP_OUT) return _operationSwapOut(data_);
if (operation_ == OPERATION_QUOTE_IN) return _operationQuoteIn(data_);
if (operation_ == OPERATION_QUOTE_OUT) return _operationQuoteOut(data_);
revert FluidDexV2RouterError(ErrorTypes.DexV2Router__InvalidOperation);
}
/// @notice Called by the dex when a settle pulls tokens in: pays `amount_` of `token_` from the swapper to the dex
/// (float-served settle) or to the Liquidity layer (Liquidity-routed settle, reached from the dex's
/// `liquidityCallback`).
function dexCallback(address token_, address to_, uint256 amount_) external {
if (msg.sender != address(DEX_V2) || _msgSender() == address(0)) {
revert FluidDexV2RouterError(ErrorTypes.DexV2Router__UnauthorizedCallback);
}
if (to_ != address(DEX_V2) && to_ != LIQUIDITY) {
revert FluidDexV2RouterError(ErrorTypes.DexV2Router__InvalidCallbackRecipient);
}
SafeTransfer.safeTransferFrom(token_, _msgSender(), to_, amount_);
}
/// @notice Sends the router's whole balance of `token_` (`NATIVE_TOKEN` for native) to the Liquidity layer, where
/// it counts toward the revenue of a token listed there (a token that is not listed is parked until it
/// is). The router holds nothing between transactions, so anything here was sent by mistake, forced in, or
/// paid to the router by the dex in someone else's settle. Only Liquidity governance. Emits
/// `LogRescueFunds`.
/// @dev Refused while a swap or quote runs: the router then holds the swapper's `msg.value`.
function rescueFunds(address token_) external onlyGovernance {
if (_msgSender() != address(0)) revert FluidDexV2RouterError(ErrorTypes.DexV2Router__Reentrancy);
uint256 amount_;
if (token_ == NATIVE_TOKEN) {
amount_ = address(this).balance;
SafeTransfer.safeTransferNative(LIQUIDITY, amount_);
} else {
amount_ = IERC20(token_).balanceOf(address(this));
SafeTransfer.safeTransfer(token_, LIQUIDITY, amount_);
}
emit LogRescueFunds(token_, amount_);
}
/// @dev accepts native tokens from the dex only. The router's own settles never cause a transfer to it: it sends
/// the exact net, so the dex has nothing to refund. What arrives here was addressed to the router in someone
/// else's settle, and leaves only through `rescueFunds`.
receive() external payable {
if (msg.sender != address(DEX_V2)) revert FluidDexV2RouterError(ErrorTypes.DexV2Router__NativeNotAccepted);
}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
contracts/libraries/access/liquidityGovernanceAuth.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
interface IFluidLiquidityGovernance {
function readFromStorage(bytes32 slot_) external view returns (uint256 result_);
}
/// @title LiquidityGovernanceAuth
/// @notice Shared helpers for contracts gated by Fluid Liquidity Layer governance.
/// @dev Liquidity proxy is set at construction (prod, permissioned, or test). Governance is the
/// EIP-1967 admin stored on that proxy (read via `readFromStorage`).
abstract contract LiquidityGovernanceAuth {
/// @dev Liquidity Layer proxy bound at deploy — not assumed identical across deployments.
address public immutable LIQUIDITY;
/// @dev EIP-1967 admin slot on Liquidity — holds the governance address.
bytes32 internal constant _LIQUIDITY_GOVERNANCE_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
error Access__Unauthorized();
/// @param liquidity_ Liquidity proxy whose EIP-1967 admin is governance for this contract.
constructor(address liquidity_) {
if (liquidity_ == address(0)) {
revert Access__Unauthorized();
}
LIQUIDITY = liquidity_;
}
/// @dev Current Liquidity Layer governance (owner) for `LIQUIDITY`.
function _governance() internal view returns (address) {
return address(uint160(IFluidLiquidityGovernance(LIQUIDITY).readFromStorage(_LIQUIDITY_GOVERNANCE_SLOT)));
}
/// @dev Whether `msg.sender` is Liquidity Layer governance.
function _isGovernance() internal view returns (bool) {
return msg.sender == _governance();
}
/// @dev Only Liquidity Layer governance.
modifier onlyGovernance() {
if (!_isGovernance()) {
revert Access__Unauthorized();
}
_;
}
}
contracts/libraries/errorTypes.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.21 <=0.8.36;
library LibsErrorTypes {
/***********************************|
| LiquidityCalcs |
|__________________________________*/
/// @notice thrown when supply or borrow exchange price is zero at calc token data (token not configured yet)
uint256 internal constant LiquidityCalcs__ExchangePriceZero = 70001;
/// @notice thrown when rate data is set to a version that is not implemented
uint256 internal constant LiquidityCalcs__UnsupportedRateVersion = 70002;
/// @notice thrown when the calculated borrow rate turns negative. This should never happen.
uint256 internal constant LiquidityCalcs__BorrowRateNegative = 70003;
/***********************************|
| SafeTransfer |
|__________________________________*/
/// @notice thrown when safe transfer from for an ERC20 fails
uint256 internal constant SafeTransfer__TransferFromFailed = 71001;
/// @notice thrown when safe transfer for an ERC20 fails
uint256 internal constant SafeTransfer__TransferFailed = 71002;
/***********************************|
| BasicValidations |
|__________________________________*/
/// @notice thrown when a passed address is the zero address
uint256 internal constant BasicValidations__AddressZero = 72001;
/***********************************|
| SafeApprove |
|__________________________________*/
/// @notice thrown when safe approve from for an ERC20 fails
uint256 internal constant SafeApprove__ApproveFailed = 81001;
}
contracts/libraries/pendingTransfers.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
/// @notice Library for managing pending token transfers using transient storage
/// @dev These transfers are temporary and only exist within a single transaction.
/// Entries are keyed by (user, token). The two count slots hold the GLOBAL number of (user, token) entries with a
/// non-zero pending supply / borrow across all users; DexV2's startOperation requires both counts to be zero, so
/// pending left by any address blocks the operation. Sign convention as used by DexV2: positive pending supply =
/// the user owes tokens to the dex (deposit), negative = the dex owes the user (withdraw); positive pending borrow
/// = the dex owes the user (borrow), negative = the user owes the dex (payback). setPendingSupply/setPendingBorrow
/// have no callers in DexV2.
library PendingTransfers {
// Custom errors
error PendingSupplyNotCleared();
error PendingBorrowNotCleared();
error PendingTransfersNotCleared(bytes data_);
// bytes32(uint256(keccak256("FLUID_DEX_V2_PENDING_SUPPLY")) - 1)
bytes32 constant PENDING_SUPPLY_SLOT = 0x1f9fe0a780efbf168c8fd810da059a7db6663cde8eba217dd821a7835cf20a90;
// bytes32(uint256(keccak256("FLUID_DEX_V2_PENDING_BORROW")) - 1)
bytes32 constant PENDING_BORROW_SLOT = 0xc635a7f3d9cd0b7d4d1f19812847a3c1f84d9f5e2122dad3be5b18f057c49939;
// Slot for tracking the number of (user, token) entries with non-zero pending supply (global across users)
// bytes32(uint256(keccak256("FLUID_DEX_V2_PENDING_SUPPLY_COUNT")) - 1)
bytes32 constant PENDING_SUPPLY_COUNT_SLOT = 0x160e3eae53eb5e6bab86ba926e1fc6aa97060a9a6c4c61fefab056c4c92aee16;
// Slot for tracking the number of (user, token) entries with non-zero pending borrow (global across users)
// bytes32(uint256(keccak256("FLUID_DEX_V2_PENDING_BORROW_COUNT")) - 1)
bytes32 constant PENDING_BORROW_COUNT_SLOT = 0x53abf9dcada09a46758e0e7f58efc5c79e938aa3968f2844595df8b0794c5ab8;
/// @notice Get the pending supply amount for a token and user
/// @param user_ The user address
/// @param token_ The token address
/// @return amount_ The pending supply amount (can be negative)
function getPendingSupply(address user_, address token_) internal view returns (int256 amount_) {
bytes32 key_ = keccak256(abi.encode(PENDING_SUPPLY_SLOT, user_, token_));
assembly ("memory-safe") {
amount_ := tload(key_)
}
}
/// @notice Get the pending borrow amount for a token and user
/// @param user_ The user address
/// @param token_ The token address
/// @return amount_ The pending borrow amount (can be negative)
function getPendingBorrow(address user_, address token_) internal view returns (int256 amount_) {
bytes32 key_ = keccak256(abi.encode(PENDING_BORROW_SLOT, user_, token_));
assembly ("memory-safe") {
amount_ := tload(key_)
}
}
/// @notice Set the pending supply amount for a token and user
/// @param user_ The user address
/// @param token_ The token address
/// @param amount_ The amount to set
function setPendingSupply(address user_, address token_, int256 amount_) internal {
bytes32 key_ = keccak256(abi.encode(PENDING_SUPPLY_SLOT, user_, token_));
int256 previousAmount_;
assembly ("memory-safe") {
previousAmount_ := tload(key_)
tstore(key_, amount_)
}
// Update the pending tokens count
if (previousAmount_ == 0 && amount_ != 0) {
incrementPendingSupplyCount();
} else if (previousAmount_ != 0 && amount_ == 0) {
decrementPendingSupplyCount();
}
}
/// @notice Set the pending borrow amount for a token and user
/// @param user_ The user address
/// @param token_ The token address
/// @param amount_ The amount to set
function setPendingBorrow(address user_, address token_, int256 amount_) internal {
bytes32 key_ = keccak256(abi.encode(PENDING_BORROW_SLOT, user_, token_));
int256 previousAmount_;
assembly ("memory-safe") {
previousAmount_ := tload(key_)
tstore(key_, amount_)
}
// Update the pending tokens count
if (previousAmount_ == 0 && amount_ != 0) {
incrementPendingBorrowCount();
} else if (previousAmount_ != 0 && amount_ == 0) {
decrementPendingBorrowCount();
}
}
/// @notice Update the pending supply amount for a token and user
/// @param user_ The user address
/// @param token_ The token address
/// @param amount_ The amount to add (can be negative)
function addPendingSupply(address user_, address token_, int256 amount_) internal {
if (amount_ == 0) return;
bytes32 key_ = keccak256(abi.encode(PENDING_SUPPLY_SLOT, user_, token_));
int256 previousAmount_;
assembly ("memory-safe") {
previousAmount_ := tload(key_)
}
int256 newAmount_ = previousAmount_ + amount_;
assembly ("memory-safe") {
tstore(key_, newAmount_)
}
// Update the pending tokens count
if (previousAmount_ == 0 && newAmount_ != 0) {
incrementPendingSupplyCount();
} else if (previousAmount_ != 0 && newAmount_ == 0) {
decrementPendingSupplyCount();
}
}
/// @notice Update the pending borrow amount for a token and user
/// @param user_ The user address
/// @param token_ The token address
/// @param amount_ The amount to add (can be negative)
function addPendingBorrow(address user_, address token_, int256 amount_) internal {
if (amount_ == 0) return;
bytes32 key_ = keccak256(abi.encode(PENDING_BORROW_SLOT, user_, token_));
int256 previousAmount_;
assembly ("memory-safe") {
previousAmount_ := tload(key_)
}
int256 newAmount_ = previousAmount_ + amount_;
assembly ("memory-safe") {
tstore(key_, newAmount_)
}
// Update the pending tokens count
if (previousAmount_ == 0 && newAmount_ != 0) {
incrementPendingBorrowCount();
} else if (previousAmount_ != 0 && newAmount_ == 0) {
decrementPendingBorrowCount();
}
}
/// @notice Get the global count of (user, token) entries with pending supply
/// @return count_ The number of (user, token) entries with non-zero pending supply, across all users
function getPendingSupplyCount() internal view returns (uint256 count_) {
assembly ("memory-safe") {
count_ := tload(PENDING_SUPPLY_COUNT_SLOT)
}
}
/// @notice Get the global count of (user, token) entries with pending borrow
/// @return count_ The number of (user, token) entries with non-zero pending borrow, across all users
function getPendingBorrowCount() internal view returns (uint256 count_) {
assembly ("memory-safe") {
count_ := tload(PENDING_BORROW_COUNT_SLOT)
}
}
/// @notice Increment the count of tokens with pending supply
function incrementPendingSupplyCount() internal {
assembly ("memory-safe") {
tstore(PENDING_SUPPLY_COUNT_SLOT, add(tload(PENDING_SUPPLY_COUNT_SLOT), 1))
}
}
/// @notice Increment the count of tokens with pending borrow
function incrementPendingBorrowCount() internal {
assembly ("memory-safe") {
tstore(PENDING_BORROW_COUNT_SLOT, add(tload(PENDING_BORROW_COUNT_SLOT), 1))
}
}
/// @notice Decrement the count of tokens with pending supply
function decrementPendingSupplyCount() internal {
assembly ("memory-safe") {
tstore(PENDING_SUPPLY_COUNT_SLOT, sub(tload(PENDING_SUPPLY_COUNT_SLOT), 1))
}
}
/// @notice Decrement the count of tokens with pending borrow
function decrementPendingBorrowCount() internal {
assembly ("memory-safe") {
tstore(PENDING_BORROW_COUNT_SLOT, sub(tload(PENDING_BORROW_COUNT_SLOT), 1))
}
}
/// @notice Check if all pending supply transfers have been cleared
/// @return True if all pending supply transfers are zero
function allPendingSupplyCleared() internal view returns (bool) {
return getPendingSupplyCount() == 0;
}
/// @notice Check if all pending borrow transfers have been cleared
/// @return True if all pending borrow transfers are zero
function allPendingBorrowCleared() internal view returns (bool) {
return getPendingBorrowCount() == 0;
}
/// @notice Check if all pending transfers (both supply and borrow) have been cleared
/// @return True if all pending transfers are zero
function allPendingTransfersCleared() internal view returns (bool) {
return allPendingSupplyCleared() && allPendingBorrowCleared();
}
/// @notice Require that all pending supply transfers have been cleared
function requireAllPendingSupplyCleared() internal view {
if(!allPendingSupplyCleared()) revert PendingSupplyNotCleared();
}
/// @notice Require that all pending borrow transfers have been cleared
function requireAllPendingBorrowCleared() internal view {
if(!allPendingBorrowCleared()) revert PendingBorrowNotCleared();
}
/// @notice Require that all pending transfers (both supply and borrow) have been cleared
/// @dev Call this at the end of transactions to ensure all tokens are properly settled
function requireAllPendingTransfersCleared(bytes memory data_) internal view {
if(!allPendingTransfersCleared()) revert PendingTransfersNotCleared(data_);
}
}
contracts/libraries/safeTransfer.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.8.21 <=0.8.36;
import { LibsErrorTypes as ErrorTypes } from "./errorTypes.sol";
/// @notice Provides minimalistic methods for safe ERC20 and native token transfers.
/// @author Instadapp
library SafeTransfer {
// pass max. 50k gas for native transfers. This ensures support for some realistic
// scenarios like WETH deposits in receive() but as restrictive as possible.
uint256 internal constant MAX_NATIVE_TRANSFER_GAS = 50000;
error FluidSafeTransferError(uint256 errorId_);
/// @dev Transfer `amount_` of `token_` from `from_` to `to_`, spending the approval given by `from_` to the
/// calling contract. If `token_` returns no value, non-reverting calls are assumed to be successful.
/// @dev Calldata assembly aligned with Solady SafeTransferLib while preserving Fluid's return-data semantics.
function safeTransferFrom(address token_, address from_, address to_, uint256 amount_) internal {
bool success_;
/// @solidity memory-safe-assembly
assembly {
// 1:1 Solady SafeTransferLib.sol L257-L262:
// https://github.com/Vectorized/solady/blob/acd959aa4bd04720d640bf4e6a5c71037510cc4b/src/utils/SafeTransferLib.sol#L257-L262
let m := mload(0x40)
mstore(0x60, amount_)
mstore(0x40, to_)
mstore(0x2c, shl(96, from_))
mstore(0x0c, 0x23b872dd000000000000000000000000)
success_ := call(gas(), token_, 0, 0x1c, 0x64, 0x00, 0x20)
// Fluid's rule instead of Solady L263-L268: 1 in at least 32 bytes, or no data, without a code check
success_ := and(success_, or(and(eq(mload(0x00), 1), gt(returndatasize(), 0x1f)), iszero(returndatasize())))
// 1:1 Solady L269-L270:
// https://github.com/Vectorized/solady/blob/acd959aa4bd04720d640bf4e6a5c71037510cc4b/src/utils/SafeTransferLib.sol#L269-L270
mstore(0x60, 0)
mstore(0x40, m)
}
if (!success_) {
revert FluidSafeTransferError(ErrorTypes.SafeTransfer__TransferFromFailed);
}
}
/// @dev Transfer `amount_` of `token_` to `to_`.
/// If `token_` returns no value, non-reverting calls are assumed to be successful.
/// @dev Calldata assembly aligned with Solady SafeTransferLib while preserving Fluid's return-data semantics.
function safeTransfer(address token_, address to_, uint256 amount_) internal {
bool success_;
/// @solidity memory-safe-assembly
assembly {
// 1:1 Solady SafeTransferLib.sol L341-L345:
// https://github.com/Vectorized/solady/blob/acd959aa4bd04720d640bf4e6a5c71037510cc4b/src/utils/SafeTransferLib.sol#L341-L345
mstore(0x14, to_)
mstore(0x34, amount_)
mstore(0x00, 0xa9059cbb000000000000000000000000)
success_ := call(gas(), token_, 0, 0x10, 0x44, 0x00, 0x20)
// Fluid's rule instead of Solady L346-L351: 1 in at least 32 bytes, or no data, without a code check
success_ := and(success_, or(and(eq(mload(0x00), 1), gt(returndatasize(), 0x1f)), iszero(returndatasize())))
// 1:1 Solady L352:
// https://github.com/Vectorized/solady/blob/acd959aa4bd04720d640bf4e6a5c71037510cc4b/src/utils/SafeTransferLib.sol#L352
mstore(0x34, 0)
}
if (!success_) {
revert FluidSafeTransferError(ErrorTypes.SafeTransfer__TransferFailed);
}
}
/// @dev Transfer `amount_` of native token to `to_` with a limited gas stipend.
function safeTransferNative(address to_, uint256 amount_) internal {
bool success_;
/// @solidity memory-safe-assembly
assembly {
// Transfer the ETH and store if it succeeded or not. Pass limited gas
success_ := call(MAX_NATIVE_TRANSFER_GAS, to_, amount_, 0, 0, 0, 0)
}
if (!success_) {
revert FluidSafeTransferError(ErrorTypes.SafeTransfer__TransferFailed);
}
}
}
contracts/periphery/dexV2/router/error.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
abstract contract Error {
error FluidDexV2RouterError(uint256 errorId_);
}
contracts/periphery/dexV2/router/errorTypes.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
library ErrorTypes {
/***********************************|
| DexV2Router |
|__________________________________*/
/// @notice thrown when the dex address given to the constructor is zero (a zero Liquidity address reverts
/// `LiquidityGovernanceAuth.Access__Unauthorized`)
uint256 internal constant DexV2Router__AddressZero = 220001;
/// @notice thrown when a swap, a quote or `rescueFunds` is entered while a swap or quote is in progress
uint256 internal constant DexV2Router__Reentrancy = 220002;
/// @notice thrown when `block.timestamp` is past the deadline of the swap
uint256 internal constant DexV2Router__DeadlinePassed = 220003;
/// @notice thrown when the path has fewer than two tokens, the hops do not match the path, or a hop swaps a token
/// into itself
uint256 internal constant DexV2Router__InvalidPath = 220004;
/// @notice thrown when a hop names a dex type other than 3 (D3) or 4 (D4)
uint256 internal constant DexV2Router__InvalidDexType = 220005;
/// @notice thrown when the recipient of the output tokens is the zero address or the router itself, or is not the
/// swapper for a path that ends in its input token (settled on the net, see SPEC §7.5)
uint256 internal constant DexV2Router__InvalidRecipient = 220006;
/// @notice thrown when a callback is not made by the dex, or outside of an operation the router opened
uint256 internal constant DexV2Router__UnauthorizedCallback = 220007;
/// @notice thrown when `dexCallback` asks to pay a recipient other than the dex or the Liquidity layer
uint256 internal constant DexV2Router__InvalidCallbackRecipient = 220008;
/// @notice thrown when the native value sent with the swap does not cover the native amount the swap pulls in
uint256 internal constant DexV2Router__InsufficientNativeValue = 220009;
/// @notice thrown when the operation data handed to `startOperationCallback` names an unknown operation, and by a
/// quote whose hops left nothing pending (a path back into its input token whose output equals its input):
/// the dex then returns instead of reverting with the result
uint256 internal constant DexV2Router__InvalidOperation = 220010;
/// @notice thrown when native tokens are sent to the router by an address other than the dex
uint256 internal constant DexV2Router__NativeNotAccepted = 220011;
}
contracts/periphery/dexV2/router/events.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
abstract contract Events {
/// @notice emitted once per swap, for the whole path. The dex emits `LogSwapIn` / `LogSwapOut` per hop with the
/// router as the swapper, so this is the only log that names the account behind the swap.
event LogSwap(
address indexed user,
address indexed to,
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 amountOut
);
/// @notice emitted by `rescueFunds` with the amount sent to the Liquidity layer
event LogRescueFunds(address indexed token, uint256 amount);
}
contracts/periphery/dexV2/router/helpers.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
import { SafeTransfer } from "../../../libraries/safeTransfer.sol";
import { PendingTransfers } from "../../../libraries/pendingTransfers.sol";
import "./variables.sol";
import "./events.sol";
abstract contract Helpers is Variables, Events {
/// @dev Reentrancy lock, swapper identity and native value of one swap. `_msgSender` is read by `dexCallback` (who
/// pays), by `startOperationCallback` (which operation window is ours) and by `rescueFunds` (no call in
/// progress); the native value not forwarded to the dex by the settles is refunded to the swapper at the end.
/// `_msgValue` is zero whenever no swap runs: every exit below leaves it at zero before control leaves the
/// router, a revert undoes the writes of its call, and nothing else writes it. A swap without value therefore
/// neither writes nor reads it.
modifier _handleMsgDetails() {
if (_msgSender() != address(0)) revert FluidDexV2RouterError(ErrorTypes.DexV2Router__Reentrancy);
_setMsgSender(msg.sender);
if (msg.value != 0) _setMsgValue(msg.value);
_;
_setMsgSender(address(0));
if (msg.value != 0) {
uint256 refund_ = _msgValue();
if (refund_ != 0) {
// reset before the transfer: the lock is released by now, and a swap entered from the swapper's
// receive hook has to find the value word at zero
_setMsgValue(0);
SafeTransfer.safeTransferNative(msg.sender, refund_);
}
}
}
/// @dev the lock of a quote: no native value, nothing to refund, and nothing is pulled from the caller. The mark of
/// a call in progress is the caller's address, so a quote from the zero address (an `eth_call` without `from`)
/// leaves it unset and is refused by `startOperationCallback`.
modifier _handleQuoteDetails() {
if (_msgSender() != address(0)) revert FluidDexV2RouterError(ErrorTypes.DexV2Router__Reentrancy);
_setMsgSender(msg.sender);
_;
_setMsgSender(address(0));
}
/// @dev path of at least two tokens, one hop per neighbouring pair, no hop from a token into itself, dex type 3 or 4
function _validatePath(address[] calldata path_, Hop[] calldata hops_) internal pure {
uint256 length_ = hops_.length;
if (length_ == 0 || path_.length != length_ + 1) {
revert FluidDexV2RouterError(ErrorTypes.DexV2Router__InvalidPath);
}
for (uint256 i; i < length_; ++i) {
if (path_[i] == path_[i + 1]) revert FluidDexV2RouterError(ErrorTypes.DexV2Router__InvalidPath);
if (hops_[i].dexType != DEX_TYPE_D3 && hops_[i].dexType != DEX_TYPE_D4) {
revert FluidDexV2RouterError(ErrorTypes.DexV2Router__InvalidDexType);
}
}
}
function _validateSwap(
address[] calldata path_,
Hop[] calldata hops_,
address to_,
uint256 deadline_
) internal view {
// an output paid to the router would be lost to the swapper: only `rescueFunds` moves the router's balance
if (to_ == address(0) || to_ == address(this)) {
revert FluidDexV2RouterError(ErrorTypes.DexV2Router__InvalidRecipient);
}
if (block.timestamp > deadline_) revert FluidDexV2RouterError(ErrorTypes.DexV2Router__DeadlinePassed);
_validatePath(path_, hops_);
// a path that ends in its input token settles that token once, on the net of input and output, with the
// swapper paying or receiving the difference: it can only pay out to the swapper
if (path_[0] == path_[path_.length - 1] && to_ != msg.sender) {
revert FluidDexV2RouterError(ErrorTypes.DexV2Router__InvalidRecipient);
}
}
/// @dev exact-input swap of one hop: `amountIn_` of `tokenIn_` into `tokenOut_` on the hop's pool, at least
/// `amountOutMin_` out (the module checks it). The pool's pending legs land on this contract.
function _swapHopIn(
address tokenIn_,
address tokenOut_,
Hop memory hop_,
uint256 amountIn_,
uint256 amountOutMin_
) internal returns (uint256 amountOut_) {
SwapInParams memory params_;
params_.dexKey = _key(tokenIn_, tokenOut_, hop_);
params_.swap0To1 = tokenIn_ < tokenOut_;
params_.amountIn = amountIn_;
params_.amountOutMin = amountOutMin_;
params_.controllerData = hop_.controllerData;
bytes memory returnData_ = DEX_V2.operate(
hop_.dexType,
SWAP_MODULE_ID,
abi.encodeCall(IFluidDexV2D3D4SwapModule.swapIn, (params_))
);
(amountOut_, , ) = abi.decode(returnData_, (uint256, uint256, uint256));
}
/// @dev exact-output swap of one hop: `amountOut_` of `tokenOut_` for at most `amountInMax_` of `tokenIn_`
function _swapHopOut(
address tokenIn_,
address tokenOut_,
Hop memory hop_,
uint256 amountOut_,
uint256 amountInMax_
) internal returns (uint256 amountIn_) {
SwapOutParams memory params_;
params_.dexKey = _key(tokenIn_, tokenOut_, hop_);
params_.swap0To1 = tokenIn_ < tokenOut_;
params_.amountOut = amountOut_;
params_.amountInMax = amountInMax_;
params_.controllerData = hop_.controllerData;
bytes memory returnData_ = DEX_V2.operate(
hop_.dexType,
SWAP_MODULE_ID,
abi.encodeCall(IFluidDexV2D3D4SwapModule.swapOut, (params_))
);
(amountIn_, , ) = abi.decode(returnData_, (uint256, uint256, uint256));
}
/// @dev the hops of the path in order, each fed the previous output; only the last hop carries the caller's floor
function _runSwapIn(
address[] memory path_,
Hop[] memory hops_,
uint256 amountIn_,
uint256 amountOutMin_
) internal returns (uint256 amountOut_) {
uint256 last_ = hops_.length - 1;
amountOut_ = amountIn_;
for (uint256 i; i <= last_; ++i) {
amountOut_ = _swapHopIn(path_[i], path_[i + 1], hops_[i], amountOut_, i == last_ ? amountOutMin_ : 0);
}
}
/// @dev the hops of the path in reverse order, each asked for the input the next one needs; only the first hop of
/// the path (the last one run) carries the caller's cap
function _runSwapOut(
address[] memory path_,
Hop[] memory hops_,
uint256 amountOut_,
uint256 amountInMax_
) internal returns (uint256 amountIn_) {
amountIn_ = amountOut_;
for (uint256 i = hops_.length; i > 0; --i) {
amountIn_ = _swapHopOut(
path_[i - 1],
path_[i],
hops_[i - 1],
amountIn_,
i == 1 ? amountInMax_ : type(uint256).max
);
}
}
/// @dev opens the operation of a swap and returns its unspecified amount (output of `swapIn`, input of `swapOut`).
/// `data_` is the operation id followed by its parameters in one encoding; the dex hands it back unread to
/// `startOperationCallback`.
function _startSwap(bytes memory data_) internal returns (uint256 amount_) {
amount_ = abi.decode(DEX_V2.startOperation(data_), (uint256));
}
/// @dev opens the operation of a quote and returns the quoted amount, which the dex hands back in its revert;
/// `data_` as in `_startSwap`
function _startQuote(bytes memory data_) internal returns (uint256 amount_) {
try DEX_V2.startOperation(data_) {
// the hops of a quote stay pending, so startOperation reverts; it returns only when they left nothing
// pending at all (a path back into its input token whose output equals its input)
revert FluidDexV2RouterError(ErrorTypes.DexV2Router__InvalidOperation);
} catch (bytes memory revertData_) {
amount_ = _decodeQuoteRevert(revertData_);
}
}
function _operationSwapIn(bytes calldata data_) internal returns (bytes memory) {
(, address[] memory path_, Hop[] memory hops_, uint256 amountIn_, uint256 amountOutMin_, address to_) = abi
.decode(data_, (uint256, address[], Hop[], uint256, uint256, address));
uint256 amountOut_ = _runSwapIn(path_, hops_, amountIn_, amountOutMin_);
_settleAll(path_, to_);
emit LogSwap(_msgSender(), to_, path_[0], path_[path_.length - 1], amountIn_, amountOut_);
return abi.encode(amountOut_);
}
function _operationSwapOut(bytes calldata data_) internal returns (bytes memory) {
(, address[] memory path_, Hop[] memory hops_, uint256 amountOut_, uint256 amountInMax_, address to_) = abi
.decode(data_, (uint256, address[], Hop[], uint256, uint256, address));
uint256 amountIn_ = _runSwapOut(path_, hops_, amountOut_, amountInMax_);
_settleAll(path_, to_);
emit LogSwap(_msgSender(), to_, path_[0], path_[path_.length - 1], amountIn_, amountOut_);
return abi.encode(amountIn_);
}
/// @dev quotes run the hops and leave the pending legs: `startOperation` then reverts with the returned amount
function _operationQuoteIn(bytes calldata data_) internal returns (bytes memory) {
(, address[] memory path_, Hop[] memory hops_, uint256 amountIn_) = abi.decode(
data_,
(uint256, address[], Hop[], uint256)
);
return abi.encode(_runSwapIn(path_, hops_, amountIn_, 0));
}
function _operationQuoteOut(bytes calldata data_) internal returns (bytes memory) {
(, address[] memory path_, Hop[] memory hops_, uint256 amountOut_) = abi.decode(
data_,
(uint256, address[], Hop[], uint256)
);
return abi.encode(_runSwapOut(path_, hops_, amountOut_, type(uint256).max));
}
/// @dev Clears every pending leg the hops left on this contract, one `settle` per distinct token of the path with
/// the "entire pending amount" sentinel on both legs: the input token nets to an inflow pulled from the swapper
/// through `dexCallback` (or sent as native value), the output token nets to an outflow paid to `to_` by the dex,
/// a token in the middle of the path nets to zero (nothing happens for D3 legs; equal D4 supply and borrow
/// legs are registered on the dex's Liquidity position without a transfer, DexV2 SPEC §7). A token that
/// appears twice in the path (a loop back into the input token) is settled once, on its net. Native inflows
/// take exactly the net from the swap's value; anything left is refunded by `_handleMsgDetails`.
/// The input and the output token of a path that does not return into its input token are settled without
/// reading their pending words first: their net is the whole input (owed to the dex) or the whole output
/// (owed by the dex), never zero, so there is nothing to decide and the sentinels resolve to the legs. Two
/// exceptions: a native input, whose net is the value the settle has to carry (a native output needs none),
/// and an output that occurs earlier in the path, which is settled where it first occurs, as a middle token.
/// Every other token is read first (`_settleToken`).
function _settleAll(address[] memory path_, address to_) internal {
uint256 length_ = path_.length;
uint256 last_ = length_ - 1;
for (uint256 i; i < length_; ++i) {
address token_ = path_[i];
bool settled_;
for (uint256 j; j < i; ++j) {
if (path_[j] == token_) {
settled_ = true;
break;
}
}
if (settled_) continue;
// unread: the input, unless it is native or the path returns into it, and the output. The last place needs
// no test for a path back into its input: there the token is the input again, settled at the first place
if (i == 0 ? (token_ != NATIVE_TOKEN && token_ != path_[last_]) : i == last_) {
DEX_V2.settle(token_, SETTLE_ALL, SETTLE_ALL, 0, to_, true);
} else {
_settleToken(token_, to_);
}
}
}
/// @dev one settle of both pending legs of `token_` after reading them; nothing if neither is pending (a middle
/// token whose legs cancelled, a loop whose output equals its input). A native net inflow is taken from the
/// swap's value.
function _settleToken(address token_, address to_) internal {
int256 pendingSupply_ = int256(
DEX_V2.readFromTransientStorage(
keccak256(abi.encode(PendingTransfers.PENDING_SUPPLY_SLOT, address(this), token_))
)
);
int256 pendingBorrow_ = int256(
DEX_V2.readFromTransientStorage(
keccak256(abi.encode(PendingTransfers.PENDING_BORROW_SLOT, address(this), token_))
)
);
if (pendingSupply_ == 0 && pendingBorrow_ == 0) return;
uint256 value_;
if (token_ == NATIVE_TOKEN) {
// positive pending supply = owed to the dex, positive pending borrow = owed by the dex
int256 net_ = pendingSupply_ - pendingBorrow_;
if (net_ > 0) {
value_ = uint256(net_);
uint256 msgValue_ = _msgValue();
if (msgValue_ < value_) revert FluidDexV2RouterError(ErrorTypes.DexV2Router__InsufficientNativeValue);
_setMsgValue(msgValue_ - value_);
}
}
DEX_V2.settle{ value: value_ }(token_, SETTLE_ALL, SETTLE_ALL, 0, to_, true);
}
/// @dev the pool key of a hop: the two tokens of the path sorted by address, the rest from the hop
function _key(address tokenIn_, address tokenOut_, Hop memory hop_) internal pure returns (DexKey memory key_) {
(key_.token0, key_.token1) = tokenIn_ < tokenOut_ ? (tokenIn_, tokenOut_) : (tokenOut_, tokenIn_);
key_.fee = hop_.fee;
key_.tickSpacing = hop_.tickSpacing;
key_.controller = hop_.controller;
}
/// @dev A quote runs the hops and returns without settling, so `startOperation` reverts with
/// `PendingTransfersNotCleared(result)` carrying the callback's return data: the quoted amount. Any other revert
/// (a module refusing the swap, an unknown pool) is bubbled up unchanged.
function _decodeQuoteRevert(bytes memory revertData_) internal pure returns (uint256 amount_) {
if (revertData_.length < 4 || bytes4(revertData_) != PendingTransfers.PendingTransfersNotCleared.selector) {
assembly {
revert(add(revertData_, 32), mload(revertData_))
}
}
bytes memory payload_;
assembly {
// skip the 4 selector bytes: the length word moves 4 bytes into the data
payload_ := add(revertData_, 4)
mstore(payload_, sub(mload(revertData_), 4))
}
bytes memory result_ = abi.decode(payload_, (bytes));
amount_ = abi.decode(result_, (uint256));
}
}
contracts/periphery/dexV2/router/interfaces.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
import { IFluidDexV2 } from "../../../protocols/dexV2/interfaces/iDexV2.sol";
import { DexKey, SwapInParams, SwapOutParams } from "../../../protocols/dexV2/dexTypes/common/d3d4common/structs.sol";
/// @dev Calldata shape of the D3 / D4 swap modules (`FluidDexV2D3SwapModule`, `FluidDexV2D4SwapModule`), reached through
/// `IFluidDexV2.operate(3 | 4, 1, data)`. Only used to encode the calls and decode their return data.
interface IFluidDexV2D3D4SwapModule {
function swapIn(
SwapInParams calldata params_
) external returns (uint256 amountOut_, uint256 protocolFeeAccrued_, uint256 lpFeeAccrued_);
function swapOut(
SwapOutParams calldata params_
) external returns (uint256 amountIn_, uint256 protocolFeeAccrued_, uint256 lpFeeAccrued_);
}
contracts/periphery/dexV2/router/structs.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
/// @dev One pool of a swap path. The tokens of the hop are the two neighbouring entries of the path (`path[i]` is swapped
/// into `path[i + 1]`); the hop names the pool of that pair by the rest of its key. D3 / D4 keys are sorted by
/// address (`token0 < token1`, DexV2 SPEC §9), so the direction of the hop follows from the path.
/// `controllerData` is forwarded verbatim to the pool controller when its fee fetch is on (DexV2 SPEC §9.2).
struct Hop {
uint256 dexType;
uint24 fee;
uint24 tickSpacing;
address controller;
bytes controllerData;
}
contracts/periphery/dexV2/router/variables.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
import "./interfaces.sol";
import "./structs.sol";
import "./error.sol";
import { ErrorTypes } from "./errorTypes.sol";
import { LiquidityGovernanceAuth } from "../../../libraries/access/liquidityGovernanceAuth.sol";
abstract contract ConstantVariables {
address internal constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev the dex types the router swaps on: D3 (concentrated smart collateral) and D4 (concentrated smart debt). The
/// D1 / D2 dex-v1-style pools are deliberately not routed; a version with them is a new router, see SPEC §12.
uint256 internal constant DEX_TYPE_D3 = 3;
uint256 internal constant DEX_TYPE_D4 = 4;
/// @dev implementation id of the swap module of both dex types (DexV2 SPEC §7, `operate`)
uint256 internal constant SWAP_MODULE_ID = 1;
/// @dev operations the router runs inside `startOperationCallback`
uint256 internal constant OPERATION_SWAP_IN = 1;
uint256 internal constant OPERATION_SWAP_OUT = 2;
uint256 internal constant OPERATION_QUOTE_IN = 3;
uint256 internal constant OPERATION_QUOTE_OUT = 4;
/// @dev `settle` sentinel: "my entire pending amount" for the supply and the borrow leg (DexV2 SPEC §7)
int256 internal constant SETTLE_ALL = type(int128).max;
}
/// @dev `LIQUIDITY` (inherited) is the Liquidity layer of the dex: the second recipient `dexCallback` may be asked to
/// pay (DexV2 SPEC §7, `liquidityCallback`), the receiver of `rescueFunds`, and the source of its governance.
abstract contract ImmutableVariables is ConstantVariables, Error, LiquidityGovernanceAuth {
/// @notice the DexV2 proxy every swap goes through
IFluidDexV2 public immutable DEX_V2;
constructor(address dexV2_, address liquidity_) LiquidityGovernanceAuth(liquidity_) {
if (dexV2_ == address(0)) revert FluidDexV2RouterError(ErrorTypes.DexV2Router__AddressZero);
DEX_V2 = IFluidDexV2(dexV2_);
}
}
abstract contract TransientVariables is ImmutableVariables {
/// @dev the swapper of the call in progress: whose tokens `dexCallback` pulls and who gets the native refund.
/// Non-zero only while a swap or quote runs, which doubles as the reentrancy lock. A full word, not `address`:
/// a packed transient address is written read-modify-write, ~280 gas more per swap.
uint256 internal transient _tMsgSender;
/// @dev native value of the swap not yet forwarded to the dex
uint256 internal transient _tMsgValue;
function _msgSender() internal view returns (address) {
return address(uint160(_tMsgSender));
}
function _setMsgSender(address sender_) internal {
_tMsgSender = uint256(uint160(sender_));
}
function _msgValue() internal view returns (uint256) {
return _tMsgValue;
}
function _setMsgValue(uint256 value_) internal {
_tMsgValue = value_;
}
}
abstract contract Variables is TransientVariables {}
contracts/protocols/dexV2/dexTypes/common/d3d4common/structs.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
// Structs shared by the D3 and D4 modules. Units: a "...Raw" field inside this file is RAW-ADJUSTED (the amount
// normalised to 9 decimals and divided by the token's Liquidity exchange price; the outer d3/ and d4/ modules call
// the same quantity "...RawAdjusted"), the unit all pool math runs in. "Adjusted" alone (used by the outer modules
// for the fee returns of _addLiquidity / _removeLiquidity, which carry no suffix there) is a 9-decimal token amount
// with the exchange price applied. Liquidity is always raw. Fees are 1e6 based. TickData and PositionData are
// STORED structs whose word order is read by offset by the Money Market; every other struct is memory-only.
/// @dev Pool identity: dexId = keccak256(abi.encode(DexKey)); the same key can exist once per dex type (3 and 4).
/// token0 must be < token1 by address (the native token sentinel sorts after almost every address). `fee` is
/// either a static LP fee in 1e6 base (1e6 = 100 %, <= X16 = 65535 = 6.5535 %, 0 allowed) or DYNAMIC_FEE_FLAG
/// (0xFFFFFF); values in between are rejected at initialize. tickSpacing in [1, 500]. `controller` is not
/// validated: it is the only address allowed to call the controller module for this pool and the address the
/// swap modules call for a fee when the fetch flag is on; address(0), or any address that cannot call `operate`
/// inside an operation window, leaves a dynamic fee pool at 0 % LP fee for good, short of governance registering
/// a replacement admin implementation that writes the fee bits. The controller's own swaps skip the fee
/// fetch.
struct DexKey {
address token0;
address token1;
uint24 fee; // The fee here tells the fee if its a static fee pool or acts as a dynamic fee flag, i.e, type(uint24).max or 0xFFFFFF for dynamic fee pools.
uint24 tickSpacing;
address controller;
}
/// @dev Memory copy of the packed `_dexVariables` word (variables.sol slot 0) as unpacked by _getDexVariables:
/// `sqrtPriceX96` is the 64|8 rounded-DOWN stored value without the swap engine's 1->0 read-up, which is what the
/// liquidity path prices positions at; the fee growth globals are the 74|8 rounded-down stored values.
struct DexVariables {
int256 currentTick;
uint256 sqrtPriceX96;
uint256 feeGrowthGlobal0X102;
uint256 feeGrowthGlobal1X102;
}
/// @dev STORED per tick in `_tickData` (variables.sol slot 4), three consecutive words in this order: word 0
/// liquidityNet (added to active liquidity when the tick is crossed 1->0, subtracted when crossed 0->1), word 1
/// feeGrowthOutside0X102, word 2 feeGrowthOutside1X102 (adjusted units per raw liquidity, Uniswap v3 semantics).
/// The Money Market reads words 1 and 2 by offset without naming this struct
/// (moneyMarket/core/other/helpers.sol), so any reorder, insert or prepend compiles and silently misreads.
struct TickData {
int256 liquidityNet;
uint256 feeGrowthOutside0X102;
uint256 feeGrowthOutside1X102;
}
/// @dev STORED per position in `_positionData` (variables.sol slot 5) under positionId =
/// keccak256(abi.encode(owner, tickLower, tickUpper, positionSalt)), owner being the `operate` caller. Three
/// consecutive words in this order: word 0 liquidity (raw), word 1 feeGrowthInside0X102, word 2
/// feeGrowthInside1X102 (snapshots at the last add / remove). The Money Market reads all three words by offset
/// to value collateral and debt and builds the struct with named arguments: adding a member breaks its build,
/// reordering the three members compiles and silently misreads. Never reorder.
struct PositionData {
uint256 liquidity;
uint256 feeGrowthInside0X102;
uint256 feeGrowthInside1X102;
}
/// @dev Per-swap transient view of a fee version 1 pool, built by _calculateDynamicFeeVariables after decaying the
/// stored net price impact: fees in 1e6 base, the zero-impact anchor price X96 and the min / max fee kink prices
/// (anchor * (1 +/- kinkImpact), clamped to [MIN_PRICE_X96, MAX_PRICE_X96]) with their sqrt prices. Nothing in
/// it is stored; only the synced impact / timestamp / decay fields go back into `_dexVariables2`.
struct DynamicFeeVariables {
uint256 minFee;
uint256 maxFee;
uint256 priceImpactToFeeDivisionFactor;
uint256 zeroPriceImpactPriceX96;
uint256 minFeeKinkPriceX96;
uint256 minFeeKinkSqrtPriceX96;
uint256 maxFeeKinkPriceX96;
uint256 maxFeeKinkSqrtPriceX96;
}
/// @dev Parameters of one dynamic-fee swap step (helpers.sol). `swap0To1` is SCRATCH SPACE, not an input: the helper
/// overwrites it from sqrtPriceCurrentX96 > sqrtPriceTargetX96 before reading it (the callers pass the
/// IS_0_TO_1_SWAP filler; the field exists only to avoid a stack-too-deep error). amountInRemaining is
/// raw, protocolFee 1e6 base.
struct ComputeSwapStepForSwapInWithDynamicFeeParams {
bool swap0To1;
uint256 sqrtPriceCurrentX96;
uint256 sqrtPriceTargetX96;
uint256 liquidity;
uint256 amountInRemaining;
uint256 protocolFee;
DynamicFeeVariables dynamicFeeVariables;
}
/// @dev swapOut twin of ComputeSwapStepForSwapInWithDynamicFeeParams; `swap0To1` is scratch space here too.
struct ComputeSwapStepForSwapOutWithDynamicFeeParams {
bool swap0To1;
uint256 sqrtPriceCurrentX96;
uint256 sqrtPriceTargetX96;
uint256 liquidity;
uint256 amountOutRemaining;
uint256 protocolFee;
DynamicFeeVariables dynamicFeeVariables;
}
/// @dev Calldata of D3 / D4 `swapIn` (exact input). amountIn and amountOutMin are normal token units; amountIn and
/// the resulting amountOut must be in [1e4, X128], amountOutMin is the caller's floor and is not limited.
/// controllerData is forwarded verbatim to the pool controller when the fetch flag is on (at
/// most 10,000 bytes then, SwapModule__ControllerDataTooLarge otherwise) and ignored otherwise; the controller
/// treats it as untrusted swapper input.
struct SwapInParams {
DexKey dexKey;
bool swap0To1;
uint256 amountIn;
uint256 amountOutMin;
bytes controllerData;
}
/// @dev Input of _swapIn and, verbatim, the argument the pool controller receives in
/// IController.fetchDynamicFeeForSwapIn (interfaces.sol). dexVariables / dexVariables2 are the packed storage
/// words (dexVariables2 already synced for fee version 1); amountInRaw is raw-adjusted (already rounded down by
/// the outer module); the exchange prices are the live Liquidity prices used for the conversion (supply for D3,
/// borrow for D4). There is NO swapper identity in here: the controller sees the dex proxy as msg.sender and
/// cannot tell who called `operate`. Adding a field changes the IController selector.
struct SwapInInternalParams {
DexKey dexKey;
uint256 dexVariables;
uint256 dexVariables2;
bool swap0To1;
uint256 amountInRaw;
bytes controllerData;
uint256 token0ExchangePrice; // NOTE: can be token0SupplyExchangePrice (for D3) or token0BorrowExchangePrice (for D4)
uint256 token1ExchangePrice; // NOTE: can be token1SupplyExchangePrice (for D3) or token1BorrowExchangePrice (for D4)
uint256 dexType;
bytes32 dexId;
}
/// @dev Scratch of _swapIn. sqrtPriceStartX96 is the effective start price (with the 1->0 read-up) or, when the
/// swap started in a zero-liquidity region, the price at which liquidity was first found
/// (sqrtPriceStartX96Changed); the sqrt price change limit is measured from it. `sqrtPriceNextX96` is never
/// written or read by _swapIn, which uses a stack local instead; _swapOut uses its twin field.
struct SwapInInternalVariables {
uint256 dexVariablesStart;
uint256 sqrtPriceStartX96;
uint256 activeLiquidityStart;
uint256 protocolFee;
uint256 protocolCutFee;
uint256 feeGrowthGlobal0X102;
uint256 feeGrowthGlobal1X102;
uint256 feeVersion;
bool isConstantLpFee;
uint256 constantLpFee;
uint256 sqrtPriceStepStartX96;
int256 nextTick;
bool initialized;
uint256 sqrtPriceNextX96;
bool sqrtPriceStartX96Changed;
}
/// @dev Calldata of D3 / D4 `swapOut` (exact output). amountOut and amountInMax are normal token units; amountOut
/// and the resulting amountIn must be in [1e4, X128], amountInMax is the caller's cap and is not limited;
/// controllerData as in SwapInParams.
struct SwapOutParams {
DexKey dexKey;
bool swap0To1;
uint256 amountOut;
uint256 amountInMax;
bytes controllerData;
}
/// @dev Input of _swapOut and, verbatim, the argument of IController.fetchDynamicFeeForSwapOut; same contents and
/// caveats as SwapInInternalParams with amountOutRaw (raw-adjusted, already rounded up) instead of amountInRaw.
struct SwapOutInternalParams {
DexKey dexKey;
uint256 dexVariables;
uint256 dexVariables2;
bool swap0To1;
uint256 amountOutRaw;
bytes controllerData;
uint256 token0ExchangePrice; // NOTE: can be token0SupplyExchangePrice (for D3) or token0BorrowExchangePrice (for D4)
uint256 token1ExchangePrice; // NOTE: can be token1SupplyExchangePrice (for D3) or token1BorrowExchangePrice (for D4)
uint256 dexType;
bytes32 dexId;
}
/// @dev Scratch of _swapOut, twin of SwapInInternalVariables (here `sqrtPriceNextX96` is used).
struct SwapOutInternalVariables {
uint256 dexVariablesStart;
uint256 sqrtPriceStartX96;
uint256 activeLiquidityStart;
uint256 protocolFee;
uint256 protocolCutFee;
uint256 feeGrowthGlobal0X102;
uint256 feeGrowthGlobal1X102;
uint256 feeVersion;
bool isConstantLpFee;
uint256 constantLpFee;
uint256 sqrtPriceStepStartX96;
int256 nextTick;
bool initialized;
uint256 sqrtPriceNextX96;
bool sqrtPriceStartX96Changed;
}
/// @dev Input of _addLiquidity (userModuleInternals.sol). dexVariables is the unpacked memory copy at the stored
/// (rounded-down) sqrt price; sqrtPriceLowerX96 / UpperX96 are TickMath sqrt ratios of the ticks, computed by the
/// outer module on unvalidated calldata ticks; amount0DesiredRaw / amount1DesiredRaw are raw-adjusted and
/// the liquidity is min(L0, L1) inside the range; isSmartCollateral selects the liquidity rounding (down for D3,
/// up for D4). The position belongs to msg.sender (the `operate` caller).
struct AddLiquidityInternalParams {
DexKey dexKey;
DexVariables dexVariables;
uint256 dexVariables2;
int24 tickLower;
int24 tickUpper;
uint256 sqrtPriceLowerX96;
uint256 sqrtPriceUpperX96;
bytes32 positionSalt; // NOTE: positionSalt for 2 positions can be same for different ranges or different owners, the overall id for a position is a combination of owner, tickLower, tickUpper & positionSalt
uint256 amount0DesiredRaw;
uint256 amount1DesiredRaw;
uint256 dexType;
bytes32 dexId;
bool isSmartCollateral;
}
struct AddLiquidityInternalVariables {
bytes32 positionId;
uint256 maxLiquidityPerTick;
uint256 feeGrowthInside0X102;
uint256 feeGrowthInside1X102;
uint256 feeGrowthBelow0X102;
uint256 feeGrowthBelow1X102;
uint256 feeGrowthAbove0X102;
uint256 feeGrowthAbove1X102;
}
/// @dev Input of _removeLiquidity; as AddLiquidityInternalParams. amount0DesiredRaw / amount1DesiredRaw are
/// raw-adjusted and unbounded (withdraw / payback skip the amount limits): the derived liquidity is clamped to
/// the position, amounts above the position remove all of it and (0, 0) only collects fees.
struct RemoveLiquidityInternalParams {
DexKey dexKey;
DexVariables dexVariables;
uint256 dexVariables2;
int24 tickLower;
int24 tickUpper;
uint256 sqrtPriceLowerX96;
uint256 sqrtPriceUpperX96;
bytes32 positionSalt; // NOTE: positionSalt for 2 positions can be same for different ranges or different owners, the overall id for a position is a combination of owner, tickLower, tickUpper & positionSalt
uint256 amount0DesiredRaw;
uint256 amount1DesiredRaw;
uint256 dexType;
bytes32 dexId;
}
struct RemoveLiquidityInternalVariables {
bytes32 positionId;
uint256 feeGrowthInside0X102;
uint256 feeGrowthInside1X102;
uint256 feeGrowthBelow0X102;
uint256 feeGrowthBelow1X102;
uint256 feeGrowthAbove0X102;
uint256 feeGrowthAbove1X102;
}
/// @dev Calldata of D3 / D4 `initialize`. sqrtPriceX96 is in the exchange-price-scaled 9-decimal raw price space
/// (sqrt(rawAdjusted1 / rawAdjusted0) * 2^96, see constantVariables.sol), not the Uniswap token-unit
/// convention, and must lie strictly inside (MIN_SQRT_PRICE_X96, MAX_SQRT_PRICE_X96).
struct InitializeParams {
DexKey dexKey;
uint256 sqrtPriceX96;
}
struct InitializeInternalParams {
DexKey dexKey;
uint256 sqrtPriceX96;
uint256 dexType;
}
/// @dev Scratch of _initialize: lpFee is the fee version 0 LP fee (0 for a dynamic fee pool); tick is derived from
/// the unrounded input price; token decimals as read from decimals() and then remapped (18 -> 15) for storage.
struct InitializeVariables {
bytes32 dexId;
uint256 lpFee;
int24 tick;
uint256 token0Decimals;
uint256 token1Decimals;
}
contracts/protocols/dexV2/interfaces/iDexV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.36;
/// @title IFluidDexV2
/// @notice Integrator-facing interface of FluidDexV2. Admin, upgrade and Liquidity-callback functions are not part of
/// this interface; see contracts/protocols/dexV2/base/core for the full surface.
/// @dev Integrators must implement IDexV2Callbacks (base/other/interfaces.sol). The trust model, accounting model and
/// accepted behaviours are documented in docs/internal-dev/dexv2-base-notes.md.
interface IFluidDexV2 {
/// @notice Starts an operation: sets the active flag, calls `startOperationCallback(data_)` on msg.sender, then
/// requires that no address has non-zero pending amounts.
/// @dev Reverts with PendingTransfersNotCleared(result_) if pending remains; the revert data carries the callback's
/// return value (used by the Money Market estimate flow) and, being a revert, unwinds the caller's storage.
/// While the operation is active, `operate` and `settle` are callable by any address, not only msg.sender.
/// A nested startOperation reverts with empty revert data.
function startOperation(bytes calldata data_) external returns (bytes memory result_);
/// @notice Routes a call to a D1 (dexType 1), D2 (dexType 2), D3 (dexType 3) or D4 (dexType 4) module:
/// implementationId 1 = swap, 2 = user, 3 = controller (D3 / D4 only).
/// @dev Only callable while an operation is active. Pending amounts created by the module are keyed by msg.sender
/// and must be cleared with `settle` before the operation ends.
function operate(
uint256 dexType_,
uint256 implementationId_,
bytes memory data_
) external returns (bytes memory returnData_);
/// @notice Routes a call to a registered admin implementation. Auth-only; does not require an active operation.
function operateAdmin(
uint256 dexType_,
uint256 implementationId_,
bytes memory data_
) external returns (bytes memory returnData_);
/// @notice Settles the caller's pending amounts for `token_` against the dex balance or the Liquidity layer.
/// @dev Semantics (see FluidDexV2.settle for the full description):
/// - supplyAmount_ / borrowAmount_ / storeAmount_ are applied as signed deltas to the caller's pending supply,
/// pending borrow and stored balance; the caller is not required to have pending amounts.
/// - type(int128).max or min for supplyAmount_ / borrowAmount_ means "my entire pending amount";
/// for storeAmount_ it means borrowAmount_ - supplyAmount_ (net zero, no token transfer).
/// - to_ receives net outflows; address(0) means msg.sender.
/// - Native token: send at least the net inflow as msg.value (excess is refunded to msg.sender);
/// isCallback_ is ignored.
/// - If the Liquidity layer call reverts for any reason, settle reverts with that error (no fallback).
function settle(
address token_,
int256 supplyAmount_,
int256 borrowAmount_,
int256 storeAmount_,
address to_,
bool isCallback_
) external payable;
/// @notice Withdraws a token balance previously stored for the caller (store credits made through settle's
/// storeAmount_).
/// @dev Pays from the dex balance first and otherwise withdraws the dex's own Liquidity supply position, so it can
/// revert with a Liquidity error (withdrawal limit, pause) or an arithmetic panic when the dex's supply for the
/// token is smaller than the amount. Does not require an active operation. Cannot be called from inside
/// `dexCallback` or during a rebalance's Liquidity call (shares the reentrancy lock with settle and rebalance).
function withdrawStoredTokens(address token_, uint256 amount_, address to_) external;
/// @notice Reads a raw storage slot. Base mappings are keyed first by BASE_SLOT (see DexV2BaseSlotsLink).
function readFromStorage(bytes32 slot_) external view returns (uint256 result_);
/// @notice Reads a raw transient storage slot (pending amounts, operation flag, locks).
function readFromTransientStorage(bytes32 slot_) external view returns (uint256 result_);
}
Compiler settingsShow
{
"metadata": {
"useLiteralContent": true
},
"optimizer": {
"runs": 10000000,
"enabled": true
},
"evmVersion": "cancun"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.