Skip to content
Verified contractExactGPL-2.0-or-later

Aggregator

Address0xb480bd00dae702b3122c182729ea57839b4bbe78
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 2,000 runs
EVM version
cancun
Via IR
yes
License
GPL-2.0-or-later
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,374,305
Creation transaction
0x2617413b4c…3c50d62aa6

105 files

The source code is large: one file is shown at a time. Choose a file in the list.

src/Aggregator.sol

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.26;

import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {ILockCallback} from "infinity-periphery/lib/infinity-core/src/interfaces/ILockCallback.sol";
import {IUnlockCallback} from "uniswap-v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {IWETH9} from "infinity-periphery/src/interfaces/external/IWETH9.sol";
import {ReentrancyLock} from "infinity-periphery/src/base/ReentrancyLock.sol";

import {NativeWrapper} from "./base/NativeWrapper.sol";
import {PausableOwner} from "./base/PausableOwner.sol";
import {FeeHelper} from "./libraries/FeeHelper.sol";
import {IAdapter} from "./interfaces/IAdapter.sol";
import {IUniV3StyledSwapCallback} from "./interfaces/IUniV3StyledSwapCallback.sol";
import {IAggregator} from "./interfaces/IAggregator.sol";
import {ISwapExecutor} from "./interfaces/ISwapExecutor.sol";
import {CommonUtils} from "./libraries/CommonUtils.sol";
import {PathRawDataHelper} from "./libraries/PathRawDataHelper.sol";
import {PathAdapterHelper} from "./libraries/PathAdapterHelper.sol";
import {Payment} from "./base/Payment.sol";

