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

UniswapXPoolExecutor

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

0 ETH

 

Транзакций

3

 

Компилятор

solc 0.8.24

 

Тот же код

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

 

Подробности

Компилятор
solc 0.8.24+commit.e11b9ed9
Язык
solidity
Оптимизация
Да, 200 прогонов
Версия EVM
cancun
Лицензия
MIT
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 485 253
Транзакция создания
0x78d9c4cbb7…25c6c358bd

src/UniswapXPoolExecutor.sol

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

import {Owned} from "solmate/auth/Owned.sol";
import {ERC20} from "solmate/tokens/ERC20.sol";
import {SafeTransferLib} from "solmate/utils/SafeTransferLib.sol";

import {IReactor, IReactorCallback, ResolvedOrder, SignedOrder} from "./external/IReactor.sol";
import {ISwapRouter02} from "./external/ISwapRouter02.sol";
import {ICurveStableSwap} from "./external/ICurveStableSwap.sol";
import {IV3Pool, IV3Factory} from "./AmmOndoArb.sol";

/**
 * UniswapXPoolExecutor: fills a UniswapX order for an Ondo GM token out of AMM
 * pools instead of Ondo. It makes no Ondo call and needs no Ondo registration.
 * `UniswapXOndoExecutor` keeps every Ondo fill; this is a second address beside
 * it, so it can never be the `exclusiveFiller` of a quote that executor won.
 *
 *   BUY  (USDC or USDT in, GM out): USDT is swapped to USDC on an owner-listed
 *        stable venue, then USDC buys the GM in up to `MAX_LEGS` GM/USDC pools.
 *        Every leg but the last spends its own `amountIn`. The last leg buys
 *        exactly what is still owed, so everything the order did not cost stays
 *        here as USDC, and a pool that moved between the quote and the block
 *        costs margin before it costs the fill.
 *
 *   SELL (GM in, USDC or USDT out): the GM is sold in up to `MAX_LEGS` pools,
 *        the last leg taking whatever is left. A USDT payout sells `stableIn` of
 *        those USDC on the stable venue for at least what the order owes.
 *
 * POOLS. A leg names a V3 factory and a fee tier, never a pool or a token. The
 * factory must be one the owner allowed, and the pool is what that factory
 * answers for (USDC, the order's GM token, fee): so a swap can only reach a pool
 * that factory deployed (Uniswap V3 and its byte-identical forks, the test
 * `AmmOndoArb` version 5 applies), and there is no pool address in the payload
 * to forge. Single-hop GM/USDC pools only.
 *
 * WHAT IT GUARANTEES, whatever the payload says:
 *   - only a whitelisted caller starts a fill, and the reactor callback runs once
 *     per `execute` and only for the reactor;
 *   - a swap callback is paid only while the pool it comes from is mid-swap, once,
 *     in the token that swap sells, and at most the amount armed for it;
 *   - the order's output is covered by what THIS fill bought;
 *   - USDC plus USDT end at least `minProfit` above where they stood before the
 *     reactor moved anything (and above what the order still has to be paid), so no
 *     payload, and no input that arrives short, can spend what earlier fills left
 *     here.
 * A bad split, a moved pool, or an order asking for more than `maxOwed` reverts
 * the whole fill. The most that costs is the gas of a transaction that mined,
 * and these fills are sent to builders only (`bot/src/live.rs`).
 *
 * Builder payment: the same entry point, cap and `BuilderPaid` event as
 * `UniswapXOndoExecutor.executeWithBuilderPayment` (`BUILDER-PAYMENT.md`).
 *
 * Leftovers stay here until the owner rescues them.
 */
