Skip to content
Verified contractPartialMIT

EntryLogicProxy

Address0x2ef5513ed9c44ddff9ff10b5120426cabd27c49d
Balance

0 ETH

 

Transactions

929

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 200 runs
EVM version
osaka
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,946,362
Creation transaction
0x48da50c50d…f043aecbae
Proxy implementation
0x90d4d775…b9246551EntryLogic

src/proxy/EntryLogicProxy.sol

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

import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
import {Authorization} from "../access/Authorization.sol";
import {BridgeConstants} from "../libraries/BridgeConstants.sol";
import {BridgeErrors} from "../libraries/BridgeErrors.sol";
import {BridgeEvents} from "../libraries/BridgeEvents.sol";

/**
 * @title EntryLogicProxy
 * @notice Transparent upgradeable proxy for EntryLogic contract
 * @dev This proxy maintains state variables that the implementation reads via assembly
 *
 * Storage Layout:
 * - Slot 0: _authorization (Authorization contract address)
 * - Slot 1: _storage (Storage contract address)
 * - Slot 2: _escrow (Escrow contract address)
 * - Slot 3: _entryLogic (implementation address for reference)
 * - Slot 4: _feeCollector (FeeCollector contract address)
 *
 */
contract EntryLogicProxy is TransparentUpgradeableProxy {
    // ========== STORAGE LAYOUT ==========
    // CRITICAL: These storage variables MUST be at specific slots
    // The implementation contract reads these via sload(slot) in assembly

    /// @dev Slot 0: Authorization contract address
    address private _authorization;

    /// @dev Slot 1: Storage contract address
    address private _storage;

    /// @dev Slot 2: Escrow contract address
    address private _escrow;

    /// @dev Slot 3: EntryLogic implementation (for reference/tracking)
    address private _entryLogic;

    /// @dev Slot 4: FeeCollector contract address
    address private _feeCollector;

    /**
     * @dev Constructor
     * @param _logic Address of the initial EntryLogic implementation
     * @param admin_ Address of the proxy admin
     * @param authorization_ Address of the Authorization contract
     * @param storage_ Address of the Storage contract
     * @param escrow_ Address of the Escrow contract
     * @param feeCollector_ Address of the FeeCollector contract
     * @param _data Initialization data to be passed to the implementation
     */
    constructor(
        address _logic,
        address admin_,
        address authorization_,
        address storage_,
        address escrow_,
        address feeCollector_,
        bytes memory _data
    ) TransparentUpgradeableProxy(_logic, admin_, _data) {
        // Initialize storage slots that implementation will read via assembly
        _authorization = authorization_;
        _storage = storage_;
        _escrow = escrow_;
        _entryLogic = _logic;
        _feeCollector = feeCollector_;
    }

    /**
     * @dev Returns the current implementation address
     * @return implementation address
     */
    function getImplementation() external view returns (address) {
        return _implementation();
    }

    /**
     * @dev Returns the Authorization contract address (slot 0)
     */
    function getAuthorization() external view returns (address) {
        return _authorization;
    }

    /**
     * @dev Repoint the slot-0 Authorization, gated by DEFAULT_ADMIN_ROLE on the CURRENT
     *      Authorization. Mirrors `Authorized.setAuthorization` on the storage contracts so all
     *      Authorization-dependent contracts can rotate in lockstep; without it this proxy's
     *      slot-0 pointer is write-once and a partial rotation would split-brain role/pause
     *      enforcement between the proxies and the storage contracts.
     */
    function setAuthorization(address newAuthorization) external {
        Authorization current = Authorization(_authorization);
        if (!current.hasRole(BridgeConstants.DEFAULT_ADMIN_ROLE, msg.sender)) {
            revert BridgeErrors.Unauthorized(msg.sender);
        }
        if (newAuthorization == address(0) || newAuthorization.code.length == 0) {
            revert BridgeErrors.InvalidAuthAddress();
        }
        address oldAuthorization = _authorization;
        _authorization = newAuthorization;
        emit BridgeEvents.AuthorizationUpdated(oldAuthorization, newAuthorization);
    }

    /**
     * @dev Returns the Storage contract address (slot 1)
     */
    function getStorage() external view returns (address) {
        return _storage;
    }

    /**
     * @dev Returns the Escrow contract address (slot 2)
     */
    function getEscrow() external view returns (address) {
        return _escrow;
    }

    /**
     * @dev Returns the FeeCollector contract address (slot 4)
     */
    function getFeeCollector() external view returns (address) {
        return _feeCollector;
    }

    /**
     * @dev Receive function to accept plain ETH transfers
     */
    receive() external payable {}
}

