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

UniswapXOndoExecutor

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

0 ETH

 

Транзакций

1

 

Компилятор

solc 0.8.24

 

Тот же код

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

 

Подробности

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

src/UniswapXOndoExecutor.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 {IGMTokenManager} from "./external/IGMTokenManager.sol";
import {ISwapRouter02} from "./external/ISwapRouter02.sol";
import {IUSDYInstantManager} from "./external/IUSDYInstantManager.sol";
import {ICurveStableSwap} from "./external/ICurveStableSwap.sol";

/**
 * UniswapXOndoExecutor — a UniswapX filler executor for Ondo Global Markets tokens
 * (NVDAon, TSLAon, ...). It fills BOTH directions of a Dutch-auction order, chosen
 * by the Ondo attestation `side` carried in callbackData. The reactor has already
 * pulled the swapper's input into this contract before the callback:
 *
 *   MINT (side 0) — buy GM: input USDC/USDT, output a GM token.
 *     1. obtain USDC: USDC input used directly; USDT input swapped to USDC through
 *        the venue the payload's `SwapRoute` names (see STABLE VENUES below)
 *     2. gm.mintWithAttestation(quote, sig, USDC, mintUsdcAmount) -> GM token to here
 *     3. approve the reactor to pull the GM token, which it forwards to the swapper
 *
 *   REDEEM (side 1) — sell GM: input a GM token, output USDC or USDT.
 *     1. gm.redeemWithAttestation(quote, sig, USDC, minOut) -> USDC to here
 *     2. USDT output only: swap `SwapRoute.stableIn` of those USDC to USDT through
 *        the named venue, which must deliver at least what the order owes (#441)
 *     3. approve the reactor to pull the owed stable, which it forwards to the swapper
 *
 *   STABLE VENUES — where the USDT<->USDC leg of a mint or a redeem trades (#451).
 *     One pool was the only route, and a $250k fill could push it 1.4% off peg
 *     for the next one (2026-11-05: two won quotes faded). The bot now names, per
 *     fill, one venue out of an owner-set list, after quoting each for the exact
 *     size. Venue 0 is built in — Uniswap V3 0.01%, the old fixed route — so a
 *     fresh deploy behaves as the previous version did before the owner lists
 *     anything. A venue is a pool and its parameters, never calldata: the payload
 *     names an id, and the id can reach only USDT and USDC on a target the owner
 *     chose. Every swap is judged by this contract's balance delta, not by what
 *     the venue reports.
 *
 *   SWAP ([redeem, mint]) — GM for GM, e.g. QQQon -> SPYon: input one GM token,
 *   output another. ~20% of GM volume on 1inch Fusion is this shape.
 *     1. gm.redeemWithAttestation on the input leg -> USDC to here
 *     2. gm.mintWithAttestation on the output leg, depositing those proceeds
 *     3. approve the reactor to pull the owed GM
 *   The USDC never leaves this contract and no inventory is held: the two Ondo
 *   calls are one transaction, so an expired attestation on either leg reverts the
 *   whole fill. This is what v1 of this contract could not express — it decoded a
 *   single `quote.side`, which is one Ondo call by construction.
 *
 *   INVENTORY (side 2) — settle out of stock this contract already holds. No
 *     attestation, no mint, no burn, no swap: the reactor has already pulled the
 *     swapper's input in here, so all that remains is to approve the reactor for
 *     the owed output. Both directions collapse to that one operation, and the
 *     incoming asset restocks the side just spent — a buy takes GM off the shelf
 *     and leaves stablecoin, a sell takes stablecoin off the shelf and leaves GM.
 *
 *     What it gives up, stated plainly because it is the whole risk of the mode:
 *     a mispriced mint fill simply REVERTED — the acquire was atomic, so a bad
 *     price could not cost anything. An inventory fill hands over real stock.
 *     Pricing is the bot's job (the reactor still enforces the decayed amount the
 *     order agreed to); what this contract does is bound the damage — see
 *     `inventoryMaxFill`.
 *
 *   USDY (sides 3 and 4) — the MINT and REDEEM shapes above, against USDY's own
 *     primary market (`usdyManager`, Ondo's `USDY_InstantManager`) instead of the
 *     GM manager: side 3 subscribes stable -> USDY, side 4 redeems USDY -> stable.
 *     There is no attestation — USDY prices off an on-chain oracle — so the
 *     leg's `quote` carries only `asset`, `quantity` and `side`, and `signature`
 *     is empty. Every other guard is the GM leg's, unchanged. A contract deployed
 *     with no manager (zero address) rejects both sides `UnsupportedSide`, the
 *     same answer an older contract gives.
 *
 * This contract IS the Ondo-whitelisted user (its on-chain userId must match the
 * attestation's userId) — KYB registers THIS address for BOTH mint and redeem. The
 * off-chain bot fetches the ~30s-valid attestation and submits `execute` within the
 * window; if the tx doesn't mine in time the mint/redeem reverts (attestation
 * expired) and the whole fill reverts atomically — no capital lost, just a missed fill.
 *
 * Profit (leftover USDC from the swap, leftover GM token over the order output)
 * accrues in this contract; the owner withdraws it with `rescue`.
 *
 * Security: holds approvals/funds. `execute` is gated to a whitelisted bot
 * wallet; `reactorCallback` is gated to the reactor (without that gate anyone
 * could invoke the callback and drain approvals). All token ops use
 * SafeTransferLib (USDT returns no bool and would break a plain IERC20).
 */