contract UniswapXPoolExecutor is IReactorCallback, Owned {
    using SafeTransferLib for ERC20;

    /// @notice One pool: the (USDC, GM, `fee`) pool of an allowed V3 `factory`.
    /// @dev `amountIn` is USDC on a buy and GM on a sell. It must be non-zero on
    ///      every leg but the last, and zero on the last: that leg does the rest.
    struct PoolLeg {
        address factory;
        uint24 fee;
        uint256 amountIn;
    }

    /// @notice Decoded from `callbackData`; built by the bot (`bot/src/pool_source.rs`).
    struct PoolFill {
        PoolLeg[] legs; // 1..MAX_LEGS
        uint256 maxOwed; // the most the order may ask for in the block this lands in
        uint256 minProfit; // USDC + USDT (6dp, counted 1:1) this fill must leave here
        uint8 venue; // stable venue, for a USDT leg only
        uint256 stableIn; // sell paid in USDT: the USDC sold for it; otherwise unused (0)
    }

    /// @notice An owner-listed stable venue. `kind` 0 = not listed. The same struct
    ///         and getter as `UniswapXOndoExecutor`, so the bot reads both alike.
    struct Venue {
        uint8 kind;
        address pool;
        uint24 fee;
        int128 iUsdt;
        int128 iUsdc;
    }

    uint8 internal constant KIND_V3 = 1;
    uint8 internal constant KIND_CURVE = 2;

    /// @dev Pools one fill may split over.
    uint256 internal constant MAX_LEGS = 4;
    /// @dev Venue 0's pool: Uniswap V3 USDC/USDT 0.01%, the deepest stable pool.
    uint24 internal constant STABLE_POOL_FEE = 100;
    /// @dev Gas forwarded with a builder payment; same figure and reasoning as
    ///      `UniswapXOndoExecutor`: the callee is the block producer's choice.
    uint256 internal constant BUILDER_PAYMENT_GAS = 100_000;
    // TickMath bounds: a swap with these limits never stops on price.
    uint160 internal constant MIN_SQRT_RATIO_PLUS_1 = 4295128740;
    uint160 internal constant MAX_SQRT_RATIO_MINUS_1 = 1461446703485210103287273052203988822378723970341;

    // Transient slots (EIP-1153). `PHASE` is the reentrancy lock and the proof that a
    // reactor callback belongs to a running `execute`; `BEFORE` is where the stables
    // stood when that `execute` began; the next three are the swap being paid for and
    // `PAID` is what it took. Every one is back to zero when the call returns.
    uint256 private constant T_PHASE = 0;
    uint256 private constant T_POOL = 1;
    uint256 private constant T_TOKEN = 2;
    uint256 private constant T_MAX = 3;
    uint256 private constant T_PAID = 4;
    uint256 private constant T_BEFORE = 5;
    uint256 private constant IDLE = 0;
    uint256 private constant EXECUTING = 1;
    uint256 private constant CALLED_BACK = 2;

    IReactor public immutable reactor;
    ISwapRouter02 public immutable swapRouter;
    ERC20 public immutable usdt;
    ERC20 public immutable usdc;

    /// @notice Bot wallets (nonce lanes) allowed to submit fills.
    mapping(address => bool) public whitelistedCallers;
    /// @notice V3 factories whose GM/USDC pools a fill may trade.
    mapping(address => bool) public allowedFactory;
    /// @notice Ceiling on ONE fill's builder payment, in wei. 0 (a fresh deploy)
    ///         refuses every non-zero payment; fills keep working, unpaid.
    uint256 public maxBuilderPaymentWei;
    /// @notice Stable venues by id. Id 0 is the built-in V3 0.01% pool.
    mapping(uint8 => Venue) public venues;

    event WhitelistedCallerUpdated(address indexed caller, bool allowed);
    event FactoryUpdated(address indexed factory, bool allowed);
    event VenueSet(uint8 indexed id, uint8 kind, address pool, uint24 fee, int128 iUsdt, int128 iUsdc);
    event StableSwapped(
        bytes32 indexed orderHash, uint8 indexed venue, address tokenIn, uint256 amountIn, uint256 amountOut
    );
    event MaxBuilderPaymentUpdated(uint256 maxWei);
    event BuilderPaid(address indexed builder, uint256 amount);
    /// @notice `profit` is the stable (USDC + USDT) this fill left here.
    event PoolFilled(
        bytes32 indexed orderHash, address indexed gm, bool buy, uint256 amountIn, uint256 owed, uint256 profit
    );

    error NotReactor();
    error NotWhitelistedCaller();
    error NoCallers();
    error ZeroAddress();
    error Reentrancy();
    /// @dev The reactor called back with no `execute` running, or twice in one.
    error NotExecuting();
    /// @dev `legs` is empty, too long, or its amounts do not fit what arrived.
    error BadLegs();
    /// @dev Not exactly one stable side and one token side.
    error UnsupportedOrder();
    /// @dev The order's outputs are in more than one token.
    error UnsupportedOutput();
    /// @dev The order asks for more than the bot sized this fill for: it landed
    ///      earlier in the decay than planned, or inside a rival's exclusivity
    ///      window, where the reactor adds the override. Neither is ever paid.
    error OwedAboveMax();
    error FactoryNotAllowed();
    error PoolNotFound();
    error NotActivePool();
    /// @dev A pool asked for more than the swap was armed with.
    error OverBudget();
    /// @dev The pools delivered less than the order owes.
    error InsufficientOutput();
    /// @dev The stable leg delivered less than its floor.
    error InsufficientSwapOut();
    /// @dev The fill would leave less than `minProfit` of stable here.
    error Unprofitable();
    error UnknownVenue();
    error BadVenue();
    error BuilderPaymentTooLarge();
    error BuilderPaymentFailed();
    error BuilderPaymentMismatch();

    modifier onlyWhitelistedCaller() {
        if (!whitelistedCallers[msg.sender]) revert NotWhitelistedCaller();
        _;
    }

    /// @dev Held across the builder payment too, so nothing it calls can start
    ///      another fill in the same transaction.
    modifier nonReentrant() {
        if (_tget(T_PHASE) != IDLE) revert Reentrancy();
        _tset(T_PHASE, EXECUTING);
        _;
        _tset(T_PHASE, IDLE);
    }

    /// @param _reactor   the UniswapX reactor this address fills for (deploy-time env)
    /// @param _factories V3 factories allowed from the start (more: `setAllowedFactory`)
    constructor(
        address _owner,
        address _reactor,
        address _swapRouter,
        address _usdt,
        address _usdc,
        address[] memory _callers,
        address[] memory _factories
    ) Owned(_owner) {
        if (
            _owner == address(0) || _reactor == address(0) || _swapRouter == address(0) || _usdt == address(0)
                || _usdc == address(0)
        ) revert ZeroAddress();
        if (_callers.length == 0) revert NoCallers();
        reactor = IReactor(_reactor);
        swapRouter = ISwapRouter02(_swapRouter);
        usdt = ERC20(_usdt);
        usdc = ERC20(_usdc);
        for (uint256 i; i < _callers.length; ++i) {
            _setCaller(_callers[i], true);
        }
        for (uint256 i; i < _factories.length; ++i) {
            _setFactory(_factories[i], true);
        }
    }

    /// @notice The `callbackData` layout this contract decodes (`PoolFill`). Read by
    ///         the bot at boot: an address without it is not a pool executor.
    function poolFillVersion() external pure returns (uint8) {
        return 1;
    }

    /// @notice Fill one order through pools. `callbackData` is `abi.encode(PoolFill)`.
    function execute(SignedOrder calldata order, bytes calldata callbackData)
        external
        onlyWhitelistedCaller
        nonReentrant
    {
        _execute(order, callbackData);
    }

    /// @notice `execute`, then `payment` wei to `block.coinbase`, atomically. The
    ///         payment is exactly `msg.value`, so this contract holds no ETH between
    ///         fills and the cap is the whole risk of one call. It is made last: a
    ///         reverting fill pays nothing.
    function executeWithBuilderPayment(SignedOrder calldata order, bytes calldata callbackData, uint256 payment)
        external
        payable
        onlyWhitelistedCaller
        nonReentrant
    {
        if (payment > maxBuilderPaymentWei) revert BuilderPaymentTooLarge();
        if (msg.value != payment) revert BuilderPaymentMismatch();

        _execute(order, callbackData);

        if (payment != 0) {
            // Raw call with a bounded forward: fee recipients are often contracts
            // (a 2300 stipend strands the payment), and an unbounded forward lets a
            // producer-chosen callee burn the transaction.
            (bool paid,) = block.coinbase.call{value: payment, gas: BUILDER_PAYMENT_GAS}("");
            if (!paid) revert BuilderPaymentFailed();
            emit BuilderPaid(block.coinbase, payment);
        }
    }

    /// @dev The stables are counted HERE, before the reactor pulls the swapper's input:
    ///      in the callback the input is already in the balance, and subtracting what the
    ///      order says it is would take a USDT transfer fee out of what earlier fills left.
    function _execute(SignedOrder calldata order, bytes calldata callbackData) private {
        _tset(T_BEFORE, _stables());
        reactor.executeWithCallback(order, callbackData);
        _tset(T_BEFORE, 0);
    }

    /// @notice Reactor callback: the order's input is already here.
    function reactorCallback(ResolvedOrder[] calldata resolvedOrders, bytes calldata callbackData) external override {
        if (msg.sender != address(reactor)) revert NotReactor();
        if (_tget(T_PHASE) != EXECUTING) revert NotExecuting();
        _tset(T_PHASE, CALLED_BACK);

        ResolvedOrder calldata ro = resolvedOrders[0];
        PoolFill memory f = abi.decode(callbackData, (PoolFill));
        if (f.legs.length == 0 || f.legs.length > MAX_LEGS) revert BadLegs();

        (address assetOut, uint256 owed) = _owed(ro);
        if (owed > f.maxOwed) revert OwedAboveMax();
        address assetIn = address(ro.input.token);
        bool buy = _isStable(assetIn);
        if (buy == _isStable(assetOut)) revert UnsupportedOrder();

        if (buy) _buy(ro, f, ERC20(assetOut), owed);
        else _sell(ro, f, ERC20(assetIn), assetOut, owed);

        // THE invariant, whatever the legs did and whatever arrived: stable ends
        // `minProfit` above where it stood before this fill, counting what the reactor
        // is about to pull as already gone.
        uint256 floor = _tget(T_BEFORE) + f.minProfit;
        if (!buy) floor += owed;
        uint256 end = _stables();
        if (end < floor) revert Unprofitable();

        // Exactly what the order owes: the reactor pulls all of it right after this
        // returns, so no allowance outlives the fill.
        ERC20(assetOut).safeApprove(address(reactor), owed);

        emit PoolFilled(ro.hash, buy ? assetOut : assetIn, buy, ro.input.amount, owed, end - floor + f.minProfit);
    }

    /// @dev What the order owes in total: its one output token and the sum of every
    ///      output (a swapper's output plus an interface fee, say).
    function _owed(ResolvedOrder calldata ro) private pure returns (address token, uint256 owed) {
        token = ro.outputs[0].token;
        for (uint256 i; i < ro.outputs.length; ++i) {
            if (ro.outputs[i].token != token) revert UnsupportedOutput();
            owed += ro.outputs[i].amount;
        }
    }

    /// @dev USDC to spend, then every leg but the last at its own size, then the last
    ///      one for exactly what is still owed, out of what is left of the USDC.
    function _buy(ResolvedOrder calldata ro, PoolFill memory f, ERC20 gm, uint256 owed) private {
        uint256 available = ro.input.amount;
        if (address(ro.input.token) == address(usdt)) {
            // No floor here: what a bad stable swap costs comes off the same margin
            // `minProfit` guards.
            available = _stableSwap(ro.hash, f.venue, usdt, usdc, available, 0);
        }

        uint256 gmBefore = gm.balanceOf(address(this));
        uint256 last = f.legs.length - 1;
        uint256 spent;
        for (uint256 i; i < last; ++i) {
            uint256 amountIn = f.legs[i].amountIn;
            if (amountIn == 0 || amountIn > available - spent) revert BadLegs();
            spent += _swap(f.legs[i], usdc, gm, int256(_fits(amountIn)), amountIn);
        }
        if (f.legs[last].amountIn != 0) revert BadLegs();
        uint256 got = gm.balanceOf(address(this)) - gmBefore;
        if (got < owed) {
            _swap(f.legs[last], usdc, gm, -int256(_fits(owed - got)), available - spent);
            got = gm.balanceOf(address(this)) - gmBefore;
        }
        if (got < owed) revert InsufficientOutput();
    }

    /// @dev The delivered GM into the pools, the last leg taking what is left, then the
    ///      owed stable out of the proceeds.
    function _sell(ResolvedOrder calldata ro, PoolFill memory f, ERC20 gm, address assetOut, uint256 owed) private {
        uint256 usdcBefore = usdc.balanceOf(address(this));
        uint256 last = f.legs.length - 1;
        uint256 left = ro.input.amount;
        for (uint256 i; i < last; ++i) {
            uint256 amountIn = f.legs[i].amountIn;
            if (amountIn == 0 || amountIn >= left) revert BadLegs();
            // What the pool TOOK: one that ran out leaves the rest to the last leg.
            left -= _swap(f.legs[i], gm, usdc, int256(_fits(amountIn)), amountIn);
        }
        if (f.legs[last].amountIn != 0) revert BadLegs();
        _swap(f.legs[last], gm, usdc, int256(_fits(left)), left);

        uint256 usdcOut = usdc.balanceOf(address(this)) - usdcBefore;
        if (assetOut == address(usdc)) {
            if (usdcOut < owed) revert InsufficientOutput();
        } else {
            // Sold out of THIS fill's proceeds, for at least what is owed.
            if (f.stableIn == 0 || f.stableIn > usdcOut) revert InsufficientOutput();
            _stableSwap(ro.hash, f.venue, usdc, usdt, f.stableIn, owed);
        }
    }

    /*//////////////////////////////////////////////////////////////
                                POOLS
    //////////////////////////////////////////////////////////////*/

    /// @dev One swap through the pool `leg` names, armed to pay it at most `maxIn` of
    ///      `tokenIn`. `amount` is V3's signed amount: positive sells that much,
    ///      negative buys that much. Returns what the callback paid, not what the pool
    ///      says it took. `tokenIn` and `tokenOut` are always USDC and the order's own
    ///      GM token, never payload.
    function _swap(PoolLeg memory leg, ERC20 tokenIn, ERC20 tokenOut, int256 amount, uint256 maxIn)
        private
        returns (uint256 paid)
    {
        if (!allowedFactory[leg.factory]) revert FactoryNotAllowed();
        address pool = IV3Factory(leg.factory).getPool(address(tokenIn), address(tokenOut), leg.fee);
        if (pool == address(0)) revert PoolNotFound();

        // V3 sorts a pool's tokens by address.
        bool zeroForOne = address(tokenIn) < address(tokenOut);
        _tset(T_POOL, uint256(uint160(pool)));
        _tset(T_TOKEN, uint256(uint160(address(tokenIn))));
        _tset(T_MAX, maxIn);
        IV3Pool(pool).swap(
            address(this), zeroForOne, amount, zeroForOne ? MIN_SQRT_RATIO_PLUS_1 : MAX_SQRT_RATIO_MINUS_1, ""
        );
        paid = _tget(T_PAID);
        // A pool that never called back stays armed otherwise, for the rest of the call.
        _disarm();
    }

    /// @notice A V3 pool asking for the input of the swap it is running. Paid once, in
    ///         the armed token, up to the armed amount; from anyone else it reverts.
    function uniswapV3SwapCallback(int256 a0, int256 a1, bytes calldata) external {
        // An empty slot reads as the zero address: nothing is active then.
        if (msg.sender != address(uint160(_tget(T_POOL))) || msg.sender == address(0)) revert NotActivePool();
        ERC20 token = ERC20(address(uint160(_tget(T_TOKEN))));
        uint256 max = _tget(T_MAX);
        _disarm();
        uint256 amount = uint256(a0 > 0 ? a0 : (a1 > 0 ? a1 : int256(0)));
        if (amount > max) revert OverBudget();
        _tset(T_PAID, amount);
        token.safeTransfer(msg.sender, amount);
    }

    function _disarm() private {
        _tset(T_POOL, 0);
        _tset(T_TOKEN, 0);
        _tset(T_MAX, 0);
        _tset(T_PAID, 0);
    }

    /// @dev `x` where its `int256` cast keeps its value (V3 takes signed amounts).
    function _fits(uint256 x) private pure returns (uint256) {
        if (x > uint256(uint128(type(int128).max))) revert BadLegs();
        return x;
    }

    /*//////////////////////////////////////////////////////////////
                              STABLE VENUES
    //////////////////////////////////////////////////////////////*/

    /// @dev `UniswapXOndoExecutor._stableSwap`: sell `amountIn` of one stable for the
    ///      other on venue `venueId`, judged by the balance delta. The approval is
    ///      exact and cleared afterwards (USDT refuses a non-zero to non-zero one).
    function _stableSwap(
        bytes32 orderHash,
        uint8 venueId,
        ERC20 tokenIn,
        ERC20 tokenOut,
        uint256 amountIn,
        uint256 minOut
    ) private returns (uint256 got) {
        uint256 before = tokenOut.balanceOf(address(this));
        Venue memory v;
        if (venueId == 0) {
            v = Venue({kind: KIND_V3, pool: address(0), fee: STABLE_POOL_FEE, iUsdt: 0, iUsdc: 0});
        } else {
            v = venues[venueId];
        }
        if (v.kind == KIND_V3) {
            tokenIn.safeApprove(address(swapRouter), amountIn);
            swapRouter.exactInputSingle(
                ISwapRouter02.ExactInputSingleParams({
                    tokenIn: address(tokenIn),
                    tokenOut: address(tokenOut),
                    fee: v.fee,
                    recipient: address(this),
                    amountIn: amountIn,
                    amountOutMinimum: minOut,
                    sqrtPriceLimitX96: 0
                })
            );
            tokenIn.safeApprove(address(swapRouter), 0);
        } else if (v.kind == KIND_CURVE) {
            (int128 i, int128 j) = address(tokenIn) == address(usdt) ? (v.iUsdt, v.iUsdc) : (v.iUsdc, v.iUsdt);
            tokenIn.safeApprove(v.pool, amountIn);
            ICurveStableSwap(v.pool).exchange(i, j, amountIn, minOut);
            tokenIn.safeApprove(v.pool, 0);
        } else {
            revert UnknownVenue();
        }
        got = tokenOut.balanceOf(address(this)) - before;
        if (got < minOut) revert InsufficientSwapOut();
        emit StableSwapped(orderHash, venueId, address(tokenIn), amountIn, got);
    }

    function _isStable(address token) private view returns (bool) {
        return token == address(usdc) || token == address(usdt);
    }

    function _stables() private view returns (uint256) {
        return usdc.balanceOf(address(this)) + usdt.balanceOf(address(this));
    }

    function _tget(uint256 slot) private view returns (uint256 v) {
        assembly {
            v := tload(slot)
        }
    }

    function _tset(uint256 slot, uint256 v) private {
        assembly {
            tstore(slot, v)
        }
    }

    /*//////////////////////////////////////////////////////////////
                                 ADMIN
    //////////////////////////////////////////////////////////////*/

    /// @notice Add or remove a bot wallet. Removing every caller is the kill switch:
    ///         funds, factories and the reactor binding stay put.
    function setWhitelistedCaller(address caller, bool allowed) external onlyOwner {
        _setCaller(caller, allowed);
    }

    /// @notice Allow (or stop allowing) a V3 factory. Only a factory whose pools run
    ///         canonical UniswapV3Pool code belongs here: its pools are paid from the
    ///         swap callback.
    function setAllowedFactory(address factory, bool allowed) external onlyOwner {
        _setFactory(factory, allowed);
    }

    /// @notice List (or, with `kind` 0, delist) stable venue `id`. Same rules as
    ///         `UniswapXOndoExecutor.setVenue`: id 0 is built in, and a Curve listing
    ///         is checked against the pool's own `coins()`.
    function setVenue(uint8 id, uint8 kind, address pool, uint24 fee, int128 iUsdt, int128 iUsdc) external onlyOwner {
        if (id == 0) revert BadVenue();
        if (kind == KIND_V3) {
            if (fee == 0) revert BadVenue();
            pool = address(0);
            (iUsdt, iUsdc) = (0, 0);
        } else if (kind == KIND_CURVE) {
            if (pool == address(0) || iUsdt < 0 || iUsdc < 0 || iUsdt == iUsdc) revert BadVenue();
            if (
                ICurveStableSwap(pool).coins(uint256(uint128(iUsdt))) != address(usdt)
                    || ICurveStableSwap(pool).coins(uint256(uint128(iUsdc))) != address(usdc)
            ) revert BadVenue();
            fee = 0;
        } else if (kind == 0) {
            (pool, fee, iUsdt, iUsdc) = (address(0), 0, 0, 0);
        } else {
            revert BadVenue();
        }
        venues[id] = Venue({kind: kind, pool: pool, fee: fee, iUsdt: iUsdt, iUsdc: iUsdc});
        emit VenueSet(id, kind, pool, fee, iUsdt, iUsdc);
    }

    /// @notice Set the ceiling on a single builder payment (wei). 0 is the kill switch
    ///         for payments; fills keep working.
    function setMaxBuilderPayment(uint256 maxWei) external onlyOwner {
        maxBuilderPaymentWei = maxWei;
        emit MaxBuilderPaymentUpdated(maxWei);
    }

    /// @notice Withdraw profit or stuck tokens.
    function rescueERC20(address token, address to, uint256 amount) external onlyOwner {
        if (to == address(0)) revert ZeroAddress();
        ERC20(token).safeTransfer(to, amount);
    }

    /// @notice Withdraw native ETH (the reactor refunds its own stray balance here).
    function rescueETH(address to, uint256 amount) external onlyOwner {
        if (to == address(0)) revert ZeroAddress();
        SafeTransferLib.safeTransferETH(to, amount);
    }

    function _setCaller(address caller, bool allowed) private {
        if (caller == address(0)) revert ZeroAddress();
        whitelistedCallers[caller] = allowed;
        emit WhitelistedCallerUpdated(caller, allowed);
    }

    function _setFactory(address factory, bool allowed) private {
        if (factory == address(0)) revert ZeroAddress();
        allowedFactory[factory] = allowed;
        emit FactoryUpdated(factory, allowed);
    }

    /// @dev The reactor refunds any ETH it holds to the filler after a fill, so a fill
    ///      must be able to receive it: anyone can send the reactor a wei, and without
    ///      this every fill would revert from then on.
    receive() external payable {}
}

