🤖 AI Agent Full Setup Guide

💬 Support Chat: Click Here

📝 Development Site: Click Here

📜 Source Code

// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

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";

interface IUniswapV3Factory {
    function getPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) external view returns (address pool);
}

interface IUniswapV3Pool {
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);
}

interface IUniswapV3SwapCallback {
    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

interface IWETH9 is IERC20 {
    function deposit() external payable;

    function withdraw(uint256 amount) external;
}

/// @title MultiHopSwap
/// @notice Strict exact-input swaps through canonical Uniswap V3 pools.
/// @dev Security assumptions:
///      - Deploy only with a verified canonical V3 factory and WETH9.
///      - Supported tokens must have standard, non-rebasing ERC-20 behavior.
///      - Balance checks reject observed discrepancies, but cannot prove
///        that a malicious token implementation is safe.
///
///      Execution:
///      - Every hop must consume its entire input and produce output.
///      - Every pool is resolved before collecting the user's input.
///      - Intermediate outputs are held here only during execution.
///      - Callers must select a meaningful amountOutMin and deadline.
///      - A zero amountOutMin explicitly disables the output floor.
///
///      Custody:
///      - No owner, upgrades, arbitrary execution, approvals, or rescue.
///      - Unsolicited tokens and forced ETH may be permanently stranded.
contract MultiHopSwap is
    ReentrancyGuard,
    IUniswapV3SwapCallback
{
    using SafeERC20 for IERC20;

    IUniswapV3Factory public immutable factory;
    IWETH9 public immutable weth;

    address public constant NATIVE = address(0);

    // Canonical TickMath.MIN_SQRT_RATIO + 1.
    uint160 private constant MIN_PRICE_LIMIT = 4295128740;

    // Canonical TickMath.MAX_SQRT_RATIO - 1.
    uint160 private constant MAX_PRICE_LIMIT =
        1461446703485210103287273052203988822378723970341;

    // Authorization exists only during one synchronous pool.swap call.
    address private activePool;
    address private activeInput;
    uint256 private activeAmount;
    bool private activeZeroForOne;

    error ZeroAmount();
    error AmountTooLarge();
    error DeadlineInPast();
    error InvalidPath();
    error InvalidToken(address token);
    error InvalidDeployment();
    error PoolNotFound();
    error WrongMsgValue();
    error NotWeth();
    error UnauthorizedCallback();
    error UnexpectedCallbackData();
    error InvalidSwapDelta();
    error IncompleteSwap();
    error UnexpectedBalanceChange(address token);
    error InsufficientOutput(uint256 received, uint256 minimum);
    error EthTransferFailed();

    event Swapped(
        address indexed user,
        address indexed tokenIn,
        address indexed tokenOut,
        uint256 amountIn,
        uint256 amountOut
    );

    /// @dev Code-existence checks do not authenticate these dependencies.
    ///      Verify canonical, chain-specific addresses before deployment.
    constructor(address factory_, address weth_) {
        if (
            factory_ == address(0)
                || weth_ == address(0)
                || factory_ == weth_
                || factory_.code.length == 0
                || weth_.code.length == 0
        ) {
            revert InvalidDeployment();
        }

        factory = IUniswapV3Factory(factory_);
        weth = IWETH9(weth_);
    }

    /// @dev Accepts ordinary ETH transfers only from WETH9.
    ///      Forced ETH transfers cannot be prevented.
    receive() external payable {
        if (msg.sender != address(weth)) revert NotWeth();
    }

    /// @notice Swap through one pool with full input consumption.
    /// @dev Use NATIVE for native ETH input or output.
    ///      Native ETH and WETH are the same pool asset, so a direct
    ///      native-to-WETH or WETH-to-native route is not a valid swap.
    /// @param amountOutMin Minimum final output; zero disables the floor.
    /// @param deadline Latest permitted block timestamp, inclusive.
    function swapExactInputSingle(
        address tokenIn,
        address tokenOut,
        uint24 fee,
        uint256 amountIn,
        uint256 amountOutMin,
        uint256 deadline
    ) external payable nonReentrant returns (uint256 amountOut) {
        _validateRequest(amountIn, deadline);

        address realTokenIn =
            tokenIn == NATIVE ? address(weth) : tokenIn;
        address realTokenOut =
            tokenOut == NATIVE ? address(weth) : tokenOut;

        _validateToken(realTokenIn);
        _validateToken(realTokenOut);
        _validatePair(realTokenIn, realTokenOut, fee);

        // Resolve and validate before collecting user funds.
        address pool = _resolvePool(realTokenIn, realTokenOut, fee);

        _receiveInput(realTokenIn, tokenIn == NATIVE, amountIn);

        amountOut = _swapHop(
            realTokenIn,
            realTokenOut,
            pool,
            amountIn
        );

        _requireMinimum(amountOut, amountOutMin);
        _deliverOutput(realTokenOut, tokenOut == NATIVE, amountOut);

        emit Swapped(
            msg.sender,
            tokenIn,
            tokenOut,
            amountIn,
            amountOut
        );
    }

    /// @notice Swap along a canonical packed V3 path.
    /// @dev Format: token(20) | fee(3) | token(20) | ...
    ///      Native ETH must be represented by WETH inside the path.
    ///      Every hop must fully consume its input and produce output.
    ///      Contract callers requesting native output must accept ETH.
    /// @param amountOutMin Minimum final output; zero disables the floor.
    /// @param deadline Latest permitted block timestamp, inclusive.
    function swapExactInputMultihop(
        bytes calldata path,
        bool ethIn,
        bool ethOut,
        uint256 amountIn,
        uint256 amountOutMin,
        uint256 deadline
    ) external payable nonReentrant returns (uint256 amountOut) {
        _validateRequest(amountIn, deadline);

        (
            address firstToken,
            address lastToken,
            address[] memory pools
        ) = _validateAndResolvePath(path);

        if (ethIn && firstToken != address(weth)) {
            revert InvalidPath();
        }

        if (ethOut && lastToken != address(weth)) {
            revert InvalidPath();
        }

        _receiveInput(firstToken, ethIn, amountIn);

        amountOut = amountIn;

        for (uint256 i; i < pools.length; ++i) {
            uint256 offset = i * 23;

            amountOut = _swapHop(
                _tokenAt(path, offset),
                _tokenAt(path, offset + 23),
                pools[i],
                amountOut
            );
        }

        _requireMinimum(amountOut, amountOutMin);
        _deliverOutput(lastToken, ethOut, amountOut);

        emit Swapped(
            msg.sender,
            ethIn ? NATIVE : firstToken,
            ethOut ? NATIVE : lastToken,
            amountIn,
            amountOut
        );
    }

    /// @notice Pay the currently active authenticated V3 pool.
    /// @dev Intentionally not nonReentrant: the pool invokes this during
    ///      a guarded swap entry point.
    ///
    ///      The exact pool is selected from the immutable trusted factory.
    ///      Authorization is consumed before transferring payment.
    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external override {
        if (
            activePool == address(0)
                || msg.sender != activePool
        ) {
            revert UnauthorizedCallback();
        }

        if (data.length != 0) revert UnexpectedCallbackData();

        address input = activeInput;
        uint256 amount = activeAmount;

        int256 inputDelta = activeZeroForOne
            ? amount0Delta
            : amount1Delta;

        int256 outputDelta = activeZeroForOne
            ? amount1Delta
            : amount0Delta;

        if (inputDelta <= 0 || outputDelta >= 0) {
            revert InvalidSwapDelta();
        }

        // Reject partial fills before paying the pool.
        if (uint256(inputDelta) != amount) {
            revert IncompleteSwap();
        }

        delete activePool;
        delete activeInput;
        delete activeAmount;
        delete activeZeroForOne;

        IERC20(input).safeTransfer(msg.sender, amount);
    }

    /// @notice Encode a canonical V3 path.
    /// @dev Pure encoding does not verify token code or pool existence.
    function encodePath(
        address[] calldata tokens,
        uint24[] calldata fees
    ) external pure returns (bytes memory path) {
        if (
            tokens.length < 2
                || fees.length != tokens.length - 1
        ) {
            revert InvalidPath();
        }

        path = new bytes(20 + fees.length * 23);

        for (uint256 i; i < tokens.length; ++i) {
            if (tokens[i] == NATIVE) revert InvalidPath();

            uint256 offset = i * 23;
            bytes20 tokenBytes = bytes20(tokens[i]);

            for (uint256 j; j < 20; ++j) {
                path[offset + j] = tokenBytes[j];
            }

            if (i < fees.length) {
                _validatePair(tokens[i], tokens[i + 1], fees[i]);

                bytes3 feeBytes = bytes3(fees[i]);

                for (uint256 j; j < 3; ++j) {
                    path[offset + 20 + j] = feeBytes[j];
                }
            }
        }
    }

    /// @dev The pool argument must originate from _resolvePool.
    ///      Both private call sites satisfy this requirement.
    function _swapHop(
        address tokenIn,
        address tokenOut,
        address pool,
        uint256 amountIn
    ) private returns (uint256 amountOut) {
        _validateAmount(amountIn);

        if (activePool != address(0)) {
            revert UnauthorizedCallback();
        }

        IERC20 input = IERC20(tokenIn);
        IERC20 output = IERC20(tokenOut);

        uint256 inputBefore = input.balanceOf(address(this));
        uint256 outputBefore = output.balanceOf(address(this));

        bool zeroForOne = tokenIn < tokenOut;

        activePool = pool;
        activeInput = tokenIn;
        activeAmount = amountIn;
        activeZeroForOne = zeroForOne;

        (int256 amount0, int256 amount1) = IUniswapV3Pool(pool).swap(
            address(this),
            zeroForOne,
            int256(amountIn),
            zeroForOne ? MIN_PRICE_LIMIT : MAX_PRICE_LIMIT,
            bytes("")
        );

        // A successful swap must have consumed callback authorization.
        if (activePool != address(0)) revert IncompleteSwap();

        int256 inputDelta = zeroForOne ? amount0 : amount1;
        int256 outputDelta = zeroForOne ? amount1 : amount0;

        if (inputDelta <= 0 || uint256(inputDelta) != amountIn) {
            revert IncompleteSwap();
        }

        if (
            outputDelta >= 0
                || outputDelta == type(int256).min
        ) {
            revert InvalidSwapDelta();
        }

        amountOut = uint256(-outputDelta);

        _requireDecrease(
            tokenIn,
            inputBefore,
            input.balanceOf(address(this)),
            amountIn
        );

        _requireIncrease(
            tokenOut,
            outputBefore,
            output.balanceOf(address(this)),
            amountOut
        );
    }

    function _receiveInput(
        address token,
        bool ethIn,
        uint256 amount
    ) private {
        if (ethIn) {
            if (token != address(weth)) revert InvalidPath();
            if (msg.value != amount) revert WrongMsgValue();

            uint256 wethBefore = weth.balanceOf(address(this));
            uint256 ethBefore = address(this).balance;

            weth.deposit{value: amount}();

            _requireIncrease(
                token,
                wethBefore,
                weth.balanceOf(address(this)),
                amount
            );

            _requireDecrease(
                NATIVE,
                ethBefore,
                address(this).balance,
                amount
            );

            return;
        }

        if (msg.value != 0) revert WrongMsgValue();

        IERC20 asset = IERC20(token);

        uint256 helperBefore = asset.balanceOf(address(this));
        uint256 senderBefore = asset.balanceOf(msg.sender);

        asset.safeTransferFrom(msg.sender, address(this), amount);

        _requireIncrease(
            token,
            helperBefore,
            asset.balanceOf(address(this)),
            amount
        );

        // Detect observed extra fees charged to the input sender.
        _requireDecrease(
            token,
            senderBefore,
            asset.balanceOf(msg.sender),
            amount
        );
    }

    function _deliverOutput(
        address token,
        bool ethOut,
        uint256 amount
    ) private {
        if (ethOut) {
            if (token != address(weth)) revert InvalidPath();

            uint256 wethBefore = weth.balanceOf(address(this));
            uint256 ethBefore = address(this).balance;

            weth.withdraw(amount);

            _requireDecrease(
                token,
                wethBefore,
                weth.balanceOf(address(this)),
                amount
            );

            _requireIncrease(
                NATIVE,
                ethBefore,
                address(this).balance,
                amount
            );

            (bool ok, ) = payable(msg.sender).call{value: amount}("");
            if (!ok) revert EthTransferFailed();

            return;
        }

        IERC20 asset = IERC20(token);

        uint256 helperBefore = asset.balanceOf(address(this));
        uint256 recipientBefore = asset.balanceOf(msg.sender);

        asset.safeTransfer(msg.sender, amount);

        _requireDecrease(
            token,
            helperBefore,
            asset.balanceOf(address(this)),
            amount
        );

        _requireIncrease(
            token,
            recipientBefore,
            asset.balanceOf(msg.sender),
            amount
        );
    }

    function _resolvePool(
        address tokenIn,
        address tokenOut,
        uint24 fee
    ) private view returns (address pool) {
        pool = factory.getPool(tokenIn, tokenOut, fee);

        if (pool == address(0) || pool.code.length == 0) {
            revert PoolNotFound();
        }
    }

    function _validateRequest(
        uint256 amountIn,
        uint256 deadline
    ) private view {
        _validateAmount(amountIn);

        if (deadline < block.timestamp) revert DeadlineInPast();
    }

    function _validateAmount(uint256 amount) private pure {
        if (amount == 0) revert ZeroAmount();

        if (amount > uint256(type(int256).max)) {
            revert AmountTooLarge();
        }
    }

    function _validateToken(address token) private view {
        if (
            token == NATIVE
                || token == address(this)
                || token.code.length == 0
        ) {
            revert InvalidToken(token);
        }
    }

    function _validatePair(
        address tokenIn,
        address tokenOut,
        uint24 fee
    ) private pure {
        if (
            tokenIn == NATIVE
                || tokenOut == NATIVE
                || tokenIn == tokenOut
                || fee >= 1_000_000
        ) {
            revert InvalidPath();
        }
    }

    /// @dev Validates the entire route and resolves all pools before
    ///      any input transfer or WETH deposit takes place.
    function _validateAndResolvePath(
        bytes calldata path
    )
        private
        view
        returns (
            address firstToken,
            address lastToken,
            address[] memory pools
        )
    {
        if (
            path.length < 43
                || (path.length - 20) % 23 != 0
        ) {
            revert InvalidPath();
        }

        uint256 hopCount = (path.length - 20) / 23;
        pools = new address[](hopCount);

        firstToken = _tokenAt(path, 0);
        _validateToken(firstToken);

        address currentToken = firstToken;

        for (uint256 i; i < hopCount; ++i) {
            uint256 offset = i * 23;
            address nextToken = _tokenAt(path, offset + 23);
            uint24 fee = _feeAt(path, offset + 20);

            _validateToken(nextToken);
            _validatePair(currentToken, nextToken, fee);

            pools[i] = _resolvePool(currentToken, nextToken, fee);
            currentToken = nextToken;
        }

        lastToken = currentToken;
    }

    function _requireMinimum(
        uint256 amount,
        uint256 minimum
    ) private pure {
        if (amount < minimum) {
            revert InsufficientOutput(amount, minimum);
        }
    }

    function _requireIncrease(
        address token,
        uint256 beforeBalance,
        uint256 afterBalance,
        uint256 expected
    ) private pure {
        if (
            afterBalance < beforeBalance
                || afterBalance - beforeBalance != expected
        ) {
            revert UnexpectedBalanceChange(token);
        }
    }

    function _requireDecrease(
        address token,
        uint256 beforeBalance,
        uint256 afterBalance,
        uint256 expected
    ) private pure {
        if (
            afterBalance > beforeBalance
                || beforeBalance - afterBalance != expected
        ) {
            revert UnexpectedBalanceChange(token);
        }
    }

    function _tokenAt(
        bytes calldata path,
        uint256 offset
    ) private pure returns (address) {
        return address(bytes20(path[offset:offset + 20]));
    }

    function _feeAt(
        bytes calldata path,
        uint256 offset
    ) private pure returns (uint24) {
        return uint24(bytes3(path[offset:offset + 3]));
    }
}

📚 Full Text Guide

(Following along with the video is much easier)

That's all there is to it!
Leave a like on the video if you enjoyed it and subscribe for more.