Skip to content
Verified contractExactMIT

OndoGmAdapter

Address0x79878dd1e27a6f6407b7ea74809369825ee39bbf
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 1 runs
EVM version
paris
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,445,696
Creation transaction
0x49b6449c5d…e58facb7ee

contracts/adapters/ondo/OndoGmAdapter.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";

import {IAdapter} from "../base/IAdapter.sol";
import {AdapterErrors} from "../base/AdapterErrors.sol";
import {IGMTokenManager, IOndoIDRegistry, IOndoSanityCheckOracle} from "./IOndoGm.sol";

interface IOndoAdapterEscrow {
    function underlyingToken() external view returns (address);
    function hasRole(bytes32 role, address account) external view returns (bool);
}

/// @title OndoGmAdapter
/// @notice Buys and sells one Ondo Global Markets token (an ETF token such as
///         SGOVon) for one weavr pool's `AssetManagerEscrow`, by Ondo's primary
///         mint and redeem at a price Ondo signs (`GMTokenManager`
///         `mintWithAttestation` / `redeemWithAttestation`).
///
/// @dev Why this contract exists. Ondo's manager mints to and pays
///      `msg.sender` only, and `msg.sender` must have a userId in Ondo's ID
///      registry equal to `quote.userId`. The escrow cannot be that caller (it
///      has no generic call and cannot approve the manager), so this contract
///      is: it is the address Ondo registers, and the only caller of the
///      manager on our side.
///
///      Who holds what. The escrow holds the position (the GM token) and the
///      USDC. A trade is one synchronous call: the escrow pushes the input with
///      `pushAndExecute`, this contract pays exactly the quote's cost (buy) or
///      exactly its quantity (sell), and forwards the measured output to the
///      escrow in the same transaction. Nothing rests here between calls. Any
///      failure on Ondo's side reverts the whole `pushAndExecute`, so the
///      funds never leave the escrow; an expired quote is a revert, not a
///      quiet success.
///
///      The one barrier. A quote binds to our userId, not to an address, so
///      whoever can make this contract call the manager can execute our pending
///      quotes. `execute` is therefore callable by the escrow only, and the
///      escrow only by its `PROCESSING_MANAGER`.
///
///      Deployment. One `TransparentUpgradeableProxy` per weavr pool, deployed
///      with this implementation and `initialize` in its constructor data, so
///      no registered proxy ever exists uninitialised. Its ProxyAdmin goes to
///      the 48 h timelock before the address goes to Ondo. Settings live in
///      proxy storage (ERC-7201 namespace `weavr.storage.OndoGmAdapter`) and are
///      set once; there are no setters, a change is an upgrade.
///
///      Not policy-aware (plain `IAdapter`). The price is Ondo's signature,
///      inside Ondo's own 10% sanity band; the keeper's bound (`minOut`) is
///      enforced here. No price feed is read: a retired feed would stop the
///      pool until an upgrade through the timelock.
///
///      Actions (`execute`, escrow only; first word is the action id):
///      | action | params                                                         | result             |
///      |--------|----------------------------------------------------------------|--------------------|
///      | swap   | (bytes32, address tokenIn, uint256 amountIn, address tokenOut, | uint256 amountOut  |
///      |        |  uint256 minOut, bytes data)                                   |                    |
///
///      `data = abi.encode(IGMTokenManager.Quote quote, bytes signature)`.
///      Buy: `tokenIn` USDC, `amountIn = quoteCost(quantity, price)`, `tokenOut`
///      the GM token, `minOut <= quote.quantity`. Sell: `tokenIn` the GM token,
///      `amountIn = quote.quantity`, `tokenOut` USDC,
///      `minOut <= quoteProceeds(quantity, price)`. The layout is the
///      aggregator `swap` layout, so the live escrow binds the pushed amount to
///      word 3 and `tokenOut` to `expectedAsset` or USDC. Any other action id
///      reverts `UnknownAction`.
///
///      USDon. A buy that paid more than `quantity × price / 1e18` would get the
///      excess back from Ondo as USDon, which we cannot turn into USDC. The
///      exact-cost check leaves at most 1e12 - 1 wei of USDon per mint. USDon
///      leaves this contract only through the escrow's `sweepAdapter`, by an
///      admin's choice; `guardianCollect` never moves it.
contract OndoGmAdapter is Initializable, ReentrancyGuardUpgradeable, IAdapter {
    using SafeERC20 for IERC20;

    // =========================================================================
    // CONSTANTS
    // =========================================================================

    string public constant VERSION = "ondo-gm-adapter/1";

    bytes32 internal constant ACTION_SWAP = keccak256("swap");
    /// @dev The `GuardianActed` action of `guardianCollect`, as the Centrifuge
    ///      adapter names the same exit.
    bytes32 internal constant ACTION_COLLECT = keccak256("collect");

    bytes32 internal constant ESCROW_ADMIN = keccak256("ADMIN");
    bytes32 internal constant ESCROW_GUARDIAN = keccak256("GUARDIAN");

    /// @dev Ondo's `GM_NORMALIZER` (`GMTokenManager.sol:81`): USD values are
    ///      `quantity × price / 1e18`, in 18 decimals.
    uint256 internal constant GM_NORMALIZER = 1e18;
    /// @dev USDon (18 dp) per micro-USDC (6 dp), the converter's 1:1 rate.
    uint256 internal constant USDON_PER_MICRO_USDC = 1e12;

    // =========================================================================
    // STORAGE (ERC-7201)
    // =========================================================================

    /// @custom:storage-location erc7201:weavr.storage.OndoGmAdapter
    struct AdapterStorage {
        /// @dev The pool's AssetManagerEscrow: sole caller of `execute` and
        ///      `sweep`, sole destination of every token this contract releases.
        address assetManager;
        address usdc;
        /// @dev The one Ondo GM token this pool holds.
        address gmToken;
        /// @dev Ondo's `GMTokenManager`.
        address manager;
        /// @dev `manager.usdon()`, immutable in the manager.
        address usdon;
    }

    /// @dev keccak256(abi.encode(uint256(keccak256("weavr.storage.OndoGmAdapter")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant STORAGE_LOCATION =
        0x38ebea7f350ee8bd3bcc89b5f924e90754937fecc93f12f1745a5ecd1da3db00;

    function _s() private pure returns (AdapterStorage storage $) {
        assembly {
            $.slot := STORAGE_LOCATION
        }
    }

    // =========================================================================
    // EVENTS
    // =========================================================================

    /// @notice A buy landed: `usdcIn` micro-USDC paid, `gmOut` tokens forwarded
    ///         to the escrow, at Ondo's signed `price` (USD, 18 dp).
    event Minted(uint256 indexed attestationId, uint256 usdcIn, uint256 gmOut, uint256 price);
    /// @notice A sell landed: `gmIn` tokens redeemed, `usdcOut` micro-USDC
    ///         forwarded to the escrow (what the keeper records as the
    ///         redeem's amount out).
    event Redeemed(uint256 indexed attestationId, uint256 gmIn, uint256 usdcOut, uint256 price);
    event GuardianActed(address indexed by, bytes32 indexed action);

    // =========================================================================
    // ERRORS
    // =========================================================================

    error NotAContract(address account);
    error UnderlyingMismatch(address escrowUnderlying, address usdc);
    error WrongDecimals(address token, uint8 decimals);
    error GMTokenNotAccepted(address gmToken);

    /// @notice Check 1a: this contract does not hold `amount` of `token`.
    error PushMissing(address token, uint256 amount);
    /// @notice Check 2: `(tokenIn, tokenOut, quote.side)` is neither
    ///         `(usdc, gmToken, BUY)` nor `(gmToken, usdc, SELL)`.
    error DirectionMismatch();
    /// @notice Check 3: `quote.asset` is not this pool's GM token.
    error AssetMismatch();
    /// @notice Check 4: `block.timestamp > expiration`.
    error QuoteExpired(uint256 expiration);
    /// @notice Check 5: `quote.additionalData` is not zero.
    error AdditionalDataSet();
    /// @notice Check 6: a buy's `amountIn` is not `quoteCost(quantity, price)`.
    error CostMismatch(uint256 cost, uint256 amountIn);
    /// @notice Check 7: a sell's `amountIn` is not `quote.quantity`.
    error QuantityMismatch();

    // =========================================================================
    // CONSTRUCTOR / INITIALIZER
    // =========================================================================

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /// @notice One-time setup, run in the proxy's constructor data.
    /// @param assetManager_ The pool's AssetManagerEscrow (its `underlyingToken`
    ///        must be `usdc_`).
    /// @param usdc_ USDC on this chain (6 decimals).
    /// @param gmToken_ The Ondo GM token this pool holds (18 decimals, accepted
    ///        by the manager, which refuses look-alike tokens).
    /// @param manager_ Ondo's `GMTokenManager`.
    function initialize(address assetManager_, address usdc_, address gmToken_, address manager_)
        external
        initializer
    {
        if (
            assetManager_ == address(0) || usdc_ == address(0) || gmToken_ == address(0)
                || manager_ == address(0)
        ) revert AdapterErrors.InvalidAddress();
        if (assetManager_.code.length == 0) revert NotAContract(assetManager_);
        if (manager_.code.length == 0) revert NotAContract(manager_);
        address underlying = IOndoAdapterEscrow(assetManager_).underlyingToken();
        if (underlying != usdc_) revert UnderlyingMismatch(underlying, usdc_);
        uint8 d = IERC20Metadata(usdc_).decimals();
        if (d != 6) revert WrongDecimals(usdc_, d);
        d = IERC20Metadata(gmToken_).decimals();
        if (d != 18) revert WrongDecimals(gmToken_, d);
        if (!IGMTokenManager(manager_).gmTokenAccepted(gmToken_)) revert GMTokenNotAccepted(gmToken_);

        __ReentrancyGuard_init();

        AdapterStorage storage $ = _s();
        $.assetManager = assetManager_;
        $.usdc = usdc_;
        $.gmToken = gmToken_;
        $.manager = manager_;
        $.usdon = IGMTokenManager(manager_).usdon();
    }

    // =========================================================================
    // MODIFIERS
    // =========================================================================

    /// @dev Check 1.
    modifier onlyAssetManager() {
        if (msg.sender != _s().assetManager) revert AdapterErrors.Unauthorized();
        _;
    }

    /// @dev The escrow's GUARDIAN or ADMIN, read live from the escrow.
    modifier onlyEscrowGuardian() {
        IOndoAdapterEscrow e = IOndoAdapterEscrow(_s().assetManager);
        if (!e.hasRole(ESCROW_GUARDIAN, msg.sender) && !e.hasRole(ESCROW_ADMIN, msg.sender)) {
            revert AdapterErrors.Unauthorized();
        }
        _;
    }

    // =========================================================================
    // IADAPTER
    // =========================================================================

    /// @notice This adapter's own kind. Nothing on chain reads it.
    function kind() external pure override returns (bytes32) {
        return keccak256("ondo-gm");
    }

    function assetManager() external view override returns (address) {
        return _s().assetManager;
    }

    /// @notice USDC (pushed for a buy) and the GM token (pushed for a sell).
    ///         The escrow snapshots this at `acceptAdapter` and then refuses
    ///         any other pushed token.
    function assets() external view override returns (address[] memory toks) {
        AdapterStorage storage $ = _s();
        toks = new address[](2);
        toks[0] = $.usdc;
        toks[1] = $.gmToken;
    }

    function execute(bytes calldata params)
        external
        override
        onlyAssetManager
        nonReentrant
        returns (bytes memory)
    {
        if (params.length < 32) revert AdapterErrors.UnknownAction(bytes32(0));
        bytes32 action = bytes32(params[0:32]);
        if (action != ACTION_SWAP) revert AdapterErrors.UnknownAction(action);
        (, address tokenIn, uint256 amountIn, address tokenOut, uint256 minOut, bytes memory data) =
            abi.decode(params, (bytes32, address, uint256, address, uint256, bytes));
        return abi.encode(_swap(tokenIn, amountIn, tokenOut, minOut, data));
    }

    /// @notice Send this adapter's whole balance of `token` to the escrow,
    ///         through the escrow's ADMIN-only `sweepAdapter`. The only way
    ///         USDon leaves this contract.
    function sweep(address token) external override onlyAssetManager nonReentrant {
        if (token == address(0)) revert AdapterErrors.InvalidAddress();
        uint256 bal = IERC20(token).balanceOf(address(this));
        if (bal > 0) IERC20(token).safeTransfer(_s().assetManager, bal);
    }

    // =========================================================================
    // GUARDIAN EXIT PATH
    // =========================================================================

    /// @notice Stray USDC and GM tokens (a donation, a mis-push) to the escrow.
    ///         Never USDon. Works while the escrow is paused and after
    ///         `removeAdapter`, when the escrow's `sweepAdapter` cannot reach
    ///         this contract. The only destination is the escrow.
    /// @dev Each token is sent on its own and the outputs say what moved: a
    ///      GM token Ondo has paused or blocklisted reverts every transfer of
    ///      it, and must not hold the USDC stray here with it (after
    ///      `removeAdapter` this is the USDC's only exit).
    function guardianCollect()
        external
        onlyEscrowGuardian
        nonReentrant
        returns (uint256 usdcOut, uint256 gmOut)
    {
        AdapterStorage storage $ = _s();
        usdcOut = IERC20($.usdc).balanceOf(address(this));
        gmOut = IERC20($.gmToken).balanceOf(address(this));
        if (usdcOut > 0 && !IERC20($.usdc).trySafeTransfer($.assetManager, usdcOut)) usdcOut = 0;
        if (gmOut > 0 && !IERC20($.gmToken).trySafeTransfer($.assetManager, gmOut)) gmOut = 0;
        emit GuardianActed(msg.sender, ACTION_COLLECT);
    }

    // =========================================================================
    // SWAP
    // =========================================================================

    /// @dev Checks 1a to 11 of the design (check 1 is `onlyAssetManager`).
    ///      The cheap ones repeat Ondo's, so the revert is ours, named, and
    ///      before any approval. Ondo is called through the typed interface, so
    ///      its own custom errors reach the caller unchanged.
    function _swap(address tokenIn, uint256 amountIn, address tokenOut, uint256 minOut, bytes memory data)
        internal
        returns (uint256 amountOut)
    {
        AdapterStorage storage $ = _s();

        // 1a. The escrow can reach `execute` with nothing pushed
        //     (`executeAdapter`, or `pushAndExecute` with amountIn 0), and
        //     checks a pushed token only against the `assets()` snapshot.
        if (IERC20(tokenIn).balanceOf(address(this)) < amountIn) revert PushMissing(tokenIn, amountIn);

        (IGMTokenManager.Quote memory quote, bytes memory signature) =
            abi.decode(data, (IGMTokenManager.Quote, bytes));

        address usdc_ = $.usdc;
        address gm = $.gmToken;

        // 2. The params' direction is the side Ondo signed.
        bool buy;
        if (tokenIn == usdc_ && tokenOut == gm && quote.side == IGMTokenManager.QuoteSide.BUY) {
            buy = true;
        } else if (!(tokenIn == gm && tokenOut == usdc_ && quote.side == IGMTokenManager.QuoteSide.SELL)) {
            revert DirectionMismatch();
        }
        // 3.
        if (quote.asset != gm) revert AssetMismatch();
        // 4. Ondo: `block.timestamp > quote.expiration` reverts (GMTokenManager.sol:334).
        if (block.timestamp > quote.expiration) revert QuoteExpired(quote.expiration);
        // 5. Zero in every executed quote; if Ondo gives it a meaning we look first.
        if (quote.additionalData != bytes32(0)) revert AdditionalDataSet();

        IGMTokenManager m = IGMTokenManager($.manager);
        if (buy) {
            // 6. Ondo pulls whatever it is passed and refunds the excess as USDon.
            uint256 cost = quoteCost(quote.quantity, quote.price);
            if (amountIn != cost) revert CostMismatch(cost, amountIn);
            // 8.
            if (quote.quantity < minOut) revert AdapterErrors.SlippageTooHigh(minOut, quote.quantity);

            // 9.
            uint256 before = IERC20(gm).balanceOf(address(this));
            IERC20(usdc_).forceApprove(address(m), cost);
            m.mintWithAttestation(quote, signature, usdc_, cost);
            IERC20(usdc_).forceApprove(address(m), 0);

            // 10. Exactly the signed quantity.
            amountOut = IERC20(gm).balanceOf(address(this)) - before;
            if (amountOut != quote.quantity) revert AdapterErrors.SlippageTooHigh(quote.quantity, amountOut);

            // 11.
            IERC20(gm).safeTransfer($.assetManager, amountOut);
            emit Minted(quote.attestationId, cost, amountOut, quote.price);
        } else {
            // 7. The manager pulls exactly `quote.quantity`.
            if (amountIn != quote.quantity) revert QuantityMismatch();
            // 8.
            uint256 proceeds = quoteProceeds(quote.quantity, quote.price);
            if (proceeds < minOut) revert AdapterErrors.SlippageTooHigh(minOut, proceeds);

            // 9. Always paid in USDC, so USDon is never taken as proceeds.
            uint256 before = IERC20(usdc_).balanceOf(address(this));
            IERC20(gm).forceApprove(address(m), quote.quantity);
            m.redeemWithAttestation(quote, signature, usdc_, minOut);
            IERC20(gm).forceApprove(address(m), 0);

            // 10. `redeemWithAttestation` returns the USDon value, not the
            //     USDC paid, so the payment is measured.
            amountOut = IERC20(usdc_).balanceOf(address(this)) - before;
            if (amountOut < minOut) revert AdapterErrors.SlippageTooHigh(minOut, amountOut);

            // 11.
            IERC20(usdc_).safeTransfer($.assetManager, amountOut);
            emit Redeemed(quote.attestationId, quote.quantity, amountOut, quote.price);
        }
    }

    // =========================================================================
    // VIEWS
    // =========================================================================

    /// @notice Micro-USDC a buy of `quantity` at `price` must pay:
    ///         `ceil(floor(quantity × price / 1e18) / 1e12)`. The manager values
    ///         the mint at `floor(quantity × price / 1e18)` USDon and the
    ///         converter gives 1e12 USDon per micro-USDC, so this is the least
    ///         that does not revert, and it leaves under 1e12 wei of USDon.
    function quoteCost(uint256 quantity, uint256 price) public pure returns (uint256) {
        uint256 usdonValue = (quantity * price) / GM_NORMALIZER;
        uint256 cost = usdonValue / USDON_PER_MICRO_USDC;
        return usdonValue % USDON_PER_MICRO_USDC == 0 ? cost : cost + 1;
    }

    /// @notice Micro-USDC a sell of `quantity` at `price` pays:
    ///         `floor(floor(quantity × price / 1e18) / 1e12)`, the converter's
    ///         rounding (`USDonConverter.sol:161`).
    function quoteProceeds(uint256 quantity, uint256 price) public pure returns (uint256) {
        return (quantity * price) / GM_NORMALIZER / USDON_PER_MICRO_USDC;
    }

    function usdc() external view returns (address) {
        return _s().usdc;
    }

    function gmToken() external view returns (address) {
        return _s().gmToken;
    }

    function manager() external view returns (address) {
        return _s().manager;
    }

    function usdon() external view returns (address) {
        return _s().usdon;
    }

    /// @notice Our userId at Ondo: zero when this address is not registered.
    ///         The registry and the key are read live from the manager, so this
    ///         follows a registry Ondo replaces.
    function registeredUserId() public view returns (bytes32) {
        IGMTokenManager m = IGMTokenManager(_s().manager);
        return IOndoIDRegistry(m.ondoIDRegistry()).getRegisteredID(m.gmIdentifier(), address(this));
    }

    /// @notice What can stop a trade on the manager's side, in one call:
    ///         our userId, whether the token is accepted, the global and
    ///         per-token pauses folded per side, and the sanity price's stamp
    ///         and staleness bound. The other stops (converter, rate limiter,
    ///         token pause, escrow) are read by the keeper itself.
    function venueState()
        external
        view
        returns (
            bytes32 userId,
            bool accepted,
            bool mintPaused,
            bool redeemPaused,
            uint256 sanityUpdatedAt,
            uint256 sanityMaxDelay
        )
    {
        AdapterStorage storage $ = _s();
        IGMTokenManager m = IGMTokenManager($.manager);
        address gm = $.gmToken;
        userId = registeredUserId();
        accepted = m.gmTokenAccepted(gm);
        mintPaused = m.globalMintingPaused() || m.gmTokenMintingPaused(gm);
        redeemPaused = m.globalRedeemingPaused() || m.gmTokenRedemptionsPaused(gm);
        (, uint64 lastUpdated, uint32 maxTimeDelay,) = IOndoSanityCheckOracle(m.sanityCheckOracle()).prices(gm);
        sanityUpdatedAt = lastUpdated;
        sanityMaxDelay = maxTimeDelay;
    }

    /// @notice Balances held here: rounding USDon from mints, and strays.
    function dust() external view returns (uint256 usdcBal, uint256 gmBal, uint256 usdonBal) {
        AdapterStorage storage $ = _s();
        usdcBal = IERC20($.usdc).balanceOf(address(this));
        gmBal = IERC20($.gmToken).balanceOf(address(this));
        usdonBal = IERC20($.usdon).balanceOf(address(this));
    }
}