lib/solmate/src/auth/Owned.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;

/// @notice Simple single owner authorization mixin.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol)
abstract contract Owned {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event OwnershipTransferred(address indexed user, address indexed newOwner);

    /*//////////////////////////////////////////////////////////////
                            OWNERSHIP STORAGE
    //////////////////////////////////////////////////////////////*/

    address public owner;

    modifier onlyOwner() virtual {
        require(msg.sender == owner, "UNAUTHORIZED");

        _;
    }

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor(address _owner) {
        owner = _owner;

        emit OwnershipTransferred(address(0), _owner);
    }

    /*//////////////////////////////////////////////////////////////
                             OWNERSHIP LOGIC
    //////////////////////////////////////////////////////////////*/

    function transferOwnership(address newOwner) public virtual onlyOwner {
        owner = newOwner;

        emit OwnershipTransferred(msg.sender, newOwner);
    }
}

lib/solmate/src/tokens/ERC20.sol

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event Transfer(address indexed from, address indexed to, uint256 amount);

    event Approval(address indexed owner, address indexed spender, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                            METADATA STORAGE
    //////////////////////////////////////////////////////////////*/

    string public name;

    string public symbol;

    uint8 public immutable decimals;

    /*//////////////////////////////////////////////////////////////
                              ERC20 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 public totalSupply;

    mapping(address => uint256) public balanceOf;

    mapping(address => mapping(address => uint256)) public allowance;

    /*//////////////////////////////////////////////////////////////
                            EIP-2612 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 internal immutable INITIAL_CHAIN_ID;

    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;

    mapping(address => uint256) public nonces;

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor(
        string memory _name,
        string memory _symbol,
        uint8 _decimals
    ) {
        name = _name;
        symbol = _symbol;
        decimals = _decimals;

        INITIAL_CHAIN_ID = block.chainid;
        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
    }

    /*//////////////////////////////////////////////////////////////
                               ERC20 LOGIC
    //////////////////////////////////////////////////////////////*/

    function approve(address spender, uint256 amount) public virtual returns (bool) {
        allowance[msg.sender][spender] = amount;

        emit Approval(msg.sender, spender, amount);

        return true;
    }

    function transfer(address to, uint256 amount) public virtual returns (bool) {
        balanceOf[msg.sender] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(msg.sender, to, amount);

        return true;
    }

    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual returns (bool) {
        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.

        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;

        balanceOf[from] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(from, to, amount);

        return true;
    }

    /*//////////////////////////////////////////////////////////////
                             EIP-2612 LOGIC
    //////////////////////////////////////////////////////////////*/

    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");

        // Unchecked because the only math done is incrementing
        // the owner's nonce which cannot realistically overflow.
        unchecked {
            address recoveredAddress = ecrecover(
                keccak256(
                    abi.encodePacked(
                        "\x19\x01",
                        DOMAIN_SEPARATOR(),
                        keccak256(
                            abi.encode(
                                keccak256(
                                    "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                ),
                                owner,
                                spender,
                                value,
                                nonces[owner]++,
                                deadline
                            )
                        )
                    )
                ),
                v,
                r,
                s
            );

            require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");

            allowance[recoveredAddress][spender] = value;
        }

        emit Approval(owner, spender, value);
    }

    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
    }

    function computeDomainSeparator() internal view virtual returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                    keccak256(bytes(name)),
                    keccak256("1"),
                    block.chainid,
                    address(this)
                )
            );
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL MINT/BURN LOGIC
    //////////////////////////////////////////////////////////////*/

    function _mint(address to, uint256 amount) internal virtual {
        totalSupply += amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(address(0), to, amount);
    }

    function _burn(address from, uint256 amount) internal virtual {
        balanceOf[from] -= amount;

        // Cannot underflow because a user's balance
        // will never be larger than the total supply.
        unchecked {
            totalSupply -= amount;
        }

        emit Transfer(from, address(0), amount);
    }
}

lib/solmate/src/utils/SafeTransferLib.sol

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

