Skip to content
Verified contractExactMIT

HexOrderBook

Address0x6d7ba6ad41d0f1fc413afab88f09ff4920715dc9
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.25

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.25+commit.b61c2a91
Language
solidity
Optimization
Yes, 1,000 runs
EVM version
shanghai
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,425,323
Creation transaction
0xe82b87a977…cc3eb5b7c1

src/ethereum/HexOrderBook.sol

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

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

import {BridgeLink} from "../common/BridgeLink.sol";
import {SwapPayments} from "../common/SwapPayments.sol";
import {IAMB} from "../interfaces/IAMB.sol";
import {IHexOrderSettlement} from "../interfaces/IHexBridge.sol";

/// @title HexOrderBook
/// @notice Buy a .hex name from Ethereum. The money waits here until PulseChain confirms the name
///         was registered to the buyer, then goes to whoever registered it.
/// @dev The flow:
///        1. The buyer places an order: they pay, in USDC or any token or ETH that is swapped to
///           USDC, and give the registrar commitment for their name plus the details behind it
///           encrypted for the filler. The commitment hides the name until it is registered.
///        2. A filler registers the name to the buyer on PulseChain within minutes, paying from its
///           own stablecoins, through `HexOrderFiller`, which sends a message back over the bridge.
///        3. When the bridge delivers it, `settle` pays the order's money to the filler. If the
///           name could not be registered, the message refunds the buyer instead.
///        4. If no message arrives at all, the buyer can take the money back with `reclaim` once
///           `RECLAIM_DELAY` has passed after the fill deadline.
///      Only messages sent by the linked `HexOrderFiller` on PulseChain, delivered by the official
///      bridge, can settle an order, and each order settles once. No owner and no admin functions.
contract HexOrderBook is BridgeLink, SwapPayments, ReentrancyGuard, IHexOrderSettlement {
    using SafeERC20 for IERC20;

    /// @notice Where an order is.
    enum Status {
        NONE,
        OPEN,
        FILLED,
        REFUNDED,
        RECLAIMED
    }

    /// @notice An order.
    struct Order {
        address buyer; // who paid, and who refunds go to
        uint96 amount; // USDC held for the order
        bytes32 commitment; // the registrar commitment for the name
        uint64 deadline; // the name must be registered on PulseChain by this time
        Status status;
    }

    /// @notice How long a filler has to register an order's name, from when it is placed.
    uint64 public immutable FILL_WINDOW;

    /// @notice How long after the fill deadline the buyer must wait before `reclaim`, so that a fill
    ///         made in time has had ample time to arrive over the bridge.
    uint64 public immutable RECLAIM_DELAY;

    /// @notice The number of orders placed. Order ids start at 1.
    uint256 public orderCount;

    /// @notice Orders, by id.
    mapping(uint256 orderId => Order order) public orders;

    /// @notice USDC owed to an account because a direct transfer to it failed. Withdraw with `withdraw`.
    mapping(address account => uint256 amount) public owed;

    /// @notice An order was placed. `encryptedReveal` holds the details behind `commitment`,
    ///         encrypted for the filler.
    event OrderPlaced(
        uint256 indexed orderId,
        address indexed buyer,
        bytes32 indexed commitment,
        uint256 amount,
        uint64 deadline,
        bytes encryptedReveal
    );

    /// @notice An order was closed and its money sent to `to`.
    event OrderSettled(uint256 indexed orderId, Status status, address indexed to, uint256 amount);

    /// @notice A settlement message did not match an open order, and changed nothing.
    event SettlementIgnored(uint256 indexed orderId, bytes32 commitment, uint64 deadline, bool filled);

    /// @notice A transfer failed, so the amount was recorded in `owed` instead.
    event PaymentDeferred(address indexed to, uint256 amount);

    /// @notice An account withdrew what it was owed.
    event Withdrawn(address indexed account, uint256 amount);

    /// @notice The order amount is zero or too large.
    error InvalidAmount();
    /// @notice The commitment is zero.
    error InvalidCommitment();
    /// @notice The order is not open.
    error OrderNotOpen(uint256 orderId);
    /// @notice `reclaim` was called before `RECLAIM_DELAY` had passed after the deadline.
    error TooEarly(uint256 availableAt);

    /// @param amb The bridge's message contract on Ethereum.
    /// @param pulseChainId The chain id of PulseChain (369).
    /// @param linker Who may set the PulseChain `HexOrderFiller`, once.
    /// @param usdc USDC, the token orders are held in.
    /// @param weth Wrapped ETH, used for orders paid in ETH.
    /// @param routers Uniswap-V2-style routers to allow, e.g. Uniswap V2. Fixed for good.
    /// @param fillWindow How long a filler has to register an order's name.
    /// @param reclaimDelay How long after the fill deadline a buyer may reclaim an unsettled order.
    constructor(
        IAMB amb,
        uint256 pulseChainId,
        address linker,
        IERC20 usdc,
        IERC20 weth,
        address[] memory routers,
        uint64 fillWindow,
        uint64 reclaimDelay
    ) BridgeLink(amb, pulseChainId, linker) SwapPayments(usdc, weth, routers) {
        FILL_WINDOW = fillWindow;
        RECLAIM_DELAY = reclaimDelay;
    }

    // ------------------------------------------------------------------------------------------
    // Placing orders
    // ------------------------------------------------------------------------------------------

    /// @notice Places an order paid in USDC. The caller must have approved `amount`.
    /// @param commitment The registrar commitment for the name, from the registrar's `makeCommitment`.
    /// @param amount USDC to hold for the order: the registrar's price plus the filler's fee.
    /// @param encryptedReveal The details behind `commitment`, encrypted for the filler.
    function placeOrder(bytes32 commitment, uint256 amount, bytes calldata encryptedReveal)
        external
        nonReentrant
        returns (uint256 orderId)
    {
        uint256 got = _pull(PAYMENT_TOKEN, amount);
        if (got < amount) revert InsufficientPayment(got, amount);
        orderId = _open(commitment, amount, encryptedReveal);
    }

    /// @notice Places an order paid with `amountIn` of `tokenIn`, swapped to USDC. Any USDC beyond
    ///         `amount` is sent back. The caller must have approved `amountIn` of `tokenIn`.
    function placeOrderWithToken(
        bytes32 commitment,
        uint256 amount,
        bytes calldata encryptedReveal,
        IERC20 tokenIn,
        uint256 amountIn,
        Swap calldata swap
    ) external nonReentrant returns (uint256 orderId, uint256 change) {
        _validateRoute(address(tokenIn), swap.router, swap.path);
        uint256 got = _toPaymentToken(tokenIn, _pull(tokenIn, amountIn), swap);
        if (got < amount) revert InsufficientPayment(got, amount);
        orderId = _open(commitment, amount, encryptedReveal);
        change = _refund(got - amount);
    }

    /// @notice Places an order paid with the ETH sent along, swapped to USDC. Any USDC beyond
    ///         `amount` is sent back. `swap.path` must start with WETH.
    function placeOrderWithETH(bytes32 commitment, uint256 amount, bytes calldata encryptedReveal, Swap calldata swap)
        external
        payable
        nonReentrant
        returns (uint256 orderId, uint256 change)
    {
        _validateRoute(address(WRAPPED_NATIVE), swap.router, swap.path);
        uint256 got = _toPaymentToken(WRAPPED_NATIVE, _wrap(), swap);
        if (got < amount) revert InsufficientPayment(got, amount);
        orderId = _open(commitment, amount, encryptedReveal);
        change = _refund(got - amount);
    }

    /// @notice Roughly how much of `path[0]` buys `amount` USDC. Ignores transfer taxes; add a buffer.
    function quote(uint256 amount, address router, address[] calldata path) external view returns (uint256 amountIn) {
        return _quoteIn(amount, router, path);
    }

    // ------------------------------------------------------------------------------------------
    // Closing orders
    // ------------------------------------------------------------------------------------------

    /// @inheritdoc IHexOrderSettlement
    /// @dev Only the bridge, delivering a message from the linked PulseChain `HexOrderFiller`, may
    ///      call this. A message that does not match an open order changes nothing, rather than
    ///      reverting, so it is not left failed on the bridge.
    function settle(uint256 orderId, bytes32 commitment, uint64 deadline, address payee, bool filled)
        external
        onlyPeerMessage
        nonReentrant
    {
        Order storage order = orders[orderId];
        if (order.status != Status.OPEN || order.commitment != commitment || order.deadline != deadline) {
            emit SettlementIgnored(orderId, commitment, deadline, filled);
            return;
        }
        if (filled) {
            order.status = Status.FILLED;
            _pay(payee, order.amount, orderId, Status.FILLED);
        } else {
            order.status = Status.REFUNDED;
            _pay(order.buyer, order.amount, orderId, Status.REFUNDED);
        }
    }

    /// @notice Refunds an order that was never settled, once `RECLAIM_DELAY` has passed after its
    ///         fill deadline. Anyone may call it; the money always goes to the buyer.
    function reclaim(uint256 orderId) external nonReentrant {
        Order storage order = orders[orderId];
        if (order.status != Status.OPEN) revert OrderNotOpen(orderId);
        uint256 availableAt = uint256(order.deadline) + RECLAIM_DELAY;
        if (block.timestamp <= availableAt) revert TooEarly(availableAt + 1);
        order.status = Status.RECLAIMED;
        _pay(order.buyer, order.amount, orderId, Status.RECLAIMED);
    }

    /// @notice Withdraws USDC owed to the caller after a transfer to it failed.
    function withdraw() external nonReentrant {
        uint256 amount = owed[msg.sender];
        owed[msg.sender] = 0;
        PAYMENT_TOKEN.safeTransfer(msg.sender, amount);
        emit Withdrawn(msg.sender, amount);
    }

    // ------------------------------------------------------------------------------------------
    // Internals
    // ------------------------------------------------------------------------------------------

    function _open(bytes32 commitment, uint256 amount, bytes calldata encryptedReveal)
        private
        returns (uint256 orderId)
    {
        if (commitment == bytes32(0)) revert InvalidCommitment();
        if (amount == 0 || amount > type(uint96).max) revert InvalidAmount();
        orderId = ++orderCount;
        uint64 deadline = uint64(block.timestamp) + FILL_WINDOW;
        orders[orderId] = Order({
            buyer: msg.sender, amount: uint96(amount), commitment: commitment, deadline: deadline, status: Status.OPEN
        });
        emit OrderPlaced(orderId, msg.sender, commitment, amount, deadline, encryptedReveal);
    }

    /// @dev Sends USDC to `to`. If the transfer fails (for example, `to` is blocked by the token),
    ///      the amount is recorded in `owed` instead, so a bridge message never fails because of it.
    function _pay(address to, uint256 amount, uint256 orderId, Status status) private {
        (bool ok, bytes memory ret) = address(PAYMENT_TOKEN).call(abi.encodeCall(IERC20.transfer, (to, amount)));
        if (!ok || (ret.length != 0 && !abi.decode(ret, (bool))) || address(PAYMENT_TOKEN).code.length == 0) {
            owed[to] += amount;
            emit PaymentDeferred(to, amount);
        }
        emit OrderSettled(orderId, status, to, amount);
    }
}

