Skip to content
Verified contractExactBUSL-1.1

SwapRouter

Address0x5ce697fc962ed2c3f31a42e2a24f287c227e65d4
Balance

0 ETH

 

Transactions

5

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,240,691
Creation transaction
0xbdc05a293f…fef3b0e5ea

src/swaps/SwapRouter.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

import {SafeERC20} from "@oz/token/ERC20/utils/SafeERC20.sol";
import {IERC20Metadata, IERC20} from "@oz/token/ERC20/extensions/IERC20Metadata.sol";
import {IERC4626} from "@oz/interfaces/IERC4626.sol";
import {IV2Vault} from "./IV2Vault.sol";
import {ISwapRouter} from "./ISwapRouter.sol";
import {IWeth} from "./IWeth.sol";
import {OwnableGuarded} from "../core/OwnableGuarded.sol";

/**
 * @title Swap Router.
 * @dev This is a standalone periphery contract that lets users atomically swap any whitelisted token via any whitelisted DEX aggregator
 *      and deposit the proceeds into any August vault.
 *      The contract never holds funds between transactions.
 */
contract SwapRouter is ISwapRouter, OwnableGuarded {
    // --------------------------------------------------------------------------------------
    // Constants
    // --------------------------------------------------------------------------------------
    /// @notice Indicates that the Vault is a standard ERC-4626
    uint8 public constant VAULT_TYPE_ERC4626 = 1;

    /// @notice Indicates that the Vault is a Tokenized Vault V2
    uint8 public constant VAULT_TYPE_TOKENIZED_VAULT_V2 = 2;

    /// @notice The address of the native token for the current chain, per ERC-7528
    address public constant NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    /// @notice The maximum swap fee that can be set
    uint256 public constant MAX_SWAP_FEE_BPS = 7000;

    /// @notice The maximum origin fee
    uint256 public constant MAX_ORIGIN_FEE_BPS = 7000;

    /// @notice The maximum number of swaps that can be run
    uint256 public constant MAX_SWAPS = 9;

    /// @notice The bps denominator
    uint256 public constant BPS_DENOMINATOR = 1e4;

    // --------------------------------------------------------------------------------------
    // Storage layout
    // --------------------------------------------------------------------------------------
    /// @notice Indicates whether the smart contract is paused or not.
    bool public isPaused;

    /// @notice The address of the fees collector.
    address public feesCollector;

    /// @notice The address of the native wrapped token for the current chain (eg: WETH, WAVAX, etc)
    address public immutable wrappedNativeTokenAddress;

    /// @notice The list of whitelisted tokens
    mapping(address => bool) public whitelistedTokens;

    /// @notice Tracks the token transfer proxy of a given router (routerAddr > tokenApprovalAddr)
    mapping(address => address) public tokenTransferProxies;

    /// @notice The authorized selector per router (router > selector > bool)
    mapping(address => mapping(bytes4 => bool)) private _authorizedRouterSelectors;

    /// @notice The swap fee of each vault, expressed in bps. Zero unless set by the owner.
    mapping(address => uint256) public vaultSwapFees;

    /// @notice The whitelisted referrers, in the form (origin code => info)
    mapping(bytes32 => OriginEntry) public origins;

    // --------------------------------------------------------------------------
    // Modifiers
    // --------------------------------------------------------------------------
    /// @dev Throws if the contract is paused
    modifier ifNotPaused() {
        if (isPaused) revert ContractIsPaused();
        _;
    }

    /// @dev Throws if the contract is not paused
    modifier ifPaused() {
        if (!isPaused) revert ContractNotPaused();
        _;
    }

    // --------------------------------------------------------------------------------------
    // Constructor
    // --------------------------------------------------------------------------------------
    /**
     * @notice Constructor
     * @param ownerAddr The owner of this contract.
     * @param newFeesCollectorAddr The address of the fee collector.
     * @param wrappedNativeTokenAddr The address of the native token wrapper for the current chain.
     */
    constructor(address ownerAddr, address newFeesCollectorAddr, address wrappedNativeTokenAddr) {
        if (ownerAddr == address(this)) revert InvalidAddress();
        if (wrappedNativeTokenAddr == address(0)) revert ZeroAddress();
        if (newFeesCollectorAddr == address(0)) revert ZeroAddress();
        if (newFeesCollectorAddr == address(this)) revert InvalidAddress();

        _transferOwnership(ownerAddr);
        feesCollector = newFeesCollectorAddr;
        wrappedNativeTokenAddress = wrappedNativeTokenAddr;
    }

    // --------------------------------------------------------------------------------------
    // Pause/Resume
    // --------------------------------------------------------------------------------------
    /**
     * @notice Pauses the smart contract.
     */
    function pause() external nonReentrant onlyOwner ifNotPaused {
        isPaused = true;
        emit ContractPaused();
    }

    /**
     * @notice Resumes (unpauses) the smart contract.
     */
    function unPause() external nonReentrant onlyOwner ifPaused {
        isPaused = false;
        emit ContractResumed();
    }

    // --------------------------------------------------------------------------------------
    // Tokens Management
    // --------------------------------------------------------------------------------------
    /**
     * @notice Enables the token specified.
     * @param token The ERC20 token to enable.
     */
    function enableToken(IERC20Metadata token) external nonReentrant onlyOwner {
        uint8 decs = token.decimals();
        if (decs != 6 && decs != 8 && decs != 18) revert InvalidErc20Token();

        address tokenAddr = address(token);
        if (whitelistedTokens[tokenAddr]) revert TokenAlreadyEnabled();

        whitelistedTokens[tokenAddr] = true;
        emit TokenEnabled(tokenAddr);
    }

    /**
     * @notice Disables the token specified.
     * @param tokenAddr The ERC20 token to disable.
     */
    function disableToken(address tokenAddr) external nonReentrant onlyOwner {
        if (!whitelistedTokens[tokenAddr]) revert TokenAlreadyDisabled();

        delete whitelistedTokens[tokenAddr];
        emit TokenDisabled(tokenAddr);
    }

    /**
     * @notice Updates the address of the fees collector.
     * @param newFeesCollectorAddr The address of the new fees collector.
     */
    function updateFeesCollector(address newFeesCollectorAddr) external nonReentrant onlyOwner {
        if (newFeesCollectorAddr == address(0)) revert ZeroAddress();
        if (newFeesCollectorAddr == address(this)) revert InvalidAddress();
        if (feesCollector == newFeesCollectorAddr) revert FeesCollectorNoOp();

        feesCollector = newFeesCollectorAddr;
        emit FeesCollectorUpdated(newFeesCollectorAddr);
    }

    // --------------------------------------------------------------------------------------
    // Vaults Management
    // --------------------------------------------------------------------------------------
    /**
     * @notice Sets the swap fee charged on swaps that deposit into the vault specified.
     * @dev Any vault can be deposited into without being configured; this only sets its fee.
     * @param vaultAddr The vault address.
     * @param swapFee The swap fee, expressed in BPS.
     */
    function setVaultSwapFee(address vaultAddr, uint256 swapFee) external nonReentrant onlyOwner {
        if (vaultAddr == address(0)) revert ZeroAddress();
        if (swapFee > MAX_SWAP_FEE_BPS) revert SwapFeeTooHigh();

        vaultSwapFees[vaultAddr] = swapFee;
        emit VaultSwapFeeUpdated(vaultAddr, swapFee);
    }

    // --------------------------------------------------------------------------------------
    // Routers Management
    // --------------------------------------------------------------------------------------
    /**
     * @notice Enables the router specified.
     * @dev Throws if any of the addresses are zero addresses. Overwrites are intentional.
     * @param routerAddr The address of the external router.
     * @param tokenApprovalAddr The address of the tokens approval contract, if any. Pass the router address otherwise.
     * @param authorizedSelector The selector of the authorized function call.
     */
    function enableRouter(address routerAddr, address tokenApprovalAddr, bytes4 authorizedSelector)
        external
        nonReentrant
        onlyOwner
    {
        if (
            routerAddr == address(0) || tokenApprovalAddr == address(0) || routerAddr == address(this)
                || tokenApprovalAddr == address(this)
        ) revert InvalidRouterPath(routerAddr, tokenApprovalAddr);
        if (authorizedSelector == bytes4(0)) revert SelectorRequired();

        tokenTransferProxies[routerAddr] = tokenApprovalAddr;
        _authorizedRouterSelectors[routerAddr][authorizedSelector] = true;

        emit RouterPathEnabled(routerAddr, tokenApprovalAddr);
    }

    /**
     * @notice Disables the router specified.
     * @dev Throws if the router is disabled already.
     * @param routerAddr The address of the external router.
     * @param authorizedSelector The selector of the authorized function call.
     */
    function disableRouter(address routerAddr, bytes4 authorizedSelector) external nonReentrant onlyOwner {
        if (tokenTransferProxies[routerAddr] == address(0)) revert RouterPathAlreadyDisabled(routerAddr);

        delete tokenTransferProxies[routerAddr];
        delete _authorizedRouterSelectors[routerAddr][authorizedSelector];

        emit RouterPathDisabled(routerAddr);
    }

    // --------------------------------------------------------------------------------------
    // Origins Management
    // --------------------------------------------------------------------------------------
    /**
     * @notice Enables a new referrer.
     * @dev Reverts if the referrer already exists.
     * @param originCode The code of the referrer.
     * @param originFee The fee taken by the referrer, expressed in bps. It can be zero.
     * @param originFeeCollector The fee collector of the referrer.
     */
    function addOrigin(bytes32 originCode, uint256 originFee, address originFeeCollector)
        external
        nonReentrant
        onlyOwner
        ifNotPaused
    {
        if (originCode == bytes32(0)) revert InvalidOrigin();
        if ((originFeeCollector == address(0)) || (originFeeCollector == address(this))) revert InvalidFeeCollector();
        if (origins[originCode].originFeeCollector != address(0)) revert OriginAlreadyExists();
        if (originFee > MAX_ORIGIN_FEE_BPS) revert OriginFeeTooHigh();

        origins[originCode] = OriginEntry({originFee: originFee, originFeeCollector: originFeeCollector});

        emit OriginAdded(originCode, originFee, originFeeCollector);
    }

    /**
     * @notice Updates the settings of the referrer specified.
     * @dev Reverts if the referrer does not exist.
     * @param originCode The code of the referrer.
     * @param originFee The fee taken by the referrer, expressed in bps. It can be zero.
     * @param originFeeCollector The fee collector of the referrer.
     */
    function updateOrigin(bytes32 originCode, uint256 originFee, address originFeeCollector)
        external
        nonReentrant
        onlyOwner
        ifNotPaused
    {
        if ((originFeeCollector == address(0)) || (originFeeCollector == address(this))) {
            revert InvalidFeeCollector();
        }
        if (origins[originCode].originFeeCollector == address(0)) revert InvalidOrigin();
        if (originFee > MAX_ORIGIN_FEE_BPS) revert OriginFeeTooHigh();

        origins[originCode].originFee = originFee;
        origins[originCode].originFeeCollector = originFeeCollector;

        emit OriginUpdated(originCode, originFee, originFeeCollector);
    }

    /**
     * @notice Disables the referrer specified.
     * @param originCode The code of the referrer.
     */
    function revokeOrigin(bytes32 originCode) external nonReentrant onlyOwner ifNotPaused {
        if (origins[originCode].originFeeCollector == address(0)) revert InvalidOrigin();
        delete origins[originCode];
        emit OriginRevoked(originCode);
    }

    // --------------------------------------------------------------------------------------
    // Swap and Deposit Functions
    // --------------------------------------------------------------------------------------
    /**
     * @notice Runs multiple swaps and deposits the output in the vault specified.
     * @param originCode The origin code. Passing zero bytes32 means there is no origin code at all.
     * @param vaultAddr The address of the vault.
     * @param vaultType The type of vault: 1 for ERC-4626, 2 for Tokenized Vault V2.
     * @param receiverAddr The receiving address.
     * @param swapParams The parameters of each swap.
     * @return shares The resulting number of shares issued by the vault.
     */
    function swapAndDeposit(
        bytes32 originCode,
        address vaultAddr,
        uint8 vaultType,
        address receiverAddr,
        SwapParams[] calldata swapParams
    ) external override nonReentrant ifNotPaused returns (uint256 shares) {
        if (swapParams.length < 1) revert EmptySwapParams();
        if (swapParams.length > MAX_SWAPS) revert TooManySwaps();

        address referenceAsset = _validateSwapParams(originCode, vaultAddr, vaultType, receiverAddr, swapParams);

        _sweepTokens(1, referenceAsset, feesCollector, swapParams);

        uint256 dynamicShares = 0;

        for (uint256 i; i < swapParams.length; i++) {
            (uint256 depositAmount, uint256 swapFeeAmount) = _runSwapErc20(vaultAddr, swapParams[i]);

            dynamicShares += _depositErc20(
                originCode,
                referenceAsset,
                vaultAddr,
                vaultType,
                swapParams[i].tokenOut,
                depositAmount,
                swapFeeAmount,
                receiverAddr
            );
        }

        // Refund any excess of input tokens
        _sweepTokens(2, referenceAsset, msg.sender, swapParams);

        shares = dynamicShares;
    }

    /**
     * @notice Swaps the native token of the network and deposits the wrapped version of it into the vault specified.
     * @dev Throws if the wrapped native token is not set.
     * @param originCode The origin code. Passing zero bytes32 means there is no origin code at all.
     * @param vaultAddr The address of the vault.
     * @param vaultType The type of vault: 1 for ERC-4626, 2 for Tokenized Vault V2.
     * @param receiverAddr The receiving address.
     * @return shares The resulting number of shares issued by the vault.
     */
    function swapAndDepositNativeToken(bytes32 originCode, address vaultAddr, uint8 vaultType, address receiverAddr)
        external
        payable
        override
        nonReentrant
        ifNotPaused
        returns (uint256 shares)
    {
        if (msg.value < 1) revert ZeroAmount();

        address referenceAsset = _validateCommonParams(originCode, vaultAddr, vaultType, receiverAddr);

        uint256 cb = IERC20(wrappedNativeTokenAddress).balanceOf(address(this));
        if (cb > 0) {
            emit ResidualBalanceSwept(wrappedNativeTokenAddress, feesCollector, cb);
            SafeERC20.safeTransfer(IERC20(wrappedNativeTokenAddress), feesCollector, cb);
        }

        // Swap
        IWeth(wrappedNativeTokenAddress).deposit{value: msg.value}();

        cb = IERC20(wrappedNativeTokenAddress).balanceOf(address(this));
        if (cb != msg.value) revert NativeSwapFailed();

        uint256 swapFeeAmount;
        (cb, swapFeeAmount) = _applySwapFee(vaultAddr, wrappedNativeTokenAddress, cb);

        // Deposit
        shares = _depositErc20(
            originCode, referenceAsset, vaultAddr, vaultType, wrappedNativeTokenAddress, cb, swapFeeAmount, receiverAddr
        );

        // Refund any dust
        cb = IERC20(wrappedNativeTokenAddress).balanceOf(address(this));
        if (cb > 0) {
            emit ResidualRefund(wrappedNativeTokenAddress, msg.sender, cb);
            SafeERC20.safeTransfer(IERC20(wrappedNativeTokenAddress), msg.sender, cb);
        }
    }

    /**
     * @notice Deposits an ERC20 token in the vault specified.
     * @param originCode The origin code. Passing zero bytes32 means there is no origin code at all.
     * @param depositAmount The deposit amount.
     * @param vaultAddr The address of the vault.
     * @param vaultType The type of vault: 1 for ERC-4626, 2 for Tokenized Vault V2.
     * @param assetAddr The asset to deposit.
     * @param receiverAddr The receiving address.
     * @return shares The number of shares issued by the vault.
     */
    function deposit(
        bytes32 originCode,
        uint256 depositAmount,
        address vaultAddr,
        uint8 vaultType,
        address assetAddr,
        address receiverAddr
    ) external override nonReentrant ifNotPaused returns (uint256 shares) {
        if (depositAmount < 1) revert ZeroAmount();
        if (!whitelistedTokens[assetAddr]) revert InputTokenNotWhitelisted(assetAddr);

        address referenceAsset = _validateCommonParams(originCode, vaultAddr, vaultType, receiverAddr);

        uint256 cb = IERC20(assetAddr).balanceOf(address(this));
        if (cb > 0) {
            emit ResidualBalanceSwept(assetAddr, feesCollector, cb);
            SafeERC20.safeTransfer(IERC20(assetAddr), feesCollector, cb);
        }

        SafeERC20.safeTransferFrom(IERC20(assetAddr), msg.sender, address(this), depositAmount);

        shares =
            _depositErc20(originCode, referenceAsset, vaultAddr, vaultType, assetAddr, depositAmount, 0, receiverAddr);

        // Refund any residual tokens
        cb = IERC20(assetAddr).balanceOf(address(this));
        if (cb > 0) {
            emit ResidualRefund(assetAddr, msg.sender, cb);
            SafeERC20.safeTransfer(IERC20(assetAddr), msg.sender, cb);
        }
    }

    /**
     * @notice Deposits the native token in the vault specified.
     * @param originCode The origin code. Passing zero bytes32 means there is no origin code at all.
     * @param vaultAddr The address of the vault.
     * @param vaultType The type of vault: 1 for ERC-4626, 2 for Tokenized Vault V2.
     * @param receiverAddr The receiving address.
     * @return shares The number of shares issued by the vault.
     */
    function depositNativeToken(bytes32 originCode, address vaultAddr, uint8 vaultType, address receiverAddr)
        external
        payable
        override
        nonReentrant
        ifNotPaused
        returns (uint256 shares)
    {
        if (msg.value < 1) revert ZeroAmount();

        address referenceAsset = _validateCommonParams(originCode, vaultAddr, vaultType, receiverAddr);

        uint256 cb = IERC20(wrappedNativeTokenAddress).balanceOf(address(this));
        if (cb > 0) {
            emit ResidualBalanceSwept(wrappedNativeTokenAddress, feesCollector, cb);
            SafeERC20.safeTransfer(IERC20(wrappedNativeTokenAddress), feesCollector, cb);
        }

        IWeth(wrappedNativeTokenAddress).deposit{value: msg.value}();

        cb = IERC20(wrappedNativeTokenAddress).balanceOf(address(this));
        if (cb != msg.value) revert NativeSwapFailed();

        shares = _depositErc20(
            originCode, referenceAsset, vaultAddr, vaultType, wrappedNativeTokenAddress, cb, 0, receiverAddr
        );

        // Refund any dust
        cb = IERC20(wrappedNativeTokenAddress).balanceOf(address(this));
        if (cb > 0) {
            emit ResidualRefund(wrappedNativeTokenAddress, msg.sender, cb);
            SafeERC20.safeTransfer(IERC20(wrappedNativeTokenAddress), msg.sender, cb);
        }
    }

    // --------------------------------------------------------------------------------------
    // Internal functions
    // --------------------------------------------------------------------------------------
    /**
     * @dev Validates the parameters of swaps and deposits
     * @param originCode The origin code
     * @param vaultAddr The vault address
     * @param vaultType The type of vault
     * @param receiverAddr The address of the receiver
     * @return referenceAsset The reference asset of the vault
     */
    function _validateCommonParams(bytes32 originCode, address vaultAddr, uint8 vaultType, address receiverAddr)
        private
        view
        returns (address referenceAsset)
    {
        if (originCode != bytes32(0) && origins[originCode].originFeeCollector == address(0)) {
            revert InvalidOrigin();
        }
        if (receiverAddr == address(0) || receiverAddr == address(this)) revert InvalidReceiver();

        if (vaultType != VAULT_TYPE_ERC4626 && vaultType != VAULT_TYPE_TOKENIZED_VAULT_V2) revert InvalidVaultType();

        referenceAsset = IV2Vault(vaultAddr).asset();
        if (referenceAsset == address(0)) revert InvalidVault();
        if (referenceAsset == NATIVE_TOKEN_ADDRESS) revert NativeReferenceAssetNotSupported();
    }

    /**
     * @dev Validates the parameters of a swap. The output token can be duplicated (eg: USDC > USDT and WETH > USDT)
     * @param originCode The origin code
     * @param vaultAddr The vault address
     * @param vaultType The type of vault
     * @param receiverAddr The address of the receiver
     * @param swapParams The swap parameters
     * @return referenceAsset The reference asset of the vault
     */
    function _validateSwapParams(
        bytes32 originCode,
        address vaultAddr,
        uint8 vaultType,
        address receiverAddr,
        SwapParams[] calldata swapParams
    ) private view returns (address referenceAsset) {
        referenceAsset = _validateCommonParams(originCode, vaultAddr, vaultType, receiverAddr);

        // Validate swap params
        for (uint256 i; i < swapParams.length; i++) {
            if (swapParams[i].tokenIn == swapParams[i].tokenOut) revert InvalidPair();
            if (swapParams[i].amountIn < 1) revert ZeroAmount();

            // The output of a swap cannot be the native token
            if (swapParams[i].tokenOut == NATIVE_TOKEN_ADDRESS) revert OutputTokenCannotBeNativeToken();

            if (swapParams[i].payload.length < 4) revert InvalidPayload();

            // Validate the router specified
            address tokenApprovalAddr = _getTokenTransferProxy(swapParams[i].router);
            if (tokenApprovalAddr == address(0)) revert InvalidRouter();

            // Make sure the input token is whitelisted
            if (!whitelistedTokens[swapParams[i].tokenIn]) revert InputTokenNotWhitelisted(swapParams[i].tokenIn);

            // Make sure the output token is whitelisted
            if (!whitelistedTokens[swapParams[i].tokenOut]) revert OutputTokenNotWhitelisted(swapParams[i].tokenOut);
        }
    }

    /**
     * @dev Deposits an ERC20 in the vault specified.
     * @param originCode The origin code
     * @param referenceAsset The reference asset of the vault
     * @param vaultAddr The vault address
     * @param vaultType The type of vault
     * @param assetAddr The asset to deposit
     * @param depositAmount The amount to deposit
     * @param swapFeeAmount The swap fee already taken from the deposit amount
     * @param receiverAddr The address of the receiver
     * @return shares The number of shares issued by the vault
     */
    function _depositErc20(
        bytes32 originCode,
        address referenceAsset,
        address vaultAddr,
        uint8 vaultType,
        address assetAddr,
        uint256 depositAmount,
        uint256 swapFeeAmount,
        address receiverAddr
    ) private returns (uint256 shares) {
        // Apply the origin fees
        (uint256 effectiveDepositAmount, uint256 originFee, address originFeeCollector) =
            _applyOriginFees(depositAmount, originCode, assetAddr);

        SafeERC20.safeApprove(IERC20(assetAddr), vaultAddr, effectiveDepositAmount);

        if (vaultType == VAULT_TYPE_ERC4626) {
            if (assetAddr != referenceAsset) revert AssetNotAcceptedByVault();
            shares = IERC4626(vaultAddr).deposit(effectiveDepositAmount, receiverAddr);
        } else {
            shares = IV2Vault(vaultAddr).deposit(assetAddr, effectiveDepositAmount, receiverAddr);
        }

        SafeERC20.safeApprove(IERC20(assetAddr), vaultAddr, 0);
        if (shares < 1) revert ZeroSharesReceived();

        emit DepositRouted(
            msg.sender,
            vaultAddr,
            originCode,
            receiverAddr,
            assetAddr,
            depositAmount,
            effectiveDepositAmount,
            shares,
            originFee,
            depositAmount - effectiveDepositAmount,
            originFeeCollector,
            swapFeeAmount
        );
    }

    /**
     * @dev Applies origin fees. The fee is applied if -and only if- the origin code is valid.
     * @param consumableAmount The amount that can be consumed
     * @param originCode The origin code
     * @param assetAddr The asset to deposit in the vault
     * @return newBalance The applicable balance of the asset
     * @return originFee The origin fee, expressed in bps. Zero if the origin code is not registered.
     * @return originFeeCollector The fee collector of the origin. Zero address if the origin code is not registered.
     */
    function _applyOriginFees(uint256 consumableAmount, bytes32 originCode, address assetAddr)
        private
        returns (uint256 newBalance, uint256 originFee, address originFeeCollector)
    {
        uint256 applicableOriginFee = 0;
        originFeeCollector = origins[originCode].originFeeCollector;

        // If the origin code is valid then apply the respective fee.
        // Otherwise, the applicable fee is zero.
        if (originFeeCollector != address(0)) {
            originFee = origins[originCode].originFee;
            if (originFee > 0) {
                if (originFee * consumableAmount < 1e4) revert OriginFeeTooLow();
                applicableOriginFee = (originFee * consumableAmount) / 1e4;
            }
        }

        if (applicableOriginFee >= consumableAmount) revert OriginFeeTooHigh();
        newBalance = consumableAmount - applicableOriginFee;

        if (applicableOriginFee > 0) {
            // Transfer the origin fee to the collector specified.
            SafeERC20.safeTransfer(IERC20(assetAddr), originFeeCollector, applicableOriginFee);
        }
    }

    /**
     * @dev Sweeps all residual tokens to the address specified.
     * @param sweepType The type of sweep (1 = existing balance, 2 = refund)
     * @param referenceAsset The reference asset of the vault
     * @param receiverAddr The address of the receiver
     * @param swapParams The swap parameters
     */
    function _sweepTokens(
        uint8 sweepType,
        address referenceAsset,
        address receiverAddr,
        SwapParams[] calldata swapParams
    ) private {
        uint256 cb = IERC20(referenceAsset).balanceOf(address(this));
        if (cb > 0) SafeERC20.safeTransfer(IERC20(referenceAsset), receiverAddr, cb);

        for (uint256 i; i < swapParams.length; i++) {
            cb = IERC20(swapParams[i].tokenIn).balanceOf(address(this));
            if (cb > 0) {
                if (sweepType == 1) {
                    emit ResidualBalanceSwept(swapParams[i].tokenIn, receiverAddr, cb);
                } else {
                    emit ResidualRefund(swapParams[i].tokenIn, receiverAddr, cb);
                }
                SafeERC20.safeTransfer(IERC20(swapParams[i].tokenIn), receiverAddr, cb);
            }

            cb = IERC20(swapParams[i].tokenOut).balanceOf(address(this));
            if (cb > 0) {
                if (sweepType == 1) {
                    emit ResidualBalanceSwept(swapParams[i].tokenOut, receiverAddr, cb);
                } else {
                    emit ResidualRefund(swapParams[i].tokenOut, receiverAddr, cb);
                }
                SafeERC20.safeTransfer(IERC20(swapParams[i].tokenOut), receiverAddr, cb);
            }
        }
    }

    /**
     * @dev Runs an atomic swap.
     * @param vaultAddr The vault address.
     * @param swapParams The swap parameters.
     * @return depositableAmount The amount that can be deposited in the vault.
     * @return swapFeeAmount The swap fee taken from the output of the swap.
     */
    function _runSwapErc20(address vaultAddr, SwapParams calldata swapParams)
        private
        returns (uint256 depositableAmount, uint256 swapFeeAmount)
    {
        // Make sure the selector is authorized.
        // Why?
        //    While the router address is whitelisted, the payload is fully user-controlled.
        //    A malicious user could craft a payload that calls a different function on the whitelisted router (not just swap),
        //    potentially exploiting any function on that contract.
        //    For example, if a whitelisted DEX aggregator has an approve or transfer function, a user could call it via this contract's token approvals.
        if (!_authorizedRouterSelectors[swapParams.router][bytes4(swapParams.payload)]) revert InvalidNotWhitelisted();

        // The token transfer proxy (aka: token approval address) is dynamic, since it is defined by the router.
        // Thus such an address is subject to change on the fly.
        // If the router does not require a token transfer proxy then the token approval address is the router itself.
        address tokenApprovalAddr = _getTokenTransferProxy(swapParams.router);

        // The minimum number of output tokens to receive after the swap.
        if (swapParams.minAmountOut == 0) revert MissingSlippageProtection();

        // Transfer the amount of tokens specified from the message sender to this contract
        SafeERC20.safeTransferFrom(IERC20(swapParams.tokenIn), msg.sender, address(this), swapParams.amountIn);

        uint256 amountInBeforeSwap = IERC20(swapParams.tokenIn).balanceOf(address(this));

        uint256 cbTokenOut = IERC20(swapParams.tokenOut).balanceOf(address(this));

        // Approve the external router
        SafeERC20.safeApprove(IERC20(swapParams.tokenIn), tokenApprovalAddr, swapParams.amountIn);

        // Execute the swap. Run the untrusted call against the router
        (bool success, bytes memory returndata) = swapParams.router.call(swapParams.payload);
        if (!success) revert SwapFailed(returndata);

        uint256 delta = IERC20(swapParams.tokenOut).balanceOf(address(this)) - cbTokenOut;

        // Revoke the ERC20 approval
        SafeERC20.safeApprove(IERC20(swapParams.tokenIn), tokenApprovalAddr, 0);

        // Slippage check
        if (delta < swapParams.minAmountOut) revert SlippageError(swapParams.tokenOut, delta, swapParams.minAmountOut);

        // Swap check
        uint256 cbTokenIn = IERC20(swapParams.tokenIn).balanceOf(address(this));
        if (amountInBeforeSwap == cbTokenIn) revert InputTokenNotSwapped(swapParams.tokenIn);

        (depositableAmount, swapFeeAmount) = _applySwapFee(vaultAddr, swapParams.tokenOut, delta);
    }

    /**
     * @dev Applies a swap fee on the token specified.
     * @param vaultAddr The vault address.
     * @param tokenOutAddr The output token of the swap.
     * @param swapAmountOut The actual output amount of the swap.
     * @return newBalance The new balance of the output token after applying fees.
     * @return applicablePlatformFee The swap fee amount transferred to the fees collector.
     */
    function _applySwapFee(address vaultAddr, address tokenOutAddr, uint256 swapAmountOut)
        private
        returns (uint256 newBalance, uint256 applicablePlatformFee)
    {
        uint256 swapFee = vaultSwapFees[vaultAddr];

        if (swapFee > 0) {
            // Safe because MAX_SWAP_FEE_BPS (7000) < BPS_DENOMINATOR (10000), so applicablePlatformFee
            // is always strictly less than swapAmountOut.
            // Do not raise MAX_SWAP_FEE_BPS to >= 1e4 without restoring the `applicablePlatformFee >= swapAmountOut` guard.
            if (swapFee * swapAmountOut < BPS_DENOMINATOR) revert SwapFeeAmountTooLow();
            applicablePlatformFee = (swapFee * swapAmountOut) / BPS_DENOMINATOR;

            newBalance = swapAmountOut - applicablePlatformFee;

            // Transfer the fee to the fees collector
            SafeERC20.safeTransfer(IERC20(tokenOutAddr), feesCollector, applicablePlatformFee);
        } else {
            newBalance = swapAmountOut;
        }
    }

    /**
     * @dev Gets the token transfer proxy of the router specified.
     * @param routerAddr The router address.
     * @return address The address of the token transfer proxy.
     */
    function _getTokenTransferProxy(address routerAddr) internal view virtual returns (address) {
        return tokenTransferProxies[routerAddr];
    }

    /**
     * @notice Indicates if a given selector is authorized on the router specified.
     * @param routerAddr The router address.
     * @param selector The selector.
     * @return bool Returns true if the selector is whitelisted.
     */
    function isAuthorizedSelector(address routerAddr, bytes4 selector) public view returns (bool) {
        return _authorizedRouterSelectors[routerAddr][selector];
    }
}