import {ERC20} from "../tokens/ERC20.sol";

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
library SafeTransferLib {
    /*//////////////////////////////////////////////////////////////
                             ETH OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferETH(address to, uint256 amount) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Transfer the ETH and store if it succeeded or not.
            success := call(gas(), to, amount, 0, 0, 0, 0)
        }

        require(success, "ETH_TRANSFER_FAILED");
    }

    /*//////////////////////////////////////////////////////////////
                            ERC20 OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferFrom(
        ERC20 token,
        address from,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "from" argument.
            mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
            mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

            // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
            // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
            success := call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)

            // Set success to whether the call reverted, if not we check it either
            // returned exactly 1 (can't just be non-zero data), or had no return data and token has code.
            if and(iszero(and(eq(mload(0), 1), gt(returndatasize(), 31))), success) {
                success := iszero(or(iszero(extcodesize(token)), returndatasize())) 
            }
        }

        require(success, "TRANSFER_FROM_FAILED");
    }

    function safeTransfer(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

            // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
            // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
            success := call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)

            // Set success to whether the call reverted, if not we check it either
            // returned exactly 1 (can't just be non-zero data), or had no return data and token has code.
            if and(iszero(and(eq(mload(0), 1), gt(returndatasize(), 31))), success) {
                success := iszero(or(iszero(extcodesize(token)), returndatasize())) 
            }
        }

        require(success, "TRANSFER_FAILED");
    }

    function safeApprove(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

            // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
            // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
            success := call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)

            // Set success to whether the call reverted, if not we check it either
            // returned exactly 1 (can't just be non-zero data), or had no return data and token has code.
            if and(iszero(and(eq(mload(0), 1), gt(returndatasize(), 31))), success) {
                success := iszero(or(iszero(extcodesize(token)), returndatasize())) 
            }
        }

        require(success, "APPROVE_FAILED");
    }
}

src/AmmOndoArb.sol

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

import {Owned} from "solmate/auth/Owned.sol";
import {ERC20} from "solmate/tokens/ERC20.sol";
import {SafeTransferLib} from "solmate/utils/SafeTransferLib.sol";

import {IGMTokenManager} from "./external/IGMTokenManager.sol";
import {IWETH9} from "./external/IWETH9.sol";

/// @notice The slice of a Uniswap V3 / PancakeSwap V3 pool this contract uses.
///         The two share the swap ABI; only the callback name differs.
interface IV3Pool {
    function token0() external view returns (address);
    function token1() external view returns (address);
    function factory() external view returns (address);
    function fee() external view returns (uint24);
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);
}

/// @notice A Ring Swap V2 pair (a Uniswap V2 fork). It holds Few Wrapped
///         Tokens, not the raw tokens, and charges 0.3%.
interface IRingPair {
    function token0() external view returns (address);
    function token1() external view returns (address);
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
    function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;
}

/// @notice A Few Wrapped Token: 1:1 over `token()`. `wrapTo` pulls the raw
///         token from the caller by `transferFrom`.
interface IFewWrappedToken {
    function token() external view returns (address);
    function wrapTo(uint256 amount, address to) external returns (uint256);
    function unwrapTo(uint256 amount, address to) external returns (uint256);
}

/// @notice The slice of the Uniswap V4 PoolManager this contract uses (v4-core).
interface IV4PoolManager {
    struct PoolKey {
        address currency0;
        address currency1;
        uint24 fee;
        int24 tickSpacing;
        address hooks;
    }

    struct SwapParams {
        bool zeroForOne;
        int256 amountSpecified; // negative = exact input
        uint160 sqrtPriceLimitX96;
    }

    function unlock(bytes calldata data) external returns (bytes memory);
    /// @return delta BalanceDelta: amount0 in the upper 128 bits, amount1 in the
    ///         lower; negative is owed by the caller.
    function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData) external returns (int256 delta);
    function sync(address currency) external;
    function settle() external payable returns (uint256);
    function take(address currency, address to, uint256 amount) external;
    function extsload(bytes32 slot) external view returns (bytes32);
}

/// @notice What a V3 pool's own factory answers, to prove the pool is one of
///         its deployments (Uniswap V3, PancakeSwap V3, byte-identical forks).
interface IV3Factory {
    function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address);
}

/**
 * AmmOndoArb — closes the gap between a GM token's AMM pool and Ondo's primary
 * market, atomically, out of this contract's own stable.
 *
 *   MINT-SELL (side 0) — the pool is rich: mint at Ondo with `depositAmount` of
 *     the stable, sell what was minted through `hops` back into the stable.
 *
 *   BUY-REDEEM (side 1) — the pool is cheap: buy GM with `amountIn` of the stable
 *     through `hops`, redeem `quote.quantity` of it at Ondo for the stable.
 *
 * `hops` is a route of owner-listed pools, walked by token: each hop swaps the
 * whole output of the previous one (FXIon -> WBNB -> USDT is two hops). A hop is
 * a V3 pool (`pool`), a Ring V2 pair (`pool`, listed by `setRingPair`) or a V4
 * pool (`v4Id`, its poolId, with `pool` zero). V4
 * pools are listed by their full PoolKey and swapped inside the PoolManager's
 * unlock callback; ERC20 currencies and hookless keys only.
 *
 * THE invariant, checked last and the reason this is safe to run unattended:
 * the stable balance must end at least `minProfit` above where it started and
 * the GM balance must not fall. A raced pool, a worse signed price than the soft
 * quote, an expired attestation or a bad route all revert the whole
 * transaction — the most a failed arb costs is its gas. The bot decides WHEN,
 * Ondo signs the PRICE, and this contract refuses any outcome that is not a
 * profit.
 *
 * Same Ondo trust model as the fill contracts: this address is the Ondo-
 * whitelisted user, and a leg names an attestation and nothing else — no
 * arbitrary call target anywhere in the payload. Pools are trusted once listed
 * (they are paid from the swap callback), so listing is owner-only.
 *
 * FLASH (`flashArb`): the same arb with no working capital. The stable outlay
 * is taken from the V4 PoolManager inside one `unlock` and settled back before
 * it closes — V4's flash accounting charges no fee, and the manager holds the
 * stable of every V4 pool on the chain. Inside that lock a V4 hop swaps directly
 * (the manager cannot be unlocked twice); V3 hops and Ondo run as in `arb`. If
 * the manager is short of the stable, or the arb cannot repay, the transaction
 * reverts like any other failed arb.
 *
 * BUILDER PAYMENT (`flashArbWithBuilderPayment`): the flash arb, then `payment`
 * wei to `block.coinbase`, paid per arb out of `msg.value` (never a balance this
 * contract holds), last, and only if the arb succeeded. On mainnet a bundle is
 * ranked by what it pays the builder, not by its priority fee — the fill rail's
 * lesson (`BUILDER-PAYMENT.md`), copied here entry for entry: the same
 * `BuilderPaid` event, the same 100k-gas forward, the same owner cap that
 * starts at 0. It is never meant for BSC, where `block.coinbase` is the
 * validator and the payment would not reach the builder.
 *
 * MULTI (`flashMultiArb`, version 2): several legs in ONE flash, each leg one
 * Ondo attestation with several routes. Buy-redeem buys GM through every route
 * and redeems the total once; mint-sell mints once and sells a slice into each
 * route. The outlay is the sum over the whole call and `maxNotional` caps it.
 * The checks are `arb`'s, over the whole call: the stable must end `minProfit`
 * up and no GM balance may fall. One raced route lowers the total, and the whole
 * call reverts if that takes it under `minProfit`. Flash only. The single-pool
 * entry points above are unchanged, so a version-1 caller works here as is.
 *
 * RING (version 3): a hop may be a Ring Swap V2 pair. Its reserves are Few
 * Wrapped Tokens, so the hop wraps the raw input straight into the pair
 * (`wrapTo`), prices the output off `getReserves` at 997/1000, swaps it out to
 * this contract and unwraps it (`unwrapTo`). Both fw tokens and their raw
 * tokens are read once when the owner lists the pair, never from calldata.
 * The hop is the same `Hop` (the pair in `pool`), so callers encode it like a
 * V3 hop; the listing decides how it is walked.
 *
 * PAID FROM PROFIT (version 4, `flashArbFundedByProfit`): the builder payment
 * and the lane's gas come out of the stable this arb just earned, not out of ETH
 * the lane holds. After the arb, it buys exactly `payment + refund` of wrapped
 * native through the owner-set stable/native V3 pool, unwraps it, pays
 * `block.coinbase`, and refunds `msg.sender` the gas measured so far. The lane
 * then only needs ETH to be allowed to send, so a bid is no longer cut to what
 * it holds (2026-11-14: a $408 CRCLon arb bid $45 out of a 0.23 ETH lane and
 * lost to a $397 bid). The swap may spend at most the arb's own profit and at
 * most `maxStablePerNative` per native token, the bot's signed price bound, so
 * a builder that moves the pool ahead of it makes the arb revert, not overpay.
 * The 1inch resolver's `settleOrdersFundedByFill` (#472), on this contract's
 * own V3 swap path.
 *
 * BY FACTORY (version 5): a V3 pool need not be listed one by one. A hop whose
 * pool is not listed is accepted if its `factory()` is an owner-allowed factory
 * that answers `getPool(token0, token1, fee)` with that very pool; the pool is
 * then listed for good (`PoolListed`), so the check runs once. Its two tokens
 * must be the stable, the GM token Ondo signed for THIS arb (`quote.asset`), or
 * an owner-allowed quote (`allowedQuote`, e.g. WETH/WBNB): a canonical pool
 * runs canonical code, so its callback asks for exactly what it is owed, and
 * the token rule keeps a canonical pool of a fake token out of every route. A
 * V4 pool is listed by anyone through `listV4Pool` (hookless, ERC20,
 * initialized), and its tokens are checked the same way on every use. The
 * owner can block a pool or a V4 id for good (`blocked`), which wins over both.
 * Ring pairs stay owner-listed (`setRingPair`).
 *
 * Default-off three times over: a fresh deploy has no listed pools, a zero
 * `maxNotional` and a zero `maxBuilderPaymentWei`, so nothing trades and
 * nothing pays until the owner opts in.
 */