lib/contracts-v2/contracts/lib/openzeppelin-contracts/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);
}

lib/contracts-v2/contracts/lib/openzeppelin-contracts/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";

lib/contracts-v2/contracts/lib/openzeppelin-contracts/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";

lib/contracts-v2/contracts/lib/openzeppelin-contracts/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);
}

lib/contracts-v2/contracts/lib/openzeppelin-contracts/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);
    }
}

lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol

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

lib/contracts-v2/contracts/lib/openzeppelin-contracts/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);
}

src/common/BridgeLink.sol

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

import {IAMB} from "../interfaces/IAMB.sol";
import {ZeroAddress} from "./Errors.sol";

/// @title BridgeLink
/// @notice Pairs a contract with one contract on the other chain, over the official PulseChain bridge.
/// @dev Each side needs the other's address, so neither can take it as a constructor argument.
///      `LINKER` sets it once with `link`, and after that nothing can change it.
abstract contract BridgeLink {
    /// @notice The bridge's message contract on this chain.
    IAMB public immutable AMB;

    /// @notice The chain the paired contract is on.
    uint256 public immutable PEER_CHAIN_ID;

    /// @notice The only account that may call `link`, once.
    address public immutable LINKER;

    /// @notice The paired contract on the other chain, or zero until linked.
    address public peer;

    /// @notice The paired contract was set.
    event Linked(address indexed peer);

    /// @notice `link` was called by someone other than `LINKER`.
    error NotLinker();
    /// @notice `link` was already called.
    error AlreadyLinked();
    /// @notice A message needed the paired contract before it was set.
    error NotLinked();
    /// @notice The call did not come from the paired contract through the bridge.
    error NotFromPeer();

    constructor(IAMB amb, uint256 peerChainId, address linker) {
        if (address(amb) == address(0) || linker == address(0)) revert ZeroAddress();
        AMB = amb;
        PEER_CHAIN_ID = peerChainId;
        LINKER = linker;
    }

    /// @notice Sets the paired contract on the other chain. Can only be done once, by `LINKER`.
    function link(address peer_) external {
        if (msg.sender != LINKER) revert NotLinker();
        if (peer != address(0)) revert AlreadyLinked();
        if (peer_ == address(0)) revert ZeroAddress();
        peer = peer_;
        emit Linked(peer_);
    }

    /// @dev Lets a call through only if the bridge is delivering a message the paired contract
    ///      sent from the paired chain.
    modifier onlyPeerMessage() {
        address p = peer;
        if (
            msg.sender != address(AMB) || p == address(0) || AMB.messageSender() != p
                || AMB.messageSourceChainId() != PEER_CHAIN_ID
        ) {
            revert NotFromPeer();
        }
        _;
    }

    /// @dev Sends `data` to the paired contract, to be run with `gas` gas.
    function _sendToPeer(bytes memory data, uint256 gas) internal returns (bytes32 messageId) {
        address p = peer;
        if (p == address(0)) revert NotLinked();
        return AMB.requireToPassMessage(p, data, gas);
    }
}

