Executive Summary & Direct Answer

An arbitrary-call swap interface can turn a contract’s existing ERC-20 approvals into an attacker-controlled withdrawal mechanism. If user-supplied data can choose both the call target and calldata, a “swap” may instead call an approved token’s transferFrom and move assets from the vulnerable contract to an attacker. The production fix is to remove arbitrary target-and-calldata execution: use trusted, allowlisted executors with typed parameters, grant only temporary exact-amount approvals, and verify actual input and output balance changes.

This guide applies that fix to the failure pattern described in the BlockSec analysis of the SwapNet and Aperture Finance incidents. In both cases, insufficient validation let attacker-controlled low-level calls operate against assets the victim contracts had previously approved.

Environment and security boundary

Examples target Solidity ^0.8.24 and the Cancun EVM. The code uses OpenZeppelin Contracts v5.x SafeERC20; pin an exact dependency version in production, for example @openzeppelin/[email protected]. The key issue is not a Solidity compiler defect: it is a design flaw in which a contract holding token balances and approvals exposes a call capability that users can redirect.

A router should receive only the authority needed to perform a specific swap. It should not receive a general-purpose capability to call any address with any bytes. Treat the following as separate controls:

  • Target policy: which executor contracts can be called?
  • Operation policy: which operation can each executor perform?
  • Asset policy: which tokens may enter and leave?
  • Allowance policy: how much can the executor spend, and for how long?
  • Outcome policy: what measurable result must the call produce?

A check on only one of these dimensions is not a substitute for the others.

The vulnerable pattern: user chooses target and calldata

A common aggregator interface accepts a router address and an opaque calldata blob:

// Vulnerable: the caller controls both destination and operation.
function execute(address target, bytes calldata data) external {
    (bool ok, bytes memory result) = target.call(data);
    require(ok, "call failed");

    // A separate approval to a spender may already exist.
    // No guarantee the target performed a legitimate swap.
}

The low-level call executes from the contract’s address. If the target is an ERC-20 token and the data encodes transferFrom(victim, attacker, amount), the token sees the victim contract as msg.sender. Any sufficient allowance the victim previously granted can authorize the transfer.

That is the core mechanism reconstructed in the BlockSec report: an attacker could make a victim contract treat a token address as an execution target and issue attacker-controlled calldata. The report describes a similar gap in Aperture’s custom-swap path: validating an approval spender did not ensure that the actual call target was the intended router. A balance check did not rescue the design when its expected output was itself caller-controlled or when the check did not enforce a genuine, measured output.

Do not fix this by checking only target != token, only the function selector, or only the approval spender. A permitted target can expose dangerous methods; a permitted selector can be used with malicious arguments; and an approval to a trusted spender does not make an unrelated execution target safe.

Production pattern: trusted executor, typed operation, measured result

Remove arbitrary calldata from the public interface. The example below uses a trusted executor with a typed swap method. The caller can choose bounded swap parameters, but cannot select a target, recipient, or raw call bytes.

// 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 ISwapExecutor {
    function swap(
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minOut,
        address recipient,
        uint256 deadline
    ) external returns (uint256 reportedOut);
}