lib/open-zeppelin/interfaces/IERC4626.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (interfaces/IERC4626.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/IERC20.sol";
import "../token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 *
 * _Available since v4.7._
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}

lib/open-zeppelin/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

lib/open-zeppelin/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
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);
}

lib/open-zeppelin/token/ERC20/extensions/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

lib/open-zeppelin/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 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 {
    using Address for address;

    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), 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 data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

lib/open-zeppelin/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

src/core/OwnableGuarded.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

abstract contract OwnableGuarded {
    // ----------------------------------------------------------------------------------------------------
    // Constants
    // ----------------------------------------------------------------------------------------------------
    // 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;

    // ----------------------------------------------------------------------------------------------------
    // Errors
    // ----------------------------------------------------------------------------------------------------
    error OwnerOnly();
    error OwnerAddressRequired();
    error ReentrancyGuardReentrantCall();

    // ----------------------------------------------------------------------------------------------------
    // Storage layout
    // ----------------------------------------------------------------------------------------------------
    uint256 private _status;
    address internal _owner;

    // ----------------------------------------------------------------------------------------------------
    // Events
    // ----------------------------------------------------------------------------------------------------
    /**
     * @notice Triggers when contract ownership changes.
     * @param previousOwner The previous owner of the contract.
     * @param newOwner The new owner of the contract.
     */
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    // ----------------------------------------------------------------------------------------------------
    // Modifiers
    // ----------------------------------------------------------------------------------------------------
    /**
     * @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() {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;

        _;

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

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        if (msg.sender != _owner) revert OwnerOnly();
        _;
    }

    // ----------------------------------------------------------------------------------------------------
    // Functions
    // ----------------------------------------------------------------------------------------------------
    /**
     * @notice Transfers ownership of the contract to the account specified.
     * @param newOwner The address of the new owner.
     */
    function transferOwnership(address newOwner) external virtual nonReentrant onlyOwner {
        _transferOwnership(newOwner);
    }

    function _transferOwnership(address newOwner) internal virtual {
        if (newOwner == address(0)) revert OwnerAddressRequired();

        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }

    /**
     * @notice Gets the owner of the contract.
     * @return address The address who owns the contract.
     */
    function owner() external view virtual returns (address) {
        return _owner;
    }
}

