Verified contractExactBUSL-1.1
UniV3ForkSR02Implementation
Address0x6dcee3efbe8d6d20d2898f740feaa5e5e5bff2aa
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 1,000,000 runs
- EVM version
- cancun
- Via IR
- yes
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,109,923
- Creation transaction
- 0x16f3cca1bd…6ea817b829
14 files
- src/dex-implementations/uniV3Fork/UniV3ForkSR02Implementation.solmain4.23 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol193 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol13.31 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- src/dex-implementations/uniV3Fork/BaseUniV3ForkImplementation.sol27.99 KB
- src/interfaces/IDexImplementation.sol6.15 KB
- src/interfaces/IQuoterV2.sol1.57 KB
- src/interfaces/ISwapRouter.sol1.36 KB
- src/interfaces/IUniswapV3Factory.sol223 B
- src/interfaces/IUniswapV3Pool.sol1.43 KB
- src/libraries/SwapWizardStorage.sol3.4 KB
src/dex-implementations/uniV3Fork/UniV3ForkSR02Implementation.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
// ╔════════════════════════════════════════════════════════════════════════════╗
// ║ UniV3ForkSR02Implementation ║
// ║ Concrete adapter for UniV3 forks that ship SwapRouter02 (no deadline in ║
// ║ the params struct). Examples per chain (`v3_fork_dexes` router_kind=0): ║
// ║ Eth : Uniswap V3 ║
// ║ BSC : Uniswap V3, PancakeSwap V3 SmartRouter ║
// ║ Polygon : Uniswap V3 ║
// ║ Base : Uniswap V3 ║
// ║ Arbitrum: Uniswap V3 ║
// ╚════════════════════════════════════════════════════════════════════════════╝
import {ISwapRouter} from "../../interfaces/ISwapRouter.sol";
import {BaseUniV3ForkImplementation} from "./BaseUniV3ForkImplementation.sol";
contract UniV3ForkSR02Implementation is BaseUniV3ForkImplementation {
/// @dev "UNIV3_SR02" as left-padded bytes32.
bytes32 public constant KIND = 0x554e4956335f5352303200000000000000000000000000000000000000000000;
constructor(address router_, address quoter_, address factory_, address stable_, address bridge_)
BaseUniV3ForkImplementation(router_, quoter_, factory_, stable_, bridge_)
{}
function kind() external pure override returns (bytes32) {
return KIND;
}
// ── SR02 exact-input variants (no `deadline` field in the struct) ───────
function _execExactInputSingle(
address tokenIn,
address tokenOut,
uint24 fee,
uint256 amountIn,
uint256 minOut,
address recipient,
uint256 /*deadline*/
) internal override returns (uint256) {
return ISwapRouter(ROUTER).exactInputSingle(
ISwapRouter.ExactInputSingleParams({
tokenIn: tokenIn,
tokenOut: tokenOut,
fee: fee,
recipient: recipient,
amountIn: amountIn,
amountOutMinimum: minOut,
sqrtPriceLimitX96: 0
})
);
}
function _execExactInput(
bytes memory path,
uint256 amountIn,
uint256 minOut,
address recipient,
uint256 /*deadline*/
) internal override returns (uint256) {
return ISwapRouter(ROUTER).exactInput(
ISwapRouter.ExactInputParams({
path: path,
recipient: recipient,
amountIn: amountIn,
amountOutMinimum: minOut
})
);
}
function _execExactOutputSingle(
address tokenIn,
address tokenOut,
uint24 fee,
uint256 amountOut,
uint256 maxIn,
address recipient,
uint256 /*deadline*/
) internal override returns (uint256) {
return ISwapRouter(ROUTER).exactOutputSingle(
ISwapRouter.ExactOutputSingleParams({
tokenIn: tokenIn,
tokenOut: tokenOut,
fee: fee,
recipient: recipient,
amountOut: amountOut,
amountInMaximum: maxIn,
sqrtPriceLimitX96: 0
})
);
}
function _execExactOutput(
bytes memory path,
uint256 amountOut,
uint256 maxIn,
address recipient,
uint256 /*deadline*/
) internal override returns (uint256) {
return ISwapRouter(ROUTER).exactOutput(
ISwapRouter.ExactOutputParams({
path: path,
recipient: recipient,
amountOut: amountOut,
amountInMaximum: maxIn
})
);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
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 value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` 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 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Transfer `value` 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.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
* return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
* value: the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
* the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
src/dex-implementations/uniV3Fork/BaseUniV3ForkImplementation.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
// ╔════════════════════════════════════════════════════════════════════════════╗
// ║ BaseUniV3ForkImplementation (abstract) ║
// ║ Route discovery / quoting / path encoding shared by Uniswap-V3 and all ║
// ║ ABI-compatible forks. Concrete subclasses only override the 4 router ║
// ║ call wrappers to account for the SR02 (no-deadline) vs legacy (with- ║
// ║ deadline) ABI split. ║
// ╠════════════════════════════════════════════════════════════════════════════╣
// ║ Storage safety: this contract declares ZERO state variables. All ║
// ║ per-chain config lives in `immutable`s (baked into bytecode, not ║
// ║ storage); all runtime state (registry + approval cache) lives in the ║
// ║ Core's ERC-7201 namespaced slot via SwapWizardStorage. This is ║
// ║ load-bearing: the contract is invoked by SwapWizardCore through ║
// ║ `delegatecall`, so any storage declared here would collide with Core. ║
// ╚════════════════════════════════════════════════════════════════════════════╝
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IDexImplementation} from "../../interfaces/IDexImplementation.sol";
import {IUniswapV3Factory} from "../../interfaces/IUniswapV3Factory.sol";
import {IUniswapV3Pool} from "../../interfaces/IUniswapV3Pool.sol";
import {IQuoterV2} from "../../interfaces/IQuoterV2.sol";
import {SwapWizardStorage} from "../../libraries/SwapWizardStorage.sol";
abstract contract BaseUniV3ForkImplementation is IDexImplementation {
using SafeERC20 for IERC20;
// ── Immutable per-chain config ──────────────────────────────────────────
/// @notice SwapRouter (or SwapRouter02) address for this fork.
address public immutable ROUTER;
/// @notice QuoterV2 address for this fork. Quoter reverts on no-route, so
/// every discovery probe is wrapped in try/catch.
address public immutable QUOTER;
/// @notice V3 factory — used to short-circuit pool existence checks before
/// wasting a quoter call.
IUniswapV3Factory public immutable FACTORY;
/// @notice Chain's canonical stable (USDC by default). Probed as a multihop
/// intermediate. Set to address(0) to disable the stable hop.
address public immutable STABLE;
/// @notice Chain's canonical bridge asset (WETH/WBNB/etc). Probed as a
/// second multihop intermediate. Set to address(0) to disable.
address public immutable BRIDGE;
// ── Canonical V3 fee tiers ──────────────────────────────────────────────
uint24 internal constant FEE_100 = 100; // 0.01%
uint24 internal constant FEE_500 = 500; // 0.05%
uint24 internal constant FEE_3000 = 3000; // 0.30%
uint24 internal constant FEE_10000 = 10_000; // 1.00%
/// @dev Sentinel: first 32 bytes of execDataIn. Signals that the blob
/// carries extra intermediary token addresses for multihop discovery.
/// Format: abi.encode(uint256 tag, address[] intermediaries)
uint256 internal constant HINT_TAG_INTERMEDIARIES = type(uint256).max;
// ══════════════════════════════════════════════════════════════════════
// Route encoding
// ══════════════════════════════════════════════════════════════════════
/// @dev Two route shapes supported by this family. Meta-adapters (Split,
/// V4) use their own encodings — they never reach this contract.
enum RouteKind {
Direct, // single pool: tokenIn --feeA--> tokenOut
Multihop // two pools via `mid`: tokenIn --feeA--> mid --feeB--> tokenOut
}
/// @notice ABI-encoded blob used as `execData` for this adapter family.
/// Produced by `_discover*` during off-chain quoting and consumed
/// verbatim by the on-chain swap path.
struct RouteData {
RouteKind kind;
uint24 feeA;
uint24 feeB; // unused when kind == Direct
address mid; // unused when kind == Direct
}
// ── Errors ──────────────────────────────────────────────────────────────
error ZeroAddress();
error InvalidExecData();
error NoPool();
error InsufficientOutput();
constructor(address router_, address quoter_, address factory_, address stable_, address bridge_) {
if (router_ == address(0) || quoter_ == address(0) || factory_ == address(0)) revert ZeroAddress();
ROUTER = router_;
QUOTER = quoter_;
FACTORY = IUniswapV3Factory(factory_);
STABLE = stable_;
BRIDGE = bridge_;
}
// ══════════════════════════════════════════════════════════════════════
// IDexImplementation — metadata
// ══════════════════════════════════════════════════════════════════════
/// @dev Concrete subclasses override with a stable tag
/// (e.g. "UNIV3_SR02" / "UNIV3_LEGACY").
function kind() external pure virtual returns (bytes32);
/// @notice Maximum `liquidity()` observed across the 4 canonical fee tiers
/// for the direct (tokenIn, tokenOut) pair. Intentionally ignores
/// multihop routes — this value is only used for intra-family
/// ranking by the off-chain picker and doesn't need to be exact.
function liquidityFor(address tokenIn, address tokenOut) external view returns (uint256) {
uint24[4] memory fees = [FEE_100, FEE_500, FEE_3000, FEE_10000];
uint128 best;
for (uint256 i; i < 4; ) {
address pool = FACTORY.getPool(tokenIn, tokenOut, fees[i]);
if (pool != address(0)) {
try IUniswapV3Pool(pool).liquidity() returns (uint128 L) {
if (L > best) best = L;
} catch {}
}
unchecked { ++i; }
}
return best;
}
// ══════════════════════════════════════════════════════════════════════
// IDexImplementation — quoting
// ══════════════════════════════════════════════════════════════════════
function quoteExactIn(address tokenIn, address tokenOut, uint256 amountIn, bytes calldata execDataIn)
external
returns (uint256 amountOut, bytes memory execDataOut)
{
if (execDataIn.length == 0) {
return _discoverExactIn(tokenIn, tokenOut, amountIn);
}
if (_isIntermediaryHint(execDataIn)) {
return _discoverWithIntermediariesIn(tokenIn, tokenOut, amountIn, execDataIn);
}
RouteData memory r = abi.decode(execDataIn, (RouteData));
amountOut = _quoteRouteIn(tokenIn, tokenOut, amountIn, r);
execDataOut = execDataIn;
}
function quoteExactOut(address tokenIn, address tokenOut, uint256 amountOut, bytes calldata execDataIn)
external
returns (uint256 amountIn, bytes memory execDataOut)
{
if (execDataIn.length == 0) {
return _discoverExactOut(tokenIn, tokenOut, amountOut);
}
if (_isIntermediaryHint(execDataIn)) {
return _discoverWithIntermediariesOut(tokenIn, tokenOut, amountOut, execDataIn);
}
RouteData memory r = abi.decode(execDataIn, (RouteData));
amountIn = _quoteRouteOut(tokenIn, tokenOut, amountOut, r);
execDataOut = execDataIn;
}
// ══════════════════════════════════════════════════════════════════════
// IDexImplementation — execution
// ══════════════════════════════════════════════════════════════════════
function swapExactIn(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minOut,
address recipient,
uint256 deadline,
bytes calldata execData
) external payable returns (uint256 amountOut) {
RouteData memory r = _routeOrDiscoverIn(tokenIn, tokenOut, amountIn, execData);
_ensureApproved(tokenIn, ROUTER);
if (r.kind == RouteKind.Direct) {
amountOut = _execExactInputSingle(tokenIn, tokenOut, r.feeA, amountIn, minOut, recipient, deadline);
} else {
bytes memory path = abi.encodePacked(tokenIn, r.feeA, r.mid, r.feeB, tokenOut);
amountOut = _execExactInput(path, amountIn, minOut, recipient, deadline);
}
// Routers already enforce minOut, but we revert on the degenerate
// 0-output case explicitly.
if (amountOut == 0) revert InsufficientOutput();
}
function swapExactOut(
address tokenIn,
address tokenOut,
uint256 amountOut,
uint256 maxIn,
address recipient,
uint256 deadline,
bytes calldata execData
) external payable returns (uint256 amountInSpent) {
RouteData memory r = _routeOrDiscoverOut(tokenIn, tokenOut, amountOut, execData);
_ensureApproved(tokenIn, ROUTER);
if (r.kind == RouteKind.Direct) {
amountInSpent = _execExactOutputSingle(tokenIn, tokenOut, r.feeA, amountOut, maxIn, recipient, deadline);
} else {
// Exact-output paths are encoded tail-first: tokenOut -> mid -> tokenIn
// with the fees in reverse order too (feeB first, then feeA).
bytes memory path = abi.encodePacked(tokenOut, r.feeB, r.mid, r.feeA, tokenIn);
amountInSpent = _execExactOutput(path, amountOut, maxIn, recipient, deadline);
}
}
// ══════════════════════════════════════════════════════════════════════
// Virtual hooks — ABI split between SR02 (no-deadline) and legacy.
// Concrete subclasses override these with their router-specific calls.
// ══════════════════════════════════════════════════════════════════════
function _execExactInputSingle(
address tokenIn,
address tokenOut,
uint24 fee,
uint256 amountIn,
uint256 minOut,
address recipient,
uint256 deadline
) internal virtual returns (uint256 amountOut);
function _execExactInput(
bytes memory path,
uint256 amountIn,
uint256 minOut,
address recipient,
uint256 deadline
) internal virtual returns (uint256 amountOut);
function _execExactOutputSingle(
address tokenIn,
address tokenOut,
uint24 fee,
uint256 amountOut,
uint256 maxIn,
address recipient,
uint256 deadline
) internal virtual returns (uint256 amountInSpent);
function _execExactOutput(
bytes memory path,
uint256 amountOut,
uint256 maxIn,
address recipient,
uint256 deadline
) internal virtual returns (uint256 amountInSpent);
// ══════════════════════════════════════════════════════════════════════
// Discovery
// ══════════════════════════════════════════════════════════════════════
/// @dev Search for the best exact-input route: direct pools (4 fee tiers),
/// then multihop through STABLE, then multihop through BRIDGE.
function _discoverExactIn(address tokenIn, address tokenOut, uint256 amountIn)
internal
returns (uint256 bestOut, bytes memory bestData)
{
// 1. Direct
uint24[4] memory fees = [FEE_100, FEE_500, FEE_3000, FEE_10000];
for (uint256 i; i < 4; ) {
uint24 f = fees[i];
if (FACTORY.getPool(tokenIn, tokenOut, f) != address(0)) {
uint256 out = _safeQuoteSingleIn(tokenIn, tokenOut, f, amountIn);
if (out > bestOut) {
bestOut = out;
bestData = abi.encode(RouteData(RouteKind.Direct, f, 0, address(0)));
}
}
unchecked { ++i; }
}
// 2. Via STABLE
if (_isUsableMid(STABLE, tokenIn, tokenOut)) {
(uint256 out, uint24 fA, uint24 fB) = _bestMultihopIn(tokenIn, STABLE, tokenOut, amountIn);
if (out > bestOut) {
bestOut = out;
bestData = abi.encode(RouteData(RouteKind.Multihop, fA, fB, STABLE));
}
}
// 3. Via BRIDGE
if (_isUsableMid(BRIDGE, tokenIn, tokenOut) && BRIDGE != STABLE) {
(uint256 out, uint24 fA, uint24 fB) = _bestMultihopIn(tokenIn, BRIDGE, tokenOut, amountIn);
if (out > bestOut) {
bestOut = out;
bestData = abi.encode(RouteData(RouteKind.Multihop, fA, fB, BRIDGE));
}
}
}
/// @dev Exact-output discovery: lowest `amountIn` wins. Returns (0, "")
/// when no route was found (callers rely on the 0-sentinel).
function _discoverExactOut(address tokenIn, address tokenOut, uint256 amountOut)
internal
returns (uint256 bestIn, bytes memory bestData)
{
bestIn = type(uint256).max;
// 1. Direct
uint24[4] memory fees = [FEE_100, FEE_500, FEE_3000, FEE_10000];
for (uint256 i; i < 4; ) {
uint24 f = fees[i];
if (FACTORY.getPool(tokenIn, tokenOut, f) != address(0)) {
uint256 inAmt = _safeQuoteSingleOut(tokenIn, tokenOut, f, amountOut);
if (inAmt != 0 && inAmt < bestIn) {
bestIn = inAmt;
bestData = abi.encode(RouteData(RouteKind.Direct, f, 0, address(0)));
}
}
unchecked { ++i; }
}
// 2. Via STABLE
if (_isUsableMid(STABLE, tokenIn, tokenOut)) {
(uint256 inAmt, uint24 fA, uint24 fB) = _bestMultihopOut(tokenIn, STABLE, tokenOut, amountOut);
if (inAmt != 0 && inAmt < bestIn) {
bestIn = inAmt;
bestData = abi.encode(RouteData(RouteKind.Multihop, fA, fB, STABLE));
}
}
// 3. Via BRIDGE
if (_isUsableMid(BRIDGE, tokenIn, tokenOut) && BRIDGE != STABLE) {
(uint256 inAmt, uint24 fA, uint24 fB) = _bestMultihopOut(tokenIn, BRIDGE, tokenOut, amountOut);
if (inAmt != 0 && inAmt < bestIn) {
bestIn = inAmt;
bestData = abi.encode(RouteData(RouteKind.Multihop, fA, fB, BRIDGE));
}
}
if (bestIn == type(uint256).max) bestIn = 0;
}
/// @dev Probe (fA, fB) combinations using the low/mid tier set. The 10000
/// tier is omitted on multihop intentionally — stable/bridge pools
/// almost never live there and the extra branch dominates gas.
function _bestMultihopIn(address a, address mid, address b, uint256 amountIn)
internal
returns (uint256 bestOut, uint24 bestFa, uint24 bestFb)
{
uint24[3] memory fees = [FEE_100, FEE_500, FEE_3000];
for (uint256 i; i < 3; ) {
uint24 fA = fees[i];
if (FACTORY.getPool(a, mid, fA) != address(0)) {
for (uint256 j; j < 3; ) {
uint24 fB = fees[j];
if (FACTORY.getPool(mid, b, fB) != address(0)) {
bytes memory path = abi.encodePacked(a, fA, mid, fB, b);
uint256 out = _safeQuoteIn(path, amountIn);
if (out > bestOut) {
bestOut = out;
bestFa = fA;
bestFb = fB;
}
}
unchecked { ++j; }
}
}
unchecked { ++i; }
}
}
function _bestMultihopOut(address a, address mid, address b, uint256 amountOut)
internal
returns (uint256 bestIn, uint24 bestFa, uint24 bestFb)
{
bestIn = type(uint256).max;
uint24[3] memory fees = [FEE_100, FEE_500, FEE_3000];
for (uint256 i; i < 3; ) {
uint24 fA = fees[i];
if (FACTORY.getPool(a, mid, fA) != address(0)) {
for (uint256 j; j < 3; ) {
uint24 fB = fees[j];
if (FACTORY.getPool(mid, b, fB) != address(0)) {
bytes memory path = abi.encodePacked(b, fB, mid, fA, a);
uint256 inAmt = _safeQuoteOut(path, amountOut);
if (inAmt != 0 && inAmt < bestIn) {
bestIn = inAmt;
bestFa = fA;
bestFb = fB;
}
}
unchecked { ++j; }
}
}
unchecked { ++i; }
}
if (bestIn == type(uint256).max) bestIn = 0;
}
// ══════════════════════════════════════════════════════════════════════
// Pre-picked route — re-quote a known RouteData
// ══════════════════════════════════════════════════════════════════════
function _quoteRouteIn(address tokenIn, address tokenOut, uint256 amountIn, RouteData memory r)
internal
returns (uint256)
{
if (r.kind == RouteKind.Direct) {
return _safeQuoteSingleIn(tokenIn, tokenOut, r.feeA, amountIn);
}
bytes memory path = abi.encodePacked(tokenIn, r.feeA, r.mid, r.feeB, tokenOut);
return _safeQuoteIn(path, amountIn);
}
function _quoteRouteOut(address tokenIn, address tokenOut, uint256 amountOut, RouteData memory r)
internal
returns (uint256)
{
if (r.kind == RouteKind.Direct) {
return _safeQuoteSingleOut(tokenIn, tokenOut, r.feeA, amountOut);
}
bytes memory path = abi.encodePacked(tokenOut, r.feeB, r.mid, r.feeA, tokenIn);
return _safeQuoteOut(path, amountOut);
}
// ══════════════════════════════════════════════════════════════════════
// Safe quoter wrappers
//
// V3 quoters run the swap in a try/revert pattern, so the expected
// failure mode on "no route" is a revert, not a 0 return. Every probe is
// wrapped in try/catch so discovery can continue past dead pools.
// ══════════════════════════════════════════════════════════════════════
function _safeQuoteSingleIn(address tokenIn, address tokenOut, uint24 fee, uint256 amountIn)
internal
virtual
returns (uint256)
{
IQuoterV2.QuoteExactInputSingleParams memory p = IQuoterV2.QuoteExactInputSingleParams({
tokenIn: tokenIn,
tokenOut: tokenOut,
amountIn: amountIn,
fee: fee,
sqrtPriceLimitX96: 0
});
try IQuoterV2(QUOTER).quoteExactInputSingle(p) returns (uint256 out, uint160, uint32, uint256) {
return out;
} catch {
return 0;
}
}
function _safeQuoteSingleOut(address tokenIn, address tokenOut, uint24 fee, uint256 amountOut)
internal
virtual
returns (uint256)
{
IQuoterV2.QuoteExactOutputSingleParams memory p = IQuoterV2.QuoteExactOutputSingleParams({
tokenIn: tokenIn,
tokenOut: tokenOut,
amount: amountOut,
fee: fee,
sqrtPriceLimitX96: 0
});
try IQuoterV2(QUOTER).quoteExactOutputSingle(p) returns (uint256 inAmt, uint160, uint32, uint256) {
return inAmt;
} catch {
return 0;
}
}
function _safeQuoteIn(bytes memory path, uint256 amountIn) internal virtual returns (uint256) {
try IQuoterV2(QUOTER).quoteExactInput(path, amountIn)
returns (uint256 out, uint160[] memory, uint32[] memory, uint256)
{
return out;
} catch {
return 0;
}
}
function _safeQuoteOut(bytes memory path, uint256 amountOut) internal virtual returns (uint256) {
try IQuoterV2(QUOTER).quoteExactOutput(path, amountOut)
returns (uint256 inAmt, uint160[] memory, uint32[] memory, uint256)
{
return inAmt;
} catch {
return 0;
}
}
// ══════════════════════════════════════════════════════════════════════
// Helpers
// ══════════════════════════════════════════════════════════════════════
/// @dev Execute path: decode pre-picked route if present, otherwise
/// rediscover on-chain.
function _routeOrDiscoverIn(address tokenIn, address tokenOut, uint256 amountIn, bytes calldata execData)
internal
returns (RouteData memory r)
{
if (execData.length != 0) return abi.decode(execData, (RouteData));
(, bytes memory dd) = _discoverExactIn(tokenIn, tokenOut, amountIn);
if (dd.length == 0) revert NoPool();
r = abi.decode(dd, (RouteData));
}
function _routeOrDiscoverOut(address tokenIn, address tokenOut, uint256 amountOut, bytes calldata execData)
internal
returns (RouteData memory r)
{
if (execData.length != 0) return abi.decode(execData, (RouteData));
(uint256 inAmt, bytes memory dd) = _discoverExactOut(tokenIn, tokenOut, amountOut);
if (inAmt == 0 || dd.length == 0) revert NoPool();
r = abi.decode(dd, (RouteData));
}
function _isUsableMid(address mid, address tokenIn, address tokenOut) internal pure returns (bool) {
return mid != address(0) && mid != tokenIn && mid != tokenOut;
}
// ══════════════════════════════════════════════════════════════════════
// Intermediary hint support
// ══════════════════════════════════════════════════════════════════════
function _isIntermediaryHint(bytes calldata data) internal pure returns (bool) {
if (data.length < 32) return false;
uint256 firstWord;
assembly { firstWord := calldataload(data.offset) }
return firstWord == HINT_TAG_INTERMEDIARIES;
}
function _decodeIntermediaries(bytes calldata data) internal pure returns (address[] memory) {
(, address[] memory mids) = abi.decode(data, (uint256, address[]));
return mids;
}
function _discoverWithIntermediariesIn(
address tokenIn, address tokenOut, uint256 amountIn, bytes calldata hintData
) internal returns (uint256 bestOut, bytes memory bestData) {
(bestOut, bestData) = _discoverExactIn(tokenIn, tokenOut, amountIn);
address[] memory mids = _decodeIntermediaries(hintData);
for (uint256 i; i < mids.length; ) {
address mid = mids[i];
if (_isUsableMid(mid, tokenIn, tokenOut) && mid != STABLE && mid != BRIDGE) {
(uint256 out, uint24 fA, uint24 fB) = _bestMultihopIn(tokenIn, mid, tokenOut, amountIn);
if (out > bestOut) {
bestOut = out;
bestData = abi.encode(RouteData(RouteKind.Multihop, fA, fB, mid));
}
}
unchecked { ++i; }
}
}
function _discoverWithIntermediariesOut(
address tokenIn, address tokenOut, uint256 amountOut, bytes calldata hintData
) internal returns (uint256 bestIn, bytes memory bestData) {
(bestIn, bestData) = _discoverExactOut(tokenIn, tokenOut, amountOut);
address[] memory mids = _decodeIntermediaries(hintData);
for (uint256 i; i < mids.length; ) {
address mid = mids[i];
if (_isUsableMid(mid, tokenIn, tokenOut) && mid != STABLE && mid != BRIDGE) {
(uint256 inAmt, uint24 fA, uint24 fB) = _bestMultihopOut(tokenIn, mid, tokenOut, amountOut);
if (inAmt != 0 && inAmt < bestIn) {
bestIn = inAmt;
bestData = abi.encode(RouteData(RouteKind.Multihop, fA, fB, mid));
}
}
unchecked { ++i; }
}
}
/// @dev Lazy infinite-approval cache keyed by (spender, token). Shared
/// across every adapter in the Core via the namespaced storage.
/// `forceApprove` handles tokens that require an explicit zero step.
function _ensureApproved(address token, address spender) internal {
SwapWizardStorage.Layout storage $ = SwapWizardStorage.layout();
if ($.approved[spender][token]) return;
IERC20(token).forceApprove(spender, type(uint256).max);
$.approved[spender][token] = true;
}
}
src/interfaces/IDexImplementation.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
/// @title IDexImplementation
/// @notice Interface every DEX adapter must satisfy to be registered in
/// SwapWizardCore. Adapters are invoked by the Core via `delegatecall`,
/// so they MUST keep their own storage empty: all state visible at
/// runtime is the Core's (see SwapWizardStorage).
///
/// @dev The `execData` blob is opaque to the Core. Adapters decide their
/// own encoding — typically the pool discriminators they need (fee
/// tier for V3 forks, tickSpacing for Slipstream, PoolKey for V4,
/// SplitLeg[] for SplitRouter, etc).
///
/// Two execution modes are supported:
/// * Off-chain pre-picked. Off-chain calls `quoteExactIn` on every
/// registered DEX in parallel (staticcall), compares, and then
/// invokes `swapExactIn` on the winner passing back the exact
/// `execData` returned by the quote. This skips a second pool
/// discovery on-chain.
/// * On-chain discovery. `swapExactIn` is called with an empty
/// `execData`; the adapter is expected to rediscover the best
/// pool itself.
interface IDexImplementation {
/// @notice Stable tag identifying the adapter family. Examples:
/// "UNIV3_SR02", "UNIV3_LEGACY", "SLIPSTREAM", "UNIV4", "SPLIT".
/// @dev Returned from a pure function so the off-chain picker can read
/// it without a state call. Each concrete adapter hardcodes its
/// own value.
function kind() external pure returns (bytes32);
/// @notice Best-effort liquidity indicator for the (tokenIn, tokenOut)
/// pair across the pools this adapter can route through. The
/// unit is adapter-specific (for V3-style it's `liquidity()` —
/// virtual L, not reserves); only meaningful for intra-family
/// ranking, not cross-family comparison.
/// @return liquidity 0 if no routable pool exists.
function liquidityFor(address tokenIn, address tokenOut) external view returns (uint256 liquidity);
/// @notice Simulate an exact-input swap and return the predicted output
/// along with the `execData` blob required to replay the same
/// route in `swapExactIn`.
/// @dev Not `view`: Uniswap V3-style quoters work by simulating a
/// swap in a try/revert pattern, which mutates transient state
/// during the call even if it reverts back. Off-chain callers
/// should invoke via `eth_call` (staticcall) to avoid any actual
/// state change.
///
/// `execDataIn` controls behavior:
/// * Empty → discover the best route on-chain, return it in
/// `execDataOut`. Used by the off-chain picker's initial
/// parallel staticcall.
/// * Non-empty → quote the exact route encoded in this blob.
/// Used by the Core to produce the slippage guard for a
/// pre-picked swap without re-running discovery. `execDataOut`
/// is returned unchanged (or normalized if needed).
/// @return amountOut Predicted output if the route were executed now.
/// @return execDataOut Canonical blob to pass back to `swapExactIn`.
/// Empty if no route was found.
function quoteExactIn(address tokenIn, address tokenOut, uint256 amountIn, bytes calldata execDataIn)
external
returns (uint256 amountOut, bytes memory execDataOut);
/// @notice Simulate an exact-output swap: how much `tokenIn` is needed
/// to receive exactly `amountOut` of `tokenOut`.
/// `execDataIn` follows the same empty/non-empty semantics as in
/// `quoteExactIn`.
/// @return amountIn Predicted input required.
/// @return execDataOut Canonical blob to pass back to `swapExactOut`.
function quoteExactOut(address tokenIn, address tokenOut, uint256 amountOut, bytes calldata execDataIn)
external
returns (uint256 amountIn, bytes memory execDataOut);
/// @notice Execute an exact-input swap.
/// @dev Invoked by the Core via `delegatecall`. `tokenIn` balance is
/// assumed to already sit in `address(this)` (the Core); the
/// adapter is responsible for approving the target router if
/// needed (using the shared approval cache in SwapWizardStorage)
/// and delivering `tokenOut` directly to `recipient`.
///
/// If `execData` is empty, the adapter rediscovers the best
/// route on-chain. Otherwise it executes the exact route encoded
/// in `execData` (used by `swapExactIn` after an off-chain quote).
///
/// MUST revert on routing failure (returns-0 is not a success).
/// @param minOut Slippage guard. The adapter MUST revert if the
/// actual output is below this value.
/// @param deadline Timestamp after which the swap must revert.
/// @return amountOut Actual `tokenOut` delivered to `recipient`.
function swapExactIn(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minOut,
address recipient,
uint256 deadline,
bytes calldata execData
) external payable returns (uint256 amountOut);
/// @notice Execute an exact-output swap.
/// @dev Pulls at most `maxIn` from `address(this)`'s `tokenIn` balance
/// and delivers exactly `amountOut` of `tokenOut` to `recipient`.
/// Any unspent `tokenIn` remains in `address(this)` — the Core
/// is responsible for refunding the user.
/// @return amountInSpent Actual `tokenIn` consumed (≤ maxIn).
function swapExactOut(
address tokenIn,
address tokenOut,
uint256 amountOut,
uint256 maxIn,
address recipient,
uint256 deadline,
bytes calldata execData
) external payable returns (uint256 amountInSpent);
}
src/interfaces/IQuoterV2.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
interface IQuoterV2 {
struct QuoteExactInputSingleParams {
address tokenIn;
address tokenOut;
uint256 amountIn;
uint24 fee;
uint160 sqrtPriceLimitX96;
}
function quoteExactInputSingle(QuoteExactInputSingleParams memory params)
external
returns (
uint256 amountOut,
uint160 sqrtPriceX96After,
uint32 initializedTicksCrossed,
uint256 gasEstimate
);
function quoteExactInput(bytes memory path, uint256 amountIn)
external
returns (
uint256 amountOut,
uint160[] memory sqrtPriceX96AfterList,
uint32[] memory initializedTicksCrossedList,
uint256 gasEstimate
);
struct QuoteExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint256 amount;
uint24 fee;
uint160 sqrtPriceLimitX96;
}
function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)
external
returns (
uint256 amountIn,
uint160 sqrtPriceX96After,
uint32 initializedTicksCrossed,
uint256 gasEstimate
);
function quoteExactOutput(bytes memory path, uint256 amountOut)
external
returns (
uint256 amountIn,
uint160[] memory sqrtPriceX96AfterList,
uint32[] memory initializedTicksCrossedList,
uint256 gasEstimate
);
}
src/interfaces/ISwapRouter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ISwapRouter {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
struct ExactInputParams {
bytes path;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
}
function exactInputSingle(ExactInputSingleParams calldata params)
external
payable
returns (uint256 amountOut);
function exactInput(ExactInputParams calldata params)
external
payable
returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
struct ExactOutputParams {
bytes path;
address recipient;
uint256 amountOut;
uint256 amountInMaximum;
}
function exactOutputSingle(ExactOutputSingleParams calldata params)
external
payable
returns (uint256 amountIn);
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
src/interfaces/IUniswapV3Factory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
interface IUniswapV3Factory {
function getPool(
address tokenA,
address tokenB,
uint24 fee
) external view returns (address pool);
}
src/interfaces/IUniswapV3Pool.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
interface IUniswapV3Pool {
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
function token0() external view returns (address);
function token1() external view returns (address);
function fee() external view returns (uint24);
function tickSpacing() external view returns (int24);
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128);
function feeGrowthGlobal0X128() external view returns (uint256);
function feeGrowthGlobal1X128() external view returns (uint256);
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
function liquidity() external view returns (uint128);
}
src/libraries/SwapWizardStorage.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
/// @title SwapWizardStorage
/// @notice ERC-7201 namespaced storage shared by SwapWizardCore and every
/// IDexImplementation that runs inside the Core via `delegatecall`.
/// Using a namespaced slot keeps our state out of the 0/1 slots used
/// by OpenZeppelin's AccessControl / ReentrancyGuard, and makes slot
/// collisions between Core and impls structurally impossible.
/// @dev Slot was computed as:
/// keccak256(abi.encode(uint256(keccak256("swapwizard.core.v1")) - 1)) & ~bytes32(uint256(0xff))
library SwapWizardStorage {
/// @custom:storage-location erc7201:swapwizard.core.v1
struct Layout {
/// @notice The append-only DEX registry. Index is stable and is the
/// public identifier of each DEX (the `dexIdx` argument used
/// by every Core entry point and by SplitRouter legs).
DexEntry[] dexes;
/// @notice Lazy-approval cache. `true` means `token` is already
/// approved to `spender` for `type(uint256).max`.
/// Written by impls the first time they hit a new router.
mapping(address spender => mapping(address token => bool approved)) approved;
/// @notice Recipient of the protocol fee. If `address(0)`, no fee is
/// ever taken regardless of `treasuryFeeBps` or affiliate entries.
address treasuryAddress;
/// @notice Default fee in bps (1/10_000) applied to every swap when
/// no affiliate code is provided. Initialized to 5 (0.05 %)
/// by the Core constructor. Structural bound:
/// `< BPS_DENOM` — anything ≥ 100 % is degenerate.
uint16 treasuryFeeBps;
/// @notice Registered affiliates with configurable fee split.
mapping(address => Affiliate) affiliates;
/// @notice Enumerable list of affiliate addresses for off-chain queries.
address[] affiliateList;
}
/// @notice A single row of the registry.
/// `impl` — address of an IDexImplementation deployed on this chain.
/// `kind` — opaque tag (e.g. "UNIV3_SR02", "UNIV3_LEGACY",
/// "SLIPSTREAM", "SPLIT") that tells the off-chain
/// picker how to encode the `execData` blob.
/// `name` — human-readable label (e.g. "Uniswap V3", "Aerodrome Slipstream").
/// `enabled` — EMERGENCY_ROLE can flip this to pause a DEX without
/// shifting indexes.
struct DexEntry {
address impl;
bytes32 kind;
string name;
bool enabled;
}
/// @notice Affiliate configuration.
/// `ourFee` — bps retained by protocol treasury.
/// `theirFee` — bps sent to the affiliate address.
/// `exists` — distinguishes "not registered" from "registered with (0,0)".
/// Packed into a single slot (5 bytes).
struct Affiliate {
uint16 ourFee;
uint16 theirFee;
bool exists;
}
bytes32 internal constant SLOT = 0x97544f499d3937c3024f1475d21de7067452902ac9a3252197cf6a1199a83800;
function layout() internal pure returns (Layout storage $) {
assembly ("memory-safe") {
$.slot := SLOT
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 1000000,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.