contract UniswapXOndoExecutor is IReactorCallback, Owned {
    using SafeTransferLib for ERC20;

    /// @notice One Ondo call. `quote.side` says which: 0 = GM mint, 1 = GM redeem,
    ///         3 = USDY subscribe, 4 = USDY redeem.
    /// @dev The two amount fields are per-side:
    ///      - redeem (sides 1, 4): `minOut` is the floor the redeem must pay in
    ///        the settlement stable, and `depositAmount` is unused (0).
    ///      - mint   (side 0): `depositAmount` is the stable deposited into
    ///        `mintWithAttestation`, and `minOut` is unused (0).
    ///      - subscribe (side 3): `depositAmount` is the stable deposited, and
    ///        `minOut` is the floor on the USDY received.
    ///      v1 packed both meanings into one `swapMinOut`, which also carried the
    ///      USDT->USDC input-swap floor — three jobs in one field.
    struct Leg {
        IGMTokenManager.Quote quote; // Ondo attestation quote (signed off-chain)
        bytes signature; // Ondo attestation signature
        uint256 minOut; // redeem: floor on the stable received
        uint256 depositAmount; // mint: stable deposited
    }

    /// @notice Decoded from `callbackData`; built off-chain by the bot.
    ///
    /// @dev A BOUNDED sequence of Ondo calls, not a single tagged one. Three legal
    ///      shapes, and `_dispatch` rejects everything else:
    ///
    ///        [mint]           stable -> GM   (v1's side 0)
    ///        [redeem]         GM -> stable   (v1's side 1)
    ///        [redeem, mint]   GM -> GM       (new)
    ///
    ///      The array is what makes the third shape expressible at all, and it is
    ///      why a fourth would not need another deploy — this contract is immutable
    ///      and Ondo KYB-whitelists it BY ADDRESS for mint and redeem, so every
    ///      redeploy costs an approval round with them.
    ///
    ///      It is still a TYPED payload, not a generic multicall: a leg names an
    ///      Ondo attestation and nothing else. There is no `{target, value, data}`
    ///      here and there must never be — this contract holds standing approvals.
    struct OndoFillV2 {
        Leg[] legs; // 1 or 2, see above
        uint256 swapMinOut; // min USDC out of the USDT->USDC input swap (mint-from-USDT only)
    }

    /// @notice Which venue the stable leg trades on, decoded alongside the fill:
    ///         `callbackData = abi.encode(OndoFillV2, SwapRoute)` (version 4).
    /// @dev Kept OUT of `OndoFillV2` on purpose: that struct is byte-identical to
    ///      `OneInchOndoResolver`'s and to the bot's one Rust encoder (AbiParity),
    ///      so a field added to it would fork the encoding of a contract that is
    ///      not changing. The route is a sibling the bot appends.
    ///      - `venue`: 0 = the built-in V3 0.01% pool; anything else must be listed.
    ///      - `stableIn`: USDC sold into a USDT-output redeem (at most what the
    ///        redeem paid; the order's owed USDT is the swap's floor). Unused (0)
    ///        on a mint, which swaps the whole delivered input with `swapMinOut`
    ///        as its floor.
    struct SwapRoute {
        uint8 venue;
        uint256 stableIn;
    }

    /// @notice An owner-listed stable venue. `kind` 0 = not listed.
    /// @dev `KIND_V3`: a Uniswap V3 pool of `fee` through `swapRouter` (`pool`
    ///      unused). `KIND_CURVE`: a Curve stableswap `pool` whose coin indices for
    ///      USDT and USDC are `iUsdt` / `iUsdc` (checked against `coins()` when listed).
    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 Legs a payload may carry. Two is what GM -> GM needs; the bound exists
    ///      so a malformed or adversarial payload cannot loop this contract's
    ///      approvals an unbounded number of times.
    uint256 internal constant MAX_LEGS = 2;

    /// @dev Uniswap V3 USDC/USDT pool: 0.01% fee tier (deepest stable pool).
    uint24 internal constant POOL_FEE = 100;

    /// @dev Gas forwarded with a direct builder payment. `block.coinbase` is an
    ///      address the block PRODUCER chooses, so this call hands control to a
    ///      party we do not pick and cannot simulate against. Unbounded, a
    ///      hostile producer could burn the transaction's remaining gas and still
    ///      return false. Same figure and reasoning as `OneInchOndoResolver`.
    uint256 internal constant BUILDER_PAYMENT_GAS = 100_000;

    IReactor public immutable reactor;
    IGMTokenManager public immutable gm;
    ISwapRouter02 public immutable swapRouter;
    ERC20 public immutable usdt;
    ERC20 public immutable usdc;
    /// @notice Ondo `USDY_InstantManager`, or zero where USDY legs are not offered.
    IUSDYInstantManager public immutable usdyManager;
    /// @notice The token `usdyManager` mints and burns (zero with no manager).
    ///         Read from the manager at deploy, so the two cannot disagree.
    ERC20 public immutable usdy;

    /// @notice Bot wallets allowed to submit fills (gas payers).
    /// @dev A SET, not a single address, because each wallet is an independent
    ///      nonce lane. One EOA can only have one transaction pending per nonce,
    ///      so a burst of fills queues: transaction N+1 cannot mine before N, and
    ///      every fill behind the head targets a block it cannot reach. Measured
    ///      on mainnet, submissions inside 12s of each other won 30.8% of the time
    ///      against 55.6% for isolated ones. Independent lanes remove the ordering
    ///      dependency between concurrent fills entirely.
    mapping(address => bool) public whitelistedCallers;

    /// @notice Per-token ceiling on a SINGLE inventory fill, denominated in the
    ///         asset we hand over (18-dp GM on a buy, 6-dp USDC on a sell).
    ///         Zero — the value every entry has on a fresh deploy — disables
    ///         inventory filling in that token.
    /// @dev One mapping doing three jobs, for one cold SLOAD on a path whose
    ///      entire point is gas:
    ///        - default-off: inventory cannot fill until the owner opts a token in,
    ///          so deploying this contract changes nothing until someone decides it should;
    ///        - kill switch: setting a token back to 0 stops inventory fills in it
    ///          immediately, leaving funds, reactor binding and caller whitelist untouched —
    ///          the Ondo path keeps filling while the shelf is frozen;
    ///        - blast radius: the caller whitelist is all that stands between a
    ///          compromised bot key and the shelf. Before inventory that was worth
    ///          leftover dust; now it is worth the stock.
    ///      Per-token rather than one global scalar because the cap is denominated
    ///      in the asset handed over, and one number cannot mean the same thing in
    ///      both 18-dp GM and 6-dp USDC.
    mapping(address => uint256) public inventoryMaxFill;

    /// @notice Ceiling on a SINGLE direct builder payment, in wei. 0 — the
    ///         state a fresh deploy starts in — refuses every non-zero payment,
    ///         so PAYING is opt-in, by the owner, after deploy.
    /// @dev    A cap of 0 does not close `executeWithBuilderPayment`: it still
    ///         settles an ordinary fill with `payment == 0`. Per call, never a
    ///         cumulative budget — and since the payment must arrive as exactly
    ///         `msg.value`, this contract holds no ETH between fills, so the cap
    ///         is the whole risk of one fill.
    ///         Same semantics as the 1inch resolver's cap; runbook in
    ///         `contracts/BUILDER-PAYMENT.md`.
    uint256 public maxBuilderPaymentWei;

    /// @notice Stable venues the bot may name in `SwapRoute.venue` (id 0 is the
    ///         built-in V3 0.01% route and is never stored here).
    mapping(uint8 => Venue) public venues;

    event VenueSet(uint8 indexed id, uint8 kind, address pool, uint24 fee, int128 iUsdt, int128 iUsdc);
    /// @notice One stable leg: `amountIn` of `tokenIn` sold on venue `venue` for
    ///         `amountOut` of the other stable, measured as a balance delta.
    event StableSwapped(bytes32 indexed orderHash, uint8 indexed venue, address tokenIn, uint256 amountIn, uint256 amountOut);

    event MaxBuilderPaymentUpdated(uint256 maxWei);
    /// @notice A direct `block.coinbase` payment made alongside a settled fill.
    event BuilderPaid(address indexed builder, uint256 amount);

    event WhitelistedCallerUpdated(address indexed caller, bool allowed);
    event InventoryMaxFillUpdated(address indexed token, uint256 maxFill);
    /// @notice Emitted on an inventory fill: `amountOut` of `assetOut` left the
    ///         shelf to settle the order, and `amountIn` of `assetIn` arrived to
    ///         restock the other side.
    event SettledFromInventory(
        bytes32 indexed orderHash,
        address indexed assetOut,
        uint256 amountOut,
        address assetIn,
        uint256 amountIn
    );
    event Filled(
        bytes32 indexed orderHash, address indexed asset, uint256 amountIn, uint256 usdcOut, uint256 minted
    );
    /// @notice Emitted on a redeem (sell) fill: `gmIn` GM redeemed -> `usdcOut` USDC
    ///         from Ondo, of which `owed` settles the order (the rest is profit).
    event Redeemed(
        bytes32 indexed orderHash, address indexed asset, uint256 gmIn, uint256 usdcOut, uint256 owed
    );

    /// @notice Emitted on a GM -> GM fill: `gmIn` of `assetIn` redeemed to
    ///         `stableMid` in the settlement stable, which minted `minted` of
    ///         `assetOut`, of which `owed` settles the order.
    event Swapped(
        bytes32 indexed orderHash,
        address indexed assetIn,
        address indexed assetOut,
        uint256 gmIn,
        uint256 stableMid,
        uint256 minted,
        uint256 owed
    );

    error NotReactor();
    error NotWhitelistedCaller();
    error NoCallers();
    error ZeroAddress();
    error UnsupportedSide();
    error UnsupportedInput();
    error UnsupportedOutput();
    error OutputAssetMismatch();
    error InputAssetMismatch();
    error InsufficientUsdcOut();
    error NothingMinted();
    error InsufficientMint();
    error NothingRedeemed();
    error RedeemExceedsInput();
    /// @dev `legs` was empty or longer than MAX_LEGS.
    error BadLegCount();
    /// @dev A two-leg payload that is not exactly [redeem, mint]. Checked on the
    ///      SIDES rather than inferred from the tokens: [mint, redeem] would spend
    ///      this contract's own stable balance and leave GM dust behind, and
    ///      [redeem, redeem] would burn inventory. Neither is a shape we ever build.
    error BadLegShape();
    error InventoryDisabled();
    error InventoryFillTooLarge();
    error InsufficientInventory();
    error BuilderPaymentTooLarge();
    error BuilderPaymentFailed();
    /// @dev `msg.value` must be exactly `payment` (as on `AmmOndoArb`). Checked
    ///      before the fill: a short balance makes `block.coinbase.call` return
    ///      false, which would read as the builder refusing the transfer, and an
    ///      excess would stay here for a later call to spend.
    error BuilderPaymentMismatch();
    /// @dev `SwapRoute.venue` names no listed venue.
    error UnknownVenue();
    /// @dev A venue the owner tried to list is malformed (id 0, no fee, no pool,
    ///      or coin indices that do not point at USDT and USDC).
    error BadVenue();
    /// @dev The stable leg delivered less than its floor.
    error InsufficientSwapOut();

    modifier onlyReactor() {
        if (msg.sender != address(reactor)) revert NotReactor();
        _;
    }

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

    /// @param _owner            admin (should be a multisig/timelock in prod)
    /// @param _reactor          per-chain UniswapX reactor (deploy-time env, never hardcoded)
    /// @param _gm               Ondo GM token manager
    /// @param _swapRouter       Uniswap V3 SwapRouter02
    /// @param _usdt             input token pulled from swappers
    /// @param _usdc             Ondo mint deposit token
    /// @param _usdyManager      Ondo USDY_InstantManager; zero disables sides 3 and 4
    /// @param _callers        bot wallets allowed to call `execute` (nonce lanes; at least one)
    constructor(
        address _owner,
        address _reactor,
        address _gm,
        address _swapRouter,
        address _usdt,
        address _usdc,
        address _usdyManager,
        address[] memory _callers
    ) Owned(_owner) {
        if (
            _owner == address(0) || _reactor == address(0) || _gm == address(0)
                || _swapRouter == address(0) || _usdt == address(0) || _usdc == address(0)
        ) revert ZeroAddress();
        if (_callers.length == 0) revert NoCallers();
        reactor = IReactor(_reactor);
        gm = IGMTokenManager(_gm);
        swapRouter = ISwapRouter02(_swapRouter);
        usdt = ERC20(_usdt);
        usdc = ERC20(_usdc);
        usdyManager = IUSDYInstantManager(_usdyManager);
        usdy = ERC20(_usdyManager == address(0) ? address(0) : IUSDYInstantManager(_usdyManager).rwaToken());
        for (uint256 i; i < _callers.length; ++i) {
            if (_callers[i] == address(0)) revert ZeroAddress();
            whitelistedCallers[_callers[i]] = true;
            emit WhitelistedCallerUpdated(_callers[i], true);
        }
    }

    /// @notice Submit a single Ondo fill. The bot builds `callbackData` as an
    ///         abi-encoded `OndoFill` carrying a fresh attestation.
    function execute(SignedOrder calldata order, bytes calldata callbackData)
        external
        onlyWhitelistedCaller
    {
        reactor.executeWithCallback(order, callbackData);
    }

    /// @notice `execute`, then `payment` wei to `block.coinbase`, atomically.
    /// @dev Once a UniswapX order's exclusivity window closes it is an open race
    ///      decided in one block, and a bundle is ranked by what it pays the
    ///      builder, not by priority fee (#372: 59 of 71 lost post-window V2
    ///      orders went to a rival in the block we targeted, while we bid $0).
    ///      Only meaningful on the bundle route; the bot never pays on a
    ///      public-only submit.
    ///
    ///      The payment is exactly `msg.value`, paid per fill from the submitting
    ///      lane; this contract never funds it. It is made LAST: a reverting fill pays nothing, and a re-entering
    ///      coinbase finds no state left to corrupt (and would need to be a
    ///      whitelisted caller to do anything).
    function executeWithBuilderPayment(SignedOrder calldata order, bytes calldata callbackData, uint256 payment)
        external
        payable
        onlyWhitelistedCaller
    {
        if (payment > maxBuilderPaymentWei) revert BuilderPaymentTooLarge();
        if (msg.value != payment) revert BuilderPaymentMismatch();

        reactor.executeWithCallback(order, callbackData);

        if (payment != 0) {
            // Raw call with a bounded forward: builder 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);
        }
    }

    /// @notice The `callbackData` layout this contract decodes. v1 decoded a single
    ///         tagged `OndoFill`; v2 decodes `OndoFillV2` with a leg array, and the
    ///         two encodings are not interchangeable in either direction.
    /// @dev Read by the bot at startup to pick an encoder per executor address, so
    ///      one image can serve old and new deployments while a migration is in
    ///      flight. A v1 contract has no such function and the call reverts — which
    ///      is the answer, not an error (`verify-multilane.sh` already uses the same
    ///      reverts-means-old-bytecode trick for `whitelistedCallers`).
    ///
    ///      3 = the v2 layout, unchanged, plus USDY sides 3 and 4. The payload is
    ///      byte-compatible with v2, so the bump only says which SIDES decode; a
    ///      v2 contract handed side 3 or 4 reverts `UnsupportedSide`. Whether
    ///      THIS address offers USDY is `usdyManager() != 0`, not the version.
    ///
    ///      4 = `abi.encode(OndoFillV2, SwapRoute)`: the v3 fill with a stable
    ///      route appended (#451), and USDT-output redeems (#441). NOT
    ///      byte-compatible either way: a v3 payload sent here, or a v4 one to a
    ///      v3 contract, fails to decode and the fill reverts with no selector.
    function ondoFillVersion() external pure returns (uint8) {
        return 4;
    }

    /// @notice Reactor callback. The order's input is already in this contract; the
    ///         leg array selects what we do with it.
    function reactorCallback(ResolvedOrder[] calldata resolvedOrders, bytes calldata callbackData)
        external
        override
        onlyReactor
    {
        // Single-order Ondo flow.
        ResolvedOrder calldata ro = resolvedOrders[0];
        (OndoFillV2 memory f, SwapRoute memory r) = abi.decode(callbackData, (OndoFillV2, SwapRoute));

        if (f.legs.length == 1) {
            uint8 side = f.legs[0].quote.side;
            // Before anything moves: a mint-side fill swaps its input first, and
            // a contract with no USDY manager must refuse without doing so.
            if ((side == 3 || side == 4) && address(usdyManager) == address(0)) revert UnsupportedSide();
            if (side == 0 || side == 3) {
                _fillMint(ro, f, r);
            } else if (side == 1 || side == 4) {
                _fillRedeem(ro, f, r);
            } else if (side == 2) {
                _fillInventory(ro);
            } else {
                revert UnsupportedSide();
            }
        } else if (f.legs.length == MAX_LEGS) {
            // Exactly [redeem, mint]. Asserted on the sides, never inferred from the
            // tokens: the token checks inside each leg would pass for [mint, redeem]
            // on an order whose input and output happened to line up, and that
            // ordering spends stable this fill did not earn.
            if (f.legs[0].quote.side != 1 || f.legs[1].quote.side != 0) revert BadLegShape();
            _fillSwap(ro, f);
        } else {
            revert BadLegCount();
        }
    }

    /// @dev INVENTORY: settle the order's owed output out of what this contract
    ///      already holds. The swapper's input is already here (the reactor
    ///      pulled it before the callback) and needs no handling — it simply
    ///      restocks the opposite side of the shelf.
    function _fillInventory(ResolvedOrder calldata ro) private {
        address assetOut = ro.outputs[0].token;
        uint256 owed = ro.outputs[0].amount;

        // Cap first: one cold SLOAD, and it rejects a disabled token before we
        // pay for an external balance call.
        uint256 cap = inventoryMaxFill[assetOut];
        if (cap == 0) revert InventoryDisabled();
        if (owed > cap) revert InventoryFillTooLarge();

        // The reactor's transferFrom would fail anyway if the shelf were short,
        // but with no clue which token ran out — the same trade `_fillMint`
        // already makes with `InsufficientMint`.
        if (ERC20(assetOut).balanceOf(address(this)) < owed) revert InsufficientInventory();

        // Approve exactly what the order owes, so no standing reactor allowance
        // is left behind (mirrors both Ondo paths).
        ERC20(assetOut).safeApprove(address(reactor), owed);

        emit SettledFromInventory(
            ro.hash, assetOut, owed, address(ro.input.token), ro.input.amount
        );
    }

    /*//////////////////////////////////////////////////////////////
                              ONDO LEGS
    //////////////////////////////////////////////////////////////*/

    /// @dev One REDEEM leg: burn `leg.quote.quantity` of `gmToken` and receive the
    ///      settlement stable here. Returns what was ACTUALLY received, measured as
    ///      a balance delta rather than taken from the return value, so a
    ///      fee-on-transfer stable cannot over-report what this fill can spend.
    ///
    ///      `delivered` caps the quantity. Without that cap Ondo would pull the
    ///      difference from THIS contract's own GM inventory — a silent loss — and
    ///      the bot sizes `quote.quantity` to the fill, so this only ever catches a
    ///      stale or oversized attestation.
    ///
    ///      Side 4 is the same leg against `usdyManager`: no attestation, and the
    ///      token must be USDY itself.
    function _ondoRedeem(Leg memory leg, ERC20 gmToken, uint256 delivered)
        private
        returns (uint256 stableOut)
    {
        if (address(gmToken) != leg.quote.asset) revert InputAssetMismatch();
        if (leg.quote.quantity > delivered) revert RedeemExceedsInput();

        uint256 stableBefore = usdc.balanceOf(address(this));
        if (leg.quote.side == 4) {
            if (address(gmToken) != address(usdy)) revert InputAssetMismatch();
            gmToken.safeApprove(address(usdyManager), leg.quote.quantity);
            usdyManager.redeem(leg.quote.quantity, address(usdc), leg.minOut);
        } else {
            gmToken.safeApprove(address(gm), leg.quote.quantity);
            gm.redeemWithAttestation(leg.quote, leg.signature, address(usdc), leg.minOut);
        }
        stableOut = usdc.balanceOf(address(this)) - stableBefore;
        if (stableOut == 0) revert NothingRedeemed();
    }

    /// @dev One MINT leg: deposit `leg.depositAmount` of the settlement stable and
    ///      receive `owedAsset` here. Returns what was ACTUALLY received, as a
    ///      balance delta rather than the manager's return value — the same
    ///      measurement `_ondoRedeem` takes, so neither leg trusts a counterparty
    ///      to report what this contract can settle with.
    ///
    ///      `available` is the stable THIS FILL produced — the swapped input on a
    ///      mint, the redeem's proceeds on a swap — and requiring it to cover the
    ///      deposit is load-bearing, not a restatement of the balance. Profit
    ///      accrues here in the settlement stable between fills, so without this
    ///      check a fill could quietly mint from the accumulated profit and still
    ///      settle: every guard downstream would pass and the loss would show up
    ///      only as a balance that stopped growing.
    ///
    ///      Side 3 is the same leg against `usdyManager`: no attestation, the
    ///      owed token must be USDY itself, and `leg.minOut` floors what it mints.
    function _ondoMint(Leg memory leg, address owedAsset, uint256 available)
        private
        returns (uint256 minted)
    {
        if (owedAsset != leg.quote.asset) revert OutputAssetMismatch();
        if (available < leg.depositAmount) revert InsufficientUsdcOut();

        uint256 gmBefore = ERC20(owedAsset).balanceOf(address(this));
        if (leg.quote.side == 3) {
            if (owedAsset != address(usdy)) revert OutputAssetMismatch();
            usdc.safeApprove(address(usdyManager), leg.depositAmount);
            usdyManager.subscribe(address(usdc), leg.depositAmount, leg.minOut);
        } else {
            usdc.safeApprove(address(gm), leg.depositAmount);
            gm.mintWithAttestation(leg.quote, leg.signature, address(usdc), leg.depositAmount);
        }
        minted = ERC20(owedAsset).balanceOf(address(this)) - gmBefore;
        if (minted == 0) revert NothingMinted();
    }

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

    /// @dev Sell `amountIn` of one stable for the other on venue `venueId`, and
    ///      return what ARRIVED, as a balance delta: the venue's own return value
    ///      is not trusted, and a Curve pool returns nothing at all. Reverts below
    ///      `minOut`. The approval is exact and is cleared afterwards, so no
    ///      standing allowance outlives the fill — and USDT, which refuses a
    ///      non-zero -> non-zero approve, still approves on the next 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: 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);
    }

    /// @dev MINT (buy GM): input USDC/USDT -> mint the owed GM token -> settle to reactor.
    function _fillMint(ResolvedOrder calldata ro, OndoFillV2 memory f, SwapRoute memory r) private {
        // The asset Ondo will mint must be exactly what the swapper is owed.
        // Checked HERE, before the input swap, as well as inside `_ondoMint`: a
        // mismatch is a bot bug, and catching it first keeps the revert readable
        // (the simulation gate decodes these selectors) instead of surfacing as
        // whatever the swap leg happens to do with a nonsense deposit. `_ondoMint`
        // keeps its own copy because it is also `_fillSwap`'s only such guard.
        if (ro.outputs[0].token != f.legs[0].quote.asset) revert OutputAssetMismatch();

        ERC20 inputToken = ro.input.token;
        uint256 amountIn = ro.input.amount; // authoritative amount the reactor delivered

        // 1. Obtain the stable to mint with. USDC input is used directly (no swap —
        //    cheaper gas, no swap slippage); USDT input is swapped to USDC first, on
        //    the venue the bot picked for this size, floored at `swapMinOut`.
        uint256 usdcOut;
        if (address(inputToken) == address(usdc)) {
            usdcOut = amountIn;
        } else if (address(inputToken) == address(usdt)) {
            usdcOut = _stableSwap(ro.hash, r.venue, usdt, usdc, amountIn, f.swapMinOut);
        } else {
            revert UnsupportedInput();
        }

        // 2. Mint the GM token to this contract (msg.sender == whitelisted entity).
        //    The asset Ondo mints must be exactly what the swapper is owed, and the
        //    deposit must be covered by the stable this fill just sourced — both
        //    checked inside `_ondoMint`.
        uint256 owed = ro.outputs[0].amount;
        uint256 minted = _ondoMint(f.legs[0], ro.outputs[0].token, usdcOut);
        // Must have minted at least what the swapper is owed. Fail early with a clear
        // error rather than relying on the reactor's transferFrom to revert implicitly.
        if (minted < owed) revert InsufficientMint();

        // 3. Let the reactor pull the owed GM to pay the swapper. Approve exactly
        //    `owed` (mirror _fillRedeem): the leftover GM (minted - owed) and leftover
        //    USDC stay here as profit with NO standing reactor allowance in between.
        ERC20(ro.outputs[0].token).safeApprove(address(reactor), owed);

        emit Filled(ro.hash, f.legs[0].quote.asset, amountIn, usdcOut, minted);
    }

    /// @dev REDEEM (sell GM): input a GM token -> redeem for USDC via Ondo -> (USDT
    ///      output: swap part of it to USDT) -> settle the owed stable to the
    ///      reactor. Mirror of mint.
    function _fillRedeem(ResolvedOrder calldata ro, OndoFillV2 memory f, SwapRoute memory r) private {
        uint256 gmIn = ro.input.amount; // authoritative amount the reactor delivered
        // Checked before the redeem, so an output we cannot pay fails before Ondo
        // is called (the order `_fillMint` checks its output asset in).
        ERC20 owedAsset = ERC20(ro.outputs[0].token);
        if (address(owedAsset) != address(usdc) && address(owedAsset) != address(usdt)) revert UnsupportedOutput();

        // 1. Redeem the GM for USDC. Asset match and the "never redeem more than was
        //    delivered" cap live in `_ondoRedeem`.
        uint256 usdcOut = _ondoRedeem(f.legs[0], ro.input.token, gmIn);

        // 2. Cover the order. Leftover stable (and any GM dust if more was delivered
        //    than redeemed) stays here as profit.
        uint256 owed = ro.outputs[0].amount;
        if (owedAsset == usdc) {
            if (usdcOut < owed) revert InsufficientUsdcOut();
        } else {
            // USDT owed (#441): sell `stableIn` of THIS fill's proceeds for at least
            // `owed`. Capping it at `usdcOut` is the redeem-side twin of
            // `_ondoMint`'s `available` check: the swap may spend the fill's margin,
            // never the contract's accumulated profit.
            if (r.stableIn == 0 || r.stableIn > usdcOut) revert InsufficientUsdcOut();
            _stableSwap(ro.hash, r.venue, usdc, usdt, r.stableIn, owed);
        }
        owedAsset.safeApprove(address(reactor), owed);

        emit Redeemed(ro.hash, f.legs[0].quote.asset, gmIn, usdcOut, owed);
    }

    /// @dev SWAP (GM -> GM): redeem the input leg into the settlement stable, mint
    ///      the output leg with those proceeds, settle the owed GM to the reactor.
    ///
    ///      No new trust: it is `_fillRedeem`'s first half followed by `_fillMint`'s
    ///      second, sharing every guard. What is new is the join between them — the
    ///      mint may only spend what the redeem just produced (`stableOut`), never
    ///      this contract's accumulated profit. See `_ondoMint`.
    ///
    ///      Ondo charges its spread on BOTH legs and the fill burns roughly double a
    ///      one-leg fill's gas, so the economics are decided off-chain; on-chain the
    ///      only question is whether the output covers what is owed.
    function _fillSwap(ResolvedOrder calldata ro, OndoFillV2 memory f) private {
        uint256 gmIn = ro.input.amount; // authoritative amount the reactor delivered
        uint256 owed = ro.outputs[0].amount;

        uint256 stableOut = _ondoRedeem(f.legs[0], ro.input.token, gmIn);
        uint256 minted = _ondoMint(f.legs[1], ro.outputs[0].token, stableOut);
        if (minted < owed) revert InsufficientMint();

        // Leftover stable (stableOut - deposit) and leftover GM (minted - owed) both
        // stay here as profit, with no standing reactor allowance in between.
        ERC20(ro.outputs[0].token).safeApprove(address(reactor), owed);

        emit Swapped(
            ro.hash, f.legs[0].quote.asset, f.legs[1].quote.asset, gmIn, stableOut, minted, owed
        );
    }

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

    /// @notice Add or remove a bot wallet allowed to submit fills.
    /// @dev Removing the last caller is permitted and stops filling entirely. That
    ///      is deliberate: it gives the owner a kill switch that does not disturb
    ///      the reactor binding or the token approvals.
    function setWhitelistedCaller(address _caller, bool _allowed) external onlyOwner {
        if (_caller == address(0)) revert ZeroAddress();
        whitelistedCallers[_caller] = _allowed;
        emit WhitelistedCallerUpdated(_caller, _allowed);
    }

    /// @notice Set the per-fill inventory ceiling for `token` (0 disables it).
    /// @dev The only way inventory filling is ever switched on, and the fastest
    ///      way to switch it off: setting a token to 0 stops inventory fills in
    ///      it on the next block while leaving the funds, the reactor binding and
    ///      the caller whitelist alone, so the Ondo path keeps filling meanwhile.
    function setInventoryMaxFill(address token, uint256 maxFill) external onlyOwner {
        if (token == address(0)) revert ZeroAddress();
        inventoryMaxFill[token] = maxFill;
        emit InventoryMaxFillUpdated(token, maxFill);
    }

    /// @notice List (or, with `kind` 0, delist) stable venue `id` for the bot to
    ///         name in `SwapRoute.venue`.
    /// @dev Id 0 is the built-in V3 0.01% route and cannot be changed. A Curve
    ///      listing is checked against the pool's own `coins()`, so a wrong index
    ///      cannot swap a third coin of the pool (3pool's DAI) into this contract.
    ///      Delisting is immediate and is the kill switch for a venue gone bad;
    ///      venue 0 keeps working throughout.
    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 direct builder payment (wei).
    /// @dev Starts at 0, which refuses every non-zero payment while leaving the
    ///      entry point open for `payment == 0` fills. Setting it back to 0 is
    ///      the payment kill switch; fills keep working.
    function setMaxBuilderPayment(uint256 _maxWei) external onlyOwner {
        maxBuilderPaymentWei = _maxWei;
        emit MaxBuilderPaymentUpdated(_maxWei);
    }

    /// @notice Emitted by `restock`: the shelf was topped up (side 0, stable in
    ///         and GM out of Ondo) or trimmed (side 1, GM in and stable out).
    event Restocked(address indexed asset, uint8 side, uint256 stableAmount, uint256 gmAmount);

    /// @notice Re-centre the shelf through Ondo, out of THIS contract's own
    ///         balances. A one-leg MINT deposits `depositAmount` of the settlement
    ///         stable and takes the minted GM onto the shelf; a one-leg REDEEM
    ///         burns `quote.quantity` of shelf GM for stable. Nothing leaves the
    ///         contract either way — a rogue caller can churn, not drain — and the
    ///         token must already be opted in via `inventoryMaxFill`, so the switch
    ///         that starts shelf fills is the one that permits restocking them.
    /// @dev Caller-gated like a fill: the bot decides WHEN (the shelf's band), Ondo
    ///      decides the PRICE (the signed attestation), and this contract bounds
    ///      WHAT (own funds, an opted-in token, one leg). `_ondoMint` is handed the
    ///      whole stable balance as `available` on purpose — minting out of
    ///      accumulated proceeds is exactly what a restock is, where in a fill it
    ///      would be spending profit the fill never earned.
    function restock(OndoFillV2 calldata f) external onlyWhitelistedCaller {
        if (f.legs.length != 1) revert BadLegCount();
        Leg memory leg = f.legs[0];
        address asset = leg.quote.asset;
        if (inventoryMaxFill[asset] == 0) revert InventoryDisabled();
        if (leg.quote.side == 0) {
            uint256 minted = _ondoMint(leg, asset, usdc.balanceOf(address(this)));
            emit Restocked(asset, 0, leg.depositAmount, minted);
        } else if (leg.quote.side == 1) {
            uint256 stableOut = _ondoRedeem(leg, ERC20(asset), ERC20(asset).balanceOf(address(this)));
            emit Restocked(asset, 1, stableOut, leg.quote.quantity);
        } else {
            revert UnsupportedSide();
        }
    }

    /// @notice Withdraw ERC20 profit / 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 (e.g. accidental sends).
    function rescueETH(address to, uint256 amount) external onlyOwner {
        if (to == address(0)) revert ZeroAddress();
        SafeTransferLib.safeTransferETH(to, amount);
    }

    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/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/IUSDYInstantManager.sol

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