lib/openzeppelin-contracts/contracts/access/AccessControl.sol

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

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {IERC165, ERC165} from "../utils/introspection/ERC165.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 AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

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

    /// @inheritdoc IERC165
    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) {
        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) {
        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 {
        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) {
        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) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

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

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

pragma solidity >=0.8.4;

/**
 * @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/openzeppelin-contracts/contracts/access/Ownable.sol

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

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol

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

pragma solidity >=0.4.11;

/**
 * @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/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol

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

pragma solidity ^0.8.22;

import {Proxy} from "../Proxy.sol";
import {ERC1967Utils} from "./ERC1967Utils.sol";

/**
 * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
 * implementation address that can be changed. This address is stored in storage in the location specified by
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967], so that it doesn't conflict with the storage layout of the
 * implementation behind the proxy.
 */
contract ERC1967Proxy is Proxy {
    /**
     * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
     *
     * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
     * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
     *
     * Requirements:
     *
     * - If `data` is empty, `msg.value` must be zero.
     */
    constructor(address implementation, bytes memory _data) payable {
        ERC1967Utils.upgradeToAndCall(implementation, _data);
    }

    /**
     * @dev Returns the current implementation address.
     *
     * 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.
     * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
     */
    function _implementation() internal view virtual override returns (address) {
        return ERC1967Utils.getImplementation();
    }
}

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

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

pragma solidity ^0.8.21;

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/openzeppelin-contracts/contracts/proxy/Proxy.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (proxy/Proxy.sol)

pragma solidity ^0.8.20;

/**
 * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
 * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
 * be specified by overriding the virtual {_implementation} function.
 *
 * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
 * different contract through the {_delegate} function.
 *
 * The success and return data of the delegated call will be returned back to the caller of the proxy.
 */
abstract contract Proxy {
    /**
     * @dev Delegates the current call to `implementation`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _delegate(address implementation) internal virtual {
        assembly {
            // Copy msg.data. We take full control of memory in this inline assembly
            // block because it will not return to Solidity code. We overwrite the
            // Solidity scratch pad at memory position 0.
            calldatacopy(0x00, 0x00, calldatasize())

            // Call the implementation.
            // out and outsize are 0 because we don't know the size yet.
            let result := delegatecall(gas(), implementation, 0x00, calldatasize(), 0x00, 0x00)

            // Copy the returned data.
            returndatacopy(0x00, 0x00, returndatasize())

            switch result
            // delegatecall returns 0 on error.
            case 0 {
                revert(0x00, returndatasize())
            }
            default {
                return(0x00, returndatasize())
            }
        }
    }

    /**
     * @dev This is a virtual function that should be overridden so it returns the address to which the fallback
     * function and {_fallback} should delegate.
     */
    function _implementation() internal view virtual returns (address);

    /**
     * @dev Delegates the current call to the address returned by `_implementation()`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _fallback() internal virtual {
        _delegate(_implementation());
    }

    /**
     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
     * function in the contract matches the call data.
     */
    fallback() external payable virtual {
        _fallback();
    }
}

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

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

pragma solidity >=0.4.16;

/**
 * @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/openzeppelin-contracts/contracts/proxy/transparent/ProxyAdmin.sol

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

pragma solidity ^0.8.22;

import {ITransparentUpgradeableProxy} from "./TransparentUpgradeableProxy.sol";
import {Ownable} from "../../access/Ownable.sol";

/**
 * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
 * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
 */
contract ProxyAdmin is Ownable {
    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address,address)`
     * and `upgradeAndCall(address,address,bytes)` are present, and `upgrade` must be used if no function should be called,
     * while `upgradeAndCall` will invoke the `receive` function if the third argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeAndCall(address,address,bytes)` is present, and the third 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 Sets the initial owner who can perform upgrades.
     */
    constructor(address initialOwner) Ownable(initialOwner) {}

    /**
     * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation.
     * See {TransparentUpgradeableProxy-_dispatchUpgradeToAndCall}.
     *
     * Requirements:
     *
     * - This contract must be the admin of `proxy`.
     * - If `data` is empty, `msg.value` must be zero.
     */
    function upgradeAndCall(
        ITransparentUpgradeableProxy proxy,
        address implementation,
        bytes memory data
    ) public payable virtual onlyOwner {
        proxy.upgradeToAndCall{value: msg.value}(implementation, data);
    }
}

lib/openzeppelin-contracts/contracts/proxy/transparent/TransparentUpgradeableProxy.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (proxy/transparent/TransparentUpgradeableProxy.sol)

pragma solidity ^0.8.22;

import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";
import {ERC1967Proxy} from "../ERC1967/ERC1967Proxy.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {ProxyAdmin} from "./ProxyAdmin.sol";

/**
 * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}
 * does not implement this interface directly, and its upgradeability mechanism is implemented by an internal dispatch
 * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not
 * include them in the ABI so this interface must be used to interact with it.
 */
interface ITransparentUpgradeableProxy is IERC1967 {
    /// @dev See {UUPSUpgradeable-upgradeToAndCall}
    function upgradeToAndCall(address newImplementation, bytes calldata data) external payable;
}

/**
 * @dev This contract implements a proxy that is upgradeable through an associated {ProxyAdmin} instance.
 *
 * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
 * clashing], which can potentially be used in an attack, this contract uses the
 * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
 * things that go hand in hand:
 *
 * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
 * that call matches the {ITransparentUpgradeableProxy-upgradeToAndCall} function exposed by the proxy itself.
 * 2. If the admin calls the proxy, it can call the `upgradeToAndCall` function, but any other call won't be forwarded to
 * the implementation. If the admin tries to call a function on the implementation it will fail with an error indicating
 * the proxy admin cannot fallback to the target implementation.
 *
 * These properties mean that the admin account can only be used for upgrading the proxy, so it's best if it's a
 * dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to
 * call a function from the proxy implementation. For this reason, the proxy deploys an instance of {ProxyAdmin} and
 * allows upgrades only if they come through it. You should think of the `ProxyAdmin` instance as the administrative
 * interface of the proxy, including the ability to change who can trigger upgrades by transferring ownership.
 *
 * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not
 * inherit from that interface, and instead `upgradeToAndCall` is implicitly implemented using a custom dispatch
 * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to
 * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the
 * implementation.
 *
 * NOTE: This proxy does not inherit from {Context} deliberately. The {ProxyAdmin} of this contract won't send a
 * meta-transaction in any way, and any other meta-transaction setup should be made in the implementation contract.
 *
 * IMPORTANT: This contract avoids unnecessary storage reads by setting the admin only during construction as an
 * immutable variable, preventing any changes thereafter. However, the admin slot defined in ERC-1967 can still be
 * overwritten by the implementation logic pointed to by this proxy. In such cases, the contract may end up in an
 * undesirable state where the admin slot is different from the actual admin. Relying on the value of the admin slot
 * is generally fine if the implementation is trusted.
 *
 * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the
 * compiler will not check that there are no selector conflicts, due to the note above. A selector clash between any new
 * function and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This
 * could render the `upgradeToAndCall` function inaccessible, preventing upgradeability and compromising transparency.
 */
