Skip to content
Verified contractPartialMIT

SwapRouter

Address0xceb45b38565acfcd2e5066a71968ee77ab61a160
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.37

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.37+commit.f401782d
Language
solidity
Optimization
Yes, 10,000 runs
EVM version
shanghai
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,405,340
Creation transaction
0x33b7639931…32fe0c29d9

src/SwapRouter.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.37 <0.9.0;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

import { ExecutorDispatcher } from "./core/ExecutorDispatcher.sol";
import { RouteTypes } from "./core/RouteTypes.sol";
import { RouterPayments } from "./core/RouterPayments.sol";
import { ISwapRouter } from "./interfaces/ISwapRouter.sol";
import { IExecutor } from "./interfaces/IExecutor.sol";
import { INativeCurrencyExecutor } from "./interfaces/INativeCurrencyExecutor.sol";

/// @title SwapRouter
/// @notice Chain-agnostic entry point for executing routes produced by the aggregator API.
/// @dev Protocol-specific executors are trusted stateless modules invoked with `delegatecall`. The router retains
/// token custody, verifies observed balance changes, and forwards callback selectors to the active executor.
contract SwapRouter is ExecutorDispatcher, RouterPayments, ReentrancyGuard {
    using SafeERC20 for IERC20;

    constructor(
        address initialOwner,
        address wrappedNative_,
        address permit2_,
        address[] memory initialExecutors
    )
        ExecutorDispatcher(initialOwner, initialExecutors)
        RouterPayments(wrappedNative_, permit2_)
    { }

    /// @inheritdoc ISwapRouter
    function exactInput(
        RouteTypes.ExactInputParams calldata params,
        Permit2Permit calldata permitData
    )
        external
        payable
        override
        nonReentrant
        returns (uint256 amountOut)
    {
        return _exactInput(params, permitData, false);
    }

    /// @inheritdoc ISwapRouter
    function exactInputWithAllowance(RouteTypes.ExactInputParams calldata params)
        external
        payable
        override
        nonReentrant
        returns (uint256 amountOut)
    {
        return _exactInput(params, Permit2Permit({ nonce: 0, signature: "" }), true);
    }

    function _exactInput(
        RouteTypes.ExactInputParams calldata params,
        Permit2Permit memory permitData,
        bool useAllowance
    )
        private
        returns (uint256 amountOut)
    {
        address tokenIn = _normalizeToken(params.tokenIn);
        address tokenOut = _normalizeToken(params.tokenOut);

        _validateCommon(tokenIn, tokenOut, params.recipient, params.deadline);
        if (params.amountIn == 0 || params.amountOutMinimum == 0 || params.paths.length == 0) revert InvalidAmount();
        _takeInput(params.tokenIn, tokenIn, params.amountIn, params.deadline, permitData, useAllowance);

        uint256 allocatedInput;
        uint256 routerAmountOut;
        for (uint256 pathIndex; pathIndex < params.paths.length;) {
            RouteTypes.ExactInputPath calldata path = params.paths[pathIndex];
            allocatedInput += path.amountIn;
            routerAmountOut += _executeExactInputPath(path, tokenIn, tokenOut);
            unchecked {
                ++pathIndex;
            }
        }
        if (allocatedInput != params.amountIn) revert IncorrectInputAmount(params.amountIn, allocatedInput);

        amountOut = _sendOutput(params.tokenOut, tokenOut, params.recipient, routerAmountOut);
        if (amountOut < params.amountOutMinimum) revert SlippageExceeded(params.amountOutMinimum, amountOut);

        emit SwapExecuted(
            msg.sender,
            params.recipient,
            params.tokenIn,
            params.tokenOut,
            params.amountIn,
            amountOut,
            false
        );
    }

    /// @inheritdoc ISwapRouter
    function exactOutput(
        RouteTypes.ExactOutputParams calldata params,
        Permit2Permit calldata permitData
    )
        external
        payable
        override
        nonReentrant
        returns (uint256 amountIn)
    {
        return _exactOutput(params, permitData, false);
    }

    /// @inheritdoc ISwapRouter
    function exactOutputWithAllowance(RouteTypes.ExactOutputParams calldata params)
        external
        payable
        override
        nonReentrant
        returns (uint256 amountIn)
    {
        return _exactOutput(params, Permit2Permit({ nonce: 0, signature: "" }), true);
    }

    function _exactOutput(
        RouteTypes.ExactOutputParams calldata params,
        Permit2Permit memory permitData,
        bool useAllowance
    )
        private
        returns (uint256 amountIn)
    {
        address tokenIn = _normalizeToken(params.tokenIn);
        address tokenOut = _normalizeToken(params.tokenOut);

        _validateCommon(tokenIn, tokenOut, params.recipient, params.deadline);
        if (params.amountOut == 0 || params.amountInMaximum == 0 || params.paths.length == 0) revert InvalidAmount();
        _takeInput(params.tokenIn, tokenIn, params.amountInMaximum, params.deadline, permitData, useAllowance);

        uint256 allocatedOutput;
        uint256 routerAmountOut;
        for (uint256 pathIndex; pathIndex < params.paths.length;) {
            RouteTypes.ExactOutputPath calldata path = params.paths[pathIndex];
            allocatedOutput += path.amountOut;
            uint256 remainingInput = params.amountInMaximum - amountIn;
            (uint256 pathAmountIn, uint256 pathAmountOut) =
                _executeExactOutputPath(path, tokenIn, tokenOut, remainingInput);
            amountIn += pathAmountIn;
            routerAmountOut += pathAmountOut;
            unchecked {
                ++pathIndex;
            }
        }
        if (allocatedOutput != params.amountOut) revert InvalidRoute();
        if (amountIn > params.amountInMaximum) revert InputLimitExceeded(params.amountInMaximum, amountIn);

        uint256 amountOut = _sendOutput(params.tokenOut, tokenOut, params.recipient, routerAmountOut);
        if (amountOut < params.amountOut) revert SlippageExceeded(params.amountOut, amountOut);

        _refundInput(params.tokenIn, tokenIn, params.amountInMaximum - amountIn);

        emit SwapExecuted(msg.sender, params.recipient, params.tokenIn, params.tokenOut, amountIn, amountOut, true);
    }

    function _executeExactInputPath(
        RouteTypes.ExactInputPath calldata path,
        address routeTokenIn,
        address routeTokenOut
    )
        private
        returns (uint256 amountOut)
    {
        if (path.amountIn == 0 || path.steps.length == 0) revert InvalidRoute();

        amountOut = path.amountIn;
        address expectedTokenIn = routeTokenIn;
        for (uint256 stepIndex; stepIndex < path.steps.length;) {
            RouteTypes.ExactInputStep calldata step = path.steps[stepIndex];
            if (step.tokenIn != expectedTokenIn) revert InvalidRoute();
            _validateStep(step.executor, step.tokenIn, step.tokenOut);

            amountOut = _executeExactInputStep(step, amountOut);
            expectedTokenIn = step.tokenOut;
            unchecked {
                ++stepIndex;
            }
        }
        if (expectedTokenIn != routeTokenOut) revert InvalidRoute();
    }

    function _executeExactOutputPath(
        RouteTypes.ExactOutputPath calldata path,
        address routeTokenIn,
        address routeTokenOut,
        uint256 amountInMaximum
    )
        private
        returns (uint256 amountIn, uint256 amountOut)
    {
        if (path.amountOut == 0 || path.steps.length == 0) revert InvalidRoute();

        uint256 availableInput = amountInMaximum;
        address expectedTokenIn = routeTokenIn;
        for (uint256 stepIndex; stepIndex < path.steps.length;) {
            RouteTypes.ExactOutputStep calldata step = path.steps[stepIndex];
            if (step.amountOut == 0 || step.tokenIn != expectedTokenIn) revert InvalidRoute();
            _validateStep(step.executor, step.tokenIn, step.tokenOut);

            (uint256 spent, uint256 received) = _executeExactOutputStep(step, availableInput);

            if (stepIndex == 0) {
                amountIn = spent;
            } else if (spent < availableInput) {
                IERC20(step.tokenIn).safeTransfer(msg.sender, availableInput - spent);
            }

            availableInput = received;
            expectedTokenIn = step.tokenOut;
            unchecked {
                ++stepIndex;
            }
        }
        if (expectedTokenIn != routeTokenOut || path.steps[path.steps.length - 1].amountOut != path.amountOut) {
            revert InvalidRoute();
        }
        amountOut = availableInput;
    }

    function _executeExactInputStep(
        RouteTypes.ExactInputStep calldata step,
        uint256 amountIn
    )
        private
        returns (uint256 amountOut)
    {
        uint256 inputBefore = _balanceOf(step.tokenIn);
        uint256 outputBefore = _balanceOf(step.tokenOut);

        bytes memory result = _delegateToExecutor(
            step.executor, abi.encodeCall(IExecutor.swapExactInput, (step.tokenIn, step.tokenOut, amountIn, step.data))
        );

        uint256 amountSpent = _decrease(step.tokenIn, inputBefore, _balanceOf(step.tokenIn));
        amountOut = _increase(step.tokenOut, outputBefore, _balanceOf(step.tokenOut));
        if (amountSpent != amountIn) revert IncorrectInputAmount(amountIn, amountSpent);
        if (amountOut == 0) revert SlippageExceeded(1, 0);

        _verifyExecutorResult(result, amountOut);
    }

    function _executeExactOutputStep(
        RouteTypes.ExactOutputStep calldata step,
        uint256 amountInMaximum
    )
        private
        returns (uint256 amountIn, uint256 amountOut)
    {
        uint256 inputBefore = _balanceOf(step.tokenIn);
        uint256 outputBefore = _balanceOf(step.tokenOut);

        bytes memory result = _delegateToExecutor(
            step.executor,
            abi.encodeCall(
                IExecutor.swapExactOutput, (step.tokenIn, step.tokenOut, step.amountOut, amountInMaximum, step.data)
            )
        );

        amountIn = _decrease(step.tokenIn, inputBefore, _balanceOf(step.tokenIn));
        amountOut = _increase(step.tokenOut, outputBefore, _balanceOf(step.tokenOut));
        if (amountIn > amountInMaximum) revert InputLimitExceeded(amountInMaximum, amountIn);
        if (amountOut < step.amountOut) revert SlippageExceeded(step.amountOut, amountOut);

        _verifyExecutorResult(result, amountIn);
    }

    function _validateStep(address executor, address tokenIn, address tokenOut) private view {
        if (!isExecutor[executor]) revert InvalidExecutor(executor);
        if (tokenIn == address(0) || tokenOut == address(0) || tokenIn == tokenOut) revert InvalidRoute();
    }

    function _validateCommon(address tokenIn, address tokenOut, address recipient, uint256 deadline) private view {
        if (block.timestamp > deadline) revert DeadlineExpired(deadline);
        if (recipient == address(0) || recipient == address(this)) revert InvalidAddress();
        if (tokenIn == tokenOut) revert InvalidRoute();
    }

    function _verifyExecutorResult(bytes memory result, uint256 observed) private pure {
        if (result.length != 32) revert ExecutorResultMismatch(0, observed);
        uint256 reported = abi.decode(result, (uint256));
        if (reported != observed) revert ExecutorResultMismatch(reported, observed);
    }

    function _acceptNativeSender(address sender) internal view override returns (bool) {
        if (super._acceptNativeSender(sender)) return true;

        address executor = _activeExecutorAddress();
        if (executor == address(0)) return false;

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory result) =
            executor.staticcall(abi.encodeCall(INativeCurrencyExecutor.nativeCurrencySender, ()));
        return success && result.length == 32 && abi.decode(result, (address)) == sender;
    }
}

