ROBINEXBack to transparency
ROBINEX / ORIGINAL CONTRACT

Source and build.

Source for the earlier Robinex exchange contract. The current exchange address is listed on the transparency page.

Build evidence

On 7 November 2026, this source was compiled locally using Solidity 0.8.30, optimizer enabled with 200 runs, EVM target Paris and OpenZeppelin Contracts 5.4.0. Source path: src/RobinexExchange.sol. Remapping: @openzeppelin/contracts/=lib/openzeppelin-contracts/. The resulting deployed runtime hash matched the original contract’s observed on-chain runtime hash below.

Contract
0xeAA6564bEAC0fa540Ce55046bFA256b37272a19F View on explorer
Runtime hash
0x52fbf439aad6cab5f8332175b68d70cfe9362f3d58893923b4adf5efe8527149

The original exchange source and its seven imported OpenZeppelin files are shown below. On 7 November 2026, the dependency files were compared byte-for-byte with the official OpenZeppelin v5.4.0 release. The dependency license is included in the local source package. A reproducible source folder is included in the local site package at reference-contract/; run forge build there with Foundry and hash the deployed bytecode. No Robinex public repository or independent audit report is linked in this build. Verify the exact source and build independently.

SOURCE / ROBINEXEXCHANGE.SOL

Exchange source

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

/// @dev Each escrow offer holds its own assets, isolated from other offers.
contract RobinexEscrowVault {
    using SafeERC20 for IERC20;
    address private immutable exchange;
    error UnauthorizedVault();
    error NonExactTransfer();
    error NativeTransferFailed();
    constructor() { exchange = msg.sender; }
    receive() external payable { if (msg.sender != exchange) revert UnauthorizedVault(); }
    function release(address token, address to, uint256 amount) external {
        if (msg.sender != exchange) revert UnauthorizedVault();
        if (token == address(0)) {
            (bool ok,) = payable(to).call{value: amount}("");
            if (!ok) revert NativeTransferFailed();
        } else {
            IERC20 asset = IERC20(token);
            uint256 beforeFrom=asset.balanceOf(address(this));
            uint256 beforeTo=asset.balanceOf(to);
            asset.safeTransfer(to, amount);
            uint256 afterFrom=asset.balanceOf(address(this));
            uint256 afterTo=asset.balanceOf(to);
            if (afterFrom>beforeFrom || beforeFrom-afterFrom!=amount || afterTo<beforeTo || afterTo-beforeTo!=amount) revert NonExactTransfer();
        }
    }
}