@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reinitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
     *
     * NOTE: Consider following the ERC-7201 formula to derive storage locations.
     */
    function _initializableStorageSlot() internal pure virtual returns (bytes32) {
        return INITIALIZABLE_STORAGE;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        bytes32 slot = _initializableStorageSlot();
        assembly {
            $.slot := slot
        }
    }
}

@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuardUpgradeable is Initializable {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
    struct ReentrancyGuardStorage {
        uint256 _status;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
        assembly {
            $.slot := ReentrancyGuardStorageLocation
        }
    }

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        $._status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if ($._status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        $._status = ENTERED;
    }

    function _nonReentrantAfter() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        $._status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        return $._status == ENTERED;
    }
}

@openzeppelin/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

@openzeppelin/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

@openzeppelin/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

contracts/adapters/base/AdapterErrors.sol

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

/// @notice Custom errors shared across the adapter layer.
library AdapterErrors {
    /// @notice Caller is not the AssetManagerEscrow that owns this adapter.
    error Unauthorized();

    /// @notice Action is recognized but not implemented by this adapter.
    error NotSupported();

    /// @notice First 32 bytes of `params` did not match any known action discriminator.
    error UnknownAction(bytes32 action);

    /// @notice Output amount fell below the caller-provided floor.
    error SlippageTooHigh(uint256 minOut, uint256 actualOut);

    /// @notice External router/protocol call returned `false` or reverted.
    error SwapFailed();

    /// @notice A burn is already in flight; only one active burn allowed per adapter.
    error ConcurrentBurnNotAllowed(uint256 activeBurnId);

    /// @notice The given burnId is not in PENDING status.
    error BurnNotPending(uint256 burnId);

    /// @notice The given burn is still in cooldown / queue.
    error BurnNotReady(uint256 burnId, uint256 readyAt);

    /// @notice Address argument is the zero address.
    error InvalidAddress();

    /// @notice Amount argument is zero or otherwise invalid.
    error InvalidAmount();

    /// @notice Router calldata selector is not the bound aggregator `swap()`.
    error SwapSelectorNotAllowed(bytes4 selector);

    /// @notice Router calldata does not match this call's bound arguments.
    error SwapCalldataNotBound();

    /// @notice The swap directs its output somewhere other than this adapter.
    error SwapDestinationNotSelf(address dstReceiver);

    /// @notice Aggregator calldata takes a partner/protocol fee from custody.
    error SwapFeeNotAllowed();

    /// @notice Deploy path refused because the PriceBoard (or other) reference is stale.
    error ReferenceStale();

    /// @notice No usable board/protocol reference for this token pair.
    error MissingReference();

    /// @notice Swap `tokenOut` is neither USDC nor the escrow `expectedAsset` (M-16).
    error UnexpectedTokenOut();
}