contract AmmOndoArb is Owned {
    using SafeTransferLib for ERC20;

    /// @notice Byte-for-byte the fill contracts' `Leg`, so the bot's encoder
    ///         serves both. Mint reads `depositAmount`, redeem reads `minOut`.
    struct Leg {
        IGMTokenManager.Quote quote;
        bytes signature;
        uint256 minOut;
        uint256 depositAmount;
    }

    struct Hop {
        address pool; // V3 pool, or zero for a V4 hop
        bytes32 v4Id; // V4 poolId when `pool` is zero
    }

    struct Arb {
        Leg leg;
        Hop[] hops; // route, mint: GM -> ... -> stable; redeem: stable -> ... -> GM
        uint256 amountIn; // redeem only: stable into the first hop
        uint256 minProfit; // stable, on top of breaking even
    }

    struct Route {
        Hop[] hops;
        uint256 amountIn; // buy-redeem: stable into the route; mint-sell: GM into the route
    }

    /// @notice One leg of a multi arb: one attestation, its GM split over `routes`.
    struct MultiLeg {
        Leg leg;
        Route[] routes;
    }

    /// @dev Hops one arb may take. Two covers GM/WBNB + WBNB/stable.
    uint256 internal constant MAX_HOPS = 3;
    // TickMath bounds: an exact-input swap with these limits never stops on price.
    uint160 internal constant MIN_SQRT_RATIO_PLUS_1 = 4295128740;
    uint160 internal constant MAX_SQRT_RATIO_MINUS_1 = 1461446703485210103287273052203988822378723970341;
    // What an unlock is for: one V4 hop of `arb`, or a whole `flashArb`.
    uint8 internal constant UNLOCK_HOP = 0;
    uint8 internal constant UNLOCK_FLASH = 1;
    uint8 internal constant UNLOCK_FLASH_MULTI = 2;
    /// @dev Legs one multi arb may hold, and routes one leg may split over.
    uint256 internal constant MAX_LEGS = 4;
    uint256 internal constant MAX_ROUTES = 4;
    /// @dev Gas forwarded with a builder payment. `block.coinbase` is chosen by
    ///      the block producer, so an unbounded call would let a hostile one burn
    ///      the whole transaction; 100k is far above what a payout recipient
    ///      needs. Same figure and reasoning as `OneInchOndoResolver`.
    uint256 internal constant BUILDER_PAYMENT_GAS = 100_000;
    /// @dev Gas a funded payment spends after it measures the refund: 21k
    ///      intrinsic, the native swap, the unwrap and the two ETH transfers.
    ///      Calibrated on a mainnet fork (`test_funded_refund_covers_the_gas`).
    uint256 internal constant REFUND_OVERHEAD_GAS = 21_000 + 190_000;

    IGMTokenManager public immutable gm;
    /// @notice Ondo's settlement token on this chain (BSC: USDT).
    ERC20 public immutable stable;
    /// @notice Uniswap V4 PoolManager on this chain; zero where V4 is not used.
    IV4PoolManager public immutable v4Manager;

    mapping(address => bool) public whitelistedCallers;
    mapping(address => bool) public listedPool;
    /// @dev Listed V4 pools by poolId. An unlisted id has currency0 == 0.
    mapping(bytes32 => IV4PoolManager.PoolKey) internal v4Key;
    /// @notice Ceiling on ONE arb's stable outlay (`depositAmount` or `amountIn`;
    ///         for a multi arb, the sum over the call). 0 — a fresh deploy —
    ///         refuses every arb.
    uint256 public maxNotional;

    /// @dev The pool (or V4 manager) currently mid-swap; the only address a
    ///      callback is accepted from. Set and cleared around each swap.
    address private activePool;
    /// @dev True while a `flashArb` holds the V4 lock: V4 hops swap inline.
    bool private flashing;
    /// @notice Ceiling on ONE arb's builder payment, in wei. 0 — a fresh deploy —
    ///         refuses every non-zero payment. Declared last: the bot overrides
    ///         `maxNotional` by its slot (4) in simulation.
    uint256 public maxBuilderPaymentWei;

    /// @dev A listed Ring pair's fw tokens and the raw tokens under them, by
    ///      pair. An unlisted pair has fw0 == 0. Declared after every older slot,
    ///      so the bot's slot overrides still land.
    struct RingPair {
        address fw0;
        address fw1;
        address raw0;
        address raw1;
    }

    mapping(address => RingPair) public ringPair;

    /// @notice Wrapped native and the stable/wrapped-native V3 pool the funded
    ///         entry points buy native through. Zero (a fresh deploy) refuses
    ///         them; nothing else reads either. Declared last, like `ringPair`.
    address public nativeWrapped;
    address public nativePool;

    /// @notice V3 factories (Uniswap V3, PancakeSwap V3, GM forks) whose pools
    ///         trade without a listing (version 5). Declared after every older
    ///         slot, so the bot's slot overrides still land.
    mapping(address => bool) public allowedFactory;
    /// @notice Quote tokens a factory-checked pool may hold besides the stable
    ///         and the arb's GM (wrapped native).
    mapping(address => bool) public allowedQuote;
    /// @notice Pools and V4 ids the owner refused, keyed by `bytes32(uint160(pool))`
    ///         or the poolId: never traded, whatever their factory.
    mapping(bytes32 => bool) public blocked;
    /// @dev V4 ids listed by `listV4Pool` rather than the owner: their tokens are
    ///      checked against each arb's GM, as a factory-checked pool's are.
    mapping(bytes32 => bool) internal v4Open;

    event WhitelistedCallerUpdated(address indexed caller, bool allowed);
    event PoolListed(address indexed pool, bool listed);
    event V4PoolListed(bytes32 indexed id, bool listed);
    event MaxNotionalUpdated(uint256 maxNotional);
    event Arbed(address indexed asset, uint8 side, uint256 outlay, uint256 profit);
    event MultiArbed(uint256 legs, uint256 outlay, uint256 profit);
    event MaxBuilderPaymentUpdated(uint256 maxWei);
    /// @notice Same signature as the fill rail's, so the bot reads both the same way.
    event BuilderPaid(address indexed builder, uint256 amount);
    event RingPairListed(address indexed pair, bool listed);
    event NativeSwapUpdated(address wrapped, address pool);
    /// @notice A funded payment: wei to the builder, wei refunded to the lane,
    ///         and the stable the native cost.
    event ProfitFundedPayment(address indexed lane, uint256 payment, uint256 refund, uint256 stableSpent);
    event Allowed(address indexed factoryOrQuote, bool quote, bool allowed);
    event Blocked(bytes32 indexed key, bool blocked);

    error NotWhitelistedCaller();
    error ZeroAddress();
    error UnsupportedSide();
    error BadRoute();
    error PoolNotListed();
    error HookedPool();
    error NotActivePool();
    error NotionalTooLarge();
    error RedeemExceedsBought();
    error SellExceedsMinted();
    error InventorySpent();
    error Unprofitable();
    error BuilderPaymentTooLarge();
    error BuilderPaymentMismatch();
    error BuilderPaymentFailed();
    error NativeSwapDisabled();
    error PaymentUnfunded();
    error GasRefundFailed();
    error TokenNotAllowed();

    modifier onlyWhitelistedCaller() {
        if (!whitelistedCallers[msg.sender]) revert NotWhitelistedCaller();
        _;
    }

    /// @param _v4Manager  Uniswap V4 PoolManager, or zero to run V3-only
    constructor(address _owner, address _gm, address _stable, address _v4Manager, address[] memory _callers)
        Owned(_owner)
    {
        if (_owner == address(0) || _gm == address(0) || _stable == address(0)) revert ZeroAddress();
        gm = IGMTokenManager(_gm);
        stable = ERC20(_stable);
        v4Manager = IV4PoolManager(_v4Manager);
        for (uint256 i; i < _callers.length; ++i) {
            if (_callers[i] == address(0)) revert ZeroAddress();
            whitelistedCallers[_callers[i]] = true;
            emit WhitelistedCallerUpdated(_callers[i], true);
        }
    }

    function arb(Arb calldata a) external onlyWhitelistedCaller returns (uint256 profit) {
        return _arb(a);
    }

    /// @notice `arb` funded by a fee-free V4 flash of the stable outlay, repaid in
    ///         the same lock: no working capital. Profit and checks are `arb`'s.
    function flashArb(Arb calldata a) external onlyWhitelistedCaller returns (uint256 profit) {
        return _flash(a);
    }

    /// @notice `flashArb`, then `payment` wei to `block.coinbase`. The caller sends
    ///         exactly the payment as `msg.value`, so the contract holds no ETH
    ///         between arbs and the cap is the whole blast radius of one call.
    /// @dev Ordering is load-bearing: the payment is made LAST, after the arb has
    ///      settled and the flash is repaid. A failed arb reverts everything and
    ///      pays nothing, and a re-entering coinbase finds no lock held and would
    ///      need to be a whitelisted caller to do anything. Bundle route only: in
    ///      the public mempool a coinbase payment buys no ordering.
    function flashArbWithBuilderPayment(Arb calldata a, uint256 payment)
        external
        payable
        onlyWhitelistedCaller
        returns (uint256 profit)
    {
        _checkPayment(payment);
        profit = _flash(a);
        _payBuilder(payment);
    }

    /// @notice `flashArb`, then the builder payment and the lane's gas, paid out
    ///         of this arb's profit. See PAID FROM PROFIT above.
    /// @param payment             wei to `block.coinbase`; capped by `maxBuilderPaymentWei`.
    /// @param maxStablePerNative  most stable (base units) one native token (1e18 wei) may cost.
    function flashArbFundedByProfit(Arb calldata a, uint256 payment, uint256 maxStablePerNative)
        external
        onlyWhitelistedCaller
        returns (uint256 profit)
    {
        uint256 startGas = gasleft();
        if (payment > maxBuilderPaymentWei) revert BuilderPaymentTooLarge();
        profit = _flash(a);
        _payFromProfit(startGas, profit, payment, maxStablePerNative);
    }

    /// @notice `flashMultiArb`, paid out of its profit like `flashArbFundedByProfit`.
    function flashMultiArbFundedByProfit(
        MultiLeg[] calldata legs,
        uint256 minProfit,
        uint256 payment,
        uint256 maxStablePerNative
    ) external onlyWhitelistedCaller returns (uint256 profit) {
        uint256 startGas = gasleft();
        if (payment > maxBuilderPaymentWei) revert BuilderPaymentTooLarge();
        profit = _flashMulti(legs, minProfit);
        _payFromProfit(startGas, profit, payment, maxStablePerNative);
    }

    /// @notice Version 2 adds the multi entry points, version 3 Ring hops,
    ///         version 4 the funded payment, version 5 pools by factory and
    ///         `listV4Pool`; version 1 contracts have no such function, so a
    ///         reverting probe means version 1.
    function arbVersion() external pure returns (uint256) {
        return 5;
    }

    /// @notice Every leg in one V4 flash: the outlay of the whole call is borrowed
    ///         fee-free and repaid in the same lock. See MULTI above.
    function flashMultiArb(MultiLeg[] calldata legs, uint256 minProfit)
        external
        onlyWhitelistedCaller
        returns (uint256 profit)
    {
        return _flashMulti(legs, minProfit);
    }

    /// @notice `flashMultiArb`, then `payment` wei to `block.coinbase`, with the
    ///         same rules and ordering as `flashArbWithBuilderPayment`.
    function flashMultiArbWithBuilderPayment(MultiLeg[] calldata legs, uint256 minProfit, uint256 payment)
        external
        payable
        onlyWhitelistedCaller
        returns (uint256 profit)
    {
        _checkPayment(payment);
        profit = _flashMulti(legs, minProfit);
        _payBuilder(payment);
    }

    function _checkPayment(uint256 payment) private view {
        if (payment > maxBuilderPaymentWei) revert BuilderPaymentTooLarge();
        if (msg.value != payment) revert BuilderPaymentMismatch();
    }

    /// @dev Last, after the arb has settled and the flash is repaid.
    function _payBuilder(uint256 payment) private {
        if (payment != 0) {
            // Raw call, not `transfer`: payout recipients are often contracts, and
            // a 2300-gas stipend would strand the payment. A failed payment
            // reverts the arb rather than land one that bought nothing.
            (bool paid,) = block.coinbase.call{value: payment, gas: BUILDER_PAYMENT_GAS}("");
            if (!paid) revert BuilderPaymentFailed();
            emit BuilderPaid(block.coinbase, payment);
        }
    }

    /// @dev After the arb has settled and the flash is repaid: buy exactly
    ///      `payment + refund` of wrapped native with at most `profit` (and at
    ///      most `maxStablePerNative` a token), unwrap it, pay the builder, refund
    ///      the lane. The refund is measured here, at `tx.gasprice`, so a caller
    ///      can only refund itself what the transaction cost.
    function _payFromProfit(uint256 startGas, uint256 profit, uint256 payment, uint256 maxStablePerNative) private {
        address wrapped = nativeWrapped;
        address pool = nativePool;
        if (wrapped == address(0)) revert NativeSwapDisabled();
        uint256 refund = (startGas - gasleft() + REFUND_OVERHEAD_GAS + msg.data.length * 16) * tx.gasprice;
        uint256 need = payment + refund;
        if (need == 0) return;
        uint256 priced = (need * maxStablePerNative + 1e18 - 1) / 1e18;
        uint256 cap = profit < priced ? profit : priced;
        bool zeroForOne = IV3Pool(pool).token0() == address(stable);
        activePool = pool;
        (int256 a0, int256 a1) = IV3Pool(pool)
            .swap(
                address(this),
                zeroForOne,
                -int256(need),
                zeroForOne ? MIN_SQRT_RATIO_PLUS_1 : MAX_SQRT_RATIO_MINUS_1,
                abi.encode(address(stable))
            );
        activePool = address(0);
        uint256 spent = uint256(zeroForOne ? a0 : a1);
        if (spent > cap || uint256(-(zeroForOne ? a1 : a0)) < need) revert PaymentUnfunded();
        IWETH9(wrapped).withdraw(need);
        _payBuilder(payment);
        if (refund != 0) {
            (bool ok,) = msg.sender.call{value: refund}("");
            if (!ok) revert GasRefundFailed();
        }
        emit ProfitFundedPayment(msg.sender, payment, refund, spent);
    }

    /// @dev Only the wrapped native's unwrap pays this contract ETH.
    receive() external payable {
        if (msg.sender != nativeWrapped || msg.sender == address(0)) revert NotActivePool();
    }

    function _flash(Arb calldata a) private returns (uint256 profit) {
        if (address(v4Manager) == address(0)) revert ZeroAddress();
        activePool = address(v4Manager);
        flashing = true;
        profit = abi.decode(v4Manager.unlock(abi.encode(UNLOCK_FLASH, abi.encode(a))), (uint256));
        flashing = false;
        activePool = address(0);
    }

    function _flashMulti(MultiLeg[] calldata legs, uint256 minProfit) private returns (uint256 profit) {
        if (address(v4Manager) == address(0)) revert ZeroAddress();
        activePool = address(v4Manager);
        flashing = true;
        // One blob per leg: decoding the nested array whole runs the decoder out of
        // stack, a leg at a time does not.
        bytes[] memory blobs = new bytes[](legs.length);
        for (uint256 i; i < legs.length; ++i) {
            blobs[i] = abi.encode(legs[i]);
        }
        profit = abi.decode(v4Manager.unlock(abi.encode(UNLOCK_FLASH_MULTI, abi.encode(blobs, minProfit))), (uint256));
        flashing = false;
        activePool = address(0);
    }

    /// @dev The stable a multi arb puts in: each mint's deposit, each buy route's
    ///      `amountIn`. Also where the shape is checked, before anything moves.
    function _outlay(MultiLeg[] memory legs) private pure returns (uint256 outlay) {
        if (legs.length == 0 || legs.length > MAX_LEGS) revert BadRoute();
        for (uint256 i; i < legs.length; ++i) {
            MultiLeg memory l = legs[i];
            if (l.routes.length == 0 || l.routes.length > MAX_ROUTES) revert BadRoute();
            for (uint256 r; r < l.routes.length; ++r) {
                Route memory rt = l.routes[r];
                if (rt.hops.length == 0 || rt.hops.length > MAX_HOPS || rt.amountIn == 0) revert BadRoute();
                if (l.leg.quote.side == 1) outlay += rt.amountIn;
            }
            if (l.leg.quote.side == 0) outlay += l.leg.depositAmount;
            else if (l.leg.quote.side != 1) revert UnsupportedSide();
        }
    }

    function _multi(MultiLeg[] memory legs, uint256 minProfit, uint256 outlay) private returns (uint256 profit) {
        if (outlay > maxNotional) revert NotionalTooLarge();
        uint256 stableBefore = stable.balanceOf(address(this));
        uint256[] memory gmBefore = new uint256[](legs.length);
        for (uint256 i; i < legs.length; ++i) {
            gmBefore[i] = ERC20(legs[i].leg.quote.asset).balanceOf(address(this));
        }
        for (uint256 i; i < legs.length; ++i) {
            _multiLeg(legs[i]);
        }
        for (uint256 i; i < legs.length; ++i) {
            if (ERC20(legs[i].leg.quote.asset).balanceOf(address(this)) < gmBefore[i]) revert InventorySpent();
        }
        uint256 stableAfter = stable.balanceOf(address(this));
        if (stableAfter < stableBefore + minProfit) revert Unprofitable();
        profit = stableAfter - stableBefore;
        emit MultiArbed(legs.length, outlay, profit);
    }

    /// @dev `unlockCallback`'s multi branch, apart so the decode has its own stack.
    function _flashMultiBody(bytes memory body) private returns (uint256 borrow, uint256 profit) {
        (bytes[] memory blobs, uint256 minProfit) = abi.decode(body, (bytes[], uint256));
        MultiLeg[] memory legs = new MultiLeg[](blobs.length);
        for (uint256 i; i < blobs.length; ++i) {
            legs[i] = abi.decode(blobs[i], (MultiLeg));
        }
        borrow = _outlay(legs);
        v4Manager.take(address(stable), address(this), borrow);
        profit = _multi(legs, minProfit, borrow);
    }

    function _multiLeg(MultiLeg memory l) private {
        IGMTokenManager.Quote memory q = l.leg.quote;
        ERC20 asset = ERC20(q.asset);
        uint256 gmBefore = asset.balanceOf(address(this));
        if (q.side == 0) {
            stable.safeApprove(address(gm), l.leg.depositAmount);
            gm.mintWithAttestation(q, l.leg.signature, address(stable), l.leg.depositAmount);
            uint256 minted = asset.balanceOf(address(this)) - gmBefore;
            uint256 sold;
            for (uint256 r; r < l.routes.length; ++r) {
                sold += l.routes[r].amountIn;
            }
            // Only what this leg minted, never GM the contract already held.
            if (sold > minted) revert SellExceedsMinted();
            for (uint256 r; r < l.routes.length; ++r) {
                if (_route(l.routes[r].hops, address(asset), l.routes[r].amountIn, address(asset)) != address(stable)) {
                    revert BadRoute();
                }
            }
        } else {
            for (uint256 r; r < l.routes.length; ++r) {
                if (_route(l.routes[r].hops, address(stable), l.routes[r].amountIn, address(asset)) != address(asset)) {
                    revert BadRoute();
                }
            }
            if (q.quantity > asset.balanceOf(address(this)) - gmBefore) revert RedeemExceedsBought();
            asset.safeApprove(address(gm), q.quantity);
            gm.redeemWithAttestation(q, l.leg.signature, address(stable), l.leg.minOut);
        }
    }

    function _arb(Arb memory a) private returns (uint256 profit) {
        if (a.hops.length == 0 || a.hops.length > MAX_HOPS) revert BadRoute();
        IGMTokenManager.Quote memory q = a.leg.quote;
        ERC20 asset = ERC20(q.asset);
        uint256 stableBefore = stable.balanceOf(address(this));
        uint256 gmBefore = asset.balanceOf(address(this));

        if (q.side == 0) {
            if (a.leg.depositAmount > maxNotional) revert NotionalTooLarge();
            stable.safeApprove(address(gm), a.leg.depositAmount);
            gm.mintWithAttestation(q, a.leg.signature, address(stable), a.leg.depositAmount);
            uint256 minted = asset.balanceOf(address(this)) - gmBefore;
            if (_route(a.hops, address(asset), minted, address(asset)) != address(stable)) revert BadRoute();
        } else if (q.side == 1) {
            if (a.amountIn > maxNotional) revert NotionalTooLarge();
            if (_route(a.hops, address(stable), a.amountIn, address(asset)) != address(asset)) revert BadRoute();
            // Only what this arb bought, never GM the contract already held.
            if (q.quantity > asset.balanceOf(address(this)) - gmBefore) revert RedeemExceedsBought();
            asset.safeApprove(address(gm), q.quantity);
            gm.redeemWithAttestation(q, a.leg.signature, address(stable), a.leg.minOut);
        } else {
            revert UnsupportedSide();
        }

        if (asset.balanceOf(address(this)) < gmBefore) revert InventorySpent();
        uint256 stableAfter = stable.balanceOf(address(this));
        if (stableAfter < stableBefore + a.minProfit) revert Unprofitable();
        profit = stableAfter - stableBefore;
        emit Arbed(address(asset), q.side, q.side == 0 ? a.leg.depositAmount : a.amountIn, profit);
    }

    /// @dev Swap `amountIn` of `tokenIn` through each hop in turn; returns the
    ///      token the route ends in. Direction is read from the pool, so a hop
    ///      whose pool does not hold the incoming token reverts. `asset` is the
    ///      GM token Ondo signed for this arb: the one non-quote token a
    ///      factory-checked or openly listed pool may hold.
    function _route(Hop[] memory hops, address tokenIn, uint256 amountIn, address asset) private returns (address) {
        for (uint256 i; i < hops.length; ++i) {
            // int128: the narrower of the V3 (int256) and V4 (int128 delta) bounds.
            if (amountIn > uint256(int256(type(int128).max))) revert BadRoute();
            address pool = hops[i].pool;
            if (pool == address(0)) {
                bytes32 id = hops[i].v4Id;
                if (v4Key[id].currency0 == address(0) || blocked[id]) revert PoolNotListed();
                if (v4Open[id]) _checkTokens(v4Key[id].currency0, v4Key[id].currency1, asset);
                if (flashing) {
                    (tokenIn, amountIn) = _v4Swap(id, tokenIn, amountIn); // already inside the lock
                    continue;
                }
                activePool = address(v4Manager);
                (tokenIn, amountIn) = abi.decode(
                    v4Manager.unlock(abi.encode(UNLOCK_HOP, abi.encode(id, tokenIn, amountIn))), (address, uint256)
                );
                activePool = address(0);
                continue;
            }
            if (blocked[bytes32(uint256(uint160(pool)))]) revert PoolNotListed();
            if (ringPair[pool].fw0 != address(0)) {
                (tokenIn, amountIn) = _ringSwap(pool, tokenIn, amountIn);
                continue;
            }
            if (!listedPool[pool]) _listByFactory(pool, asset);
            address t0 = IV3Pool(pool).token0();
            bool zeroForOne = tokenIn == t0;
            if (!zeroForOne && tokenIn != IV3Pool(pool).token1()) revert BadRoute();

            activePool = pool;
            (int256 a0, int256 a1) = IV3Pool(pool)
                .swap(
                    address(this),
                    zeroForOne,
                    int256(amountIn),
                    zeroForOne ? MIN_SQRT_RATIO_PLUS_1 : MAX_SQRT_RATIO_MINUS_1,
                    abi.encode(tokenIn)
                );
            activePool = address(0);

            tokenIn = zeroForOne ? IV3Pool(pool).token1() : t0;
            amountIn = uint256(-(zeroForOne ? a1 : a0));
        }
        return tokenIn;
    }

    /// @dev List an unlisted V3 pool by its factory, or revert `PoolNotListed`.
    ///      `factory()` is the pool's own claim; the allowed factory's answer is
    ///      what proves it. Its tokens must pass `_checkTokens` against this
    ///      arb's GM, which Ondo signed, so a listing never admits a fake token.
    function _listByFactory(address pool, address asset) private {
        // A pool without these reverts here, which is as good as unlisted.
        address factory = IV3Pool(pool).factory();
        if (!allowedFactory[factory]) revert PoolNotListed();
        address t0 = IV3Pool(pool).token0();
        address t1 = IV3Pool(pool).token1();
        if (IV3Factory(factory).getPool(t0, t1, IV3Pool(pool).fee()) != pool) revert PoolNotListed();
        _checkTokens(t0, t1, asset);
        listedPool[pool] = true;
        emit PoolListed(pool, true);
    }

    /// @dev Both tokens of a factory-checked or openly listed pool must be the
    ///      stable, this arb's GM, or an allowed quote.
    function _checkTokens(address a, address b, address asset) private view {
        if (!_tokenOk(a, asset) || !_tokenOk(b, asset)) revert TokenNotAllowed();
    }

    function _tokenOk(address t, address asset) private view returns (bool) {
        return t == address(stable) || t == asset || allowedQuote[t];
    }

    /// @dev Exact-in through a listed Ring pair: wrap the input into the pair,
    ///      take the V2 output (0.3% fee) at the current reserves, unwrap it
    ///      here. The pair checks K against its balances, so a wrong output
    ///      reverts rather than overpays. Returns (tokenOut, amountOut).
    function _ringSwap(address pair, address tokenIn, uint256 amountIn) private returns (address, uint256) {
        RingPair memory p = ringPair[pair];
        bool zeroForOne = tokenIn == p.raw0;
        if (!zeroForOne && tokenIn != p.raw1) revert BadRoute();
        uint256 out = _ringOut(pair, zeroForOne, amountIn);
        if (out == 0) revert BadRoute();
        address fwIn = zeroForOne ? p.fw0 : p.fw1;

        ERC20(tokenIn).safeApprove(fwIn, amountIn);
        IFewWrappedToken(fwIn).wrapTo(amountIn, pair);
        IRingPair(pair).swap(zeroForOne ? 0 : out, zeroForOne ? out : 0, address(this), "");
        IFewWrappedToken(zeroForOne ? p.fw1 : p.fw0).unwrapTo(out, address(this));
        return (zeroForOne ? p.raw1 : p.raw0, out);
    }

    /// @dev Uniswap V2's `getAmountOut` at 997/1000 over the pair's reserves.
    function _ringOut(address pair, bool zeroForOne, uint256 amountIn) private view returns (uint256) {
        (uint256 r0, uint256 r1,) = IRingPair(pair).getReserves();
        (uint256 rIn, uint256 rOut) = zeroForOne ? (r0, r1) : (r1, r0);
        uint256 inFee = amountIn * 997;
        return inFee * rOut / (rIn * 1000 + inFee);
    }

    function uniswapV3SwapCallback(int256 a0, int256 a1, bytes calldata data) external {
        _pay(a0, a1, data);
    }

    function pancakeV3SwapCallback(int256 a0, int256 a1, bytes calldata data) external {
        _pay(a0, a1, data);
    }

    /// @dev Pay the pool what the swap owes it. Only the pool `_route` is calling
    ///      may collect — without that, anyone could invoke a callback and be paid.
    function _pay(int256 a0, int256 a1, bytes calldata data) private {
        if (msg.sender != activePool || msg.sender == address(0)) revert NotActivePool();
        ERC20(abi.decode(data, (address))).safeTransfer(msg.sender, uint256(a0 > 0 ? a0 : a1));
    }

    /// @dev Inside the PoolManager's lock: one V4 hop of `arb`, or a whole
    ///      `flashArb` / `flashMultiArb` — borrow the outlay, arb, repay it before
    ///      the lock closes.
    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        if (msg.sender != activePool || msg.sender != address(v4Manager)) revert NotActivePool();
        (uint8 mode, bytes memory body) = abi.decode(data, (uint8, bytes));
        if (mode == UNLOCK_HOP && !flashing) {
            (bytes32 id, address tokenIn, uint256 amountIn) = abi.decode(body, (bytes32, address, uint256));
            (address tokenOut, uint256 out) = _v4Swap(id, tokenIn, amountIn);
            return abi.encode(tokenOut, out);
        }
        if (!flashing) revert NotActivePool();
        uint256 borrow;
        uint256 profit;
        if (mode == UNLOCK_FLASH) {
            Arb memory a = abi.decode(body, (Arb));
            borrow = a.leg.quote.side == 0 ? a.leg.depositAmount : a.amountIn;
            v4Manager.take(address(stable), address(this), borrow);
            profit = _arb(a);
        } else if (mode == UNLOCK_FLASH_MULTI) {
            (borrow, profit) = _flashMultiBody(body);
        } else {
            revert NotActivePool();
        }
        v4Manager.sync(address(stable));
        stable.safeTransfer(address(v4Manager), borrow);
        v4Manager.settle();
        return abi.encode(profit);
    }

    /// @dev Swap exact-in through a listed V4 pool, pay what the pool is owed,
    ///      take what it owes us. Caller holds the lock. Returns (tokenOut, amountOut).
    function _v4Swap(bytes32 id, address tokenIn, uint256 amountIn) private returns (address, uint256) {
        IV4PoolManager.PoolKey memory key = v4Key[id];
        bool zeroForOne = tokenIn == key.currency0;
        if (!zeroForOne && tokenIn != key.currency1) revert BadRoute();

        int256 delta = v4Manager.swap(
            key,
            IV4PoolManager.SwapParams({
                zeroForOne: zeroForOne,
                amountSpecified: -int256(amountIn),
                sqrtPriceLimitX96: zeroForOne ? MIN_SQRT_RATIO_PLUS_1 : MAX_SQRT_RATIO_MINUS_1
            }),
            ""
        );
        int128 d0 = int128(delta >> 128);
        int128 d1 = int128(delta);
        (int128 dIn, int128 dOut) = zeroForOne ? (d0, d1) : (d1, d0);
        address tokenOut = zeroForOne ? key.currency1 : key.currency0;
        uint256 out = uint256(int256(dOut));

        v4Manager.sync(tokenIn);
        ERC20(tokenIn).safeTransfer(address(v4Manager), uint256(-int256(dIn)));
        v4Manager.settle();
        v4Manager.take(tokenOut, address(this), out);
        return (tokenOut, out);
    }

    /*//////////////////////////////////////////////////////////////
                                 ADMIN
    //////////////////////////////////////////////////////////////*/

    /// @dev Removing every caller is the kill switch: funds and listings stay put.
    function setWhitelistedCaller(address caller, bool allowed) external onlyOwner {
        if (caller == address(0)) revert ZeroAddress();
        whitelistedCallers[caller] = allowed;
        emit WhitelistedCallerUpdated(caller, allowed);
    }

    /// @dev A listed pool is paid from the callback, so list only real V3 pools.
    function setPool(address pool, bool listed) external onlyOwner {
        if (pool == address(0)) revert ZeroAddress();
        listedPool[pool] = listed;
        emit PoolListed(pool, listed);
    }

    /// @dev Native-currency and hooked V4 pools are refused: this contract
    ///      settles ERC20s only, and a hook is code the pool runs on every swap.
    function setV4Pool(IV4PoolManager.PoolKey calldata key, bool listed) external onlyOwner {
        if (address(v4Manager) == address(0) || key.currency0 == address(0)) revert ZeroAddress();
        if (key.hooks != address(0)) revert HookedPool();
        bytes32 id = keccak256(abi.encode(key));
        if (listed) v4Key[id] = key;
        else delete v4Key[id];
        emit V4PoolListed(id, listed);
    }

    /// @dev Lists a Ring V2 pair: its fw tokens and their raw tokens are read
    ///      here and stored, so a route can only ever wrap into and swap through
    ///      what the owner listed. Delisting forgets them.
    function setRingPair(address pair, bool listed) external onlyOwner {
        if (pair == address(0)) revert ZeroAddress();
        if (listed) {
            address fw0 = IRingPair(pair).token0();
            address fw1 = IRingPair(pair).token1();
            ringPair[pair] = RingPair({
                fw0: fw0, fw1: fw1, raw0: IFewWrappedToken(fw0).token(), raw1: IFewWrappedToken(fw1).token()
            });
        } else {
            delete ringPair[pair];
        }
        emit RingPairListed(pair, listed);
    }

    /// @notice List a V4 pool without the owner: hookless, ERC20 currencies and
    ///         initialized only. Its tokens are checked against each arb's GM on
    ///         every use, so listing a pool of a fake token gains nothing.
    function listV4Pool(IV4PoolManager.PoolKey calldata key) external {
        if (address(v4Manager) == address(0) || key.currency0 == address(0)) revert ZeroAddress();
        if (key.hooks != address(0)) revert HookedPool();
        bytes32 id = keccak256(abi.encode(key));
        if (blocked[id]) revert PoolNotListed();
        if (v4Key[id].currency0 != address(0)) return;
        // v4-core StateLibrary: pool state at keccak256(id . POOLS_SLOT = 6), slot0 first.
        if (uint160(uint256(v4Manager.extsload(keccak256(abi.encode(id, uint256(6)))))) == 0) revert PoolNotListed();
        v4Key[id] = key;
        v4Open[id] = true;
        emit V4PoolListed(id, true);
    }

    /// @notice Allow (or stop allowing) a V3 factory whose pools trade without
    ///         a listing, or with `quote` a quote token such a pool may hold.
    function setAllowed(address a, bool quote, bool allowed) external onlyOwner {
        if (a == address(0)) revert ZeroAddress();
        (quote ? allowedQuote : allowedFactory)[a] = allowed;
        emit Allowed(a, quote, allowed);
    }

    /// @notice Keep a pool (`bytes32(uint256(uint160(pool)))`) or a V4 id out of
    ///         every route, whatever its factory or listing, until unblocked.
    function setBlocked(bytes32 key, bool isBlocked) external onlyOwner {
        blocked[key] = isBlocked;
        emit Blocked(key, isBlocked);
    }

    function setMaxNotional(uint256 _maxNotional) external onlyOwner {
        maxNotional = _maxNotional;
        emit MaxNotionalUpdated(_maxNotional);
    }

    /// @dev A per-arb ceiling, not a budget: a bot that misprices every arb can
    ///      pay up to this on each. 0 is the kill switch; arbs keep going, unpaid.
    function setMaxBuilderPayment(uint256 _maxWei) external onlyOwner {
        maxBuilderPaymentWei = _maxWei;
        emit MaxBuilderPaymentUpdated(_maxWei);
    }

    /// @notice Enable the funded entry points: wrapped native and the V3 pool
    ///         between it and the stable (mainnet WETH, USDC/WETH 0.05%
    ///         0x88e6A0c2...5640). `wrapped == 0` disables them.
    function setNativeSwap(address wrapped, address pool) external onlyOwner {
        if (wrapped != address(0)) {
            address t0 = IV3Pool(pool).token0();
            address t1 = IV3Pool(pool).token1();
            if (!(t0 == address(stable) && t1 == wrapped) && !(t1 == address(stable) && t0 == wrapped)) {
                revert BadRoute();
            }
        }
        nativeWrapped = wrapped;
        nativePool = pool;
        emit NativeSwapUpdated(wrapped, pool);
    }

    function rescueERC20(address token, address to, uint256 amount) external onlyOwner {
        if (to == address(0)) revert ZeroAddress();
        ERC20(token).safeTransfer(to, amount);
    }
}

