Skip to content
Verified contractExactBUSL-1.1

HubPortal

Address0xf1c63a35b68a5513b97e05fa2e111d7cc55beaee
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 3,000 runs
EVM version
prague
Via IR
yes
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,833,534
Creation transaction
0x44d267cdaa…e614919d91

42 files

lib/m-portal-v2/evm/src/HubPortal.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.34;

import { IERC20 } from "../lib/common/src/interfaces/IERC20.sol";
import { IndexingMath } from "../lib/common/src/libs/IndexingMath.sol";

import { IBridgeAdapter } from "./interfaces/IBridgeAdapter.sol";
import { IMTokenLike } from "./interfaces/IMTokenLike.sol";
import { IMerkleTreeBuilderLike } from "./interfaces/IMerkleTreeBuilderLike.sol";
import { IRegistrarLike } from "./interfaces/IRegistrarLike.sol";
import { IHubPortal } from "./interfaces/IHubPortal.sol";

import { Portal } from "./Portal.sol";
import { PayloadType, PayloadEncoder } from "./libraries/PayloadEncoder.sol";

struct SpokeChainConfig {
    /// The principal amount of M tokens bridged to the Spoke chain (only tracked for isolated Spokes).
    uint248 bridgedPrincipal;
    /// Indicates whether cross-Spoke token transfer is enabled for this Spoke chain.
    bool crossSpokeTokenTransferEnabled;
}

abstract contract HubPortalStorageLayout {
    /// @custom:storage-location erc7201:M0.storage.HubPortal
    struct HubPortalStorageStruct {
        /// Deprecated Portal V1 migration flag, kept to preserve the storage layout.
        bool migrating;
        bool wasEarningEnabled;
        uint128 disableEarningIndex;
        mapping(uint32 spokeChainId => SpokeChainConfig) spokeConfig;
    }

    // keccak256(abi.encode(uint256(keccak256("M0.storage.HubPortal")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 constant HUB_PORTAL_STORAGE_LOCATION = 0xa5b90c3f089c3e60896514f7e936c66a2ae73f34e81023f4d0032218558d8b00;

    function _getHubPortalStorageLocation() internal pure returns (HubPortalStorageStruct storage $) {
        assembly {
            $.slot := HUB_PORTAL_STORAGE_LOCATION
        }
    }
}

/// @title  HubPortal
/// @author M0 Labs
/// @notice Deployed on Ethereum and responsible for sending and receiving M tokens
///         as well as propagating M token index, Registrar keys and list status to the Spoke chain.
/// @dev    Tokens are bridged using lock-release mechanism.
contract HubPortal is Portal, HubPortalStorageLayout, IHubPortal {
    /// @inheritdoc IHubPortal
    bytes32 public constant SVM_EARNER_LIST = bytes32("solana-earners");

    /// @inheritdoc IHubPortal
    address public immutable merkleTreeBuilder;

    /// @notice Constructs HubPortal Implementation contract
    /// @dev    Sets immutable storage.
    /// @param  mToken_            The address of M token.
    /// @param  registrar_         The address of Registrar.
    /// @param  swapFacility_      The address of Swap Facility.
    /// @param  orderBook_         The address of Order Book.
    /// @param  merkleTreeBuilder_ The address of Merkle Tree Builder.
    constructor(
        address mToken_,
        address registrar_,
        address swapFacility_,
        address orderBook_,
        address merkleTreeBuilder_
    ) Portal(mToken_, registrar_, swapFacility_, orderBook_) {
        if ((merkleTreeBuilder = merkleTreeBuilder_) == address(0)) revert ZeroMerkleTreeBuilder();
    }

    /// @inheritdoc IHubPortal
    function initialize(address owner, address pauser, address operator) external initializer {
        _initialize(owner, pauser, operator);

        HubPortalStorageStruct storage $ = _getHubPortalStorageLocation();
        $.disableEarningIndex = IndexingMath.EXP_SCALED_ONE;
    }

    ///////////////////////////////////////////////////////////////////////////
    //                     EXTERNAL INTERACTIVE FUNCTIONS                    //
    ///////////////////////////////////////////////////////////////////////////

    /// @inheritdoc IHubPortal
    function sendMTokenIndex(
        uint32 destinationChainId,
        bytes32 refundAddress,
        bytes calldata bridgeAdapterArgs
    ) external payable whenSendNotPaused whenNotLocked returns (bytes32 messageId) {
        return _sendMTokenIndex(destinationChainId, refundAddress, defaultBridgeAdapter(destinationChainId), bridgeAdapterArgs);
    }

    /// @inheritdoc IHubPortal
    function sendMTokenIndex(
        uint32 destinationChainId,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) external payable whenSendNotPaused whenNotLocked returns (bytes32 messageId) {
        return _sendMTokenIndex(destinationChainId, refundAddress, bridgeAdapter, bridgeAdapterArgs);
    }

    /// @inheritdoc IHubPortal
    function sendRegistrarKey(
        uint32 destinationChainId,
        bytes32 key,
        bytes32 refundAddress,
        bytes calldata bridgeAdapterArgs
    ) external payable whenSendNotPaused whenNotLocked returns (bytes32 messageId) {
        return _sendRegistrarKey(destinationChainId, key, refundAddress, defaultBridgeAdapter(destinationChainId), bridgeAdapterArgs);
    }

    /// @inheritdoc IHubPortal
    function sendRegistrarKey(
        uint32 destinationChainId,
        bytes32 key,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) external payable whenSendNotPaused whenNotLocked returns (bytes32 messageId) {
        return _sendRegistrarKey(destinationChainId, key, refundAddress, bridgeAdapter, bridgeAdapterArgs);
    }

    /// @inheritdoc IHubPortal
    function sendRegistrarListStatus(
        uint32 destinationChainId,
        bytes32 listName,
        address account,
        bytes32 refundAddress,
        bytes calldata bridgeAdapterArgs
    ) external payable whenSendNotPaused whenNotLocked returns (bytes32 messageId) {
        return _sendRegistrarListStatus(
            destinationChainId, listName, account, refundAddress, defaultBridgeAdapter(destinationChainId), bridgeAdapterArgs
        );
    }

    /// @inheritdoc IHubPortal
    function sendRegistrarListStatus(
        uint32 destinationChainId,
        bytes32 listName,
        address account,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) external payable whenSendNotPaused whenNotLocked returns (bytes32 messageId) {
        return _sendRegistrarListStatus(destinationChainId, listName, account, refundAddress, bridgeAdapter, bridgeAdapterArgs);
    }

    /// @inheritdoc IHubPortal
    function sendEarnersMerkleRoot(
        uint32 destinationChainId,
        bytes32 refundAddress,
        bytes calldata bridgeAdapterArgs
    ) external payable whenSendNotPaused whenNotLocked returns (bytes32 messageId) {
        return _sendEarnersMerkleRoot(destinationChainId, refundAddress, defaultBridgeAdapter(destinationChainId), bridgeAdapterArgs);
    }

    /// @inheritdoc IHubPortal
    function sendEarnersMerkleRoot(
        uint32 destinationChainId,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) external payable whenSendNotPaused whenNotLocked returns (bytes32 messageId) {
        return _sendEarnersMerkleRoot(destinationChainId, refundAddress, bridgeAdapter, bridgeAdapterArgs);
    }

    /// @inheritdoc IHubPortal
    function enableEarning() external {
        if (_isEarningEnabled()) revert EarningIsEnabled();

        HubPortalStorageStruct storage $ = _getHubPortalStorageLocation();
        if ($.wasEarningEnabled) revert EarningCannotBeReenabled();

        $.wasEarningEnabled = true;

        IMTokenLike(mToken).startEarning();

        emit EarningEnabled(IMTokenLike(mToken).currentIndex());
    }

    /// @inheritdoc IHubPortal
    function disableEarning() external {
        if (!_isEarningEnabled()) revert EarningIsDisabled();

        uint128 currentMIndex = IMTokenLike(mToken).currentIndex();

        HubPortalStorageStruct storage $ = _getHubPortalStorageLocation();
        $.disableEarningIndex = currentMIndex;

        IMTokenLike(mToken).stopEarning(address(this));

        emit EarningDisabled(currentMIndex);
    }

    ///////////////////////////////////////////////////////////////////////////
    //                          PRIVILEGED FUNCTIONS                         //
    ///////////////////////////////////////////////////////////////////////////

    /// @inheritdoc IHubPortal
    function enableCrossSpokeTokenTransfer(uint32 spokeChainId) external onlyRole(OPERATOR_ROLE) {
        SpokeChainConfig storage spokeConfig = _getHubPortalStorageLocation().spokeConfig[spokeChainId];
        if (spokeConfig.crossSpokeTokenTransferEnabled) return;

        spokeConfig.crossSpokeTokenTransferEnabled = true;

        uint248 spokeBridgedPrincipal = spokeConfig.bridgedPrincipal;

        // NOTE: Reset bridged principal, as tracking it
        //       for connected Spokes isn't possible on-chain.
        spokeConfig.bridgedPrincipal = 0;

        emit CrossSpokeTokenTransferEnabled(spokeChainId, spokeBridgedPrincipal);
    }

    ///////////////////////////////////////////////////////////////////////////
    //                     EXTERNAL VIEW/PURE FUNCTIONS                      //
    ///////////////////////////////////////////////////////////////////////////

    /// @inheritdoc IHubPortal
    function wasEarningEnabled() public view returns (bool) {
        HubPortalStorageStruct storage $ = _getHubPortalStorageLocation();
        return $.wasEarningEnabled;
    }

    /// @inheritdoc IHubPortal
    function disableEarningIndex() public view returns (uint128) {
        HubPortalStorageStruct storage $ = _getHubPortalStorageLocation();
        return $.disableEarningIndex;
    }

    /// @inheritdoc IHubPortal
    function bridgedPrincipal(uint32 spokeChainId) external view returns (uint248) {
        HubPortalStorageStruct storage $ = _getHubPortalStorageLocation();
        return $.spokeConfig[spokeChainId].bridgedPrincipal;
    }

    /// @inheritdoc IHubPortal
    function crossSpokeTokenTransferEnabled(uint32 spokeChainId) external view returns (bool) {
        HubPortalStorageStruct storage $ = _getHubPortalStorageLocation();
        return $.spokeConfig[spokeChainId].crossSpokeTokenTransferEnabled;
    }

    ///////////////////////////////////////////////////////////////////////////
    //                INTERNAL/PRIVATE INTERACTIVE FUNCTIONS                 //
    ///////////////////////////////////////////////////////////////////////////

    /// @dev Sends the M token index to the destination chain.
    function _sendMTokenIndex(
        uint32 destinationChainId,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) private returns (bytes32 messageId) {
        _revertIfZeroRefundAddress(refundAddress);
        _revertIfUnsupportedBridgeAdapter(destinationChainId, bridgeAdapter);

        uint128 index = _currentIndex();
        bytes32 destinationPeer = IBridgeAdapter(bridgeAdapter).getPeer(destinationChainId);
        messageId = _getMessageId(destinationChainId);
        bytes memory payload = PayloadEncoder.encodeIndex(destinationChainId, destinationPeer, messageId, index);

        _sendMessage(destinationChainId, PayloadType.Index, refundAddress, payload, bridgeAdapter, bridgeAdapterArgs);

        emit MTokenIndexSent(destinationChainId, index, bridgeAdapter, messageId);
    }

    /// @dev Sends the Registrar key to the destination chain.
    function _sendRegistrarKey(
        uint32 destinationChainId,
        bytes32 key,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) private returns (bytes32 messageId) {
        _revertIfZeroRefundAddress(refundAddress);
        _revertIfUnsupportedBridgeAdapter(destinationChainId, bridgeAdapter);

        bytes32 value = IRegistrarLike(registrar).get(key);
        bytes32 destinationPeer = IBridgeAdapter(bridgeAdapter).getPeer(destinationChainId);
        messageId = _getMessageId(destinationChainId);
        uint128 index = _currentIndex();
        bytes memory payload = PayloadEncoder.encodeRegistrarKey(destinationChainId, destinationPeer, messageId, index, key, value);

        _sendMessage(destinationChainId, PayloadType.RegistrarKey, refundAddress, payload, bridgeAdapter, bridgeAdapterArgs);

        emit RegistrarKeySent(destinationChainId, key, value, index, bridgeAdapter, messageId);
    }

    /// @dev Sends the Registrar list status for an account to the destination chain.
    function _sendRegistrarListStatus(
        uint32 destinationChainId,
        bytes32 listName,
        address account,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) private returns (bytes32 messageId) {
        _revertIfZeroRefundAddress(refundAddress);
        _revertIfUnsupportedBridgeAdapter(destinationChainId, bridgeAdapter);

        bool status = IRegistrarLike(registrar).listContains(listName, account);
        bytes32 destinationPeer = IBridgeAdapter(bridgeAdapter).getPeer(destinationChainId);
        messageId = _getMessageId(destinationChainId);
        uint128 index = _currentIndex();
        bytes memory payload =
            PayloadEncoder.encodeRegistrarList(destinationChainId, destinationPeer, messageId, index, listName, account, status);

        _sendMessage(destinationChainId, PayloadType.RegistrarList, refundAddress, payload, bridgeAdapter, bridgeAdapterArgs);

        emit RegistrarListStatusSent(destinationChainId, listName, account, status, index, bridgeAdapter, messageId);
    }

    /// @dev Sends the Earner Merkle Root to the destination chain.
    function _sendEarnersMerkleRoot(
        uint32 destinationChainId,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) private returns (bytes32 messageId) {
        _revertIfZeroRefundAddress(refundAddress);
        _revertIfUnsupportedBridgeAdapter(destinationChainId, bridgeAdapter);

        uint128 index = _currentIndex();
        bytes32 destinationPeer = IBridgeAdapter(bridgeAdapter).getPeer(destinationChainId);
        messageId = _getMessageId(destinationChainId);
        bytes32 earnerMerkleRoot = IMerkleTreeBuilderLike(merkleTreeBuilder).getRoot(SVM_EARNER_LIST);
        bytes memory payload =
            PayloadEncoder.encodeEarnerMerkleRoot(destinationChainId, destinationPeer, messageId, index, earnerMerkleRoot);

        _sendMessage(destinationChainId, PayloadType.EarnerMerkleRoot, refundAddress, payload, bridgeAdapter, bridgeAdapterArgs);

        emit EarnerMerkleRootSent(destinationChainId, index, earnerMerkleRoot, bridgeAdapter, messageId);
    }

    function _burnOrLock(uint32 destinationChainId, uint256 amount) internal override {
        SpokeChainConfig storage spokeConfig = _getHubPortalStorageLocation().spokeConfig[destinationChainId];
        // Only track bridged principal for isolated Spokes
        if (spokeConfig.crossSpokeTokenTransferEnabled) return;

        spokeConfig.bridgedPrincipal += IndexingMath.getPrincipalAmountRoundedDown(uint240(amount), _currentIndex());
    }

    /// @dev Unlocks M tokens to `recipient`.
    /// @param sourceChainId The ID of the source chain.
    /// @param recipient     The account to unlock/transfer M tokens to.
    /// @param amount        The amount of $M Token to unlock to the recipient.
    function _mintOrUnlock(uint32 sourceChainId, address recipient, uint256 amount, uint128) internal override {
        _decreaseBridgedPrincipal(sourceChainId, amount);

        if (recipient != address(this)) {
            IERC20(mToken).transfer(recipient, amount);
        }
    }

    /// @dev Decreases the principal amount bridged when receiving transfer from an isolated Spoke chain.
    ///      Reverts when trying to unlock more than was bridged to the Spoke.
    function _decreaseBridgedPrincipal(uint32 spokeChainId, uint256 amount) private {
        SpokeChainConfig storage spokeConfig = _getHubPortalStorageLocation().spokeConfig[spokeChainId];

        // Only track bridged principal for isolated Spokes
        if (spokeConfig.crossSpokeTokenTransferEnabled) return;

        uint248 totalBridgedPrincipal = spokeConfig.bridgedPrincipal;
        uint248 principalAmount = IndexingMath.getPrincipalAmountRoundedDown(uint240(amount), _currentIndex());

        // Prevents unlocking more than was bridged to the Spoke
        if (principalAmount > totalBridgedPrincipal) revert InsufficientBridgedBalance();

        unchecked {
            spokeConfig.bridgedPrincipal = totalBridgedPrincipal - principalAmount;
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    //                 INTERNAL/PRIVATE VIEW/PURE FUNCTIONS                  //
    ///////////////////////////////////////////////////////////////////////////

    /// @dev If earning is enabled returns the current M token index,
    ///      otherwise, returns the index at the time when earning was disabled.
    function _currentIndex() internal view override returns (uint128) {
        return _isEarningEnabled() ? IMTokenLike(mToken).currentIndex() : disableEarningIndex();
    }

    /// @dev Returns whether earning was enabled for HubPortal or not.
    function _isEarningEnabled() internal view returns (bool) {
        return wasEarningEnabled() && disableEarningIndex() == IndexingMath.EXP_SCALED_ONE;
    }

    /// @dev Reverts if the difference between the specified and the actual amount of $M received
    ///      exceeds the maximum acceptable rounding tolerance.
    ///      When HubPortal ($M earner) receives $M from a non-earner (e.g. the SwapFacility),
    ///      the receiver's principal is rounded down as `amount * EXP_SCALED_ONE / index`, so the
    ///      resulting balance increase can be up to `index / EXP_SCALED_ONE + 1` wei less than the
    ///      transferred amount. The accepted deficit is covered from the yield earned by HubPortal.
    ///      NOTE: The tolerance assumes HubPortal remains an $M earner and the SwapFacility a non-earner.
    ///      It is applied even if earning is ever disabled; this is accepted, as $M transfers are then
    ///      exact and any absorbed shortfall is bounded by the same tolerance.
    function _revertIfInsufficientMReceived(uint256 specifiedAmount, uint256 actualAmount) internal view override {
        if (specifiedAmount > actualAmount) {
            unchecked {
                uint256 roundingTolerance = (_currentIndex() / IndexingMath.EXP_SCALED_ONE) + 1;
                if (specifiedAmount - actualAmount > roundingTolerance) {
                    revert InsufficientAmountReceived(specifiedAmount, actualAmount);
                }
            }
        }
    }
}

lib/m-portal-v2/evm/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/m-portal-v2/evm/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/m-portal-v2/evm/lib/common/lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol

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

pragma solidity ^0.8.22;

import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

lib/m-portal-v2/evm/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/m-portal-v2/evm/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/m-portal-v2/evm/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/m-portal-v2/evm/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/m-portal-v2/evm/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/m-portal-v2/evm/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/m-portal-v2/evm/lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

lib/m-portal-v2/evm/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/m-portal-v2/evm/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/m-portal-v2/evm/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/m-portal-v2/evm/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/m-portal-v2/evm/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/m-portal-v2/evm/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/m-portal-v2/evm/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/m-portal-v2/evm/lib/common/src/libs/IndexingMath.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.20 <0.9.0;

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

/**
 * @title  Helper library for indexing math functions.
 * @author M^0 Labs
 */
library IndexingMath {
    /* ============ Variables ============ */

    /// @notice The scaling of indexes for exponent math.
    uint56 internal constant EXP_SCALED_ONE = 1e12;

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

    /// @notice Emitted when a division by zero occurs.
    error DivisionByZero();

    /* ============ Exposed Functions ============ */

    /**
     * @notice Helper function to calculate `(x * EXP_SCALED_ONE) / y`, rounded down.
     * @dev    Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
     */
    function divide240By128Down(uint240 x, uint128 y) internal pure returns (uint112) {
        if (y == 0) revert DivisionByZero();

        unchecked {
            // NOTE: While `uint256(x) * EXP_SCALED_ONE` can technically overflow, these divide/multiply functions are
            //       only used for the purpose of principal/present amount calculations for continuous indexing, and
            //       so for an `x` to be large enough to overflow this, it would have to be a possible result of
            //       `multiply112By128Down` or `multiply112By128Up`, which would already satisfy
            //       `uint256(x) * EXP_SCALED_ONE < type(uint240).max`.
            return UIntMath.safe112((uint256(x) * EXP_SCALED_ONE) / y);
        }
    }

    /**
     * @notice Helper function to calculate `(x * EXP_SCALED_ONE) / y`, rounded up.
     * @dev    Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
     */
    function divide240By128Up(uint240 x, uint128 y) internal pure returns (uint112) {
        if (y == 0) revert DivisionByZero();

        unchecked {
            // NOTE: While `uint256(x) * EXP_SCALED_ONE` can technically overflow, these divide/multiply functions are
            //       only used for the purpose of principal/present amount calculations for continuous indexing, and
            //       so for an `x` to be large enough to overflow this, it would have to be a possible result of
            //       `multiply112By128Down` or `multiply112By128Up`, which would already satisfy
            //       `uint256(x) * EXP_SCALED_ONE < type(uint240).max`.
            return UIntMath.safe112(((uint256(x) * EXP_SCALED_ONE) + y - 1) / y);
        }
    }

    /**
     * @notice Helper function to calculate `(x * y) / EXP_SCALED_ONE`, rounded down.
     * @dev    Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
     */
    function multiply112By128Down(uint112 x, uint128 y) internal pure returns (uint240) {
        unchecked {
            return uint240((uint256(x) * y) / EXP_SCALED_ONE);
        }
    }

    /**
     * @notice Helper function to calculate `(x * index) / EXP_SCALED_ONE`, rounded up.
     * @dev    Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
     */
    function multiply112By128Up(uint112 x, uint128 index) internal pure returns (uint240 z) {
        unchecked {
            return uint240(((uint256(x) * index) + (EXP_SCALED_ONE - 1)) / EXP_SCALED_ONE);
        }
    }

    /**
     * @dev    Returns the present amount (rounded down) given the principal amount and an index.
     * @param  principalAmount The principal amount.
     * @param  index           An index.
     * @return The present amount rounded down.
     */
    function getPresentAmountRoundedDown(uint112 principalAmount, uint128 index) internal pure returns (uint240) {
        return multiply112By128Down(principalAmount, index);
    }

    /**
     * @dev    Returns the present amount (rounded up) given the principal amount and an index.
     * @param  principalAmount The principal amount.
     * @param  index           An index.
     * @return The present amount rounded up.
     */
    function getPresentAmountRoundedUp(uint112 principalAmount, uint128 index) internal pure returns (uint240) {
        return multiply112By128Up(principalAmount, index);
    }

    /**
     * @dev    Returns the principal amount given the present amount, using the current index.
     * @param  presentAmount The present amount.
     * @param  index         An index.
     * @return The principal amount rounded down.
     */
    function getPrincipalAmountRoundedDown(uint240 presentAmount, uint128 index) internal pure returns (uint112) {
        return divide240By128Down(presentAmount, index);
    }

    /**
     * @dev    Returns the principal amount given the present amount, using the current index.
     * @param  presentAmount The present amount.
     * @param  index         An index.
     * @return The principal amount rounded up.
     */
    function getPrincipalAmountRoundedUp(uint240 presentAmount, uint128 index) internal pure returns (uint112) {
        return divide240By128Up(presentAmount, index);
    }
}

lib/m-portal-v2/evm/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;
    }
}