contracts/adapters/base/IAdapter.sol

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

/// @notice Universal interface implemented by every adapter (direct or aggregator).
/// @dev See spec §5.3 for full design rationale.
///
/// AssetManagerEscrow delegates work through `execute(bytes)`. The adapter
/// decodes an action discriminator (the first 32 bytes of `params`) and
/// dispatches to its internal logic. Direct adapters inline the swap chain
/// in Solidity; aggregator adapters forward opaque router calldata.
///
/// v2 adapters also implement `IPolicyAdapter.execute(bytes, Policy)`.
/// v1 `execute(bytes)` is kept so already-whitelisted adapters keep working
/// until they are removed.
interface IAdapter {
    /// @notice Either `keccak256("direct")` or `keccak256("aggregator")`.
    /// @dev Off-chain uses this to know how to encode `params` for `execute`.
    function kind() external pure returns (bytes32);

    /// @notice Universal entry point. Decodes action from `params` and dispatches internally.
    /// @param params ABI-encoded `(bytes32 action, ...args)`. Args layout depends on action.
    /// @return result ABI-encoded result. Layout depends on action (e.g. `uint256 amountOut`,
    ///         `uint256 burnId`).
    function execute(bytes calldata params) external returns (bytes memory result);

    /// @notice The AssetManagerEscrow that owns this adapter (sole authorized caller of `execute`).
    function assetManager() external view returns (address);