src/external/ICurveStableSwap.sol

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

/// @notice The two Curve stableswap calls a stable venue uses.
/// @dev Declared with NO return value on purpose: 3pool
///      (`0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7`, coins DAI/USDC/USDT =
///      0/1/2) returns nothing from `exchange`, while newer pools return the
///      amount. Ignoring returndata serves both, and the caller measures what
///      arrived as a balance delta anyway.
interface ICurveStableSwap {
    function exchange(int128 i, int128 j, uint256 dx, uint256 minDy) external;

    function coins(uint256 i) external view returns (address);
}

src/external/IGMTokenManager.sol

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

/**
 * Ondo Global Markets token manager (mint + redeem).
 *
 * Vendored from dollarparking `contracts/src/OndoMinter.sol`; the redeem side
 * mirrors the live Ondo GMTokenManager ABI (see the `Ondo API` project's
 * `packages/core/src/contracts.ts` GM_TOKEN_MANAGER_ABI). The `Quote` tuple field
 * ORDER is consensus-critical: the off-chain attestation signature is over exactly
 * this layout (go-ethereum packs by order), and the bot's `Quote` struct mirrors
 * it field-for-field. Do not reorder.
 */
interface IGMTokenManager {
    struct Quote {
        uint256 chainId;
        uint256 attestationId;
        bytes32 userId;
        address asset; // the GM token Ondo mints/redeems; read to know what to forward
        uint256 price;
        uint256 quantity;
        uint256 expiration;
        uint8 side; // 0 = buy/mint, 1 = sell/redeem
        bytes32 additionalData;
    }