/// @dev UUPS upgradeable: deployed behind an ERC1967 proxy. The formerly-inlined adapters
///      (UniV2/PCSV2, UniV3-styled, Infinity, UniV4) now live in the SwapExecutor contract and are
///      reached via delegatecall — the combined bytecode no longer fits under the EIP-170 limit with
///      the upgradeability machinery included. Because it is delegatecall, everything still executes
///      in this contract's context: traders keep approving the proxy, the swap callbacks still hit
///      the proxy, and route calldata is byte-for-byte compatible with the non-upgradeable version.
///
///      Storage layout rules for future upgrades: the variables declared below occupy slots from 0
///      in declaration order and are APPEND-ONLY — never reorder, retype or delete them. Inherited
///      OZ upgradeable state (Ownable2Step, Pausable, Initializable) lives in ERC-7201 namespaced
///      slots and cannot collide. ReentrancyLock uses transient storage only.
contract Aggregator is IAggregator, Payment, NativeWrapper, PausableOwner, ReentrancyLock, UUPSUpgradeable {
    using CommonUtils for *;
    using PathRawDataHelper for uint256;
    using PathAdapterHelper for uint256;
    using FeeHelper for uint256;

    /// @notice emit event when a fee is charged
    /// @dev Carries only the protocol's share of the fee; a referral partner's share is reported
    ///      separately by PartnerFeeRecord. Not emitted at all when the protocol share is zero.
    event FeeRecord(address indexed token, uint256 feeAmount, address recipient);

    /// @notice emit event when a swap order is executed successfully
    /// @dev orderId is the caller-supplied id used to track the order. It is indexed so an order can
    ///      be looked up directly, and it lives here rather than in a separate early event so that a
    ///      transaction carrying several swaps pairs each id with its own result unambiguously.
    event OrderRecord(
        uint256 indexed orderId,
        address inputToken,
        address outputToken,
        address sender,
        uint256 inputAmount,
        uint256 outputAmount,
        address recipient
    );

    /// @notice emit event when an adapter is whitelisted / unwhitelisted
    event AdapterWhitelisted(address adapter, bool whitelisted);

    /// @notice emit event when the protocol fee receiver address is updated
    event FeeReceiverUpdated(address indexed newFeeReceiver);

    /// @notice emit event when a referral fee is paid out to a partner
    /// @dev feeAmount and surplusAmount are reported separately because the two are scaled by
    ///      independent rates; the partner receives them as a single transfer of the sum. `token` is
    ///      the swap's output token, carried here so payouts can be attributed without joining
    ///      against the OrderRecord of the same transaction.
    event PartnerFeeRecord(
        uint16 indexed partnerId,
        address indexed recipient,
        address indexed token,
        uint256 feeAmount,
        uint256 surplusAmount
    );

    /// @notice emit event when a partner is registered or updated
    event PartnerSet(uint16 indexed partnerId, address indexed recipient, uint16 feeShareBps, uint16 surplusBps);

    /// @notice emit event when a swap executed through `swapExactInWithSource` succeeds, recording
    ///         which entry point the trade was attributed to
    /// @dev Emitted after the swap, in the same transaction as the matching OrderRecord. orderId is
    ///      carried for the same reason as on OrderRecord: a transaction may hold several swaps and
    ///      the two events are joined on (txHash, orderId). `sender` is the attributed account the
    ///      backend signed for (defaults to msg.sender when the caller passed address(0)), which for
    ///      a contract integrator is the trader rather than the integrator. Multiple SourceRecords
    ///      with the same orderId across transactions indicate a replay (see
    ///      IAggregator.swapExactInWithSource) and should be deduplicated off-chain.
    event SourceRecord(uint256 indexed orderId, address indexed sender, uint32 indexed sourceId);

    /// @notice emit event when a source signer is enabled or disabled
    event SourceSignerSet(address indexed signer, bool enabled);

    /// @notice Thrown when the swap executor address passed to the constructor is zero
    error ZeroAddress();

    /// @notice Thrown when the fallback receives a selector that is not one of the SwapExecutor's
    ///         swap callbacks
    error UnknownCallback(bytes4 selector);

    /// @notice The delegatecall target hosting the formerly-inlined adapters and their callbacks.
    /// @dev Immutable in the implementation, so swapping the executor requires a UUPS upgrade to a
    ///      new implementation — deliberately the same authorization path as any other code change.
    address public immutable SWAP_EXECUTOR;

    /// @notice exteranl adapters are by default not allowed to be used in the aggregator unless whitelisted
    mapping(address => bool) public isAdapterWhitelisted;

    /// @notice Protocol-level fee receiver: receives all percentage fees and positive price-impact
    ///         surplus that is not split off to a referral partner. Must be set by the owner before
    ///         any fee-bearing swap is executed.
    address public feeReceiver;

    /// @notice Referral partner registry. partnerId 0 is permanently reserved to mean "no partner",
    ///         so it is never written and always reads as an unregistered entry.
    mapping(uint16 => Partner) public partners;

    /// @notice Backend keys allowed to sign source attributions for `swapExactInWithSource`.
    /// @dev Written only by the owner via batchSetSourceSigners; a single cold SLOAD on the swap
    ///      path. Appended after `partners` to keep the storage layout upgrade-safe.
    mapping(address => bool) public isSourceSigner;

    /// @notice EIP-712 type hash of the struct a source signer signs, see IAggregator.swapExactInWithSource
    bytes32 public constant SOURCE_TYPEHASH = keccak256("Source(uint32 sourceId,address sender,bytes32 paramsHash)");

    bytes32 private constant EIP712_DOMAIN_TYPEHASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
    bytes32 private constant EIP712_NAME_HASH = keccak256("PancakeSwapAggregator");
    bytes32 private constant EIP712_VERSION_HASH = keccak256("1");

    /// @dev WETH9 and SWAP_EXECUTOR are immutables baked into the implementation's code, which is
    ///      the standard (and gas-cheapest) way to carry per-chain constants in a UUPS setup.
    /// @custom:oz-upgrades-unsafe-allow constructor state-variable-immutable
    constructor(IWETH9 _weth9, address _swapExecutor) NativeWrapper(_weth9) {
        if (_swapExecutor == address(0)) revert ZeroAddress();
        SWAP_EXECUTOR = _swapExecutor;

        _disableInitializers();
    }

    /// @notice Forwarder for the swap callbacks whose implementations live in the SwapExecutor:
    ///         the PancakeSwap V3 / Uniswap V3-styled (incl. Aerodrome Slipstream) swap callbacks,
    ///         the Infinity Vault `lockAcquired` and the Uniswap V4 PoolManager `unlockCallback`.
    ///         Reached via delegatecall so the executor pays pools from this contract's
    ///         balance/approvals; msg.sender is preserved, so the executor's own guards (transient
    ///         pool address for V3, `onlyByVault`, `onlyByPoolManager`) apply exactly as when the
    ///         code was inlined. Any selector outside this whitelist reverts, matching the
    ///         previous behaviour where unknown calls found no function to land on. Plain ETH
    ///         transfers are unaffected: they go to NativeWrapper's `receive()`.
    /// @dev The selector whitelist is deliberately hardcoded: extending it requires a UUPS
    ///      upgrade, the same authorization path as changing SWAP_EXECUTOR itself. The executor's
    ///      return data is already ABI-encoded for the original caller (the pool/vault), so it is
    ///      bubbled up raw instead of a decode/re-encode round trip.
    fallback() external {
        bytes4 selector = msg.sig;
        if (
            selector != IUniV3StyledSwapCallback.pancakeV3SwapCallback.selector
                && selector != IUniV3StyledSwapCallback.uniswapV3SwapCallback.selector
                && selector != ILockCallback.lockAcquired.selector
                && selector != IUnlockCallback.unlockCallback.selector
        ) {
            revert UnknownCallback(selector);
        }

        bytes memory returnData = _delegateToExecutor(msg.data);
        assembly ("memory-safe") {
            return(add(returnData, 32), mload(returnData))
        }
    }

    /// @notice Initializes the proxy. Replaces the old constructor's `Ownable(msg.sender)` +
    ///         `feeReceiver = msg.sender` with explicit parameters, since under a proxy msg.sender
    ///         would be whatever deployed the proxy rather than the intended operator.
    function initialize(address initialOwner, address _feeReceiver) external initializer {
        __PausableOwner_init(initialOwner);
        __UUPSUpgradeable_init();

        if (_feeReceiver == address(0)) revert InvalidFeeReceiver();
        feeReceiver = _feeReceiver;
        emit FeeReceiverUpdated(_feeReceiver);
    }

    /// @dev UUPS upgrade authorization — owner only.
    function _authorizeUpgrade(address) internal override onlyOwner {}

    modifier checkDeadline(uint256 deadline) {
        if (block.timestamp > deadline) revert TransactionDeadlinePassed();
        _;
    }

    /// @inheritdoc IAggregator
    function swapWrap(uint256 orderId, uint256 amount, bool isWrap, uint256 feeConfig, address recipient)
        external
        payable
        isNotLocked
        whenNotPaused
        returns (uint256 outputAmtReceived)
    {
        if (recipient == address(0)) recipient = msg.sender;

        if (amount == 0) {
            revert ZeroAmount();
        }

        address inputToken;
        address outputToken;
        if (isWrap) {
            if (msg.value == 0) revert ZeroNativeToken();
            if (msg.value != amount) revert AmountMisMatch();

            inputToken = CommonUtils.ETH;
            outputToken = address(WETH9);

            _wrap(amount);
        } else {
            if (msg.value > 0) revert NonZeroNativeToken();

            inputToken = address(WETH9);
            outputToken = CommonUtils.ETH;

            _transferInternal(msg.sender, address(this), inputToken, amount);
            _unwrap(amount);
        }

        outputAmtReceived = amount;
        if (feeConfig != 0) {
            // swapWrap is a 1:1 conversion; only a percentage fee applies (no price-impact surplus).
            uint256 feeAmount = feeConfig.getFeeAmount(outputAmtReceived);
            outputAmtReceived -= feeAmount;
            _settleFee(outputToken, feeAmount, 0, feeConfig.getPartnerId());
        }
        _transferInternal(address(this), recipient, outputToken, outputAmtReceived);

        emit OrderRecord(orderId, inputToken, outputToken, msg.sender, amount, outputAmtReceived, recipient);
    }

    /// @inheritdoc IAggregator
    function swapExactIn(
        uint256 orderId,
        BaseExactInRequest calldata request,
        uint256[] calldata routesAmount,
        RouterPath[][] calldata routes,
        uint256 feeConfig,
        address recipient
    ) external payable returns (uint256 outputAmtReceived) {
        /// @dev Unspent input from a partially filled hop returns to the caller, which is the exact
        ///      behaviour this selector had before `refundTo` existed. For an EOA trader that is the
        ///      trader; for a contract integrator it is the integrator, so integrators swapping on
        ///      behalf of a user should call `swapExactInWithRefundTo` instead.
        return _swapExactIn(orderId, request, routesAmount, routes, feeConfig, recipient, msg.sender);
    }

    /// @inheritdoc IAggregator
    function swapExactInWithRefundTo(
        uint256 orderId,
        BaseExactInRequest calldata request,
        uint256[] calldata routesAmount,
        RouterPath[][] calldata routes,
        uint256 feeConfig,
        address recipient,
        address refundTo
    ) external payable returns (uint256 outputAmtReceived) {
        return _swapExactIn(
            orderId, request, routesAmount, routes, feeConfig, recipient, refundTo == address(0) ? msg.sender : refundTo
        );
    }

    /// @inheritdoc IAggregator
    function swapExactInWithSource(
        uint256 orderId,
        BaseExactInRequest calldata request,
        uint256[] calldata routesAmount,
        RouterPath[][] calldata routes,
        uint256 feeConfig,
        address recipient,
        address refundTo,
        bytes calldata sourceData
    ) external payable returns (uint256 outputAmtReceived) {
        /// @dev Hash the decoded values re-encoded canonically rather than a slice of msg.data: ABI
        ///      dynamic parameters are located via offsets, so a caller could craft a non-canonical
        ///      encoding where the hashed bytes match what was signed while the routes actually
        ///      decoded point elsewhere. abi.encode of the decoded values maps uniquely onto the
        ///      off-chain abi.encode the backend hashed. Raw recipient / refundTo are hashed, before
        ///      the address(0) -> msg.sender fallback, so the backend signs exactly what is sent.
        (uint32 sourceId, address sender) = _verifySource(
            keccak256(abi.encode(orderId, request, routesAmount, routes, feeConfig, recipient, refundTo)), sourceData
        );

        outputAmtReceived = _swapExactIn(
            orderId, request, routesAmount, routes, feeConfig, recipient, refundTo == address(0) ? msg.sender : refundTo
        );

        emit SourceRecord(orderId, sender, sourceId);
    }

    /// @notice Decode `sourceData` and check its signature against the enabled source signers.
    /// @dev Reverts rather than returning a flag: a source call with a bad signature must not fall
    ///      through to an unattributed swap, or integrators could never tell the two apart.
    /// @param paramsHash keccak256 of the canonically re-encoded swap parameters
    /// @param sourceData abi.encode(uint32 sourceId, address sender, bytes signature)
    /// @return sourceId The non-zero source identifier that was signed
    /// @return sender The attributed account that was signed: the caller-supplied value, or
    ///                msg.sender when that was address(0)
    function _verifySource(bytes32 paramsHash, bytes calldata sourceData)
        internal
        view
        returns (uint32 sourceId, address sender)
    {
        bytes memory signature;
        (sourceId, sender, signature) = abi.decode(sourceData, (uint32, address, bytes));
        if (sourceId == 0) revert InvalidSourceId();
        if (sender == address(0)) sender = msg.sender;

        bytes32 digest = MessageHashUtils.toTypedDataHash(
            DOMAIN_SEPARATOR(), keccak256(abi.encode(SOURCE_TYPEHASH, sourceId, sender, paramsHash))
        );
        // tryRecover rejects malformed lengths and high-s (malleable) signatures with a non-zero error
        (address signer, ECDSA.RecoverError err,) = ECDSA.tryRecover(digest, signature);
        if (err != ECDSA.RecoverError.NoError || !isSourceSigner[signer]) revert InvalidSourceSignature();
    }

    /// @notice EIP-712 domain separator for source signatures
    /// @dev Rebuilt on every call rather than cached: an immutable would be computed in the
    ///      implementation's constructor with address(this) == implementation, not the proxy, and
    ///      storage would need a reinitializer on upgrade. One keccak over five words costs less
    ///      than the SLOAD a cached value would need, and it follows a chain-id change for free.
    function DOMAIN_SEPARATOR() public view returns (bytes32) {
        return keccak256(
            abi.encode(EIP712_DOMAIN_TYPEHASH, EIP712_NAME_HASH, EIP712_VERSION_HASH, block.chainid, address(this))
        );
    }

    /// @notice Shared implementation behind `swapExactIn`, `swapExactInWithRefundTo` and
    ///         `swapExactInWithSource`.
    /// @dev Without the unreachable self-call at the top, the Yul optimizer inlines this whole body
    ///      into every external entrypoint that calls it (one copy each, ~3KB apiece at 2000 runs),
    ///      which is what pushed the implementation against the EIP-170 limit when the third
    ///      entrypoint was added. The inliner never inlines a function that calls itself, so the
    ///      dead branch keeps exactly one copy of the body behind a plain internal jump; the
    ///      condition cannot be proven false at compile time (calldata length) and can never be true
    ///      at run time (calldata is bounded by gas). It costs one comparison per swap.
    ///      testAggregator_ByteCodeSize catches it if a future compiler sees through the guard.
    /// @param refundTo Receives the unspent input of a partially filled hop. Already normalised by
    ///                 the calling entrypoint, so it is never address(0).
    function _swapExactIn(
        uint256 orderId,
        BaseExactInRequest calldata request,
        uint256[] calldata routesAmount,
        RouterPath[][] calldata routes,
        uint256 feeConfig,
        address recipient,
        address refundTo
    ) internal checkDeadline(request.deadline) isNotLocked whenNotPaused returns (uint256 outputAmtReceived) {
        // unreachable: see the @dev note above
        if (routesAmount.length == type(uint256).max) {
            return _swapExactIn(orderId, request, routesAmount, routes, feeConfig, recipient, refundTo);
        }

        if (recipient == address(0)) recipient = msg.sender;

        address inputToken = request.inputToken;
        address payer = inputToken == CommonUtils.ETH ? address(this) : msg.sender;
        uint256 totalInputTokenAmount;
        {
            if (inputToken == CommonUtils.ETH && msg.value == 0) {
                revert ZeroNativeToken();
            }

            if (inputToken != CommonUtils.ETH && msg.value > 0) {
                revert NonZeroNativeToken();
            }

            if (routesAmount.length != routes.length) revert RoutesLengthNotMatchRoutesAmountLength();

            /// @dev make sure inputToken always match the fromToken speicified in the route[*][0]
            uint256 amount;
            for (uint256 i = 0; i < routes.length; ++i) {
                totalInputTokenAmount += routesAmount[i];
                if (request.inputToken != routes[i][0].fromToken) {
                    if (inputToken.isETH() && routes[i][0].fromToken == address(WETH9)) {
                        amount += routesAmount[i];
                    } else if (inputToken == address(WETH9) && routes[i][0].fromToken.isETH()) {
                        amount += routesAmount[i];
                    } else {
                        revert InputTokenNotMatchRouteFromToken();
                    }
                }
            }

            if (inputToken.isETH() && msg.value != totalInputTokenAmount) {
                revert AmountMisMatch();
            }

            // in case more than one route requires wrap/unwrap, we batch it together
            if (amount > 0) {
                if (inputToken.isETH()) {
                    _wrap(amount);
                } else {
                    // means inputToken is WETH9 and routes[i].fromToken has .isETH()
                    _transferInternal(msg.sender, address(this), inputToken, totalInputTokenAmount);
                    _unwrap(amount);
                }
                payer = address(this);
            }
        }

        address outputToken = request.outputToken;
        // check the output token balance of the recipient before the swap
        uint256 initialUserOutputTokenBalance = outputToken.balanceOf(recipient);

        /// @dev check if we need to send the output token back to the aggregator contract, this can happen in 2 cases:
        ///   1. output token is ETH or WETH (wrap/unwrap might be needed)
        ///   2. feeConfig is not 0, which means we need to charge a fee
        bool sendOutputBackToAggregator = (outputToken.isETH() || outputToken == address(WETH9)) || feeConfig != 0;

        /// @notice execute each route in sequence (assume we have several routes)
        for (uint256 i = 0; i < routes.length; ++i) {
            _execExactInRoute(
                payer,
                sendOutputBackToAggregator ? address(this) : recipient, // recipient
                refundTo, // refundTo: where unspent hop input goes
                routesAmount[i], // input token amount
                routes[i] // hops
            );
        }

        /// @dev batch wrap/unwrap output token if necessary
        if (outputToken.isETH()) {
            _unwrapIfAny();
        } else if (outputToken == address(WETH9)) {
            _wrapIfAny();
        }

        if (sendOutputBackToAggregator) {
            /// @dev we can assure that all the output token has been sent back to this contract
            outputAmtReceived = outputToken.balanceOf(address(this));

            if (feeConfig != 0) {
                // Step 1: Capture positive price-impact surplus.
                // quotedAmount is encoded in bits 223-0 of feeConfig.
                // Surplus capture is only active when quotedAmount is strictly above the user's
                // slippage floor (request.minOutputAmount), ensuring it represents a meaningful
                // price-improvement rather than an arbitrary low value. When active and the actual
                // swap output exceeds quotedAmount, the difference represents favourable price
                // movement between quote time and on-chain execution. We cap the user-visible
                // output at quotedAmount; the excess becomes surplus, split in Step 3.
                uint256 surplus;
                uint256 quotedAmount = feeConfig.getQuotedAmount();
                if (quotedAmount > request.minOutputAmount && outputAmtReceived > quotedAmount) {
                    surplus = outputAmtReceived - quotedAmount;
                    // Cap user-visible output to what was quoted; the surplus is settled below
                    outputAmtReceived = quotedAmount;
                }

                // Step 2: Calculate the percentage-based fee on the (possibly capped) output.
                // feePercentage == 0 is permitted for surplus-only mode (no percentage fee charged).
                uint256 feeAmount = feeConfig.getFeeAmount(outputAmtReceived);
                outputAmtReceived -= feeAmount;

                // Step 3: Split the fee between the referral partner named by feeConfig (if any)
                // and the protocol feeReceiver, then pay both out. The two fee types are passed
                // separately because a partner is configured with an independent rate for each.
                _settleFee(outputToken, feeAmount, surplus, feeConfig.getPartnerId());
            }

            _transferInternal(address(this), recipient, outputToken, outputAmtReceived);
        } else {
            /// @dev output token is already with user, no need to transfer
        }

        // slippage check
        // Balance delta (not arithmetic) to support deflationary tokens; if a fee payout address is also
        // `recipient`, that fee is counted into this number - never use feeReceiver/partner.recipient as one.
        outputAmtReceived = outputToken.balanceOf(recipient) - initialUserOutputTokenBalance;
        if (outputAmtReceived < request.minOutputAmount) revert MinReturnNotReached();

        emit OrderRecord(
            orderId, inputToken, outputToken, msg.sender, totalInputTokenAmount, outputAmtReceived, recipient
        );
    }

    /// @notice This function manages a single swap route that might involve multiple hops through different liquidity pools or swapping protocols.
    /// @dev It iterates through the provided `hops`, executing each segment of the route in sequence.
    /// @param payer The address who will pay the input token for current hop, this will be updated after each hop
    /// @param recipient The address who will receive the output token of the last hop in the route
    /// @param refundTo The address who will receive the unspent input token when a hop is only partially filled
    /// @param curInputAmount The amount of input token to be used in the current route, this will be updated after each hop
    /// @param hops The detailed swap information for all hops in the route
    function _execExactInRoute(
        address payer,
        address recipient,
        address refundTo,
        uint256 curInputAmount,
        RouterPath[] calldata hops
    ) internal {
        address fromToken;
        bool tokenAlreadySentToNextHop;
        // by default we need to transfer the output token to the next hop as input
        // unless the current pool has already done that
        bool requireTransfer = true;

        uint256 ethBalanceBeforeHop;
        uint256 wethBalanceBeforeHop;

        uint256 hopLength = hops.length;
        for (uint256 i = 0; i < hopLength; ++i) {
            if (i > 0) {
                fromToken = hops[i].fromToken;

                // start from the second hop, we need to check if we need to wrap/unwrap the token
                // since the output token of the previous hop can contain both ETH and WETH
                // imagine we have forks in previous hop i.e. [30% usdc->weth, 70% usdc->eth]
                if (fromToken.isETH()) {
                    uint256 wethBalanceAfterHop = WETH9.balanceOf(address(this));
                    // if previous hop output: WETH and current hop input: ETH, convert WETH from previous hop output to ETH
                    if (wethBalanceAfterHop > wethBalanceBeforeHop) {
                        _unwrap(wethBalanceAfterHop - wethBalanceBeforeHop);
                    }
                    uint256 ethBalanceAfterHop = address(this).balance;
                    curInputAmount = ethBalanceAfterHop - ethBalanceBeforeHop;
                } else if (fromToken == address(WETH9)) {
                    uint256 ethBalanceAfterHop = address(this).balance;
                    // if previous hop output: ETH and current hop input: WETH, convert ETH from previous hop output to WETH
                    if (ethBalanceAfterHop > ethBalanceBeforeHop) _wrap(ethBalanceAfterHop - ethBalanceBeforeHop);
                    uint256 wethBalanceAfterHop = WETH9.balanceOf(address(this));
                    curInputAmount = wethBalanceAfterHop - wethBalanceBeforeHop;
                } else {
                    // previous hop output is not ETH/WETH, then we don't need to worry we will touch input token
                    // for other routes by mistake, as the input token won't be transferred ahead of time

                    curInputAmount = fromToken.balanceOf(address(this));
                }
                payer = address(this);
            }

            address to = address(this);
            if (i == hopLength - 1) {
                to = recipient;
            } else if (
                i < hopLength - 1 && hops[i + 1].assetTo.length == 1
                    && !(hops[i + 1].mixAdapters[0].shouldInputWrapped()
                        || hops[i + 1].mixAdapters[0].shouldInputUnwrapped())
            ) {
                // if next hop has only one fork and wrap/unwrap is not needed, send output to next hop directly to save one transfer
                to = hops[i + 1].assetTo[0];
                tokenAlreadySentToNextHop = true;
            } else {
                // if we have multiple forks in the next hop, we need to mannually split the output token
                // so we need to send the output token back to this contract first
                // address to = address(this);
                tokenAlreadySentToNextHop = false;
            }

            // if not the last hop, and next hop fromToken is ETH/WETH, record the current balance of ETH/WETH before next hop
            if (i < hopLength - 1 && (hops[i + 1].fromToken.isETH() || hops[i + 1].fromToken == address(WETH9))) {
                bool willTransferFromThisContract = payer == address(this) && requireTransfer;

                /// @dev in case input token is also output token here, we need to deduct the input token amount
                ethBalanceBeforeHop = address(this).balance
                    - (hops[i].fromToken.isETH() && willTransferFromThisContract ? curInputAmount : 0);
                wethBalanceBeforeHop = WETH9.balanceOf(address(this))
                    - (hops[i].fromToken == address(WETH9) && willTransferFromThisContract ? curInputAmount : 0);
            }
            // execute forks
            _execExactInHop(payer, to, refundTo, curInputAmount, hops[i], requireTransfer);
            requireTransfer = !tokenAlreadySentToNextHop;
        }
    }

    /// @notice Executes single hop in a route, however, input token could be further split into multiple forks.
    ///         It iterates through the provided `forks`, each fork represents a different liquidity pool or swapping protocol.
    ///         For example, a hop with 3 forks could be [30% fork1(UNIV2), 30% fork2(PCSV3), 40% fork3(PCSINFINITY)]
    /// @param payer The address who will pay the input token for current hop
    /// @param receiver The address who will receive the output token for current hop
    /// @param refundTo The address who will receive the unspent input token when a fork is only partially filled
    /// @param curInputAmount The amount of input token to be used in the current hop
    /// @param path The detailed swap information for all forks in the hop
    /// @param requireTransfer A boolean indicating whether the output token should be transferred to the address specified in the `assetTo` field
    function _execExactInHop(
        address payer,
        address receiver,
        address refundTo,
        uint256 curInputAmount,
        RouterPath calldata path,
        bool requireTransfer
    ) internal {
        address fromToken = path.fromToken;
        uint256 totalWeight;
        // execute multiple Adapters for a transaction pair
        uint256 pathLength = path.mixAdapters.length;
        uint256 alreadyUsedAmt = 0;
        for (uint256 i = 0; i < pathLength; ++i) {
            uint256 adapter = path.mixAdapters[i];

            (address poolAddress, uint256 weight, bool reverse) = path.rawData[i].decodePathRawData();
            totalWeight += weight;
            if (i == pathLength - 1) {
                if (totalWeight != 10_000) revert PathWeightInvalid();
            }

            /// @dev wrap/unwrap input token if necessary
            // This wrap/unwrap part is designed based on the consideration of those 4 cases:
            // 1. fromToken = eth, pool = weth -> X  :  wrap, transfer
            // 2. fromToken = weth, pool = eth -> X  :  transfer if first hop, wrap, transfer
            // 3. (no wrap/unwrap) fromToken = weth, pool = weth -> X :  transfer only
            // 4. (no wrap/unwrap) fromToken = eth, pool = eth -> X   :  transfer only
            uint256 _fromTokenAmount;
            if (i == pathLength - 1) {
                // fix the accumulated rounding error
                // Example scenario:
                // curInputAmount = 100
                // weights: [3333, 3333, 3334] (should total 10000)

                // First fork:  (100 * 3333) / 10000 = 33.33 -> 33
                // Second fork: (100 * 3333) / 10000 = 33.33 -> 33
                // Third fork:  (100 * 3334) / 10000 = 33.34 -> 33

                // this is to make sure that no token is left due to precision loss
                _fromTokenAmount = curInputAmount - alreadyUsedAmt;
            } else {
                _fromTokenAmount = weight == 10_000 ? curInputAmount : (curInputAmount * weight) / 10_000;
                alreadyUsedAmt += _fromTokenAmount;
            }

            if (adapter.shouldInputWrapped()) {
                // case 1
                _wrap(_fromTokenAmount);
                fromToken = address(WETH9);
                payer = address(this);
            } else if (adapter.shouldInputUnwrapped()) {
                // case 2
                if (payer != address(this)) {
                    // first hop of a route, weth from external payer
                    _transferInternal(payer, address(this), fromToken, _fromTokenAmount);
                }
                _unwrap(_fromTokenAmount);
                fromToken = CommonUtils.ETH;
                payer = address(this);
            }

            /// @dev these protocols used to be inlined; they now live in the SwapExecutor and are
            ///      reached via delegatecall so they still run in this contract's context (payer
            ///      approvals, ETH balance and swap callbacks all behave as before)
            if (adapter.isUniV2Adapter() || adapter.isPcsV2Adapter()) {
                if (requireTransfer) {
                    _transferInternal(payer, path.assetTo[i], fromToken, _fromTokenAmount);
                }

                // for uni/pcs v2, the executor applies a different fee ratio
                _delegateToExecutor(
                    abi.encodeCall(ISwapExecutor.uniV2Swap, (receiver, poolAddress, reverse, adapter.isPcsV2Adapter()))
                );
            } else if (adapter.isUniV3StyledAdapter()) {
                /// @dev path.extraData[i] equal to abi.encode(uint160 sqrtX96PriceLimit, address fromToken, address toToken, uint24 fee)
                _delegateToExecutor(
                    abi.encodeCall(
                        ISwapExecutor.uniV3Swap,
                        (_fromTokenAmount, payer, receiver, refundTo, poolAddress, path.extraData[i])
                    )
                );
            } else if (adapter.isInfinitySwapAdapter()) {
                _delegateToExecutor(
                    abi.encodeCall(
                        ISwapExecutor.infinitySwap,
                        (_fromTokenAmount, payer, receiver, refundTo, poolAddress, path.extraData[i])
                    )
                );
            } else if (adapter.isUniV4StyledAdapter()) {
                _delegateToExecutor(
                    abi.encodeCall(
                        ISwapExecutor.uniV4Swap, (_fromTokenAmount, payer, receiver, refundTo, path.extraData[i])
                    )
                );
            } else {
                address adapterAddress = adapter.bytes32ToAddress();
                if (!isAdapterWhitelisted[adapterAddress]) revert AdapterNotWhitelisted();

                // execute the swap through the external adapter
                if (requireTransfer) {
                    _transferInternal(payer, path.assetTo[i], fromToken, _fromTokenAmount);
                }

                /// @dev We keep the `reverse`-based selector split for adapter compatibility.
                ///      Some adapters (e.g. Balancer) encode tokenIn/tokenOut in `path.extraData[i]`, so both selectors
                ///      end up calling the same swap with the same params; others (e.g. Fluid-style) may use the selector
                ///      itself to indicate swap direction.
                if (reverse) {
                    IAdapter(adapterAddress).swapExactOneForZero(receiver, poolAddress, path.extraData[i]);
                } else {
                    IAdapter(adapterAddress).swapExactZeroForOne(receiver, poolAddress, path.extraData[i]);
                }
            }
        }
    }

    /// @dev Delegatecalls the SwapExecutor and bubbles up any revert unchanged, so errors from the
    ///      pools/adapters surface exactly as they did when the code was inlined.
    function _delegateToExecutor(bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returnData) = SWAP_EXECUTOR.delegatecall(data);
        if (!success) {
            assembly ("memory-safe") {
                revert(add(returnData, 32), mload(returnData))
            }
        }
        return returnData;
    }

    /// @notice Split the fee charged by a swap between a referral partner and the protocol, and pay
    ///         both out.
    /// @dev The two fee types are scaled by independent rates, so they are passed separately even
    ///      though the partner is paid in a single transfer. The protocol leg is computed as the
    ///      remainder rather than a second multiplication, so rounding dust always accrues to the
    ///      protocol and the two payouts sum to `percentageFee + surplus` exactly.
    ///
    ///      An unregistered or removed partnerId is deliberately not an error: the whole fee falls
    ///      through to feeReceiver. Reverting would brick in-flight swaps whenever a partner is
    ///      offboarded.
    /// @param token The token the fee is denominated in, i.e. the swap's output token
    /// @param percentageFee The percentage-based fee taken from the output amount
    /// @param surplus The captured positive price-impact surplus; 0 when there is none
    /// @param partnerId The referral partner from feeConfig; 0 means no partner
    function _settleFee(address token, uint256 percentageFee, uint256 surplus, uint16 partnerId) internal {
        uint256 totalFee = percentageFee + surplus;
        if (totalFee == 0) return;

        uint256 partnerFee;
        if (partnerId != 0) {
            Partner storage partner = partners[partnerId];
            if (partner.recipient != address(0)) {
                // Each leg rounds down independently, in the protocol's favour. Plain checked
                // arithmetic rather than FullMath: both shares are validated to be <= MAX_FEE on
                // write, so an intermediate overflow would need an amount above ~1.1e73, and it
                // would revert rather than wrap.
                uint256 partnerPercentageFee = (percentageFee * partner.feeShareBps) / FeeHelper.MAX_FEE;
                uint256 partnerSurplus = (surplus * partner.surplusBps) / FeeHelper.MAX_FEE;

                partnerFee = partnerPercentageFee + partnerSurplus;
                if (partnerFee > 0) {
                    // WARNING: if token is native ETH and recipient can't receive it, this reverts every such swap.
                    _transferInternal(address(this), partner.recipient, token, partnerFee);
                    emit PartnerFeeRecord(partnerId, partner.recipient, token, partnerPercentageFee, partnerSurplus);
                }
            }
        }

        uint256 protocolFee = totalFee - partnerFee;
        if (protocolFee > 0) {
            _transferInternal(address(this), feeReceiver, token, protocolFee);
            emit FeeRecord(token, protocolFee, feeReceiver);
        }
    }

    /// @inheritdoc IAggregator
    function batchSetPartners(uint16[] calldata partnerIds, Partner[] calldata infos) external onlyOwner {
        if (partnerIds.length != infos.length) revert BadParams();

        for (uint256 i = 0; i < partnerIds.length;) {
            _setPartner(partnerIds[i], infos[i].recipient, infos[i].feeShareBps, infos[i].surplusBps);
            unchecked {
                ++i;
            }
        }
    }

    /// @notice Validation and write behind `batchSetPartners`.
    /// @dev A zero `recipient` is the removal encoding: the slot is cleared, the id then reads as
    ///      unregistered, and swaps still naming it fall through to a 100% protocol fee. Removal is
    ///      idempotent — clearing an id that was never registered is a no-op.
    function _setPartner(uint16 partnerId, address recipient, uint16 feeShareBps, uint16 surplusBps) internal {
        // partnerId 0 is the "no partner" sentinel and must never resolve to a payout address.
        if (partnerId == 0) revert BadParams();

        if (recipient == address(0)) {
            delete partners[partnerId];
            // keep the log consistent with the cleared slot rather than echoing ignored bps
            feeShareBps = 0;
            surplusBps = 0;
        } else {
            // recipient == address(this) would make _transferInternal short-circuit on payer == to,
            // silently stranding the fee in this contract until it is swept.
            // ETH-receivability is not checkable here; see the warning in _settleFee.
            if (recipient == address(this) || feeShareBps > FeeHelper.MAX_FEE || surplusBps > FeeHelper.MAX_FEE) {
                revert BadParams();
            }

            partners[partnerId] = Partner(recipient, feeShareBps, surplusBps);
        }

        emit PartnerSet(partnerId, recipient, feeShareBps, surplusBps);
    }

    /// @inheritdoc IAggregator
    function whitelistAdapter(address adapter, bool whitelisted) external onlyOwner {
        isAdapterWhitelisted[adapter] = whitelisted;

        emit AdapterWhitelisted(adapter, whitelisted);
    }

    /// @inheritdoc IAggregator
    function batchSetSourceSigners(address[] calldata signers, bool[] calldata enabled) external onlyOwner {
        if (signers.length != enabled.length) revert BadParams();

        for (uint256 i = 0; i < signers.length;) {
            // Invariant: address(0) must never be an enabled signer. ECDSA.tryRecover happens to reject
            // a zero recovery today, but this check is what enforces the invariant here; do not remove it
            // or swap tryRecover for raw ecrecover without keeping it. Disabling address(0) stays allowed.
            if (enabled[i] && signers[i] == address(0)) revert ZeroAddress();
            isSourceSigner[signers[i]] = enabled[i];
            emit SourceSignerSet(signers[i], enabled[i]);
            unchecked {
                ++i;
            }
        }
    }

    /// @inheritdoc IAggregator
    function setFeeReceiver(address _feeReceiver) external onlyOwner {
        if (_feeReceiver == address(0)) revert InvalidFeeReceiver();
        feeReceiver = _feeReceiver;
        emit FeeReceiverUpdated(_feeReceiver);
    }

    /// @notice the aggregation contract is not expected to hold tokens
    ///         this function helps to rescue tokens left in the contract for any reasons
    function sweep(address token, address recipient, uint256 amountMinimum) external isNotLocked onlyOwner {
        uint256 balance = token.balanceOf(address(this));
        if (balance < amountMinimum) revert InsufficientToken();
        if (balance > 0) _transferInternal(address(this), recipient, token, balance);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 2000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "infinity-core/=lib/infinity-periphery/lib/infinity-core/",
    "uniswap-v4-core/=lib/v4-core/",
    "ds-test/=lib/infinity-periphery/lib/infinity-core/lib/forge-std/lib/ds-test/src/",
    "openzeppelin-contracts/=lib/infinity-periphery/lib/infinity-core/lib/openzeppelin-contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "solmate/=lib/infinity-periphery/lib/infinity-core/lib/solmate/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/infinity-periphery/lib/infinity-core/lib/forge-gas-snapshot/src/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/infinity-periphery/lib/infinity-core/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "infinity-periphery/=lib/infinity-periphery/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "pancake-create3-factory/=lib/infinity-periphery/lib/pancake-create3-factory/",
    "permit2/=lib/infinity-periphery/lib/permit2/",
    "v4-core/=lib/v4-core/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.