Skip to content
Verified contractExactMIT

AlphabrosRouterFactory

Address0xd42bbeb6996dedfa9990894f58d7abff251bc4ec
Balance

0 ETH

 

Transactions

6

 

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
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,101,160
Creation transaction
0xa04abc1f45…e59ab274c6

src/alphabros/AlphabrosRouterFactory.sol

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

/// @title Alphabros router factory
/// @notice Lets anyone deploy their own Alphabros router, and holds the fees every router takes.
///
/// @dev Three contracts, one per role:
///
///      - `AlphabrosRouterFactory` (this, one per chain). Anyone calls `createRouter` and gets their own router: an
///        EIP-1167 clone of one fixed implementation, at a CREATE2 address salted by their address. The factory
///        holds the fee floor (in the chain's native coin), holds every fee as a per-wallet balance, and deploys
///        one executor per user. No price feed: nothing external can move the floor or block a swap.
///
///      - `AlphabrosRouter` (a clone per deployer — the "trader"). Runs swaps exactly like v1. Fees are a
///        percentage of the trade: the protocol's `PROTOCOL_FEE_BPS` (0.25%, fixed forever) plus the trader's own
///        `traderFeeBps` (0 to `MAX_TRADER_FEE_BPS` = 0.25%, fixed forever), so at most 0.5% in total, and never
///        less than the floor `minFee` (native wei, e.g. 0.0002 ETH, 0.001 BNB, 0.5 USDC on Arc). Every swap must
///        have the native coin, the wrapped native coin (WETH / WBNB) or the native mirror on at least one side, or
///        it reverts; so the contract always values the trade itself. The user signs a MAXIMUM fee; after the swap
///        the contract charges exactly max(floor, input x rate, actual output x rate) and refunds the rest. No
///        front-end can take more than that. A token -> token trade routes through the wrapped native coin.
///        Each fee splits in proportion: the protocol gets fee x 25 / (25 + traderFeeBps), the trader the rest.
///        Both shares are credited here in the same call; nothing is pushed to a wallet during a swap, so a fee
///        wallet that rejects native coin cannot block anyone's swap.
///
///      - `AlphabrosSwapExecutor` (a clone per user). Runs a user's swap calls. It serves every router this factory
///        created, so a user deploys it once no matter how many deployers' routers they use, and it only ever acts
///        for its own user.
///
///      Who can change what:
///      - The factory owner (2-step transfer) can change the protocol fee wallet and the floor `minFee` (never
///        above `MAX_MIN_FEE`, fixed per chain at deployment). Chain facts (wrapped native, native mirror) and
///        every cap are immutable.
///      - A router's owner can change that router's fee wallet. Its `traderFeeBps` (0 to 0.25%) is set once at
///        creation and can never change, so nobody can raise the fee under a user's signed swap; a trader who wants
///        a different rate deploys another router.
///      - The percentages themselves (`PROTOCOL_FEE_BPS`, `MAX_TRADER_FEE_BPS`) are constants: nobody can change them.
///      - Nobody can move a user's tokens, a user's executor balance, or a wallet's collectable fees except to
///        that user / that wallet.
///
///      Fees already credited stay with the wallet they were credited to, even if a fee wallet is later changed.
contract AlphabrosRouterFactory {
    // ------------------------------------------------------------------ chain facts and caps, fixed forever

    /// WETH / WBNB (Arc: the USDC mirror). Executors always check it as a route intermediate; routers value it 1:1.
    address public immutable WRAPPED_NATIVE;
    /// ERC-20 that shares the native balance (Arc's USDC), or `address(0)`.
    address public immutable NATIVE_MIRROR;
    /// Cap on `minFee`, in native wei: the most the floor can ever be on this chain (about $10). Fixed forever.
    uint256 public immutable MAX_MIN_FEE;
    /// Code behind every router and every executor.
    address public immutable ROUTER_IMPL;
    address public immutable EXECUTOR_IMPL;

    /// Protocol fee: 0.25% of the trade. Fixed forever.
    uint256 public constant PROTOCOL_FEE_BPS = 25;
    /// Most a trader can add on top: 0.25% of the trade (0.5% total). Fixed forever.
    uint256 public constant MAX_TRADER_FEE_BPS = 25;

    // ------------------------------------------------------------------ owner-controlled, within the caps

    address public owner;
    address public pendingOwner;
    /// Receives the protocol's share of every swap fee.
    address public protocolFeeWallet;
    /// The fee floor, in native wei: every swap pays at least this. At most `MAX_MIN_FEE`.
    uint256 public minFee;

    // ------------------------------------------------------------------ state

    /// Routers this factory created. Only they can credit fees and drive executors.
    mapping(address => bool) public isRouter;
    /// Native coin each wallet can collect.
    mapping(address => uint256) public collectable;
    /// Sum of `collectable`; always equal to this contract's balance.
    uint256 public totalCollectable;

    uint256 private _locked = 1;

    event RouterCreated(address indexed deployer, address indexed router, address feeWallet, uint256 traderFeeBps, bytes32 salt);
    event ExecutorCreated(address indexed user, address executor);
    event FeesCredited(
        address indexed router, address indexed protocolWallet, uint256 protocolFee, address indexed deployerWallet, uint256 deployerFee
    );
    event Collected(address indexed wallet, address indexed to, uint256 amount);
    event Recovered(address indexed user, address[] tokens);
    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    event ProtocolFeeWalletSet(address wallet);
    event MinFeeSet(uint256 minFee);

    error ZeroAddress();
    error AboveCap(uint256 value, uint256 cap);
    error OnlyOwner();
    error OnlyPendingOwner();
    error OnlyRouter();
    error DeployFailed();
    error NativeTransferFailed();
    error Reentrancy();

    modifier onlyOwner() {
        if (msg.sender != owner) revert OnlyOwner();
        _;
    }

    modifier onlyRouter() {
        if (!isRouter[msg.sender]) revert OnlyRouter();
        _;
    }

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

    /// @param owner_ Factory owner. Explicit, because a CREATE3 deployment's msg.sender is a proxy.
    /// @param protocolFeeWallet_ Receives the protocol's share.
    /// @param minFee_ The fee floor in native wei (e.g. 0.0002 ETH). At most `maxMinFee`.
    /// @param maxMinFee Cap on the floor in native wei, fixed forever (about $10 on the chain).
    /// @param wrappedNative WETH / WBNB (Arc: the USDC mirror).
    /// @param nativeMirror ERC-20 sharing the native balance (Arc's USDC), or `address(0)`.
    constructor(
        address owner_,
        address protocolFeeWallet_,
        uint256 minFee_,
        uint256 maxMinFee,
        address wrappedNative,
        address nativeMirror
    ) {
        // The factory itself would be a protocol wallet nobody can collect for (matches setProtocolFeeWallet).
        if (owner_ == address(0) || protocolFeeWallet_ == address(0) || protocolFeeWallet_ == address(this)) {
            revert ZeroAddress();
        }
        if (wrappedNative == address(0)) revert ZeroAddress();
        if (minFee_ > maxMinFee) revert AboveCap(minFee_, maxMinFee);

        WRAPPED_NATIVE = wrappedNative;
        NATIVE_MIRROR = nativeMirror;
        MAX_MIN_FEE = maxMinFee;

        owner = owner_;
        protocolFeeWallet = protocolFeeWallet_;
        minFee = minFee_;
        emit OwnershipTransferred(address(0), owner_);
        emit MinFeeSet(minFee_);

        ROUTER_IMPL = address(new AlphabrosRouter(wrappedNative, nativeMirror));
        EXECUTOR_IMPL = address(new AlphabrosSwapExecutor(wrappedNative, nativeMirror));
    }

    // ================================================================== routers

    /// @notice Deploy your own router. You become its owner; `feeWallet` receives your share of its fees.
    /// @param traderFeeBps Your fee on top of the protocol's 0.25%, in basis points (0 to 25 = 0 to 0.25%).
    /// @param salt Any value; lets one deployer create several routers. The address is `predictRouter(you, salt)`.
    function createRouter(address feeWallet, uint256 traderFeeBps, bytes32 salt) external returns (address router) {
        router = _clone(ROUTER_IMPL, _routerSalt(msg.sender, salt));
        isRouter[router] = true;
        AlphabrosRouter(router).initialize(msg.sender, feeWallet, traderFeeBps);
        emit RouterCreated(msg.sender, router, feeWallet, traderFeeBps, salt);
    }

    function predictRouter(address deployer, bytes32 salt) external view returns (address) {
        return _predict(ROUTER_IMPL, _routerSalt(deployer, salt));
    }

    function _routerSalt(address deployer, bytes32 salt) private pure returns (bytes32) {
        return keccak256(abi.encode(deployer, salt));
    }

    // ================================================================== executors

    /// @notice `user`'s executor, whether or not it is deployed yet. Funds there are `user`'s alone.
    function executorOf(address user) public view returns (address) {
        return _predict(EXECUTOR_IMPL, bytes32(uint256(uint160(user))));
    }

    /// `user`'s executor, deployed on first use. Routers call this with their own msg.sender.
    function executorFor(address user) external onlyRouter returns (address ex) {
        ex = executorOf(user);
        if (ex.code.length == 0) {
            if (_clone(EXECUTOR_IMPL, bytes32(uint256(uint160(user)))) != ex) revert DeployFailed();
            AlphabrosSwapExecutor(payable(ex)).initialize(user);
            emit ExecutorCreated(user, ex);
        }
    }

    /// @notice Send your own executor's balance of each of `tokens` (`address(0)` = native) back to you. No fee.
    function recover(address[] calldata tokens) external nonReentrant {
        address ex = executorOf(msg.sender);
        if (ex.code.length == 0) return;
        AlphabrosSwapExecutor(payable(ex)).recover(tokens);
        emit Recovered(msg.sender, tokens);
    }

    // ================================================================== fee floor

    /// @notice The fee floor every swap pays at least, in native wei. A plain stored value: no price feed.
    function minFeeWei() public view returns (uint256) {
        return minFee;
    }

    // ================================================================== fees: credit and collect

    /// A router hands over a swap's whole fee: `protocolFee` for the protocol wallet, the rest for
    /// `deployerWallet`. Nothing leaves this contract here.
    function creditFees(address deployerWallet, uint256 protocolFee) external payable onlyRouter {
        uint256 deployerFee = msg.value - protocolFee; // reverts if protocolFee > msg.value
        address protocolWallet = protocolFeeWallet;
        collectable[protocolWallet] += protocolFee;
        collectable[deployerWallet] += deployerFee;
        totalCollectable += msg.value;
        emit FeesCredited(msg.sender, protocolWallet, protocolFee, deployerWallet, deployerFee);
    }

    /// @notice Send `wallet` everything it can collect. Anyone may trigger it; the coins only ever go to `wallet`.
    function collect(address wallet) external nonReentrant returns (uint256 amount) {
        amount = _debit(wallet);
        _sendNative(wallet, amount);
        emit Collected(wallet, wallet, amount);
    }

    /// @notice Send your own collectable balance to `to` — for a fee wallet that cannot receive native coin itself.
    function collectTo(address to) external nonReentrant returns (uint256 amount) {
        if (to == address(0)) revert ZeroAddress();
        amount = _debit(msg.sender);
        _sendNative(to, amount);
        emit Collected(msg.sender, to, amount);
    }

    function _debit(address wallet) private returns (uint256 amount) {
        amount = collectable[wallet];
        collectable[wallet] = 0;
        totalCollectable -= amount;
    }

    // ================================================================== owner

    function transferOwnership(address newOwner) external onlyOwner {
        pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner, newOwner);
    }

    function acceptOwnership() external {
        if (msg.sender != pendingOwner) revert OnlyPendingOwner();
        emit OwnershipTransferred(owner, msg.sender);
        owner = msg.sender;
        pendingOwner = address(0);
    }

    /// Future fees only; what is already collectable stays with the old wallet.
    function setProtocolFeeWallet(address wallet) external onlyOwner {
        if (wallet == address(0) || wallet == address(this)) revert ZeroAddress();
        protocolFeeWallet = wallet;
        emit ProtocolFeeWalletSet(wallet);
    }

    /// The floor, in native wei; at most `MAX_MIN_FEE`. Applies to swaps from the next block on: a user signs a
    /// `maxFee`, so a raise can never take more than that.
    function setMinFee(uint256 value) external onlyOwner {
        if (value > MAX_MIN_FEE) revert AboveCap(value, MAX_MIN_FEE);
        minFee = value;
        emit MinFeeSet(value);
    }

    // ================================================================== internals

    function _sendNative(address to, uint256 amount) private {
        if (amount == 0) return;
        (bool ok,) = to.call{value: amount}("");
        if (!ok) revert NativeTransferFailed();
    }

    /// OpenZeppelin Clones.cloneDeterministic (v4.9).
    function _clone(address impl, bytes32 salt) private returns (address instance) {
        assembly {
            mstore(0x00, or(shr(0xe8, shl(0x60, impl)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            mstore(0x20, or(shl(0x78, impl), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(0, 0x09, 0x37, salt)
        }
        if (instance == address(0)) revert DeployFailed();
    }

    /// OpenZeppelin Clones.predictDeterministicAddress (v4.9), deployer = this.
    function _predict(address impl, bytes32 salt) private view returns (address predicted) {
        assembly {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), address())
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), impl)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := keccak256(add(ptr, 0x43), 0x55)
        }
    }
}

