Перейти к содержимому
Проверенный контрактТочноеMIT

StatelessFeeRouter

Адрес0xbb87cedb7b1b47554baf0a82ee6c0769bf87bb8a
Баланс

0 ETH

 

Транзакций

1

 

Компилятор

solc 0.8.24

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.24+commit.e11b9ed9
Язык
solidity
Оптимизация
Да, 200 прогонов
Версия EVM
cancun
Через IR
да
Лицензия
MIT
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 460 530
Транзакция создания
0x2f5373a620…2886bcd02c

src/StatelessFeeRouter.sol

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

/// @title StatelessFeeRouter
/// @notice Minimal non-custodial fee router. Pulls the user's input, optionally
///         takes a *disclosed* fee from input or output, optionally splits any
///         output above a user-supplied quoted net (positive slippage) at a
///         disclosed share (default 50/50, capped at 50% to the operator),
///         forwards the rest to a target AMM router with user-supplied calldata,
///         and sends leftover output to the recipient. The user always receives
///         at least the quoted net plus their surplus share, and never less than
///         `minAmountOutNet`. There is no hidden spread: the quoted net is a
///         floor, not a padded midpoint.
/// @dev This contract is tested on a local anvil/Foundry fork of Base only.
///      It is not deployed to mainnet from this repository.
interface IERC20 {
    function balanceOf(address account) external view returns (uint256);
    function allowance(address owner, address spender) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

/// @dev Canonical Uniswap Permit2 (AllowanceTransfer). Same address on every chain it is deployed to.
interface IPermit2 {
    function approve(address token, address spender, uint160 amount, uint48 expiration) external;
    function allowance(address user, address token, address spender)
        external
        view
        returns (uint160 amount, uint48 expiration, uint48 nonce);
    function transferFrom(address from, address to, uint160 amount, address token) external;
}

interface IWETH {
    function deposit() external payable;
    function withdraw(uint256 amount) external;
    function transfer(address to, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
}

contract StatelessFeeRouter {
    address public immutable weth;

    /// @notice Hard cap on the disclosed swap fee: 1%. Helm's public tiers are 10/50/100 bps.
    uint16 public constant MAX_FEE_BPS = 100;
    /// @notice Hard cap on the operator's positive-slippage share, as a share of gross output: 1%.
    uint16 public constant MAX_SURPLUS_OF_GROSS_BPS = 100;
    /// @notice Isolated contract that performs the arbitrary `target` call. It never holds a user
    ///         approval, so swap calldata can never spend an allowance granted to this router.
    address public immutable executor;
    address public constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
    /// @notice Canonical Permit2. Only used by `swapExactInputViaPermit2`, for targets
    ///         (e.g. Uniswap's Universal Router for v4 swaps) that pull input via Permit2
    ///         rather than via a plain ERC-20 allowance.
    address public constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;

    error FeeTooHigh();
    error ReferrerShareTooHigh();
    error ZeroAmount();
    error CallFailed(bytes data);
    error InsufficientOutput();
    error BadTarget();
    error BadValue();
    error TransferFailed();
    error Reentrancy();
    error ZeroTreasury();
    error FeeTooLow();
    error TreasuryNotAllowed();
    error TargetNotAllowed();
    error SurplusShareTooHigh();
    error OrderExpired();
    error BadSignature();
    error OrderCancelled();
    error OrderAlreadyFilled();
    error SliceNotReady();
    error InvalidOrder();
    error NativeOrdersUnsupported();
    error Permit2AmountTooLarge();
    error SameAsset();
    error QuoteBelowMinimum();

    event SwapWithFee(
        address indexed user,
        address indexed tokenIn,
        address indexed tokenOut,
        uint256 amountIn,
        uint256 amountOutNet,
        uint256 feeAmount,
        uint16 feeBps,
        address treasury,
        address referrer,
        uint256 referrerShare
    );

    event SurplusShared(
        address indexed user,
        address indexed tokenOut,
        uint256 quotedOutNet,
        uint256 surplus,
        uint256 operatorShare,
        uint16 surplusShareBps
    );

    event OrderFilled(
        bytes32 indexed orderHash,
        address indexed maker,
        address indexed keeper,
        uint8 kind,
        uint16 sliceIndex,
        uint256 amountIn,
        uint256 amountOutNet,
        uint16 feeBps
    );

    event OrderNonceCancelled(address indexed maker, uint256 nonce);
    event OrdersCancelledUpTo(address indexed maker, uint256 minNonce);

    struct FeeParams {
        uint16 feeBps;
        bool feeFromInput;
        address treasury;
        address referrer;
        uint16 referrerShareBps; // share of the fee, 0–10000
        /// @notice Net output shown on the quote (after the disclosed swap fee).
        ///         If execution yields more, the extra is split. 0 disables sharing
        ///         (all extra goes to the user), matching the pre-surplus behavior.
        uint256 quotedOutNet;
        /// @notice Operator share of (amountOutNet - quotedOutNet), in bps. Capped at
        ///         MAX_SURPLUS_SHARE_BPS (5000 = 50%). 0 disables sharing.
        uint16 surplusShareBps;
    }

    /// @notice EIP-712 signed limit or DCA order. Funds stay in `maker` until a
    ///         keeper calls `fillSignedOrder`, which pulls via Permit2.
    struct SignedOrder {
        address maker;
        address tokenIn;
        address tokenOut;
        uint256 amountIn;
        uint256 minAmountOut;
        uint256 deadline;
        uint256 nonce;
        uint16 feeBps;
        address treasury;
        address referrer;
        uint16 referrerShareBps;
        uint16 surplusShareBps;
        uint8 kind; // 0 = limit (single fill), 1 = DCA
        uint16 slices;
        uint32 intervalSeconds;
    }

    uint16 public constant MAX_SURPLUS_SHARE_BPS = 5000;
    uint8 public constant ORDER_LIMIT = 0;
    uint8 public constant ORDER_DCA = 1;

    bytes32 public constant ORDER_TYPEHASH = keccak256(
        "SignedOrder(address maker,address tokenIn,address tokenOut,uint256 amountIn,uint256 minAmountOut,uint256 deadline,uint256 nonce,uint16 feeBps,address treasury,address referrer,uint16 referrerShareBps,uint16 surplusShareBps,uint8 kind,uint16 slices,uint32 intervalSeconds)"
    );
    bytes32 private constant _EIP712_DOMAIN_TYPEHASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
    bytes32 private constant _NAME_HASH = keccak256(bytes("StatelessFeeRouter"));
    bytes32 private constant _VERSION_HASH = keccak256(bytes("1"));

    mapping(address => mapping(uint256 => bool)) public nonceCancelled;
    mapping(address => uint256) public minNonce;
    mapping(bytes32 => uint16) public filledSlices;
    mapping(bytes32 => uint256) public lastFillTime;

    /// @notice Protocol floor on the disclosed swap fee. Set at deploy; there is no admin to change it.
    uint16 public immutable minFeeBps;
    /// @notice When true, `FeeParams.treasury` must be in the constructor allowlist. Immutable policy.
    bool public immutable treasuryAllowlistEnabled;
    /// @notice When true, the AMM `target` must be in the constructor venue allowlist. Immutable policy.
    ///         An empty venue list leaves the existing denylist-only behavior (any target except the
    ///         router, executor, tokens, WETH, and Permit2).
    bool public immutable venueAllowlistEnabled;
    mapping(address => bool) public allowedTreasury;
    mapping(address => bool) public allowedVenue;

    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;
    uint256 private _status = _NOT_ENTERED;

    /// @param _minFeeBps Inclusive floor on `feeBps` (0 keeps the v1.3 "fee optional" behavior).
    /// @param _treasuries If non-empty, only these addresses may receive the disclosed fee / surplus.
    /// @param _venues If non-empty, only these AMM routers may be used as `target`.
    constructor(address _weth, uint16 _minFeeBps, address[] memory _treasuries, address[] memory _venues) {
        require(_weth != address(0), "weth");
        if (_minFeeBps > MAX_FEE_BPS) revert FeeTooHigh();
        if (_minFeeBps > 0 && _treasuries.length == 0) revert ZeroTreasury();
        weth = _weth;
        minFeeBps = _minFeeBps;
        treasuryAllowlistEnabled = _treasuries.length > 0;
        venueAllowlistEnabled = _venues.length > 0;
        uint256 i;
        for (i = 0; i < _treasuries.length; i++) {
            address t = _treasuries[i];
            if (t == address(0)) revert ZeroTreasury();
            allowedTreasury[t] = true;
        }
        for (i = 0; i < _venues.length; i++) {
            address v = _venues[i];
            if (v == address(0) || v == address(this) || v == PERMIT2) revert BadTarget();
            allowedVenue[v] = true;
        }
        executor = address(new HelmSwapExecutor(_weth));
        // Re-check treasuries against the now-known executor (cannot be a fee sink).
        for (i = 0; i < _treasuries.length; i++) {
            if (_treasuries[i] == address(this) || _treasuries[i] == executor) revert BadTarget();
        }
    }

    /// @notice Build identifier, readable on-chain for the deploy page's verification step.
    function version() external pure returns (string memory) {
        return "helm-stateless-fee-router-1.4-sec";
    }

    modifier nonReentrant() {
        if (_status == _ENTERED) revert Reentrancy();
        _status = _ENTERED;
        _;
        _status = _NOT_ENTERED;
    }

    receive() external payable {}

    /// @notice Swap through `target`, which pulls input from this contract with a plain
    ///         ERC-20 allowance (exact amount, reset to zero after the call).
    function swapExactInput(
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOutNet,
        address target,
        bytes calldata data,
        address recipient,
        FeeParams calldata fee
    ) external payable nonReentrant returns (uint256 amountOutNet) {
        return _swap(tokenIn, tokenOut, amountIn, minAmountOutNet, target, data, recipient, fee, false, msg.sender, false);
    }

    /// @notice Same as `swapExactInput`, but `target` pulls input through Permit2
    ///         (Universal Router `V4_SWAP` / `INFI_SWAP` / `PERMIT2_TRANSFER_FROM`). This contract grants
    ///         the canonical Uniswap Permit2 an exact ERC-20 allowance and `target` an exact Permit2
    ///         allowance that expires this block, then zeroes BOTH after the call. Still one target call.
    function swapExactInputViaPermit2(
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOutNet,
        address target,
        bytes calldata data,
        address recipient,
        FeeParams calldata fee
    ) external payable nonReentrant returns (uint256 amountOutNet) {
        return _swapMem(tokenIn, tokenOut, amountIn, minAmountOutNet, target, data, recipient, fee, true, msg.sender, false, PERMIT2);
    }

    /// @notice Same as `swapExactInputViaPermit2`, but grants the exact allowance on `permit2`
    ///         instead of the canonical Uniswap Permit2. Use this when the target (e.g.
    ///         PancakeSwap Infinity Universal Router) is wired to a different Permit2.
    ///         Exact approve → zero on both the ERC-20 allowance to `permit2` and the
    ///         Permit2 allowance to `target`. Still one target call. No custody after return.
    function swapExactInputViaPermit2At(
        address permit2,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOutNet,
        address target,
        bytes calldata data,
        address recipient,
        FeeParams calldata fee
    ) external payable nonReentrant returns (uint256 amountOutNet) {
        if (permit2 == address(0) || permit2 == address(this)) revert BadTarget();
        return _swapMem(tokenIn, tokenOut, amountIn, minAmountOutNet, target, data, recipient, fee, true, msg.sender, false, permit2);
    }


    /// @notice Cancel a single order nonce. Only the maker can call. Takes effect immediately.
    function cancelNonce(uint256 nonce) external {
        nonceCancelled[msg.sender][nonce] = true;
        emit OrderNonceCancelled(msg.sender, nonce);
    }

    /// @notice Cancel every order with `nonce < minNonce_`. Only the maker can call.
    function cancelUpTo(uint256 minNonce_) external {
        if (minNonce_ <= minNonce[msg.sender]) revert InvalidOrder();
        minNonce[msg.sender] = minNonce_;
        emit OrdersCancelledUpTo(msg.sender, minNonce_);
    }

    function isNonceLive(address maker, uint256 nonce) public view returns (bool) {
        return nonce >= minNonce[maker] && !nonceCancelled[maker][nonce];
    }

    function domainSeparator() public view returns (bytes32) {
        return keccak256(abi.encode(_EIP712_DOMAIN_TYPEHASH, _NAME_HASH, _VERSION_HASH, block.chainid, address(this)));
    }

    function hashOrder(SignedOrder calldata order) public view returns (bytes32) {
        return keccak256(
            abi.encodePacked(
                "\x19\x01",
                domainSeparator(),
                keccak256(
                    abi.encode(
                        ORDER_TYPEHASH,
                        order.maker,
                        order.tokenIn,
                        order.tokenOut,
                        order.amountIn,
                        order.minAmountOut,
                        order.deadline,
                        order.nonce,
                        order.feeBps,
                        order.treasury,
                        order.referrer,
                        order.referrerShareBps,
                        order.surplusShareBps,
                        order.kind,
                        order.slices,
                        order.intervalSeconds
                    )
                )
            )
        );
    }

    /// @notice Keeper fill of a user-signed limit or DCA order. Pulls `amountIn` (or one
    ///         DCA slice) from the maker via Permit2, swaps through `target`, and sends
    ///         the net output to the maker. The maker's funds never sit here between fills.
    ///         Surplus sharing is forced to 0 on keeper fills (`quotedOutNet` and
    ///         `surplusShareBps` are ignored) so any output above the signed minimum goes
    ///         to the maker; a keeper cannot skim filler surplus. Route-internal MEV
    ///         (the AMM itself skimming inside `data`) cannot be closed on-chain without
    ///         an oracle or breaking permissionless fills — operators must review venues.
    ///         Never broadcasts itself; the keeper submits this call. Not deployed from this repo.
    function fillSignedOrder(
        SignedOrder calldata order,
        bytes calldata signature,
        address target,
        bytes calldata data,
        bool viaPermit2
    ) external nonReentrant returns (uint256 amountOutNet) {
        if (block.timestamp > order.deadline) revert OrderExpired();
        if (order.maker == address(0) || order.amountIn == 0) revert InvalidOrder();
        if (_isNative(order.tokenIn) || _isNative(order.tokenOut)) revert NativeOrdersUnsupported();
        if (order.feeBps > MAX_FEE_BPS) revert FeeTooHigh();
        if (order.feeBps < minFeeBps) revert FeeTooLow();
        if (treasuryAllowlistEnabled && order.feeBps > 0 && !allowedTreasury[order.treasury]) revert TreasuryNotAllowed();
        if (venueAllowlistEnabled && !allowedVenue[target]) revert TargetNotAllowed();
        if (order.referrerShareBps > 10_000) revert ReferrerShareTooHigh();
        if (order.surplusShareBps > MAX_SURPLUS_SHARE_BPS) revert SurplusShareTooHigh();
        if (!isNonceLive(order.maker, order.nonce)) revert OrderCancelled();
        if (order.kind != ORDER_LIMIT && order.kind != ORDER_DCA) revert InvalidOrder();
        uint16 slices = order.kind == ORDER_DCA ? order.slices : 1;
        if (slices == 0) revert InvalidOrder();

        bytes32 orderHash = hashOrder(order);
        if (!_isValidSignature(order.maker, orderHash, signature)) revert BadSignature();

        uint16 sliceIndex = filledSlices[orderHash];
        if (sliceIndex >= slices) revert OrderAlreadyFilled();
        if (sliceIndex > 0 && order.intervalSeconds > 0) {
            if (block.timestamp < lastFillTime[orderHash] + uint256(order.intervalSeconds)) revert SliceNotReady();
        }

        (uint256 sliceIn, uint256 sliceMinOut) = _dcaSlice(order.amountIn, order.minAmountOut, slices, sliceIndex);

        // Effects before interactions (state is rolled back if anything below reverts).
        filledSlices[orderHash] = sliceIndex + 1;
        lastFillTime[orderHash] = block.timestamp;
        if (sliceIndex + 1 >= slices) {
            nonceCancelled[order.maker][order.nonce] = true;
        }

        if (sliceIn > type(uint160).max) revert Permit2AmountTooLarge();
        IPermit2(PERMIT2).transferFrom(order.maker, address(this), uint160(sliceIn), order.tokenIn);

        FeeParams memory fee = FeeParams({
            feeBps: order.feeBps,
            feeFromInput: false,
            treasury: order.treasury,
            referrer: order.referrer,
            referrerShareBps: order.referrerShareBps,
            quotedOutNet: 0,
            surplusShareBps: 0
        });

        // _swap expects FeeParams calldata; copy to a temporary by calling through an internal
        // helper that takes memory. See _swapFromBalance.
        amountOutNet = _swapFromBalance(
            order.tokenIn,
            order.tokenOut,
            sliceIn,
            sliceMinOut,
            target,
            data,
            order.maker,
            fee,
            viaPermit2,
            order.maker
        );

        emit OrderFilled(orderHash, order.maker, msg.sender, order.kind, sliceIndex, sliceIn, amountOutNet, order.feeBps);
    }

    function _dcaSlice(uint256 amountIn, uint256 minAmountOut, uint16 slices, uint16 idx)
        internal
        pure
        returns (uint256 sliceIn, uint256 sliceMin)
    {
        sliceIn = amountIn / uint256(slices);
        sliceMin = minAmountOut / uint256(slices);
        if (idx == slices - 1) {
            sliceIn = amountIn - sliceIn * (uint256(slices) - 1);
            sliceMin = minAmountOut - sliceMin * (uint256(slices) - 1);
        }
    }

    function _isValidSignature(address maker, bytes32 orderHash, bytes calldata signature) internal view returns (bool) {
        if (signature.length != 65) return false;
        bytes32 r;
        bytes32 s;
        uint8 v;
        assembly {
            r := calldataload(signature.offset)
            s := calldataload(add(signature.offset, 32))
            v := byte(0, calldataload(add(signature.offset, 64)))
        }
        if (v < 27) v += 27;
        if (v != 27 && v != 28) return false;
        address recovered = ecrecover(orderHash, v, r, s);
        return recovered != address(0) && recovered == maker;
    }

    /// @dev Memory-params wrapper so `fillSignedOrder` can build FeeParams in memory.
    function _swapFromBalance(
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOutNet,
        address target,
        bytes calldata data,
        address recipient,
        FeeParams memory fee,
        bool viaPermit2,
        address payer
    ) internal returns (uint256) {
        return _swapMem(tokenIn, tokenOut, amountIn, minAmountOutNet, target, data, recipient, fee, viaPermit2, payer, true, PERMIT2);
    }

    /// @dev External-style calldata wrapper is used by the public swap functions; this copy
    ///      exists because Solidity cannot pass memory FeeParams as calldata. The body is the
    ///      same as `_swap` and is kept in sync (see AUDIT.md). To avoid duplication, `_swap`
    ///      just forwards to `_swapMem`.

    function _swap(
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOutNet,
        address target,
        bytes calldata data,
        address recipient,
        FeeParams calldata fee,
        bool viaPermit2,
        address payer,
        bool alreadyFunded
    ) internal returns (uint256 amountOutNet) {
        return _swapMem(tokenIn, tokenOut, amountIn, minAmountOutNet, target, data, recipient, fee, viaPermit2, payer, alreadyFunded, PERMIT2);
    }

    function _swapMem(
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOutNet,
        address target,
        bytes calldata data,
        address recipient,
        FeeParams memory fee,
        bool viaPermit2,
        address payer,
        bool alreadyFunded,
        address permit2Used
    ) internal returns (uint256 amountOutNet) {
        if (amountIn == 0) revert ZeroAmount();
        if (fee.feeBps > MAX_FEE_BPS) revert FeeTooHigh();
        if (fee.feeBps < minFeeBps) revert FeeTooLow();
        if (fee.referrerShareBps > 10_000) revert ReferrerShareTooHigh();
        if (fee.surplusShareBps > MAX_SURPLUS_SHARE_BPS) revert SurplusShareTooHigh();
        if (treasuryAllowlistEnabled && fee.feeBps > 0 && !allowedTreasury[fee.treasury]) revert TreasuryNotAllowed();
        if (venueAllowlistEnabled && !allowedVenue[target]) revert TargetNotAllowed();
        if (target == address(0) || target == address(this) || target == PERMIT2 || target == permit2Used) revert BadTarget();
        // The target must be an AMM/router, never one of the tokens being moved: a call
        // like token.approve(x) from this contract would otherwise leave a residual allowance.
        if (target == tokenIn || target == tokenOut || target == weth) revert BadTarget();
        if (recipient == address(0)) revert BadTarget();
        // Funds sent to the router/executor would be swept by the next caller.
        if (
            recipient == address(this) || recipient == executor || fee.treasury == address(this)
                || fee.treasury == executor || fee.referrer == address(this) || fee.referrer == executor
        ) revert BadTarget();
        if (fee.feeBps > 0 && fee.treasury == address(0)) revert ZeroTreasury();
        if (target == executor) revert BadTarget();
        if ((_isNative(tokenIn) ? weth : tokenIn) == (_isNative(tokenOut) ? weth : tokenOut)) revert SameAsset();
        // A positive-slippage split is only valid against a real quote at or above the user's floor.
        if (fee.surplusShareBps > 0 && fee.quotedOutNet > 0 && fee.quotedOutNet < minAmountOutNet) {
            revert QuoteBelowMinimum();
        }

        bool inNative = _isNative(tokenIn);
        if (inNative) {
            if (msg.value != amountIn) revert BadValue();
        } else if (msg.value != 0) {
            revert BadValue();
        }

        uint256 swapAmount = amountIn;
        uint256 inputFee = 0;
        if (fee.feeFromInput && fee.feeBps > 0) {
            inputFee = (amountIn * fee.feeBps) / 10_000;
            swapAmount = amountIn - inputFee;
            _payFee(tokenIn, inputFee, fee, alreadyFunded ? address(this) : payer);
        }

        // Take custody of the swap amount (not the input fee, already paid).
        // For fee-on-transfer tokens, use the amount actually received.
        address spendToken = inNative ? weth : tokenIn;
        uint256 pulled;
        if (inNative) {
            if (alreadyFunded) revert InvalidOrder();
            IWETH(weth).deposit{value: swapAmount}();
            pulled = swapAmount;
            // Target is called with no msg.value; native input is swapped as WETH.
        } else if (alreadyFunded) {
            pulled = IERC20(tokenIn).balanceOf(address(this));
            if (pulled == 0) revert ZeroAmount();
            if (pulled < swapAmount) swapAmount = pulled;
        } else {
            uint256 beforeIn = IERC20(tokenIn).balanceOf(address(this));
            _safeTransferFrom(tokenIn, payer, address(this), swapAmount);
            pulled = IERC20(tokenIn).balanceOf(address(this)) - beforeIn;
            if (pulled == 0) revert ZeroAmount();
            swapAmount = pulled;
        }

        if (viaPermit2) {
            if (permit2Used == address(0) || permit2Used == address(this)) revert BadTarget();
            if (swapAmount > type(uint160).max) revert BadValue();
        }

        // The router never calls `target` itself. It hands the exact swap amount to the isolated
        // executor, which approves (ERC-20 or Permit2) exactly that amount, calls `target`, zeroes
        // the approvals and returns all leftover input and any output it received, in this call.
        uint256 outBefore = _balance(tokenOut, address(this));
        _safeTransfer(spendToken, executor, swapAmount);
        HelmSwapExecutor(payable(executor)).execute(spendToken, tokenOut, target, data, viaPermit2 ? permit2Used : address(0));
        uint256 received = _balance(tokenOut, address(this)) - outBefore;

        uint256 outputFee = 0;
        amountOutNet = received;
        if (!fee.feeFromInput && fee.feeBps > 0) {
            outputFee = (received * fee.feeBps) / 10_000;
            amountOutNet = received - outputFee;
            _payFee(tokenOut, outputFee, fee, address(this));
        }

        if (amountOutNet < minAmountOutNet) revert InsufficientOutput();

        // Disclosed positive-slippage split. Disabled when surplusShareBps or quotedOutNet is 0.
        // The user always keeps at least max(minAmountOutNet, quotedOutNet + their share).
        uint256 operatorSurplus = 0;
        if (fee.surplusShareBps > 0 && fee.quotedOutNet > 0 && amountOutNet > fee.quotedOutNet) {
            uint256 surplus = amountOutNet - fee.quotedOutNet;
            operatorSurplus = (surplus * fee.surplusShareBps) / 10_000;
            uint256 surplusCap = (received * MAX_SURPLUS_OF_GROSS_BPS) / 10_000;
            if (operatorSurplus > surplusCap) operatorSurplus = surplusCap;
            uint256 userAmount = amountOutNet - operatorSurplus;
            if (userAmount < minAmountOutNet) {
                userAmount = minAmountOutNet;
                operatorSurplus = amountOutNet - userAmount;
            }
            if (operatorSurplus > 0) {
                if (fee.treasury == address(0)) revert ZeroTreasury();
                _push(tokenOut, fee.treasury, operatorSurplus);
                emit SurplusShared(
                    payer,
                    tokenOut,
                    fee.quotedOutNet,
                    surplus,
                    operatorSurplus,
                    fee.surplusShareBps
                );
            }
            amountOutNet = userAmount;
        }

        if (amountOutNet > 0) {
            if (_isNative(tokenOut)) {
                _push(tokenOut, recipient, amountOutNet);
            } else {
                // Enforce the floor on what the recipient actually receives, so fee-on-transfer
                // and rebasing output tokens fail closed instead of under-delivering.
                uint256 recBefore = IERC20(tokenOut).balanceOf(recipient);
                _push(tokenOut, recipient, amountOutNet);
                uint256 recAfter = IERC20(tokenOut).balanceOf(recipient);
                if (recAfter < recBefore || recAfter - recBefore < minAmountOutNet) revert InsufficientOutput();
            }
        }

        // Any leftover input (refunds from the AMM) goes back to the payer, never the treasury.
        // Native input: refunds may come back as WETH or as native ETH; both return to the payer.
        uint256 leftoverIn = inNative ? _balance(NATIVE, address(this)) : _balance(spendToken, address(this));
        if (leftoverIn > 0) {
            _push(inNative ? NATIVE : tokenIn, payer, leftoverIn);
        }

        emit SwapWithFee(
            payer,
            tokenIn,
            tokenOut,
            amountIn,
            amountOutNet,
            fee.feeFromInput ? inputFee : outputFee,
            fee.feeBps,
            fee.treasury,
            fee.referrer,
            fee.referrerShareBps
        );
    }

    function _payFee(address token, uint256 amount, FeeParams memory fee, address from) internal {
        if (amount == 0) return;
        uint256 referrerAmt = 0;
        if (fee.referrer != address(0) && fee.referrerShareBps > 0) {
            referrerAmt = (amount * fee.referrerShareBps) / 10_000;
        }
        uint256 treasuryAmt = amount - referrerAmt;
        if (referrerAmt > 0) {
            if (_isNative(token)) _payReferrerNative(fee.referrer, referrerAmt);
            else if (from == address(this)) _push(token, fee.referrer, referrerAmt);
            else _pullAndPush(token, from, fee.referrer, referrerAmt);
        }
        if (treasuryAmt > 0) {
            if (from == address(this)) _push(token, fee.treasury, treasuryAmt);
            else _pullAndPush(token, from, fee.treasury, treasuryAmt);
        }
    }

    /// @dev Audit 2026-11-18: a referrer is chosen by whoever shares the link, so it may be a contract
    ///      that reverts or burns gas on receive. Native shares get a bounded gas stipend; if the
    ///      call fails the share is paid as WETH instead (no callback), so the user's swap never
    ///      fails or overpays gas because of the referrer.
    uint256 internal constant REFERRER_GAS_STIPEND = 30_000;
    function _payReferrerNative(address to, uint256 amount) internal {
        uint256 ethBal = address(this).balance;
        if (ethBal < amount) IWETH(weth).withdraw(amount - ethBal);
        bool ok;
        // No returndata copy (a referrer cannot return-bomb the caller).
        assembly ("memory-safe") {
            ok := call(REFERRER_GAS_STIPEND, to, amount, 0, 0, 0, 0)
        }
        if (!ok) {
            IWETH(weth).deposit{value: amount}();
            if (!IWETH(weth).transfer(to, amount)) revert TransferFailed();
        }
    }

    function _pullAndPush(address token, address from, address to, uint256 amount) internal {
        if (_isNative(token)) {
            (bool ok,) = to.call{value: amount}("");
            if (!ok) revert TransferFailed();
        } else {
            _safeTransferFrom(token, from, to, amount);
        }
    }

    function _push(address token, address to, uint256 amount) internal {
        if (_isNative(token)) {
            uint256 ethBal = address(this).balance;
            if (ethBal < amount) {
                // Leftover may be WETH: unwrap only the shortfall, then send ETH.
                IWETH(weth).withdraw(amount - ethBal);
            }
            (bool ok,) = to.call{value: amount}("");
            if (!ok) revert TransferFailed();
        } else if (token == weth && to == address(0)) {
            revert BadTarget();
        } else {
            _safeTransfer(token, to, amount);
        }
    }

    function _balance(address token, address who) internal view returns (uint256) {
        if (_isNative(token)) {
            return address(this).balance + IWETH(weth).balanceOf(who);
        }
        return IERC20(token).balanceOf(who);
    }

    function _isNative(address token) internal pure returns (bool) {
        return token == NATIVE || token == address(0);
    }

    function _approveExact(address token, address spender, uint256 amount) internal {
        // Always reset first: some ERC-20s (USDT-style) reject changing a non-zero allowance.
        uint256 current = IERC20(token).allowance(address(this), spender);
        if (current != 0) {
            _safeApprove(token, spender, 0);
        }
        if (amount != 0) {
            _safeApprove(token, spender, amount);
        }
    }

    function _safeTransfer(address token, address to, uint256 amount) internal {
        (bool ok, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, amount));
        if (!ok || (data.length != 0 && !abi.decode(data, (bool)))) revert TransferFailed();
    }

