Verified contractExactMIT
SwapRouter
Address0xb6d55b223e55bd3ebf3a08a7da6bbebdfe49a2c1
- Balance
0 ETH
- Transactions
20
- Compiler
solc 0.8.19
- Same code
Only this contract
Details
- Compiler
- solc 0.8.19+commit.7dd6d404
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,104,967
- Creation transaction
- 0x5a87b4497c…13a578a010
11 files
- contracts/SwapRouter.solmain31.6 KB
- contracts/dex/IDexAdapter.sol1.74 KB
- contracts/dex/SwapTypes.sol1.04 KB
- contracts/interfaces/IRouterAllowlist.sol3.18 KB
- contracts/interfaces/external/aerodrome/ISlipstreamFactory.sol195 B
- contracts/interfaces/external/algebra/IAlgebraFactory.sol14.41 KB
- contracts/interfaces/external/uniswap/IUniswapV3Factory.sol4.18 KB
- contracts/interfaces/external/uniswap/IUniswapV3Pool.sol9.26 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.77 KB
- lib/solmate/src/tokens/ERC20.sol6.81 KB
- lib/solmate/src/utils/SafeTransferLib.sol6.26 KB
contracts/SwapRouter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeTransferLib } from "solmate/utils/SafeTransferLib.sol";
import { IRouterAllowlist } from "contracts/interfaces/IRouterAllowlist.sol";
import {
IUniswapV3Factory
} from "contracts/interfaces/external/uniswap/IUniswapV3Factory.sol";
import {
IAlgebraFactory
} from "contracts/interfaces/external/algebra/IAlgebraFactory.sol";
import {
IUniswapV3Pool,
IUniswapV3PoolImmutables
} from "contracts/interfaces/external/uniswap/IUniswapV3Pool.sol";
import {
ISlipstreamFactory
} from "contracts/interfaces/external/aerodrome/ISlipstreamFactory.sol";
import { IDexAdapter } from "contracts/dex/IDexAdapter.sol";
import { DexType, SwapStep } from "contracts/dex/SwapTypes.sol";
/// @title SwapRouter
/// @notice A router that executes multi-hop swaps across different DEXs
/// @dev Called via AggregatorConnector like Paraswap/Odos. Each
/// `DexType` is handled by a hot-swappable adapter registered via
/// `setDexAdapter`. SwapRouter owns custody of tokens and ETH; adapters
/// orchestrate via `adapterApprove` / `adapterCall` / `adapterPull`
/// while marked as `_activeAdapter`.
contract SwapRouter {
// ══════════════════════════════════════════════════════════════════════════════
// CONSTANTS
// ══════════════════════════════════════════════════════════════════════════════
/// @notice Maximum fee in basis points (1%)
uint256 public constant MAX_FEE_BPS = 100;
/// @notice Basis points denominator
uint256 public constant BPS_DENOMINATOR = 10_000;
// ══════════════════════════════════════════════════════════════════════════════
// IMMUTABLES
// ══════════════════════════════════════════════════════════════════════════════
/// @notice Router allowlist for security
IRouterAllowlist public immutable allowlist;
/// @notice Fee collector address
address public immutable feeCollector;
/// @notice Wrapped native token address (WETH/WAVAX/etc.)
address public immutable wrappedNative;
// ══════════════════════════════════════════════════════════════════════════════
// STORAGE
// ══════════════════════════════════════════════════════════════════════════════
/// @notice Admin address for configuration
address public admin;
/// @notice Fee in basis points (default 1 bp = 0.01%)
uint256 public feeBps = 1;
/// @notice Per-`DexType` adapter address. `_executeStep` dispatches
/// every swap through the registered adapter; an unset slot reverts
/// with `AdapterNotSet`.
/// @dev Keyed by `uint8` (not `DexType`) so future enum entries can
/// be appended without breaking the public ABI on already-deployed
/// instances.
mapping(uint8 dexType => address adapter) public dexAdapter;
/// @notice Adapter currently authorised to call `adapterApprove` /
/// `adapterCall` / `adapterPull`. Set immediately before
/// `IDexAdapter.swap` and cleared after it returns. Regular storage
/// (not TSTORE/TLOAD) because not every chain in the deployment
/// matrix is confirmed Cancun-capable; explicit clear gives the
/// same single-call-scoping guarantee at a small gas cost.
address private _activeAdapter;
// ══════════════════════════════════════════════════════════════════════════════
// ERRORS
// ══════════════════════════════════════════════════════════════════════════════
error AdapterNotSet(DexType dexType);
error AdapterNotContract();
error NotAdapter();
error SwapFailed(bytes error);
error InsufficientOutputAmount(uint256 received, uint256 minRequired);
error InvalidStepsLength();
error InvalidSplitLength();
error InvalidEthInput();
error Expired();
error NotAdmin();
error InvalidAddress();
error FeeTooHigh();
error InvalidPool();
error InvalidTokenIn();
error InvalidTokenPath();
error FeeOnTransferNotSupported();
// ══════════════════════════════════════════════════════════════════════════════
// EVENTS
// ══════════════════════════════════════════════════════════════════════════════
event MultiSwap(
address indexed sender,
address indexed tokenIn,
address indexed tokenOut,
uint256 amountIn,
uint256 minAmountOut,
uint256 amountOut,
uint256 feeAmount
);
event Sweep(address indexed token, uint256 amount);
event FeeUpdated(uint256 oldFeeBps, uint256 newFeeBps);
event AdminUpdated(address oldAdmin, address newAdmin);
event DexAdapterSet(
uint8 indexed dexType, address oldAdapter, address newAdapter
);
// ══════════════════════════════════════════════════════════════════════════════
// STRUCTS
// ══════════════════════════════════════════════════════════════════════════════
//
// `DexType` and `SwapStep` are declared at file scope in
// `contracts/dex/SwapTypes.sol` so per-DEX adapters can reference them
// without depending on this concrete `SwapRouter` implementation.
// ══════════════════════════════════════════════════════════════════════════════
// CONSTRUCTOR
// ══════════════════════════════════════════════════════════════════════════════
/// @param allowlist_ Router allowlist contract
/// @param admin_ Admin address for configuration
/// @param feeCollector_ Address to receive fees
constructor(
address allowlist_,
address admin_,
address feeCollector_,
address wrappedNative_
) {
if (allowlist_ == address(0)) revert InvalidAddress();
if (admin_ == address(0)) revert InvalidAddress();
if (feeCollector_ == address(0)) revert InvalidAddress();
if (wrappedNative_ == address(0)) revert InvalidAddress();
allowlist = IRouterAllowlist(allowlist_);
admin = admin_;
feeCollector = feeCollector_;
wrappedNative = wrappedNative_;
}
// ══════════════════════════════════════════════════════════════════════════════
// EXTERNAL FUNCTIONS
// ══════════════════════════════════════════════════════════════════════════════
/// @notice Execute a multi-step swap
/// @param steps Array of swap steps to execute
/// @param amountIn Amount of input token
/// @param minAmountOut Minimum output amount
/// @param recipient Address to receive output tokens
/// @param deadline Transaction deadline
/// @return amountOut Actual output amount
function swap(
SwapStep[] calldata steps,
uint256 amountIn,
uint256 minAmountOut,
address recipient,
uint256 deadline
) external payable returns (uint256 amountOut) {
(amountOut,) = _swap(steps, amountIn, minAmountOut, recipient, deadline);
}
/// @notice Execute a multi-step swap and return both output and fee.
/// @dev Used by `BridgeRouter` for exact bridge telemetry without inferring
/// fees from fee-collector balance changes.
function swapWithFee(
SwapStep[] calldata steps,
uint256 amountIn,
uint256 minAmountOut,
address recipient,
uint256 deadline
) external payable returns (uint256 amountOut, uint256 fee) {
return _swap(steps, amountIn, minAmountOut, recipient, deadline);
}
function _swap(
SwapStep[] calldata steps,
uint256 amountIn,
uint256 minAmountOut,
address recipient,
uint256 deadline
) internal returns (uint256 amountOut, uint256 fee) {
if (block.timestamp > deadline) revert Expired();
if (steps.length == 0) revert InvalidStepsLength();
// Execute all steps — use actual received amount (may differ for FOT
// tokens)
uint256 currentAmount = _pullInput(steps[0].tokenIn, amountIn);
for (uint256 i; i < steps.length; i++) {
if (i > 0 && steps[i].tokenIn != steps[i - 1].tokenOut) {
revert InvalidTokenPath();
}
currentAmount = _executeStep(steps[i], currentAmount);
}
// Apply fee and transfer output
address tokenOut = steps[steps.length - 1].tokenOut;
(amountOut, fee) = _applyFeeAndTransfer(
tokenOut, currentAmount, minAmountOut, recipient
);
emit MultiSwap(
msg.sender,
steps[0].tokenIn,
tokenOut,
amountIn,
minAmountOut,
amountOut,
fee
);
}
/// @notice Execute a split swap across multiple parallel routes
/// @dev All routes must have the same input token and output token
/// @param routes Array of routes, each route is an array of swap steps
/// @param amounts Amount of input token for each route
/// @param minAmountOut Minimum total output amount
/// @param recipient Address to receive output tokens
/// @param deadline Transaction deadline
/// @return amountOut Total output amount after fees
function swapSplit(
SwapStep[][] calldata routes,
uint256[] calldata amounts,
uint256 minAmountOut,
address recipient,
uint256 deadline
) external payable returns (uint256 amountOut) {
if (block.timestamp > deadline) revert Expired();
if (routes.length == 0 || routes.length != amounts.length) {
revert InvalidSplitLength();
}
// All routes must have same input and output token
address tokenIn = routes[0][0].tokenIn;
address tokenOut = routes[0][routes[0].length - 1].tokenOut;
// Calculate total input and validate routes
uint256 totalAmountIn =
_validateAndSumAmounts(routes, amounts, tokenIn, tokenOut);
uint256 actualReceived = _pullInput(tokenIn, totalAmountIn);
if (actualReceived != totalAmountIn) {
revert FeeOnTransferNotSupported();
}
// Execute all routes and sum outputs
uint256 totalOutput = _executeRoutes(routes, amounts);
// Apply fee and transfer
uint256 fee;
(amountOut, fee) = _applyFeeAndTransfer(
tokenOut, totalOutput, minAmountOut, recipient
);
emit MultiSwap(
msg.sender,
tokenIn,
tokenOut,
totalAmountIn,
minAmountOut,
amountOut,
fee
);
}
function _validateAndSumAmounts(
SwapStep[][] calldata routes,
uint256[] calldata amounts,
address tokenIn,
address tokenOut
) internal pure returns (uint256 total) {
if (routes[0].length == 0) revert InvalidStepsLength();
total = amounts[0];
for (uint256 i = 1; i < amounts.length; i++) {
total += amounts[i];
if (routes[i].length == 0) revert InvalidStepsLength();
if (routes[i][0].tokenIn != tokenIn) revert InvalidStepsLength();
if (routes[i][routes[i].length - 1].tokenOut != tokenOut) {
revert InvalidStepsLength();
}
}
}
function _executeRoutes(
SwapStep[][] calldata routes,
uint256[] calldata amounts
) internal returns (uint256 totalOutput) {
for (uint256 r; r < routes.length; r++) {
totalOutput += _executeSingleRoute(routes[r], amounts[r]);
}
}
function _executeSingleRoute(
SwapStep[] calldata steps,
uint256 amountIn
) internal returns (uint256 currentAmount) {
currentAmount = amountIn;
for (uint256 s; s < steps.length; s++) {
if (s > 0 && steps[s].tokenIn != steps[s - 1].tokenOut) {
revert InvalidTokenPath();
}
currentAmount = _executeStep(steps[s], currentAmount);
}
}
function _applyFeeAndTransfer(
address tokenOut,
uint256 totalOutput,
uint256 minAmountOut,
address recipient
) internal returns (uint256 amountAfterFee, uint256 fee) {
fee = (totalOutput * feeBps) / BPS_DENOMINATOR;
amountAfterFee = totalOutput - fee;
if (amountAfterFee < minAmountOut) {
revert InsufficientOutputAmount(amountAfterFee, minAmountOut);
}
if (fee > 0) {
if (tokenOut == address(0)) {
SafeTransferLib.safeTransferETH(feeCollector, fee);
} else {
SafeTransferLib.safeTransfer(tokenOut, feeCollector, fee);
}
}
if (tokenOut == address(0)) {
SafeTransferLib.safeTransferETH(recipient, amountAfterFee);
} else {
SafeTransferLib.safeTransfer(tokenOut, recipient, amountAfterFee);
}
}
/// @notice Sweep stuck ERC20 tokens to fee collector
/// @param token Token to sweep
function sweep(
address token
) external {
if (msg.sender != admin) revert NotAdmin();
uint256 balance = IERC20(token).balanceOf(address(this));
if (balance > 0) {
SafeTransferLib.safeTransfer(token, feeCollector, balance);
emit Sweep(token, balance);
}
}
/// @notice Sweep stuck ETH to fee collector
function sweepETH() external {
if (msg.sender != admin) revert NotAdmin();
uint256 balance = address(this).balance;
if (balance > 0) {
SafeTransferLib.safeTransferETH(feeCollector, balance);
emit Sweep(address(0), balance);
}
}
/// @notice Set a new admin
/// @param newAdmin Address of the new admin
function setAdmin(
address newAdmin
) external {
if (msg.sender != admin) revert NotAdmin();
if (newAdmin == address(0)) revert InvalidAddress();
emit AdminUpdated(admin, newAdmin);
admin = newAdmin;
}
/// @notice Set the swap fee
/// @param newFeeBps New fee in basis points
function setFee(
uint256 newFeeBps
) external {
if (msg.sender != admin) revert NotAdmin();
if (newFeeBps > MAX_FEE_BPS) revert FeeTooHigh();
uint256 oldFeeBps = feeBps;
feeBps = newFeeBps;
emit FeeUpdated(oldFeeBps, newFeeBps);
}
/// @notice Register or replace the adapter handling `dexType`.
/// Setting `adapter` to `address(0)` clears the slot, causing
/// subsequent swaps for that `DexType` to revert with
/// `AdapterNotSet`. Non-zero `adapter` must be a contract; this
/// mirrors the EOA-rejection that `RouterAllowlist.setRouter`
/// already does for external routers.
function setDexAdapter(uint8 dexType, address adapter) external {
if (msg.sender != admin) revert NotAdmin();
if (adapter != address(0) && adapter.code.length == 0) {
revert AdapterNotContract();
}
address oldAdapter = dexAdapter[dexType];
if (oldAdapter == adapter) return;
dexAdapter[dexType] = adapter;
emit DexAdapterSet(dexType, oldAdapter, adapter);
}
/// @notice Clear the adapter for `dexType`. After this call any
/// swap step with that type reverts with `AdapterNotSet`.
function emergencyDisableAdapter(uint8 dexType) external {
if (msg.sender != admin) revert NotAdmin();
address oldAdapter = dexAdapter[dexType];
if (oldAdapter == address(0)) return;
dexAdapter[dexType] = address(0);
emit DexAdapterSet(dexType, oldAdapter, address(0));
}
/// @notice Set an ERC20 approval from this contract to `spender` on
/// behalf of the active adapter. Used by router-style adapters so
/// the eventual `transferFrom` lifts tokens directly from
/// `SwapRouter`, keeping the single-FOT-hit accounting (a re-pull
/// into an adapter would tax the transfer twice).
function adapterApprove(
address token,
address spender,
uint256 amount
) external {
if (msg.sender != _activeAdapter) revert NotAdapter();
SafeTransferLib.safeApprove(token, spender, 0);
if (amount > 0) {
SafeTransferLib.safeApprove(token, spender, amount);
}
}
/// @notice Execute an external call from this contract on behalf of
/// the active adapter. Bubbles raw revert data so typed errors
/// (e.g. `InvalidPool()` from `uniswapV3SwapCallback`) reach
/// consumers unchanged.
function adapterCall(
address target,
uint256 value,
bytes calldata data
) external returns (bytes memory) {
if (msg.sender != _activeAdapter) revert NotAdapter();
(bool success, bytes memory result) =
target.call{ value: value }(data);
if (!success) {
if (result.length == 0) revert SwapFailed(result);
assembly {
revert(add(result, 0x20), mload(result))
}
}
return result;
}
/// @notice Transfer custody of `amount` of `token` from this
/// contract to `to`. Adapters use this for the pre-deposit-style
/// router pattern (Velodrome UniversalRouter with
/// `payerIsUser = false`) and inside pool callbacks (where MSR
/// itself is the payer but the active adapter scheduled the swap).
function adapterPull(
address token,
uint256 amount,
address to
) external {
if (msg.sender != _activeAdapter) revert NotAdapter();
SafeTransferLib.safeTransfer(token, to, amount);
}
// ══════════════════════════════════════════════════════════════════════════════
// INTERNAL FUNCTIONS
// ══════════════════════════════════════════════════════════════════════════════
function _pullInput(
address tokenIn,
uint256 amountIn
) internal returns (uint256) {
if (msg.value > 0) {
if (amountIn != msg.value) revert InvalidEthInput();
if (tokenIn != address(0)) revert InvalidEthInput();
return amountIn;
} else {
if (tokenIn == address(0)) revert InvalidEthInput();
uint256 balanceBefore = IERC20(tokenIn).balanceOf(address(this));
SafeTransferLib.safeTransferFrom(
tokenIn, msg.sender, address(this), amountIn
);
return IERC20(tokenIn).balanceOf(address(this)) - balanceBefore;
}
}
function _executeStep(
SwapStep calldata step,
uint256 amountIn
) internal returns (uint256) {
// Router allowlist check (all except direct pool swaps and wrap/unwrap)
if (
step.dexType != DexType.UniswapV3Pool
&& step.dexType != DexType.AlgebraPool
&& step.dexType != DexType.WrapWETH
&& step.dexType != DexType.UnwrapWETH
) {
allowlist.requireAllowed(step.router);
}
// All swap types except WrapWETH, UnwrapWETH, and UniswapV4 require
// ERC20 tokenIn (not native ETH)
if (
step.dexType != DexType.WrapWETH
&& step.dexType != DexType.UnwrapWETH
&& step.dexType != DexType.UniswapV4
&& step.dexType != DexType.PancakeInfinity
) {
if (step.tokenIn == address(0)) revert InvalidAddress();
}
address adapter = dexAdapter[uint8(step.dexType)];
if (adapter == address(0)) revert AdapterNotSet(step.dexType);
return _dispatchAdapter(adapter, step, amountIn);
}
/// @dev Dispatch the step through a registered DEX adapter. Sets
/// the active-adapter slot so the adapter can call back into
/// `adapterApprove` / `adapterCall` / `adapterPull` for the
/// duration of one swap, measures the `tokenOut` balance delta as
/// the authoritative output amount, then clears the slot.
function _dispatchAdapter(
address adapter,
SwapStep calldata step,
uint256 amountIn
) internal returns (uint256) {
uint256 balanceBefore = _balanceOf(step.tokenOut);
_activeAdapter = adapter;
IDexAdapter(adapter).swap(step, amountIn);
_activeAdapter = address(0);
return _balanceDelta(step.tokenOut, balanceBefore);
}
function _balanceOf(
address token
) internal view returns (uint256) {
if (token == address(0)) {
return address(this).balance;
}
return IERC20(token).balanceOf(address(this));
}
function _balanceDelta(
address token,
uint256 balanceBefore
) internal view returns (uint256) {
return _balanceOf(token) - balanceBefore;
}
// ══════════════════════════════════════════════════════════════════════════════
// POOL CALLBACK HELPERS
//
// Direct-pool adapters (`UniswapV3PoolAdapter`, `AlgebraPoolAdapter`)
// invoke `pool.swap(...)` via `adapterCall`, so `SwapRouter` is the
// caller and the pool dispatches its payment callback here. The
// callback re-validates that `msg.sender` is a pool produced by an
// allow-listed factory (independent of the adapter's pre-call
// check) and then pays the requested amount from this contract's
// balance.
// ══════════════════════════════════════════════════════════════════════════════
function _readFeeAndTickSpacing(
address pool
) internal view returns (uint24 fee, int24 tickSpacing) {
(bool ok, bytes memory data) = pool.staticcall(
abi.encodeWithSelector(IUniswapV3PoolImmutables.fee.selector)
);
if (ok && data.length >= 32) {
fee = abi.decode(data, (uint24));
}
(ok, data) = pool.staticcall(
abi.encodeWithSelector(
IUniswapV3PoolImmutables.tickSpacing.selector
)
);
if (ok && data.length >= 32) {
tickSpacing = abi.decode(data, (int24));
}
}
function _isPoolFromFactory(
address factory,
address token0,
address token1,
uint24 fee,
int24 tickSpacing,
address pool
) internal view returns (bool) {
(bool ok, address expected) =
_tryGetV3Pool(factory, token0, token1, fee);
if (ok && expected == pool) return true;
(ok, expected) =
_tryGetSlipstreamPool(factory, token0, token1, tickSpacing);
if (ok && expected == pool) return true;
return false;
}
function _tryGetV3Pool(
address factory,
address token0,
address token1,
uint24 fee
) internal view returns (bool, address) {
(bool success, bytes memory data) = factory.staticcall(
abi.encodeWithSelector(
IUniswapV3Factory.getPool.selector, token0, token1, fee
)
);
if (!success || data.length < 32) {
return (false, address(0));
}
return (true, abi.decode(data, (address)));
}
function _tryGetSlipstreamPool(
address factory,
address token0,
address token1,
int24 tickSpacing
) internal view returns (bool, address) {
(bool success, bytes memory data) = factory.staticcall(
abi.encodeWithSelector(
ISlipstreamFactory.getPool.selector, token0, token1, tickSpacing
)
);
if (!success || data.length < 32) {
return (false, address(0));
}
return (true, abi.decode(data, (address)));
}
function _validateAlgebraPoolTokenIn(
address pool,
address tokenIn,
address customDeployer
) internal view {
(address token0, address token1, address factory) =
_readAlgebraPoolTokensAndFactory(pool);
allowlist.requireAllowedFactory(factory);
if (!_isAlgebraPoolFromFactory(
factory, token0, token1, pool, customDeployer
)) {
revert InvalidPool();
}
if (tokenIn != token0 && tokenIn != token1) {
revert InvalidTokenIn();
}
}
function _readAlgebraPoolTokensAndFactory(
address pool
) internal view returns (address token0, address token1, address factory) {
IUniswapV3Pool algebraPool = IUniswapV3Pool(pool);
token0 = algebraPool.token0();
token1 = algebraPool.token1();
factory = algebraPool.factory();
}
function _isAlgebraPoolFromFactory(
address factory,
address token0,
address token1,
address pool,
address customDeployer
) internal view returns (bool) {
(bool ok, address expected) =
_tryGetAlgebraPoolByPair(factory, token0, token1);
if (ok) {
if (expected == pool) return true;
if (expected != address(0) && customDeployer == address(0)) {
return false;
}
}
if (customDeployer != address(0)) {
allowlist.requireAllowedCustomDeployer(factory, customDeployer);
(ok, expected) = _tryGetAlgebraCustomPoolByPair(
factory, customDeployer, token0, token1
);
if (ok && expected == pool) return true;
}
return false;
}
function _tryGetAlgebraPoolByPair(
address factory,
address token0,
address token1
) internal view returns (bool, address) {
(bool success, bytes memory data) = factory.staticcall(
abi.encodeWithSelector(
IAlgebraFactory.poolByPair.selector, token0, token1
)
);
if (!success || data.length < 32) {
return (false, address(0));
}
return (true, abi.decode(data, (address)));
}
function _tryGetAlgebraCustomPoolByPair(
address factory,
address deployer,
address token0,
address token1
) internal view returns (bool, address) {
(bool success, bytes memory data) = factory.staticcall(
abi.encodeWithSelector(
IAlgebraFactory.customPoolByPair.selector,
deployer,
token0,
token1
)
);
if (!success || data.length < 32) {
return (false, address(0));
}
return (true, abi.decode(data, (address)));
}
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external {
if (amount0Delta <= 0 && amount1Delta <= 0) return;
IUniswapV3Pool v3pool = IUniswapV3Pool(msg.sender);
address token0 = v3pool.token0();
address token1 = v3pool.token1();
address factory = v3pool.factory();
allowlist.requireAllowedFactory(factory);
(uint24 fee, int24 tickSpacing) = _readFeeAndTickSpacing(msg.sender);
if (!_isPoolFromFactory(
factory, token0, token1, fee, tickSpacing, msg.sender
)) {
revert InvalidPool();
}
address payer = abi.decode(data, (address));
// forge-lint: disable-next-line(unsafe-typecast)
uint256 amountToPay =
amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta);
address tokenToPay = amount0Delta > 0 ? token0 : token1;
if (payer == address(this)) {
SafeTransferLib.safeTransfer(tokenToPay, msg.sender, amountToPay);
}
}
/// @notice Callback for Algebra pool swaps
/// @dev Called by the pool during swap to request token payment
function algebraSwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external {
// Decode callback data
(address tokenIn, address payer, address customDeployer) =
abi.decode(data, (address, address, address));
_validateAlgebraPoolTokenIn(msg.sender, tokenIn, customDeployer);
// Determine which token to pay (positive delta = tokens owed to pool)
// forge-lint: disable-next-line(unsafe-typecast)
uint256 amountToPay =
amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta);
// Transfer tokens to the pool
if (payer == address(this)) {
SafeTransferLib.safeTransfer(tokenIn, msg.sender, amountToPay);
}
}
receive() external payable { }
}
contracts/dex/IDexAdapter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { SwapStep } from "contracts/dex/SwapTypes.sol";
/// @title IDexAdapter
/// @notice Interface implemented by per-DEX adapter contracts that
/// `SwapRouter` dispatches to when its `dexAdapter[dexType]` slot is set.
/// @dev Under the Option C custody model, the adapter starts with no
/// tokens and pulls them from `SwapRouter` via `adapterPull` while
/// `SwapRouter` holds it as the in-flight active adapter. Output tokens
/// land back in `SwapRouter`, which measures the balance delta to compute
/// the hop's effective output. The function is `payable` so `SwapRouter`
/// can forward native ETH custody alongside the swap when
/// `step.tokenIn == address(0)`. The interface intentionally does not
/// import the concrete `SwapRouter` contract — adapters depend on the
/// shared `SwapTypes` only.
interface IDexAdapter {
/// @notice Adapter implementation version. Off-chain tooling
/// (vfat-api, deploy scripts) reads this to detect which adapter
/// build is currently wired into `SwapRouter`.
function version() external view returns (uint16);
/// @notice Execute a single swap step on behalf of `SwapRouter`.
/// @param step Swap step parameters (dex type, router, tokens, dex-
/// specific data) as defined by `SwapRouter`'s public ABI.
/// @param amountIn Amount of `step.tokenIn` available for this step.
/// @return amountOut Amount of `step.tokenOut` the adapter believes
/// it delivered to `SwapRouter`. Informational only — `SwapRouter`
/// cross-checks via a balance delta.
function swap(
SwapStep calldata step,
uint256 amountIn
) external payable returns (uint256 amountOut);
}
contracts/dex/SwapTypes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
/// @notice DEX types `SwapRouter` knows how to dispatch. Kept as `uint8`
/// in the public ABI (see `SwapStep.dexType`); adapters and external
/// callers should append new entries rather than reordering existing
/// ones — `dexAdapter[uint8]` mappings on every deployed `SwapRouter`
/// instance are keyed by this enum's byte value.
enum DexType {
UniswapV2,
UniswapV3Router02,
Solidly,
Algebra,
UniswapV4,
VelodromeUniversalRouter,
UniswapV3Router,
AerodromeRouter,
AlgebraPool,
SlipstreamRouter,
BlackholeV2Router,
UniswapV3Pool,
WrapWETH,
UnwrapWETH,
CamelotV2Router,
PancakeInfinity
}
/// @notice One hop of a multi-step swap. Stable, ABI-stable struct used
/// by `SwapRouter`, every `IDexAdapter`, every bridge swap receiver, and
/// every off-chain encoder (vfat-api, deploy scripts).
struct SwapStep {
DexType dexType;
address router;
address tokenIn;
address tokenOut;
bytes dexData;
}
contracts/interfaces/IRouterAllowlist.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
interface IRouterAllowlist {
/// @notice Check if a router is allowed
/// @param router The router address to check
/// @return True if the router is allowed
function isAllowed(address router) external view returns (bool);
/// @notice Revert if the router is not allowed
/// @param router The router address to check
function requireAllowed(address router) external view;
/// @notice Check if a factory is allowed
/// @param factory The factory address to check
/// @return True if the factory is allowed
function isAllowedFactory(address factory) external view returns (bool);
/// @notice Revert if the factory is not allowed
/// @param factory The factory address to check
function requireAllowedFactory(address factory) external view;
/// @notice Check if a custom pool deployer is allowed for a factory
/// @param factory The factory address to check
/// @param deployer The custom pool deployer address to check
/// @return True if the custom deployer is allowed for the factory
function isAllowedCustomDeployer(address factory, address deployer) external view returns (bool);
/// @notice Revert if the custom pool deployer is not allowed for a factory
/// @param factory The factory address to check
/// @param deployer The custom pool deployer address to check
function requireAllowedCustomDeployer(address factory, address deployer) external view;
/// @notice Check if a v4 hook is allowed
/// @param hook The hook address to check
/// @return True if the hook is allowed
function isAllowedHook(address hook) external view returns (bool);
/// @notice Revert if the v4 hook is not allowed
/// @param hook The hook address to check
function requireAllowedHook(address hook) external view;
/// @notice Check if a bridge contract is allowed
/// @param bridge The bridge contract address
/// @return True if the bridge is allowed
function isAllowedBridge(address bridge) external view returns (bool);
/// @notice Revert if the bridge contract is not allowed
/// @param bridge The bridge contract address
function requireAllowedBridge(address bridge) external view;
/// @notice Check if a function selector is allowed for a bridge contract
/// @param bridge The bridge contract address
/// @param selector The function selector
/// @return True if the selector is allowed
function isAllowedSelector(address bridge, bytes4 selector) external view returns (bool);
/// @notice Revert if the function selector is not allowed for a bridge contract
/// @param bridge The bridge contract address
/// @param selector The function selector
function requireAllowedSelector(address bridge, bytes4 selector) external view;
/// @notice Enumerate the currently-allowed function selectors for a bridge
/// @param bridge The bridge contract address
/// @return selectors The set of selectors currently marked allowed for the bridge
function bridgeSelectors(address bridge) external view returns (bytes4[] memory selectors);
}
contracts/interfaces/external/aerodrome/ISlipstreamFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ISlipstreamFactory {
function getPool(address token0, address token1, int24 tickSpacing) external view returns (address);
}
contracts/interfaces/external/algebra/IAlgebraFactory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma abicoder v2;
enum YieldMode {
AUTOMATIC,
VOID,
CLAIMABLE
}
/// @title The interface for the Algebra Factory
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraFactory {
/// @notice Emitted when a process of ownership renounce is started
/// @param timestamp The timestamp of event
/// @param finishTimestamp The timestamp when ownership renounce will be
/// possible to finish
event RenounceOwnershipStart(uint256 timestamp, uint256 finishTimestamp);
/// @notice Emitted when a process of ownership renounce cancelled
/// @param timestamp The timestamp of event
event RenounceOwnershipStop(uint256 timestamp);
/// @notice Emitted when a process of ownership renounce finished
/// @param timestamp The timestamp of ownership renouncement
event RenounceOwnershipFinish(uint256 timestamp);
/// @notice Emitted when a pool is created
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param pool The address of the created pool
event Pool(address indexed token0, address indexed token1, address pool);
/// @notice Emitted when the default community fee is changed
/// @param newDefaultCommunityFee The new default community fee value
event DefaultCommunityFee(uint16 newDefaultCommunityFee);
/// @notice Emitted when the default tickspacing is changed
/// @param newDefaultTickspacing The new default tickspacing value
event DefaultTickspacing(int24 newDefaultTickspacing);
/// @notice Emitted when the default fee is changed
/// @param newDefaultFee The new default fee value
event DefaultFee(uint16 newDefaultFee);
/// @notice Emitted when the defaultPluginFactory address is changed
/// @param defaultPluginFactoryAddress The new defaultPluginFactory address
event DefaultPluginFactory(address defaultPluginFactoryAddress);
/// @notice Emitted when the vaultFactory address is changed
/// @param newVaultFactory The new vaultFactory address
event VaultFactory(address newVaultFactory);
/// @notice Emitted when the pools creation mode is changed
/// @param mode_ The new pools creation mode
event PublicPoolCreationMode(bool mode_);
/// @dev Emitted when set new default blast governor address is changed.
/// @param defaultBlastGovernor The new default blast governor address
event DefaultBlastGovernor(address indexed defaultBlastGovernor);
/// @dev Emitted when set new default blast points address is changed.
/// @param defaultBlastPoints The new default blast points address
event DefaultBlastPoints(address indexed defaultBlastPoints);
/// @dev Emitted when set new default blast points operator address is
/// changed.
/// @param defaultBlastPointsOperator The new default blast points operator
/// address
event DefaultBlastPointsOperator(
address indexed defaultBlastPointsOperator
);
/// @notice Emitted when the rebase configuration for a token is set or
/// updated
/// @param token The address of the token whose rebase configuration has
/// been set or updated
/// @param isRebase Indicates whether the token is set as a rebasing token
/// @param mode The yield mode that has been set for the token, defining its
/// rebasing behavior
event ConfigurationForRebaseToken(
address token, bool isRebase, YieldMode mode
);
/// @dev Emitted when the rebasing tokens governor address is set.
/// @param oldRebasingTokensGovernor The previous address of the rebasing
/// tokens governor.
/// @param newRebasingTokensGovernor The new address of the rebasing tokens
/// governor.
event SetRebasingTokensGovernor(
address indexed oldRebasingTokensGovernor,
address indexed newRebasingTokensGovernor
);
/// @notice role that can change communityFee and tickspacing in pools
/// @return The hash corresponding to this role
function POOLS_ADMINISTRATOR_ROLE() external view returns (bytes32);
/// @notice role that can create pools when public pool creation is disabled
/// @return The hash corresponding to this role
function POOLS_CREATOR_ROLE() external view returns (bytes32);
/// @notice Returns `true` if `account` has been granted `role` or `account`
/// is owner.
/// @param role The hash corresponding to the role
/// @param account The address for which the role is checked
/// @return bool Whether the address has this role or the owner role or not
function hasRoleOrOwner(
bytes32 role,
address account
) external view returns (bool);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via transferOwnership(address
/// newOwner)
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the current default blast governor
/// @return The address of the default blast governor
function defaultBlastGovernor() external view returns (address);
/// @notice Returns the current default blast points
/// @return The address of the default blast points
function defaultBlastPoints() external view returns (address);
/// @notice Returns the current default blast points operator
/// @return The address of the default blast points operator
function defaultBlastPointsOperator() external view returns (address);
/// @notice Retrieves the yield mode configuration for a specified token
/// @param token The address of the token for which to retrieve the yield
/// mode
/// @return The yield mode (rebasing configuration) set for the given token
function configurationForBlastRebaseTokens(
address token
) external view returns (YieldMode);
/// @notice Return if a token is marked as a rebasing token in the factory
/// configuration
/// @param token The address of the token to check
/// @return True if the token is a rebasing token, false otherwise
function isRebaseToken(
address token
) external view returns (bool);
/// @notice Returns the current poolDeployerAddress
/// @return The address of the poolDeployer
function poolDeployer() external view returns (address);
/// @notice Returns the status of enable public pool creation mode
/// @return bool Whether the public creation mode is enable or not
function isPublicPoolCreationMode() external view returns (bool);
/// @notice Returns the default community fee
/// @return Fee which will be set at the creation of the pool
function defaultCommunityFee() external view returns (uint16);
/// @notice Returns the default fee
/// @return Fee which will be set at the creation of the pool
function defaultFee() external view returns (uint16);
/// @notice Returns the default tickspacing
/// @return Tickspacing which will be set at the creation of the pool
function defaultTickspacing() external view returns (int24);
/// @notice Return the current pluginFactory address
/// @dev This contract is used to automatically set a plugin address in new
/// liquidity pools
/// @return Algebra plugin factory
function defaultPluginFactory() external view returns (address);
/// @notice Address of the rebasing tokens governor
/// @return rebasing tokens governor
function rebasingTokensGovernor() external view returns (address);
/// @notice Return the current vaultFactory address
/// @dev This contract is used to automatically set a vault address in new
/// liquidity pools
/// @return Algebra vault factory
function vaultFactory() external view returns (address);
/// @notice Returns the default communityFee, tickspacing, fee and
/// communityFeeVault for pool
/// @param pool the address of liquidity pool
/// @return communityFee which will be set at the creation of the pool
/// @return tickSpacing which will be set at the creation of the pool
/// @return fee which will be set at the creation of the pool
/// @return communityFeeVault the address of communityFeeVault
function defaultConfigurationForPool(
address pool
)
external
view
returns (
uint16 communityFee,
int24 tickSpacing,
uint16 fee,
address communityFeeVault
);
/// @notice Deterministically computes the pool address given the token0 and
/// token1
/// @dev The method does not check if such a pool has been created
/// @param token0 first token
/// @param token1 second token
/// @return pool The contract address of the Algebra pool
function computePoolAddress(
address token0,
address token1
) external view returns (address pool);
/// @notice Returns the pool address for a given pair of tokens, or address
/// 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or
/// token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @return pool The pool address
function poolByPair(
address tokenA,
address tokenB
) external view returns (address pool);
/// @notice Returns the custom pool address for a given deployer and pair
/// @param deployer The custom pool deployer address
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @return customPool The custom pool address
function customPoolByPair(
address deployer,
address tokenA,
address tokenB
) external view returns (address customPool);
/// @notice returns keccak256 of AlgebraPool init bytecode.
/// @dev the hash value changes with any change in the pool bytecode
/// @return Keccak256 hash of AlgebraPool contract init bytecode
function POOL_INIT_CODE_HASH() external view returns (bytes32);
/// @return timestamp The timestamp of the beginning of the
/// renounceOwnership process
function renounceOwnershipStartTimestamp()
external
view
returns (uint256 timestamp);
/// @notice Creates a pool for the given two tokens
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or
/// token1/token0.
/// The call will revert if the pool already exists or the token arguments
/// are invalid.
/// @return pool The address of the newly created pool
function createPool(
address tokenA,
address tokenB
) external returns (address pool);
/// @dev updates pools creation mode
/// @param mode_ the new mode for pools creation proccess
function setIsPublicPoolCreationMode(
bool mode_
) external;
/// @notice Sets the rebase configuration for a specific token
/// @param token_ The address of the token to configure
/// @param isRebase_ A boolean indicating whether the token is a rebasing
/// token or not
/// @param mode_ The yield mode to apply, defining how the rebasing
/// mechanism should operate
function setConfigurationForRebaseToken(
address token_,
bool isRebase_,
YieldMode mode_
) external;
/// @notice Sets the address of the rebasing tokens governor.
/// @dev Updates the address of the rebasing tokens governor. Can only be
/// called by an account with the DEFAULT_ADMIN_ROLE.
/// @param rebasingTokensGovernor_ The new address of the rebasing tokens
/// governor.
/// Emits a {SetRebasingTokensGovernor} event.
function setRebasingTokensGovernor(
address rebasingTokensGovernor_
) external;
/// @dev updates default community fee for new pools
/// @param newDefaultCommunityFee The new community fee, _must_ be <=
/// MAX_COMMUNITY_FEE
function setDefaultCommunityFee(
uint16 newDefaultCommunityFee
) external;
/// @dev updates default fee for new pools
/// @param newDefaultFee The new fee, _must_ be <= MAX_DEFAULT_FEE
function setDefaultFee(
uint16 newDefaultFee
) external;
/// @dev updates default tickspacing for new pools
/// @param newDefaultTickspacing The new tickspacing, _must_ be <=
/// MAX_TICK_SPACING and >= MIN_TICK_SPACING
function setDefaultTickspacing(
int24 newDefaultTickspacing
) external;
/// @dev updates pluginFactory address
/// @param newDefaultPluginFactory address of new plugin factory
function setDefaultPluginFactory(
address newDefaultPluginFactory
) external;
/// @dev updates vaultFactory address
/// @param newVaultFactory address of new vault factory
function setVaultFactory(
address newVaultFactory
) external;
/// @notice Starts process of renounceOwnership. After that, a certain
/// period
/// of time must pass before the ownership renounce can be completed.
function startRenounceOwnership() external;
/// @notice Stops process of renounceOwnership and removes timer.
function stopRenounceOwnership() external;
/// @dev updates default blast governor address on the factory
/// @param defaultBlastGovernor_ The new defautl blast governor address
function setDefaultBlastGovernor(
address defaultBlastGovernor_
) external;
/// @dev updates default blast points address on the factory
/// @param defaultBlastPoints_ The new defautl blast points address
function setDefaultBlastPoints(
address defaultBlastPoints_
) external;
/// @dev updates default blast points operator address on the factory
/// @param defaultBlastPointsOperator_ The new defautl blast points operator
/// address
function setDefaultBlastPointsOperator(
address defaultBlastPointsOperator_
) external;
}
contracts/interfaces/external/uniswap/IUniswapV3Factory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and
/// control over the protocol fees
interface IUniswapV3Factory {
/// @notice Emitted when the owner of the factory is changed
/// @param oldOwner The owner before the owner was changed
/// @param newOwner The owner after the owner was changed
event OwnerChanged(address indexed oldOwner, address indexed newOwner);
/// @notice Emitted when a pool is created
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in
/// hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param pool The address of the created pool
event PoolCreated(
address indexed token0,
address indexed token1,
uint24 indexed fee,
int24 tickSpacing,
address pool
);
/// @notice Emitted when a new fee amount is enabled for pool creation via
/// the factory
/// @param fee The enabled fee, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// for pools created with the given fee
event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via setOwner
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the tick spacing for a given fee amount, if enabled, or
/// 0 if not enabled
/// @dev A fee amount can never be removed, so this value should be hard
/// coded or cached in the calling context
/// @param fee The enabled fee, denominated in hundredths of a bip. Returns
/// 0 in case of unenabled fee
/// @return The tick spacing
function feeAmountTickSpacing(
uint24 fee
) external view returns (int24);
/// @notice Returns the pool address for a given pair of tokens and a fee,
/// or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or
/// token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param fee The fee collected upon every swap in the pool, denominated in
/// hundredths of a bip
/// @return pool The pool address
function getPool(
address tokenA,
address tokenB,
uint24 fee
) external view returns (address pool);
/// @notice Creates a pool for the given two tokens and fee
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param fee The desired fee for the pool
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or
/// token1/token0. tickSpacing is retrieved
/// from the fee. The call will revert if the pool already exists, the fee
/// is invalid, or the token arguments
/// are invalid.
/// @return pool The address of the newly created pool
function createPool(
address tokenA,
address tokenB,
uint24 fee
) external returns (address pool);
/// @notice Updates the owner of the factory
/// @dev Must be called by the current owner
/// @param _owner The new owner of the factory
function setOwner(
address _owner
) external;
/// @notice Enables a fee amount with the given tickSpacing
/// @dev Fee amounts may never be removed once enabled
/// @param fee The fee amount to enable, denominated in hundredths of a bip
/// (i.e. 1e-6)
/// @param tickSpacing The spacing between ticks to be enforced for all
/// pools created with the given fee amount
function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}
contracts/interfaces/external/uniswap/IUniswapV3Pool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods
/// will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the
/// IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and
/// always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick,
/// i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always
/// positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick
/// in the range
/// @dev This parameter is enforced per tick to prevent liquidity from
/// overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding
/// in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any
/// frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is
/// exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a
/// sqrt(token1/token0) Q64.96 value
/// @return tick The current tick of the pool, i.e. according to the last
/// tick transition that was run.
/// This value may not always be equal to
/// SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// @return observationIndex The index of the last oracle observation that
/// was written,
/// @return observationCardinality The current maximum number of
/// observations stored in the pool,
/// @return observationCardinalityNext The next maximum number of
/// observations, to be updated when the observation.
/// @return feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted
/// 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap
/// fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit
/// of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit
/// of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees()
external
view
returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all
/// ticks
/// @return The liquidity at the current price of the pool
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses
/// the pool either as tick lower or
/// tick upper
/// @return liquidityNet how much liquidity changes when the pool price
/// crosses the tick,
/// @return feeGrowthOutside0X128 the fee growth on the other side of the
/// tick from the current tick in token0,
/// @return feeGrowthOutside1X128 the fee growth on the other side of the
/// tick from the current tick in token1,
/// @return tickCumulativeOutside the cumulative tick value on the other
/// side of the tick from the current tick
/// @return secondsPerLiquidityOutsideX128 the seconds spent per liquidity
/// on the other side of the tick from the current tick,
/// @return secondsOutside the seconds spent on the other side of the tick
/// from the current tick,
/// @return initialized Set to true if the tick is initialized, i.e.
/// liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if
/// liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in
/// comparison to previous snapshots for
/// a specific position.
function ticks(
int24 tick
)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See
/// TickBitmap for more information
function tickBitmap(
int16 wordPosition
) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the
/// owner, tickLower and tickUpper
/// @return liquidity The amount of liquidity in the position,
/// @return feeGrowthInside0LastX128 fee growth of token0 inside the tick
/// range as of the last mint/burn/poke,
/// @return feeGrowthInside1LastX128 fee growth of token1 inside the tick
/// range as of the last mint/burn/poke,
/// @return tokensOwed0 the computed amount of token0 owed to the position
/// as of the last mint/burn/poke,
/// @return tokensOwed1 the computed amount of token1 owed to the position
/// as of the last mint/burn/poke
function positions(
bytes32 key
)
external
view
returns (
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to
/// get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// @return tickCumulative the tick multiplied by seconds elapsed for the
/// life of the pool as of the observation timestamp,
/// @return secondsPerLiquidityCumulativeX128 the seconds per in range
/// liquidity for the life of the pool as of the observation timestamp,
/// @return initialized whether the observation has been initialized and the
/// values are safe to use
function observations(
uint256 index
)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState {
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
}
lib/openzeppelin-contracts/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);
}
lib/solmate/src/tokens/ERC20.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/*//////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*//////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*//////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*//////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*//////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
address recoveredAddress = ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
),
v,
r,
s
);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*//////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
lib/solmate/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
import {ERC20} from "../tokens/ERC20.sol";
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
error ETHTransferFailed();
error TransferFromFailed();
error TransferFailed();
error ApproveFailed();
/*//////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Transfer the ETH and store if it succeeded or not.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
if (!success) revert ETHTransferFailed();
}
/*//////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferFrom(
address token,
address from,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
)
}
if (!success) revert TransferFromFailed();
}
function safeTransfer(
address token,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
if (!success) revert TransferFailed();
}
function safeApprove(
address token,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
if (!success) revert ApproveFailed();
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris",
"remappings": [
"solmate/=lib/solmate/src/",
"@openzeppelin/=lib/openzeppelin-contracts/",
"@morpho-blue/=lib/morpho-blue/src/",
"ds-test/=lib/solmate/lib/ds-test/src/",
"forge-std/=lib/forge-std/src/",
"morpho-blue/=lib/morpho-blue/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.