Skip to content
Verified contractExactBUSL-1.1

OrderBook

Address0x94fcf9727385e852febf6fb813f1aa4545271334
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.33

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.33+commit.64118f21
Language
solidity
Optimization
Yes, 1,000 runs
EVM version
cancun
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,288,181
Creation transaction
0xf5e04f6a6c…171408e3ba

26 files

src/OrderBook.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.33;

import { IERC20 } from "../lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol";
import { IERC20Extended } from "../lib/common/src/interfaces/IERC20Extended.sol";
import { AccessControlUpgradeable } from "../lib/common/lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol";
import { PausableUpgradeable } from "../lib/common/lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol";
import { ERC712ExtendedUpgradeable } from "../lib/common/src/ERC712ExtendedUpgradeable.sol";
import { TypeConverter } from "../lib/common/src/libs/TypeConverter.sol";
import { UIntMath } from "../lib/common/src/libs/UIntMath.sol";
import { SafeERC20 } from "./libs/SafeERC20.sol";

import { IOrderBook } from "./interfaces/IOrderBook.sol";
import { IPortalV2Like } from "./interfaces/IPortalV2Like.sol";

abstract contract OrderBookStorageLayout {
    /// @custom:storage-location erc7201:M0.storage.OrderBook
    struct OrderBookStorageStruct {
        // supported destination chains
        mapping(uint32 destChainId => bool isSupported) supportedDestinations;
        // only store full data about origin orders, status is tracked for all orders
        mapping(bytes32 orderId => IOrderBook.Order) orders;
        // store fill amounts for both origin and destination orders
        mapping(bytes32 orderId => IOrderBook.FilledAmounts) filledAmounts;
        // track nonces for each sender to ensure unique order IDs
        mapping(address sender => uint64 nonce) senderNonces;
    }

    // keccak256(abi.encode(uint256(keccak256("M0.storage.OrderBook")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant _ORDER_BOOK_STORAGE_LOCATION =
        0x820bf725beb8a0ae85e433f17c2d2091cee8f490a62ab8bd0d9dd95db3dddc00;

    function _getOrderBookStorageLocation() internal pure returns (OrderBookStorageStruct storage $) {
        assembly {
            $.slot := _ORDER_BOOK_STORAGE_LOCATION
        }
    }
}