    function _safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        (bool ok, bytes memory data) =
            token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, amount));
        if (!ok || (data.length != 0 && !abi.decode(data, (bool)))) revert TransferFailed();
    }

    function _safeApprove(address token, address spender, uint256 amount) internal {
        (bool ok, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, spender, amount));
        if (!ok || (data.length != 0 && !abi.decode(data, (bool)))) revert TransferFailed();
    }
}

/// @title HelmSwapExecutor
/// @notice Created by StatelessFeeRouter in its constructor; only that router can call it. Users
///         never approve this contract, so the caller-chosen `target` call below cannot reach any
///         user's allowance. Holds funds only inside one router call and sends everything back
///         before returning. No owner, no upgrade, no admin functions.
contract HelmSwapExecutor {
    address public immutable router;
    address public immutable weth;
    address internal constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
    address internal constant CANONICAL_PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;

    error OnlyRouter();
    error BadTarget();
    error BadValue();
    error CallFailed(bytes data);
    error TransferFailed();

    constructor(address _weth) {
        router = msg.sender;
        weth = _weth;
    }

    /// @dev Targets may pay native output (e.g. unwrapWETH9 to msg.sender); forwarded below.
    receive() external payable {}

    function execute(address spendToken, address tokenOut, address target, bytes calldata data, address permit2)
        external
    {
        if (msg.sender != router) revert OnlyRouter();
        if (
            target == address(0) || target == address(this) || target == router || target == spendToken
                || target == tokenOut || target == weth || target == CANONICAL_PERMIT2
                || (permit2 != address(0) && target == permit2)
        ) revert BadTarget();

        if (_isApprovalSelector(data)) revert BadTarget();

        uint256 amount = IERC20(spendToken).balanceOf(address(this));
        if (permit2 != address(0)) {
            if (amount > type(uint160).max) revert BadValue();
            _approveExact(spendToken, permit2, amount);
            // Expires at the end of this block; zeroed below regardless.
            IPermit2(permit2).approve(spendToken, target, uint160(amount), uint48(block.timestamp));
        } else {
            _approveExact(spendToken, target, amount);
        }

        (bool ok, bytes memory ret) = target.call(data);
        if (!ok) revert CallFailed(ret);

        if (permit2 != address(0)) {
            IPermit2(permit2).approve(spendToken, target, 0, 0);
            _approveExact(spendToken, permit2, 0);
        } else {
            _approveExact(spendToken, target, 0);
        }

        // Everything goes back to the router: unspent input, and output paid to this contract.
        _sweep(spendToken);
        if (tokenOut == NATIVE || tokenOut == address(0)) {
            _sweep(weth);
        } else {
            _sweep(tokenOut);
        }
        uint256 eth = address(this).balance;
        if (eth > 0) {
            (bool sent,) = router.call{value: eth}("");
            if (!sent) revert TransferFailed();
        }
    }

    /// @dev Security fix HS-C-01 (2026-11-20): the caller-chosen target call must never make this executor
    ///      grant a standing allowance (ERC-20/721 approve, increaseAllowance, setApprovalForAll, or a Permit2
    ///      allowance on any Permit2 deployment). Such allowances outlive the swap and let the grantee pull
    ///      whatever the executor holds in a later user's swap.
    function _isApprovalSelector(bytes calldata data) internal pure returns (bool) {
        if (data.length < 4) return false;
        bytes4 s = bytes4(data[:4]);
        return s == 0x095ea7b3 // approve(address,uint256)
            || s == 0x39509351 // increaseAllowance(address,uint256)
            || s == 0xd73dd623 // increaseApproval(address,uint256)
            || s == 0xa22cb465 // setApprovalForAll(address,bool)
            || s == 0x87517c45 // Permit2 approve(address,address,uint160,uint48)
            || s == 0x2b67b570 // Permit2 permit(single)
            || s == 0x2a2d80d1; // Permit2 permit(batch)
    }

    function _sweep(address token) internal {
        uint256 bal = IERC20(token).balanceOf(address(this));
        if (bal == 0) return;
        (bool ok, bytes memory d) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, router, bal));
        if (!ok || (d.length != 0 && !abi.decode(d, (bool)))) revert TransferFailed();
    }

    function _approveExact(address token, address spender, uint256 amount) internal {
        if (IERC20(token).allowance(address(this), spender) != 0) _approve(token, spender, 0);
        if (amount != 0) _approve(token, spender, amount);
    }

    function _approve(address token, address spender, uint256 amount) internal {
        (bool ok, bytes memory d) = token.call(abi.encodeWithSelector(IERC20.approve.selector, spender, amount));
        if (!ok || (d.length != 0 && !abi.decode(d, (bool)))) revert TransferFailed();
    }
}
Настройки компилятораПоказать
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ]
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.