src/common/Errors.sol

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

/// @notice An address argument was zero.
error ZeroAddress();

src/common/SwapPayments.sol

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

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

import {ISwapRouterLike} from "../interfaces/ISwapRouterLike.sol";
import {IWrappedNative} from "../interfaces/IWrappedNative.sol";
import {ZeroAddress} from "./Errors.sol";

/// @title SwapPayments
/// @notice Takes payment in any token with a pool, or in the chain's native coin, and turns it into
///         one stablecoin. Shared by `AnyTokenCheckout` on PulseChain and `HexOrderBook` on Ethereum.
/// @dev Every amount is measured as a balance change, so tokens that charge a transfer tax work,
///      and tokens sent to the contract directly are never counted towards anyone's payment.
///      Swaps only use routers fixed at deployment.
abstract contract SwapPayments {
    using SafeERC20 for IERC20;

    /// @notice How to turn the input into `PAYMENT_TOKEN`.
    /// @dev Leave `path` empty, and `router` zero, when paying with `PAYMENT_TOKEN` itself.
    struct Swap {
        address router; // an allow-listed Uniswap-V2-style router
        address[] path; // path[0] = input token (the wrapped coin for native payments), last = PAYMENT_TOKEN
        uint256 amountOutMin; // the least PAYMENT_TOKEN the swap may return
        uint256 deadline; // unix time after which the swap reverts
    }

    /// @notice The stablecoin every payment is turned into.
    IERC20 public immutable PAYMENT_TOKEN;

    /// @notice The chain's wrapped native coin (WPLS or WETH), used for native payments.
    IERC20 public immutable WRAPPED_NATIVE;

    /// @notice Routers that swaps may use. Set once, in the constructor.
    mapping(address router => bool allowed) public isAllowedRouter;

    /// @notice A router was allowed at deployment.
    event RouterAllowed(address indexed router);

    /// @notice `router` is not on the allow-list.
    error RouterNotAllowed(address router);
    /// @notice The swap path does not run from the input token to `PAYMENT_TOKEN`.
    error InvalidPath();
    /// @notice A native-coin payment was called without any coins.
    error NoValue();
    /// @notice The payment came to less than was needed.
    error InsufficientPayment(uint256 received, uint256 needed);

    constructor(IERC20 paymentToken, IERC20 wrappedNative, address[] memory routers) {
        if (address(paymentToken) == address(0) || address(wrappedNative) == address(0)) revert ZeroAddress();
        PAYMENT_TOKEN = paymentToken;
        WRAPPED_NATIVE = wrappedNative;
        for (uint256 i = 0; i < routers.length; ++i) {
            if (routers[i] == address(0)) revert ZeroAddress();
            isAllowedRouter[routers[i]] = true;
            emit RouterAllowed(routers[i]);
        }
    }

    /// @dev Checks the route before any tokens move.
    function _validateRoute(address tokenIn, address router, address[] calldata path) internal view {
        uint256 n = path.length;
        if (tokenIn == address(PAYMENT_TOKEN)) {
            if (n != 0) revert InvalidPath();
            return;
        }
        if (!isAllowedRouter[router]) revert RouterNotAllowed(router);
        if (n < 2 || path[0] != tokenIn || path[n - 1] != address(PAYMENT_TOKEN)) revert InvalidPath();
    }

    /// @dev Pulls `amount` of `token` from the caller and returns what actually arrived.
    function _pull(IERC20 token, uint256 amount) internal returns (uint256 received) {
        uint256 before = token.balanceOf(address(this));
        token.safeTransferFrom(msg.sender, address(this), amount);
        received = token.balanceOf(address(this)) - before;
    }

    /// @dev Wraps the coins sent with the call and returns the wrapped amount received.
    function _wrap() internal returns (uint256 received) {
        if (msg.value == 0) revert NoValue();
        uint256 before = WRAPPED_NATIVE.balanceOf(address(this));
        IWrappedNative(address(WRAPPED_NATIVE)).deposit{value: msg.value}();
        received = WRAPPED_NATIVE.balanceOf(address(this)) - before;
    }

    /// @dev Swaps `amount` of `tokenIn` into `PAYMENT_TOKEN` and returns what arrived.
    ///      Assumes `_validateRoute` passed.
    function _toPaymentToken(IERC20 tokenIn, uint256 amount, Swap calldata swap) internal returns (uint256 got) {
        if (address(tokenIn) == address(PAYMENT_TOKEN)) return amount;
        uint256 before = PAYMENT_TOKEN.balanceOf(address(this));
        tokenIn.forceApprove(swap.router, amount);
        ISwapRouterLike(swap.router)
            .swapExactTokensForTokensSupportingFeeOnTransferTokens(
                amount, swap.amountOutMin, swap.path, address(this), swap.deadline
            );
        tokenIn.forceApprove(swap.router, 0);
        got = PAYMENT_TOKEN.balanceOf(address(this)) - before;
    }

    /// @dev Roughly how much of `path[0]` buys `amountOut` of `PAYMENT_TOKEN`. Ignores transfer taxes.
    function _quoteIn(uint256 amountOut, address router, address[] calldata path) internal view returns (uint256) {
        if (path.length == 0) return amountOut;
        _validateRoute(path[0], router, path);
        return ISwapRouterLike(router).getAmountsIn(amountOut, path)[0];
    }

    /// @dev Sends `amount` of `PAYMENT_TOKEN` back to the caller.
    function _refund(uint256 amount) internal returns (uint256) {
        if (amount != 0) PAYMENT_TOKEN.safeTransfer(msg.sender, amount);
        return amount;
    }
}

