Skip to content
Verified contractExactMIT

FedoraRouter

Address0xc69762f183a4df729039fbc1e6437a63d1ca9ff8
Balance

0 ETH

 

Transactions

10

 

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
paris
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,409,747
Creation transaction
0x7caad752b7…9a63aea703

src/FedoraRouter.sol

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

/*//////////////////////////////////////////////////////////////////////////////
    FedoraRouter — non-custodial fee-collecting swap router        PRE-AUDIT DRAFT
    ----------------------------------------------------------------------------
    Takes Fedora's fee off the top of the FULL input, forwards the remainder to a
    whitelisted DEX/aggregator, and sweeps the output to the user — all in ONE
    transaction. The contract is an atomic pass-through: it holds funds for ZERO
    time across transactions, so it is NON-CUSTODIAL by construction.

    ONE Solidity contract, CREATE2-deployed to the same address across all ~104
    EVM chains. Captures Fedora's fee in front of every provider, on full
    liquidity, provider-independent.

    SECURITY MODEL / INVARIANTS  (must hold — enforced by tests + external audit):
      1. ATOMIC PASS-THROUGH — every entrypoint sweeps all input + output to the
         user before returning; step 6 asserts no input residue remains.
      2. FEE on the FULL input, capped at MAX_FEE_BPS — a bug can never overcharge.
      3. WHITELISTED targets only — the arbitrary `target.call(swapData)` is the #1
         risk surface, so only owner-approved DEX/aggregator routers are callable.
      4. EXACT approve + reset to 0 after every call — no dangling allowance.
      5. nonReentrant on the swap path.
      Blast radius of a malicious/buggy target is bounded to THIS swap's input
      (approved exactly, reset after); the router never holds funds between calls.

    DONE since first draft: swapETH native-ETH input; Pausable guardian kill-switch
      (owner+guardian pause, owner-only unpause); rescue events.

    NOT DONE BEFORE MAINNET (tracked):
      - External audit / contest (Code4rena / Sherlock) + Immunefi bounty.
      - Fee-on-transfer source token handling (this draft assumes standard ERC-20).
      - Multi-recipient `{recipient,bps}[]` fee split — future (interface designed
        for it; v1 ships single-recipient).
      - On-chain fee enforcement — feeBps is caller-supplied, so a direct caller can
        set it to 0 (revenue leak, NOT a fund-safety issue). Signed-params design in
        AUDIT_SCOPE.md if/when worth it.
      - Owner -> multisig + timelock before mainnet (operational, not code).
//////////////////////////////////////////////////////////////////////////////*/