/// @notice Experimental token-for-token exchange. Not audited; do not use with real value.
/// @dev Only exact-transfer ERC-20s are supported. address(0) represents native ETH in escrow mode.
contract RobinexExchange is ReentrancyGuard {
    using SafeERC20 for IERC20;
    uint256 public constant MAX_ASSETS = 10;
    /// @notice 0.5% of each received asset, rounded down to its smallest unit.
    uint256 public constant FEE_DENOMINATOR = 200;
    address public constant FEE_RECIPIENT = 0x2744e2eeEdD3969cEf92FD305dE92fDaE5f1853C;

    enum Mode { Escrow, Mutual }
    enum Status { Unset, Open, Filled, Cancelled }
    struct Asset { address token; uint256 amount; }
    struct Offer {
        address maker;
        Mode mode;
        Status status;
        uint64 expiry;
        address vault;
        Asset[] give;
        Asset[] want;
    }
    struct Request { bool requested; bool makerConfirmed; bool takerConfirmed; uint256 nonce; Asset[] proposal; }

    uint256 public nextOfferId = 1;
    mapping(uint256 => Offer) private _offers;
    mapping(uint256 => mapping(address => Request)) private _requests;
    mapping(uint256 => mapping(address => uint256)) private _requestNonces;
    mapping(uint256 => mapping(uint256 => bool)) private _withdrawn;

    error InvalidOffer();
    error InvalidBasket();
    error DuplicateToken();
    error InvalidToken();
    error NativeNotSupported();
    error IncorrectNativeValue();
    error OfferUnavailable();
    error OfferExpired();
    error Unauthorized();
    error InvalidMode();
    error InvalidRequest();
    error AlreadyConfirmed();
    error InsufficientFunding();
    error NonExactTransfer();
    error NativeTransferFailed();
    error AssetAlreadyWithdrawn();
    error InsufficientSurplus();

    event OfferCreated(uint256 indexed offerId, address indexed maker, Mode mode, uint64 expiry);
    event OfferCancelled(uint256 indexed offerId);
    event EscrowAssetReturned(uint256 indexed offerId, uint256 indexed index);
    event EscrowAssetPending(uint256 indexed offerId, uint256 indexed index);
    event EscrowSurplusRecovered(uint256 indexed offerId, address indexed token, uint256 amount);
    event TradeRequested(uint256 indexed offerId, address indexed taker);
    event RequestWithdrawn(uint256 indexed offerId, address indexed taker, address indexed actor);
    event TradeConfirmed(uint256 indexed offerId, address indexed taker, address indexed participant);
    event ConfirmationRevoked(uint256 indexed offerId, address indexed taker, address indexed participant);
    event OfferFilled(uint256 indexed offerId, address indexed taker);

    function createOffer(Asset[] calldata give, Asset[] calldata want, Mode mode, uint64 expiry)
        external payable nonReentrant returns (uint256 id)
    {
        if (expiry != 0 && expiry <= block.timestamp) revert OfferExpired();
        uint256 giveNative = _validate(give, mode);
        if (want.length != 0) _validate(want, mode);
        if (msg.value != (mode == Mode.Escrow ? giveNative : 0)) revert IncorrectNativeValue();
        id = nextOfferId++;
        Offer storage offer = _offers[id];
        offer.maker = msg.sender;
        offer.mode = mode;
        offer.status = Status.Open;
        offer.expiry = expiry;
        if (mode == Mode.Escrow) {
            offer.vault = address(new RobinexEscrowVault());
            if (giveNative != 0) {
                (bool ok,) = payable(offer.vault).call{value: giveNative}("");
                if (!ok) revert NativeTransferFailed();
            }
        }
        for (uint256 i; i < give.length; ++i) {
            offer.give.push(give[i]);
            if (mode == Mode.Escrow && give[i].token != address(0)) {
                _pullExact(give[i].token, msg.sender, offer.vault, give[i].amount);
            } else if (mode == Mode.Mutual && IERC20(give[i].token).balanceOf(msg.sender) < give[i].amount) {
                revert InsufficientFunding();
            }
        }
        for (uint256 i; i < want.length; ++i) offer.want.push(want[i]);
        emit OfferCreated(id, msg.sender, mode, expiry);
    }

    function getOffer(uint256 id) external view returns (
        address maker, Mode mode, Status status, uint64 expiry, Asset[] memory give, Asset[] memory want
    ) {
        Offer storage o = _offers[id];
        if (o.status == Status.Unset) revert InvalidOffer();
        return (o.maker, o.mode, o.status, o.expiry, o.give, o.want);
    }

    function escrowInfo(uint256 id) external view returns (address vault, bool[] memory returned) {
        Offer storage o = _offers[id];
        if (o.status == Status.Unset) revert InvalidOffer();
        returned = new bool[](o.give.length);
        for (uint256 i; i < o.give.length; ++i) returned[i] = _withdrawn[id][i];
        return (o.vault, returned);
    }

    function getRequest(uint256 id, address taker) external view returns (Request memory) {
        if (_offers[id].status == Status.Unset) revert InvalidOffer();
        return _requests[id][taker];
    }

    /// @notice Settle an escrow offer atomically. The taker's required native ETH is supplied here.
    function acceptEscrow(uint256 id) external payable nonReentrant {
        Offer storage o = _active(id);
        if (o.mode != Mode.Escrow) revert InvalidMode();
        if (o.want.length == 0) revert InvalidRequest();
        if (msg.sender == o.maker) revert Unauthorized();
        if (msg.value != _nativeAmount(o.want)) revert IncorrectNativeValue();
        o.status = Status.Filled;
        for (uint256 i; i < o.want.length; ++i) {
            Asset storage a = o.want[i];
            if (a.token == address(0)) _sendNativeWithFee(o.maker, a.amount);
            else _pullWithFee(a.token, msg.sender, o.maker, a.amount);
        }
        for (uint256 i; i < o.give.length; ++i) {
            Asset storage a = o.give[i];
            _releaseWithFee(o.vault, a.token, msg.sender, a.amount);
        }
        emit OfferFilled(id, msg.sender);
    }

    /// @notice Signal interest in a non-escrow offer. Multiple takers may request independently.
    function requestTrade(uint256 id) external nonReentrant {
        Offer storage o = _active(id);
        if (o.mode != Mode.Mutual || o.want.length == 0) revert InvalidMode();
        if (msg.sender == o.maker) revert Unauthorized();
        Request storage r = _requests[id][msg.sender];
        if (r.requested) revert InvalidRequest();
        r.requested = true;
        r.nonce = ++_requestNonces[id][msg.sender];
        emit TradeRequested(id, msg.sender);
    }

    /// @notice Propose a concrete counter-basket. It cannot be settled without both confirmations.
    function requestProposal(uint256 id, Asset[] calldata proposal) external nonReentrant {
        Offer storage o = _active(id);
        if (msg.sender == o.maker) revert Unauthorized();
        _validate(proposal, Mode.Mutual);
        Request storage r = _requests[id][msg.sender];
        if (r.requested) revert InvalidRequest();
        r.requested = true;
        r.nonce = ++_requestNonces[id][msg.sender];
        for (uint256 i; i < proposal.length; ++i) {
            if (IERC20(proposal[i].token).balanceOf(msg.sender) < proposal[i].amount) revert InsufficientFunding();
            r.proposal.push(proposal[i]);
        }
        emit TradeRequested(id, msg.sender);
    }

    /// @notice The taker can withdraw a request; the maker can reject it. Clears both confirmations.
    function withdrawRequest(uint256 id, address taker, uint256 expectedNonce) external nonReentrant {
        Offer storage o = _active(id);
        if (o.mode != Mode.Mutual && o.want.length != 0 && _requests[id][taker].proposal.length == 0) revert InvalidMode();
        if (msg.sender != o.maker && msg.sender != taker) revert Unauthorized();
        if (!_requests[id][taker].requested || _requests[id][taker].nonce != expectedNonce) revert InvalidRequest();
        delete _requests[id][taker];
        emit RequestWithdrawn(id, taker, msg.sender);
    }

    /// @notice Each party confirms separately. The second confirmation executes both transfers atomically.
    function confirmTrade(uint256 id, address taker, uint256 expectedNonce) external nonReentrant {
        Offer storage o = _active(id);
        if (o.mode != Mode.Mutual && o.want.length != 0 && _requests[id][taker].proposal.length == 0) revert InvalidMode();
        Request storage r = _requests[id][taker];
        if (!r.requested || r.nonce != expectedNonce || taker == o.maker || taker == address(0)) revert InvalidRequest();
        Asset[] storage payment = r.proposal.length != 0 ? r.proposal : o.want;
        if (msg.sender == o.maker) {
            if (r.makerConfirmed) revert AlreadyConfirmed();
            if (o.mode == Mode.Mutual) _requireFunding(o.give, o.maker);
            r.makerConfirmed = true;
        } else if (msg.sender == taker) {
            if (r.takerConfirmed) revert AlreadyConfirmed();
            _requireFunding(payment, taker);
            r.takerConfirmed = true;
        } else revert Unauthorized();
        emit TradeConfirmed(id, taker, msg.sender);
        if (r.makerConfirmed && r.takerConfirmed) {
            o.status = Status.Filled;
            for (uint256 i; i < o.give.length; ++i) {
                Asset storage a = o.give[i];
                if (o.mode == Mode.Escrow) _releaseWithFee(o.vault, a.token, taker, a.amount);
                else _pullWithFee(a.token, o.maker, taker, a.amount);
            }
            for (uint256 i; i < payment.length; ++i) {
                Asset storage a = payment[i];
                _pullWithFee(a.token, taker, o.maker, a.amount);
            }
            emit OfferFilled(id, taker);
        }
    }

    function revokeConfirmation(uint256 id, address taker, uint256 expectedNonce) external nonReentrant {
        Offer storage o = _active(id);
        if (o.mode != Mode.Mutual && o.want.length != 0 && _requests[id][taker].proposal.length == 0) revert InvalidMode();
        Request storage r = _requests[id][taker];
        if (!r.requested || r.nonce != expectedNonce) revert InvalidRequest();
        if (msg.sender == o.maker && r.makerConfirmed) r.makerConfirmed = false;
        else if (msg.sender == taker && r.takerConfirmed) r.takerConfirmed = false;
        else revert Unauthorized();
        emit ConfirmationRevoked(id, taker, msg.sender);
    }

    /// @notice Cancellation remains possible after expiry. Failed individual refunds stay claimable.
    function cancelOffer(uint256 id) external nonReentrant {
        Offer storage o = _offers[id];
        if (o.status != Status.Open) revert OfferUnavailable();
        if (msg.sender != o.maker) revert Unauthorized();
        o.status = Status.Cancelled;
        if (o.mode == Mode.Escrow) {
            for (uint256 i; i < o.give.length; ++i) {
                Asset storage a = o.give[i];
                try RobinexEscrowVault(payable(o.vault)).release{gas: 200_000}(a.token, o.maker, a.amount) {
                    _withdrawn[id][i] = true;
                    emit EscrowAssetReturned(id, i);
                } catch { emit EscrowAssetPending(id, i); }
            }
        }
        emit OfferCancelled(id);
    }

    /// @notice Retry one failed return without blocking other assets in the same basket.
    function withdrawEscrowAsset(uint256 id, uint256 index) external nonReentrant {
        Offer storage o = _offers[id];
        if (o.status != Status.Cancelled || o.mode != Mode.Escrow) revert OfferUnavailable();
        if (msg.sender != o.maker) revert Unauthorized();
        if (index >= o.give.length) revert InvalidBasket();
        if (_withdrawn[id][index]) revert AssetAlreadyWithdrawn();
        _withdrawn[id][index] = true;
        Asset storage a = o.give[index];
        RobinexEscrowVault(payable(o.vault)).release(a.token, o.maker, a.amount);
        emit EscrowAssetReturned(id, index);
    }

    /// @notice Recover only assets exceeding this offer's outstanding escrow obligations.
    /// @dev Unexpected deposits belong to the offer maker, not necessarily their sender.
    function recoverEscrowSurplus(uint256 id, address token, uint256 amount) external nonReentrant {
        Offer storage o = _offers[id];
        if (o.status == Status.Unset || o.mode != Mode.Escrow) revert OfferUnavailable();
        if (msg.sender != o.maker) revert Unauthorized();
        uint256 reserved;
        for (uint256 i; i < o.give.length; ++i) {
            if (o.give[i].token == token && (o.status == Status.Open || (o.status == Status.Cancelled && !_withdrawn[id][i]))) {
                reserved = o.give[i].amount;
                break;
            }
        }
        uint256 balance = token == address(0) ? o.vault.balance : IERC20(token).balanceOf(o.vault);
        if (amount == 0 || balance < reserved || amount > balance - reserved) revert InsufficientSurplus();
        RobinexEscrowVault(payable(o.vault)).release(token, o.maker, amount);
        emit EscrowSurplusRecovered(id, token, amount);
    }

    function _active(uint256 id) private view returns (Offer storage o) {
        o = _offers[id];
        if (o.status != Status.Open) revert OfferUnavailable();
        if (o.expiry != 0 && block.timestamp >= o.expiry) revert OfferExpired();
    }

    function _validate(Asset[] calldata basket, Mode mode) private view returns (uint256 nativeAmount) {
        if (basket.length == 0 || basket.length > MAX_ASSETS) revert InvalidBasket();
        for (uint256 i; i < basket.length; ++i) {
            Asset calldata a = basket[i];
            if (a.amount == 0) revert InvalidBasket();
            if (a.token == address(0)) {
                if (mode == Mode.Mutual) revert NativeNotSupported();
                nativeAmount = a.amount;
            } else if (a.token.code.length == 0) revert InvalidToken();
            for (uint256 j; j < i; ++j) if (basket[j].token == a.token) revert DuplicateToken();
        }
    }

    function _nativeAmount(Asset[] storage basket) private view returns (uint256 amount) {
        for (uint256 i; i < basket.length; ++i) if (basket[i].token == address(0)) return basket[i].amount;
    }

    function _requireFunding(Asset[] storage basket, address owner) private view {
        for (uint256 i; i < basket.length; ++i) {
            IERC20 token = IERC20(basket[i].token);
            if (token.balanceOf(owner) < basket[i].amount || token.allowance(owner, address(this)) < basket[i].amount) {
                revert InsufficientFunding();
            }
        }
    }

    function _pullExact(address token, address from, address to, uint256 amount) private {
        IERC20 asset = IERC20(token);
        uint256 beforeFrom = asset.balanceOf(from);
        uint256 beforeTo = asset.balanceOf(to);
        asset.safeTransferFrom(from, to, amount);
        _checkExact(asset, from, to, amount, beforeFrom, beforeTo);
    }

    function _checkExact(IERC20 token, address from, address to, uint256 amount, uint256 beforeFrom, uint256 beforeTo)
        private view
    {
        uint256 afterFrom = token.balanceOf(from);
        uint256 afterTo = token.balanceOf(to);
        if (afterFrom > beforeFrom || beforeFrom - afterFrom != amount || afterTo < beforeTo || afterTo - beforeTo != amount) {
            revert NonExactTransfer();
        }
    }

    /// @dev Direct fee transfers and delivery are part of the same atomic transaction.
    function _pullWithFee(address token, address from, address to, uint256 gross) private {
        uint256 fee = gross / FEE_DENOMINATOR;
        if (fee == 0 || to == FEE_RECIPIENT) {
            _pullExact(token, from, to, gross);
        } else {
            _pullExact(token, from, to, gross - fee);
            // If the sender is also the recipient, retaining the fee is equivalent.
            if (from != FEE_RECIPIENT) _pullExact(token, from, FEE_RECIPIENT, fee);
        }
    }

    function _releaseWithFee(address vault, address token, address to, uint256 gross) private {
        uint256 fee = gross / FEE_DENOMINATOR;
        if (fee == 0 || to == FEE_RECIPIENT) {
            RobinexEscrowVault(payable(vault)).release(token, to, gross);
        } else {
            RobinexEscrowVault(payable(vault)).release(token, to, gross - fee);
            RobinexEscrowVault(payable(vault)).release(token, FEE_RECIPIENT, fee);
        }
    }

    function _sendNativeWithFee(address to, uint256 gross) private {
        uint256 fee = gross / FEE_DENOMINATOR;
        if (fee == 0 || to == FEE_RECIPIENT) {
            _sendNative(to, gross);
        } else {
            _sendNative(to, gross - fee);
            _sendNative(FEE_RECIPIENT, fee);
        }
    }

    function _sendNative(address to, uint256 amount) private {
        (bool ok,) = payable(to).call{value: amount}("");
        if (!ok) revert NativeTransferFailed();
    }
}
DEPENDENCIES / OPENZEPPELIN 5.4.0