contract OrderBook is
    IOrderBook,
    OrderBookStorageLayout,
    AccessControlUpgradeable,
    PausableUpgradeable,
    ERC712ExtendedUpgradeable
{
    using TypeConverter for *;
    using SafeERC20 for IERC20;
    using UIntMath for uint256;

    // ========== State Variables ========== //

    bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");

    /// @notice Version of the limit order system
    uint16 public constant VERSION = 1;

    /// @notice the type hash used for cancel order signatures
    /// @dev keccak256("CancelOrder(bytes32 orderId,address bridgeAdapter,bytes bridgeAdapterArgs)")
    bytes32 public constant CANCEL_ORDER_TYPEHASH = 0xd7cf6d47f97dd3a3fc3f51421ddc4df9388bdfe3897719dccae3180a7a5a52e3;

    /// @notice the portal contract used for cross-chain communication
    /// @dev sends crosschain messages to report fills and cancels on this chain to other chains
    ///      receives crosschain messages reporting fills and cancels on other chains to this chain
    address public immutable portal;

    /* ========== Construct and Initialize ========== */

    constructor(address portal_) {
        _disableInitializers(); // prevent initializing the implementation contract

        if (portal_ == address(0)) revert ZeroPortal();
        portal = portal_;
    }

    function initialize(address admin, address pauser) external initializer {
        if (admin == address(0)) revert ZeroAdmin();
        if (pauser == address(0)) revert ZeroPauser();

        __ERC712ExtendedUpgradeable_init("M0 OrderBook");

        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        _grantRole(PAUSER_ROLE, pauser);
    }

    /* ========== Creating Orders ========== */

    /// @inheritdoc IOrderBook
    function openOrder(OrderParams calldata orderParams_) external override returns (bytes32 orderId_) {
        orderId_ = _openOrder(msg.sender, orderParams_);
    }

    /// @inheritdoc IOrderBook
    function openOrderWithPermit(
        OrderParams calldata orderParams_,
        uint256 deadline_,
        uint8 v_,
        bytes32 r_,
        bytes32 s_
    ) external override returns (bytes32 orderId_) {
        try
            IERC20Extended(orderParams_.tokenIn).permit(
                msg.sender,
                address(this),
                uint256(orderParams_.amountIn),
                deadline_,
                v_,
                r_,
                s_
            )
        {} catch {}
        orderId_ = _openOrder(msg.sender, orderParams_);
    }

    /// @inheritdoc IOrderBook
    function openOrderWithPermit(
        OrderParams calldata orderParams_,
        uint256 deadline_,
        bytes memory permitSignature_
    ) external override returns (bytes32 orderId_) {
        try
            IERC20Extended(orderParams_.tokenIn).permit(
                msg.sender,
                address(this),
                uint256(orderParams_.amountIn),
                deadline_,
                permitSignature_
            )
        {} catch {}
        orderId_ = _openOrder(msg.sender, orderParams_);
    }

    function _openOrder(
        address funder_,
        OrderParams memory orderParams_
    ) internal whenNotPaused returns (bytes32 orderId_) {
        // Validate order parameters
        if (uint256(orderParams_.fillDeadline) < block.timestamp) revert InvalidDeadline();
        if (orderParams_.amountIn == 0) revert AmountInZero();
        if (orderParams_.amountOut == 0) revert AmountOutZero();
        if (orderParams_.recipient == bytes32(0)) revert InvalidRecipient();
        if (orderParams_.solver == orderParams_.recipient) revert InvalidSolver();
        if (orderParams_.sender == address(0)) revert ZeroSender();

        // Validate that tokenIn and tokenOut are not the same for same-chain orders
        uint32 chainId = block.chainid.safe32();
        if (orderParams_.destChainId == chainId && orderParams_.tokenOut == orderParams_.tokenIn.toBytes32())
            revert SameTokenOrder();

        // Destination chain must either be the current chain or a supported destination
        if (!isDestinationSupported(orderParams_.destChainId)) revert InvalidDestinationChain();

        // Create order
        OrderBookStorageStruct storage $ = _getOrderBookStorageLocation();
        uint64 nonce_ = $.senderNonces[orderParams_.sender]++;

        orderId_ = getOrderId(
            OrderData({
                version: VERSION, // origin contract version
                originChainId: chainId,
                sender: orderParams_.sender.toBytes32(),
                nonce: nonce_,
                destChainId: orderParams_.destChainId,
                createdAt: uint64(block.timestamp),
                fillDeadline: uint64(orderParams_.fillDeadline),
                tokenIn: orderParams_.tokenIn.toBytes32(),
                tokenOut: orderParams_.tokenOut,
                recipient: orderParams_.recipient,
                amountIn: orderParams_.amountIn,
                amountOut: orderParams_.amountOut,
                solver: orderParams_.solver
            })
        );

        // Shouldn't be needed due to uniqueness of order ID, but
        // it is good to be explicit about the expected state
        // and this protects against a (very unlikely) hash collision
        if ($.orders[orderId_].status != OrderStatus.DoesNotExist) revert OrderAlreadyExists();

        $.orders[orderId_] = Order({
            version: VERSION, // origin contract version
            status: OrderStatus.Created,
            destChainId: orderParams_.destChainId,
            createdAt: uint32(block.timestamp),
            fillDeadline: orderParams_.fillDeadline,
            nonce: nonce_,
            tokenIn: orderParams_.tokenIn,
            tokenOut: orderParams_.tokenOut,
            sender: orderParams_.sender,
            recipient: orderParams_.recipient,
            amountIn: orderParams_.amountIn,
            amountOut: orderParams_.amountOut,
            solver: orderParams_.solver
        });

        // Transfer tokens in from the funder, ensuring the required amount is received
        // Note: sender_ is the order owner (for cancellation/refunds), funder_ provides the tokens
        IERC20(orderParams_.tokenIn).safeTransferExactFrom(funder_, address(this), uint256(orderParams_.amountIn));

        emit OrderOpened(
            orderId_,
            funder_,
            orderParams_.sender,
            orderParams_.tokenIn,
            orderParams_.amountIn,
            orderParams_.destChainId,
            orderParams_.tokenOut,
            orderParams_.amountOut,
            orderParams_.solver,
            orderParams_.fillDeadline
        );
    }

    /* ========== Refunding Orders ========== */

    /// @inheritdoc IOrderBook
    function cancelOrder(
        bytes32 orderId_,
        OrderData calldata orderData_
    ) external payable override returns (bytes32 messageId_) {
        messageId_ = _cancelOrder(orderId_, orderData_, address(0), new bytes(0));
    }

    /// @inheritdoc IOrderBook
    function cancelOrder(
        bytes32 orderId_,
        OrderData calldata orderData_,
        bytes calldata bridgeAdapterArgs_
    ) external payable override returns (bytes32 messageId_) {
        messageId_ = _cancelOrder(orderId_, orderData_, address(0), bridgeAdapterArgs_);
    }

    /// @inheritdoc IOrderBook
    function cancelOrder(
        bytes32 orderId_,
        OrderData calldata orderData_,
        address bridgeAdapter_,
        bytes calldata bridgeAdapterArgs_
    ) external payable override returns (bytes32 messageId_) {
        messageId_ = _cancelOrder(orderId_, orderData_, bridgeAdapter_, bridgeAdapterArgs_);
    }

    function _cancelOrder(
        bytes32 orderId_,
        OrderData calldata orderData_,
        address bridgeAdapter_,
        bytes memory bridgeAdapterArgs_
    ) internal returns (bytes32 messageId_) {
        // Cancellation Authorization:
        // 1. Before deadline:
        //   - Same-chain orders: sender OR recipient
        //   - Cross-chain orders: recipient only (sender address is non-native)
        // 2. After deadline:
        //   - All orders: anyone (enables permissionless refunds)
        if (
            block.timestamp <= orderData_.fillDeadline &&
            !(orderData_.recipient.toAddress() == msg.sender ||
                (orderData_.originChainId == block.chainid && orderData_.sender.toAddress() == msg.sender))
        ) revert NotAuthorized();

        messageId_ = _cancel(orderId_, orderData_, bridgeAdapter_, bridgeAdapterArgs_);
    }

    /// @inheritdoc IOrderBook
    function cancelOrderFor(
        bytes32 orderId_,
        OrderData calldata orderData_,
        bytes calldata signature_
    ) external payable override returns (bytes32 messageId_) {
        messageId_ = _cancelOrderFor(orderId_, orderData_, signature_, address(0), new bytes(0));
    }

    /// @inheritdoc IOrderBook
    function cancelOrderFor(
        bytes32 orderId_,
        OrderData calldata orderData_,
        bytes calldata signature_,
        bytes calldata bridgeAdapterArgs_
    ) external payable override returns (bytes32 messageId_) {
        messageId_ = _cancelOrderFor(orderId_, orderData_, signature_, address(0), bridgeAdapterArgs_);
    }

    /// @inheritdoc IOrderBook
    function cancelOrderFor(
        bytes32 orderId_,
        OrderData calldata orderData_,
        bytes calldata signature_,
        address bridgeAdapter_,
        bytes calldata bridgeAdapterArgs_
    ) external payable override returns (bytes32 messageId_) {
        messageId_ = _cancelOrderFor(orderId_, orderData_, signature_, bridgeAdapter_, bridgeAdapterArgs_);
    }

    function _cancelOrderFor(
        bytes32 orderId_,
        OrderData calldata orderData_,
        bytes calldata signature_,
        address bridgeAdapter_,
        bytes memory bridgeAdapterArgs_
    ) internal returns (bytes32 messageId_) {
        // Verify signature
        if (signature_.length == 64) {
            (bytes32 r, bytes32 vs) = abi.decode(signature_, (bytes32, bytes32));
            _revertIfInvalidSignature(
                orderData_.recipient.toAddress(),
                getCancelOrderDigest(orderId_, bridgeAdapter_, bridgeAdapterArgs_),
                r,
                vs
            );
        } else {
            _revertIfInvalidSignature(
                orderData_.recipient.toAddress(),
                getCancelOrderDigest(orderId_, bridgeAdapter_, bridgeAdapterArgs_),
                signature_
            );
        }

        messageId_ = _cancel(orderId_, orderData_, bridgeAdapter_, bridgeAdapterArgs_);
    }

    function _cancel(
        bytes32 orderId_,
        OrderData calldata orderData_,
        address bridgeAdapter_,
        bytes memory bridgeAdapterArgs_
    ) internal whenNotPaused returns (bytes32 messageId_) {
        _revertIfOrderIdMismatch(orderId_, orderData_);

        // Can't cancel an order before it's created
        if (orderData_.createdAt > block.timestamp) revert InvalidTimestamp();

        Order storage order = _getOrderBookStorageLocation().orders[orderId_];
        _revertIfInvalidStatusToFillOrCancel(order, orderData_);

        // Order destination chain must be this chain
        if (block.chainid != orderData_.destChainId) revert InvalidDestinationChain();

        // Calculate amount to refund
        IOrderBook.FilledAmounts storage filledAmounts = _getOrderBookStorageLocation().filledAmounts[orderId_];
        uint128 amountInRemaining_ = orderData_.amountIn - filledAmounts.amountInReleased;
        // filledAmounts.amountInRefunded doesn't need to be considered here because it must be zero prior to cancellation

        // Update order status and refunded amount
        order.status = OrderStatus.Cancelled;
        filledAmounts.amountInRefunded += amountInRemaining_;

        if (orderData_.originChainId == block.chainid) {
            if (msg.value != 0) revert InvalidMsgValue();

            // Local orders can be immediately refunded
            IERC20(order.tokenIn).safeTransfer(order.sender, uint256(amountInRemaining_));

            emit RefundClaimed(orderId_, order.sender, amountInRemaining_);
        } else {
            // Cross-chain orders require sending a cancel report to the origin chain
            CancelReport memory report_ = CancelReport({
                orderId: orderId_,
                orderSender: orderData_.sender,
                tokenIn: orderData_.tokenIn,
                amountInToRefund: amountInRemaining_
            });

            messageId_ =
                bridgeAdapter_ == address(0)
                    ? IPortalV2Like(portal).sendCancelReport{ value: msg.value }(
                        orderData_.originChainId,
                        report_,
                        msg.sender.toBytes32(), // refundAddress
                        bridgeAdapterArgs_
                    )
                    : IPortalV2Like(portal).sendCancelReport{ value: msg.value }(
                        orderData_.originChainId,
                        report_,
                        msg.sender.toBytes32(), // refundAddress
                        bridgeAdapter_,
                        bridgeAdapterArgs_
                    );
        }

        emit OrderCancelled(orderId_, messageId_);
    }

    /* ========== Filling Orders ========== */

    /// @inheritdoc IOrderBook
    function fillOrder(
        bytes32 orderId_,
        OrderData calldata orderData_,
        FillParams calldata fillerParams_
    ) external payable override returns (bytes32 messageId_) {
        messageId_ = _fillOrder(orderId_, orderData_, fillerParams_, address(0), new bytes(0));
    }

    /// @inheritdoc IOrderBook
    function fillOrder(
        bytes32 orderId_,
        OrderData calldata orderData_,
        FillParams calldata fillerParams_,
        bytes calldata bridgeAdapterArgs_
    ) external payable override returns (bytes32 messageId_) {
        messageId_ = _fillOrder(orderId_, orderData_, fillerParams_, address(0), bridgeAdapterArgs_);
    }

    /// @inheritdoc IOrderBook
    function fillOrder(
        bytes32 orderId_,
        OrderData calldata orderData_,
        FillParams calldata fillerParams_,
        address bridgeAdapter_,
        bytes calldata bridgeAdapterArgs_
    ) external payable override returns (bytes32 messageId_) {
        messageId_ = _fillOrder(orderId_, orderData_, fillerParams_, bridgeAdapter_, bridgeAdapterArgs_);
    }

    function _fillOrder(
        bytes32 orderId_,
        OrderData calldata orderData_,
        FillParams calldata fillerParams_,
        address bridgeAdapter_,
        bytes memory bridgeAdapterArgs_
    ) internal whenNotPaused returns (bytes32 messageId_) {
        _revertIfOrderIdMismatch(orderId_, orderData_);

        // Validate fill data
        if (block.chainid != orderData_.destChainId) revert InvalidDestinationChain();
        if (orderData_.fillDeadline < block.timestamp) revert OrderExpired();
        if (orderData_.version != VERSION) revert InvalidOrderVersion();
        if (orderData_.createdAt > block.timestamp) revert InvalidTimestamp();
        if (fillerParams_.amountOutToFill == 0) revert FillAmountZero();
        if (fillerParams_.originRecipient == bytes32(0)) revert InvalidRecipient();

        // If the solver is specified, ensure that the caller is the designated solver
        address solver_ = orderData_.solver.toAddress();
        if (solver_ != address(0) && solver_ != msg.sender) revert NotAuthorized();

        OrderBookStorageStruct storage $ = _getOrderBookStorageLocation();
        Order storage order = $.orders[orderId_];
        _revertIfInvalidStatusToFillOrCancel(order, orderData_);

        uint128 amountInToRelease_;
        uint128 amountOutToFill_;
        // Local scope to avoid stack too deep errors
        {
            // Calculate fill amount as the minimum of the filler provided amount and the remaining unfilled amount
            IOrderBook.FilledAmounts storage filledAmounts = $.filledAmounts[orderId_];

            bool fullFill_;
            (fullFill_, amountInToRelease_, amountOutToFill_) = _calculateFill(
                orderData_.amountIn,
                orderData_.amountOut,
                filledAmounts.amountInReleased,
                filledAmounts.amountOutFilled,
                fillerParams_.amountOutToFill
            );

            // Update filled amounts
            filledAmounts.amountOutFilled += amountOutToFill_;
            filledAmounts.amountInReleased += amountInToRelease_;

            // If full fill, update order status to completed
            if (fullFill_) {
                order.status = OrderStatus.Completed;
                emit OrderCompleted(orderId_);
            } else {
                // Set order status to created in case of uninitialized cross-chain order
                if (orderData_.originChainId != block.chainid && order.status == OrderStatus.DoesNotExist) {
                    order.status = OrderStatus.Created;
                }
            }
        }

        // Transfer tokens from the solver to the recipient
        IERC20(orderData_.tokenOut.toAddress()).safeTransferExactFrom(
            msg.sender,
            orderData_.recipient.toAddress(),
            uint256(amountOutToFill_)
        );

        // If local order, release the corresponding amount of origin tokens to the filler
        if (block.chainid == orderData_.originChainId) {
            // Validate msg.value is 0 for local fills
            if (msg.value != 0) revert InvalidMsgValue();

            // If this is a fill on the origin chain, we can immediately release the token in to the filler
            // This is because the origin and destination chains are the same, so no cross-chain messaging is needed
            IERC20(order.tokenIn).safeTransferExact(
                fillerParams_.originRecipient.toAddress(),
                uint256(amountInToRelease_)
            );
        } else {
            // If this is a fill on a different chain than the origin chain,
            // we need to send a message back to the origin chain to release
            // the corresponding amount of tokenIn to the solver's recipient
            FillReport memory report_ = FillReport({
                orderId: orderId_,
                originRecipient: fillerParams_.originRecipient,
                amountOutFilled: amountOutToFill_,
                amountInToRelease: amountInToRelease_,
                tokenIn: orderData_.tokenIn
            });

            // Send fill report to the origin chain and pass along msg.value
            // to the portal for crosschain message fee
            bytes32 refundAddress =
                fillerParams_.refundAddress == bytes32(0) ? msg.sender.toBytes32() : fillerParams_.refundAddress;
            messageId_ =
                bridgeAdapter_ == address(0)
                    ? IPortalV2Like(portal).sendFillReport{ value: msg.value }(
                        orderData_.originChainId, // destinationChainId (of this message)
                        report_,
                        refundAddress,
                        bridgeAdapterArgs_
                    )
                    : IPortalV2Like(portal).sendFillReport{ value: msg.value }(
                        orderData_.originChainId, // destinationChainId (of this message)
                        report_,
                        refundAddress,
                        bridgeAdapter_,
                        bridgeAdapterArgs_
                    );
        }

        emit OrderFilled(orderId_, msg.sender, amountInToRelease_, amountOutToFill_, messageId_);
    }

    /* ========== Receiving Crosschain Reports ========== */

    /// @inheritdoc IOrderBook
    function reportFill(uint32 sourceChainId_, FillReport calldata report_) external override {
        OrderBookStorageStruct storage $ = _getOrderBookStorageLocation();
        Order storage order = $.orders[report_.orderId];

        // Validate the fill report and sender
        if (msg.sender != portal) revert NotAuthorized();
        // We allow reporting fills for both Created and Cancelled orders
        // The latter allows for fills that were in-flight at the time of cancellation
        // that may have arrived after the cancel report was processed due to the fact that
        // crosschain messages do not have to processed in the order they were sent.
        if (!(order.status == OrderStatus.Created || order.status == OrderStatus.Cancelled))
            revert InvalidOrderStatus();
        if (report_.tokenIn != order.tokenIn.toBytes32()) revert InvalidReport();
        if (sourceChainId_ != order.destChainId) revert InvalidReportSource();

        // Calculate the fill to determine if it completely fills the order
        (bool fullFill, , ) = _calculateFill(
            order.amountIn,
            order.amountOut,
            $.filledAmounts[report_.orderId].amountInReleased,
            $.filledAmounts[report_.orderId].amountOutFilled,
            report_.amountOutFilled
        );

        // Update the fill amounts for the order
        IOrderBook.FilledAmounts storage filledAmounts = $.filledAmounts[report_.orderId];
        filledAmounts.amountOutFilled += report_.amountOutFilled;
        filledAmounts.amountInReleased += report_.amountInToRelease;

        // Validate that the filled amounts do not exceed the order amounts
        // For tokenIn amounts, this includes both released and refunded amounts since
        // both reduce the amount available to be filled. Refunded amounts may have been
        // paid out previously via a cancel report.
        if (
            filledAmounts.amountOutFilled > order.amountOut ||
            filledAmounts.amountInReleased + filledAmounts.amountInRefunded > order.amountIn
        ) revert InvalidReport();

        // Mark order as completed if fully filled
        if (fullFill) {
            order.status = OrderStatus.Completed;
            emit OrderCompleted(report_.orderId);
        }

        // Transfer the amount in to release to the recipient specified by the filler
        // We do not check fee on transfer here to avoid potential reverts on reported fills
        IERC20(order.tokenIn).safeTransfer(report_.originRecipient.toAddress(), uint256(report_.amountInToRelease));

        emit FillReported(
            report_.orderId,
            report_.originRecipient.toAddress(),
            report_.amountInToRelease,
            report_.amountOutFilled
        );
    }

    /// @inheritdoc IOrderBook
    function reportCancel(uint32 sourceChainId_, CancelReport calldata report_) external override {
        Order storage order = _getOrderBookStorageLocation().orders[report_.orderId];

        // Validate the cancel report and sender
        if (msg.sender != portal) revert NotAuthorized();
        if (order.status != OrderStatus.Created) revert InvalidOrderStatus();
        if (sourceChainId_ != order.destChainId) revert InvalidReportSource();

        // Validate the reported order sender and token in match
        // This isn't strictly required because we use local data,
        // but invalid reports should not be sent so we prevent this
        if (order.tokenIn != report_.tokenIn.toAddress() || order.sender != report_.orderSender.toAddress())
            revert InvalidReport();

        // Update order status and refunded amount
        order.status = OrderStatus.Cancelled;
        FilledAmounts storage filledAmounts = _getOrderBookStorageLocation().filledAmounts[report_.orderId];
        filledAmounts.amountInRefunded += report_.amountInToRefund;

        // Validate that the refunded amount does not cause over-refunding
        if (filledAmounts.amountInRefunded + filledAmounts.amountInReleased > order.amountIn) revert InvalidReport();

        // Transfer the refund amount to the original order sender
        IERC20(order.tokenIn).safeTransfer(order.sender, uint256(report_.amountInToRefund));

        emit CancelReported(report_.orderId);
        emit RefundClaimed(report_.orderId, order.sender, report_.amountInToRefund);
    }

    /* ========== Admin Functions ========== */

    /// @inheritdoc IOrderBook
    function setDestinationSupported(
        uint32 destChainId_,
        bool isSupported_
    ) external override onlyRole(DEFAULT_ADMIN_ROLE) {
        if (destChainId_ == block.chainid) revert InvalidDestinationChain();

        OrderBookStorageStruct storage $ = _getOrderBookStorageLocation();
        bool isSupported = $.supportedDestinations[destChainId_];

        // Don't update if the value is the same
        if (isSupported == isSupported_) return;

        $.supportedDestinations[destChainId_] = isSupported_;

        emit DestinationSupportUpdated(destChainId_, isSupported_);
    }

    /// @inheritdoc IOrderBook
    function pause() external onlyRole(PAUSER_ROLE) {
        _pause();
    }

    /// @inheritdoc IOrderBook
    function unpause() external onlyRole(PAUSER_ROLE) {
        _unpause();
    }

    /* ========== View Functions ========== */

    /// @inheritdoc IOrderBook
    function getOrderId(OrderData memory orderData_) public pure override returns (bytes32) {
        return
            keccak256(
                abi.encodePacked(
                    orderData_.version,
                    orderData_.sender,
                    orderData_.nonce,
                    orderData_.originChainId,
                    orderData_.destChainId,
                    orderData_.createdAt,
                    orderData_.fillDeadline,
                    orderData_.tokenIn,
                    orderData_.tokenOut,
                    orderData_.amountIn,
                    orderData_.amountOut,
                    orderData_.recipient,
                    orderData_.solver
                )
            );
    }

    /// @inheritdoc IOrderBook
    function getOrder(bytes32 orderId_) external view override returns (Order memory) {
        OrderBookStorageStruct storage $ = _getOrderBookStorageLocation();
        return $.orders[orderId_];
    }

    /// @inheritdoc IOrderBook
    function getOrderData(bytes32 orderId_) external view override returns (OrderData memory) {
        OrderBookStorageStruct storage $ = _getOrderBookStorageLocation();
        Order storage order_ = $.orders[orderId_];

        return
            OrderData({
                version: order_.version,
                sender: order_.sender.toBytes32(),
                nonce: order_.nonce,
                originChainId: uint32(block.chainid),
                destChainId: order_.destChainId,
                createdAt: uint64(order_.createdAt),
                fillDeadline: uint64(order_.fillDeadline),
                tokenIn: order_.tokenIn.toBytes32(),
                tokenOut: order_.tokenOut,
                amountIn: order_.amountIn,
                amountOut: order_.amountOut,
                recipient: order_.recipient,
                solver: order_.solver
            });
    }

    /// @inheritdoc IOrderBook
    function getFilledAmounts(bytes32 orderId_) external view override returns (FilledAmounts memory) {
        OrderBookStorageStruct storage $ = _getOrderBookStorageLocation();
        return $.filledAmounts[orderId_];
    }

    /// @inheritdoc IOrderBook
    function getSenderNonce(address sender_) external view override returns (uint64) {
        OrderBookStorageStruct storage $ = _getOrderBookStorageLocation();
        return $.senderNonces[sender_];
    }

    /// @inheritdoc IOrderBook
    function isDestinationSupported(uint32 destChainId_) public view override returns (bool) {
        return destChainId_ == block.chainid || _getOrderBookStorageLocation().supportedDestinations[destChainId_];
    }

    /* ========== EIP-712 Digest Functions ========== */

    /// @inheritdoc IOrderBook
    function getCancelOrderDigest(
        bytes32 orderId_,
        address bridgeAdapter_,
        bytes memory bridgeAdapterArgs_
    ) public view override returns (bytes32) {
        return
            _getDigest(
                keccak256(abi.encode(CANCEL_ORDER_TYPEHASH, orderId_, bridgeAdapter_, keccak256(bridgeAdapterArgs_)))
            );
    }

    /* ========== Internal Helper Functions ========== */

    function _revertIfInvalidStatusToFillOrCancel(Order storage order_, OrderData memory orderData_) internal view {
        // Check order status
        // If local order, status must be Created
        // If cross-chain order, status must be DoesNotExist (if not filled at all yet) or Created (if already partially filled)
        if (
            !(
                orderData_.originChainId == block.chainid
                    ? order_.status == OrderStatus.Created
                    : (order_.status == OrderStatus.Created || order_.status == OrderStatus.DoesNotExist)
            )
        ) revert InvalidOrderStatus();
    }

    function _revertIfOrderIdMismatch(bytes32 orderId_, OrderData memory orderData_) internal pure {
        // Ensures that the specified orderId, used to retrieve the order data from storage,
        // is bound to the orderData provided as input. This prevents the caller from specifying
        // inconsistent (malicious) orderData compared to the content of the order fetched from storage.
        if (orderId_ != getOrderId(orderData_)) revert OrderIdMismatch();
    }

    /// @notice Calculates the fill amounts for an order fill from the provided state and amount out to fill
    /// @param totalAmountIn_ The total amount of token in for the order
    /// @param totalAmountOut_ The total amount of token out for the order
    /// @param amountInReleased_ The amount of token in already released for the order
    /// @param amountOutFilled_ The amount of token out already filled for the order
    /// @param amountOutToFill_ The amount of token out the filler wants to fill
    /// @return fullFill_ Whether the fill is a full fill
    /// @return amountInToRelease_ The amount of token in to release to the filler
    /// @return amountOutToFill_ The amount of token out to fill, this is the minimum of the provided amount and the remaining unfilled amount
    function _calculateFill(
        uint128 totalAmountIn_,
        uint128 totalAmountOut_,
        uint128 amountInReleased_,
        uint128 amountOutFilled_,
        uint128 amountOutToFill_
    ) internal pure returns (bool, uint128, uint128) {
        // Determine the amount out to fill as the minimum of the filler provided amount and the remaining unfilled amount
        uint128 amountOutRemaining_ = totalAmountOut_ - amountOutFilled_; // can't underflow bc amountOutFilled_ <= totalAmountOut_
        bool fullFill_ = amountOutToFill_ >= amountOutRemaining_;
        amountOutToFill_ = fullFill_ ? amountOutRemaining_ : amountOutToFill_;

        // Calculate the corresponding amount of token in to release to the filler
        uint128 amountInToRelease_ =
            fullFill_
                ? totalAmountIn_ - amountInReleased_ // remaining amount
                : ((uint256(totalAmountIn_) * amountOutToFill_) / totalAmountOut_).toUint128();

        return (fullFill_, amountInToRelease_, amountOutToFill_);
    }
}