contract ConfinedSwap is ReentrancyGuard {
    using SafeERC20 for IERC20;

    error NotAuthorized();
    error UnsupportedAsset();
    error InvalidAmount();
    error InvalidExecutor();
    error Expired();
    error UnexpectedInputDelta();
    error InsufficientOutput(uint256 actual, uint256 minimum);
    error ResidualAllowance();

    address public owner;
    mapping(address => bool) public supportedAsset;
    mapping(address => bool) public trustedExecutor;

    constructor(address owner_) {
        if (owner_ == address(0)) revert NotAuthorized();
        owner = owner_;
    }

    function setAsset(address token, bool enabled) external {
        if (msg.sender != owner) revert NotAuthorized();
        supportedAsset[token] = enabled;
    }

    function setExecutor(address executor, bool enabled) external {
        if (msg.sender != owner) revert NotAuthorized();
        trustedExecutor[executor] = enabled;
    }

    function swap(
        address executor,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minOut,
        uint256 deadline
    ) external nonReentrant returns (uint256 actualOut) {
        if (!trustedExecutor[executor]) revert InvalidExecutor();
        if (!supportedAsset[tokenIn] || !supportedAsset[tokenOut]) {
            revert UnsupportedAsset();
        }
        if (tokenIn == tokenOut || amountIn == 0 || minOut == 0) {
            revert InvalidAmount();
        }
        if (block.timestamp > deadline) revert Expired();

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

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

        // Grant only this executor authority for this operation.
        input.forceApprove(executor, amountIn);

        ISwapExecutor(executor).swap(
            tokenIn,
            tokenOut,
            amountIn,
            minOut,
            address(this),
            deadline
        );

        // Do not leave a standing allowance if the executor spent less.
        input.forceApprove(executor, 0);

        uint256 inputAfter = input.balanceOf(address(this));
        uint256 outputAfter = output.balanceOf(address(this));

        if (inputAfter > inputBefore ||
            inputBefore - inputAfter != amountIn) {
            revert UnexpectedInputDelta();
        }

        actualOut = outputAfter > outputBefore
            ? outputAfter - outputBefore
            : 0;

        if (actualOut < minOut) {
            revert InsufficientOutput(actualOut, minOut);
        }

        if (input.allowance(address(this), executor) != 0) {
            revert ResidualAllowance();
        }
    }
}

The executor must itself be reviewed and trusted: allowlisting an unsafe executor merely moves the arbitrary-call vulnerability one hop away. The code also deliberately requires the executor to spend exactly amountIn. If a supported route permits partial fills, define that behavior explicitly and check that the input delta is nonzero and no greater than the authorized amount instead.

For production use, add authorization and delivery semantics appropriate to the product—for example, bind the caller or recipient to the swap and transfer measured output to that recipient. Do not let an untrusted caller choose an unrelated payout address if the contract holds pooled assets. Rejecting unsupported tokens matters too: rebasing or otherwise non-standard tokens can make balance-delta assumptions invalid unless the integration is designed for them. SafeERC20 handles common return-value irregularities; it does not make a malicious token trustworthy. See Preventing Short Address and Zero-Address Bugs in Solidity for related input-boundary concerns.

Why balance deltas matter

A router’s return value is not proof that the contract received assets. It may be inaccurate, malicious, or based on a caller-controlled expected amount. Measuring the contract’s balances before and after the external call checks the effect on the contract itself.

The exact-input invariant in the example is:

inputBefore - inputAfter == amountIn
outputAfter - outputBefore >= minOut

A production integration may need different invariants for partial fills, fee-on-transfer assets, rebasing assets, or multi-hop routes. Specify those cases rather than weakening the check until it accepts unexplained balance changes. For the broader hazards of failing to inspect external-call results, see Preventing Unchecked Low-Level Call Failures in Solidity.

Quantitative trade-offs

These are design-level estimates, not benchmark results. Actual gas depends on token behavior, executor implementation, compiler settings, and whether storage slots are warm. Cold storage reads are charged under the EVM’s access-cost rules; transaction-specific measurements must be made against the intended deployment.

ApproachExternal-call authorityAllowance exposureTypical added checksSecurity result
Arbitrary target.call(data)Any address and calldata supplied by callerPotentially any existing allowanceOne low-level call; no policy checksCan redirect an approved token’s transferFrom
Allowlisted target, arbitrary calldataAny calldata to an approved targetDepends on prior approvalsTarget lookup; calldata remains unboundedSafer only if the target cannot perform harmful operations
Typed trusted executor, exact approvalOne configured executor and typed operationAt most amountIn for one call; reset afterwardAsset/executor checks, balance reads, approval set/resetConstrains target, arguments, spending, and measured output