lib/m-portal-v2/evm/src/Portal.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.34;

import { IERC20 } from "../lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import {
    SafeERC20
} from "../lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {
    AccessControlUpgradeable
} from "../lib/common/lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol";
import { UUPSUpgradeable } from "../lib/common/lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol";

import { IERC20Extended } from "../lib/common/src/interfaces/IERC20Extended.sol";

import { IBridgeAdapter } from "./interfaces/IBridgeAdapter.sol";
import { IPortal } from "./interfaces/IPortal.sol";
import { ISwapFacilityLike } from "./interfaces/ISwapFacilityLike.sol";
import { IOrderBookLike } from "./interfaces/IOrderBookLike.sol";
import { ReentrancyLock } from "./utils/ReentrancyLock.sol";
import { PayloadType, PayloadEncoder } from "./libraries/PayloadEncoder.sol";
import { TypeConverter } from "./libraries/TypeConverter.sol";

struct ChainConfig {
    /// @notice Default bridge adapter for each remote chain used if no bridge adapter is specified.
    address defaultBridgeAdapter;
    /// @notice Supported bridge adapters for each remote chain.
    mapping(address bridgeAdapter => bool supported) supportedBridgeAdapter;
    /// @notice Gas limit required to process different types of payload on destination chains.
    mapping(PayloadType payloadType => uint256 gasLimit) payloadGasLimit;
}

abstract contract PortalStorageLayout {
    /// @custom:storage-location erc7201:M0.storage.Portal
    struct PortalStorageStruct {
        /// @notice Ensures the uniqueness of each cross-chain message.
        uint256 nonce;
        /// @notice Configuration required to send cross-chain messages to the remote chain.
        mapping(uint32 chainId => ChainConfig) remoteChainConfig;
        /// @notice Supported bridging paths for cross-chain transfers.
        mapping(address sourceToken => mapping(uint32 destinationChainId => mapping(bytes32 destinationToken => bool supported)))
            supportedBridgingPath;
        /// @notice Indicates whether a message with a given hash has been processed.
        mapping(bytes32 messageId => bool) processedMessages;
        /// @notice Indicates whether sending cross-chain messages is paused.
        bool sendPaused;
        /// @notice Indicates whether receiving cross-chain messages is paused.
        bool receivePaused;
    }

    // keccak256(abi.encode(uint256(keccak256("M0.storage.Portal")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 constant PORTAL_STORAGE_LOCATION = 0xc28186249f0e66be857064e66a873ce85cfd996b5352867e3f7c1d7931e67d00;

    function _getPortalStorageLocation() internal pure returns (PortalStorageStruct storage $) {
        assembly {
            $.slot := PORTAL_STORAGE_LOCATION
        }
    }
}