/// @title Alphabros router
/// @notice One trader's router. Takes the swap fee, credits the protocol's and the trader's share in the factory,
///         then runs the app's swap calldata through the user's executor.
///
/// @dev The swap path is v1's: the router only ever moves tokens from `msg.sender`, never makes a call whose target
///      or data the caller chose, measures `tokenOut` on the caller's balance against `minOut`, and enforces a
///      deadline. The owner's only power is this router's fee wallet; the fee rate is fixed at creation.
contract AlphabrosRouter {
    AlphabrosRouterFactory public immutable FACTORY;
    /// WETH / WBNB: worth exactly its amount in the native coin, so a swap with it on either side is valued here.
    address public immutable WRAPPED_NATIVE;
    /// ERC-20 that shares the native balance (Arc's USDC), or `address(0)`.
    address public immutable NATIVE_MIRROR;
    /// Multiplier from the mirror's units to native wei (1e12 for Arc's 6-decimal USDC); 0 without a mirror.
    uint256 public immutable MIRROR_SCALE;

    /// Protocol fee: 0.25% of the trade. Fixed forever.
    uint256 public constant PROTOCOL_FEE_BPS = 25;
    /// Most a trader can add: 0.25% of the trade. Fixed forever.
    uint256 public constant MAX_TRADER_FEE_BPS = 25;
    uint256 internal constant BPS = 10_000;

    address internal constant NATIVE = address(0);

    struct Swap {
        /// What the caller pays in. Pulled from the caller into their executor.
        address tokenIn;
        uint256 amountIn;
        /// What the caller must end up with, and at least how much of it.
        address tokenOut;
        uint256 minOut;
        /// Run in order by the caller's executor, with the executor as `msg.sender`.
        AlphabrosSwapExecutor.Call[] calls;
        /// Intermediate tokens the route passes through the executor; a leftover of any reverts the swap.
        address[] hops;
        /// Unix time after which the swap reverts. Zero always reverts.
        uint256 deadline;
    }

    address public owner;
    address public pendingOwner;
    /// Receives this router's share of every fee.
    address public feeWallet;
    /// This router's fee on top of the protocol's, in basis points (0 to 25). Set once at creation; no setter.
    uint256 public traderFeeBps;

    bool private _initialized;
    uint256 private _locked; // 0 or 1 = unlocked, 2 = locked (clones start at 0)

    event FeePaid(address indexed user, uint256 protocolFee, uint256 deployerFee);
    event FeeRefunded(address indexed user, uint256 amount);
    event Executed(address indexed user, address indexed tokenIn, address indexed tokenOut, uint256 amountIn, uint256 amountOut);
    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    event FeeWalletSet(address wallet);
    event TraderFeeSet(uint256 traderFeeBps);

    error AlreadyInitialized();
    error OnlyOwner();
    error OnlyPendingOwner();
    error ZeroAddress();
    error AboveCap(uint256 value, uint256 cap);
    error WrongValue();
    error SameToken();
    error ZeroMinOut();
    error Expired();
    error FeeTooLow(uint256 fee, uint256 minFee);
    /// Neither side of the swap is the native coin, the wrapped native coin or the mirror, so it cannot be priced.
    error UnpricedPair();
    error InsufficientOutput(uint256 received, uint256 minOut);
    error TokenTransferFailed();
    error RefundFailed();
    error Reentrancy();

    modifier onlyOwner() {
        if (msg.sender != owner) revert OnlyOwner();
        _;
    }

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

    /// The implementation, deployed by the factory. It is locked; only clones are ever initialized.
    constructor(address wrappedNative, address nativeMirror) {
        FACTORY = AlphabrosRouterFactory(msg.sender);
        WRAPPED_NATIVE = wrappedNative;
        NATIVE_MIRROR = nativeMirror;
        MIRROR_SCALE = nativeMirror == address(0) ? 0 : 10 ** (18 - IAbERC20Balance(nativeMirror).decimals());
        _initialized = true;
    }

    /// Called once by the factory, in the same transaction that creates the clone.
    function initialize(address owner_, address feeWallet_, uint256 traderFeeBps_) external {
        if (msg.sender != address(FACTORY) || _initialized) revert AlreadyInitialized();
        _initialized = true;
        owner = owner_;
        emit OwnershipTransferred(address(0), owner_);
        _setFeeWallet(feeWallet_);
        _setTraderFeeBps(traderFeeBps_);
    }

    /// @notice This router's total fee rate: the protocol's 0.25% plus the trader's, in basis points (25 to 50).
    function totalFeeBps() public view returns (uint256) {
        return PROTOCOL_FEE_BPS + traderFeeBps;
    }

    /// @notice The floor every fee must reach, in native wei (the factory's `minFee`).
    function minFeeWei() external view returns (uint256) {
        return FACTORY.minFeeWei();
    }

    /// @notice The fee to send for a trade worth `nativeValue` wei of the native coin:
    ///         max(floor, nativeValue x totalFeeBps), rounded up. Apps value token trades off-chain and pass the
    ///         native-coin equivalent here.
    function quoteFee(uint256 nativeValue) external view returns (uint256) {
        uint256 floor = FACTORY.minFeeWei();
        uint256 pct = _pct(nativeValue, totalFeeBps());
        return pct > floor ? pct : floor;
    }

    /// @notice `user`'s executor (shared by every router of this factory).
    function executorOf(address user) external view returns (address) {
        return FACTORY.executorOf(user);
    }

    /// @notice Run the swap, paying at most `maxFee` in the native coin.
    /// @dev `msg.value` must equal `maxFee` plus `amountIn` if `tokenIn` is native.
    ///      Every swap must have the native coin, the wrapped native coin (WETH / WBNB) or the native mirror on at
    ///      least one side (`UnpricedPair` otherwise), so the contract can always value the trade itself. The fee is
    ///      settled after the swap at exactly max(floor, input x rate, actual output x rate); the rest of `maxFee`
    ///      is refunded in the same transaction. No front-end can charge more than that, and a fill better than
    ///      quoted costs a little more fee instead of reverting, as long as it stays within `maxFee`. It reverts
    ///      only if that exact fee is above `maxFee`. The charged fee splits in proportion: the protocol gets
    ///      fee x 25 / totalFeeBps(), this router's fee wallet the rest.
    function execute(Swap calldata swap, uint256 maxFee) external payable nonReentrant returns (uint256 amountOut) {
        if (_sameAsset(swap.tokenIn, swap.tokenOut)) revert SameToken();
        if (!_priced(swap.tokenIn) && !_priced(swap.tokenOut)) revert UnpricedPair();
        if (swap.minOut == 0) revert ZeroMinOut();
        if (block.timestamp > swap.deadline) revert Expired();
        if (msg.value != maxFee + (swap.tokenIn == NATIVE ? swap.amountIn : 0)) revert WrongValue();

        // Fail fast on what is already known: the floor and the percentage of a priced input.
        uint256 totalBps = totalFeeBps();
        uint256 need = _max(FACTORY.minFeeWei(), _pct(_nativeValue(swap.tokenIn, swap.amountIn), totalBps));
        if (maxFee < need) revert FeeTooLow(maxFee, need);

        amountOut = _run(swap);

        // Settle at the exact fee: the actual output's percentage may be above the input's.
        uint256 charged = _max(need, _pct(_nativeValue(swap.tokenOut, amountOut), totalBps));
        if (charged > maxFee) revert FeeTooLow(maxFee, charged);
        _creditFee(charged, totalBps);
        if (maxFee > charged) _refund(maxFee - charged);

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

    /// Credits `fee` in the factory, split in proportion; never held here, never pushed to a wallet.
    function _creditFee(uint256 fee, uint256 totalBps) private {
        uint256 protocolFee = fee * PROTOCOL_FEE_BPS / totalBps;
        FACTORY.creditFees{value: fee}(feeWallet, protocolFee);
        emit FeePaid(msg.sender, protocolFee, fee - protocolFee);
    }

    /// The unused part of `maxFee`, back to the caller in the same transaction.
    function _refund(uint256 amount) private {
        (bool ok,) = msg.sender.call{value: amount}("");
        if (!ok) revert RefundFailed();
        emit FeeRefunded(msg.sender, amount);
    }

    /// Moves the input into the caller's executor, runs the calls, and returns how much tokenOut the caller got.
    function _run(Swap calldata swap) private returns (uint256 amountOut) {
        AlphabrosSwapExecutor executor = AlphabrosSwapExecutor(payable(FACTORY.executorFor(msg.sender)));

        // tokenOut already in the executor is the caller's from before: return it first, so the balance delta
        // below counts only this swap's output.
        if (_holds(address(executor), swap.tokenOut)) executor.returnHeld(swap.tokenOut, msg.sender);

        uint256 before = _balanceOf(swap.tokenOut, msg.sender);

        uint256 nativeIn;
        if (swap.tokenIn == NATIVE) {
            nativeIn = swap.amountIn;
        } else if (swap.amountIn != 0) {
            _transferFrom(swap.tokenIn, msg.sender, address(executor), swap.amountIn);
        }

        executor.run{value: nativeIn}(swap.calls, msg.sender, swap.tokenIn, swap.tokenOut, swap.hops);

        amountOut = _balanceOf(swap.tokenOut, msg.sender) - before;
        if (amountOut < swap.minOut) revert InsufficientOutput(amountOut, swap.minOut);
    }

    // ------------------------------------------------------------------ owner

    function transferOwnership(address newOwner) external onlyOwner {
        pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner, newOwner);
    }

    function acceptOwnership() external {
        if (msg.sender != pendingOwner) revert OnlyPendingOwner();
        emit OwnershipTransferred(owner, msg.sender);
        owner = msg.sender;
        pendingOwner = address(0);
    }

    /// Future fees only; what is already collectable stays with the old wallet.
    function setFeeWallet(address wallet) external onlyOwner {
        _setFeeWallet(wallet);
    }

    /// The factory itself would be a wallet nobody can collect for.
    function _setFeeWallet(address wallet) private {
        if (wallet == address(0) || wallet == address(FACTORY)) revert ZeroAddress();
        feeWallet = wallet;
        emit FeeWalletSet(wallet);
    }

    function _setTraderFeeBps(uint256 value) private {
        if (value > MAX_TRADER_FEE_BPS) revert AboveCap(value, MAX_TRADER_FEE_BPS);
        traderFeeBps = value;
        emit TraderFeeSet(value);
    }

    // ------------------------------------------------------------------ internals

    /// `amount` of `token` in native wei when the contract can value it itself: the native coin, its mirror, or
    /// the wrapped native coin (1:1, it is redeemable for exactly that). 0 for any other token, whose value the app
    /// prices off-chain. The mirror is checked first: on Arc mainnet the wrapped native IS the 6-decimal mirror.
    function _nativeValue(address token, uint256 amount) private view returns (uint256) {
        if (token == NATIVE) return amount;
        if (token == NATIVE_MIRROR && NATIVE_MIRROR != address(0)) return amount * MIRROR_SCALE;
        if (token == WRAPPED_NATIVE) return amount;
        return 0;
    }

    /// Whether the contract can value `token` itself: the native coin, the wrapped native coin or the mirror.
    function _priced(address token) private view returns (bool) {
        return token == NATIVE || token == WRAPPED_NATIVE || (NATIVE_MIRROR != address(0) && token == NATIVE_MIRROR);
    }

    function _max(uint256 x, uint256 y) private pure returns (uint256) {
        return x > y ? x : y;
    }

    /// `amount` x `bps` / 10,000, rounded up.
    function _pct(uint256 amount, uint256 bps) private pure returns (uint256) {
        return (amount * bps + BPS - 1) / BPS;
    }

    function _sameAsset(address a, address b) private view returns (bool) {
        if (a == b) return true;
        address m = NATIVE_MIRROR;
        return m != address(0) && ((a == NATIVE && b == m) || (a == m && b == NATIVE));
    }

    /// Whether `who` holds any `token` (for the native mirror, any native coin too).
    function _holds(address who, address token) private view returns (bool) {
        if (_balanceOf(token, who) != 0) return true;
        return token != NATIVE && token == NATIVE_MIRROR && who.balance != 0;
    }

    function _balanceOf(address token, address who) private view returns (uint256) {
        return token == NATIVE ? who.balance : IAbERC20Balance(token).balanceOf(who);
    }

    /// Tolerates tokens that return nothing (USDT); rejects `false` and codeless tokens.
    function _transferFrom(address token, address from, address to, uint256 amount) private {
        (bool ok, bytes memory ret) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, amount));
        if (!ok || token.code.length == 0 || (ret.length != 0 && !abi.decode(ret, (bool)))) {
            revert TokenTransferFailed();
        }
    }
}