src/swaps/ISwapRouter.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

/**
 * @notice Defines the interface of a Swap Router
 */
interface ISwapRouter {
    // --------------------------------------------------------------------------------------
    // Structs
    // --------------------------------------------------------------------------------------
    struct SwapParams {
        address tokenIn;
        address tokenOut;
        uint256 amountIn;
        uint256 minAmountOut;
        address router; // Must be whitelisted
        bytes payload; // Encoded swap call
    }

    // Represents an origin
    struct OriginEntry {
        uint256 originFee; // The fee taken by the origin, expressed in bps.
        address originFeeCollector; // The fee collector of the origin
    }

    // --------------------------------------------------------------------------------------
    // Errors
    // --------------------------------------------------------------------------------------
    error ContractIsPaused();
    error ContractNotPaused();
    error InvalidVault();
    error ZeroAddress();
    error InvalidErc20Token();
    error TokenAlreadyEnabled();
    error TokenAlreadyDisabled();
    error SwapFailed(bytes returnData);
    error RouterPathAlreadyDisabled(address routerAddr);
    error InvalidRouterPath(address routerAddr, address tokenApprovalAddr);
    error InvalidRouter();
    error InvalidReceiver();
    error InvalidVaultType();
    error SlippageError(address tokenAddr, uint256 amountOut, uint256 minAmountOut);
    error InputTokenNotWhitelisted(address tokenAddr);
    error OutputTokenNotWhitelisted(address tokenAddr);
    error InputTokenNotSwapped(address tokenAddr);
    error SwapFeeAmountTooLow();
    error SwapFeeTooHigh();
    error OriginFeeTooLow();
    error OriginFeeTooHigh();
    error ZeroSharesReceived();
    error AssetNotAcceptedByVault();
    error NativeTokenTransferFailed();
    error InvalidOrigin();
    error OriginAlreadyExists();
    error InvalidFeeCollector();
    error ZeroAmount();
    error NativeReferenceAssetNotSupported();
    error OutputTokenCannotBeNativeToken();
    error EmptySwapParams();
    error InvalidPair();
    error NativeSwapFailed();
    error InvalidPayload();
    error InvalidNotWhitelisted();
    error SelectorRequired();
    error TooManySwaps();
    error InvalidAddress();
    error MissingSlippageProtection();
    error FeesCollectorNoOp();