    /// @notice Tokens this adapter may receive via `pushAndExecute`.
    /// @dev Snapshotted onto the escrow at `acceptAdapter` / `emergencyAddAdapter`.
    ///      An empty list means the adapter did not declare a bind (v1 aggregators).
    function assets() external view returns (address[] memory);

    /// @notice Sweep `token` balance back to the escrow. Only the asset manager.
    function sweep(address token) external;
}

contracts/adapters/ondo/IOndoGm.sol

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

/// @notice The parts of Ondo Global Markets on Ethereum that `OndoGmAdapter`
///         calls or reads. Transcribed from Ondo's verified sources, not
///         imported (they are BUSL-1.1 and pinned to 0.8.16):
///         - `GMTokenManager` `0x2c158BC456e027b2AfFCCadF1BDBD9f5fC4c5C8c`
///           (`IGMTokenManager.sol`, `IGMTokenManagerErrors.sol`, the public
///           state of `GMTokenManager.sol:61-138`);
///         - `OndoIDRegistry` (`IOndoIDRegistry.sol`);
///         - `OndoSanityCheckOracle` `0x914D5Cb27cb30E80BdE8215ff577eD63Eb986B79`
///           (the `prices` getter of `OndoSanityCheckOracle.sol:58`).
///
/// @dev `Quote` and `QuoteSide` are field for field Ondo's
///      (`IGMTokenManager.sol:25-54`): the EIP-712 type string the manager
///      signs over is
///      `Quote(uint256 chainId,uint256 attestationId,bytes32 userId,address asset,uint256 price,uint256 quantity,uint256 expiration,uint8 side,bytes32 additionalData)`,
///      and an enum encodes as `uint8`, so the ABI of the two functions below
///      is the live one (selectors pinned in the unit test).
interface IGMTokenManager {
    enum QuoteSide {
        /// The user is buying GM tokens.
        BUY,
        /// The user is selling GM tokens.
        SELL
    }

