Skip to content
Verified contractExactMIT

UniswapXOndoExecutor

Address0x55425eb9b6a16f45e8ff7e7ceb9c48d064b643fa
Balance

0 ETH

 

Transactions

101

 

Compiler

solc 0.8.24

 

Same code

1 more 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
25,933,260
Creation transaction
0x52876f9ac7…7410fe616c

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

/**
 * 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 on V3 (0.01%)
 *     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.
 *     1. gm.redeemWithAttestation(quote, sig, USDC, minOut) -> USDC to here
 *     2. approve the reactor to pull the owed USDC, which it forwards to the swapper
 *   (A USDT-output redeem would add a USDC->USDT swap leg — not yet supported.)
 *
 *   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.
 *
 * 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 = mint, 1 = redeem.
    /// @dev The two amount fields are per-side and never both meaningful:
    ///      - redeem (side 1): `minOut` is the floor `redeemWithAttestation` 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).
    ///      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)
    }

    /// @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;

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

    /// @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;

    event WhitelistedCallerUpdated(address indexed caller, bool allowed);
    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();

    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 _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[] 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);
        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 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`).
    function ondoFillVersion() external pure returns (uint8) {
        return 2;
    }

    /// @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 = abi.decode(callbackData, (OndoFillV2));

        if (f.legs.length == 1) {
            if (f.legs[0].quote.side == 0) {
                _fillMint(ro, f);
            } else if (f.legs[0].quote.side == 1) {
                _fillRedeem(ro, f);
            } 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();
        }
    }

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

        gmToken.safeApprove(address(gm), leg.quote.quantity);
        uint256 stableBefore = usdc.balanceOf(address(this));
        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.
    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();

        usdc.safeApprove(address(gm), leg.depositAmount);
        uint256 gmBefore = ERC20(owedAsset).balanceOf(address(this));
        gm.mintWithAttestation(leg.quote, leg.signature, address(usdc), leg.depositAmount);
        minted = ERC20(owedAsset).balanceOf(address(this)) - gmBefore;
        if (minted == 0) revert NothingMinted();
    }

    /// @dev MINT (buy GM): input USDC/USDT -> mint the owed GM token -> settle to reactor.
    function _fillMint(ResolvedOrder calldata ro, OndoFillV2 memory f) 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.
        uint256 usdcOut;
        if (address(inputToken) == address(usdc)) {
            usdcOut = amountIn;
        } else if (address(inputToken) == address(usdt)) {
            // Approve exactly what the router pulls; it consumes the full amountIn,
            // leaving zero allowance (safe to re-approve USDT next time).
            inputToken.safeApprove(address(swapRouter), amountIn);
            usdcOut = swapRouter.exactInputSingle(
                ISwapRouter02.ExactInputSingleParams({
                    tokenIn: address(usdt),
                    tokenOut: address(usdc),
                    fee: POOL_FEE,
                    recipient: address(this),
                    amountIn: amountIn,
                    amountOutMinimum: f.swapMinOut,
                    sqrtPriceLimitX96: 0
                })
            );
        } 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 -> settle
    ///      the owed USDC to the reactor. Mirror of mint. MVP: USDC-output orders
    ///      only (Ondo redeems to USDC; a USDT-output order would add a USDC->USDT
    ///      swap leg, not yet supported).
    function _fillRedeem(ResolvedOrder calldata ro, OndoFillV2 memory f) private {
        uint256 gmIn = ro.input.amount; // authoritative amount the reactor delivered
        // MVP: the order must owe USDC (Ondo settles redeem in USDC; no swap leg).
        if (ro.outputs[0].token != address(usdc)) 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, then let the reactor pull the owed USDC. Leftover USDC
        //    (and any GM dust if more was delivered than redeemed) stay here as profit.
        uint256 owed = ro.outputs[0].amount;
        if (usdcOut < owed) revert InsufficientUsdcOut();
        usdc.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 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/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 `exactInputSingle` interface.
/// @dev Router `0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45` (same on all chains).
///      USDC/USDT 0.01% pool = fee tier 100 (deepest stable pool).
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);
}
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.