Skip to content
Verified contractExactMIT

Runner

Address0x34d8a2debe49dcca0f7cc77d74163cfb94cc19f5
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 200 runs
EVM version
shanghai
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,335,795
Creation transaction
0x236d9895ab…f366dcda81

src/Runner.sol

// 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 {NATIVE, PERMIT2, Order, Step, Write, Payout, Recipe, Action} from "./SwapicTypes.sol";
import {IRunner} from "./interfaces/IRunner.sol";
import {ISwapic} from "./interfaces/ISwapic.sol";
import {IScaler} from "./interfaces/IScaler.sol";
import {ICkHelper} from "./interfaces/ICkHelper.sol";
import {Envelope} from "./libraries/Envelope.sol";

/// The hands. Every balance it checks is relative to the start of the call,
/// so a donation changes nothing; every approval it grants is exact and
/// reset after the call it was for.
contract Runner is IRunner {
    using SafeERC20 for IERC20;

    /// A self-call starved anywhere below it leaves `fill` about 1/64 of the
    /// gas for every frame between them (63/64 rule), so a starved arrival
    /// ends with at most 1/8 left for routers up to eight frames deep; the
    /// envelope's signed `minGas` covers deeper ones. An action that fails by
    /// burning all the gas it is given also reverts, at any gas limit.
    uint256 internal constant STARVED = 8;

    address public immutable swapic;
    address public immutable cctpReceiver;
    address public immutable ckHelper;
    /// an order with `tokenIn == NATIVE` arrives wrapped in this token
    address public immutable wrappedNative;

    uint256 private _lock = 1;

    modifier nonReentrant() {
        if (_lock != 1) revert Reentrancy();
        _lock = 2;
        _;
        _lock = 1;
    }

    constructor(address swapic_, address cctpReceiver_, address ckHelper_, address wrappedNative_) {
        swapic = swapic_;
        cctpReceiver = cctpReceiver_;
        ckHelper = ckHelper_;
        wrappedNative = wrappedNative_;
    }

    receive() external payable {}

    // ------------------------------------------------------------------
    // source: the signed steps
    // ------------------------------------------------------------------

    /// Swapic's only. The lock is the Runner's own: Swapic is not locked while
    /// a CCTP arrival runs `fill`, so without it a recipe could call `run` and
    /// nest a whole order inside the arrival.
    function execute(Order calldata o, bytes32 id, uint256 inBaseline) external nonReentrant {
        if (msg.sender != swapic) revert OnlySwapic();
        if (o.payout.token != address(0)) _checkRecipient(o.payout.recipient);
        (address[] memory tokens, uint256[] memory base) = _baselines(o, inBaseline);

        uint256 n = o.steps.length;
        for (uint256 i; i < n; ++i) {
            _step(o.steps[i], tokens, base);
        }

        Payout calldata p = o.payout;
        if (p.token != address(0)) {
            uint256 out = _delta(p.token, tokens, base);
            if (out < p.minOut) revert Short();
            _pay(p.token, p.recipient, out, p.minOut);
            emit PaidOut(id, p.recipient, p.token, out);
        }

        for (uint256 i; i < tokens.length; ++i) {
            if (_balance(tokens[i]) != base[i]) revert LeftOver();
        }
    }

    /// The tracked tokens (tokenIn, every step token, the payout token, each
    /// once) and their balances at the start of this order. A NATIVE tokenIn
    /// arrived wrapped, so the wrapped token is tracked in its place.
    function _baselines(Order calldata o, uint256 inBaseline)
        internal
        view
        returns (address[] memory tokens, uint256[] memory base)
    {
        uint256 n = o.steps.length;
        tokens = new address[](n + 2);
        base = new uint256[](n + 2);
        address tokenIn = o.tokenIn == NATIVE ? wrappedNative : o.tokenIn;
        uint256 count;
        for (uint256 i; i < n + 2; ++i) {
            address t = i == 0 ? tokenIn : i == n + 1 ? o.payout.token : o.steps[i - 1].token;
            if (t == address(0)) continue;
            bool seen;
            for (uint256 j; j < count; ++j) {
                if (tokens[j] == t) {
                    seen = true;
                    break;
                }
            }
            if (seen) continue;
            tokens[count] = t;
            if (t == tokenIn) base[count] = inBaseline;
            else if (t == NATIVE) base[count] = address(this).balance;
            else base[count] = IERC20(t).balanceOf(address(this));
            ++count;
        }
        assembly ("memory-safe") {
            mstore(tokens, count)
            mstore(base, count)
        }
    }

    function _step(Step calldata s, address[] memory tokens, uint256[] memory base) internal {
        address token = s.token;
        bytes memory data = s.data;
        uint256 d;
        if (token == address(0)) {
            if (s.writes.length != 0) revert BadWrite();
        } else {
            d = _delta(token, tokens, base);
            if (d < s.min) revert Short();
            _write(data, s.writes, d);
        }
        // after the writes: a write may cover the selector
        _guard(s.target, data);

        if (token == NATIVE) {
            _call(s.target, d, data);
        } else if (token != address(0)) {
            IERC20(token).forceApprove(s.target, d);
            _call(s.target, 0, data);
            IERC20(token).forceApprove(s.target, 0);
        } else {
            _call(s.target, 0, data);
        }
    }

    function _write(bytes memory data, Write[] calldata ws, uint256 d) internal pure {
        uint256 len = data.length;
        for (uint256 i; i < ws.length; ++i) {
            uint256 at = ws[i].at;
            uint256 minus = ws[i].minus;
            if (at + 32 > len || d < minus) revert BadWrite();
            uint256 v = d - minus;
            assembly ("memory-safe") {
                mstore(add(add(data, 32), at), v)
            }
        }
    }

    function _delta(address token, address[] memory tokens, uint256[] memory base) internal view returns (uint256) {
        for (uint256 i; i < tokens.length; ++i) {
            if (tokens[i] == token) return _balance(token) - base[i];
        }
        revert BadStep();
    }

    // ------------------------------------------------------------------
    // arrival
    // ------------------------------------------------------------------

    function fill(address token, uint256 amount, bytes calldata envelope, Recipe calldata recipe)
        external
        nonReentrant
    {
        ISwapic s = ISwapic(swapic);
        if (s.paused()) revert IsPaused();
        // a door is pulling tokens into this contract right now
        if (s.locked()) revert Reentrancy();
        Envelope.Data memory e = Envelope.decode(envelope);
        if (e.action == Action.Deliver) revert WrongAction();
        _checkRecipient(e.recipient);
        // else whoever picks the recipe could pay the arriving token to
        // themselves and still pass
        if (e.action == Action.Swap && (e.minOut == 0 || e.tokenOut == address(0) || e.tokenOut == token)) {
            revert BadArrival();
        }

        uint256 base = IERC20(token).balanceOf(address(this));
        IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
        uint256 received = IERC20(token).balanceOf(address(this)) - base;

        if (_act(token, received, base, e, recipe)) return;
        IERC20(token).safeTransfer(e.recipient, received);
        emit Refunded(e.ref, e.recipient, token, received);
    }

    /// The action in an undoable self-call (no returndata copied). The signed
    /// `minGas` must be left for it; a self-call starved anyway is the
    /// caller's doing, not a failed action: both revert so the arrival can be
    /// retried with more gas.
    function _act(address token, uint256 received, uint256 base, Envelope.Data memory e, Recipe calldata recipe)
        internal
        returns (bool ok)
    {
        bytes memory cd = e.action == Action.Swap
            ? abi.encodeCall(this.swapAll, (token, received, base, e, recipe))
            : abi.encodeCall(this.ckDepositAll, (token, received, base, e));
        uint256 before = gasleft();
        // the self-call receives at most 63/64 of what is left here
        if (before - before / 64 < e.minGas) revert OutOfGas();
        assembly ("memory-safe") {
            ok := call(gas(), address(), 0, add(cd, 32), mload(cd), 0, 0)
        }
        if (!ok && gasleft() <= before / STARVED) revert OutOfGas();
    }

    /// All of `received` spent, at least `minOut` of tokenOut, all of it paid.
    function swapAll(address token, uint256 received, uint256 base, Envelope.Data calldata e, Recipe calldata r)
        external
        returns (uint256 out)
    {
        if (msg.sender != address(this)) revert OnlySelf();
        bytes memory data = r.data;
        if (r.scaler != address(0)) {
            bool ok;
            (ok, data) = IScaler(r.scaler).getScaledInputData(data, received);
            if (!ok) revert BadStep();
        }
        if (r.target == token) revert BadStep();
        _guard(r.target, data);

        address tokenOut = e.tokenOut;
        uint256 outBase = _balance(tokenOut);
        IERC20(token).forceApprove(r.target, received);
        _call(r.target, 0, data);
        IERC20(token).forceApprove(r.target, 0);
        if (IERC20(token).balanceOf(address(this)) != base) revert LeftOver();

        out = _balance(tokenOut) - outBase;
        if (out < e.minOut) revert Short();
        _pay(tokenOut, e.recipient, out, e.minOut);
        emit Delivered(e.ref, e.recipient, tokenOut, received, out);
    }

    function ckDepositAll(address token, uint256 received, uint256 base, Envelope.Data calldata e) external {
        if (msg.sender != address(this)) revert OnlySelf();
        if (ckHelper == address(0)) revert NoHelper();
        IERC20(token).forceApprove(ckHelper, received);
        ICkHelper(ckHelper).depositErc20(token, received, e.principal, e.subaccount);
        IERC20(token).forceApprove(ckHelper, 0);
        if (IERC20(token).balanceOf(address(this)) != base) revert LeftOver();
        emit CkDeposited(e.ref, e.principal, e.subaccount, received);
    }

    // ------------------------------------------------------------------
    // shared
    // ------------------------------------------------------------------

    /// Rule 2: never our own contracts or Permit2, never an address without
    /// code, never a call that moves or grants someone else's allowance.
    function _guard(address target, bytes memory data) internal view {
        if (
            target == swapic || target == address(this) || target == cctpReceiver || target == PERMIT2
                || target.code.length == 0
        ) revert BadStep();
        if (data.length >= 4) {
            bytes4 sel;
            assembly ("memory-safe") {
                sel := mload(add(data, 32))
            }
            if (_grants(sel)) revert BadStep();
        }
    }

    /// Calls that move someone else's tokens or leave a standing right with
    /// someone (the Runner makes its own exact approvals, so no step needs one).
    function _grants(bytes4 sel) internal pure returns (bool) {
        return sel == 0x23b872dd // transferFrom
            || sel == 0x095ea7b3 // approve
            || sel == 0x39509351 // increaseAllowance
            || sel == 0xd505accf // permit
            || sel == 0xa22cb465 // setApprovalForAll
            || sel == 0xd73dd623 // increaseApproval
            || sel == 0x959b8c3f // ERC-777 holder authorization
            || sel == 0x3177029f // ERC-1363 approveAndCall(address,uint256)
            || sel == 0xcae9ca51 // ERC-1363 approveAndCall(address,uint256,bytes)
            || sel == 0xdaea85c5 // DSToken approve(address)
            || sel == 0x558a7297 // ERC-6909 grant for all ids
            || sel == 0x426a8493 // ERC-6909 approve(address,uint256,uint256)
            || sel == 0x5df8122f // ERC-1820 setManager
            || sel == 0x29965a1d // ERC-1820 setInterfaceImplementer
            || sel == 0x110496e5 // Comet allow
            || sel == 0xeecea000 // Morpho setAuthorization
            || sel == 0xc04a8a10 // Aave approveDelegation
            || sel == 0xfa6e671d // Balancer setRelayerApproval
            || sel == 0xa3b22fc4; // Maker hope
    }

    /// Never nowhere, never one of our own contracts (funds there are stuck
    /// or takeable by anyone).
    function _checkRecipient(address to) internal view {
        if (to == address(0) || to == swapic || to == address(this) || to == cctpReceiver) revert BadRecipient();
    }

    function _balance(address token) internal view returns (uint256) {
        return token == NATIVE ? address(this).balance : IERC20(token).balanceOf(address(this));
    }

    /// All of `amount` to `to`, who must end up with at least `minOut` of an
    /// ERC-20 as received (a fee-on-transfer token pays less than it sends).
    function _pay(address token, address to, uint256 amount, uint256 minOut) internal {
        if (token == NATIVE) {
            _call(to, amount, "");
            return;
        }
        uint256 before = IERC20(token).balanceOf(to);
        IERC20(token).safeTransfer(to, amount);
        if (IERC20(token).balanceOf(to) - before < minOut) revert Short();
    }

    /// No returndata copied (return-bomb safe); a failure reverts.
    function _call(address target, uint256 value, bytes memory data) internal {
        bool ok;
        assembly ("memory-safe") {
            ok := call(gas(), target, value, add(data, 32), mload(data), 0, 0)
        }
        if (!ok) revert CallFailed();
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

lib/openzeppelin-contracts/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

import {Errors} from "./Errors.sol";

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

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

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

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

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

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

lib/openzeppelin-contracts/contracts/utils/Errors.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

src/SwapicTypes.sol

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

// Ether, wherever a token address is expected.
address constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

// Uniswap's Permit2: a door for Swapic, a banned target for the Runner.
address constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;

/// Writes (delta - minus) as one uint256 word at byte `at` of a step's data.
/// `at` is any byte offset, not a word index.
struct Write {
    uint32 at;
    uint256 minus;
}

/// One call the Runner makes. `token` ERC-20: the Runner approves `target`
/// exactly its delta of `token`; `token == NATIVE`: it sends that delta as
/// value; `token == 0`: no approval, no value, no writes.
struct Step {
    address target;
    bytes data;
    address token;
    uint256 min;
    Write[] writes;
}

/// `token == 0`: no payout (cross-chain orders).
struct Payout {
    address token;
    address recipient;
    uint256 minOut;
}

/// `memo`: a pool deposit's encoded terms, whose keccak256 is `ref`; empty on
/// every other order. Swapic only signs it into the id and emits it.
struct Order {
    bytes32 ref;
    address payer;
    address tokenIn;
    uint256 amountIn;
    uint256 deadline;
    Step[] steps;
    Payout payout;
    bytes memo;
}

enum Door {
    Auth3009,
    Permit2612,
    Permit2
}

/// Auth3009: `validAfter`, `validBefore` and `signature` (r ++ s ++ v).
/// Permit2612: `signature` is the permit (swallowed if it fails) and
/// `acceptance` the payer's QuoteAcceptance signature. Permit2: `nonce`,
/// `deadline` and `signature` of the witness transfer.
struct GaslessAuth {
    Door door;
    uint256 validAfter;
    uint256 validBefore;
    uint256 nonce;
    uint256 deadline;
    bytes signature;
    bytes acceptance;
}

struct Permit2Auth {
    uint256 nonce;
    uint256 deadline;
    bytes signature;
}

enum Action {
    Deliver,
    Swap,
    CkDeposit
}

/// The arrival swap. `scaler == 0`: `data` as is; else `data` is first
/// rescaled to the amount that arrived.
struct Recipe {
    address target;
    bytes data;
    address scaler;
}

src/interfaces/ICkHelper.sol

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

/// The ck minter's ERC-20 deposit helper on Ethereum: it pulls `amount` of
/// `erc20Address` from the caller for the minter and logs the beneficiary.
interface ICkHelper {
    function depositErc20(address erc20Address, uint256 amount, bytes32 principal, bytes32 subaccount) external;
}

src/interfaces/IRunner.sol

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

import {Order, Recipe} from "../SwapicTypes.sol";
import {Envelope} from "../libraries/Envelope.sol";

/// Runs the signed steps of an order (only Swapic may ask) and every arrival
/// (anyone may ask, paying with their own tokens). Nobody approves it, it
/// holds nothing between transactions, and every outcome is all or nothing.
interface IRunner {
    /// A same-chain order paid `amount` of `token` to `recipient`.
    event PaidOut(bytes32 indexed id, address indexed recipient, address token, uint256 amount);
    /// An arrival of `amountIn` was swapped whole into `amountOut` of `tokenOut`.
    event Delivered(
        bytes32 indexed ref, address indexed recipient, address tokenOut, uint256 amountIn, uint256 amountOut
    );
    event CkDeposited(bytes32 indexed ref, bytes32 indexed principal, bytes32 subaccount, uint256 amount);
    /// The arrival action failed: all of the arrived `token` went to `recipient`.
    event Refunded(bytes32 indexed ref, address indexed recipient, address token, uint256 amount);

    error OnlySwapic();
    error OnlySelf();
    error Reentrancy();
    error IsPaused();
    error BadStep();
    error BadWrite();
    error Short();
    error LeftOver();
    error CallFailed();
    error WrongAction();
    error BadArrival();
    error BadRecipient();
    error NoHelper();
    error OutOfGas();

    function swapic() external view returns (address);
    function cctpReceiver() external view returns (address);
    function ckHelper() external view returns (address);
    function wrappedNative() external view returns (address);

    /// Only Swapic, after it pulled `amountIn` into the Runner. `inBaseline`
    /// is the Runner's `tokenIn` balance before that pull (for a NATIVE
    /// tokenIn: of the wrapped native token, which is what arrived).
    function execute(Order calldata order, bytes32 id, uint256 inBaseline) external;

    /// Anyone (Eco's executor, the CCTP receiver, any rail that can approve
    /// and call): pulls `amount` of `token` from the caller, then acts on
    /// exactly what arrived as the envelope says. Swap: through `recipe`, all
    /// of it into at least `minOut` of `tokenOut`, all paid to the recipient;
    /// CkDeposit: all of it into the ck helper. If the action fails, all of
    /// what arrived goes to the recipient instead. Reverts (so nothing
    /// arrives) when paused, while a Swapic door runs, on a bad or Deliver
    /// envelope or a bad recipient, when less than the envelope's `minGas`
    /// is left for the action or the action was starved of gas (`OutOfGas`,
    /// retry with more), or if the refund transfer itself fails.
    function fill(address token, uint256 amount, bytes calldata envelope, Recipe calldata recipe) external;

    /// Self-call only: the undoable halves of `fill`.
    function swapAll(address token, uint256 received, uint256 base, Envelope.Data calldata e, Recipe calldata recipe)
        external
        returns (uint256 out);
    function ckDepositAll(address token, uint256 received, uint256 base, Envelope.Data calldata e) external;
}

src/interfaces/IScaler.sol

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

/// KyberSwap's InputScalingHelper (`0x2f577A41BeC1BE1152AeEA12e73b7391d15f655D`
/// on Base, Arbitrum and Ethereum): rewrites router calldata built for one
/// input amount to `newAmount`.
interface IScaler {
    function getScaledInputData(bytes calldata inputData, uint256 newAmount)
        external
        view
        returns (bool isSuccess, bytes memory data);
}

src/interfaces/ISwapic.sol

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

import {Order, GaslessAuth, Permit2Auth} from "../SwapicTypes.sol";

/// The door: the only contract users approve. It takes exactly the signed
/// `amountIn` from the payer, once per order, hands it to the Runner, and
/// makes no other call.
interface ISwapic {
    /// `memo` is the order's own, so its terms can be read back from the chain.
    event OrderStarted(
        bytes32 indexed id,
        bytes32 indexed ref,
        address indexed payer,
        address tokenIn,
        uint256 amountIn,
        bytes memo
    );
    event Paused(address by);
    event Unpaused(address by);
    event GuardianSet(address guardian);
    event CanisterSet(address canister);
    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    error IsPaused();
    error Expired();
    error Used();
    error NotPayer();
    error NotCanister();
    error NotOwner();
    error NotGuardianOrOwner();
    error BadValue();
    error NotAccepted();
    error BadParams();
    error Reentrancy();
    error NotReceived();

    /// By the payer. `tokenIn == NATIVE`: `msg.value == amountIn`, wrapped
    /// into `wrappedNative()` and handed to the Runner as that token (the
    /// steps are built for it); else `msg.value == 0` and Swapic pulls
    /// `amountIn` from the payer.
    function run(Order calldata order) external payable returns (bytes32 id);

    /// By the payer, ERC-20 only: a Permit2 witness transfer (witness = id).
    function runWithPermit2(Order calldata order, Permit2Auth calldata auth) external returns (bytes32 id);

    /// By the canister, ERC-20 only, through one of three gasless doors, each
    /// bound to `id`: the 3009 nonce, the 2612 QuoteAcceptance, the Permit2
    /// witness.
    function runFor(Order calldata order, GaslessAuth calldata auth) external returns (bytes32 id);

    function orderId(Order calldata order) external view returns (bytes32);
    /// What the payer signs on the 2612 door.
    function acceptanceDigest(Order calldata order) external view returns (bytes32);
    function used(bytes32 id) external view returns (bool);
    function runner() external view returns (address);
    function cctpReceiver() external view returns (address);
    function wrappedNative() external view returns (address);

    function paused() external view returns (bool);
    /// true while a door runs: the Runner refuses `fill` meanwhile, so no
    /// callback during a pull can act on the payer's tokens in flight
    function locked() external view returns (bool);
    function owner() external view returns (address);
    function pendingOwner() external view returns (address);
    function guardian() external view returns (address);
    /// the canister's EVM address
    function canister() external view returns (address);

    /// EIP-5267: the domain of the order id and the QuoteAcceptance.
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );

    function pause() external;
    function unpause() external;
    function setGuardian(address guardian) external;
    function setCanister(address canister) external;
    function transferOwnership(address newOwner) external;
    function acceptOwnership() external;
}

src/libraries/Envelope.sol

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

import {Action} from "../SwapicTypes.sol";

/// The sealed arrival instruction: `abi.encode` of 10 static words, 320
/// bytes, word i at byte 32 * i:
///
///   0  uint8   version      3
///   1  bytes32 ref          Order.ref
///   2  uint8   action       0 Deliver, 1 Swap, 2 CkDeposit
///   3  uint64  deadline     end of the canister-or-recipient window (CCTP)
///   4  address recipient    tokenOut receiver and refund receiver
///   5  address tokenOut     Swap only (NATIVE for ether)
///   6  uint256 minOut       Swap only, in tokenOut
///   7  bytes32 principal    CkDeposit only
///   8  bytes32 subaccount   CkDeposit only
///   9  uint64  minGas       gas `fill` must have left for the action
///
/// In a CCTP v2 message it starts at byte 376; in an Eco route it is the
/// `envelope` argument of `Runner.fill`.
library Envelope {
    uint256 internal constant VERSION = 3;
    uint256 internal constant LENGTH = 320;

    struct Data {
        uint8 version;
        bytes32 ref;
        Action action;
        uint64 deadline;
        address recipient;
        address tokenOut;
        uint256 minOut;
        bytes32 principal;
        bytes32 subaccount;
        uint64 minGas;
    }

    error BadEnvelope();

    function encode(Data memory d) internal pure returns (bytes memory) {
        return abi.encode(d);
    }

    /// Exactly 320 bytes, version 3, every narrow word clean.
    function decode(bytes calldata b) internal pure returns (Data memory d) {
        if (b.length != LENGTH) revert BadEnvelope();
        (
            uint256 version,
            bytes32 ref,
            uint256 action,
            uint256 deadline,
            uint256 recipient,
            uint256 tokenOut,
            uint256 minOut,
            bytes32 principal,
            bytes32 subaccount,
            uint256 minGas
        ) = abi.decode(b, (uint256, bytes32, uint256, uint256, uint256, uint256, uint256, bytes32, bytes32, uint256));
        if (
            version != VERSION || action > uint256(Action.CkDeposit) || deadline > type(uint64).max
                || recipient > type(uint160).max || tokenOut > type(uint160).max || minGas > type(uint64).max
        ) revert BadEnvelope();
        d = Data({
            version: uint8(version),
            ref: ref,
            action: Action(action),
            deadline: uint64(deadline),
            recipient: address(uint160(recipient)),
            tokenOut: address(uint160(tokenOut)),
            minOut: minOut,
            principal: principal,
            subaccount: subaccount,
            minGas: uint64(minGas)
        });
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "shanghai",
  "remappings": [
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.