    struct Quote {
        uint256 chainId;
        uint256 attestationId;
        bytes32 userId;
        address asset;
        uint256 price;
        uint256 quantity;
        uint256 expiration;
        QuoteSide side;
        bytes32 additionalData;
    }

    /// @notice Mints `quote.quantity` GM tokens to `msg.sender`, pulling
    ///         `depositTokenAmount` of `depositToken` from it. The excess over
    ///         `quantity × price / 1e18` comes back to `msg.sender` as USDon.
    function mintWithAttestation(
        Quote calldata quote,
        bytes memory signature,
        address depositToken,
        uint256 depositTokenAmount
    ) external returns (uint256 receivedGmTokenAmount);

    /// @notice Burns `quote.quantity` GM tokens pulled from `msg.sender` and
    ///         pays `msg.sender` in `receiveToken`. Returns the USDon value,
    ///         not the amount paid.
    function redeemWithAttestation(
        Quote calldata quote,
        bytes memory signature,
        address receiveToken,
        uint256 minimumReceiveAmount
    ) external returns (uint256 redemptionUSDonValue);

    // Public state of GMTokenManager.sol.
    function usdon() external view returns (address);
    function gmIdentifier() external view returns (address);
    function ondoIDRegistry() external view returns (address);
    function sanityCheckOracle() external view returns (address);
    function gmTokenAccepted(address token) external view returns (bool);
    function globalMintingPaused() external view returns (bool);
    function globalRedeemingPaused() external view returns (bool);
    function gmTokenMintingPaused(address token) external view returns (bool);
    function gmTokenRedemptionsPaused(address token) external view returns (bool);
}