lib/common/lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;


    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
    struct AccessControlStorage {
        mapping(bytes32 role => RoleData) _roles;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;

    function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
        assembly {
            $.slot := AccessControlStorageLocation
        }
    }

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        AccessControlStorage storage $ = _getAccessControlStorage();
        bytes32 previousAdminRole = getRoleAdmin(role);
        $._roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (!hasRole(role, account)) {
            $._roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (hasRole(role, account)) {
            $._roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

lib/common/lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

lib/common/lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol

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

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

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

lib/common/lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol

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

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Pausable
    struct PausableStorage {
        bool _paused;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;

    function _getPausableStorage() private pure returns (PausableStorage storage $) {
        assembly {
            $.slot := PausableStorageLocation
        }
    }

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    function __Pausable_init() internal onlyInitializing {
    }

    function __Pausable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        PausableStorage storage $ = _getPausableStorage();
        return $._paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = false;
        emit Unpaused(_msgSender());
    }
}

lib/common/lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol

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

pragma solidity ^0.8.20;

import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165Upgradeable is Initializable, IERC165 {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/IAccessControl.sol)

pragma solidity ^0.8.20;

/**
 * @dev External interface of AccessControl declared to support ERC-165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted to signal this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

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

lib/common/src/ERC712ExtendedUpgradeable.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.20 <0.9.0;

import { Initializable } from "../lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol";

import { IERC712 } from "./interfaces/IERC712.sol";
import { IERC712Extended } from "./interfaces/IERC712Extended.sol";

import { SignatureChecker } from "./libs/SignatureChecker.sol";

abstract contract ERC712ExtendedUpgradeableStorageLayout {
    /// @custom:storage-location erc7201:M0.storage.ERC712Extended
    struct ERC712ExtendedStorageStruct {
        uint256 initialChainId;
        bytes32 initialDomainSeparator;
        string name;
    }

    // keccak256(abi.encode(uint256(keccak256("M0.storage.ERC712Extended")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant _ERC712_EXTENDED_STORAGE_LOCATION =
        0x103ce0bed7138196cdb0d79ef04042681b16e7a2c58d74b78443c813042ea100;

    function _getERC712ExtendedStorageLocation() internal pure returns (ERC712ExtendedStorageStruct storage $) {
        assembly {
            $.slot := _ERC712_EXTENDED_STORAGE_LOCATION
        }
    }
}

/**
 * @title  Typed structured data hashing and signing via EIP-712, extended by EIP-5267.
 * @author M0 Labs
 * @dev    An abstract implementation to satisfy EIP-712: https://eips.ethereum.org/EIPS/eip-712
 */
abstract contract ERC712ExtendedUpgradeable is ERC712ExtendedUpgradeableStorageLayout, IERC712Extended, Initializable {
    /* ============ Variables ============ */

    /// @dev keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
    bytes32 internal constant _EIP712_DOMAIN_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;

    /// @dev keccak256("1")
    bytes32 internal constant _EIP712_VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;

    /* ============ Initializer ============ */

    /**
     * @notice Initializes the ERC712ExtendedUpgradeable contract.
     * @param  name_ The name of the contract.
     */
    function __ERC712ExtendedUpgradeable_init(string memory name_) internal onlyInitializing {
        ERC712ExtendedStorageStruct storage $ = _getERC712ExtendedStorageLocation();

        $.name = name_;
        $.initialChainId = block.chainid;
        $.initialDomainSeparator = _getDomainSeparator();
    }

    /* ============ View/Pure Functions ============ */

    /// @inheritdoc IERC712Extended
    function eip712Domain()
        external
        view
        virtual
        returns (
            bytes1 fields_,
            string memory name_,
            string memory version_,
            uint256 chainId_,
            address verifyingContract_,
            bytes32 salt_,
            uint256[] memory extensions_
        )
    {
        return (
            hex"0f", // 01111
            _getERC712ExtendedStorageLocation().name,
            "1",
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }

    /// @inheritdoc IERC712
    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
        ERC712ExtendedStorageStruct storage $ = _getERC712ExtendedStorageLocation();
        return block.chainid == $.initialChainId ? $.initialDomainSeparator : _getDomainSeparator();
    }

    /* ============ Internal View/Pure Functions ============ */

    /**
     * @dev    Computes the EIP-712 domain separator.
     * @return The EIP-712 domain separator.
     */
    function _getDomainSeparator() internal view returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    _EIP712_DOMAIN_HASH,
                    keccak256(bytes(_getERC712ExtendedStorageLocation().name)),
                    _EIP712_VERSION_HASH,
                    block.chainid,
                    address(this)
                )
            );
    }

    /**
     * @dev    Returns the digest to be signed, via EIP-712, given an internal digest (i.e. hash struct).
     * @param  internalDigest_ The internal digest.
     * @return The digest to be signed.
     */
    function _getDigest(bytes32 internalDigest_) internal view returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR(), internalDigest_));
    }

    /**
     * @dev   Revert if the signature is expired.
     * @param expiry_ Timestamp at which the signature expires or max uint256 for no expiry.
     */
    function _revertIfExpired(uint256 expiry_) internal view {
        if (block.timestamp > expiry_) revert SignatureExpired(expiry_, block.timestamp);
    }

    /**
     * @dev   Revert if the signature is invalid.
     * @dev   We first validate if the signature is a valid ECDSA signature and return early if it is the case.
     *        Then, we validate if it is a valid ERC-1271 signature, and return early if it is the case.
     *        If not, we revert with the error from the ECDSA signature validation.
     * @param signer_    The signer of the signature.
     * @param digest_    The digest that was signed.
     * @param signature_ The signature.
     */
    function _revertIfInvalidSignature(address signer_, bytes32 digest_, bytes memory signature_) internal view {
        SignatureChecker.Error error_ = SignatureChecker.validateECDSASignature(signer_, digest_, signature_);

        if (error_ == SignatureChecker.Error.NoError) return;

        if (SignatureChecker.isValidERC1271Signature(signer_, digest_, signature_)) return;

        _revertIfError(error_);
    }

    /**
     * @dev    Returns the signer of a signed digest, via EIP-712, and reverts if the signature is invalid.
     * @param  digest_ The digest that was signed.
     * @param  v_      v of the signature.
     * @param  r_      r of the signature.
     * @param  s_      s of the signature.
     * @return signer_ The signer of the digest.
     */
    function _getSignerAndRevertIfInvalidSignature(
        bytes32 digest_,
        uint8 v_,
        bytes32 r_,
        bytes32 s_
    ) internal pure returns (address signer_) {
        SignatureChecker.Error error_;

        (error_, signer_) = SignatureChecker.recoverECDSASigner(digest_, v_, r_, s_);

        _revertIfError(error_);
    }

    /**
     * @dev   Revert if the signature is invalid.
     * @param signer_ The signer of the signature.
     * @param digest_ The digest that was signed.
     * @param r_      An ECDSA/secp256k1 signature parameter.
     * @param vs_     An ECDSA/secp256k1 short signature parameter.
     */
    function _revertIfInvalidSignature(address signer_, bytes32 digest_, bytes32 r_, bytes32 vs_) internal pure {
        _revertIfError(SignatureChecker.validateECDSASignature(signer_, digest_, r_, vs_));
    }

    /**
     * @dev   Revert if the signature is invalid.
     * @param signer_ The signer of the signature.
     * @param digest_ The digest that was signed.
     * @param v_      v of the signature.
     * @param r_      r of the signature.
     * @param s_      s of the signature.
     */
    function _revertIfInvalidSignature(
        address signer_,
        bytes32 digest_,
        uint8 v_,
        bytes32 r_,
        bytes32 s_
    ) internal pure {
        _revertIfError(SignatureChecker.validateECDSASignature(signer_, digest_, v_, r_, s_));
    }

    /**
     * @dev   Revert if error.
     * @param error_ The SignatureChecker Error enum.
     */
    function _revertIfError(SignatureChecker.Error error_) private pure {
        if (error_ == SignatureChecker.Error.NoError) return;
        if (error_ == SignatureChecker.Error.InvalidSignature) revert InvalidSignature();
        if (error_ == SignatureChecker.Error.InvalidSignatureLength) revert InvalidSignatureLength();
        if (error_ == SignatureChecker.Error.InvalidSignatureS) revert InvalidSignatureS();
        if (error_ == SignatureChecker.Error.InvalidSignatureV) revert InvalidSignatureV();
        if (error_ == SignatureChecker.Error.SignerMismatch) revert SignerMismatch();

        revert InvalidSignature();
    }
}