    // --------------------------------------------------------------------------------------
    // Events
    // --------------------------------------------------------------------------------------
    /// @notice Triggers when the swap fee of a vault is set.
    /// @param vaultAddr The vault address
    /// @param swapFee The swap fee, expressed in bps
    event VaultSwapFeeUpdated(address indexed vaultAddr, uint256 swapFee);

    /// @notice Triggers when this contract gets paused.
    event ContractPaused();

    /// @notice Triggers when the contract resumes its normal activity.
    event ContractResumed();

    event OriginAdded(bytes32 indexed originCode, uint256 originFee, address originFeeCollector);
    event OriginUpdated(bytes32 indexed originCode, uint256 originFee, address originFeeCollector);
    event OriginRevoked(bytes32 indexed originCode);

    /**
     * @notice Triggers on every deposit, including the ones without fees or origin code.
     * @param sender The address funding the deposit.
     * @param vaultAddr The vault address.
     * @param originCode The origin code, or zero bytes32 if none.
     * @param receiverAddr The address receiving the shares.
     * @param assetAddr The asset deposited in the vault.
     * @param grossAmount The amount before the origin fee. For swaps, this is the swap output after the swap fee.
     * @param depositedAmount The amount deposited in the vault, after the origin fee.
     * @param shares The number of shares issued by the vault.
     * @param originFeeBps The origin fee applied, expressed in bps.
     * @param originFeeAmount The origin fee amount.
     * @param originFeeCollector The fee collector of the origin, or the zero address if the origin is not registered.
     * @param swapFeeAmount The swap fee amount, or zero if no swap fee was applied.
     */
    event DepositRouted(
        address sender,
        address indexed vaultAddr,
        bytes32 indexed originCode,
        address indexed receiverAddr,
        address assetAddr,
        uint256 grossAmount,
        uint256 depositedAmount,
        uint256 shares,
        uint256 originFeeBps,
        uint256 originFeeAmount,
        address originFeeCollector,
        uint256 swapFeeAmount
    );