/// @notice `IGMTokenManagerErrors.sol:24-84`, verbatim. Not used by the
///         adapter (Ondo's reverts pass through its typed calls unchanged); kept
///         here so the mocks revert with the live selectors and the keeper's
///         selector table can be checked against one file.
interface IGMTokenManagerErrors {
    error TokenAddressCantBeZero();
    error DepositAmountTooSmall();
    error UserNotRegistered();
    error RedemptionAmountTooSmall();
    error IDRegistryAddressCantBeZero();
    error RateLimiterAddressCantBeZero();
    error GlobalMintsPaused();
    error GlobalRedemptionsPaused();
    error GMTokenMintsPaused();
    error GMTokenRedemptionsPaused();
    error SanityCheckOracleAddressCantBeZero();
    error AttestationExpired();
    error InvalidAttestationSigner();
    error InvalidChainId();
    error InvalidQuoteSide();
    error UserIdMismatch(bytes32 expected, bytes32 actual);
    error AttestationAlreadyExecuted();
    error IssuanceHoursAddressCantBeZero();
    error USDonManagerNotEnabled();
    error GMTokenNotRegistered();
    error USDonAddressCantBeZero();
}

/// @notice `IOndoIDRegistry.sol`. The manager keys every GM registration on
///         one address, `gmIdentifier()`, not on the token.
interface IOndoIDRegistry {
    function getRegisteredID(address rwaToken, address user) external view returns (bytes32 userID);
}

/// @notice The public getter of `OndoSanityCheckOracle.prices`
///         (`OndoSanityCheckOracle.sol:44-58`): price in USD with 18 decimals,
///         the time it was posted, and the per-token staleness and band.
interface IOndoSanityCheckOracle {
    function prices(address token)
        external
        view
        returns (uint256 price, uint64 lastUpdated, uint32 maxTimeDelay, uint16 allowedDeviationBps);
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.