interface IERC20 {
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function transfer(address to, uint256 amount) external returns (bool);
    function approve(address spender, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
}

contract FedoraRouter {
    // ─── Admin state ──────────────────────────────────────────────────────────
    address public owner;
    address public pendingOwner;                 // 2-step ownership transfer (must acceptOwnership)
    address public feeRecipient;                 // v1: single recipient (split = future)
    address public guardian;                     // hot key: may pause (incident response), may NOT unpause
    uint16  public constant MAX_FEE_BPS = 100;   // 1.00% hard cap (cannot overcharge)
    bool    public paused;                        // kill switch — blocks swaps; rescue still works
    mapping(address => bool) public allowedTargets;
    mapping(address => uint256) public maxInPerToken; // per-token input cap (0 = unlimited) — bounds blast radius pre-audit
    uint256 public maxInEth;                          // native-ETH input cap (0 = unlimited)

    // ─── Guards ───────────────────────────────────────────────────────────────
    uint256 private _lock = 1;
    modifier nonReentrant()  { require(_lock == 1, "REENTRANCY"); _lock = 2; _; _lock = 1; }
    modifier onlyOwner()     { require(msg.sender == owner, "NOT_OWNER"); _; }
    modifier whenNotPaused() { require(!paused, "PAUSED"); _; }

    // ─── Events ───────────────────────────────────────────────────────────────
    event Swapped(
        address indexed user, address indexed tokenIn, address indexed tokenOut,
        uint256 amountIn, uint256 fee, uint256 amountOut, address target
    );
    event Bridged(
        address indexed user, address indexed tokenIn, address indexed target,
        uint256 amountIn, uint256 fee
    );
    event TargetSet(address indexed target, bool allowed);
    event FeeRecipientSet(address indexed recipient);
    event OwnerSet(address indexed owner);
    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
    event GuardianSet(address indexed guardian);
    event Paused(address indexed by);
    event Unpaused(address indexed by);
    event Rescued(address indexed token, address indexed to, uint256 amount); // token == address(0) -> native ETH
    event MaxInSet(address indexed token, uint256 amount);
    event MaxInEthSet(uint256 amount);

    // `_owner` is the ONLY constructor arg so the CREATE2 address is identical on
    // every EVM chain. feeRecipient varies per chain (different fee wallets), so
    // it is NOT a constructor arg (that would shift the deployed address) — it's
    // set per-chain AFTER deploy via setFeeRecipient(). owner is explicit (NOT
    // msg.sender) because CREATE2 deploys through a proxy, whose address would
    // otherwise become the owner. feeRecipient defaults to owner = fail-closed
    // (the fee can never go to address(0) before it's configured).
    constructor(address _owner) {
        require(_owner != address(0), "ZERO_OWNER");
        owner = _owner;
        feeRecipient = _owner;
        emit OwnerSet(_owner);
        emit FeeRecipientSet(_owner);
    }

    // ─── Admin setters ─────────────────────────────────────────────────────────
    // 2-step ownership: a typo'd new owner can't brick admin — the new owner must accept.
    function transferOwnership(address o) external onlyOwner { require(o != address(0), "ZERO"); pendingOwner = o; emit OwnershipTransferStarted(owner, o); }
    function acceptOwnership() external { require(msg.sender == pendingOwner, "NOT_PENDING_OWNER"); emit OwnerSet(pendingOwner); owner = pendingOwner; pendingOwner = address(0); }
    function setFeeRecipient(address r) external onlyOwner { require(r != address(0), "ZERO"); feeRecipient = r; emit FeeRecipientSet(r); }
    function setTarget(address t, bool a) external onlyOwner { allowedTargets[t] = a; emit TargetSet(t, a); }
    function setTargets(address[] calldata ts, bool a) external onlyOwner {
        for (uint256 i; i < ts.length; ++i) { allowedTargets[ts[i]] = a; emit TargetSet(ts[i], a); }
    }
    function setGuardian(address g) external onlyOwner { guardian = g; emit GuardianSet(g); }

    // Kill switch for incident response. Owner OR guardian (hot key) can pause;
    // only owner (cold key) can resume. A compromised guardian can only DoS, never steal.
    function pause() external {
        require(msg.sender == owner || msg.sender == guardian, "NOT_AUTHORIZED");
        paused = true;
        emit Paused(msg.sender);
    }
    function unpause() external onlyOwner { paused = false; emit Unpaused(msg.sender); }

    // Per-swap input caps — bound the most a single transaction can risk while
    // running pre-audit. 0 = unlimited (default). Lift to 0 once audited.
    function setMaxIn(address token, uint256 amount) external onlyOwner { maxInPerToken[token] = amount; emit MaxInSet(token, amount); }
    function setMaxInEth(uint256 amount) external onlyOwner { maxInEth = amount; emit MaxInEthSet(amount); }

    /*//////////////////////////////////////////////////////////////////////////
        SWAP — ERC-20 input. Fedora's fee taken off the FULL input, in front.
        @param tokenIn    source ERC-20
        @param amountIn   FULL input (fee is a % of THIS)
        @param feeBps     Fedora fee, bps (<= MAX_FEE_BPS)
        @param tokenOut   expected output (address(0) = native ETH out)
        @param minOut     slippage floor on output delivered to `recipient`
        @param recipient  receives the output
        @param target     WHITELISTED DEX/aggregator router
        @param swapData   pre-built calldata for `target`; MUST send output to
                          THIS contract so the router can deliver + check minOut.
    //////////////////////////////////////////////////////////////////////////*/
    function swapERC20(
        address tokenIn,
        uint256 amountIn,
        uint16  feeBps,
        address tokenOut,
        uint256 minOut,
        address recipient,
        address target,
        bytes calldata swapData
    ) external whenNotPaused nonReentrant returns (uint256 amountOut) {
        require(allowedTargets[target], "TARGET_NOT_ALLOWED");
        require(feeBps <= MAX_FEE_BPS, "FEE_TOO_HIGH");
        require(amountIn > 0, "ZERO_IN");
        require(recipient != address(0), "ZERO_RECIPIENT");
        require(target != tokenIn && target != tokenOut, "TARGET_IS_TOKEN"); // defense-in-depth vs whitelist misconfig
        require(maxInPerToken[tokenIn] == 0 || amountIn <= maxInPerToken[tokenIn], "OVER_CAP");

        // 1. Pull the FULL input from the user.
        _pull(tokenIn, msg.sender, amountIn);

        // 2. Fee on the FULL amount → feeRecipient (in the input token).
        uint256 fee = (amountIn * feeBps) / 10_000;
        if (fee > 0) _send(tokenIn, feeRecipient, fee);

        // 3. Forward the remainder to the target. Exact approve, call, reset.
        uint256 swapAmount = amountIn - fee;
        _approve(tokenIn, target, swapAmount);
        (bool ok, ) = target.call(swapData);
        require(ok, "SWAP_FAILED");
        _approve(tokenIn, target, 0);

        // 4. Deliver output to recipient + slippage check.
        amountOut = (tokenOut == address(0))
            ? address(this).balance
            : IERC20(tokenOut).balanceOf(address(this));
        require(amountOut >= minOut, "INSUFFICIENT_OUTPUT");
        if (amountOut > 0) _send(tokenOut, recipient, amountOut);

        // 5. Refund any leftover input dust to the user (some DEXs underspend).
        uint256 dust = IERC20(tokenIn).balanceOf(address(this));
        if (dust > 0) _send(tokenIn, msg.sender, dust);

        // 6. NON-CUSTODIAL INVARIANT — nothing of this swap's input remains.
        require(IERC20(tokenIn).balanceOf(address(this)) == 0, "LEFTOVER_IN");

        emit Swapped(msg.sender, tokenIn, tokenOut, amountIn, fee, amountOut, target);
    }

    /*//////////////////////////////////////////////////////////////////////////
        SWAP — native ETH input. Same model: fee off the FULL ETH input, in front.
        @param tokenOut  ERC-20 to receive (must be non-zero; ETH→ETH unsupported)
        @param swapData  target calldata; for Uniswap SwapRouter02 set tokenIn=WETH
                         and the router forwards ETH as value (the router wraps it).
                         MUST send output to THIS contract.
    //////////////////////////////////////////////////////////////////////////*/
    function swapETH(
        uint16  feeBps,
        address tokenOut,
        uint256 minOut,
        address recipient,
        address target,
        bytes calldata swapData
    ) external payable whenNotPaused nonReentrant returns (uint256 amountOut) {
        require(allowedTargets[target], "TARGET_NOT_ALLOWED");
        require(feeBps <= MAX_FEE_BPS, "FEE_TOO_HIGH");
        require(msg.value > 0, "ZERO_IN");
        require(recipient != address(0), "ZERO_RECIPIENT");
        require(tokenOut != address(0), "ETH_OUT_UNSUPPORTED");
        require(target != tokenOut, "TARGET_IS_TOKEN"); // defense-in-depth vs whitelist misconfig
        require(maxInEth == 0 || msg.value <= maxInEth, "OVER_CAP");

        // 1. Fee on the FULL ETH input → feeRecipient.
        uint256 fee = (msg.value * feeBps) / 10_000;
        if (fee > 0) _send(address(0), feeRecipient, fee);

        // 2. Forward remaining ETH to the target (DEX wraps + swaps).
        uint256 swapAmount = msg.value - fee;
        (bool ok, ) = target.call{value: swapAmount}(swapData);
        require(ok, "SWAP_FAILED");

        // 3. Deliver tokenOut to recipient + slippage check.
        amountOut = IERC20(tokenOut).balanceOf(address(this));
        require(amountOut >= minOut, "INSUFFICIENT_OUTPUT");
        if (amountOut > 0) _send(tokenOut, recipient, amountOut);

        // 4. Refund any leftover ETH to the user (pass-through → router keeps nothing).
        uint256 dust = address(this).balance;
        if (dust > 0) _send(address(0), msg.sender, dust);

        emit Swapped(msg.sender, address(0), tokenOut, msg.value, fee, amountOut, target);
    }

    /*//////////////////////////////////////////////////////////////////////////
        BRIDGE — cross-chain, ERC-20 source. Fee off the FULL input, in front;
        remainder forwarded to a WHITELISTED bridge/aggregator. The output is
        delivered on the DESTINATION chain by the bridge — the recipient and the
        dest-chain min-out are baked into `bridgeData` — so there is intentionally
        NO source-side output delivery or minOut here. Same non-custodial invariant:
        the router keeps nothing of the input.
        @param tokenIn    source ERC-20
        @param amountIn   FULL input (fee is a % of THIS)
        @param feeBps     Fedora fee, bps (<= MAX_FEE_BPS)
        @param target     WHITELISTED bridge/aggregator router
        @param bridgeData pre-built calldata for `target`; MUST pull `swapAmount`
                          (== amountIn - fee) from THIS contract and deliver to the
                          user on the destination chain.
    //////////////////////////////////////////////////////////////////////////*/
    function swapBridgeERC20(
        address tokenIn,
        uint256 amountIn,
        uint16  feeBps,
        address target,
        bytes calldata bridgeData
    ) external whenNotPaused nonReentrant {
        require(allowedTargets[target], "TARGET_NOT_ALLOWED");
        require(feeBps <= MAX_FEE_BPS, "FEE_TOO_HIGH");
        require(amountIn > 0, "ZERO_IN");
        require(target != tokenIn, "TARGET_IS_TOKEN"); // defense-in-depth vs whitelist misconfig
        require(maxInPerToken[tokenIn] == 0 || amountIn <= maxInPerToken[tokenIn], "OVER_CAP");

        // 1. Pull the FULL input from the user.
        _pull(tokenIn, msg.sender, amountIn);

        // 2. Fee on the FULL amount → feeRecipient (in the input token).
        uint256 fee = (amountIn * feeBps) / 10_000;
        if (fee > 0) _send(tokenIn, feeRecipient, fee);

        // 3. Forward the remainder to the bridge. Exact approve, call, reset.
        uint256 swapAmount = amountIn - fee;
        _approve(tokenIn, target, swapAmount);
        (bool ok, ) = target.call(bridgeData);
        require(ok, "BRIDGE_FAILED");
        _approve(tokenIn, target, 0);

        // 4. Refund any input the bridge UNDER-pulled (some pull less than approved).
        uint256 dust = IERC20(tokenIn).balanceOf(address(this));
        if (dust > 0) _send(tokenIn, msg.sender, dust);

        // 5. NON-CUSTODIAL INVARIANT — nothing of this swap's input remains. The
        //    output is on the DEST chain (not this contract), so there is nothing to
        //    deliver or check here; the bridge enforces its own dest-chain min-out.
        require(IERC20(tokenIn).balanceOf(address(this)) == 0, "LEFTOVER_IN");

        emit Bridged(msg.sender, tokenIn, target, amountIn, fee);
    }

    /*//////////////////////////////////////////////////////////////////////////
        BRIDGE — cross-chain, native-ETH source. Same model: fee off the FULL ETH
        input, in front; `swapAmount` ETH forwarded to the whitelisted bridge as
        value. Output delivered on the dest chain (per `bridgeData`).
    //////////////////////////////////////////////////////////////////////////*/
    function swapBridgeETH(
        uint16  feeBps,
        address target,
        bytes calldata bridgeData
    ) external payable whenNotPaused nonReentrant {
        require(allowedTargets[target], "TARGET_NOT_ALLOWED");
        require(feeBps <= MAX_FEE_BPS, "FEE_TOO_HIGH");
        require(msg.value > 0, "ZERO_IN");
        require(maxInEth == 0 || msg.value <= maxInEth, "OVER_CAP");

        // 1. Fee on the FULL ETH input → feeRecipient.
        uint256 fee = (msg.value * feeBps) / 10_000;
        if (fee > 0) _send(address(0), feeRecipient, fee);

        // 2. Forward the remaining ETH to the bridge.
        uint256 swapAmount = msg.value - fee;
        (bool ok, ) = target.call{value: swapAmount}(bridgeData);
        require(ok, "BRIDGE_FAILED");

        // 3. Refund any ETH the bridge under-pulled (pass-through → router keeps 0).
        uint256 dust = address(this).balance;
        if (dust > 0) _send(address(0), msg.sender, dust);

        emit Bridged(msg.sender, address(0), target, msg.value, fee);
    }

    // ─── Rescue (owner) — pass-through means this should never hold funds, but a
    //     malformed swapData edge case must never strand user money. ────────────
    function rescueERC20(address token, address to, uint256 amount) external onlyOwner { _send(token, to, amount); emit Rescued(token, to, amount); }
    function rescueETH(address to, uint256 amount) external onlyOwner {
        (bool ok, ) = to.call{value: amount}(""); require(ok, "ETH_RESCUE_FAILED");
        emit Rescued(address(0), to, amount);
    }

    receive() external payable {}

    /*  ─── Forward: fee + plain transfer, ONE signature ────────────────────────

        THE PROBLEM THESE SOLVE. Deposit-address providers (ChangeNow, Exolix,
        SimpleSwap, StealthEX, Trocador) take funds at an address THEY generate
        per order and settle off-chain. There is no contract to call and no
        affiliate parameter that routes a fee to an address we control, so the
        only way to charge a Fedora Fee was a Pattern-B skim: a SEPARATE transfer
        before the deposit. On EVM that is a second wallet popup, which is why
        ChangeNow and Trocador have the skim switched off entirely — the UX cost
        was judged worse than the revenue.

        That was a false choice. Routing the deposit THROUGH the router collapses
        both legs into one transaction: the fee is split off on-chain and the
        remainder continues to the provider's deposit address. One signature, fee
        guaranteed, no dependence on any provider's affiliate programme. This is
        how every major aggregator does it.

        WHY NO ALLOWLIST HERE, when bridgeNative/bridgeERC20 require one.
        `allowedTargets` exists to stop the router being made to CALL an arbitrary
        contract with arbitrary calldata. These functions pass NO calldata — the
        forward is a bare value transfer, so there is no call to abuse. That
        matters because a deposit address is generated per order and cannot be
        allowlisted in advance; requiring it would make these unusable for the
        exact case they exist for.

        What remains, and why it is acceptable:
          • A destination with a malicious receive() can re-enter → nonReentrant.
          • A destination that reverts on receipt → the whole tx reverts, the
            user keeps their funds. Fail-closed.
          • A caller could forward to any address → they could do that directly
            from their wallet without us. The router holds nothing between calls,
            so there is nothing to drain.
          • feeBps is caller-supplied but capped at MAX_FEE_BPS, so a bug or a
            hostile caller can never overcharge — only undercharge themselves.

        Pass-through: the router must never retain value. Native dust is swept to
        the caller; the ERC-20 path transfers the exact amounts and keeps none.  */

    /// Native in → fee to feeRecipient, remainder to `destination`. One tx.
    /// @param feeBps      Fedora fee in bps, <= MAX_FEE_BPS.
    /// @param destination Provider's per-order deposit address (EOA, no calldata).
    function forwardNative(uint16 feeBps, address destination)
        external payable whenNotPaused nonReentrant
    {
        require(feeBps <= MAX_FEE_BPS, "FEE_TOO_HIGH");
        require(msg.value > 0, "ZERO_IN");
        require(destination != address(0), "ZERO_DEST");
        require(maxInEth == 0 || msg.value <= maxInEth, "OVER_CAP");

        uint256 fee = (msg.value * feeBps) / 10_000;
        if (fee > 0) _send(address(0), feeRecipient, fee);

        (bool ok, ) = destination.call{value: msg.value - fee}("");
        require(ok, "FORWARD_FAILED");

        // Pass-through guarantee: never retain native value.
        uint256 dust = address(this).balance;
        if (dust > 0) _send(address(0), msg.sender, dust);

        emit Bridged(msg.sender, address(0), destination, msg.value, fee);
    }

    /// ERC-20 in → fee to feeRecipient, remainder to `destination`. One tx
    /// (after the usual one-time approve, same as swapERC20).
    function forwardERC20(address token, uint256 amountIn, uint16 feeBps, address destination)
        external whenNotPaused nonReentrant
    {
        require(feeBps <= MAX_FEE_BPS, "FEE_TOO_HIGH");
        require(amountIn > 0, "ZERO_IN");
        require(destination != address(0), "ZERO_DEST");
        require(token != address(0), "ZERO_TOKEN");
        require(maxInPerToken[token] == 0 || amountIn <= maxInPerToken[token], "OVER_CAP");

        // Measure what actually arrived: fee-on-transfer tokens deliver less than
        // amountIn, and forwarding the nominal figure would revert or overdraw.
        uint256 before = IERC20(token).balanceOf(address(this));
        _pull(token, msg.sender, amountIn);
        uint256 received = IERC20(token).balanceOf(address(this)) - before;
        require(received > 0, "NOTHING_RECEIVED");

        uint256 fee = (received * feeBps) / 10_000;
        if (fee > 0) _send(token, feeRecipient, fee);
        _send(token, destination, received - fee);

        emit Bridged(msg.sender, token, destination, received, fee);
    }

    // ─── Safe transfer helpers (tolerate non-standard ERC-20s + native) ────────
    function _pull(address token, address from, uint256 amount) private {
        (bool ok, bytes memory data) =
            token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, address(this), amount));
        require(ok && (data.length == 0 || abi.decode(data, (bool))), "PULL_FAILED");
    }
    function _send(address token, address to, uint256 amount) private {
        if (token == address(0)) { (bool sent, ) = to.call{value: amount}(""); require(sent, "ETH_SEND_FAILED"); return; }
        (bool ok, bytes memory data) =
            token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, amount));
        require(ok && (data.length == 0 || abi.decode(data, (bool))), "SEND_FAILED");
    }
    function _approve(address token, address spender, uint256 amount) private {
        (bool ok, bytes memory data) =
            token.call(abi.encodeWithSelector(IERC20.approve.selector, spender, amount));
        require(ok && (data.length == 0 || abi.decode(data, (bool))), "APPROVE_FAILED");
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.