    /// @notice Triggers when a router path is enabled.
    /// @param routerAddr The address of the router.
    /// @param tokenApprovalAddr The address of the token approval proxy, if any. It should be the router address by default.
    event RouterPathEnabled(address indexed routerAddr, address indexed tokenApprovalAddr);

    /// @notice Triggers when a router path is disabled.
    /// @param routerAddr The address of the router.
    event RouterPathDisabled(address indexed routerAddr);

    /// @notice Triggers when a token is whitelisted.
    /// @param tokenAddr The token address that was enabled.
    event TokenEnabled(address indexed tokenAddr);

    /// @notice Triggers when a token is disabled.
    /// @param tokenAddr The token address that was disabled.
    event TokenDisabled(address indexed tokenAddr);

    /// @notice Triggers when the address of the fees collector gets updated.
    /// @param newAddr The address of the new fees collector.
    event FeesCollectorUpdated(address indexed newAddr);

    /**
     * @notice Triggers when the contract sweeps a token prior running a swap or deposit.
     * @param token The token to sweep
     * @param to The destination address
     * @param amount The amount to sweep
     */
    event ResidualBalanceSwept(address indexed token, address indexed to, uint256 amount);

    /**
     * @notice Triggers when the contract refunds any dust after running a swap or deposit.
     * @param token The token to refund
     * @param to The destination address
     * @param amount The refund amount
     */
    event ResidualRefund(address indexed token, address indexed to, uint256 amount);