Imported files

token/ERC20/IERC20.sol

SHA-256: 01b6f5c4fa45fd38822b286ecef6daf983d27306dd6362496fa71b3e4600b72c · OpenZeppelin v5.4.0 source

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

pragma solidity >=0.4.16;

/**
 * @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);
}
token/ERC20/utils/SafeERC20.sol

SHA-256: ac1fd9fa99b194a8db8dfa9ae8e3ff44feaa8f16668241fd2b66ae8b47d7c082 · OpenZeppelin v5.4.0 source

// 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);
    }
}
utils/ReentrancyGuard.sol

SHA-256: 32fbb1c908ec1b4de85cc1bb10091aebd5816ffe80dfdd5ca5e084fbea67a462 · OpenZeppelin v5.4.0 source

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

pragma solidity ^0.8.20;

/**
 * @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 ReentrancyGuard {
    // 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;

    uint256 private _status;

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

    constructor() {
        _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 {
        // 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 {
        // 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) {
        return _status == ENTERED;
    }
}
interfaces/IERC1363.sol

SHA-256: 9c3a75a925a6dac9e88b03cddc58d42fe3131b0aaaad84408521f3f7af2f991b · OpenZeppelin v5.4.0 source

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

pragma solidity >=0.6.2;

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);
}
interfaces/IERC20.sol

SHA-256: 0158e2d3e0e28bedd99eec13dcf1a8aa3a70a5b7e4bb2ad709609c95fcc740d1 · OpenZeppelin v5.4.0 source

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

pragma solidity >=0.4.16;

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

SHA-256: dfb3f56fa928a7c6cae41a7ce2c86b9210fa18d33fa26389099d66a0fa790368 · OpenZeppelin v5.4.0 source

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

pragma solidity >=0.4.16;

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

SHA-256: 9055c2994b37dea1a41b7b7926dcb510f05dbe2540b0aafc5fbee9558fffd0ca · OpenZeppelin v5.4.0 source

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

pragma solidity >=0.4.16;

/**
 * @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);
}