node_modules/@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

node_modules/@openzeppelin/contracts/access/Ownable2Step.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

import {Ownable} from "./Ownable.sol";

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

node_modules/@openzeppelin/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);
}

node_modules/@openzeppelin/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";

node_modules/@openzeppelin/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";

node_modules/@openzeppelin/contracts/interfaces/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20Metadata.sol)

pragma solidity >=0.6.2;

import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

node_modules/@openzeppelin/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);
}

node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity >=0.6.2;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.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 Attempts to fetch the token decimals. A return value of false indicates that the attempt failed in some way.
    function tryGetDecimals(IERC20 token) internal view returns (bool success, uint8 decimals) {
        bytes4 selector = IERC20Metadata.decimals.selector;
        assembly ("memory-safe") {
            mstore(0x00, selector)
            success := staticcall(gas(), token, 0x00, 4, 0x00, 0x20)
            success := and(and(success, gt(returndatasize(), 0x1f)), lt(mload(0x00), 0x100))
            decimals := mul(success, mload(0x00))
        }
    }

    /**
     * @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 approve
     * @param bubble Behavior switch if the approve 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)
        }
    }
}

node_modules/@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

import {StorageSlot} from "./StorageSlot.sol";

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 *
 * IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
 * by the {ReentrancyGuardTransient} variant in v6.0.
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuard {
    using StorageSlot for bytes32;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

node_modules/@openzeppelin/contracts/utils/StorageSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

node_modules/@openzeppelin/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/core/ExecutorDispatcher.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.37 <0.9.0;

import { ExecutorRegistry } from "./ExecutorRegistry.sol";

/// @title ExecutorDispatcher
/// @notice Runs trusted executors in router storage and forwards pool callbacks to the active executor.
abstract contract ExecutorDispatcher is ExecutorRegistry {
    address private activeExecutor;

    constructor(
        address initialOwner,
        address[] memory initialExecutors
    )
        ExecutorRegistry(initialOwner, initialExecutors)
    { }

    // solhint-disable-next-line no-complex-fallback
    fallback() external {
        address executor = activeExecutor;
        if (executor == address(0)) revert UnexpectedCallback(msg.sig, msg.sender);

        // solhint-disable-next-line no-inline-assembly
        assembly ("memory-safe") {
            calldatacopy(0, 0, calldatasize())
            let success := delegatecall(gas(), executor, 0, calldatasize(), 0, 0)
            returndatacopy(0, 0, returndatasize())
            switch success
            case 0 { revert(0, returndatasize()) }
            default { return(0, returndatasize()) }
        }
    }

    function _delegateToExecutor(address executor, bytes memory callData) internal returns (bytes memory result) {
        activeExecutor = executor;
        bool success;
        // solhint-disable-next-line avoid-low-level-calls
        (success, result) = executor.delegatecall(callData);
        activeExecutor = address(0);

        if (!success) {
            if (result.length == 0) revert ExecutorCallFailed(executor);
            // solhint-disable-next-line no-inline-assembly
            assembly ("memory-safe") {
                revert(add(result, 0x20), mload(result))
            }
        }
    }

    function _activeExecutorAddress() internal view returns (address) {
        return activeExecutor;
    }
}

src/core/ExecutorRegistry.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.37 <0.9.0;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Ownable2Step } from "@openzeppelin/contracts/access/Ownable2Step.sol";

import { ISwapRouter } from "../interfaces/ISwapRouter.sol";

/// @title ExecutorRegistry
/// @notice Owner-managed allowlist of trusted protocol executors.
/// @dev Inheriting the registry adds no external call to the swap path. Executor bytecode runs with router storage
/// through `delegatecall`, so only reviewed, stateless executors should be registered.
abstract contract ExecutorRegistry is ISwapRouter, Ownable2Step {
    mapping(address executor => bool enabled) public override isExecutor;

    constructor(address initialOwner, address[] memory initialExecutors) Ownable(initialOwner) {
        for (uint256 index; index < initialExecutors.length;) {
            _setExecutor(initialExecutors[index], true);
            unchecked {
                ++index;
            }
        }
    }

    /// @inheritdoc ISwapRouter
    function setExecutor(address executor, bool enabled) external override onlyOwner {
        _setExecutor(executor, enabled);
    }

    /// @inheritdoc ISwapRouter
    function setExecutors(address[] calldata executors, bool enabled) external override onlyOwner {
        for (uint256 index; index < executors.length;) {
            _setExecutor(executors[index], enabled);
            unchecked {
                ++index;
            }
        }
    }

    function _setExecutor(address executor, bool enabled) private {
        if (executor == address(0) || executor == address(this) || (enabled && executor.code.length == 0)) {
            revert InvalidExecutor(executor);
        }
        if (isExecutor[executor] == enabled) return;

        isExecutor[executor] = enabled;
        emit ExecutorSet(executor, enabled);
    }
}

src/core/RouteTypes.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.37 <0.9.0;

/// @title RouteTypes
/// @notice Shared route data used by the swap router and its off-chain encoder.
library RouteTypes {
    /// @notice One protocol-specific hop in an exact-input path.
    /// @param executor Registered module that implements the protocol call.
    /// @param tokenIn ERC-20 consumed by this hop.
    /// @param tokenOut ERC-20 produced by this hop.
    /// @param data Protocol-specific executor calldata without the executor function selector.
    struct ExactInputStep {
        address executor;
        address tokenIn;
        address tokenOut;
        bytes data;
    }

    /// @notice One protocol-specific hop in an exact-output path.
    /// @dev `amountOut` is required for every hop so mixed-protocol paths can execute sequentially.
    /// @param executor Registered module that implements the protocol call.
    /// @param tokenIn ERC-20 consumed by this hop.
    /// @param tokenOut ERC-20 produced by this hop.
    /// @param amountOut Minimum output that this hop must produce.
    /// @param data Protocol-specific executor calldata without the executor function selector.
    struct ExactOutputStep {
        address executor;
        address tokenIn;
        address tokenOut;
        uint256 amountOut;
        bytes data;
    }

    /// @notice One direct or multihop exact-input path.
    /// @param amountIn Exact input allocated to this path.
    /// @param steps Ordered protocol hops from the route input to the route output.
    struct ExactInputPath {
        uint256 amountIn;
        ExactInputStep[] steps;
    }

    /// @notice One direct or multihop exact-output path.
    /// @param amountOut Output allocated to this path; must equal its final step's target.
    /// @param steps Ordered protocol hops from the route input to the route output.
    struct ExactOutputPath {
        uint256 amountOut;
        ExactOutputStep[] steps;
    }

    /// @notice Parameters shared by direct, multihop, and split exact-input swaps.
    /// @param tokenIn ERC-20 input, or `address(0)` for native currency.
    /// @param tokenOut ERC-20 output, or `address(0)` for native currency.
    /// @param amountIn Exact total input; path inputs must sum to this value.
    /// @param amountOutMinimum Minimum amount the recipient must actually receive.
    /// @param recipient Destination of the final output.
    /// @param deadline Last timestamp at which execution is allowed.
    /// @param paths One path for direct/multihop execution, or multiple paths for a split.
    struct ExactInputParams {
        address tokenIn;
        address tokenOut;
        uint256 amountIn;
        uint256 amountOutMinimum;
        address recipient;
        uint256 deadline;
        ExactInputPath[] paths;
    }

    /// @notice Parameters shared by direct, multihop, and split exact-output swaps.
    /// @param tokenIn ERC-20 input, or `address(0)` for native currency.
    /// @param tokenOut ERC-20 output, or `address(0)` for native currency.
    /// @param amountOut Required aggregate output; path outputs must sum to this value.
    /// @param amountInMaximum Maximum aggregate original input that may be spent.
    /// @param recipient Destination of the final output.
    /// @param deadline Last timestamp at which execution is allowed.
    /// @param paths One path for direct/multihop execution, or multiple paths for a split.
    struct ExactOutputParams {
        address tokenIn;
        address tokenOut;
        uint256 amountOut;
        uint256 amountInMaximum;
        address recipient;
        uint256 deadline;
        ExactOutputPath[] paths;
    }
}

src/core/RouterPayments.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.37 <0.9.0;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import { ISwapRouter } from "../interfaces/ISwapRouter.sol";
import { IPermit2 } from "../interfaces/IPermit2.sol";
import { IWrappedNative } from "../interfaces/IWrappedNative.sol";

/// @title RouterPayments
/// @notice Handles input custody, Permit2 transfers, native wrapping, outputs, and refunds for the router.
abstract contract RouterPayments is ISwapRouter {
    using SafeERC20 for IERC20;

    address private immutable WRAPPED_NATIVE;
    address private immutable PERMIT2;

    constructor(address wrappedNative_, address permit2_) {
        if (
            wrappedNative_ == address(0) || wrappedNative_.code.length == 0 || permit2_ == address(0)
                || permit2_.code.length == 0
        ) revert InvalidAddress();

        WRAPPED_NATIVE = wrappedNative_;
        PERMIT2 = permit2_;
    }

    /// @notice Accepts native currency only from an expected settlement source.
    receive() external payable {
        if (!_acceptNativeSender(msg.sender)) revert UnexpectedCallback(msg.sig, msg.sender);
    }

    /// @inheritdoc ISwapRouter
    function wrappedNative() external view override returns (address) {
        return WRAPPED_NATIVE;
    }

    /// @inheritdoc ISwapRouter
    function permit2() external view override returns (address) {
        return PERMIT2;
    }

    function _takeInput(
        address rawToken,
        address token,
        uint256 amount,
        uint256 deadline,
        Permit2Permit memory permitData,
        bool useAllowance
    )
        internal
    {
        if (rawToken == address(0)) {
            if (msg.value != amount) revert IncorrectNativeAmount(amount, msg.value);
            IWrappedNative(WRAPPED_NATIVE).deposit{ value: amount }();
            return;
        }

        if (msg.value != 0) revert IncorrectNativeAmount(0, msg.value);
        uint256 balanceBefore = _balanceOf(token);
        if (useAllowance) {
            IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
        } else {
            if (amount > type(uint160).max) revert Permit2AmountOverflow(amount);
            if (deadline > type(uint48).max) revert Permit2DeadlineOverflow(deadline);

            // Safe after the explicit Permit2 width checks above.
            // forge-lint: disable-next-line(unsafe-typecast)
            uint160 permitAmount = uint160(amount);
            // forge-lint: disable-next-line(unsafe-typecast)
            uint48 permitExpiration = uint48(deadline);
            IPermit2 permitContract = IPermit2(PERMIT2);
            if (permitData.signature.length != 0) {
                permitContract.permit(
                    msg.sender,
                    IPermit2.PermitSingle({
                        details: IPermit2.PermitDetails({
                            token: token,
                            amount: permitAmount,
                            expiration: permitExpiration,
                            nonce: permitData.nonce
                        }),
                        spender: address(this),
                        sigDeadline: deadline
                    }),
                    permitData.signature
                );
            }

            permitContract.transferFrom(msg.sender, address(this), permitAmount, token);
        }
        uint256 received = _increase(token, balanceBefore, _balanceOf(token));
        if (received != amount) revert IncorrectInputAmount(amount, received);
    }

    function _sendOutput(
        address rawToken,
        address token,
        address recipient,
        uint256 amount
    )
        internal
        returns (uint256 received)
    {
        if (rawToken == address(0)) {
            IWrappedNative(WRAPPED_NATIVE).withdraw(amount);
            _sendNative(recipient, amount);
            return amount;
        }

        uint256 balanceBefore = IERC20(token).balanceOf(recipient);
        IERC20(token).safeTransfer(recipient, amount);
        received = _increase(token, balanceBefore, IERC20(token).balanceOf(recipient));
    }

    function _refundInput(address rawToken, address token, uint256 amount) internal {
        if (amount == 0) return;

        if (rawToken == address(0)) {
            IWrappedNative(WRAPPED_NATIVE).withdraw(amount);
            _sendNative(msg.sender, amount);
        } else {
            IERC20(token).safeTransfer(msg.sender, amount);
        }
    }

    function _normalizeToken(address token) internal view returns (address) {
        return token == address(0) ? WRAPPED_NATIVE : token;
    }

    function _acceptNativeSender(address sender) internal view virtual returns (bool) {
        return sender == WRAPPED_NATIVE;
    }

    function _balanceOf(address token) internal view returns (uint256) {
        return IERC20(token).balanceOf(address(this));
    }

    function _increase(address token, uint256 beforeBalance, uint256 afterBalance) internal pure returns (uint256) {
        if (afterBalance < beforeBalance) revert TokenBalanceInvariant(token);
        return afterBalance - beforeBalance;
    }

    function _decrease(address token, uint256 beforeBalance, uint256 afterBalance) internal pure returns (uint256) {
        if (afterBalance > beforeBalance) revert TokenBalanceInvariant(token);
        return beforeBalance - afterBalance;
    }

    function _sendNative(address recipient, uint256 amount) private {
        (bool success,) = recipient.call{ value: amount }("");
        if (!success) revert NativeTransferFailed(recipient, amount);
    }
}

src/interfaces/IExecutor.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.37 <0.9.0;

/// @title IExecutor
/// @notice Boundary between the swap router and a protocol-specific executor.
/// @dev Executors are stateless trusted modules invoked with `delegatecall`. Tokens remain in the router, and an
/// executor must send pool output back to `address(this)`. The router independently verifies balance changes.
interface IExecutor {
    /// @notice Swaps an exact amount of `tokenIn` for `tokenOut`.
    /// @param tokenIn ERC-20 held by the router and consumed by the pool.
    /// @param tokenOut ERC-20 returned to the router.
    /// @param amountIn Exact amount to spend.
    /// @param data Protocol-specific encoded pool and swap parameters.
    /// @return amountOut Amount of `tokenOut` produced, independently checked by the router.
    function swapExactInput(
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        bytes calldata data
    )
        external
        payable
        returns (uint256 amountOut);

    /// @notice Acquires at least `amountOut` while spending no more than `amountInMaximum`.
    /// @param tokenIn ERC-20 held by the router and consumed by the pool.
    /// @param tokenOut ERC-20 returned to the router.
    /// @param amountOut Output target for this hop.
    /// @param amountInMaximum Maximum input made available to this hop.
    /// @param data Protocol-specific encoded pool and swap parameters.
    /// @return amountIn Amount of `tokenIn` spent, independently checked by the router.
    function swapExactOutput(
        address tokenIn,
        address tokenOut,
        uint256 amountOut,
        uint256 amountInMaximum,
        bytes calldata data
    )
        external
        payable
        returns (uint256 amountIn);
}

src/interfaces/INativeCurrencyExecutor.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.37 <0.9.0;

/// @notice Optional executor capability used to authorize native settlement callbacks while it is active.
interface INativeCurrencyExecutor {
    function nativeCurrencySender() external view returns (address);
}

src/interfaces/IPermit2.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.37 <0.9.0;

/// @title IPermit2
/// @notice Minimal Permit2 AllowanceTransfer interface used by the swap router.
interface IPermit2 {
    struct PermitDetails {
        address token;
        uint160 amount;
        uint48 expiration;
        uint48 nonce;
    }

    struct PermitSingle {
        PermitDetails details;
        address spender;
        uint256 sigDeadline;
    }

    function allowance(
        address owner,
        address token,
        address spender
    )
        external
        view
        returns (uint160 amount, uint48 expiration, uint48 nonce);

    function approve(address token, address spender, uint160 amount, uint48 expiration) external;

    function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;

    function transferFrom(address from, address to, uint160 amount, address token) external;
}

src/interfaces/ISwapRouter.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.37 <0.9.0;

import { RouteTypes } from "../core/RouteTypes.sol";

/// @title ISwapRouter
/// @notice Executes direct, multihop, and split routes assembled by the aggregator API.
/// @dev `address(0)` represents native currency only for top-level `tokenIn` and `tokenOut`. Every step uses ERC-20
/// addresses, including the configured wrapped-native token.
interface ISwapRouter {
    /// @notice Optional Permit2 allowance authorization embedded in the swap transaction.
    /// @dev Leave `signature` empty when a sufficient unexpired Permit2 allowance already exists.
    struct Permit2Permit {
        uint48 nonce;
        bytes signature;
    }

    /// @notice The route expired before execution.
    error DeadlineExpired(uint256 deadline);
    /// @notice A delegatecall to an executor failed without revert data.
    error ExecutorCallFailed(address executor);
    /// @notice An executor's return value differs from the router-observed balance delta.
    error ExecutorResultMismatch(uint256 reported, uint256 observed);
    /// @notice The supplied or spent input differs from the required amount.
    error IncorrectInputAmount(uint256 expected, uint256 received);
    /// @notice `msg.value` differs from the native input expected by the route.
    error IncorrectNativeAmount(uint256 expected, uint256 received);
    /// @notice An exact-output route spent more than its input ceiling.
    error InputLimitExceeded(uint256 maximum, uint256 actual);
    /// @notice A required address is zero or otherwise invalid for its role.
    error InvalidAddress();
    /// @notice A top-level amount or limit is zero.
    error InvalidAmount();
    /// @notice The executor is not registered or cannot be registered.
    error InvalidExecutor(address executor);
    /// @notice Route paths or steps are empty, discontinuous, or inconsistent with top-level parameters.
    error InvalidRoute();
    /// @notice Native currency could not be delivered to its recipient.
    error NativeTransferFailed(address recipient, uint256 amount);
    /// @notice Permit2 cannot represent an input amount above `uint160`.
    error Permit2AmountOverflow(uint256 amount);
    /// @notice Permit2 allowance expiration cannot represent the supplied deadline.
    error Permit2DeadlineOverflow(uint256 deadline);
    /// @notice The observed output is below its required minimum.
    error SlippageExceeded(uint256 minimum, uint256 actual);
    /// @notice A token balance changed in the opposite direction from the expected swap flow.
    error TokenBalanceInvariant(address token);
    /// @notice The router received an unsupported native transfer or callback.
    error UnexpectedCallback(bytes4 selector, address sender);

    /// @notice Emitted when an executor's authorization changes.
    event ExecutorSet(address indexed executor, bool enabled);
    /// @notice Emitted after a successful route and any exact-output refund.
    event SwapExecuted(
        address indexed sender,
        address indexed recipient,
        address indexed tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 amountOut,
        bool exactOutput
    );

    /// @notice Returns the chain's wrapped-native token used inside route steps.
    function wrappedNative() external view returns (address);

    /// @notice Returns the Permit2 contract used for all ERC-20 inputs.
    function permit2() external view returns (address);

    /// @notice Returns whether `executor` may run in the router's storage context.
    function isExecutor(address executor) external view returns (bool);

    /// @notice Registers or unregisters a trusted executor.
    /// @dev Only the owner may call this function. Enabling requires deployed bytecode; disabling remains possible if
    /// the executor bytecode is no longer available.
    function setExecutor(address executor, bool enabled) external;

    /// @notice Registers or unregisters multiple trusted executors atomically.
    function setExecutors(address[] calldata executors, bool enabled) external;

    /// @notice Executes routes that spend exactly `params.amountIn` and require a global minimum output.
    /// @return amountOut Actual amount delivered to `params.recipient`.
    function exactInput(
        RouteTypes.ExactInputParams calldata params,
        Permit2Permit calldata permitData
    )
        external
        payable
        returns (uint256 amountOut);

    /// @notice Executes an exact-input route using an ERC-20 allowance granted directly to this router.
    function exactInputWithAllowance(RouteTypes.ExactInputParams calldata params)
        external
        payable
        returns (uint256 amountOut);

    /// @notice Executes routes that acquire at least `params.amountOut` within a global maximum input.
    /// @return amountIn Actual original input spent; the remainder is refunded to `msg.sender`.
    function exactOutput(
        RouteTypes.ExactOutputParams calldata params,
        Permit2Permit calldata permitData
    )
        external
        payable
        returns (uint256 amountIn);

    /// @notice Executes an exact-output route using an ERC-20 allowance granted directly to this router.
    function exactOutputWithAllowance(RouteTypes.ExactOutputParams calldata params)
        external
        payable
        returns (uint256 amountIn);
}

src/interfaces/IWrappedNative.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.37 <0.9.0;

/// @title IWrappedNative
/// @notice Minimal interface shared by WETH, WFLR, and equivalent wrapped native tokens.
interface IWrappedNative {
    function deposit() external payable;

    function withdraw(uint256 amount) external;
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 10000,
    "enabled": true
  },
  "evmVersion": "shanghai",
  "remappings": [
    "@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
    "forge-std/=node_modules/forge-std/",
    "ds-test/=lib/permit2/lib/solmate/lib/ds-test/src/",
    "forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
    "openzeppelin-contracts/=lib/permit2/lib/openzeppelin-contracts/",
    "permit2/=lib/permit2/",
    "solmate/=lib/permit2/lib/solmate/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.