    // --------------------------------------------------------------------------------------
    // Functions
    // --------------------------------------------------------------------------------------
    /**
     * @notice Runs multiple swaps and deposits the output in the vault specified.
     * @param originCode The origin code. Passing zero bytes32 means there is no origin code at all.
     * @param vaultAddr The address of the vault.
     * @param vaultType The type of vault: 1 for ERC-4626, 2 for Tokenized Vault V2.
     * @param receiverAddr The receiving address.
     * @param swapParams The parameters of each swap.
     * @return shares The resulting number of shares issued by the vault.
     */
    function swapAndDeposit(
        bytes32 originCode,
        address vaultAddr,
        uint8 vaultType,
        address receiverAddr,
        SwapParams[] calldata swapParams
    ) external returns (uint256 shares);

    /**
     * @notice Swaps the native token of the network and deposits the wrapped version of it into the vault specified.
     * @param originCode The origin code. Passing zero bytes32 means there is no origin code at all.
     * @param vaultAddr The address of the vault.
     * @param vaultType The type of vault: 1 for ERC-4626, 2 for Tokenized Vault V2.
     * @param receiverAddr The receiving address.
     * @return shares The resulting number of shares issued by the vault.
     */
    function swapAndDepositNativeToken(bytes32 originCode, address vaultAddr, uint8 vaultType, address receiverAddr)
        external
        payable
        returns (uint256 shares);