lib/common/src/interfaces/IERC1271.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.20 <0.9.0;

/**
 * @title  Standard Signature Validation Method for Contracts via EIP-1271.
 * @author M^0 Labs
 * @dev    The interface as defined by EIP-1271: https://eips.ethereum.org/EIPS/eip-1271
 */
interface IERC1271 {
    /**
     * @dev    Returns a specific magic value if the provided signature is valid for the provided digest.
     * @param  digest     Hash of the data purported to have been signed.
     * @param  signature  Signature byte array associated with the digest.
     * @return magicValue Magic value 0x1626ba7e if the signature is valid.
     */
    function isValidSignature(bytes32 digest, bytes memory signature) external view returns (bytes4 magicValue);
}

lib/common/src/interfaces/IERC20.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.20 <0.9.0;

/**
 * @title  ERC20 Token Standard.
 * @author M^0 Labs
 * @dev    The interface as defined by EIP-20: https://eips.ethereum.org/EIPS/eip-20
 */
interface IERC20 {
    /* ============ Events ============ */

    /**
     * @notice Emitted when `spender` has been approved for `amount` of the token balance of `account`.
     * @param  account The address of the account.
     * @param  spender The address of the spender being approved for the allowance.
     * @param  amount  The amount of the allowance being approved.
     */
    event Approval(address indexed account, address indexed spender, uint256 amount);

    /**
     * @notice Emitted when `amount` tokens is transferred from `sender` to `recipient`.
     * @param  sender    The address of the sender who's token balance is decremented.
     * @param  recipient The address of the recipient who's token balance is incremented.
     * @param  amount    The amount of tokens being transferred.
     */
    event Transfer(address indexed sender, address indexed recipient, uint256 amount);

    /* ============ Interactive Functions ============ */

    /**
     * @notice Allows a calling account to approve `spender` to spend up to `amount` of its token balance.
     * @dev    MUST emit an `Approval` event.
     * @param  spender The address of the account being allowed to spend up to the allowed amount.
     * @param  amount  The amount of the allowance being approved.
     * @return Whether or not the approval was successful.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @notice Allows a calling account to transfer `amount` tokens to `recipient`.
     * @param  recipient The address of the recipient who's token balance will be incremented.
     * @param  amount    The amount of tokens being transferred.
     * @return Whether or not the transfer was successful.
     */
    function transfer(address recipient, uint256 amount) external returns (bool);

    /**
     * @notice Allows a calling account to transfer `amount` tokens from `sender`, with allowance, to a `recipient`.
     * @param  sender    The address of the sender who's token balance will be decremented.
     * @param  recipient The address of the recipient who's token balance will be incremented.
     * @param  amount    The amount of tokens being transferred.
     * @return Whether or not the transfer was successful.
     */
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /* ============ View/Pure Functions ============ */

    /**
     * @notice Returns the allowance `spender` is allowed to spend on behalf of `account`.
     * @param  account The address of the account who's token balance `spender` is allowed to spend.
     * @param  spender The address of an account allowed to spend on behalf of `account`.
     * @return The amount `spender` can spend on behalf of `account`.
     */
    function allowance(address account, address spender) external view returns (uint256);

    /**
     * @notice Returns the token balance of `account`.
     * @param  account The address of some account.
     * @return The token balance of `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /// @notice Returns the number of decimals UIs should assume all amounts have.
    function decimals() external view returns (uint8);

    /// @notice Returns the name of the contract/token.
    function name() external view returns (string memory);

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

    /// @notice Returns the current total supply of the token.
    function totalSupply() external view returns (uint256);
}

lib/common/src/interfaces/IERC20Extended.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.20 <0.9.0;

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

/**
 * @title  An ERC20 token extended with EIP-2612 permits for signed approvals (via EIP-712
 *         and with EIP-1271 compatibility), and extended with EIP-3009 transfer with authorization (via EIP-712).
 * @author M^0 Labs
 * @dev    The additional interface as defined by EIP-2612: https://eips.ethereum.org/EIPS/eip-2612
 */
interface IERC20Extended is IERC20, IERC3009 {
    /* ============ Custom Errors ============ */

    /**
     * @notice Revert message when spender's allowance is not sufficient.
     * @param  spender    Address that may be allowed to operate on tokens without being their owner.
     * @param  allowance  Amount of tokens a `spender` is allowed to operate with.
     * @param  needed     Minimum amount required to perform a transfer.
     */
    error InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @notice Revert message emitted when the transferred amount is insufficient.
     * @param  amount Amount transferred.
     */
    error InsufficientAmount(uint256 amount);

    /**
     * @notice Revert message emitted when the recipient of a token is invalid.
     * @param  recipient Address of the invalid recipient.
     */
    error InvalidRecipient(address recipient);

    /* ============ Interactive Functions ============ */

    /**
     * @notice Approves `spender` to spend up to `amount` of the token balance of `owner`, via a signature.
     * @param  owner    The address of the account who's token balance is being approved to be spent by `spender`.
     * @param  spender  The address of an account allowed to spend on behalf of `owner`.
     * @param  value    The amount of the allowance being approved.
     * @param  deadline The last timestamp where the signature is still valid.
     * @param  v        An ECDSA secp256k1 signature parameter (EIP-2612 via EIP-712).
     * @param  r        An ECDSA secp256k1 signature parameter (EIP-2612 via EIP-712).
     * @param  s        An ECDSA secp256k1 signature parameter (EIP-2612 via EIP-712).
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @notice Approves `spender` to spend up to `amount` of the token balance of `owner`, via a signature.
     * @param  owner     The address of the account who's token balance is being approved to be spent by `spender`.
     * @param  spender   The address of an account allowed to spend on behalf of `owner`.
     * @param  value     The amount of the allowance being approved.
     * @param  deadline  The last timestamp where the signature is still valid.
     * @param  signature An arbitrary signature (EIP-712).
     */
    function permit(address owner, address spender, uint256 value, uint256 deadline, bytes memory signature) external;

    /* ============ View/Pure Functions ============ */

    /// @notice Returns the EIP712 typehash used in the encoding of the digest for the permit function.
    function PERMIT_TYPEHASH() external view returns (bytes32);
}

lib/common/src/interfaces/IERC3009.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.20 <0.9.0;

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

/**
 * @title  Transfer via signed authorization following EIP-3009 standard.
 * @author M^0 Labs
 * @dev    The interface as defined by EIP-3009: https://eips.ethereum.org/EIPS/eip-3009
 */
interface IERC3009 is IStatefulERC712 {
    /* ============ Events ============ */

    /**
     * @notice Emitted when an authorization has been canceled.
     * @param  authorizer Authorizer's address.
     * @param  nonce      Nonce of the canceled authorization.
     */
    event AuthorizationCanceled(address indexed authorizer, bytes32 indexed nonce);

    /**
     * @notice Emitted when an authorization has been used.
     * @param  authorizer Authorizer's address.
     * @param  nonce      Nonce of the used authorization.
     */
    event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);

    /* ============ Custom Errors ============ */

    /**
     * @notice Emitted when an authorization has already been used.
     * @param  authorizer Authorizer's address.
     * @param  nonce      Nonce of the used authorization.
     */
    error AuthorizationAlreadyUsed(address authorizer, bytes32 nonce);

    /**
     * @notice Emitted when an authorization is expired.
     * @param  timestamp   Timestamp at which the transaction was submitted.
     * @param  validBefore Timestamp before which the authorization would have been valid.
     */
    error AuthorizationExpired(uint256 timestamp, uint256 validBefore);

    /**
     * @notice Emitted when an authorization is not yet valid.
     * @param  timestamp  Timestamp at which the transaction was submitted.
     * @param  validAfter Timestamp after which the authorization will be valid.
     */
    error AuthorizationNotYetValid(uint256 timestamp, uint256 validAfter);

    /**
     * @notice Emitted when the caller of `receiveWithAuthorization` is not the payee.
     * @param  caller Caller's address.
     * @param  payee  Payee's address.
     */
    error CallerMustBePayee(address caller, address payee);

    /* ============ Interactive Functions ============ */

    /**
     * @notice Execute a transfer with a signed authorization.
     * @param  from        Payer's address (Authorizer).
     * @param  to          Payee's address.
     * @param  value       Amount to be transferred.
     * @param  validAfter  The time after which this is valid (unix time).
     * @param  validBefore The time before which this is valid (unix time).
     * @param  nonce       Unique nonce.
     * @param  signature   A byte array ECDSA/secp256k1 signature (encoded r, s, v).
     */
    function transferWithAuthorization(
        address from,
        address to,
        uint256 value,
        uint256 validAfter,
        uint256 validBefore,
        bytes32 nonce,
        bytes memory signature
    ) external;

    /**
     * @notice Execute a transfer with a signed authorization.
     * @param  from        Payer's address (Authorizer).
     * @param  to          Payee's address.
     * @param  value       Amount to be transferred.
     * @param  validAfter  The time after which this is valid (unix time).
     * @param  validBefore The time before which this is valid (unix time).
     * @param  nonce       Unique nonce.
     * @param  r           An ECDSA/secp256k1 signature parameter.
     * @param  vs          An ECDSA/secp256k1 short signature parameter.
     */
    function transferWithAuthorization(
        address from,
        address to,
        uint256 value,
        uint256 validAfter,
        uint256 validBefore,
        bytes32 nonce,
        bytes32 r,
        bytes32 vs
    ) external;

    /**
     * @notice Execute a transfer with a signed authorization.
     * @param  from        Payer's address (Authorizer).
     * @param  to          Payee's address.
     * @param  value       Amount to be transferred.
     * @param  validAfter  The time after which this is valid (unix time).
     * @param  validBefore The time before which this is valid (unix time).
     * @param  nonce       Unique nonce.
     * @param  v           v of the signature.
     * @param  r           r of the signature.
     * @param  s           s of the signature.
     */
    function transferWithAuthorization(
        address from,
        address to,
        uint256 value,
        uint256 validAfter,
        uint256 validBefore,
        bytes32 nonce,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @notice Receive a transfer with a signed authorization from the payer.
     * @dev    This has an additional check to ensure that the payee's address matches
     *         the caller of this function to prevent front-running attacks.
     *         (See security considerations)
     * @param  from        Payer's address (Authorizer).
     * @param  to          Payee's address.
     * @param  value       Amount to be transferred.
     * @param  validAfter  The time after which this is valid (unix time).
     * @param  validBefore The time before which this is valid (unix time).
     * @param  nonce       Unique nonce.
     * @param  signature   A byte array ECDSA/secp256k1 signature (encoded r, s, v).
     */
    function receiveWithAuthorization(
        address from,
        address to,
        uint256 value,
        uint256 validAfter,
        uint256 validBefore,
        bytes32 nonce,
        bytes memory signature
    ) external;

    /**
     * @notice Receive a transfer with a signed authorization from the payer.
     * @dev    This has an additional check to ensure that the payee's address matches
     *         the caller of this function to prevent front-running attacks.
     *         (See security considerations)
     * @param  from        Payer's address (Authorizer).
     * @param  to          Payee's address.
     * @param  value       Amount to be transferred.
     * @param  validAfter  The time after which this is valid (unix time).
     * @param  validBefore The time before which this is valid (unix time).
     * @param  nonce       Unique nonce.
     * @param  r           An ECDSA/secp256k1 signature parameter.
     * @param  vs          An ECDSA/secp256k1 short signature parameter.
     */
    function receiveWithAuthorization(
        address from,
        address to,
        uint256 value,
        uint256 validAfter,
        uint256 validBefore,
        bytes32 nonce,
        bytes32 r,
        bytes32 vs
    ) external;

    /**
     * @notice Receive a transfer with a signed authorization from the payer.
     * @dev    This has an additional check to ensure that the payee's address matches
     *         the caller of this function to prevent front-running attacks.
     *         (See security considerations)
     * @param  from        Payer's address (Authorizer).
     * @param  to          Payee's address.
     * @param  value       Amount to be transferred.
     * @param  validAfter  The time after which this is valid (unix time).
     * @param  validBefore The time before which this is valid (unix time).
     * @param  nonce       Unique nonce.
     * @param  v           v of the signature.
     * @param  r           r of the signature.
     * @param  s           s of the signature.
     */
    function receiveWithAuthorization(
        address from,
        address to,
        uint256 value,
        uint256 validAfter,
        uint256 validBefore,
        bytes32 nonce,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @notice Attempt to cancel an authorization.
     * @param  authorizer Authorizer's address.
     * @param  nonce      Nonce of the authorization.
     * @param  signature  A byte array ECDSA/secp256k1 signature (encoded r, s, v).
     */
    function cancelAuthorization(address authorizer, bytes32 nonce, bytes memory signature) external;

    /**
     * @notice Attempt to cancel an authorization.
     * @param  authorizer Authorizer's address.
     * @param  nonce      Nonce of the authorization.
     * @param  r          An ECDSA/secp256k1 signature parameter.
     * @param  vs         An ECDSA/secp256k1 short signature parameter.
     */
    function cancelAuthorization(address authorizer, bytes32 nonce, bytes32 r, bytes32 vs) external;

    /**
     * @notice Attempt to cancel an authorization.
     * @param  authorizer Authorizer's address.
     * @param  nonce      Nonce of the authorization.
     * @param  v          v of the signature.
     * @param  r          r of the signature.
     * @param  s          s of the signature.
     */
    function cancelAuthorization(address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external;

    /* ============ View/Pure Functions ============ */

    /**
     * @notice Returns the state of an authorization.
     * @dev    Nonces are randomly generated 32-byte data unique to the authorizer's address
     * @param  authorizer Authorizer's address.
     * @param  nonce      Nonce of the authorization.
     * @return True if the nonce is used.
     */
    function authorizationState(address authorizer, bytes32 nonce) external view returns (bool);

    /// @notice Returns `transferWithAuthorization` typehash.
    function TRANSFER_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32);

    /// @notice Returns `receiveWithAuthorization` typehash.
    function RECEIVE_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32);

    /// @notice Returns `cancelAuthorization` typehash.
    function CANCEL_AUTHORIZATION_TYPEHASH() external view returns (bytes32);
}

lib/common/src/interfaces/IERC712.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.20 <0.9.0;

/**
 * @title  Typed structured data hashing and signing via EIP-712.
 * @author M^0 Labs
 * @dev    The interface as defined by EIP-712: https://eips.ethereum.org/EIPS/eip-712
 */
interface IERC712 {
    /* ============ Custom Errors ============ */