    /// @notice Verifies the off-chain signature, pulls depositToken from
    ///         msg.sender, mints the GM asset to msg.sender. Reverts if the
    ///         attestation is expired (~30s window) or msg.sender's on-chain
    ///         userId != quote.userId (must be Ondo-whitelisted).
    function mintWithAttestation(
        Quote calldata quote,
        bytes calldata signature,
        address depositToken,
        uint256 depositTokenAmount
    ) external returns (uint256);

    /// @notice The redeem (sell) counterpart of `mintWithAttestation`: verifies the
    ///         off-chain signature, pulls `quote.quantity` of the GM asset
    ///         (`quote.asset`) from msg.sender, burns it, and sends `receiveToken`
    ///         (USDC) back to msg.sender — at least `minimumReceiveAmount` or it
    ///         reverts. Same expiry + userId-whitelist gating as mint
    ///         (`quote.side` must be 1). Returns the receiveToken amount paid out.
    function redeemWithAttestation(
        Quote calldata quote,
        bytes calldata signature,
        address receiveToken,
        uint256 minimumReceiveAmount
    ) external returns (uint256);
}

src/external/IReactor.sol

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

import {ERC20} from "solmate/tokens/ERC20.sol";

/**
 * Minimal vendored subset of Uniswap/UniswapX reactor types.
 *
 * Only the structs and entrypoints our Ondo Executor actually touches are
 * vendored here, to avoid pulling the whole UniswapX dependency tree (permit2,
 * its own solmate/OZ pins) into this repo. The struct layouts MUST stay
 * byte-for-byte identical to UniswapX `base/ReactorStructs.sol` — the reactor
 * ABI-encodes `ResolvedOrder[]` when it calls `reactorCallback`, so any field
 * reorder/removal corrupts decoding.
 *
 * Upstream: https://github.com/Uniswap/UniswapX/blob/main/src/base/ReactorStructs.sol
 */