    /**
     * @notice Deposits an ERC20 token in the vault specified.
     * @param originCode The origin code. Passing zero bytes32 means there is no origin code at all.
     * @param depositAmount The deposit amount.
     * @param vaultAddr The address of the vault.
     * @param vaultType The type of vault: 1 for ERC-4626, 2 for Tokenized Vault V2.
     * @param assetAddr The asset to deposit.
     * @param receiverAddr The receiving address.
     * @return shares The number of shares issued by the vault.
     */
    function deposit(
        bytes32 originCode,
        uint256 depositAmount,
        address vaultAddr,
        uint8 vaultType,
        address assetAddr,
        address receiverAddr
    ) external returns (uint256 shares);

    /**
     * @notice Deposits the native token in the vault specified.
     * @param originCode The origin code. Passing zero bytes32 means there is no origin code at all.
     * @param vaultAddr The address of the vault.
     * @param vaultType The type of vault: 1 for ERC-4626, 2 for Tokenized Vault V2.
     * @param receiverAddr The receiving address.
     * @return shares The number of shares issued by the vault.
     */
    function depositNativeToken(bytes32 originCode, address vaultAddr, uint8 vaultType, address receiverAddr)
        external
        payable
        returns (uint256 shares);
}

src/swaps/IV2Vault.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

interface IV2Vault {
    function deposit(address assetIn, uint256 amountIn, address receiverAddr) external returns (uint256);

    /**
     * @notice Gets the address of the reference asset.
     * @return address The address of the reference token.
     */
    function asset() external view returns (address);
}

src/swaps/IWeth.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

interface IWeth {
    function deposit() external payable;
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "@layerzerolabs/=lib/layer-zero/",
    "@openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "@oz/=lib/open-zeppelin/",
    "@axelar-network/=node_modules/@axelar-network/",
    "@chainlink/=node_modules/@chainlink/",
    "@eth-optimism/=node_modules/@eth-optimism/",
    "@openzeppelin/=node_modules/@openzeppelin/",
    "hardhat-deploy/=node_modules/hardhat-deploy/",
    "layer-zero/=lib/layer-zero/",
    "layer-zerov2/=lib/layer-zerov2/",
    "murky/=lib/murky/",
    "open-zeppelin/=lib/open-zeppelin/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "solidity-bytes-utils/=node_modules/solidity-bytes-utils/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.