    /// @notice Revert message when an invalid signature is detected.
    error InvalidSignature();

    /// @notice Revert message when a signature with invalid length is detected.
    error InvalidSignatureLength();

    /// @notice Revert message when the S portion of a signature is invalid.
    error InvalidSignatureS();

    /// @notice Revert message when the V portion of a signature is invalid.
    error InvalidSignatureV();

    /**
     * @notice Revert message when a signature is being used beyond its deadline (i.e. expiry).
     * @param  deadline  The last timestamp where the signature is still valid.
     * @param  timestamp The current timestamp.
     */
    error SignatureExpired(uint256 deadline, uint256 timestamp);

    /// @notice Revert message when a recovered signer does not match the account being purported to have signed.
    error SignerMismatch();

    /* ============ View/Pure Functions ============ */

    /// @notice Returns the EIP712 domain separator used in the encoding of a signed digest.
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

lib/common/src/interfaces/IERC712Extended.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.20 <0.9.0;

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

/**
 * @title  EIP-712 extended by EIP-5267.
 * @author M^0 Labs
 * @dev    The additional interface as defined by EIP-5267: https://eips.ethereum.org/EIPS/eip-5267
 */
interface IERC712Extended is IERC712 {
    /* ============ Events ============ */

    /// @notice MAY be emitted to signal that the domain could have changed.
    event EIP712DomainChanged();

    /* ============ View/Pure Functions ============ */

    /// @notice Returns the fields and values that describe the domain separator used by this contract for EIP-712.
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );
}

lib/common/src/interfaces/IStatefulERC712.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.20 <0.9.0;

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

/**
 * @title  Stateful Extension for EIP-712 typed structured data hashing and signing with nonces.
 * @author M^0 Labs
 */
interface IStatefulERC712 is IERC712Extended {
    /* ============ Custom Errors ============ */

    /**
     * @notice Revert message when a signing account's nonce is not the expected current nonce.
     * @param  nonce         The nonce used in the signature.
     * @param  expectedNonce The expected nonce to be used in a signature by the signing account.
     */
    error InvalidAccountNonce(uint256 nonce, uint256 expectedNonce);

    /* ============ View/Pure Functions ============ */

    /**
     * @notice Returns the next nonce to be used in a signature by `account`.
     * @param  account The address of some account.
     * @return nonce   The next nonce to be used in a signature by `account`.
     */
    function nonces(address account) external view returns (uint256 nonce);
}

lib/common/src/libs/SignatureChecker.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.20 <0.9.0;

import { IERC1271 } from "../interfaces/IERC1271.sol";

/**
 * @title  A library to handle ECDSA/secp256k1 and ERC1271 signatures, individually or in arbitrarily in combination.
 * @author M^0 Labs
 */
library SignatureChecker {
    /* ============ Enums ============ */

    /**
     * @notice An enum representing the possible errors that can be emitted during signature validation.
     * @param  NoError                No error occurred during signature validation.
     * @param  InvalidSignature       The signature is invalid.
     * @param  InvalidSignatureLength The signature length is invalid.
     * @param  InvalidSignatureS      The signature parameter S is invalid.
     * @param  InvalidSignatureV      The signature parameter V is invalid.
     * @param  SignerMismatch         The signer does not match the recovered signer.
     */
    enum Error {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV,
        SignerMismatch
    }

    /* ============ Internal View/Pure Functions ============ */

    /**
     * @dev    Returns whether a signature is valid (ECDSA/secp256k1 or ERC1271) for a signer and digest.
     * @dev    Signatures must not be used as unique identifiers since the `ecrecover` EVM opcode
     *         allows for malleable (non-unique) signatures.
     *         See https://github.com/OpenZeppelin/openzeppelin-contracts/security/advisories/GHSA-4h98-2769-gh6h
     * @param  signer    The address of the account purported to have signed.
     * @param  digest    The hash of the data that was signed.
     * @param  signature A byte array signature.
     * @return           Whether the signature is valid or not.
     */
    function isValidSignature(address signer, bytes32 digest, bytes memory signature) internal view returns (bool) {
        return isValidECDSASignature(signer, digest, signature) || isValidERC1271Signature(signer, digest, signature);
    }

    /**
     * @dev    Returns whether an ERC1271 signature is valid for a signer and digest.
     * @param  signer    The address of the account purported to have signed.
     * @param  digest    The hash of the data that was signed.
     * @param  signature A byte array ERC1271 signature.
     * @return           Whether the signature is valid or not.
     */
    function isValidERC1271Signature(
        address signer,
        bytes32 digest,
        bytes memory signature
    ) internal view returns (bool) {
        (bool success_, bytes memory result_) = signer.staticcall(
            abi.encodeCall(IERC1271.isValidSignature, (digest, signature))
        );

        return
            success_ &&
            result_.length >= 32 &&
            abi.decode(result_, (bytes32)) == bytes32(IERC1271.isValidSignature.selector);
    }

    /**
     * @dev    Decodes an ECDSA/secp256k1 signature from a byte array to standard v, r, and s parameters.
     * @param  signature A byte array ECDSA/secp256k1 signature.
     * @return v         An ECDSA/secp256k1 signature parameter.
     * @return r         An ECDSA/secp256k1 signature parameter.
     * @return s         An ECDSA/secp256k1 signature parameter.
     */
    function decodeECDSASignature(bytes memory signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
        // ecrecover takes the signature parameters, and they can be decoded using assembly.
        /// @solidity memory-safe-assembly
        assembly {
            r := mload(add(signature, 0x20))
            s := mload(add(signature, 0x40))
            v := byte(0, mload(add(signature, 0x60)))
        }
    }

    /**
     * @dev    Decodes an ECDSA/secp256k1 short signature as defined by EIP2098
     *         from a byte array to standard v, r, and s parameters.
     * @param  signature A byte array ECDSA/secp256k1 short signature.
     * @return r         An ECDSA/secp256k1 signature parameter.
     * @return vs        An ECDSA/secp256k1 short signature parameter.
     */
    function decodeShortECDSASignature(bytes memory signature) internal pure returns (bytes32 r, bytes32 vs) {
        // ecrecover takes the signature parameters, and they can be decoded using assembly.
        /// @solidity memory-safe-assembly
        assembly {
            r := mload(add(signature, 0x20))
            vs := mload(add(signature, 0x40))
        }
    }

    /**
     * @dev    Returns whether an ECDSA/secp256k1 signature is valid for a signer and digest.
     * @param  signer    The address of the account purported to have signed.
     * @param  digest    The hash of the data that was signed.
     * @param  signature A byte array ECDSA/secp256k1 signature (encoded r, s, v).
     * @return           Whether the signature is valid or not.
     */
    function isValidECDSASignature(
        address signer,
        bytes32 digest,
        bytes memory signature
    ) internal pure returns (bool) {
        if (signature.length == 64) {
            (bytes32 r, bytes32 vs) = decodeShortECDSASignature(signature);
            return isValidECDSASignature(signer, digest, r, vs);
        }

        return validateECDSASignature(signer, digest, signature) == Error.NoError;
    }

    /**
     * @dev    Returns whether an ECDSA/secp256k1 short signature is valid for a signer and digest.
     * @param  signer The address of the account purported to have signed.
     * @param  digest The hash of the data that was signed.
     * @param  r      An ECDSA/secp256k1 signature parameter.
     * @param  vs     An ECDSA/secp256k1 short signature parameter.
     * @return        Whether the signature is valid or not.
     */
    function isValidECDSASignature(address signer, bytes32 digest, bytes32 r, bytes32 vs) internal pure returns (bool) {
        return validateECDSASignature(signer, digest, r, vs) == Error.NoError;
    }

    /**
     * @dev    Returns the signer of an ECDSA/secp256k1 signature for some digest.
     * @param  digest    The hash of the data that was signed.
     * @param  signature A byte array ECDSA/secp256k1 signature.
     * @return           An error, if any, that occurred during the signer recovery.
     * @return           The address of the account recovered form the signature (0 if error).
     */
    function recoverECDSASigner(bytes32 digest, bytes memory signature) internal pure returns (Error, address) {
        if (signature.length != 65) return (Error.InvalidSignatureLength, address(0));

        (uint8 v, bytes32 r, bytes32 s) = decodeECDSASignature(signature);

        return recoverECDSASigner(digest, v, r, s);
    }

    /**
     * @dev    Returns the signer of an ECDSA/secp256k1 short signature for some digest.
     * @dev    See https://eips.ethereum.org/EIPS/eip-2098
     * @param  digest The hash of the data that was signed.
     * @param  r      An ECDSA/secp256k1 signature parameter.
     * @param  vs     An ECDSA/secp256k1 short signature parameter.
     * @return        An error, if any, that occurred during the signer recovery.
     * @return        The address of the account recovered form the signature (0 if error).
     */
    function recoverECDSASigner(bytes32 digest, bytes32 r, bytes32 vs) internal pure returns (Error, address) {
        unchecked {
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            return recoverECDSASigner(digest, v, r, s);
        }
    }

    /**
     * @dev    Returns the signer of an ECDSA/secp256k1 signature for some digest.
     * @param  digest The hash of the data that was signed.
     * @param  v      An ECDSA/secp256k1 signature parameter.
     * @param  r      An ECDSA/secp256k1 signature parameter.
     * @param  s      An ECDSA/secp256k1 signature parameter.
     * @return        An error, if any, that occurred during the signer recovery.
     * @return signer The address of the account recovered form the signature (0 if error).
     */
    function recoverECDSASigner(
        bytes32 digest,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (Error, address signer) {
        // Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}.
        if (uint256(s) > uint256(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0))
            return (Error.InvalidSignatureS, address(0));

        if (v != 27 && v != 28) return (Error.InvalidSignatureV, address(0));

        signer = ecrecover(digest, v, r, s);

        return (signer == address(0)) ? (Error.InvalidSignature, address(0)) : (Error.NoError, signer);
    }

    /**
     * @dev    Returns an error, if any, in validating an ECDSA/secp256k1 signature for a signer and digest.
     * @param  signer    The address of the account purported to have signed.
     * @param  digest    The hash of the data that was signed.
     * @param  signature A byte array ERC1271 signature.
     * @return           An error, if any, that occurred during the signer recovery.
     */
    function validateECDSASignature(
        address signer,
        bytes32 digest,
        bytes memory signature
    ) internal pure returns (Error) {
        (Error recoverError, address recoveredSigner) = recoverECDSASigner(digest, signature);

        return (recoverError == Error.NoError) ? validateRecoveredSigner(signer, recoveredSigner) : recoverError;
    }

    /**
     * @dev    Returns an error, if any, in validating an ECDSA/secp256k1 short signature for a signer and digest.
     * @param  signer The address of the account purported to have signed.
     * @param  digest The hash of the data that was signed.
     * @param  r      An ECDSA/secp256k1 signature parameter.
     * @param  vs     An ECDSA/secp256k1 short signature parameter.
     * @return        An error, if any, that occurred during the signer recovery.
     */
    function validateECDSASignature(
        address signer,
        bytes32 digest,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (Error) {
        (Error recoverError, address recoveredSigner) = recoverECDSASigner(digest, r, vs);

        return (recoverError == Error.NoError) ? validateRecoveredSigner(signer, recoveredSigner) : recoverError;
    }

    /**
     * @dev    Returns an error, if any, in validating an ECDSA/secp256k1 signature for a signer and digest.
     * @param  signer The address of the account purported to have signed.
     * @param  digest The hash of the data that was signed.
     * @param  v      An ECDSA/secp256k1 signature parameter.
     * @param  r      An ECDSA/secp256k1 signature parameter.
     * @param  s      An ECDSA/secp256k1 signature parameter.
     * @return        An error, if any, that occurred during the signer recovery.
     */
    function validateECDSASignature(
        address signer,
        bytes32 digest,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (Error) {
        (Error recoverError, address recoveredSigner) = recoverECDSASigner(digest, v, r, s);

        return (recoverError == Error.NoError) ? validateRecoveredSigner(signer, recoveredSigner) : recoverError;
    }

    /**
     * @dev    Returns an error if `signer` is not `recoveredSigner`.
     * @param  signer          The address of the some signer.
     * @param  recoveredSigner The address of the some recoveredSigner.
     * @return                 An error if `signer` is not `recoveredSigner`.
     */
    function validateRecoveredSigner(address signer, address recoveredSigner) internal pure returns (Error) {
        return (signer == recoveredSigner) ? Error.NoError : Error.SignerMismatch;
    }
}

lib/common/src/libs/TypeConverter.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.20 <0.9.0;

/// @title  TypeConverter
/// @author M0 Labs
/// @notice Utilities for converting between different data types.
library TypeConverter {
    /// @notice Thrown when a uint256 value exceeds the max uint64 value.
    error Uint64Overflow();
    /// @notice Thrown when a uint256 value exceeds the max uint128 value.
    error Uint128Overflow();

    /// @notice Thrown when a bytes32 value doesn't represent a valid Ethereum address.
    error InvalidAddress(bytes32 value);

    /// @notice Converts a uint256 to uint64, reverting if the value overflows.
    /// @param  value The uint256 value to convert.
    /// @return The uint64 representation of the value.
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) revert Uint64Overflow();
        return uint64(value);
    }

    /// @notice Converts a uint256 to uint128, reverting if the value overflows.
    /// @param  value The uint256 value to convert.
    /// @return The uint128 representation of the value.
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) revert Uint128Overflow();
        return uint128(value);
    }