src/interfaces/IAMB.sol

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

/// @notice The parts of the official PulseChain bridge's Arbitrary Message Bridge (AMB) used here.
/// @dev TokenBridge AMB, interfaces version 6.2.0, the same contract family as Gnosis Chain's bridge.
///      Home side on PulseChain: 0x6ef79FD6f9f840264332884240539Ed7A2dA8b2b.
///      Foreign side on Ethereum: 0xd0764FAe29E0a6a96fF685f71CfC685456D5636c.
///      Both are signed for by the same 8 validators, 5 of whom must sign each message
///      (checked on-chain on 2026-11-05). Any contract may send a message.
interface IAMB {
    /// @notice Queues a call to `target` on the other chain, run with `gas` gas once validators sign.
    /// @return messageId The bridge's id for the message.
    function requireToPassMessage(address target, bytes calldata data, uint256 gas) external returns (bytes32 messageId);

    /// @notice While a message from the other chain is running: the contract that sent it.
    function messageSender() external view returns (address);

    /// @notice While a message from the other chain is running: the chain it was sent from.
    function messageSourceChainId() external view returns (uint256);

    /// @notice The most gas a message may ask for.
    function maxGasPerTx() external view returns (uint256);
}

src/interfaces/IHexBridge.sol

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

/// @notice The two messages PulseChain sends to Ethereum over the bridge.