/// @title Alphabros swap executor
/// @notice One user's executor: runs that user's swap calls for any router of its factory, then hands the output
///         and unspent input back to that user. EIP-1167 clone per user, deployed by the factory.
///
/// @dev Same guarantees as v1's executor: a route completes or reverts (`RouteIncomplete` on a leftover
///      intermediate — listed hops, wrapped native, native when no end is native, the native mirror counted as
///      native); every allowance its calls granted is reset to 0 and read back (the swap reverts otherwise);
///      nobody should ever approve it. It stores its
///      user and refuses to run or pay out for anyone else, even if a router passed a different address.
contract AlphabrosSwapExecutor {
    struct Call {
        address target;
        uint256 value;
        bytes data;
    }

    AlphabrosRouterFactory public immutable FACTORY;
    address public immutable WRAPPED_NATIVE;
    address public immutable NATIVE_MIRROR;

    bytes4 private constant APPROVE = 0x095ea7b3;
    bytes4 private constant INCREASE_ALLOWANCE = 0x39509351;
    bytes4 private constant ALLOWANCE = 0xdd62ed3e;

    /// The one user this executor serves. Set once by the factory.
    address public user;

    error OnlyFactory();
    error OnlyRouter();
    error WrongUser();
    error CallFailed(uint256 index, bytes reason);
    error RouteIncomplete(address token, uint256 leftover);
    error SweepFailed();
    error AllowanceNotReset(address token, address spender);

    constructor(address wrappedNative, address nativeMirror) {
        FACTORY = AlphabrosRouterFactory(msg.sender);
        WRAPPED_NATIVE = wrappedNative;
        NATIVE_MIRROR = nativeMirror;
        user = address(1); // the implementation serves nobody
    }

    receive() external payable {}

    function initialize(address user_) external {
        if (msg.sender != address(FACTORY) || user != address(0)) revert OnlyFactory();
        user = user_;
    }

    function run(Call[] calldata calls, address user_, address tokenIn, address tokenOut, address[] calldata hops)
        external
        payable
    {
        if (!FACTORY.isRouter(msg.sender)) revert OnlyRouter();
        if (user_ != user) revert WrongUser();

        address m = NATIVE_MIRROR;
        bool nativeEnd = tokenIn == address(0) || tokenOut == address(0)
            || (m != address(0) && (tokenIn == m || tokenOut == m));

        uint256 n = hops.length;
        address[] memory mid = new address[](n + 2);
        uint256[] memory held = new uint256[](n + 2);
        for (uint256 i; i < n; ++i) {
            mid[i] = hops[i];
        }
        mid[n] = WRAPPED_NATIVE;
        mid[n + 1] = address(0);
        for (uint256 i; i < n + 2; ++i) {
            bool isNativeAsset = mid[i] == address(0) || (m != address(0) && mid[i] == m);
            if (mid[i] == tokenIn || mid[i] == tokenOut || (nativeEnd && isNativeAsset)) mid[i] = address(1);
            else held[i] = _balance(mid[i]);
        }

        for (uint256 i; i < calls.length; ++i) {
            Call calldata c = calls[i];
            (bool ok, bytes memory ret) = c.target.call{value: c.value}(c.data);
            if (!ok) revert CallFailed(i, ret);
        }

        _resetAllowances(calls);

        for (uint256 i; i < n + 2; ++i) {
            if (mid[i] == address(1)) continue;
            uint256 bal = _balance(mid[i]);
            if (bal > held[i]) revert RouteIncomplete(mid[i], bal - held[i]);
        }

        _sweep(tokenOut, user_);
        _sweep(tokenIn, user_);
        if (nativeEnd) _sweep(address(0), user_);
    }

    /// Before a swap's balance snapshot: whatever of `token` this executor already holds is the user's from
    /// before (a leftover, a stray transfer). It goes back now, so it cannot be counted as the new swap's output.
    /// For the native mirror (Arc's USDC) the sub-unit native remainder follows too. Only for this executor's own user.
    function returnHeld(address token, address to) external {
        if (!FACTORY.isRouter(msg.sender)) revert OnlyRouter();
        if (to != user) revert WrongUser();
        _sweep(token, to);
        if (token != address(0) && token == NATIVE_MIRROR) _sweep(address(0), to);
    }

    /// This executor's balance of each token back to its user. Only the factory calls it (`recover`).
    function recover(address[] calldata tokens) external {
        if (msg.sender != address(FACTORY)) revert OnlyFactory();
        address to = user;
        for (uint256 i; i < tokens.length; ++i) {
            _sweep(tokens[i], to);
        }
    }

    /// Zeroes every allowance the calls granted, and proves it: `approve(spender, 0)` must succeed (a `false`
    /// return counts as a failure) and `allowance` must then read 0, or the whole swap reverts with
    /// `AllowanceNotReset`. Any call whose data starts with approve / increaseAllowance counts, whatever bytes
    /// follow the two arguments. A token that refuses approve(0) can only be routed with transfer-style calldata
    /// (prefund the venue with `transfer`), never with an approve.
    function _resetAllowances(Call[] calldata calls) private {
        for (uint256 i; i < calls.length; ++i) {
            bytes calldata d = calls[i].data;
            if (d.length < 68) continue;
            bytes4 sel = bytes4(d[:4]);
            if (sel != APPROVE && sel != INCREASE_ALLOWANCE) continue;
            address token = calls[i].target;
            address spender = address(uint160(uint256(bytes32(d[4:36]))));
            (bool ok, bytes memory ret) = token.call(abi.encodeWithSelector(APPROVE, spender, 0));
            // No return data (USDT) is success; otherwise it must be exactly `true`.
            if (!ok || (ret.length != 0 && (ret.length < 32 || abi.decode(ret, (uint256)) != 1))) {
                revert AllowanceNotReset(token, spender);
            }
            (ok, ret) = token.staticcall(abi.encodeWithSelector(ALLOWANCE, address(this), spender));
            // Fail closed: the readback must succeed and return exactly 0. A token whose allowance() reverts or
            // returns malformed data cannot prove the reset, so the swap reverts.
            if (!ok || ret.length < 32 || abi.decode(ret, (uint256)) != 0) revert AllowanceNotReset(token, spender);
        }
    }

    function _balance(address token) private view returns (uint256) {
        if (token == address(0)) return address(this).balance;
        if (token == address(1)) return 0;
        return IAbERC20Balance(token).balanceOf(address(this));
    }

    function _sweep(address token, address to) private {
        uint256 bal = _balance(token);
        if (bal == 0) return;
        if (token == address(0)) {
            (bool ok,) = to.call{value: bal}("");
            if (!ok) revert SweepFailed();
        } else {
            (bool ok, bytes memory ret) = token.call(abi.encodeWithSelector(0xa9059cbb, to, bal));
            if (!ok || (ret.length != 0 && !abi.decode(ret, (bool)))) revert SweepFailed();
        }
    }
}

interface IAbERC20Balance {
    function balanceOf(address) external view returns (uint256);
    function decimals() external view returns (uint8);
}

Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.