    /// @notice Convert an Ethereum address to bytes32.
    /// @dev    Pads the 20-byte address to 32 bytes by converting to uint160, then uint256, then bytes32.
    /// @param  addressValue The address to convert.
    /// @return The bytes32 representation of the address.
    function toBytes32(address addressValue) internal pure returns (bytes32) {
        return bytes32(uint256(uint160(addressValue)));
    }

    /// @notice Convert bytes32 to an Ethereum address.
    /// @dev    Truncates the 32-byte value to 20 bytes by converting to uint256, then uint160, then address.
    /// @param  bytes32Value The bytes32 value to convert.
    /// @return The address representation of the bytes32 value.
    function toAddress(bytes32 bytes32Value) internal pure returns (address) {
        if (!isValidAddress(bytes32Value)) revert InvalidAddress(bytes32Value);
        return address(uint160(uint256(bytes32Value)));
    }

    /// @notice Check if a bytes32 value represents a valid Ethereum address.
    /// @dev    An Ethereum address must have the top 12 bytes as zero.
    /// @param  bytes32Value The bytes32 value to check.
    /// @return True if the bytes32 value can be safely converted to an Ethereum address.
    function isValidAddress(bytes32 bytes32Value) internal pure returns (bool) {
        // The top 12 bytes must be zero for a valid Ethereum address
        return uint256(bytes32Value) >> 160 == 0;
    }
}

lib/common/src/libs/UIntMath.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.20 <0.9.0;

/**
 * @title  Library to perform safe math operations on uint types
 * @author M^0 Labs
 */
library UIntMath {
    /* ============ Custom Errors ============ */

    /// @notice Emitted when a passed value is greater than the maximum value of uint16.
    error InvalidUInt16();

    /// @notice Emitted when a passed value is greater than the maximum value of uint32.
    error InvalidUInt32();

    /// @notice Emitted when a passed value is greater than the maximum value of uint40.
    error InvalidUInt40();

    /// @notice Emitted when a passed value is greater than the maximum value of uint48.
    error InvalidUInt48();

    /// @notice Emitted when a passed value is greater than the maximum value of uint112.
    error InvalidUInt112();

    /// @notice Emitted when a passed value is greater than the maximum value of uint128.
    error InvalidUInt128();

    /// @notice Emitted when a passed value is greater than the maximum value of uint240.
    error InvalidUInt240();

    /* ============ Internal View/Pure Functions ============ */

    /**
     * @notice Casts a uint256 value to a uint16, ensuring that it is less than or equal to the maximum uint16 value.
     * @param  n The value to cast.
     * @return The value casted to uint16.
     */
    function safe16(uint256 n) internal pure returns (uint16) {
        if (n > type(uint16).max) revert InvalidUInt16();
        return uint16(n);
    }

    /**
     * @notice Casts a uint256 value to a uint32, ensuring that it is less than or equal to the maximum uint32 value.
     * @param  n The value to cast.
     * @return The value casted to uint32.
     */
    function safe32(uint256 n) internal pure returns (uint32) {
        if (n > type(uint32).max) revert InvalidUInt32();
        return uint32(n);
    }

    /**
     * @notice Casts a uint256 value to a uint40, ensuring that it is less than or equal to the maximum uint40 value.
     * @param  n The value to cast.
     * @return The value casted to uint40.
     */
    function safe40(uint256 n) internal pure returns (uint40) {
        if (n > type(uint40).max) revert InvalidUInt40();
        return uint40(n);
    }

    /**
     * @notice Casts a uint256 value to a uint48, ensuring that it is less than or equal to the maximum uint48 value.
     * @param  n The value to cast.
     * @return The value casted to uint48.
     */
    function safe48(uint256 n) internal pure returns (uint48) {
        if (n > type(uint48).max) revert InvalidUInt48();
        return uint48(n);
    }

    /**
     * @notice Casts a uint256 value to a uint112, ensuring that it is less than or equal to the maximum uint112 value.
     * @param  n The value to cast.
     * @return The value casted to uint112.
     */
    function safe112(uint256 n) internal pure returns (uint112) {
        if (n > type(uint112).max) revert InvalidUInt112();
        return uint112(n);
    }

    /**
     * @notice Casts a uint256 value to a uint128, ensuring that it is less than or equal to the maximum uint128 value.
     * @param  n The value to cast.
     * @return The value casted to uint128.
     */
    function safe128(uint256 n) internal pure returns (uint128) {
        if (n > type(uint128).max) revert InvalidUInt128();
        return uint128(n);
    }

    /**
     * @notice Casts a uint256 value to a uint240, ensuring that it is less than or equal to the maximum uint240 value.
     * @param  n The value to cast.
     * @return The value casted to uint240.
     */
    function safe240(uint256 n) internal pure returns (uint240) {
        if (n > type(uint240).max) revert InvalidUInt240();
        return uint240(n);
    }

    /**
     * @notice Limits a uint256 value to the maximum uint32 value.
     * @param  n The value to bound.
     * @return The value limited to within uint32 bounds.
     */
    function bound32(uint256 n) internal pure returns (uint32) {
        return uint32(min256(n, uint256(type(uint32).max)));
    }

    /**
     * @notice Limits a uint256 value to the maximum uint112 value.
     * @param  n The value to bound.
     * @return The value limited to within uint112 bounds.
     */
    function bound112(uint256 n) internal pure returns (uint112) {
        return uint112(min256(n, uint256(type(uint112).max)));
    }

    /**
     * @notice Limits a uint256 value to the maximum uint128 value.
     * @param  n The value to bound.
     * @return The value limited to within uint128 bounds.
     */
    function bound128(uint256 n) internal pure returns (uint128) {
        return uint128(min256(n, uint256(type(uint128).max)));
    }

    /**
     * @notice Limits a uint256 value to the maximum uint240 value.
     * @param  n The value to bound.
     * @return The value limited to within uint240 bounds.
     */
    function bound240(uint256 n) internal pure returns (uint240) {
        return uint240(min256(n, uint256(type(uint240).max)));
    }

    /**
     * @notice Compares two uint32 values and returns the larger one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The larger value.
     */
    function max32(uint32 a, uint32 b) internal pure returns (uint32) {
        return a > b ? a : b;
    }

    /**
     * @notice Compares two uint40 values and returns the larger one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The larger value.
     */
    function max40(uint40 a, uint40 b) internal pure returns (uint40) {
        return a > b ? a : b;
    }

    /**
     * @notice Compares two uint128 values and returns the larger one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The larger value.
     */
    function max128(uint128 a, uint128 b) internal pure returns (uint128) {
        return a > b ? a : b;
    }

    /**
     * @notice Compares two uint240 values and returns the larger one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The larger value.
     */
    function max240(uint240 a, uint240 b) internal pure returns (uint240) {
        return a > b ? a : b;
    }

    /**
     * @notice Compares two uint32 values and returns the lesser one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The lesser value.
     */
    function min32(uint32 a, uint32 b) internal pure returns (uint32) {
        return a < b ? a : b;
    }

    /**
     * @notice Compares two uint40 values and returns the lesser one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The lesser value.
     */
    function min40(uint40 a, uint40 b) internal pure returns (uint40) {
        return a < b ? a : b;
    }

    /**
     * @notice Compares two uint240 values and returns the lesser one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The lesser value.
     */
    function min240(uint240 a, uint240 b) internal pure returns (uint240) {
        return a < b ? a : b;
    }

    /**
     * @notice Compares two uint112 values and returns the lesser one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The lesser value.
     */
    function min112(uint112 a, uint112 b) internal pure returns (uint112) {
        return a < b ? a : b;
    }

    /**
     * @notice Compares two uint256 values and returns the lesser one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The lesser value.
     */
    function min256(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }
}

src/interfaces/IOrderBook.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;

interface IOrderBook {
    /* ========== Events ========== */

    /**
     * @notice Emitted when a new order is opened
     * @dev This event is emitted on the origin chain
     * @param orderId The ID of the order
     * @param funder The address that provided the input funds for the order
     * @param sender The address that owns the order on the origin (this) chain
     * @param tokenIn The address of the input token on the origin (this) chain
     * @param amountIn The amount of input token provided
     * @param destChainId The internal chain ID where the order will be filled
     * @param tokenOut The address of the output token on the destination chain
     * @param amountOut The amount of output token expected
     * @param solver The address of the solver that will fill the order, or zero address if any solver can fill
     * @param fillDeadline Timestamp by which the order must be filled on the destination chain
     */
    event OrderOpened(
        bytes32 orderId,
        address funder,
        address indexed sender,
        address tokenIn,
        uint128 amountIn,
        uint32 indexed destChainId,
        bytes32 tokenOut,
        uint128 amountOut,
        bytes32 indexed solver,
        uint32 fillDeadline
    );

    /**
     * @notice Emitted when an order is filled
     * @dev This event is emitted on the destination chain
     * @param orderId The ID of the order being filled
     * @param solver The address of the solver that filled the order
     * @param amountOutFilled The amount of output token that was filled
     * @param amountInToRelease The amount of input token they will receive on the origin chain
     * @param messageId The ID of the crosschain message reporting this fill back to the origin chain (zero for same-chain fills)
     */
    event OrderFilled(
        bytes32 indexed orderId,
        address indexed solver,
        uint128 amountInToRelease,
        uint128 amountOutFilled,
        bytes32 indexed messageId
    );

    /**
     * @notice Emitted when a refund is claimed for an order
     * @dev This event is emitted on the origin chain
     * @param orderId The ID of the order being refunded
     * @param sender The address that the refund is sent to
     * @param amountInRefunded The amount of input token that was refunded
     */
    event RefundClaimed(bytes32 indexed orderId, address indexed sender, uint128 amountInRefunded);

    /**
     * @notice Emitted when an order is completed (fully filled)
     * @param orderId The ID of the completed order
     */
    event OrderCompleted(bytes32 orderId);

    /**
     * @notice Emitted when an order is cancelled
     * @dev This event is emitted on the destination chain
     * @param orderId The ID of the cancelled order
     * @param messageId The ID of the crosschain message reporting this cancellation back to the origin chain (zero for same-chain cancels)
     */
    event OrderCancelled(bytes32 indexed orderId, bytes32 indexed messageId);

    /**
     * @notice Emitted when the support for a destination chain is updated
     * @dev This event is emitted on the origin chain
     * @param destChainId The internal chain ID of the destination chain
     * @param isSupported Whether orders can be created with this chain as the destination
     */
    event DestinationSupportUpdated(uint32 indexed destChainId, bool isSupported);

    /**
     * @notice Emitted when a fill is reported from a destination chain
     * @dev This event is emitted on the origin chain
     * @param orderId The ID of the order that was filled
     * @param originRecipient The address on the origin chain that received released funds
     * @param amountInToRelease The amount of input token released to the filler on the origin chain
     * @param amountOutFilled The amount of output token that was filled on the destination chain
     */
    event FillReported(
        bytes32 indexed orderId,
        address indexed originRecipient,
        uint128 amountInToRelease,
        uint128 amountOutFilled
    );