contract TransparentUpgradeableProxy is ERC1967Proxy {
    // An immutable address for the admin to avoid unnecessary SLOADs before each call
    // at the expense of removing the ability to change the admin once it's set.
    // This is acceptable if the admin is always a ProxyAdmin instance or similar contract
    // with its own ability to transfer the permissions to another account.
    address private immutable _admin;

    /**
     * @dev The proxy caller is the current admin, and can't fallback to the proxy target.
     */
    error ProxyDeniedAdminAccess();

    /**
     * @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`,
     * backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in
     * {ERC1967Proxy-constructor}.
     */
    constructor(address _logic, address initialOwner, bytes memory _data) payable ERC1967Proxy(_logic, _data) {
        _admin = address(new ProxyAdmin(initialOwner));
        // Set the storage value and emit an event for ERC-1967 compatibility
        ERC1967Utils.changeAdmin(_proxyAdmin());
    }

    /**
     * @dev Returns the admin of this proxy.
     */
    function _proxyAdmin() internal view virtual returns (address) {
        return _admin;
    }

    /**
     * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior.
     */
    function _fallback() internal virtual override {
        if (msg.sender == _proxyAdmin()) {
            if (msg.sig != ITransparentUpgradeableProxy.upgradeToAndCall.selector) {
                revert ProxyDeniedAdminAccess();
            } else {
                _dispatchUpgradeToAndCall();
            }
        } else {
            super._fallback();
        }
    }

    /**
     * @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}.
     *
     * Requirements:
     *
     * - If `data` is empty, `msg.value` must be zero.
     */
    function _dispatchUpgradeToAndCall() private {
        (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));
        ERC1967Utils.upgradeToAndCall(newImplementation, data);
    }
}

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

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

pragma solidity ^0.8.20;