/// @notice Received by `HexOrderBook` on Ethereum, sent by `HexOrderFiller` on PulseChain.
interface IHexOrderSettlement {
    /// @notice Closes an Ethereum order. `filled` true pays `payee`, false refunds the buyer.
    /// @param orderId The order's id in `HexOrderBook`.
    /// @param commitment The registrar commitment the order was placed with.
    /// @param deadline The order's fill deadline.
    function settle(uint256 orderId, bytes32 commitment, uint64 deadline, address payee, bool filled) external;
}

/// @notice Received by `HexMirrorRegistrar` on Ethereum, sent by `HexMirrorSync` on PulseChain.
interface IHexMirrorReceiver {
    /// @notice Copies the PulseChain state of `label`.hex: its owner (zero if not registered) and
    ///         expiry. `nonce` increases with every message, so stale ones can be ignored.
    function mirror(string calldata label, address owner, uint64 expiry, uint64 nonce) external;
}

/// @notice `HexMirrorSync` on PulseChain.
interface IHexMirrorSync {
    /// @notice Sends the current PulseChain state of `label`.hex to Ethereum.
    function sync(string calldata label) external returns (bytes32 messageId);
}

src/interfaces/ISwapRouterLike.sol

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

/// @notice The parts of a Uniswap-V2-style router that the checkouts call.
/// @dev PulseX V1 (0x98bf93ebf5c380C0e6Ae8e192A7e2AE08edAcc02) and V2
///      (0x165C3410fC91EF562C50559f7d2289fEbed552d9) on PulseChain, and Uniswap V2
///      (0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) on Ethereum, all expose these functions.
interface ISwapRouterLike {
    /// @notice Swaps exactly `amountIn` of `path[0]` for at least `amountOutMin` of the last token
    ///         in `path`, sent to `to`. Works with tokens that take a fee on transfer.
    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external;