    /**
     * @notice Emitted when a cancellation is reported from a destination chain
     * @dev This event is emitted on the origin chain
     * @param orderId The ID of the cancelled order
     */
    event CancelReported(bytes32 indexed orderId);

    /* ========== Errors ========== */
    error AmountInZero();
    error AmountOutZero();
    error FillAmountZero();
    error InvalidDeadline();
    error InvalidDestinationChain();
    error InvalidMsgValue();
    error InvalidOrderStatus();
    error InvalidOrderVersion();
    error InvalidRecipient();
    error InvalidSolver();
    error InvalidReport();
    error InvalidTimestamp();
    error InvalidReportSource();
    error NotAuthorized();
    error OrderExpired();
    error OrderAlreadyExists();
    error OrderIdMismatch();
    error SameTokenOrder();
    error ZeroAdmin();
    error ZeroPauser();
    error ZeroPortal();
    error ZeroSender();

    /* ========== Structs and Enums ========== */

    /**
     * @notice Parameters required to open an order onchain
     * @dev Addresses on the destination chain are stored as bytes32 to support non-EVM chains as destinations
     * @param destChainId Destination chain ID where the order is to be filled
     * @param fillDeadline Timestamp by which the order must be filled on the destination chain
     * @param tokenIn Address of the input token on the origin (this) chain
     * @param tokenOut Address of the output token on the destination chain
     * @param amountIn Amount of input token provided
     * @param amountOut Amount of output token expected
     * @param recipient Address to receive the funds on the destination chain
     * @param solver Address of the solver that will fill the order, or zero address if any solver can fill
     * @param sender Address that will own the order (for cancellation rights and refunds). Tokens are pulled from msg.sender.
     */
    struct OrderParams {
        uint32 destChainId;
        uint32 fillDeadline;
        address tokenIn;
        bytes32 tokenOut;
        uint128 amountIn;
        uint128 amountOut;
        bytes32 recipient;
        bytes32 solver;
        address sender;
    }

    /**
     * @notice Possible order statuses
     */
    enum OrderStatus {
        DoesNotExist,
        Created,
        Cancelled,
        Completed
    }

    /**
     * @notice Complete data about an order originated on this chain
     * @dev Addresses on the destination chain are stored as bytes32 to support non-EVM chains
     * @param status Current status of the order
     * @param version Version of the contract when the order was created
     * @param sender Address that owns the order on the origin chain for cancellation rights and refunds
     * @param nonce A counter tied to the sender to allow unique orders
     * @param destChainId Destination chain ID where the order is to be filled
     * @param createdAt Timestamp when the order was created
     * @param fillDeadline Timestamp by which the order must be filled on the destination chain
     * @param tokenIn Address of the input token on this chain
     * @param tokenOut Address of the output token on the destination chain
     * @param amountIn Amount of input token provided
     * @param amountOut Amount of output token expected
     * @param recipient Address to receive the funds on the destination chain
     * @param solver Address of the solver that will fill the order, or zero address if any approved solver can fill
     */
    struct Order {
        OrderStatus status; // slot 1: 1 +
        uint16 version; //             2 +
        address sender; //             20 +
        uint64 nonce; //               8 = 31 bytes
        uint32 destChainId; // slot 2: 4 +
        uint32 createdAt; //           4 +
        uint32 fillDeadline; //        4 +
        address tokenIn; //            20 = 32 bytes
        bytes32 tokenOut; //   slot 3
        uint128 amountIn; //   slot 4: 16 +
        uint128 amountOut; //          16 = 32 bytes
        bytes32 recipient; //  slot 5
        bytes32 solver; //     slot 6
    }

    /**
     * @notice Data required to identify and fill an order on a destination chain
     * @dev This struct is used to compute a unique order ID and to provide all necessary
     *      information to fill the order on the destination chain
     *      The order ID is computed as the keccak256 hash of the packed-encoding of this struct
     * @param version Version of the contract when the order was created
     * @param sender Address that owns the order on the origin chain for cancellation rights and refunds
     * @param nonce A counter tied to the sender to allow unique orders
     * @param originChainId internal chain ID where the order was created
     * @param destChainId Destination chain ID where the order is to be filled
     * @param createdAt Timestamp when the order was created
     * @param fillDeadline Timestamp by which the order must be filled on the destination chain
     * @param tokenIn Address of the input token on the origin chain
     * @param tokenOut Address of the output token on the destination chain
     * @param amountIn Amount of input token provided
     * @param amountOut Amount of output token expected on the destination chain
     * @param recipient Address to receive the funds on the destination chain
     * @param solver Address of the solver that will fill the order, or zero address if any approved solver can fill
     */
    struct OrderData {
        uint16 version;
        bytes32 sender;
        uint64 nonce;
        uint32 originChainId;
        uint32 destChainId;
        uint64 createdAt;
        uint64 fillDeadline;
        bytes32 tokenIn;
        bytes32 tokenOut;
        uint128 amountIn;
        uint128 amountOut;
        bytes32 recipient;
        bytes32 solver;
    }

    /**
     * @notice Data reported from a destination chain back to the origin chain about a fill
     * @dev This struct is sent by the portal contract to report fills that occurred
     *      on the destination chain back to the origin chain for processing
     * @param orderId The ID of the order that a fill is being reported for
     * @param amountInToRelease The amount of input token to release to the filler on the origin chain
     * @param amountOutFilled The amount of output token that was filled on the destination chain
     * @param originRecipient The address on the origin chain that should receive released funds
     * @param tokenIn The address of the input token on the origin chain
     *                This is included for non-EVM chains to provide a way to resolve the token
     */
    struct FillReport {
        bytes32 orderId;
        uint128 amountInToRelease;
        uint128 amountOutFilled;
        bytes32 originRecipient;
        bytes32 tokenIn;
    }

    /**
     * @notice Data reported from a destination chain back to the origin chain about a cancelled order
     * @dev This struct is sent by the portal contract to report order cancellations and refunds
     *      that occurred on the destination chain back to the origin chain for processing
     * @param orderId The ID of the order that a cancellation is being reported for
     * @param orderSender The address on the origin chain that created the order
     * @param tokenIn The address of the input token on the origin chain
     * @param amountInToRefund The amount of input token to refund to the order sender on the origin chain
     * The last two are included for non-EVM chains to provide a way to resolve the sender and token
     */
    struct CancelReport {
        bytes32 orderId;
        bytes32 orderSender;
        bytes32 tokenIn;
        uint128 amountInToRefund;
    }

    /**
     * @notice Parameters supplied by the filler of an order
     * @dev This struct contains parameters that are specific to the filler
     *      and are not part of the original order data
     * @param amountOutToFill The amount of output token the filler is providing to fill
     * @param originRecipient The address on the origin chain that should receive released funds
     * @param refundAddress (optional) The address to send any bridge refund costs to.
     *                       See PortalV2 for more info. If not provided (i.e. zero address),
     *                       it defaults to msg.sender. Not required for same chain fills.
     */
    struct FillParams {
        uint128 amountOutToFill;
        bytes32 originRecipient;
        bytes32 refundAddress;
    }

    /**
     * @notice Data structure to track filled amounts for an order on the origin and destination chains
     * @param amountInRefunded Amount of input token refunded to the order sender
     * @param amountInReleased Amount of input token released to solver(s)
     * @param amountOutFilled Amount of output token filled by solver(s)
     */
    struct FilledAmounts {
        uint128 amountInRefunded;
        uint128 amountInReleased;
        uint128 amountOutFilled;
    }

    /* ========== Creating Orders ========== */

    /**
     * @notice Opens an order
     * @dev Must be called by the user providing the input funds
     * @param orderParams_ order creation parameters (see OrderParams definition)
     * @return orderId_ The unique ID of the opened order
     */
    function openOrder(OrderParams calldata orderParams_) external returns (bytes32 orderId_);

    /**
     * @notice Opens an order with an EIP-2612 permit signature for token approval
     * @dev Must be called by the user providing the input funds
     * @param orderParams_ order creation parameters (see OrderParams definition)
     * @param deadline_ deadline for the permit signature
     * @param v_ v parameter of the permit signature
     * @param r_ r parameter of the permit signature
     * @param s_ s parameter of the permit signature
     * @return orderId_ The unique ID of the opened order
     */
    function openOrderWithPermit(
        OrderParams calldata orderParams_,
        uint256 deadline_,
        uint8 v_,
        bytes32 r_,
        bytes32 s_
    ) external returns (bytes32 orderId_);

    /**
     * @notice Opens an order with an EIP-2612 permit signature for token approval
     * @dev Must be called by the user providing the input funds
     * @param orderParams_ order creation parameters (see OrderParams definition)
     * @param deadline_ deadline for the permit signature
     * @param permitSignature_ packed encoding of the permit signature
     * @return orderId_ The unique ID of the opened order
     */
    function openOrderWithPermit(
        OrderParams calldata orderParams_,
        uint256 deadline_,
        bytes memory permitSignature_
    ) external returns (bytes32 orderId_);

    /* ========== Refunding Orders ========== */

    /**
     * @notice Cancel an order
     * @dev Must be called by the order's recipient (or sender if same chain order) before fill deadline
     * @dev Can be called by anyone after the fill deadline (permissionless refunds)
     * @param orderId_ - ID of the order to cancel
     * @param orderData_ OrderData payload with all order information required to identify an order to be cancelled
     * @return messageId_ The ID of the crosschain message reporting this cancellation back to the origin chain (zero for same-chain cancels)
     * @dev   The payable amount is forwarded to the underlying portal contract to send crosschain messages.
     *        This should be 0 for same chain cancels. For crosschain cancels, see the Portal V2 contract for guidance on
     *        getting a quote for the required fee
     */
    function cancelOrder(bytes32 orderId_, OrderData calldata orderData_) external payable returns (bytes32 messageId_);

    /**
     * @notice Cancel an order with additional message data required by some crosschain messages
     * @dev Must be called by the order's recipient (or sender if same chain order) before fill deadline
     * @dev Can be called by anyone after the fill deadline (permissionless refunds)
     * @param orderId_ ID of the order to cancel
     * @param orderData_ OrderData payload with all order information required to identify an order to be cancelled
     * @param bridgeAdapterArgs_ Additional data required by some crosschain message protocols (see PortalV2 for more info)
     * @return messageId_ The ID of the crosschain message reporting this cancellation back to the origin chain (zero for same-chain cancels)
     * @dev   The payable amount is forwarded to the underlying portal contract to send crosschain messages.
     *        This should be 0 for same chain cancels. For crosschain cancels, see the Portal V2 contract for guidance on
     *        getting a quote for the required fee
     */
    function cancelOrder(
        bytes32 orderId_,
        OrderData calldata orderData_,
        bytes calldata bridgeAdapterArgs_
    ) external payable returns (bytes32 messageId_);

    /**
     * @notice Cancel an order with additional message data required by some crosschain messages
     * @dev Must be called by the order's recipient (or sender if same chain order) before fill deadline
     * @dev Can be called by anyone after the fill deadline (permissionless refunds)
     * @param orderId_ ID of the order to cancel
     * @param orderData_ OrderData payload with all order information required to identify an order to be cancelled
     * @param bridgeAdapter_ Address of the bridge adapter to use for crosschain messages (must be supported by Portal V2)
     * @param bridgeAdapterArgs_ Additional data required by some crosschain message protocols (see PortalV2 for more info)
     * @return messageId_ The ID of the crosschain message reporting this cancellation back to the origin chain (zero for same-chain cancels)
     * @dev   The payable amount is forwarded to the underlying portal contract to send crosschain messages.
     *        This should be 0 for same chain cancels. For crosschain cancels, see the Portal V2 contract for guidance on
     *        getting a quote for the required fee
     */
    function cancelOrder(
        bytes32 orderId_,
        OrderData calldata orderData_,
        address bridgeAdapter_,
        bytes calldata bridgeAdapterArgs_
    ) external payable returns (bytes32 messageId_);

    /**
     * @notice Cancel an order on behalf of the recipient
     * @dev Can be called by anyone with a valid signature from the order's recipient
     * @param orderId_ ID of the order to cancel
     * @param orderData_ OrderData payload with all order information required to identify an order to be cancelled
     * @param signature_ Order sender's signature of the EIP-712 payload (see getCancelOrderDigest)
     * @return messageId_ The ID of the crosschain message reporting this cancellation back to the origin chain (zero for same-chain cancels)
     * @dev   The payable amount is forwarded to the underlying portal contract to send crosschain messages.
     *        This should be 0 for same chain cancels. For crosschain cancels, see the Portal V2 contract for guidance on
     *        getting a quote for the required fee
     */
    function cancelOrderFor(
        bytes32 orderId_,
        OrderData calldata orderData_,
        bytes calldata signature_
    ) external payable returns (bytes32 messageId_);

