Skip to content
Verified contractExactMIT

AmmOndoArb

Address0xa4d0356ae27aeea3d97bab5bc000b7d9a1245fe2
Balance

0 ETH

 

Transactions

35

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,425,086
Creation transaction
0x5d7db76796…2838079f3c

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 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;
}

/**
 * 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.
 *
 * 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;

    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);

    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();

    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 1 contracts have no such
    ///         function, so a reverting probe means version 1.
    function arbVersion() external pure returns (uint256) {
        return 4;
    }

    /// @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(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)) {
                    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(stable)) revert BadRoute();
        } else if (q.side == 1) {
            if (a.amountIn > maxNotional) revert NotionalTooLarge();
            if (_route(a.hops, address(stable), a.amountIn) != 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.
    function _route(Hop[] memory hops, address tokenIn, uint256 amountIn) 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)) revert PoolNotListed();
                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 (ringPair[pool].fw0 != address(0)) {
                (tokenIn, amountIn) = _ringSwap(pool, tokenIn, amountIn);
                continue;
            }
            if (!listedPool[pool]) revert PoolNotListed();
            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 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);
    }

    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);
    }
}

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/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/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;
}
Compiler settingsShow
{
  "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/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.