import {Errors} from "./Errors.sol";
import {LowLevelCall} from "./LowLevelCall.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);
        }
        if (LowLevelCall.callNoReturn(recipient, amount, "")) {
            // call successful, nothing to do
            return;
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @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 = LowLevelCall.callNoReturn(target, value, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @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 = LowLevelCall.staticcallNoReturn(target, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @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 = LowLevelCall.delegatecallNoReturn(target, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @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.
     *
     * NOTE: This function is DEPRECATED and may be removed in the next major release.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        // 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 (success && (returndata.length > 0 || target.code.length > 0)) {
            return returndata;
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (returndata.length > 0) {
            LowLevelCall.bubbleRevert(returndata);
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @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) {
            return returndata;
        } else if (returndata.length > 0) {
            LowLevelCall.bubbleRevert(returndata);
        } else {
            revert Errors.FailedCall();
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Context.sol

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

pragma solidity ^0.8.20;

/**
 * @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 Context {
    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/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/openzeppelin-contracts/contracts/utils/LowLevelCall.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Library of low level call functions that implement different calling strategies to deal with the return data.
 *
 * WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
 * to use the {Address} library instead.
 */
library LowLevelCall {
    /// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
    function callNoReturn(address target, bytes memory data) internal returns (bool success) {
        return callNoReturn(target, 0, data);
    }

    /// @dev Same as {callNoReturn}, but allows to specify the value to be sent in the call.
    function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function callReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        return callReturn64Bytes(target, 0, data);
    }

    /// @dev Same as {callReturnBytes32Pair}, but allows to specify the value to be sent in the call.
    function callReturn64Bytes(
        address target,
        uint256 value,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
    function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function staticcallReturn64Bytes(
        address target,
        bytes memory data
    ) internal view returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
    function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function delegatecallReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Returns the size of the return data buffer.
    function returnDataSize() internal pure returns (uint256 size) {
        assembly ("memory-safe") {
            size := returndatasize()
        }
    }

    /// @dev Returns a buffer containing the return data from the last call.
    function returnData() internal pure returns (bytes memory result) {
        assembly ("memory-safe") {
            result := mload(0x40)
            mstore(result, returndatasize())
            returndatacopy(add(result, 0x20), 0x00, returndatasize())
            mstore(0x40, add(result, add(0x20, returndatasize())))
        }
    }

    /// @dev Revert with the return data from the last call.
    function bubbleRevert() internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            returndatacopy(fmp, 0x00, returndatasize())
            revert(fmp, returndatasize())
        }
    }

    function bubbleRevert(bytes memory returndata) internal pure {
        assembly ("memory-safe") {
            revert(add(returndata, 0x20), mload(returndata))
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Pausable.sol

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

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

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

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

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

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

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

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

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

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

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

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

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

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

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/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol

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

pragma solidity ^0.8.20;

import {IERC165} from "./IERC165.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 ERC165 is IERC165 {
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

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

pragma solidity >=0.4.16;

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

src/access/Authorization.sol

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

import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";

contract Authorization is AccessControl, Pausable {
    /**
     * @dev Constructor grants DEFAULT_ADMIN_ROLE to deployer
     * @notice Admin can grant and revoke any roles
     */
    constructor() {
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
    }

    /**
     * @dev Functions to pause and unpause the contract
     * @notice Only callable by DEFAULT_ADMIN_ROLE
     */
    function pause() external onlyRole(DEFAULT_ADMIN_ROLE) {
        _pause();
    }

    function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
        _unpause();
    }
}

src/libraries/BridgeConstants.sol

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

/**
 * @title BridgeConstants
 * @notice Central location for all constant values used across the bridge
 */
library BridgeConstants {
    // ========== ROLES ==========

    /// @dev Default admin role (from AccessControl)
    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /// @dev Role for managing storage contract
    bytes32 public constant MANAGE_STORAGE_ROLE = keccak256("MANAGE_STORAGE_ROLE");

    /// @dev Role for managing escrow contract
    bytes32 public constant MANAGE_ESCROW_ROLE = keccak256("MANAGE_ESCROW_ROLE");

    /// @dev Role for relayer registry administration (register/remove relayers, manage keys)
    bytes32 public constant RELAYER_STORAGE_ADMIN = keccak256("RELAYER_STORAGE_ADMIN");

    /// @dev Role for active set administration (submit deferred active set updates)
    bytes32 public constant ACTIVE_SET_ADMIN = keccak256("ACTIVE_SET_ADMIN");

    /// @dev Role for managing message storage
    bytes32 public constant MANAGE_MESSAGES_ROLE = keccak256("MANAGE_MESSAGES_ROLE");

    /// @dev Role for managing payload whitelist
    bytes32 public constant MANAGE_WHITELIST_ROLE = keccak256("MANAGE_WHITELIST_ROLE");

    /// @dev Role for managing nonces (granted to EntryLogicProxy)
    bytes32 public constant NONCE_MANAGER_ROLE = keccak256("NONCE_MANAGER_ROLE");

    /// @dev Role granted to RelayerRegistryLogic — only it may write to RelayerRegistryStorage
    bytes32 public constant REGISTRY_LOGIC_ROLE = keccak256("REGISTRY_LOGIC_ROLE");

    /// @dev Role granted to ActiveSetLogic — only it may write to ActiveSetStorage
    bytes32 public constant ACTIVE_SET_LOGIC_ROLE = keccak256("ACTIVE_SET_LOGIC_ROLE");
    // ========== FEE ROLES ==========

    /// @dev Role for managing fee configuration (recipients, signer, token whitelist)
    bytes32 public constant MANAGE_FEE_ROLE = keccak256("MANAGE_FEE_ROLE");

    // ========== RELAYER ID CAP ==========

    /// @dev Maximum allowed relayer ID (bitmap cap)
    uint32 public constant MAX_RELAYER_ID = 6000;

    // ========== PAYLOAD ==========

    /// @dev Maximum outbound payload size in bytes — mirrors Substrate MaxPayloadSize (ConstU32<4096>).
    ///      Keep in lockstep with the Substrate runtime bound and any destination-chain adapter.
    uint256 public constant MAX_PAYLOAD_SIZE = 4096;

    // ========== EPOCH ==========

    /// @dev Minimum allowed epoch duration in blocks
    uint256 public constant MIN_EPOCH_DURATION = 5;

    // ========== OPERATIONAL KEYS ==========

    /// @dev Maximum operational keys per relayer
    uint256 public constant MAX_OP_KEYS = 10;

    // ========== BLS PROOF OF POSSESSION ==========

    /// @dev BLS Proof of Possession domain tag
    bytes public constant BLS_POP_DOMAIN = "highway:bls-pop:v1";
}

src/libraries/BridgeErrors.sol

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

/**
 * @title BridgeErrors
 * @notice Centralized custom errors for gas-efficient error handling
 * @dev Using custom errors saves gas compared to revert strings
 */
library BridgeErrors {
    // ========== GENERAL ERRORS ==========

    error InvalidAmount();
    error Unauthorized(address caller);
    error ContractPaused();

    // ========== CHAIN ERRORS ==========

    error ChainNotRegistered(uint32 chainId);
    error ChainNotActive(uint32 chainId);
    error ChainAlreadyRegistered(uint32 chainId);
    error InvalidChainName();
    error InvalidChainId();
    error SelfChainNotAllowed(uint32 chainId);
    error NoStateChange();

    // ========== TOKEN ERRORS ==========

    error TokenConfigNotFound(address token, uint32 chainId);
    error TokenConfigAlreadyExists(address token, uint32 chainId);
    error TokenNotRegistered(uint32 tokenId);
    error TokenNotConfiguredForChain(uint32 tokenId, uint32 sourceChainId);
    error TokenAlreadyRegistered(uint32 tokenId);
    error InvalidTokenId(uint32 tokenId);
    error InvalidAmountRange();
    error MinAmountBelowDecimalFloor(uint256 minAmount, uint256 conversionFactor);
    error InvalidEscrowConfiguration();
    error InvalidBridgePair();
    error ChainHasTokenConfigs(uint32 chainId);
    error TokenHasChainConfigs(uint32 tokenId);
    error TokenNotEnabled(uint32 tokenId);
    error TokenAddressNotContract(address localAddress);

    // ========== MESSAGE ERRORS ==========

    error MessageAlreadyProcessed(bytes32 messageId);
    error InvalidMessageId(bytes32 provided, bytes32 expected);
    error AmountExceedsU128(uint256 amount);
    error CompactValueTooLarge(uint256 value);

    // ========== RELAYER BITMAP ERRORS ==========

    error BitmapTooSmall();
    error BitmapTooLarge();
    error InvalidBitmapData();
    error ActiveSetContainsUnregisteredRelayer(uint256 byteIndex);

    // ========== ESCROW ERRORS ==========

    error InvalidReceiveAddress();
    error InvalidTokenAddress();
    error InsufficientContractBalance();

    // ========== RELAYER ERRORS ==========

    error UnauthorizedActiveSetUpdate(address caller);
    error RelayerAlreadyExists(uint32 relayerId);
    error RelayerDoesNotExist(uint32 relayerId);
    error RelayerStillActive(uint32 relayerId);
    error InvalidRelayerId();
    error RelayerIdOverflow();
    error InvalidRelayerAddress();
    error InvalidBlsPublicKey();
    error EpochNotMonotonicallyIncreasing();
    error NotInRegistrationWindow();
    error NextEpochAlreadyRegistered();
    error NoActiveRelayerSets();
    error PendingSetExists();
    error InvalidEpochDuration();
    error InvalidRegistrationWindowBlocks();
    error InvalidHistoricalIndex(uint32 index);
    error EpochNotFound(uint32 epoch);
    error EpochTooFarAhead(uint32 epoch, uint32 maxAllowedEpoch);

    // Relayer identity & uniqueness errors
    error InvalidManager();
    error BlsKeyAlreadyRegistered();
    error NotRelayerManager(uint32 relayerId, address caller);
    error InvalidBeneficiary();
    error RelayerIndexNotFound();

    // BLS Proof of Possession errors
    error PopVerificationFailed();
    error InvalidPopSignature();
    error BlsKeyIsInfinity();
    error PopSignatureIsInfinity();

    // Operational key errors
    error InvalidOperationalKey();
    error OperationalKeyAlreadyExists();
    error OperationalKeyNotFound();
    error TooManyOperationalKeys();
    error CannotRemoveLastOperationalKey();
    error NoOperationalKeysProvided();
    error RelayerIdentityMismatch(uint32 expected, uint32 actual);

    // ========== ROUTER ERRORS ==========

    error InvalidAuthAddress();
    error InvalidStorageAddress();
    error InvalidRegistryStorageAddress();
    error InvalidEscrowAddress();
    error InvalidLogicAddress();
    error InvalidPayloadWhitelistAddress();
    error UnknownFunction(bytes4 selector);
    error SameLogicAddress();

    // ========== ENTRY/EXECUTOR LOGIC ERRORS ==========

    error ETHTransferFailed();
    error TokenTransfersDisabled(uint32 tokenId);
    error TokenNotConfigured(address token, uint32 chainId);
    error AmountBelowMinimum(uint256 amount, uint256 minAmount);
    error AmountAboveMaximum(uint256 amount, uint256 maxAmount);
    error DecimalConversionTooSmall(uint256 sourceAmount, uint256 conversionFactor);
    error OutboundBridgingClosed();
    error InboundBridgingClosed();
    error CannotBurnNative();
    error CannotMintNative();
    error InvalidTokenTargetAddressLength(uint256 length);
    error InvalidMessageShape();
    error NoFundsAndNoPayload();
    error InvalidNetworkId();
    error PayloadCallFailed();
    error InvalidPayloadTargetAddress();
    error MintFailed();
    error InvalidSourceDecimals(uint8 sourceDecimals);
    error DecimalDeltaTooLarge(uint8 sourceDecimals, uint8 localDecimals);
    error NoPayload();
    error EscrowTransferFailed();
    error BurnFailed();
    error BurnAmountMismatch(address token, uint256 expected, uint256 actual);
    error MintAmountMismatch(address token, uint256 expected, uint256 actual);
    error MintBalanceDecreased(address token, uint256 balanceBefore, uint256 balanceAfter);

    /// @dev ERC-20 escrow transfer credited the escrow with an amount different
    ///      from `expected` (fee-on-transfer / rebasing / withholding token).
    ///      The destination chain would mint against the wrong source collateral.
    error EscrowAmountMismatch(address token, address escrow, uint256 expected, uint256 actual);

    // ========== VERIFICATION ERRORS ==========

    error EmptySignature();
    error InvalidSignatureLength();
    error InsufficientSigners(uint256 provided, uint256 required);
    error BLSVerificationFailed();
    error BlsProofExpired();
    error EpochBelowMinValid(uint32 proofEpoch, uint32 minValidEpoch);
    error EpochOutsidePinWindow(uint32 proofEpoch, uint32 currentEpoch);
    error RelayerNotInActiveSet(uint32 relayerId);
    error PubkeyCountMismatch(uint256 provided, uint256 expected);
    error PubkeyHashMismatch(uint32 relayerId);
    error ActiveSetTooSmall(uint256 activeCount, uint256 required);
    error BitmapExceedsCommitteeSize();
    error PubkeyArrayExceedsCommitteeSize();
    error CommitteeSelectionExhausted(uint256 seat, uint256 retryCap);
    error SlotNumberExceedsMaximum(uint32 slotNumber, uint256 maxSlots);

    // ========== PAYLOAD WHITELIST ERRORS ==========

    /// @dev Payload execution blocked - contract + function not whitelisted
    error PayloadNotWhitelisted(address contractAddress, bytes4 selector);

    /// @dev Invalid function selector (cannot be bytes4(0))
    error InvalidPayloadSelector();

    /// @dev Generic payload validation error
    error InvalidPayload(string reason);

    /// @dev Payload too short (must be at least 4 bytes for selector)
    error PayloadTooShort();

    /// @dev Outbound payload exceeds the maximum size accepted by the destination chain
    error PayloadTooLarge(uint256 size, uint256 max);

    /// @dev Empty selector array provided
    error EmptySelectorArray();

    /// @dev Contract already registered in whitelist
    error ContractAlreadyRegistered(address contractAddress);

    /// @dev Contract not registered in whitelist
    error ContractNotRegistered(address contractAddress);

    /// @dev Contract has whitelisted selectors and cannot be removed
    error ContractHasWhitelistedSelectors(address contractAddress);

    /// @dev Protocol-internal contract cannot be registered as a payload target
    error ProtocolInternalContract(address contractAddress);

    /// @dev A registered bridge token cannot be registered as a payload target (the executor
    ///      proxy holds mint/transfer authority over it, so a payload call would be a confused
    ///      deputy). Covers all current and future bridge tokens via the live token registry.
    error CannotWhitelistBridgeToken(address token);

    // ========== FEE ERRORS ==========

    /// @dev Fee quote TTL has expired
    error FeeQuoteExpired(uint256 ttl, uint256 currentBlock);

    /// @dev Invalid fee signature - recovered signer doesn't match
    error InvalidFeeSignature();

    /// @dev msg.value is below nativeValueForBridge + (native fee amounts)
    error IncorrectETHForFee(uint256 expected, uint256 provided);

    /// @dev Fee token is not in the supported whitelist
    error UnsupportedFeeToken(address token);

    /// @dev Native forward to an execution/platform fee recipient failed
    error ForwardFailed(address recipient);

    /// @dev ERC-20 fee transfer credited the recipient less than the signed amount
    ///      (fee-on-transfer / rebasing token). Indicates the whitelisted token
    ///      doesn't preserve the transferred amount and must be removed.
    error FeeAmountMismatch(address token, address recipient, uint256 expected, uint256 actual);
}

src/libraries/BridgeEvents.sol

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

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

/**
 * @title BridgeEvents
 * @notice Centralized event definitions for the bridge protocol
 * @dev All contracts should inherit from this or import specific events
 */
library BridgeEvents {
    // ========== MESSAGE EVENTS ==========

    event MessageProcessed(bytes32 indexed messageId);

    // ========== CHAIN MANAGEMENT EVENTS ==========

    event ChainRegistered(uint32 indexed chainId, string name, bool isActive);

    event ChainStatusUpdated(uint32 indexed chainId, bool isActive);

    event ChainRemoved(uint32 indexed chainId);

    event AuthorizationUpdated(address indexed oldAuthorization, address indexed newAuthorization);

    // ========== TOKEN MANAGEMENT EVENTS ==========

    event TokenRegistered(uint32 indexed tokenId, string symbol, string name, address localAddress, bool enabled);

    event TokenBridgeConfigured(
        uint32 indexed tokenId, uint32 indexed sourceChainId, BridgeTypes.TokenBridgeOperation indexed operation
    );

    event TokenEnabledUpdated(uint32 indexed tokenId, bool enabled);

    event TokenRemoved(uint32 indexed tokenId);

    // ========== ESCROW EVENTS ==========

    event FundsReleased(
        address indexed token, address indexed receiveAddress, uint256 amount, bytes32 indexed messageId
    );

    /// @dev Emitted when stuck funds are recovered by admin
    event FundsRecovered(address indexed token, address indexed recipient, uint256 amount, string reason);

    // ========== RELAYER EVENTS ==========

    /// @dev Carries the full BLS public key rather than its hash so indexers get the key straight
    ///      from the log — the hash is derivable from the key, but not the other way round. The
    ///      key is public by construction and already readable via `getRelayer`; the stored
    ///      `blsKeyHash` remains an on-chain index/dedup detail. Mirrors `BlsKeyUpdated`.
    event RelayerRegistered(
        uint32 indexed relayerId, address indexed manager, address indexed beneficiary, bytes blsPublicKey
    );
    event RelayerRemoved(uint32 indexed relayerId);
    event BlsKeyUpdated(uint32 indexed relayerId, bytes newKey);
    event ActiveSetUpdated(uint32 indexed epoch, uint256 startBlock, uint32 activeCount, bytes32 epochRandomness);
    event EpochDurationUpdated(uint256 oldDuration, uint256 newDuration);
    event RegistrationWindowUpdated(uint256 oldWindow, uint256 newWindow);
    event MinValidEpochUpdated(uint32 oldMinValidEpoch, uint32 newMinValidEpoch);
    event OperationalKeyAdded(uint32 indexed relayerId, address key);
    event OperationalKeyRemoved(uint32 indexed relayerId, address key);
    event BeneficiaryUpdated(uint32 indexed relayerId, address oldBeneficiary, address newBeneficiary);
    event ManagerUpdated(uint32 indexed relayerId, address oldManager, address newManager);

    // ========== ROUTER EVENTS ==========

    event EntryLogicUpdated(address indexed oldEntryLogic, address indexed newEntryLogic);

    event ExecutorLogicUpdated(address indexed oldExecutorLogic, address indexed newExecutorLogic);

    event PayloadWhitelistUpdated(address indexed oldWhitelist, address indexed newWhitelist);

    // ========== ENTRY LOGIC EVENTS ==========

    event MessageEmitted(
        bytes32 indexed messageId,
        address indexed sender,
        uint32 indexed targetChainId,
        bytes payloadTargetAddress,
        bytes payload,
        bytes tokenTargetAddress,
        uint32 tokenId,
        uint256 amount,
        uint256 blockNumber,
        uint128 nonce
    );

    // ========== EXECUTOR LOGIC EVENTS ==========

    /// @dev Always emitted for every inbound message execution
    event InboundMessageExecuted(
        bytes32 indexed messageId, uint32 indexed originChainId, uint32 relayerId, bool tokenTransferred
    );

    /// @dev Emitted when tokens are minted on inbound
    event TokenMinted(bytes32 indexed messageId, uint32 indexed tokenId, address recipient, uint256 amount);

    /// @dev Emitted when tokens are released from escrow on inbound
    event TokenReleased(bytes32 indexed messageId, uint32 indexed tokenId, address recipient, uint256 amount);

    /// @dev Emitted when a payload was executed on the target contract
    event PayloadExecuted(bytes32 indexed messageId, address indexed targetContract, bytes4 selector);

    // ========== PAYLOAD WHITELIST EVENTS ==========

    /// @dev Emitted when a contract is registered for whitelist tracking
    event ContractRegistered(address indexed contractAddress);

    /// @dev Emitted when a contract is removed from whitelist tracking
    event ContractUnregistered(address indexed contractAddress);

    /// @dev Emitted when a function is added to the whitelist
    event FunctionWhitelisted(address indexed contractAddress, bytes4 indexed selector);

    /// @dev Emitted when a function is removed from the whitelist
    event FunctionRemovedFromWhitelist(address indexed contractAddress, bytes4 indexed selector);

    /// @dev Emitted when a protocol-internal address is marked or unmarked
    event ProtocolInternalSet(address indexed target, bool internal_);

    // ========== FEE EVENTS ==========

    /// @dev Emitted when fee signer address is updated
    event FeeSignerUpdated(address indexed oldSigner, address indexed newSigner);

    /// @dev Emitted when fee validation is enabled/disabled
    event FeeValidationStatusUpdated(bool enabled);

    /// @dev Emitted when the execution-fee recipient wallet is updated
    event ExecutionRecipientUpdated(address indexed oldRecipient, address indexed newRecipient);

    /// @dev Emitted when the platform-fee recipient wallet is updated
    event PlatformRecipientUpdated(address indexed oldRecipient, address indexed newRecipient);

    /// @dev Emitted once per bridge call. Amounts are the signed values from the fee quote,
    ///      not the values actually transferred (overpayment is absorbed to the platform
    ///      recipient and does not appear here).
    event FeeCollected(
        bytes32 indexed messageId, address indexed payer, address token, uint256 executionAmount, uint256 platformAmount
    );

    /// @dev Emitted when a fee token is added to the whitelist
    event FeeTokenAdded(address indexed token);

    /// @dev Emitted when a fee token is removed from the whitelist
    event FeeTokenRemoved(address indexed token);
}

src/libraries/BridgeTypes.sol

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

/**
 * @title BridgeTypes
 * @notice Shared type definitions for the Highway Bridge Protocol
 * @dev Central location for structs, enums, and custom types used across contracts
 */
library BridgeTypes {
    // ========== ENUMS ==========

    /// @dev Bridge operation types for outbound transfers
    enum OutboundBridgeType {
        BURN, // Destroy tokens when sending (for wrapped tokens)
        ESCROW, // Lock tokens in escrow account (for native tokens)
        CLOSED // Outbound bridging disabled
    }

    /// @dev Bridge operation types for inbound transfers
    enum InboundBridgeType {
        MINT, // Create new tokens when receiving (for wrapped tokens)
        RELEASE, // Unlock from escrow when receiving (for native tokens)
        CLOSED // Inbound bridging disabled
    }

    /// @dev Lifecycle operation reported by the TokenBridgeConfigured event, so
    ///      consumers can distinguish corridor creation from deletion and partial
    ///      updates without an additional storage read.
    /// @dev Append-only: new operations must be added at the end to preserve the
    ///      on-chain meaning of existing ordinals.
    enum TokenBridgeOperation {
        CREATED, // Corridor configured for the first time
        RECONFIGURED, // Existing corridor fully replaced (decimals, directions, limits)
        LIMITS_UPDATED, // Min/max transfer limits changed
        DIRECTIONS_UPDATED, // Bridge directions/escrow changed
        REMOVED // Corridor permanently removed
    }

    // ========== STRUCTS ==========

    /// @dev Bidirectional bridge configuration.
    ///      Valid `(outbound, inbound)` pairs: (ESCROW, RELEASE), (BURN, MINT),
    ///      (ESCROW, CLOSED), (BURN, CLOSED), (CLOSED, RELEASE), (CLOSED, MINT), (CLOSED, CLOSED).
    ///      Rejected: (ESCROW, MINT), (BURN, RELEASE).
    ///      `escrow` non-zero iff `outbound == ESCROW || inbound == RELEASE`.
    struct BridgeConfiguration {
        OutboundBridgeType outbound; // How tokens leave this chain
        InboundBridgeType inbound; // How tokens arrive on this chain
        address escrow; // Shared escrow account for the corridor
    }

    /// @dev Global token information (info about token ON THIS CHAIN)
    struct GlobalTokenInfo {
        address localAddress; // 20 bytes - Token contract address on THIS chain  \
        uint32 tokenId; //  4 bytes - Highway global token ID               | slot 0 (26 bytes packed)
        uint8 localDecimals; //  1 byte  - Decimals on THIS chain                |
        bool enabled; //  1 byte  - Whether token is enabled on THIS chain/
        string symbol; // Token symbol (e.g., "USDC")                              - slot 1
        string name; // Token name (e.g., "USD Coin")                            - slot 2
    }

    /// @dev Chain-specific token configuration (how to handle tokens FROM source chain)
    /// `exists` is placed adjacent to `sourceDecimals` so they share storage slot 0
    /// (uint8 + bool = 2 bytes), avoiding an extra SSTORE on first-time writes.
    struct ChainTokenConfig {
        uint8 sourceDecimals; // Decimals on source chain
        bool exists; // Storage-only existence flag; do not set from calldata
        BridgeConfiguration bridge; // How to bridge from source chain
        uint256 minAmount; // Minimum transfer amount
        uint256 maxAmount; // Maximum transfer amount
    }

    /// @dev Caller-facing input for configureTokenBridge (no `exists` field)
    struct ChainTokenConfigInput {
        uint8 sourceDecimals;
        BridgeConfiguration bridge;
        uint256 minAmount;
        uint256 maxAmount;
    }

    /// @dev DEPRECATED: Old protocol token configuration - kept for reference only
    /// Use GlobalTokenInfo + ChainTokenConfig instead
    struct TokenConfig {
        address tokenAddress; // Local token contract address
        uint32 sourceChainId; // Source chain identifier
        bytes sourceTokenId; // Original token identifier on source chain
        uint8 sourceDecimals; // Decimals on source chain
        uint8 localDecimals; // Decimals on local chain
        bool isCanonical; // True if this is the canonical/original token
        uint256 conversionRate; // Rate for decimal conversion (if needed)
        BridgeConfiguration bridge; // Bidirectional bridge configuration
        bool enabled; // Whether transfers are enabled
        uint256 minAmount; // Minimum transfer amount
        uint256 maxAmount; // Maximum transfer amount
        string symbol; // Token symbol
        string name; // Token name
    }

    /// @dev Chain information
    struct ChainInfo {
        string name; // Human-readable chain name
        uint32 chainId; // Numeric chain identifier
        bool isActive; // Whether the chain is active for bridging
    }

    /// @dev BLS attestation proof for cross-chain message verification
    /// BLS signed message format (must match Substrate): messageId ++ ttl_LE ++ slotNumber_LE ++ relayerId_LE ++ epoch_LE
    struct BlsProof {
        bytes blsSignature; // BLS aggregated G2 signature (256 bytes uncompressed)
        uint256 signerBitmap; // Bit N = committee[N] member signed
        uint32 ttl; // TTL block number (message expires after this block)
        uint32 slotNumber; // Delivery slot number (affects committee selection)
        uint32 relayerId; // Message Relayer's ID (affects committee selection)
        uint32 epoch; // Signing epoch — committee/randomness are resolved for THIS epoch (epoch pinning)
        bytes[] blsPubkeys; // BLS public keys of signers (verified against stored hashes)
    }

    /// @dev Relayer information
    /// Storage layout (packed):
    ///   slot 0: uint32 id (4) + address manager (20) = 24 bytes
    ///   slot 1: address beneficiary (20) + bool exists (1) = 21 bytes
    ///   slot 2: bytes blsPublicKey (length slot) + data slots
    ///   slot N: bytes32 blsKeyHash (32)
    /// `exists` is placed immediately after `beneficiary` so the two sub-32-byte
    /// fields share one slot; moving it to the end would waste an entire slot.
    struct Relayer {
        uint32 id; // Unique relayer ID
        address manager; // Manager address (may be shared across relayers)
        address beneficiary; // Fee/reward recipient address (may be shared across relayers)
        bool exists; // Flag to check if relayer exists
        bytes blsPublicKey; // BLS public key (128 bytes uncompressed G1, EIP-2537 format)
        bytes32 blsKeyHash; // keccak256(blsPublicKey) for calldata verification
    }

    /// @dev Active relayer set for a specific epoch
    /// Storage layout (packed):
    ///   slot 0: uint32 epoch (4) + uint32 maxRelayerId (4) = 8 bytes
    ///   slot 1: uint256 startBlock (32)
    ///   slot 2: bytes activeBitmap (length slot) + data slots
    ///   slot N: bytes32 epochRandomness (32)
    /// `maxRelayerId` is placed adjacent to `epoch` so both uint32s share one slot;
    /// placing it after the dynamic `activeBitmap` would force it into its own slot.
    struct ActiveRelayerSet {
        uint32 epoch; // Sequential epoch number
        uint32 maxRelayerId; // Highest relayer ID ever assigned at snapshot time (for bitmap sizing)
        uint256 startBlock; // Block number at which this set becomes active
        bytes activeBitmap; // Bitmap where bit N represents if RelayerId (N+1) is active
        bytes32 epochRandomness; // Per-epoch randomness for committee selection: keccak256(drand_output || chainId)
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "osaka",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
    "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.