/// @dev External struct used to specify simple signed orders.
struct SignedOrder {
    bytes order;
    bytes sig;
}

/// @dev Validation contract callback (unused by us; kept for layout fidelity).
interface IValidationCallback {
    function validate(address filler, ResolvedOrder calldata resolvedOrder) external view;
}

struct OrderInfo {
    IReactor reactor;
    address swapper;
    uint256 nonce;
    uint256 deadline;
    IValidationCallback additionalValidationContract;
    bytes additionalValidationData;
}

struct InputToken {
    ERC20 token;
    uint256 amount;
    // Needed for dutch decaying inputs
    uint256 maxAmount;
}

struct OutputToken {
    address token;
    uint256 amount;
    address recipient;
}

struct ResolvedOrder {
    OrderInfo info;
    InputToken input;
    OutputToken[] outputs;
    bytes sig;
    bytes32 hash;
}

/// @notice Callback the reactor invokes on the executor after pulling inputs.
interface IReactorCallback {
    /// @param resolvedOrders the orders being filled; inputs already in executor
    /// @param callbackData arbitrary data the executor passed to the reactor
    function reactorCallback(ResolvedOrder[] calldata resolvedOrders, bytes calldata callbackData) external;
}

/// @notice The reactor we submit fills to.
interface IReactor {
    /// @notice Execute a single order using the given callback data.
    function executeWithCallback(SignedOrder calldata order, bytes calldata callbackData) external payable;

    /// @notice Execute a batch of orders using the given callback data.
    function executeBatchWithCallback(SignedOrder[] calldata orders, bytes calldata callbackData) external payable;
}

src/external/ISwapRouter02.sol

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

/// @notice Minimal Uniswap V3 SwapRouter02 single-pool swap interface.
/// @dev Router `0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45` (same on all chains).
///      PancakeSwap V3's SmartRouter (`0x13f4…68Dd4`, BSC) exposes the same two
///      structs — no `deadline` field, unlike the original V3 SwapRouter.
interface ISwapRouter02 {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);

    struct ExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
}

src/external/IWETH9.sol

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

/// @notice The one WETH9 call the resolver makes: unwrap to native.
/// @dev Mainnet WETH `0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2`; WBNB on BSC
///      `0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c` has the same `withdraw`.
interface IWETH9 {
    function withdraw(uint256 wad) external;
}
Настройки компилятораПоказать
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "solmate/=lib/solmate/src/",
    "ds-test/=lib/solmate/lib/ds-test/src/"
  ]
}

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

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