The secure pattern adds storage reads for allowlist and asset policy, token balance queries, and approval operations. A cold SLOAD costs 2,100 gas under EIP-2929; actual token calls commonly dominate the extra cost and vary by implementation. That overhead buys a meaningful reduction in authority: a malformed route cannot choose an arbitrary token contract and invoke arbitrary calldata through the vault.

Production pitfalls and differential verification

Executor upgrades: An address can remain constant while its implementation changes behind a proxy. Treat executor upgrades as security-sensitive configuration changes. Use governance controls, a timelock where appropriate, and a process to disable an executor before or during an incident.

Approval lifecycle: Exact approvals still create risk during the external call. A malicious or compromised executor can spend the approved amount immediately. Resetting afterward limits future exposure; it cannot undo a transfer already made. If the token or integration cannot reliably reset approval, reject that token or use a separately audited approval strategy.

Call failure and return data: A reverting executor call reverts the whole transaction, including the temporary approval. Do not catch that revert and continue as though a swap succeeded. Conversely, successful low-level execution is not proof of correct behavior: check measured deltas. Avoid trusting a caller-supplied “expected output” as the sole postcondition.

Balance accounting: Snapshot balances immediately before the operation. Account for pre-existing balances by comparing deltas, not absolute balances. Decide what to do with unsolicited token transfers and output-token dust. If the same token can be both input and output, the simple delta checks are ambiguous; the example rejects that case.

Configuration and callers: Protect executor and asset configuration with the project’s real governance model; the minimal owner in the example is not a complete access-control system. Validate every user-controlled parameter, including deadlines and recipients. If users authorize swaps with signatures, bind the complete operation to the correct chain and contract domain; see Preventing Signature Replay Attacks in Solidity.

Foundry verification

Create tests for both the exploit mechanism and the intended route. In particular, a malicious target should attempt to call transferFrom(address(this), attacker, amount); the secure contract should never invoke that target, and a non-allowlisted executor should revert before any token approval is granted.

forge test --match-path test/ConfinedSwap.t.sol -vvv
forge test --match-path test/ConfinedSwap.t.sol --fuzz-runs 10000

Add fuzz properties for: untrusted executor addresses always reverting; unsupported assets always reverting; a successful swap never leaving executor allowance nonzero; and output below minOut reverting. Use a malicious test executor that reports a fabricated return value while transferring no output—the balance-delta assertion should still reject it.

For compiler-profile differential checks, pin the compiler and optimizer settings used in deployment, then compare test results and generated code under a second profile:

forge test --use 0.8.24 --optimizer --optimizer-runs 200
forge test --use 0.8.24 --no-optimizer
solc --version
solc --ir-optimized --optimize --optimize-runs 200 src/ConfinedSwap.sol

These commands do not prove the executor is safe. They help detect profile-sensitive behavior and make the deployed compilation settings reproducible. Also inspect the executor’s source and any proxy implementation; the relevant security boundary includes every contract reached by the typed call.

Frequently Asked Questions (FAQ)

How does an arbitrary router call drain tokens approved to a Solidity contract?

The vulnerable contract makes an external call, so the token contract sees the vulnerable contract as the caller. If attacker-controlled calldata invokes transferFrom(victim, attacker, amount) and the token has a sufficient allowance from the victim contract, the token can transfer those assets to the attacker.

Is checking the router address enough to prevent arbitrary-call token drains?

No. An allowlisted address does not make arbitrary calldata, attacker-selected arguments, or an overly broad token approval safe. Use a trusted executor with a typed operation, validate supported assets and parameters, and grant only the amount needed for the operation.

Does Solidity 0.8.24 prevent the SwapNet-style arbitrary-call vulnerability?

No. Solidity 0.8.x checked arithmetic does not restrict which address a contract calls or what calldata it forwards. Preventing this class of drain requires explicit call-target and operation constraints, bounded approvals, and checks of actual token balance changes.

Learn more with useful resources