    /**
     * @notice Cancel an order on behalf of the recipient with additional message data required by some crosschain messages
     * @dev Can be called by anyone with a valid signature from the order's recipient
     * @param orderId_ ID of the order to cancel
     * @param orderData_ OrderData payload with all order information required to identify an order to be cancelled
     * @param signature_ Order sender's signature of the EIP-712 payload (see getCancelOrderDigest)
     * @param bridgeAdapterArgs_ Additional data required by some crosschain message protocols (see PortalV2 for more info)
     * @return messageId_ The ID of the crosschain message reporting this cancellation back to the origin chain (zero for same-chain cancels)
     * @dev   The payable amount is forwarded to the underlying portal contract to send crosschain messages.
     *        This should be 0 for same chain cancels. For crosschain cancels, see the Portal V2 contract for guidance on
     *        getting a quote for the required fee
     */
    function cancelOrderFor(
        bytes32 orderId_,
        OrderData calldata orderData_,
        bytes calldata signature_,
        bytes calldata bridgeAdapterArgs_
    ) external payable returns (bytes32 messageId_);

    /**
     * @notice Cancel an order on behalf of the recipient with additional message data required by some crosschain messages
     * @dev Can be called by anyone with a valid signature from the order's recipient
     * @param orderId_ ID of the order to cancel
     * @param orderData_ OrderData payload with all order information required to identify an order to be cancelled
     * @param signature_ Order sender's signature of the EIP-712 payload (see getCancelOrderDigest)
     * @param bridgeAdapter_ Address of the bridge adapter to use for crosschain messages (must be supported by Portal V2)
     * @param bridgeAdapterArgs_ Additional data required by some crosschain message protocols (see PortalV2 for more info)
     * @return messageId_ The ID of the crosschain message reporting this cancellation back to the origin chain (zero for same-chain cancels)
     * @dev   The payable amount is forwarded to the underlying portal contract to send crosschain messages.
     *        This should be 0 for same chain cancels. For crosschain cancels, see the Portal V2 contract for guidance on
     *        getting a quote for the required fee
     */
    function cancelOrderFor(
        bytes32 orderId_,
        OrderData calldata orderData_,
        bytes calldata signature_,
        address bridgeAdapter_,
        bytes calldata bridgeAdapterArgs_
    ) external payable returns (bytes32 messageId_);

    /* ========== Filling Orders ========== */

    /**
     * @notice Fill an order on this chain
     * @param orderId_ ID of the order to fill
     * @param orderData_ OrderData payload with all order information required to identify an order to be filled
     * @param fillerParams_ Parameters supplied by the solver of the order
     * @return messageId_ The ID of the crosschain message reporting this fill back to the origin chain (zero for same-chain fills)
     * @dev   The orderData is packed and hashed to verify the order ID as a safeguard for solvers
     * @dev   The payable amount is forwarded to the underlying portal contract to send crosschain messages.
     *        This should be 0 for same chain fills. For crosschain fills, see the Portal V2 contract for guidance on
     *        getting a quote for the required fee
     */
    function fillOrder(
        bytes32 orderId_,
        OrderData calldata orderData_,
        FillParams calldata fillerParams_
    ) external payable returns (bytes32 messageId_);

    /**
     * @notice Fill an order on this chain with additional message data required by some crosschain messages
     * @param orderId_ ID of the order to fill
     * @param orderData_ OrderData payload with all order information required to identify an order to be filled
     * @param fillerParams_ Parameters supplied by the solver of the order
     * @param bridgeAdapterArgs_ Additional data required by some crosschain message protocols (see PortalV2 for more info)
     * @return messageId_ The ID of the crosschain message reporting this fill back to the origin chain (zero for same-chain fills)
     * @dev   The orderData is packed and hashed to verify the order ID as a safeguard for solvers
     * @dev   The payable amount is forwarded to the underlying portal contract to send crosschain messages.
     *        This should be 0 for same chain fills. For crosschain fills, see the Portal V2 contract for guidance on
     *        getting a quote for the required fee
     */
    function fillOrder(
        bytes32 orderId_,
        OrderData calldata orderData_,
        FillParams calldata fillerParams_,
        bytes calldata bridgeAdapterArgs_
    ) external payable returns (bytes32 messageId_);

    /**
     * @notice Fill an order on this chain with additional message data required by some crosschain messages
     * @param orderId_ ID of the order to fill
     * @param orderData_ OrderData payload with all order information required to identify an order to be filled
     * @param fillerParams_ Parameters supplied by the solver of the order
     * @param bridgeAdapter_ Address of the bridge adapter to use for crosschain messages (must be supported by Portal V2)
     * @param bridgeAdapterArgs_ Additional data required by some crosschain message protocols (see PortalV2 for more info)
     * @return messageId_ The ID of the crosschain message reporting this fill back to the origin chain (zero for same-chain fills)
     * @dev   The orderData is packed and hashed to verify the order ID as a safeguard for solvers
     * @dev   The payable amount is forwarded to the underlying portal contract to send crosschain messages.
     *        This should be 0 for same chain fills. For crosschain fills, see the Portal V2 contract for guidance on
     *        getting a quote for the required fee
     */
    function fillOrder(
        bytes32 orderId_,
        OrderData calldata orderData_,
        FillParams calldata fillerParams_,
        address bridgeAdapter_,
        bytes calldata bridgeAdapterArgs_
    ) external payable returns (bytes32 messageId_);

    /**
     * @notice Report a fill that was made on another chain back to this chain as the origin chain
     * @dev Must be called by the portal contract
     * @param sourceChainId_ The chain ID that the fill report was sent from
     * @param report_ Fill data sent from the destination chain
     */
    function reportFill(uint32 sourceChainId_, FillReport calldata report_) external;

    /**
     * @notice Report a cross-chain cancellation of an order.
     * @dev Must be called by the portal contract
     * @param sourceChainId_ The chain ID that the cancel report was sent from
     * @param report_ Cancel data sent from the destination chain
     */
    function reportCancel(uint32 sourceChainId_, CancelReport calldata report_) external;

    /* ========== Admin Functions ========== */

    /**
     * @notice Set external chain support for orders
     * @dev Must be DEFAULT_ADMIN_ROLE to call
     * @param destChainId_ The chain ID for the destination chain used by the portal
     * @param isSupported_ whether support for the chain should be enabled (true activates, false deactivates)
     */
    function setDestinationSupported(uint32 destChainId_, bool isSupported_) external;

    /**
     * @notice Pauses the contract.
     * @dev    Can only be called by an account with the PAUSER_ROLE.
     * @dev    When paused, all external order actions are disabled (open, fill, and cancel).
     *         However, processing of crosschain fill and cancel reports is still allowed.
     *         This enables safe upgrades of the contract by pausing all instances and
     *         waiting until inflight messages are processed.
     */
    function pause() external;

    /**
     * @notice Unpauses the contract.
     * @dev    Can only be called by an account with the PAUSER_ROLE.
     */
    function unpause() external;

    /* ========== View Functions ========== */

    /**
     * @notice Returns the order ID for the provided OrderData payload
     * @dev The order ID is a unique value across all supported chains
     */
    function getOrderId(OrderData calldata orderData_) external pure returns (bytes32);

    /**
     * @notice Returns the state of a local order (i.e. one that originated on this chain)
     * @dev The order must have originated on this chain or the information will not be available
     */
    function getOrder(bytes32 orderId_) external view returns (Order memory);

    /**
     * @notice Returns the OrderData for a local order (i.e. one that originated on this chain)
     * @dev The order must have originated on this chain or the information will not be available
     *      This is a convenience function for solvers to get the OrderData needed to fill an order
     * @param orderId_ The ID of the order to get data for
     * @return orderData_ The OrderData struct containing all order information needed to fill
     */
    function getOrderData(bytes32 orderId_) external view returns (OrderData memory orderData_);

    /**
     * @notice Returns the amount out filled and amount in released for an order with this chain as the destination
     * @dev The order must be settled on this chain or the information will not be available
     */
    function getFilledAmounts(bytes32 orderId_) external view returns (FilledAmounts memory);

    /// @notice Returns the next nonce for the provided sender address
    function getSenderNonce(address sender_) external view returns (uint64);

    /// @notice Returns whether orders can be created with the provided chain ID as the destination
    function isDestinationSupported(uint32 destChainId_) external view returns (bool);

    /* ========== EIP-712 Digest Functions ========== */

    /**
     * @notice Returns the EIP-712 digest that a user must sign to cancel orders gaslessly
     * @param orderId_ ID of the order to cancel
     * @param bridgeAdapter_ Address of the bridge adapter to use for crosschain messages (see Portal V2 for more info).
     *                       It can be zero address to use default or for same-chain cancels.
     * @param bridgeAdapterArgs_ Additional data required by some crosschain message protocols (see PortalV2 for more info).
     *                       It can be empty for no additional args or for same-chain cancels.
     */
    function getCancelOrderDigest(
        bytes32 orderId_,
        address bridgeAdapter_,
        bytes memory bridgeAdapterArgs_
    ) external view returns (bytes32);
}

src/interfaces/IPortalV2Like.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8;

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

interface IPortalV2Like {
    /// @notice Sends the fill report to the destination chain using the default bridge adapter.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  report             The OrderBook fill report to send.
    /// @param  refundAddress      The address to receive excess native gas on the source chain.
    /// @param  bridgeAdapterArgs  The optional bridge adapter arguments, could be empty.
    /// @return messageId          The ID uniquely identifying the message.
    function sendFillReport(
        uint32 destinationChainId,
        IOrderBook.FillReport calldata report,
        bytes32 refundAddress,
        bytes calldata bridgeAdapterArgs
    ) external payable returns (bytes32 messageId);

    /// @notice Sends the fill report to the destination chain using the specified bridge adapter.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  report             The OrderBook fill report to send.
    /// @param  refundAddress      The address to receive excess native gas on the source chain.
    /// @param  bridgeAdapter      The address of the bridge adapter to use.
    /// @param  bridgeAdapterArgs  The optional bridge adapter arguments, could be empty.
    /// @return messageId          The ID uniquely identifying the message.
    function sendFillReport(
        uint32 destinationChainId,
        IOrderBook.FillReport calldata report,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) external payable returns (bytes32 messageId);

    /// @notice Sends the cancel report to the destination chain using the default bridge adapter.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  report             The OrderBook cancel report to send.
    /// @param  refundAddress      The address to receive excess native gas on the source chain
    /// @param  bridgeAdapterArgs  The optional bridge adapter arguments, could be empty.
    /// @return messageId          The ID uniquely identifying the message.
    function sendCancelReport(
        uint32 destinationChainId,
        IOrderBook.CancelReport calldata report,
        bytes32 refundAddress,
        bytes calldata bridgeAdapterArgs
    ) external payable returns (bytes32 messageId);

    /// @notice Sends the cancel report to the destination chain using the specified bridge adapter.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  report             The OrderBook cancel report to send.
    /// @param  refundAddress      The address to receive excess native gas on the source chain
    /// @param  bridgeAdapter      The address of the bridge adapter to use.
    /// @param  bridgeAdapterArgs  The optional bridge adapter arguments, could be empty.
    /// @return messageId          The ID uniquely identifying the message.
    function sendCancelReport(
        uint32 destinationChainId,
        IOrderBook.CancelReport calldata report,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) external payable returns (bytes32 messageId);
}

src/libs/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
// Modified from the original to add *Exact transfer variants which check for fee on transfer.

pragma solidity ^0.8.20;

import { IERC20 } from "../../lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol";
import { IERC1363 } from "../../lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/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 An operation with an ERC-20 token failed due to fee on transfer.
     */
    error SafeERC20FeeOnTransfer(address token, address to, uint256 expectedAmount, uint256 actualAmount);

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

    function safeTransferExact(IERC20 token, address to, uint256 value) internal {
        uint256 balanceBefore = token.balanceOf(to);
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
        uint256 balanceAfter = token.balanceOf(to);
        if (balanceAfter < balanceBefore + value) {
            revert SafeERC20FeeOnTransfer(address(token), to, value, balanceAfter - balanceBefore);
        }
    }

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

    function safeTransferExactFrom(IERC20 token, address from, address to, uint256 value) internal {
        uint256 balanceBefore = token.balanceOf(to);
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
        uint256 balanceAfter = token.balanceOf(to);
        if (balanceAfter < balanceBefore + value) {
            revert SafeERC20FeeOnTransfer(address(token), to, value, balanceAfter - balanceBefore);
        }
    }

    /**
     * @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);
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 1000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "lib/safe-utils/:forge-std/=lib/safe-utils/lib/forge-std/src/",
    "lib/safe-utils/:safe-smart-account/=lib/safe-utils/lib/safe-smart-account/contracts/",
    "lib/safe-utils/:solidity-http/=lib/safe-utils/lib/solidity-http/src/",
    "@openzeppelin/contracts-upgradeable/=lib/common/lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
    "common/=lib/common/",
    "ds-test/=lib/safe-utils/lib/solidity-stringutils/lib/ds-test/src/",
    "erc4626-tests/=lib/common/lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/common/lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/common/lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "safe-smart-account/=lib/safe-utils/lib/safe-smart-account/",
    "safe-utils/=lib/safe-utils/src/",
    "solidity-http/=lib/safe-utils/lib/solidity-http/src/",
    "solidity-stringutils/=lib/safe-utils/lib/solidity-stringutils/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.