abstract contract Portal is PortalStorageLayout, AccessControlUpgradeable, ReentrancyLock, UUPSUpgradeable, IPortal {
    using TypeConverter for *;
    using PayloadEncoder for bytes;
    using SafeERC20 for IERC20;

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

    /// @inheritdoc IPortal
    address public immutable mToken;

    /// @inheritdoc IPortal
    address public immutable registrar;

    /// @inheritdoc IPortal
    address public immutable swapFacility;

    /// @inheritdoc IPortal
    address public immutable orderBook;

    /// @dev Modifier to make a function callable only when sending messages is not paused.
    modifier whenSendNotPaused() {
        if (sendPaused()) revert SendingPaused();
        _;
    }

    /// @dev Modifier to make a function callable only when receiving messages is not paused.
    modifier whenReceiveNotPaused() {
        if (receivePaused()) revert ReceivingPaused();
        _;
    }

    /// @notice Constructs the Implementation contract
    /// @dev    Sets immutable storage.
    /// @param  mToken_       The address of M token.
    /// @param  registrar_    The address of Registrar.
    /// @param  swapFacility_ The address of Swap Facility.
    /// @param  orderBook_    The address of Order Book.
    constructor(address mToken_, address registrar_, address swapFacility_, address orderBook_) {
        _disableInitializers();

        if ((mToken = mToken_) == address(0)) revert ZeroMToken();
        if ((registrar = registrar_) == address(0)) revert ZeroRegistrar();
        if ((swapFacility = swapFacility_) == address(0)) revert ZeroSwapFacility();
        if ((orderBook = orderBook_) == address(0)) revert ZeroOrderBook();
    }

    /// @notice Initializes the Proxy's storage
    /// @param  admin    The address of the admin.
    /// @param  pauser   The address of the pauser.
    /// @param  operator The address of the operator.
    function _initialize(address admin, address pauser, address operator) internal onlyInitializing {
        if (admin == address(0)) revert ZeroAdmin();
        if (pauser == address(0)) revert ZeroPauser();
        if (operator == address(0)) revert ZeroOperator();

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

    ///////////////////////////////////////////////////////////////////////////
    //                     EXTERNAL INTERACTIVE FUNCTIONS                    //
    ///////////////////////////////////////////////////////////////////////////

    /// @inheritdoc IPortal
    function sendToken(
        uint256 amount,
        address sourceToken,
        uint32 destinationChainId,
        bytes32 destinationToken,
        bytes32 recipient,
        bytes32 refundAddress,
        bytes calldata bridgeAdapterArgs
    ) external payable whenSendNotPaused whenNotLocked returns (bytes32 messageId) {
        return _sendToken(
            amount,
            sourceToken,
            destinationChainId,
            destinationToken,
            recipient,
            refundAddress,
            defaultBridgeAdapter(destinationChainId),
            bridgeAdapterArgs
        );
    }

    function sendToken(
        uint256 amount,
        address sourceToken,
        uint32 destinationChainId,
        bytes32 destinationToken,
        bytes32 recipient,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) external payable whenSendNotPaused whenNotLocked returns (bytes32 messageId) {
        return _sendToken(
            amount, sourceToken, destinationChainId, destinationToken, recipient, refundAddress, bridgeAdapter, bridgeAdapterArgs
        );
    }

    /// @inheritdoc IPortal
    function sendTokenWithPermit(
        uint256 amount,
        address sourceToken,
        uint32 destinationChainId,
        bytes32 destinationToken,
        bytes32 recipient,
        bytes32 refundAddress,
        bytes calldata bridgeAdapterArgs,
        uint256 deadline,
        bytes calldata signature
    ) external payable whenSendNotPaused whenNotLocked returns (bytes32 messageId) {
        _permit(sourceToken, amount, deadline, signature);

        address bridgeAdapter = defaultBridgeAdapter(destinationChainId);
        return
            _sendToken(
                amount, sourceToken, destinationChainId, destinationToken, recipient, refundAddress, bridgeAdapter, bridgeAdapterArgs
            );
    }

    /// @inheritdoc IPortal
    function sendTokenWithPermit(
        uint256 amount,
        address sourceToken,
        uint32 destinationChainId,
        bytes32 destinationToken,
        bytes32 recipient,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs,
        uint256 deadline,
        bytes calldata signature
    ) external payable whenSendNotPaused whenNotLocked returns (bytes32 messageId) {
        _permit(sourceToken, amount, deadline, signature);

        return
            _sendToken(
                amount, sourceToken, destinationChainId, destinationToken, recipient, refundAddress, bridgeAdapter, bridgeAdapterArgs
            );
    }

    /// @inheritdoc IPortal
    function sendFillReport(
        uint32 destinationChainId,
        IOrderBookLike.FillReport calldata report,
        bytes32 refundAddress,
        bytes calldata bridgeAdapterArgs
    ) external payable whenSendNotPaused whenNotLocked returns (bytes32 messageId) {
        return _sendFillReport(destinationChainId, report, refundAddress, defaultBridgeAdapter(destinationChainId), bridgeAdapterArgs);
    }

    /// @inheritdoc IPortal
    function sendFillReport(
        uint32 destinationChainId,
        IOrderBookLike.FillReport calldata report,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) external payable whenSendNotPaused whenNotLocked returns (bytes32 messageId) {
        return _sendFillReport(destinationChainId, report, refundAddress, bridgeAdapter, bridgeAdapterArgs);
    }

    /// @inheritdoc IPortal
    function sendCancelReport(
        uint32 destinationChainId,
        IOrderBookLike.CancelReport calldata report,
        bytes32 refundAddress,
        bytes calldata bridgeAdapterArgs
    ) external payable whenSendNotPaused whenNotLocked returns (bytes32 messageId) {
        return _sendCancelReport(destinationChainId, report, refundAddress, defaultBridgeAdapter(destinationChainId), bridgeAdapterArgs);
    }

    /// @inheritdoc IPortal
    function sendCancelReport(
        uint32 destinationChainId,
        IOrderBookLike.CancelReport calldata report,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) external payable whenSendNotPaused whenNotLocked returns (bytes32 messageId) {
        return _sendCancelReport(destinationChainId, report, refundAddress, bridgeAdapter, bridgeAdapterArgs);
    }

    /// @inheritdoc IPortal
    function receiveMessage(uint32 sourceChainId, bytes calldata payload) external whenReceiveNotPaused whenNotLocked {
        _revertIfUnsupportedBridgeAdapter(sourceChainId, msg.sender);

        // NOTE: Defense-in-depth checks.
        //       These checks are enforced at the application layer regardless of what the
        //       underlying messaging protocol guarantees, so behavior is consistent across
        //       adapters and resilient to changes of the messaging provider.
        (uint32 targetChainId, bytes32 targetBridgeAdapter) = payload.decodeDestinationChainIdAndPeer();
        if (targetChainId != currentChainId()) revert InvalidTargetChain(targetChainId);
        if (targetBridgeAdapter != msg.sender.toBytes32()) revert InvalidTargetBridgeAdapter(targetBridgeAdapter);

        PayloadType payloadType = payload.decodePayloadType();
        bytes32 messageId = payload.decodeMessageId();
        PortalStorageStruct storage $ = _getPortalStorageLocation();
        if ($.processedMessages[messageId]) revert MessageAlreadyProcessed(messageId);

        $.processedMessages[messageId] = true;

        if (payloadType == PayloadType.TokenTransfer) {
            _receiveToken(sourceChainId, payload);
            return;
        }

        if (payloadType == PayloadType.FillReport) {
            _receiveFillReport(sourceChainId, payload);
            return;
        }

        if (payloadType == PayloadType.CancelReport) {
            _receiveCancelReport(sourceChainId, payload);
            return;
        }

        // Index, Registrar Key, or Registrar List Update on Spoke chains
        _receiveCustomPayload(sourceChainId, payloadType, payload);
    }

    ///////////////////////////////////////////////////////////////////////////
    //                          PRIVILEGED FUNCTIONS                         //
    ///////////////////////////////////////////////////////////////////////////

    /// @inheritdoc IPortal
    function setDefaultBridgeAdapter(uint32 destinationChainId, address bridgeAdapter) external onlyRole(OPERATOR_ROLE) {
        _revertIfInvalidDestinationChain(destinationChainId);
        _revertIfZeroBridgeAdapter(bridgeAdapter);

        ChainConfig storage remoteChainConfig = _getPortalStorageLocation().remoteChainConfig[destinationChainId];

        // If the bridge adapter isn't already supported, add it to the supported adapters list
        if (!remoteChainConfig.supportedBridgeAdapter[bridgeAdapter]) {
            remoteChainConfig.supportedBridgeAdapter[bridgeAdapter] = true;
            emit SupportedBridgeAdapterSet(destinationChainId, bridgeAdapter, true);
        }

        if (remoteChainConfig.defaultBridgeAdapter == bridgeAdapter) return;

        remoteChainConfig.defaultBridgeAdapter = bridgeAdapter;
        emit DefaultBridgeAdapterSet(destinationChainId, bridgeAdapter);
    }

    /// @inheritdoc IPortal
    function setSupportedBridgeAdapter(uint32 destinationChainId, address bridgeAdapter, bool supported) external onlyRole(OPERATOR_ROLE) {
        _revertIfInvalidDestinationChain(destinationChainId);
        _revertIfZeroBridgeAdapter(bridgeAdapter);

        ChainConfig storage remoteChainConfig = _getPortalStorageLocation().remoteChainConfig[destinationChainId];

        if (remoteChainConfig.supportedBridgeAdapter[bridgeAdapter] == supported) return;

        // If the bridge adapter being removed is currently set as the default, clear the default adapter
        if (!supported && remoteChainConfig.defaultBridgeAdapter == bridgeAdapter) {
            remoteChainConfig.defaultBridgeAdapter = address(0);
            emit DefaultBridgeAdapterSet(destinationChainId, address(0));
        }

        remoteChainConfig.supportedBridgeAdapter[bridgeAdapter] = supported;
        emit SupportedBridgeAdapterSet(destinationChainId, bridgeAdapter, supported);
    }

    /// @inheritdoc IPortal
    function setSupportedBridgingPath(
        address sourceToken,
        uint32 destinationChainId,
        bytes32 destinationToken,
        bool supported
    ) external onlyRole(OPERATOR_ROLE) {
        _revertIfZeroSourceToken(sourceToken);
        _revertIfInvalidDestinationChain(destinationChainId);
        _revertIfZeroDestinationToken(destinationToken);

        PortalStorageStruct storage $ = _getPortalStorageLocation();

        if ($.supportedBridgingPath[sourceToken][destinationChainId][destinationToken] == supported) return;

        $.supportedBridgingPath[sourceToken][destinationChainId][destinationToken] = supported;
        emit SupportedBridgingPathSet(sourceToken, destinationChainId, destinationToken, supported);
    }

    /// @inheritdoc IPortal
    function setPayloadGasLimit(uint32 destinationChainId, PayloadType payloadType, uint256 gasLimit) external onlyRole(OPERATOR_ROLE) {
        _revertIfInvalidDestinationChain(destinationChainId);
        ChainConfig storage remoteChainConfig = _getPortalStorageLocation().remoteChainConfig[destinationChainId];

        if (remoteChainConfig.payloadGasLimit[payloadType] == gasLimit) return;

        remoteChainConfig.payloadGasLimit[payloadType] = gasLimit;
        emit PayloadGasLimitSet(destinationChainId, payloadType, gasLimit);
    }

    /// @dev Reverts if `msg.sender` is not authorized to upgrade the contract
    function _authorizeUpgrade(address newImplementation) internal override onlyRole(DEFAULT_ADMIN_ROLE) { }

    /// @inheritdoc IPortal
    function pauseSend() public onlyRole(PAUSER_ROLE) {
        _pauseSend();
    }

    /// @inheritdoc IPortal
    function unpauseSend() public onlyRole(PAUSER_ROLE) {
        _unpauseSend();
    }

    /// @inheritdoc IPortal
    function pauseReceive() public onlyRole(PAUSER_ROLE) {
        _pauseReceive();
    }

    /// @inheritdoc IPortal
    function unpauseReceive() public onlyRole(PAUSER_ROLE) {
        _unpauseReceive();
    }

    /// @inheritdoc IPortal
    function pauseAll() public onlyRole(PAUSER_ROLE) {
        _pauseSend();
        _pauseReceive();
    }

    /// @inheritdoc IPortal
    function unpauseAll() public onlyRole(PAUSER_ROLE) {
        _unpauseSend();
        _unpauseReceive();
    }

    ///////////////////////////////////////////////////////////////////////////
    //                     EXTERNAL VIEW/PURE FUNCTIONS                      //
    ///////////////////////////////////////////////////////////////////////////

    /// @inheritdoc IPortal
    /// @dev Using block.chainid directly to prevent a replay attack if a chain undergoes a contentious hard fork.
    function currentChainId() public view returns (uint32) {
        // NOTE: For most EVM chains, ID fits into uint32
        return block.chainid.toUint32();
    }

    function getNonce() external view returns (uint256) {
        PortalStorageStruct storage $ = _getPortalStorageLocation();
        return $.nonce;
    }

    /// @inheritdoc IPortal
    function defaultBridgeAdapter(uint32 destinationChainId) public view returns (address) {
        PortalStorageStruct storage $ = _getPortalStorageLocation();
        return $.remoteChainConfig[destinationChainId].defaultBridgeAdapter;
    }

    /// @inheritdoc IPortal
    function supportedBridgeAdapter(uint32 destinationChainId, address bridgeAdapter) public view returns (bool) {
        PortalStorageStruct storage $ = _getPortalStorageLocation();
        return $.remoteChainConfig[destinationChainId].supportedBridgeAdapter[bridgeAdapter];
    }

    /// @inheritdoc IPortal
    function supportedBridgingPath(address sourceToken, uint32 destinationChainId, bytes32 destinationToken) external view returns (bool) {
        PortalStorageStruct storage $ = _getPortalStorageLocation();
        return $.supportedBridgingPath[sourceToken][destinationChainId][destinationToken];
    }

    /// @inheritdoc IPortal
    function payloadGasLimit(uint32 destinationChainId, PayloadType payloadType) public view returns (uint256) {
        PortalStorageStruct storage $ = _getPortalStorageLocation();
        return $.remoteChainConfig[destinationChainId].payloadGasLimit[payloadType];
    }

    /// @inheritdoc IPortal
    function currentIndex() external view returns (uint128) {
        return _currentIndex();
    }

    /// @inheritdoc IPortal
    function msgSender() public view returns (address) {
        return _locker;
    }

    /// @inheritdoc IPortal
    function quote(uint32 destinationChainId, PayloadType payloadType) external view returns (uint256) {
        return _quote(destinationChainId, payloadType, defaultBridgeAdapter(destinationChainId));
    }

    /// @inheritdoc IPortal
    function quote(uint32 destinationChainId, PayloadType payloadType, address bridgeAdapter) external view returns (uint256) {
        return _quote(destinationChainId, payloadType, bridgeAdapter);
    }

    /// @inheritdoc IPortal
    function sendPaused() public view returns (bool) {
        return _getPortalStorageLocation().sendPaused;
    }

    /// @inheritdoc IPortal
    function receivePaused() public view returns (bool) {
        return _getPortalStorageLocation().receivePaused;
    }

    ///////////////////////////////////////////////////////////////////////////
    //                     INTERNAL INTERACTIVE FUNCTIONS                    //
    ///////////////////////////////////////////////////////////////////////////

    /// @dev Sends the specified payload to the destination chain.
    function _sendMessage(
        uint32 destinationChainId,
        PayloadType payloadType,
        bytes32 refundAddress,
        bytes memory payload,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) internal {
        IBridgeAdapter(bridgeAdapter).sendMessage{ value: msg.value }(
            destinationChainId, _getPayloadGasLimitOrRevert(destinationChainId, payloadType), refundAddress, payload, bridgeAdapterArgs
        );
    }

    /// @dev Transfers $M Token or $M Extension to the destination chain.
    function _sendToken(
        uint256 amount,
        address sourceToken,
        uint32 destinationChainId,
        bytes32 destinationToken,
        bytes32 recipient,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) internal returns (bytes32 messageId) {
        _revertIfZeroAmount(amount);
        _revertIfZeroRefundAddress(refundAddress);
        _revertIfZeroSourceToken(sourceToken);
        _revertIfZeroDestinationToken(destinationToken);
        _revertIfZeroRecipient(recipient);
        _revertIfUnsupportedBridgeAdapter(destinationChainId, bridgeAdapter);
        _revertIfUnsupportedBridgingPath(sourceToken, destinationChainId, destinationToken);

        // Transfer and if the source token isn't $M token, unwrap it to $M token.
        _transferAndUnwrap(sourceToken, amount);

        // Burn $M tokens on Spoke.
        // In case of Hub, only update the bridged principal amount as tokens already transferred.
        _burnOrLock(destinationChainId, amount);

        bytes memory payload;
        uint128 index;
        // Prevent stack too deep error
        uint256 transferAmount = amount;
        (payload, messageId, index) =
            _createTokenTransferPayload(transferAmount, destinationChainId, destinationToken, msg.sender, recipient, bridgeAdapter);

        _sendMessage(destinationChainId, PayloadType.TokenTransfer, refundAddress, payload, bridgeAdapter, bridgeAdapterArgs);

        emit TokenSent(
            sourceToken, destinationChainId, destinationToken, msg.sender, recipient, transferAmount, index, bridgeAdapter, messageId
        );
    }

    /// @dev Attempts to approve the transfer of `sourceToken` from the sender to the Portal via a permit signature.
    ///      If the permit fails (e.g. it was front-run), the failure is swallowed and the transfer
    ///      proceeds using the existing allowance.
    ///      The permit is executed via M0's non-standard `permit(address,address,uint256,uint256,bytes)` overload,
    ///      not the canonical EIP-2612 `permit(address,address,uint256,uint256,uint8,bytes32,bytes32)`.
    /// @param sourceToken The address of the source token.
    /// @param amount      The amount of the allowance being approved.
    /// @param deadline    The last timestamp where the signature is still valid.
    /// @param  signature          The signature of the EIP-2612 permit digest: either a 65-byte ECDSA signature
    ///                            encoded as `abi.encodePacked(r, s, v)`, or an ERC-1271 contract signature
    ///                            validated against the same digest.
    function _permit(address sourceToken, uint256 amount, uint256 deadline, bytes calldata signature) private {
        try IERC20Extended(sourceToken).permit(msg.sender, address(this), amount, deadline, signature) { } catch { }
    }

    /// @dev Transfers the specified amount of `sourceToken` from the sender to the Portal
    ///      If the source token is not $M token, it unwraps it to $M token.
    ///      Reverts if the amount of $M received is insufficient (see `_revertIfInsufficientMReceived`).
    /// @param sourceToken     The address of the source token.
    /// @param specifiedAmount The amount specified by the sender to transfer.
    function _transferAndUnwrap(address sourceToken, uint256 specifiedAmount) internal {
        uint256 mBalanceBefore = _mBalanceOf(address(this));
        uint256 sourceTokenBalanceBefore = _tokenBalanceOf(sourceToken, address(this));

        // Transfer source token from the sender
        IERC20(sourceToken).safeTransferFrom(msg.sender, address(this), specifiedAmount);
        uint256 actualAmount;

        // If the source token isn't $M token, unwrap it
        if (sourceToken != mToken) {
            // The actual amount of the source tokens that Portal received from the sender.
            actualAmount = _tokenBalanceOf(sourceToken, address(this)) - sourceTokenBalanceBefore;

            // NOTE: SwapFacility doesn't support fee-on-transfer tokens.
            // Revert if the actual amount received is less than the specified amount.
            if (actualAmount < specifiedAmount) revert InsufficientAmountReceived(specifiedAmount, actualAmount);

            IERC20(sourceToken).forceApprove(swapFacility, actualAmount);
            ISwapFacilityLike(swapFacility).swapOutM(sourceToken, actualAmount, address(this));
        }

        // The actual amount of $M tokens that Portal received from the SwapFacility.
        actualAmount = _mBalanceOf(address(this)) - mBalanceBefore;

        // NOTE: The actual amount received can be less than the specified amount due to:
        //       - fee on unwrap in the source $M extension token;
        //       - $M earner principal rounding down on HubPortal (see the HubPortal override).
        _revertIfInsufficientMReceived(specifiedAmount, actualAmount);
    }

    /// @dev Creates token transfer payload.
    /// @return payload   The encoded payload.
    /// @return messageId The message ID for the cross-chain transfer.
    /// @return index     The current $M token index.
    function _createTokenTransferPayload(
        uint256 transferAmount,
        uint32 destinationChainId,
        bytes32 destinationToken,
        address sender,
        bytes32 recipient,
        address bridgeAdapter
    ) internal returns (bytes memory payload, bytes32 messageId, uint128 index) {
        messageId = _getMessageId(destinationChainId);
        index = _currentIndex();
        bytes32 destinationPeer = IBridgeAdapter(bridgeAdapter).getPeer(destinationChainId);
        payload = PayloadEncoder.encodeTokenTransfer(
            destinationChainId, destinationPeer, messageId, index, transferAmount, destinationToken, sender, recipient
        );
    }

    /// @dev Sends the fill report to the destination chain.
    function _sendFillReport(
        uint32 destinationChainId,
        IOrderBookLike.FillReport calldata report,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) private returns (bytes32 messageId) {
        if (msg.sender != orderBook) revert NotOrderBook();
        _revertIfZeroRefundAddress(refundAddress);
        _revertIfUnsupportedBridgeAdapter(destinationChainId, bridgeAdapter);

        bytes memory payload;
        uint128 index;
        // Prevent stack too deep error
        (payload, messageId, index) = _createFillReportPayload(destinationChainId, report, bridgeAdapter);

        _sendMessage(destinationChainId, PayloadType.FillReport, refundAddress, payload, bridgeAdapter, bridgeAdapterArgs);

        emit FillReportSent(
            destinationChainId,
            report.orderId,
            report.amountInToRelease,
            report.amountOutFilled,
            report.originRecipient,
            report.tokenIn,
            index,
            bridgeAdapter,
            messageId
        );
    }

    /// @dev Creates fill report payload.
    /// @return payload   The encoded payload.
    /// @return messageId The message ID for the cross-chain fill report.
    /// @return index     The current $M token index.
    function _createFillReportPayload(
        uint32 destinationChainId,
        IOrderBookLike.FillReport calldata report,
        address bridgeAdapter
    ) internal returns (bytes memory payload, bytes32 messageId, uint128 index) {
        messageId = _getMessageId(destinationChainId);
        index = _currentIndex();

        payload = PayloadEncoder.encodeFillReport(
            destinationChainId,
            IBridgeAdapter(bridgeAdapter).getPeer(destinationChainId),
            messageId,
            index,
            report.orderId,
            report.amountInToRelease,
            report.amountOutFilled,
            report.originRecipient,
            report.tokenIn
        );
    }

    function _sendCancelReport(
        uint32 destinationChainId,
        IOrderBookLike.CancelReport calldata report,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) private returns (bytes32 messageId) {
        if (msg.sender != orderBook) revert NotOrderBook();
        _revertIfZeroRefundAddress(refundAddress);
        _revertIfUnsupportedBridgeAdapter(destinationChainId, bridgeAdapter);

        uint128 index = _currentIndex();
        messageId = _getMessageId(destinationChainId);
        bytes memory payload = PayloadEncoder.encodeCancelReport(
            destinationChainId,
            IBridgeAdapter(bridgeAdapter).getPeer(destinationChainId),
            messageId,
            index,
            report.orderId,
            report.originSender,
            report.tokenIn,
            report.amountInToRefund
        );

        _sendMessage(destinationChainId, PayloadType.CancelReport, refundAddress, payload, bridgeAdapter, bridgeAdapterArgs);

        emit CancelReportSent(
            destinationChainId,
            report.orderId,
            report.originSender,
            report.tokenIn,
            report.amountInToRefund,
            index,
            bridgeAdapter,
            messageId
        );
    }

    /// @dev   Handles token transfer message on the destination.
    /// @param sourceChainId The ID of the source chain.
    /// @param payload       The message payload.
    function _receiveToken(uint32 sourceChainId, bytes memory payload) private {
        (bytes32 messageId, uint128 index, uint256 amount, address destinationToken, bytes32 sender, address recipient) =
            payload.decodeTokenTransfer();

        emit TokenReceived(sourceChainId, destinationToken, sender, recipient, amount, index, messageId);

        if (destinationToken == mToken) {
            // mints or unlocks $M Token to the recipient
            _mintOrUnlock(sourceChainId, recipient, amount, index);
        } else {
            // mints or unlocks $M Token to the Portal
            _mintOrUnlock(sourceChainId, address(this), amount, index);

            // wraps $M token and transfers it to the recipient
            _wrap(destinationToken, recipient, amount);
        }
    }

    /// @dev   Wraps $M token to the token specified by `destinationToken`.
    ///        If wrapping fails transfers $M token to `recipient_`.
    /// @param destinationToken The address of the Extension token.
    /// @param recipient        The account to receive wrapped token.
    /// @param amount           The amount to wrap.
    function _wrap(address destinationToken, address recipient, uint256 amount) private {
        IERC20(mToken).approve(swapFacility, amount);

        // Attempt to wrap $M token
        // NOTE: the call might fail with out-of-gas exception
        //       even if the destination token is the valid wrapped M token.
        //       Recipients must support both $M and wrapped $M transfers.
        (bool success,) = swapFacility.call(abi.encodeCall(ISwapFacilityLike.swapInM, (destinationToken, amount, recipient)));

        if (!success) {
            emit WrapFailed(destinationToken, recipient, amount);
            // Reset approval to prevent a potential double-spend attack
            IERC20(mToken).approve(swapFacility, 0);
            // Transfer $M token to the recipient
            IERC20(mToken).transfer(recipient, amount);
        }
    }

    /// @dev   Handles fill report message on the destination.
    /// @param sourceChainId The ID of the source chain.
    /// @param payload       The message payload.
    function _receiveFillReport(uint32 sourceChainId, bytes memory payload) private {
        (
            bytes32 messageId,
            uint128 index,
            bytes32 orderId,
            uint128 amountInToRelease,
            uint128 amountOutFilled,
            bytes32 originRecipient,
            bytes32 tokenIn
        ) = payload.decodeFillReport();

        _updateMTokenIndex(index);

        IOrderBookLike(orderBook)
            .reportFill(
                sourceChainId,
                IOrderBookLike.FillReport({
                    orderId: orderId,
                    amountInToRelease: amountInToRelease,
                    amountOutFilled: amountOutFilled,
                    originRecipient: originRecipient,
                    tokenIn: tokenIn
                })
            );

        emit FillReportReceived(sourceChainId, orderId, amountInToRelease, amountOutFilled, originRecipient, tokenIn, index, messageId);
    }

    /// @dev   Handles cancel report message on the destination.
    /// @param sourceChainId The ID of the source chain.
    /// @param payload       The message payload.
    function _receiveCancelReport(uint32 sourceChainId, bytes memory payload) private {
        (bytes32 messageId, uint128 index, bytes32 orderId, bytes32 orderSender, bytes32 tokenIn, uint128 amountInToRefund) =
            payload.decodeCancelReport();

        _updateMTokenIndex(index);

        IOrderBookLike(orderBook)
            .reportCancel(
                sourceChainId,
                IOrderBookLike.CancelReport({
                    orderId: orderId, originSender: orderSender, tokenIn: tokenIn, amountInToRefund: amountInToRefund
                })
            );

        emit CancelReportReceived(sourceChainId, orderId, orderSender, tokenIn, amountInToRefund, index, messageId);
    }

    /// @dev Pauses sending cross-chain messages.
    function _pauseSend() private {
        PortalStorageStruct storage $ = _getPortalStorageLocation();
        if ($.sendPaused) return;
        $.sendPaused = true;
        emit SendPaused();
    }

    /// @dev Unpauses sending cross-chain messages.
    function _unpauseSend() private {
        PortalStorageStruct storage $ = _getPortalStorageLocation();
        if (!$.sendPaused) return;
        $.sendPaused = false;
        emit SendUnpaused();
    }

    /// @dev Pauses receiving cross-chain messages.
    function _pauseReceive() private {
        PortalStorageStruct storage $ = _getPortalStorageLocation();
        if ($.receivePaused) return;
        $.receivePaused = true;
        emit ReceivePaused();
    }

    /// @dev Unpauses receiving cross-chain messages.
    function _unpauseReceive() private {
        PortalStorageStruct storage $ = _getPortalStorageLocation();
        if (!$.receivePaused) return;
        $.receivePaused = false;
        emit ReceiveUnpaused();
    }

    /// @dev Generates a unique across all chains message ID.
    /// @param destinationChainId The ID of the destination chain.
    function _getMessageId(uint32 destinationChainId) internal returns (bytes32) {
        return keccak256(abi.encode(currentChainId(), destinationChainId, _getPortalStorageLocation().nonce++));
    }

    /// @dev   Overridden in SpokePortal to handle custom payload messages.
    /// @param sourceChainId The ID of the source chain.
    /// @param payloadType   The type of the payload (Index, RegistrarKey, or RegistrarList).
    /// @param payload       The message payload to process.
    function _receiveCustomPayload(uint32 sourceChainId, PayloadType payloadType, bytes memory payload) internal virtual { }

    /// @dev   HubPortal:   unlocks and transfers `amount` $M tokens to `recipient`.
    ///        SpokePortal: mints `amount` $M tokens to `recipient`.
    /// @param sourceChainId The ID of the source chain.
    /// @param recipient     The account receiving $M tokens.
    /// @param amount        The amount of $M tokens to unlock/mint.
    /// @param index         The index from the source chain.
    function _mintOrUnlock(uint32 sourceChainId, address recipient, uint256 amount, uint128 index) internal virtual { }

    /// @dev   HubPortal:   locks `amount` $M tokens.
    ///        SpokePortal: burns `amount` $M tokens.
    /// @param destinationChainId The ID of the destination chain.
    /// @param amount             The amount of $M tokens to lock/burn.
    function _burnOrLock(uint32 destinationChainId, uint256 amount) internal virtual { }

    /// @dev Overridden in SpokePortal to update the $M token index.
    function _updateMTokenIndex(uint128 index) internal virtual { }

    ///////////////////////////////////////////////////////////////////////////
    //                 INTERNAL/PRIVATE VIEW/PURE FUNCTIONS                  //
    ///////////////////////////////////////////////////////////////////////////

    /// @dev Returns the fee for delivering a cross-chain message.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  payloadType        The payload type: TokenTransfer = 0, Index = 1, RegistrarKey = 2, RegistrarList = 3, FillReport = 4, EarnerMerkleRoot = 5, CancelReport = 6
    /// @param  bridgeAdapter      The address of the bridge adapter.
    function _quote(uint32 destinationChainId, PayloadType payloadType, address bridgeAdapter) private view returns (uint256) {
        _revertIfUnsupportedBridgeAdapter(destinationChainId, bridgeAdapter);

        uint256 gasLimit = _getPayloadGasLimitOrRevert(destinationChainId, payloadType);

        // NOTE: For quoting delivery fee, the content of the message doesn’t matter,
        //       only the destination chain, gas limit required to process the message on the destination
        //       and, for some protocols, payload size is relevant.
        bytes memory payload = PayloadEncoder.generateEmptyPayload(payloadType);

        return IBridgeAdapter(bridgeAdapter).quote(destinationChainId, gasLimit, payload);
    }

    /// @dev Returns the gas limit for the specified payload type on the destination chain.
    ///      Reverts if the gas limit is not set.
    function _getPayloadGasLimitOrRevert(uint32 destinationChainId, PayloadType payloadType) internal view returns (uint256) {
        uint256 gasLimit = payloadGasLimit(destinationChainId, payloadType);
        if (gasLimit == 0) revert PayloadGasLimitNotSet(destinationChainId, payloadType);
        return gasLimit;
    }

    /// @dev Reverts if `amount` is zero.
    function _revertIfZeroAmount(uint256 amount) private pure {
        if (amount == 0) revert ZeroAmount();
    }

    /// @dev Reverts if `refundAddress` is zero address.
    function _revertIfZeroRefundAddress(bytes32 refundAddress) internal pure {
        if (refundAddress == bytes32(0)) revert ZeroRefundAddress();
    }

    /// @dev Reverts if `bridgeAdapter` is zero address.
    function _revertIfZeroBridgeAdapter(address bridgeAdapter) internal pure {
        if (bridgeAdapter == address(0)) revert ZeroBridgeAdapter();
    }

    function _revertIfInvalidDestinationChain(uint32 destinationChainId) internal view {
        if (destinationChainId == currentChainId()) revert InvalidDestinationChain(destinationChainId);
    }

    function _revertIfZeroSourceToken(address sourceToken) internal pure {
        if (sourceToken == address(0)) revert ZeroSourceToken();
    }

    function _revertIfZeroDestinationToken(bytes32 destinationToken) internal pure {
        if (destinationToken == bytes32(0)) revert ZeroDestinationToken();
    }

    function _revertIfZeroRecipient(bytes32 recipient) internal pure {
        if (recipient == bytes32(0)) revert ZeroRecipient();
    }

    function _revertIfUnsupportedBridgeAdapter(uint32 chainId, address bridgeAdapter) internal view {
        if (!supportedBridgeAdapter(chainId, bridgeAdapter)) revert UnsupportedBridgeAdapter(chainId, bridgeAdapter);
    }

    function _revertIfUnsupportedBridgingPath(address sourceToken, uint32 destinationChainId, bytes32 destinationToken) internal view {
        PortalStorageStruct storage $ = _getPortalStorageLocation();
        if (!$.supportedBridgingPath[sourceToken][destinationChainId][destinationToken]) {
            revert UnsupportedBridgingPath(sourceToken, destinationChainId, destinationToken);
        }
    }

    /// @dev Returns the current M token index used by the Portal.
    function _currentIndex() internal view virtual returns (uint128) { }

    /// @dev Reverts if the actual amount of $M received by the Portal is less than the specified amount.
    ///      SpokePortal is not an $M earner and must receive the exact amount.
    ///      HubPortal overrides this check to tolerate $M earner principal rounding.
    function _revertIfInsufficientMReceived(uint256 specifiedAmount, uint256 actualAmount) internal view virtual {
        if (actualAmount < specifiedAmount) revert InsufficientAmountReceived(specifiedAmount, actualAmount);
    }

    /// @dev Returns the M Token balance of `account`.
    function _mBalanceOf(address account) internal view returns (uint256) {
        return IERC20(mToken).balanceOf(account);
    }

    /// @dev Returns the `token` balance of `account`.
    function _tokenBalanceOf(address token, address account) internal view returns (uint256) {
        return IERC20(token).balanceOf(account);
    }
}

lib/m-portal-v2/evm/src/interfaces/IBridgeAdapter.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.34;

/// @title  IBridgeAdapter interface
/// @author M0 Labs
/// @notice Interface defining a bridge adapter for cross-chain messaging functionality.
interface IBridgeAdapter {
    ///////////////////////////////////////////////////////////////////////////
    //                                 EVENTS                                //
    ///////////////////////////////////////////////////////////////////////////

    /// @notice Emitted when the address of bridge adapter on the remote chain is set.
    /// @param  chainId The ID of the remote chain.
    /// @param  peer    The address of the bridge contract on the remote chain.
    event PeerSet(uint32 chainId, bytes32 peer);

    /// @notice Emitted when the provider-specific chain ID is set.
    /// @param  chainId       The ID of the chain.
    /// @param  bridgeChainId The provider-specific chain ID.
    event BridgeChainIdSet(uint32 chainId, uint256 bridgeChainId);

    /// @notice Emitted when a previously configured `(chainId, bridgeChainId)` pair is removed
    ///         as a side effect of `setBridgeChainId` reassigning either side of the 1-1 mapping.
    /// @param  chainId       The internal chain ID whose mapping was removed.
    /// @param  bridgeChainId The provider-specific chain ID whose mapping was removed.
    event BridgeChainIdRemoved(uint32 chainId, uint256 bridgeChainId);

    ///////////////////////////////////////////////////////////////////////////
    //                             CUSTOM ERRORS                             //
    ///////////////////////////////////////////////////////////////////////////

    /// @notice Thrown when `sendMessage` function caller is not the portal.
    error NotPortal();

    /// @notice Thrown when the portal address is 0x0.
    error ZeroPortal();

    /// @notice Thrown when the admin address is 0x0.
    error ZeroAdmin();

    /// @notice Thrown when the operator address is 0x0.
    error ZeroOperator();

    /// @notice Thrown when the chain ID is 0.
    error ZeroChain();

    /// @notice Thrown when the provider-specific chain ID is 0.
    error ZeroBridgeChain();

    /// @notice Thrown when the specified remote chain isn't supported.
    error UnsupportedChain(uint32 chainId);

    /// @notice Thrown when the specified remote bridge chain isn't supported.
    error UnsupportedBridgeChain(uint256 bridgeChainId);

    /// @notice Thrown when the source chain isn't supported or configured peer doesn't match the sender.
    error UnsupportedSender(bytes32 sender);

    ///////////////////////////////////////////////////////////////////////////
    //                          VIEW/PURE FUNCTIONS                          //
    ///////////////////////////////////////////////////////////////////////////

    /// @notice Returns the address of the portal.
    function portal() external view returns (address);

    /// @notice Returns the fee for sending a message to the remote chain
    /// @param  destinationChainId The chain Id of the destination chain.
    /// @param  gasLimit           The gas limit to execute the message on the destination chain.
    /// @param  payload            The message payload to send.
    /// @return fee                The fee for sending a message.
    function quote(uint32 destinationChainId, uint256 gasLimit, bytes memory payload) external view returns (uint256 fee);

    /// @notice Returns the address of Bridge Adapter contract on the remote chain.
    /// @param  chainId The ID of the remote chain.
    function getPeer(uint32 chainId) external view returns (bytes32);

    /// @notice Returns the provider-specific chain ID.
    /// @param  chainId The internal ID of the chain.
    function getBridgeChainId(uint32 chainId) external view returns (uint256);

    /// @notice Returns the internal chain ID.
    /// @param  bridgeChainId The provider-specific chain ID.
    function getChainId(uint256 bridgeChainId) external view returns (uint32);

    ///////////////////////////////////////////////////////////////////////////
    //                         INTERACTIVE FUNCTIONS                         //
    ///////////////////////////////////////////////////////////////////////////

    /// @notice Sends a message to the remote chain.
    /// @param  destinationChainId The chain Id of the destination chain.
    /// @param  gasLimit           The gas limit to execute the message on the destination chain.
    /// @param  refundAddress      The address to refund the fee to.
    /// @param  payload            The message payload to send.
    /// @param  extraArguments     The provider-specific extra arguments required for sending the message.
    function sendMessage(
        uint32 destinationChainId,
        uint256 gasLimit,
        bytes32 refundAddress,
        bytes memory payload,
        bytes calldata extraArguments
    ) external payable;

    /// @notice Sets an address of Bridge Adapter contract on the remote chain.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  destinationPeer    The address of of the Bridge Adapter contract on the destination chain.
    function setPeer(uint32 destinationChainId, bytes32 destinationPeer) external;

    /// @notice Sets the provider-specific chain ID.
    /// @dev    Any chain whose existing pair is removed as a side effect of the 1-1 mapping
    ///         update also has its peer cleared (emitting `PeerSet` with a zero peer) and must
    ///         be reconfigured via `setPeer` before it can be used again.
    /// @param  chainId       The ID of the chain.
    /// @param  bridgeChainId The provider-specific chain ID.
    function setBridgeChainId(uint32 chainId, uint256 bridgeChainId) external;

    /// @notice Initializes the Bridge Adapter Proxy contract.
    /// @param  admin    The address of the admin.
    /// @param  operator The address of the operator.
    function initialize(address admin, address operator) external;
}

lib/m-portal-v2/evm/src/interfaces/IHubPortal.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.34;

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

/// @title  HubPortal interface.
/// @author M0 Labs
interface IHubPortal is IPortal {
    ///////////////////////////////////////////////////////////////////////////
    //                                 EVENTS                                //
    ///////////////////////////////////////////////////////////////////////////

    /// @notice Emitted when earning is enabled for the Hub Portal.
    /// @param  index The index at which earning was enabled.
    event EarningEnabled(uint128 index);

    /// @notice Emitted when earning is disabled for the Hub Portal.
    /// @param  index The index at which earning was disabled.
    event EarningDisabled(uint128 index);

    /// @notice Emitted when the M token index is sent to a destination chain.
    /// @param  destinationChainId The chain Id of the destination chain.
    /// @param  index              The the M token index.
    /// @param  bridgeAdapter      The address of the bridge adapter used to send the message.
    /// @param  messageId          The unique ID of the sent message.
    event MTokenIndexSent(uint32 indexed destinationChainId, uint128 index, address bridgeAdapter, bytes32 messageId);

    /// @notice Emitted when the Registrar key is sent to a destination chain.
    /// @param  destinationChainId The chain Id of the destination chain.
    /// @param  key                The key that was sent.
    /// @param  value              The value that was sent.
    /// @param  index              The $M token index.
    /// @param  bridgeAdapter      The address of the bridge adapter used to send the message.
    /// @param  messageId          The unique ID of the sent message.
    event RegistrarKeySent(
        uint32 indexed destinationChainId, bytes32 indexed key, bytes32 value, uint128 index, address bridgeAdapter, bytes32 messageId
    );

    /// @notice Emitted when the Registrar list status for an account is sent to a destination chain.
    /// @param  destinationChainId The chain Id of the destination chain.
    /// @param  listName           The name of the list.
    /// @param  account            The account.
    /// @param  status             The status of the account in the list.
    /// @param  index              The $M token index.
    /// @param  bridgeAdapter      The address of the bridge adapter used to send the message.
    /// @param  messageId          The unique ID of the sent message.
    event RegistrarListStatusSent(
        uint32 indexed destinationChainId,
        bytes32 indexed listName,
        address indexed account,
        bool status,
        uint128 index,
        address bridgeAdapter,
        bytes32 messageId
    );

    /// @notice Emitted when the SVM Earners Merkle Root is sent to a destination chain.
    /// @param  destinationChainId The chain Id of the destination chain.
    /// @param  index              The $M token index.
    /// @param  earnerMerkleRoot   The Earner Merkle Root.
    /// @param  bridgeAdapter      The address of the bridge adapter used to send the message.
    /// @param  messageId          The unique ID of the sent message.
    event EarnerMerkleRootSent(
        uint32 indexed destinationChainId, uint128 index, bytes32 earnerMerkleRoot, address bridgeAdapter, bytes32 messageId
    );

    /// @notice Emitted when cross-Spoke token transfer is enabled for the Spoke chain.
    /// @param  spokeChainId     The ID of the Spoke chain.
    /// @param  bridgedPrincipal The principal amount of $M tokens bridged to the Spoke chain before transfer was enabled.
    event CrossSpokeTokenTransferEnabled(uint32 spokeChainId, uint248 bridgedPrincipal);

    ///////////////////////////////////////////////////////////////////////////
    //                             CUSTOM ERRORS                             //
    ///////////////////////////////////////////////////////////////////////////

    /// @notice Thrown when the Merkle Tree Builder address is zero.
    error ZeroMerkleTreeBuilder();

    /// @notice Thrown when trying to enable earning after it has been explicitly disabled.
    error EarningCannotBeReenabled();

    /// @notice Thrown when performing an operation that is not allowed when earning is disabled.
    error EarningIsDisabled();

    /// @notice Thrown when performing an operation that is not allowed when earning is enabled.
    error EarningIsEnabled();

    /// @notice Thrown when trying to unlock more tokens than was locked.
    error InsufficientBridgedBalance();

    ///////////////////////////////////////////////////////////////////////////
    //                          VIEW/PURE FUNCTIONS                          //
    ///////////////////////////////////////////////////////////////////////////

    /// @notice The list name identifier for Solana Virtual Machine earners in the Merkle Tree Builder.
    function SVM_EARNER_LIST() external view returns (bytes32);

    /// @notice Indicates whether earning for HubPortal was ever enabled.
    function wasEarningEnabled() external view returns (bool);

    /// @notice Returns the value of M token index when earning for HubPortal was disabled.
    function disableEarningIndex() external view returns (uint128);

    /// @notice Returns the address of the Merkle Tree Builder.
    function merkleTreeBuilder() external view returns (address);

    /// @notice Returns the principal amount of M tokens bridged to a specified Spoke chain.
    /// @dev    Only applicable to isolated Spokes (i.e., `crossSpokeTokenTransferEnabled` == false).
    function bridgedPrincipal(uint32 spokeChainId) external view returns (uint248);

    /// @notice Returns whether cross-Spoke token transfer is enabled for a specified Spoke chain.
    function crossSpokeTokenTransferEnabled(uint32 spokeChainId) external view returns (bool);

    ///////////////////////////////////////////////////////////////////////////
    //                         INTERACTIVE FUNCTIONS                         //
    ///////////////////////////////////////////////////////////////////////////

    /// @notice Initializes the Proxy's storage
    /// @param  initialOwner    The address of the owner.
    /// @param  initialPauser   The address of the pauser.
    /// @param  initialOperator The address of the operator.
    function initialize(address initialOwner, address initialPauser, address initialOperator) external;

    /// @notice Sends the $M token index to the destination chain using the default bridge adapter.
    /// @param  destinationChainId The chain Id of the destination chain.
    /// @param  refundAddress      The refund address to receive excess native gas.
    /// @param  bridgeAdapterArgs  The optional bridge adapter arguments, could be empty.
    /// @return messageId          The ID uniquely identifying the message.
    function sendMTokenIndex(
        uint32 destinationChainId,
        bytes32 refundAddress,
        bytes calldata bridgeAdapterArgs
    ) external payable returns (bytes32 messageId);

    /// @notice Sends the $M token index to the destination chain using the specified bridge adapter.
    /// @param  destinationChainId The chain Id of the destination chain.
    /// @param  refundAddress      The refund address to receive excess native gas.
    /// @param  bridgeAdapter      The address of the bridge adapter used to send the message.
    /// @param  bridgeAdapterArgs  The optional bridge adapter arguments, could be empty.
    /// @return messageId          The ID uniquely identifying the message.
    function sendMTokenIndex(
        uint32 destinationChainId,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) external payable returns (bytes32 messageId);

    /// @notice Sends the Registrar key to the destination chain using the default bridge adapter.
    /// @param  destinationChainId The chain Id of the destination chain.
    /// @param  key                The key to send.
    /// @param  refundAddress      The refund address to receive excess native gas.
    /// @param  bridgeAdapterArgs  The optional bridge adapter arguments, could be empty.
    /// @return messageId          The ID uniquely identifying the message.
    function sendRegistrarKey(
        uint32 destinationChainId,
        bytes32 key,
        bytes32 refundAddress,
        bytes calldata bridgeAdapterArgs
    ) external payable returns (bytes32 messageId);

    /// @notice Sends the Registrar key to the destination chain the specified bridge adapter.
    /// @param  destinationChainId The chain Id of the destination chain.
    /// @param  key                The key to send.
    /// @param  refundAddress      The refund address to receive excess native gas.
    /// @param  bridgeAdapter      The address of the bridge adapter used to send the message.
    /// @param  bridgeAdapterArgs  The optional bridge adapter arguments, could be empty.
    /// @return messageId          The ID uniquely identifying the message.
    function sendRegistrarKey(
        uint32 destinationChainId,
        bytes32 key,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) external payable returns (bytes32 messageId);

    /// @notice Sends the Registrar list status for an account to the destination chain using the default bridge adapter.
    /// @dev    Must be used for EVM Spoke chains only.
    /// @param  destinationChainId The chain Id of the destination chain.
    /// @param  listName           The name of the list.
    /// @param  account            The account.
    /// @param  refundAddress      The refund address to receive excess native gas.
    /// @param  bridgeAdapterArgs  The optional bridge adapter arguments, could be empty.
    /// @return messageId          The ID uniquely identifying the message.
    function sendRegistrarListStatus(
        uint32 destinationChainId,
        bytes32 listName,
        address account,
        bytes32 refundAddress,
        bytes calldata bridgeAdapterArgs
    ) external payable returns (bytes32 messageId);

    /// @notice Sends the Registrar list status for an account to the destination chain using the default specified adapter.
    /// @dev    Must be used for EVM Spoke chains only.
    /// @param  destinationChainId The chain Id of the destination chain.
    /// @param  listName           The name of the list.
    /// @param  account            The account.
    /// @param  refundAddress      The refund address to receive excess native gas.
    /// @param  bridgeAdapter      The address of the bridge adapter used to send the message.
    /// @param  bridgeAdapterArgs  The optional bridge adapter arguments, could be empty.
    /// @return messageId          The ID uniquely identifying the message.
    function sendRegistrarListStatus(
        uint32 destinationChainId,
        bytes32 listName,
        address account,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) external payable returns (bytes32 messageId);

    /// @notice Sends the SVM Earners Merkle Root to the destination chain using the default bridge adapter.
    /// @dev    Must be used for SVM Spoke chains only, will revert on destination if used for EVM Spoke chains.
    /// @param  destinationChainId The chain Id of the destination chain.
    /// @param  refundAddress      The refund address to receive excess native gas.
    /// @param  bridgeAdapterArgs  The optional bridge adapter arguments, could be empty.
    /// @return messageId          The ID uniquely identifying the message.
    function sendEarnersMerkleRoot(
        uint32 destinationChainId,
        bytes32 refundAddress,
        bytes calldata bridgeAdapterArgs
    ) external payable returns (bytes32 messageId);

    /// @notice Sends the SVM Earners Merkle Root to the destination chain using the specified bridge adapter.
    /// @dev    Must be used for SVM Spoke chains only, will revert on destination if used for EVM Spoke chains.
    /// @param  destinationChainId The chain Id of the destination chain.
    /// @param  refundAddress      The refund address to receive excess native gas.
    /// @param  bridgeAdapter      The address of the bridge adapter used to send the message.
    /// @param  bridgeAdapterArgs  The optional bridge adapter arguments, could be empty.
    /// @return messageId          The ID uniquely identifying the message.
    function sendEarnersMerkleRoot(
        uint32 destinationChainId,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) external payable returns (bytes32 messageId);

    /// @notice Enables earning for the Hub Portal if allowed by TTG.
    function enableEarning() external;

    /// @notice Disables earning for the Hub Portal if disallowed by TTG.
    function disableEarning() external;

    /// @notice Enables cross-Spoke token transfer for a specified Spoke chain.
    /// @dev    Stops tracking the principal amount of $M tokens bridged to the Spoke chain.
    ///         Must be called before calling `enableCrossSpokeTokenTransfer` in SpokePortal.
    /// @param  spokeChainId The ID of the Spoke chain.
    function enableCrossSpokeTokenTransfer(uint32 spokeChainId) external;
}

lib/m-portal-v2/evm/src/interfaces/IMTokenLike.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.34;

/// @title  IMTokenLike interface
/// @author M0 Labs
/// @notice Subset of M Token interface required for Portal contracts.
interface IMTokenLike {
    /// @notice Emitted when there is insufficient balance to decrement from `account`.
    /// @param  account     The account with insufficient balance.
    /// @param  rawBalance  The raw balance of the account.
    /// @param  amount      The amount to decrement the `rawBalance` by.
    error InsufficientBalance(address account, uint256 rawBalance, uint256 amount);

    /// @notice The current index that would be written to storage if `updateIndex` is called.
    function currentIndex() external view returns (uint128);

    /// @notice Checks if account is an earner.
    /// @param  account The account to check.
    /// @return True if account is an earner, false otherwise.
    function isEarning(address account) external view returns (bool);

    /// @notice Starts earning for caller if allowed by TTG.
    function startEarning() external;

    /// @notice Stops earning for the account.
    function stopEarning(address account) external;
}

lib/m-portal-v2/evm/src/interfaces/IMerkleTreeBuilderLike.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.34;

/// @title  IMerkleTreeBuilderLike interface
/// @author M0 Labs
/// @notice Subset of MerkleTreeBuilder interface required for Portal contracts.
interface IMerkleTreeBuilderLike {
    /// @notice Retrieves the root of the Merkle tree for a list.
    function getRoot(bytes32 list) external view returns (bytes32);
}

lib/m-portal-v2/evm/src/interfaces/IOrderBookLike.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.34;

/// @title  IOrderBookLike interface
/// @author M0 Labs
/// @notice Subset of OrderBook interface required for Portal contracts.
interface IOrderBookLike {
    /// @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 refund processing.
    /// @param orderId The ID of the order being reported
    /// @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 account
    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 orders that were cancelled
    ///         on the destination chain back to the origin chain for cleanup processing.
    /// @param orderId The ID of the order being reported
    /// @param originSender 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 origin sender
    struct CancelReport {
        bytes32 orderId;
        bytes32 originSender;
        bytes32 tokenIn;
        uint128 amountInToRefund;
    }

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

lib/m-portal-v2/evm/src/interfaces/IPortal.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.34;

import { PayloadType } from "../libraries/PayloadEncoder.sol";
import { IOrderBookLike } from "./IOrderBookLike.sol";

/// @title  IPortal interface
/// @author M0 Labs
/// @notice Subset of functions inherited by both IHubPortal and ISpokePortal.
interface IPortal {
    ///////////////////////////////////////////////////////////////////////////
    //                                 EVENTS                                //
    ///////////////////////////////////////////////////////////////////////////

    /// @notice Emitted when token is sent to a destination chain.
    /// @param  sourceToken        The address of the token on the source chain.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  destinationToken   The address of the token on the destination chain.
    /// @param  sender             The account initiated bridging of the M tokens via the Portal.
    /// @param  recipient          The account receiving tokens on destination chain.
    /// @param  amount             The amount of tokens.
    /// @param  index              The $M token index.
    /// @param  bridgeAdapter      The address of the bridge adapter used to send the message.
    /// @param  messageId          The unique ID for the sent message.
    event TokenSent(
        address indexed sourceToken,
        uint32 destinationChainId,
        bytes32 destinationToken,
        address indexed sender,
        bytes32 indexed recipient,
        uint256 amount,
        uint128 index,
        address bridgeAdapter,
        bytes32 messageId
    );

    /// @notice Emitted when token is received from a source chain.
    /// @param  sourceChainId    The ID of the source chain.
    /// @param  destinationToken The address of the token on the destination chain.
    /// @param  sender           The account sending tokens.
    /// @param  recipient        The account receiving tokens.
    /// @param  amount           The amount of tokens.
    /// @param  index            $M token index received from the source chain.
    /// @param  messageId        The unique ID of the message.
    event TokenReceived(
        uint32 sourceChainId,
        address indexed destinationToken,
        bytes32 indexed sender,
        address indexed recipient,
        uint256 amount,
        uint128 index,
        bytes32 messageId
    );

    /// @notice Emitted when a fill report is sent to a origin chain.
    /// @param destinationChainId The ID of the destination chain.
    /// @param orderId            The ID of the order being reported
    /// @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
    /// @param index              $M token index.
    /// @param bridgeAdapter      The address of the bridge adapter used to send the message.
    /// @param messageId          The unique identifier for the sent message.
    event FillReportSent(
        uint32 indexed destinationChainId,
        bytes32 indexed orderId,
        uint128 amountInToRelease,
        uint128 amountOutFilled,
        bytes32 originRecipient,
        bytes32 tokenIn,
        uint128 index,
        address bridgeAdapter,
        bytes32 messageId
    );

    /// @notice Emitted when a fill report is received from a source chain.
    /// @param sourceChainId      The ID of the source chain.
    /// @param orderId            The ID of the order being reported
    /// @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
    /// @param index              $M token index received from the source chain.
    /// @param messageId          The unique identifier for the message.
    event FillReportReceived(
        uint32 indexed sourceChainId,
        bytes32 indexed orderId,
        uint128 amountInToRelease,
        uint128 amountOutFilled,
        bytes32 originRecipient,
        bytes32 tokenIn,
        uint128 index,
        bytes32 messageId
    );

    /// @notice Emitted when a cancel report is sent to a origin chain.
    /// @param destinationChainId The ID of the destination chain.
    /// @param orderId            The ID of the order being reported.
    /// @param originSender       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 origin sender.
    /// @param index              $M token index.
    /// @param bridgeAdapter      The address of the bridge adapter used to send the message.
    /// @param messageId          The unique identifier for the sent message.
    event CancelReportSent(
        uint32 indexed destinationChainId,
        bytes32 indexed orderId,
        bytes32 originSender,
        bytes32 tokenIn,
        uint128 amountInToRefund,
        uint128 index,
        address bridgeAdapter,
        bytes32 messageId
    );

    /// @notice Emitted when an order cancel report is received from a source chain.
    /// @param sourceChainId    The ID of the source chain.
    /// @param orderId          The ID of the order being reported.
    /// @param originSender     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 origin sender.
    /// @param index            $M token index received from the source chain.
    /// @param messageId        The unique identifier for the message.
    event CancelReportReceived(
        uint32 indexed sourceChainId,
        bytes32 indexed orderId,
        bytes32 originSender,
        bytes32 tokenIn,
        uint128 amountInToRefund,
        uint128 index,
        bytes32 messageId
    );

    /// @notice Emitted when wrapping M token to the Extension token is failed on the destination.
    /// @param  destinationExtension The address of M Extension on the destination chain.
    /// @param  recipient            The account receiving tokens.
    /// @param  amount               The amount of tokens.
    event WrapFailed(address indexed destinationExtension, address indexed recipient, uint256 amount);

    /// @notice Emitted when a bridging path support status is updated.
    /// @param  sourceToken        The address of the token on the current chain.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  destinationToken   The address of the token on the destination chain.
    /// @param  supported          `True` if the token is supported, `false` otherwise.
    event SupportedBridgingPathSet(
        address indexed sourceToken, uint32 indexed destinationChainId, bytes32 indexed destinationToken, bool supported
    );

    /// @notice Emitted when the gas limit for a payload type is updated.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  payloadType        The type of payload.
    /// @param  gasLimit           The gas limit.
    event PayloadGasLimitSet(uint32 indexed destinationChainId, PayloadType indexed payloadType, uint256 gasLimit);

    /// @notice Emitted when the default bridge adapter for a destination chain is set.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  bridgeAdapter      The address of the bridge adapter.
    event DefaultBridgeAdapterSet(uint32 indexed destinationChainId, address indexed bridgeAdapter);

    /// @notice Emitted when a supported bridge adapter for a destination chain is set.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  bridgeAdapter      The address of the bridge adapter.
    /// @param  supported          `True` if the bridge adapter is supported, `false` otherwise.
    event SupportedBridgeAdapterSet(uint32 indexed destinationChainId, address indexed bridgeAdapter, bool supported);

    /// @notice Emitted when sending is paused.
    event SendPaused();

    /// @notice Emitted when sending is unpaused.
    event SendUnpaused();

    /// @notice Emitted when receiving is paused.
    event ReceivePaused();

    /// @notice Emitted when receiving is unpaused.
    event ReceiveUnpaused();

    ///////////////////////////////////////////////////////////////////////////
    //                             CUSTOM ERRORS                             //
    ///////////////////////////////////////////////////////////////////////////

    /// @notice Thrown when the M token is 0x0.
    error ZeroMToken();

    /// @notice Thrown when the Wrapped M token is 0x0.
    error ZeroWrappedMToken();

    /// @notice Thrown when the Registrar address is 0x0.
    error ZeroRegistrar();

    /// @notice Thrown when the Swap Facility address is 0x0.
    error ZeroSwapFacility();

    /// @notice Thrown when the Order Book address is 0x0.
    error ZeroOrderBook();

    /// @notice Thrown when the admin address is 0x0.
    error ZeroAdmin();

    /// @notice Thrown when the pauser address is 0x0.
    error ZeroPauser();

    /// @notice Thrown when the operator address is 0x0.
    error ZeroOperator();

    /// @notice Thrown when the source token address is 0x0.
    error ZeroSourceToken();

    /// @notice Thrown when the destination token address is 0x0.
    error ZeroDestinationToken();

    /// @notice Thrown when the transfer amount is 0.
    error ZeroAmount();

    /// @notice Thrown when the refund address is 0x0.
    error ZeroRefundAddress();

    /// @notice Thrown when the recipient address is 0x0.
    error ZeroRecipient();

    /// @notice Thrown when the bridge adapter address is 0x0.
    error ZeroBridgeAdapter();

    /// @notice Thrown when `receiveMessage` function caller is not the bridge.
    error NotBridgeAdapter();

    /// @notice Thrown when `sendFillReport` function caller is not the Order Book.
    error NotOrderBook();

    /// @notice Thrown when the destination chain id is equal to the source one.
    error InvalidDestinationChain(uint32 destinationChainId);

    /// @notice Thrown in `sendToken` function when bridging path is not supported
    error UnsupportedBridgingPath(address sourceToken, uint32 destinationChainId, bytes32 destinationToken);

    /// @notice Thrown when the bridge adapter is not supported for the destination chain.
    error UnsupportedBridgeAdapter(uint32 destinationChainId, address bridgeAdapter);

    /// @notice Thrown in `sendToken` function when the actual amount received is less than the specified amount.
    error InsufficientAmountReceived(uint256 specifiedAmount, uint256 actualAmount);

    /// @notice Thrown when sending is paused.
    error SendingPaused();

    /// @notice Thrown when receiving is paused.
    error ReceivingPaused();

    /// @notice Thrown when a message with the given ID has already been processed.
    error MessageAlreadyProcessed(bytes32 messageId);

    /// @notice Thrown on the destination when the target chain ID in the payload
    ///         does not match the current chain ID.
    error InvalidTargetChain(uint32 targetChainId);

    /// @notice Thrown on the destination when the target bridge adapter in the payload
    ///         does not match the bridge adapter delivering the message.
    error InvalidTargetBridgeAdapter(bytes32 targetBridgeAdapter);

    /// @notice Thrown when the gas limit for the specified payload type is not configured.
    error PayloadGasLimitNotSet(uint32 destinationChainId, PayloadType payloadType);

    ///////////////////////////////////////////////////////////////////////////
    //                          VIEW/PURE FUNCTIONS                          //
    ///////////////////////////////////////////////////////////////////////////

    /// @notice The address of the M token.
    function mToken() external view returns (address);

    /// @notice The address of the Registrar contract.
    function registrar() external view returns (address);

    /// @notice The address of the Swap Facility contract.
    function swapFacility() external view returns (address);

    /// @notice The address of the Order Book contract.
    function orderBook() external view returns (address);

    /// @notice The ID of the chain on which the Portal contract is deployed.
    function currentChainId() external view returns (uint32);

    /// @notice Returns the current nonce used for generating unique message IDs.
    function getNonce() external view returns (uint256);

    /// @notice Returns the default bridge adapter for the given destination chain.
    /// @param  destinationChainId The ID of the destination chain.
    function defaultBridgeAdapter(uint32 destinationChainId) external view returns (address);

    /// @notice Indicates whether the provided bridge adapter is supported for the destination chain.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  bridgingAdapter    The address of the bridge adapter.
    function supportedBridgeAdapter(uint32 destinationChainId, address bridgingAdapter) external view returns (bool);

    /// @notice Indicates whether the provided bridging path is supported.
    /// @param  sourceToken        The address of the token on the current chain.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  destinationToken   The address of the token on the destination chain.
    function supportedBridgingPath(address sourceToken, uint32 destinationChainId, bytes32 destinationToken) external view returns (bool);

    /// @notice Returns the gas limit required to process a message
    ///         with the specified payload type on the destination chain.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  payloadType        The type of payload.
    function payloadGasLimit(uint32 destinationChainId, PayloadType payloadType) external view returns (uint256);

    /// @notice The current index of the Portal's earning mechanism.
    function currentIndex() external view returns (uint128);

    /// @notice The address of the original caller of `sendToken` function.
    function msgSender() external view returns (address);

    /// @notice Returns the fee for delivering a cross-chain message using the default bridge adapter.
    /// @dev    The fee must be passed as msg.value when calling any function that sends a cross-chain message (e.g. `sendToken`).
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  payloadType        The payload type: TokenTransfer = 0, Index = 1, RegistrarKey = 2, RegistrarList = 3, FillReport = 4, EarnerMerkleRoot = 5, CancelReport = 6
    function quote(uint32 destinationChainId, PayloadType payloadType) external view returns (uint256);

    /// @notice Returns the fee for delivering a cross-chain message using the specified bridge adapter.
    /// @dev    The fee must be passed as msg.value when calling any function that sends a cross-chain message (e.g. `sendToken`).
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  payloadType        The payload type: TokenTransfer = 0, Index = 1, RegistrarKey = 2, RegistrarList = 3, FillReport = 4, EarnerMerkleRoot = 5, CancelReport = 6
    /// @param  bridgeAdapter      The address of the bridge adapter.
    function quote(uint32 destinationChainId, PayloadType payloadType, address bridgeAdapter) external view returns (uint256);

    /// @notice Indicates whether sending cross-chain messages is paused.
    function sendPaused() external view returns (bool);

    /// @notice Indicates whether receiving cross-chain messages is paused.
    function receivePaused() external view returns (bool);

    ///////////////////////////////////////////////////////////////////////////
    //                         INTERACTIVE FUNCTIONS                         //
    ///////////////////////////////////////////////////////////////////////////

    /// @notice Sets a bridging path support status.
    /// @param  sourceToken        The address of the token on the current chain.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  destinationToken   The address of the token on the destination chain.
    /// @param  supported          `True` if the token is supported, `false` otherwise.
    function setSupportedBridgingPath(address sourceToken, uint32 destinationChainId, bytes32 destinationToken, bool supported) external;

    /// @notice Sets the gas limit required to process a message
    ///         with the specified payload type on the destination chain.
    /// @dev    Passing `gasLimit = 0` clears the configured gas limit, which disables `quote` and
    ///         sending the payload type to the destination chain until a non-zero gas limit is set again.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  payloadType        The payload type.
    /// @param  gasLimit           The gas limit required to process the message, or 0 to unset it.
    function setPayloadGasLimit(uint32 destinationChainId, PayloadType payloadType, uint256 gasLimit) external;

    /// @notice Sets the default bridge adapter for a destination chain.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  bridgeAdapter      The address of the bridge adapter.
    function setDefaultBridgeAdapter(uint32 destinationChainId, address bridgeAdapter) external;

    /// @notice Sets a supported bridge adapter for a destination chain.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  bridgeAdapter      The address of the bridge adapter.
    /// @param  supported          `True` if the bridge adapter is supported, `false` otherwise.
    function setSupportedBridgeAdapter(uint32 destinationChainId, address bridgeAdapter, bool supported) external;

    /// @notice Transfers $M Token or $M Extension to the destination chain using the default bridge adapter.
    /// @dev    If wrapping on the destination fails, the recipient will receive $M token.
    /// @param  amount             The amount of tokens to transfer.
    /// @param  sourceToken        The address of the token ($M or $M Extension) on the source chain.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  destinationToken   The address of the token ($M or $M Extension) on the destination chain.
    /// @param  recipient          The account to receive tokens.
    /// @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 unique identifier of the message sent.
    function sendToken(
        uint256 amount,
        address sourceToken,
        uint32 destinationChainId,
        bytes32 destinationToken,
        bytes32 recipient,
        bytes32 refundAddress,
        bytes calldata bridgeAdapterArgs
    ) external payable returns (bytes32 messageId);

    /// @notice Transfers $M Token or $M Extension to the destination chain using the specified bridge adapter.
    /// @dev    If wrapping on the destination fails, the recipient will receive $M token.
    /// @param  amount             The amount of tokens to transfer.
    /// @param  sourceToken        The address of the token ($M or $M Extension) on the source chain.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  destinationToken   The address of the token ($M or $M Extension) on the destination chain.
    /// @param  recipient          The account to receive tokens.
    /// @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 unique identifier of the message sent.
    function sendToken(
        uint256 amount,
        address sourceToken,
        uint32 destinationChainId,
        bytes32 destinationToken,
        bytes32 recipient,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) external payable returns (bytes32 messageId);

    /// @notice Transfers $M Token or $M Extension to the destination chain using the default bridge adapter,
    ///         approving the token transfer via an EIP-2612 permit signature.
    /// @dev    If wrapping on the destination fails, the recipient will receive $M token.
    ///         If the permit fails (e.g. it was front-run), the failure is swallowed and the transfer
    ///         proceeds using the existing allowance.
    ///         The permit is executed via M0's non-standard `permit(address,address,uint256,uint256,bytes)` overload,
    ///         not the canonical EIP-2612 `permit(address,address,uint256,uint256,uint8,bytes32,bytes32)`.
    ///         To grant allowance through this function, the source token must implement this overload ($M and $M Extensions do).
    /// @param  amount             The amount of tokens to transfer.
    /// @param  sourceToken        The address of the token ($M or $M Extension) on the source chain.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  destinationToken   The address of the token ($M or $M Extension) on the destination chain.
    /// @param  recipient          The account to receive tokens.
    /// @param  refundAddress      The address to receive excess native gas on the source chain.
    /// @param  bridgeAdapterArgs  The optional bridge adapter arguments, could be empty.
    /// @param  deadline           The last timestamp where the signature is still valid.
    /// @param  signature          The signature of the EIP-2612 permit digest: either a 65-byte ECDSA signature
    ///                            encoded as `abi.encodePacked(r, s, v)`, or an ERC-1271 contract signature
    ///                            validated against the same digest.
    /// @return messageId          The unique identifier of the message sent.
    function sendTokenWithPermit(
        uint256 amount,
        address sourceToken,
        uint32 destinationChainId,
        bytes32 destinationToken,
        bytes32 recipient,
        bytes32 refundAddress,
        bytes calldata bridgeAdapterArgs,
        uint256 deadline,
        bytes calldata signature
    ) external payable returns (bytes32 messageId);

    /// @notice Transfers $M Token or $M Extension to the destination chain using the specified bridge adapter,
    ///         approving the token transfer via an EIP-2612 permit signature.
    /// @dev    If wrapping on the destination fails, the recipient will receive $M token.
    ///         If the permit fails (e.g. it was front-run), the failure is swallowed and the transfer
    ///         proceeds using the existing allowance.
    ///         The permit is executed via M0's non-standard `permit(address,address,uint256,uint256,bytes)` overload,
    ///         not the canonical EIP-2612 `permit(address,address,uint256,uint256,uint8,bytes32,bytes32)`.
    ///         To grant allowance through this function, the source token must implement this overload ($M and $M Extensions do).
    /// @param  amount             The amount of tokens to transfer.
    /// @param  sourceToken        The address of the token ($M or $M Extension) on the source chain.
    /// @param  destinationChainId The ID of the destination chain.
    /// @param  destinationToken   The address of the token ($M or $M Extension) on the destination chain.
    /// @param  recipient          The account to receive tokens.
    /// @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.
    /// @param  deadline           The last timestamp where the signature is still valid.
    /// @param  signature          The signature of the EIP-2612 permit digest: either a 65-byte ECDSA signature
    ///                            encoded as `abi.encodePacked(r, s, v)`, or an ERC-1271 contract signature
    ///                            validated against the same digest.
    /// @return messageId          The unique identifier of the message sent.
    function sendTokenWithPermit(
        uint256 amount,
        address sourceToken,
        uint32 destinationChainId,
        bytes32 destinationToken,
        bytes32 recipient,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs,
        uint256 deadline,
        bytes calldata signature
    ) external payable returns (bytes32 messageId);

    /// @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,
        IOrderBookLike.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,
        IOrderBookLike.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,
        IOrderBookLike.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,
        IOrderBookLike.CancelReport calldata report,
        bytes32 refundAddress,
        address bridgeAdapter,
        bytes calldata bridgeAdapterArgs
    ) external payable returns (bytes32 messageId);

    /// @notice Receives a message from the bridge.
    /// @param  sourceChainId The chain Id of the source chain.
    /// @param  payload       The message payload.
    function receiveMessage(uint32 sourceChainId, bytes calldata payload) external;

    /// @notice Pauses sending cross-chain messages.
    function pauseSend() external;

    /// @notice Unpauses sending cross-chain messages.
    function unpauseSend() external;

    /// @notice Pauses receiving cross-chain messages.
    function pauseReceive() external;

    /// @notice Unpauses receiving cross-chain messages.
    function unpauseReceive() external;

    /// @notice Pauses both sending and receiving cross-chain messages.
    function pauseAll() external;

    /// @notice Unpauses both sending and receiving cross-chain messages.
    function unpauseAll() external;
}

lib/m-portal-v2/evm/src/interfaces/IRegistrarLike.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.34;

/// @title  IRegistrarLike interface
/// @author M0 Labs
/// @notice Subset of Registrar interface required for Portal contracts.
interface IRegistrarLike {
    /// @notice Adds `account` to `list`.
    /// @param  list    The key for some list.
    /// @param  account The address of some account to be added.
    function addToList(bytes32 list, address account) external;

    /// @notice Removes `account` from `list`.
    /// @param  list    The key for some list.
    /// @param  account The address of some account to be removed.
    function removeFromList(bytes32 list, address account) external;

    /// @notice Sets `key` to `value`.
    /// @param  key   Some key.
    /// @param  value Some value.
    function setKey(bytes32 key, bytes32 value) external;

    /// @notice Returns the value of `key`.
    /// @param  key Some key.
    /// @return Some value.
    function get(bytes32 key) external view returns (bytes32);

    /// @notice Returns whether `list` contains `account`.
    /// @param  list    The key for some list.
    /// @param  account The address of some account.
    /// @return Whether `list` contains `account`.
    function listContains(bytes32 list, address account) external view returns (bool);

    /// @notice Returns the address of the Portal contract.
    function portal() external view returns (address);
}

lib/m-portal-v2/evm/src/interfaces/ISwapFacilityLike.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.34;

/// @title  ISwapFacilityLike interface.
/// @author M0 Labs
/// @notice Subset of SwapFacility interface required for Portal contracts.
interface ISwapFacilityLike {
    /// @notice Swaps $M token to $M Extension.
    /// @param  extensionOut The address of the M Extension to swap to.
    /// @param  amount       The amount of $M token to swap.
    /// @param  recipient    The address to receive the swapped $M Extension tokens.
    function swapInM(address extensionOut, uint256 amount, address recipient) external;

    /// @notice Swaps $M Extension to $M token.
    /// @param  extensionIn The address of the $M Extension to swap from.
    /// @param  amount      The amount of $M Extension tokens to swap.
    /// @param  recipient   The address to receive $M tokens.
    function swapOutM(address extensionIn, uint256 amount, address recipient) external;
}

lib/m-portal-v2/evm/src/libraries/BytesParser.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.34;

/// @title  BytesParser
/// @author Wormhole Labs
/// @notice Parses tightly packed data.
/// @dev    Modified from
///         https://github.com/wormhole-foundation/wormhole-solidity-sdk/blob/main/src/libraries/BytesParsing.sol
library BytesParser {
    error LengthMismatch(uint256 encodedLength, uint256 expectedLength);
    error InvalidBool(uint8 value);

    function checkLength(bytes memory encoded, uint256 expected) internal pure {
        if (encoded.length != expected) revert LengthMismatch(encoded.length, expected);
    }

    function asUint8Unchecked(bytes memory encoded, uint256 offset) internal pure returns (uint8 value, uint256 nextOffset) {
        assembly ("memory-safe") {
            nextOffset := add(offset, 1)
            value := mload(add(encoded, nextOffset))
        }
    }

    function asBoolUnchecked(bytes memory encoded, uint256 offset) internal pure returns (bool value, uint256 nextOffset) {
        uint8 uint8Value;
        (uint8Value, nextOffset) = asUint8Unchecked(encoded, offset);

        if (uint8Value & 0xfe != 0) revert InvalidBool(uint8Value);

        uint256 cleanedValue = uint256(uint8Value);
        // skip 2x iszero opcode
        assembly ("memory-safe") {
            value := cleanedValue
        }
    }

    function asUint256Unchecked(bytes memory encoded, uint256 offset) internal pure returns (uint256 value, uint256 nextOffset) {
        assembly ("memory-safe") {
            nextOffset := add(offset, 32)
            value := mload(add(encoded, nextOffset))
        }
    }

    function asUint128Unchecked(bytes memory encoded, uint256 offset) internal pure returns (uint128 value, uint256 nextOffset) {
        assembly ("memory-safe") {
            nextOffset := add(offset, 16)
            value := mload(add(encoded, nextOffset))
        }
    }

    function asUint32Unchecked(bytes memory encoded, uint256 offset) internal pure returns (uint32 value, uint256 nextOffset) {
        assembly ("memory-safe") {
            nextOffset := add(offset, 4)
            value := mload(add(encoded, nextOffset))
        }
    }

    function asBytes32Unchecked(bytes memory encoded, uint256 offset) internal pure returns (bytes32 value, uint256 nextOffset) {
        uint256 uint256Value;
        (uint256Value, nextOffset) = asUint256Unchecked(encoded, offset);
        value = bytes32(uint256Value);
    }

    function asAddressUnchecked(bytes memory encoded, uint256 offset) internal pure returns (address value, uint256 nextOffset) {
        assembly ("memory-safe") {
            nextOffset := add(offset, 20)
            value := mload(add(encoded, nextOffset))
        }
    }
}

lib/m-portal-v2/evm/src/libraries/PayloadEncoder.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.34;

import { BytesParser } from "./BytesParser.sol";
import { TypeConverter } from "./TypeConverter.sol";

enum PayloadType {
    TokenTransfer,
    Index,
    RegistrarKey,
    RegistrarList,
    FillReport,
    EarnerMerkleRoot,
    CancelReport
}

/// @title  PayloadEncoder
/// @author M0 Labs
/// @notice Encodes and decodes cross-chain message payloads.
library PayloadEncoder {
    using BytesParser for bytes;
    using TypeConverter for *;

    /// @dev All payloads have a common header structure:
    /// ┌──────────────┬──────────────────────┬──────────────────┬────────────┬───────────┬───────────────────────┐
    /// │ Payload Type │ Destination Chain ID │ Destination Peer │ Message ID │ $M Index  │ Payload Specific Data │
    /// │   (uint8)    │       (uint32)       │    (bytes32)     │  (bytes32) │ (uint128) │      (variable)       │
    /// │   1 byte     │       4 bytes        │    32 bytes      │  32 bytes  │ 16 bytes  │         ...           │
    /// └──────────────┴──────────────────────┴──────────────────┴────────────┴───────────┴───────────────────────┘
    uint256 internal constant PAYLOAD_TYPE_LENGTH = 1;
    uint256 internal constant DESTINATION_CHAIN_ID_LENGTH = 4;
    uint256 internal constant DESTINATION_PEER_LENGTH = 32;
    uint256 internal constant MESSAGE_ID_LENGTH = 32;
    uint256 internal constant INDEX_LENGTH = 16;
    uint256 internal constant HEADER_LENGTH =
        PAYLOAD_TYPE_LENGTH + DESTINATION_CHAIN_ID_LENGTH + DESTINATION_PEER_LENGTH + MESSAGE_ID_LENGTH + INDEX_LENGTH;
    uint256 internal constant OFFSET = PAYLOAD_TYPE_LENGTH + DESTINATION_CHAIN_ID_LENGTH + DESTINATION_PEER_LENGTH;

    error InvalidPayloadLength(uint256 length);
    error InvalidPayloadType(uint8 value);

    /// @notice Decodes the payload type from the payload.
    /// @param  payload The payload to decode.
    function decodePayloadType(bytes memory payload) internal pure returns (PayloadType) {
        if (payload.length < HEADER_LENGTH) revert InvalidPayloadLength(payload.length);

        uint8 payloadType;
        (payloadType,) = payload.asUint8Unchecked(0);

        if (payloadType > uint8(type(PayloadType).max)) revert InvalidPayloadType(payloadType);
        return PayloadType(payloadType);
    }

    /// @notice Decodes the destination ID and peer from the payload.
    /// @param  payload            The payload to decode.
    /// @return destinationChainId The destination chain ID.
    /// @return destinationPeer    The address of the peer bridge adapter on the destination chain.
    function decodeDestinationChainIdAndPeer(bytes memory payload)
        internal
        pure
        returns (uint32 destinationChainId, bytes32 destinationPeer)
    {
        if (payload.length < HEADER_LENGTH) revert InvalidPayloadLength(payload.length);

        uint256 offset = PAYLOAD_TYPE_LENGTH;

        (destinationChainId, offset) = payload.asUint32Unchecked(offset);
        (destinationPeer, offset) = payload.asBytes32Unchecked(offset);
    }

    /// @notice Decodes the message ID from the payload.
    /// @param  payload   The payload to decode.
    /// @return messageId The message ID.
    function decodeMessageId(bytes memory payload) internal pure returns (bytes32 messageId) {
        if (payload.length < HEADER_LENGTH) revert InvalidPayloadLength(payload.length);

        (messageId,) = payload.asBytes32Unchecked(OFFSET);
    }

    /// @notice Encodes a token transfer payload.
    /// @dev    Encoded values are packed using `abi.encodePacked`.
    /// @param destinationChainId The destination chain ID.
    /// @param destinationPeer    The address of the peer bridge adapter on the destination chain.
    /// @param messageId          The message ID.
    /// @param index              The $M token index.
    /// @param amount             The amount of tokens to transfer.
    /// @param destinationToken   The address of the destination token.
    /// @param sender             The address of the sender.
    /// @param recipient          The address of the recipient.
    function encodeTokenTransfer(
        uint32 destinationChainId,
        bytes32 destinationPeer,
        bytes32 messageId,
        uint128 index,
        uint256 amount,
        bytes32 destinationToken,
        address sender,
        bytes32 recipient
    ) internal pure returns (bytes memory) {
        // Converting addresses to `bytes32` and amount to `uint128` to support non-EVM chains.
        return abi.encodePacked(
            PayloadType.TokenTransfer,
            destinationChainId,
            destinationPeer,
            messageId,
            index,
            amount.toUint128(),
            destinationToken,
            sender.toBytes32(),
            recipient
        );
    }

    /// @notice Decodes a token transfer payload.
    /// @param  payload          The payload to decode.
    /// @return messageId        The message ID.
    /// @return index            The $M token index.
    /// @return amount           The amount of tokens to transfer.
    /// @return destinationToken The address of the destination token.
    /// @return sender           The address of the sender.
    /// @return recipient        The address of the recipient.
    function decodeTokenTransfer(bytes memory payload)
        internal
        pure
        returns (bytes32 messageId, uint128 index, uint256 amount, address destinationToken, bytes32 sender, address recipient)
    {
        uint256 offset = OFFSET;
        bytes32 destinationTokenBytes32;
        bytes32 recipientBytes32;

        (messageId, offset) = payload.asBytes32Unchecked(offset);
        (index, offset) = payload.asUint128Unchecked(offset);
        (amount, offset) = payload.asUint128Unchecked(offset);
        (destinationTokenBytes32, offset) = payload.asBytes32Unchecked(offset);
        (sender, offset) = payload.asBytes32Unchecked(offset);
        (recipientBytes32, offset) = payload.asBytes32Unchecked(offset);

        destinationToken = destinationTokenBytes32.toAddress();
        recipient = recipientBytes32.toAddress();

        payload.checkLength(offset);
    }

    /// @notice Encodes $M token index payload.
    /// @param destinationChainId The destination chain ID.
    /// @param destinationPeer    The address of the peer bridge adapter on the destination chain.
    /// @param messageId          The message ID.
    /// @param index              The $M token index.
    function encodeIndex(
        uint32 destinationChainId,
        bytes32 destinationPeer,
        bytes32 messageId,
        uint128 index
    ) internal pure returns (bytes memory) {
        return abi.encodePacked(PayloadType.Index, destinationChainId, destinationPeer, messageId, index);
    }

    /// @notice Decodes $M token index payload.
    /// @param  payload   The payload to decode.
    /// @return messageId The message ID.
    /// @return index     $M token index.
    function decodeIndex(bytes memory payload) internal pure returns (bytes32 messageId, uint128 index) {
        uint256 offset = OFFSET;

        (messageId, offset) = payload.asBytes32Unchecked(offset);
        (index, offset) = payload.asUint128Unchecked(offset);

        payload.checkLength(offset);
    }

    /// @notice Encodes Registrar key-value pair payload.
    /// @param destinationChainId The destination chain ID.
    /// @param destinationPeer    The address of the peer bridge adapter on the destination chain.
    /// @param messageId          The message ID.
    /// @param index              $M token index.
    /// @param key                The Registrar key.
    /// @param value              The Registrar value.
    function encodeRegistrarKey(
        uint32 destinationChainId,
        bytes32 destinationPeer,
        bytes32 messageId,
        uint128 index,
        bytes32 key,
        bytes32 value
    ) internal pure returns (bytes memory) {
        return abi.encodePacked(PayloadType.RegistrarKey, destinationChainId, destinationPeer, messageId, index, key, value);
    }

    /// @notice Decodes Registrar key-value pair payload.
    /// @param  payload   The payload to decode.
    /// @return messageId The message ID.
    /// @return index     $M token index.
    /// @return key       The Registrar key.
    /// @return value     The Registrar value.
    function decodeRegistrarKey(bytes memory payload) internal pure returns (bytes32 messageId, uint128 index, bytes32 key, bytes32 value) {
        uint256 offset = OFFSET;

        (messageId, offset) = payload.asBytes32Unchecked(offset);
        (index, offset) = payload.asUint128Unchecked(offset);
        (key, offset) = payload.asBytes32Unchecked(offset);
        (value, offset) = payload.asBytes32Unchecked(offset);

        payload.checkLength(offset);
    }

    /// @notice Encodes Registrar list update payload.
    /// @param destinationChainId The destination chain ID.
    /// @param destinationPeer    The address of the peer bridge adapter on the destination chain.
    /// @param messageId          The message ID.
    /// @param index              $M token index.
    /// @param listName           The name of the list.
    /// @param account            The address of the account.
    /// @param add                Indicates whether to add or remove the account from the list.
    function encodeRegistrarList(
        uint32 destinationChainId,
        bytes32 destinationPeer,
        bytes32 messageId,
        uint128 index,
        bytes32 listName,
        address account,
        bool add
    ) internal pure returns (bytes memory) {
        return abi.encodePacked(PayloadType.RegistrarList, destinationChainId, destinationPeer, messageId, index, listName, account, add);
    }

    /// @notice Decodes Registrar list update payload.
    /// @param  payload   The payload to decode.
    /// @return messageId The message ID.
    /// @return index     $M token index.
    /// @return listName  The name of the list.
    /// @return account   The address of the account.
    /// @return add       Indicates whether the account was added or removed from the list.
    function decodeRegistrarList(bytes memory payload)
        internal
        pure
        returns (bytes32 messageId, uint128 index, bytes32 listName, address account, bool add)
    {
        uint256 offset = OFFSET;

        (messageId, offset) = payload.asBytes32Unchecked(offset);
        (index, offset) = payload.asUint128Unchecked(offset);
        (listName, offset) = payload.asBytes32Unchecked(offset);
        (account, offset) = payload.asAddressUnchecked(offset);
        (add, offset) = payload.asBoolUnchecked(offset);

        payload.checkLength(offset);
    }

    /// @notice Encodes OrderBook fill report payload.
    /// @param destinationChainId The destination chain ID.
    /// @param destinationPeer    The address of the peer bridge adapter on the destination chain.
    /// @param messageId          The message ID.
    /// @param index              $M token index.
    /// @param orderId            The ID of the order being reported.
    /// @param amountInToRelease  The amount of input token to release to the filler on the source chain.
    /// @param amountOutFilled    The amount of output tokens filled.
    /// @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.
    function encodeFillReport(
        uint32 destinationChainId,
        bytes32 destinationPeer,
        bytes32 messageId,
        uint128 index,
        bytes32 orderId,
        uint128 amountInToRelease,
        uint128 amountOutFilled,
        bytes32 originRecipient,
        bytes32 tokenIn
    ) internal pure returns (bytes memory) {
        return abi.encodePacked(
            PayloadType.FillReport,
            destinationChainId,
            destinationPeer,
            messageId,
            index,
            orderId,
            amountInToRelease,
            amountOutFilled,
            originRecipient,
            tokenIn
        );
    }

    /// @notice Decodes a fill report payload.
    /// @param  payload           The payload to decode.
    /// @return messageId         The message ID.
    /// @return index             $M token index.
    /// @return orderId           The ID of the order being reported.
    /// @return amountInToRelease The amount of input token to release to the filler on the source chain.
    /// @return amountOutFilled   The amount of output tokens filled.
    /// @return originRecipient   The address on the origin chain that should receive released funds.
    /// @return tokenIn           The address of the input token on the origin chain.
    function decodeFillReport(bytes memory payload)
        internal
        pure
        returns (
            bytes32 messageId,
            uint128 index,
            bytes32 orderId,
            uint128 amountInToRelease,
            uint128 amountOutFilled,
            bytes32 originRecipient,
            bytes32 tokenIn
        )
    {
        uint256 offset = OFFSET;

        (messageId, offset) = payload.asBytes32Unchecked(offset);
        (index, offset) = payload.asUint128Unchecked(offset);
        (orderId, offset) = payload.asBytes32Unchecked(offset);
        (amountInToRelease, offset) = payload.asUint128Unchecked(offset);
        (amountOutFilled, offset) = payload.asUint128Unchecked(offset);
        (originRecipient, offset) = payload.asBytes32Unchecked(offset);
        (tokenIn, offset) = payload.asBytes32Unchecked(offset);

        payload.checkLength(offset);
    }

    /// @notice Encodes Earner Merkle Root payload.
    /// @param destinationChainId The destination chain ID.
    /// @param destinationPeer    The address of the peer bridge adapter on the destination chain.
    /// @param messageId          The message ID.
    /// @param index              $M token index.
    /// @param earnerMerkleRoot   The Earner Merkle Root.
    function encodeEarnerMerkleRoot(
        uint32 destinationChainId,
        bytes32 destinationPeer,
        bytes32 messageId,
        uint128 index,
        bytes32 earnerMerkleRoot
    ) internal pure returns (bytes memory) {
        return abi.encodePacked(PayloadType.EarnerMerkleRoot, destinationChainId, destinationPeer, messageId, index, earnerMerkleRoot);
    }

    /// @notice Decodes Earner Merkle Root payload.
    /// @param  payload          The payload to decode.
    /// @return messageId        The message ID.
    /// @return index            $M token index.
    /// @return earnerMerkleRoot The Earner Merkle Root.
    function decodeEarnerMerkleRoot(bytes memory payload)
        internal
        pure
        returns (bytes32 messageId, uint128 index, bytes32 earnerMerkleRoot)
    {
        uint256 offset = OFFSET;

        (messageId, offset) = payload.asBytes32Unchecked(offset);
        (index, offset) = payload.asUint128Unchecked(offset);
        (earnerMerkleRoot, offset) = payload.asBytes32Unchecked(offset);

        payload.checkLength(offset);
    }

    /// @notice Encodes an OrderBook cancel report payload.
    /// @param destinationChainId The destination chain ID.
    /// @param destinationPeer    The address of the peer bridge adapter on the destination chain.
    /// @param messageId          The message ID.
    /// @param index              $M token index.
    /// @param orderId            The ID of the order that the cancellation is being reported for.
    /// @param orderSender        The address that originally created the order on the origin chain.
    /// @param tokenIn            The address of the input token on the origin chain.
    /// @param amountInToRefund   The amount of input token to refund to the origin sender.
    function encodeCancelReport(
        uint32 destinationChainId,
        bytes32 destinationPeer,
        bytes32 messageId,
        uint128 index,
        bytes32 orderId,
        bytes32 orderSender,
        bytes32 tokenIn,
        uint128 amountInToRefund
    ) internal pure returns (bytes memory) {
        return abi.encodePacked(
            PayloadType.CancelReport, destinationChainId, destinationPeer, messageId, index, orderId, orderSender, tokenIn, amountInToRefund
        );
    }

    /// @notice Decodes an OrderBook cancel report payload.
    /// @param  payload          The payload to decode.
    /// @return messageId        The message ID.
    /// @return index            $M token index.
    /// @return orderId          The ID of the order that the cancellation is being reported for.
    /// @return orderSender      The address that originally created the order on the origin chain.
    /// @return tokenIn          The address of the input token on the origin chain.
    /// @return amountInToRefund The amount of input token to refund to the origin sender.
    function decodeCancelReport(bytes memory payload)
        internal
        pure
        returns (bytes32 messageId, uint128 index, bytes32 orderId, bytes32 orderSender, bytes32 tokenIn, uint128 amountInToRefund)
    {
        uint256 offset = OFFSET;

        (messageId, offset) = payload.asBytes32Unchecked(offset);
        (index, offset) = payload.asUint128Unchecked(offset);
        (orderId, offset) = payload.asBytes32Unchecked(offset);
        (orderSender, offset) = payload.asBytes32Unchecked(offset);
        (tokenIn, offset) = payload.asBytes32Unchecked(offset);
        (amountInToRefund, offset) = payload.asUint128Unchecked(offset);

        payload.checkLength(offset);
    }

    /// @notice Generates a payload with empty data for the given payload type.
    /// @dev    Used for estimating gas costs for different payload types.
    function generateEmptyPayload(PayloadType payloadType) internal pure returns (bytes memory) {
        uint32 destinationChainId = 0;
        bytes32 destinationPeer = bytes32(0);
        bytes32 messageId = bytes32(0);
        uint128 index = 0;
        if (payloadType == PayloadType.TokenTransfer) {
            return encodeTokenTransfer(destinationChainId, destinationPeer, messageId, index, 0, bytes32(0), address(0), bytes32(0));
        } else if (payloadType == PayloadType.Index) {
            return encodeIndex(destinationChainId, destinationPeer, messageId, index);
        } else if (payloadType == PayloadType.RegistrarKey) {
            return encodeRegistrarKey(destinationChainId, destinationPeer, messageId, index, bytes32(0), bytes32(0));
        } else if (payloadType == PayloadType.RegistrarList) {
            return encodeRegistrarList(destinationChainId, destinationPeer, messageId, index, bytes32(0), address(0), false);
        } else if (payloadType == PayloadType.FillReport) {
            return encodeFillReport(destinationChainId, destinationPeer, messageId, index, bytes32(0), 0, 0, bytes32(0), bytes32(0));
        } else if (payloadType == PayloadType.EarnerMerkleRoot) {
            return encodeEarnerMerkleRoot(destinationChainId, destinationPeer, messageId, index, bytes32(0));
        } else if (payloadType == PayloadType.CancelReport) {
            return encodeCancelReport(destinationChainId, destinationPeer, messageId, index, bytes32(0), bytes32(0), bytes32(0), uint128(0));
        }

        revert InvalidPayloadType(uint8(payloadType));
    }
}

lib/m-portal-v2/evm/src/libraries/TypeConverter.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.34;

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

    /// @notice Thrown when a uint256 value exceeds the max uint32 value.
    error Uint32Overflow();

    /// @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 uint16, reverting if the value overflows.
    /// @param  value The uint256 value to convert.
    /// @return The uint16 representation of the value.
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) revert Uint16Overflow();
        return uint16(value);
    }

    /// @notice Converts a uint256 to uint32, reverting if the value overflows.
    /// @param  value The uint256 value to convert.
    /// @return The uint32 representation of the value.
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) revert Uint32Overflow();
        return uint32(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/m-portal-v2/evm/src/utils/ReentrancyLock.sol

// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.34;

/// @title  ReentrancyLock contract.
/// @author Uniswap Labs. Modified from https://github.com/Uniswap/v4-periphery/blob/main/src/base/ReentrancyLock.sol
/// @notice A transient reentrancy lock, that stores the caller's address as the lock
abstract contract ReentrancyLock {
    error ContractLocked();

    address internal transient _locker;

    modifier whenNotLocked() {
        if (_locker != address(0)) revert ContractLocked();
        _locker = msg.sender;
        _;
        _locker = address(0);
    }
}

lib/protocol/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/protocol/lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol

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

pragma solidity ^0.8.20;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

lib/protocol/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol

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

pragma solidity ^0.8.20;

/**
 * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

lib/protocol/lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.22;

import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This library provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit IERC1967.Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit IERC1967.AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the ERC-1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit IERC1967.BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

lib/protocol/lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

lib/protocol/lib/openzeppelin-contracts/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, bytes memory returndata) = recipient.call{value: amount}("");
        if (!success) {
            _revert(returndata);
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

lib/protocol/lib/openzeppelin-contracts/contracts/utils/Errors.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

lib/protocol/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

lib/protocol/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);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 3000,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "common/=lib/common/",
    "openzeppelin-contracts/=lib/common/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
    "safe-smart-account/=lib/safe-utils/lib/safe-smart-account/contracts/",
    "solidity-http/=lib/safe-utils/lib/solidity-http/src/",
    "solidity-stringutils/=lib/safe-utils/lib/solidity-stringutils/src/",
    "@ensdomains/=lib/evm-m-extensions/lib/uniswap-v4-periphery/lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/contracts-upgradeable/=lib/common/lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/protocol/lib/openzeppelin-contracts/contracts/",
    "@uniswap/v4-core/=lib/evm-m-extensions/lib/uniswap-v4-periphery/lib/v4-core/",
    "ds-test/=lib/safe-utils/lib/solidity-stringutils/lib/ds-test/src/",
    "erc4626-tests/=lib/protocol/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "evm-m-extensions/=lib/evm-m-extensions/",
    "forge-gas-snapshot/=lib/evm-m-extensions/lib/uniswap-v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "forge-std/=lib/forge-std/src/",
    "foundry-slack/=lib/foundry-slack/src/",
    "halmos-cheatcodes/=lib/protocol/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/evm-m-extensions/lib/uniswap-v4-periphery/lib/v4-core/node_modules/hardhat/",
    "liquidity-delivery/=lib/liquidity-delivery/",
    "m-portal-v2/=lib/m-portal-v2/",
    "openzeppelin-contracts-upgradeable/=lib/common/lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-foundry-upgrades/=lib/evm-m-extensions/lib/openzeppelin-foundry-upgrades/src/",
    "permit2/=lib/evm-m-extensions/lib/uniswap-v4-periphery/lib/permit2/",
    "protocol/=lib/protocol/",
    "safe-utils/=lib/safe-utils/src/",
    "solmate/=lib/evm-m-extensions/lib/uniswap-v4-periphery/lib/v4-core/lib/solmate/",
    "ttg/=lib/ttg/",
    "uniswap-v4-periphery/=lib/evm-m-extensions/lib/uniswap-v4-periphery/",
    "v4-core/=lib/evm-m-extensions/lib/uniswap-v4-periphery/lib/v4-core/src/",
    "wrapped-m-token/=lib/evm-m-extensions/lib/wrapped-m-token/",
    "wrapped-m/=lib/wrapped-m/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.