    /// @notice How much of `path[0]` is needed to get `amountOut` of the last token in `path`.
    /// @dev Ignores transfer taxes.
    function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);

    /// @notice How much of the last token in `path` you get for `amountIn` of `path[0]`.
    function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
}

src/interfaces/IWrappedNative.sol

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

/// @notice WETH9-style wrapper for a chain's native coin: WPLS on PulseChain, WETH on Ethereum.
///         Only `deposit` is needed here; balances and approvals use the standard ERC-20 interface.
interface IWrappedNative {
    /// @notice Wraps the coins sent with the call into the same amount of the wrapped token.
    function deposit() external payable;
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 1000,
    "enabled": true
  },
  "evmVersion": "shanghai",
  "remappings": [
    "@ens/contracts/=lib/contracts-v2/contracts/lib/ens-contracts/contracts/",
    "@ensdomains/buffer/=lib/contracts-v2/contracts/lib/buffer/",
    "@ensdomains/verifiable-factory/=lib/contracts-v2/contracts/lib/verifiable-factory/src/",
    "@ensv2/=lib/contracts-v2/contracts/src/",
    "@openzeppelin/contracts-upgradeable/=lib/contracts-v2/contracts/lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts-v5/=lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts/=lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/",
    "@unruggable/gateways/=lib/contracts-v2/contracts/lib/unruggable-gateways/",
    "buffer/=lib/contracts-v2/contracts/lib/buffer/contracts/",
    "contracts-v2/=lib/contracts-v2/",
    "ens-contracts/=lib/contracts-v2/contracts/lib/ens-contracts/contracts/",
    "forge-std/=lib/contracts-v2/contracts/lib/forge-std/src/",
    "openzeppelin-contracts-upgradeable/=lib/contracts-v2/contracts/lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts-v4/=lib/contracts-v2/contracts/lib/openzeppelin-contracts-v4/",
    "openzeppelin-contracts/=lib/contracts-v2/contracts/lib/openzeppelin-contracts/",
    "optimism/=lib/contracts-v2/contracts/lib/unruggable-gateways/lib/optimism/packages/contracts-bedrock/src/",
    "solady/=lib/contracts-v2/contracts/lib/solady/src/",
    "solsha1/=lib/contracts-v2/contracts/lib/solsha1/contracts/",
    "unruggable-gateways/=lib/contracts-v2/contracts/lib/unruggable-gateways/contracts/",
    "verifiable-factory/=lib/contracts-v2/contracts/lib/verifiable-factory/src/",
    "lib/contracts-v2/contracts/lib/ens-contracts/:@ensdomains/solsha1/contracts/=lib/contracts-v2/contracts/lib/solsha1/contracts/",
    "lib/contracts-v2/contracts/lib/ens-contracts/:@openzeppelin/contracts-v5/=lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/",
    "lib/contracts-v2/contracts/lib/ens-contracts/:@openzeppelin/contracts/=lib/contracts-v2/contracts/lib/openzeppelin-contracts-v4/contracts/",
    "lib/contracts-v2/contracts/lib/ens-contracts/:@unruggable/gateways/=lib/contracts-v2/contracts/lib/unruggable-gateways/contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.