/**
 * Ondo `USDY_InstantManager`: USDY's own primary market. Unlike the GM token
 * manager there is no attestation: the price is an on-chain oracle read, so a
 * subscribe or redeem needs nothing signed off-chain.
 *
 * Signatures from the verified mainnet contract (`0xa42613C2…1f15`), checked
 * 2026-10-22. The caller must be registered for USDY in `OndoIDRegistry`
 * (`UserNotRegistered`, `0x2163950f`, otherwise); every fill contract in
 * `deployments.json` is. Accepted tokens differ per chain: mainnet takes and
 * pays USDC only, BNB Chain USDT only — in both cases the fill contracts'
 * settlement stable. Minimums are $1 each way (`minimumDepositUSD`,
 * `minimumRedemptionUSD`); fee was 0 bps both ways on 2026-10-20.
 */
interface IUSDYInstantManager {
    /// @notice The USDY token this manager mints and burns.
    function rwaToken() external view returns (address);

    /// @notice Pulls `depositAmount` of `depositToken` from msg.sender and mints
    ///         USDY to msg.sender at the oracle price. Reverts
    ///         `RwaReceiveAmountTooSmall` under `minimumRwaReceived`.
    function subscribe(address depositToken, uint256 depositAmount, uint256 minimumRwaReceived)
        external
        returns (uint256 rwaAmountOut);

    /// @notice Burns `rwaAmount` of USDY from msg.sender and pays `receivingToken`
    ///         to msg.sender at the oracle price. Reverts `ReceiveAmountTooSmall`
    ///         under `minimumTokenReceived`.
    function redeem(uint256 rwaAmount, address receivingToken, uint256 minimumTokenReceived)
        external
        returns (uint256 receiveTokenAmount);
}
Настройки компилятораПоказать
{
  "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.

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