ETH Price: $2,791.81 (-0.55%)

Transaction Decoder

Block:
19692787 at Apr-19-2024 11:34:47 PM +UTC
Transaction Fee:
0.000429397536536696 ETH $1.20
Gas Used:
49,006 Gas / 8.762142116 Gwei

Emitted Events:

73 SendUln302.NativeFeeWithdrawn( worker=[Receiver] VerifierNetwork, receiver=[Sender] 0x21c3de23d98caddc406e3d31b25e807addf33633, amount=99000000000000000 )
74 VerifierNetwork.Withdraw( lib=SendUln302, to=[Sender] 0x21c3de23d98caddc406e3d31b25e807addf33633, amount=99000000000000000 )

Account State Difference:

  Address   Before After State Difference Code
3.312902544064671333 Eth3.312977560682314973 Eth0.00007501661764364
0x21C3de23...aDDF33633
13.595146363092935808 Eth
Nonce: 209715
13.693716965556399112 Eth
Nonce: 209716
0.098570602463463304
0xbB2Ea70C...E1372dCe1 3.047234613255690851 Eth2.948234613255690851 Eth0.099

Execution Trace

VerifierNetwork.withdrawFee( _lib=0xbB2Ea70C9E858123480642Cf96acbcCE1372dCe1, _to=0x21C3de23d98Caddc406E3d31b25e807aDDF33633, _amount=99000000000000000 )
  • SendUln302.withdrawFee( _to=0x21C3de23d98Caddc406E3d31b25e807aDDF33633, _amount=99000000000000000 )
    • EndpointV2.STATICCALL( )
    • ETH 0.099 0x21c3de23d98caddc406e3d31b25e807addf33633.CALL( )
      File 1 of 3: VerifierNetwork
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity >=0.8.0;
      struct PacketForQuote {
          address sender;
          uint32 dstEid;
          bytes message;
      }
      struct Packet {
          uint64 nonce;
          uint32 srcEid;
          address sender;
          uint32 dstEid;
          bytes32 receiver;
          bytes32 guid;
          bytes message;
      }
      struct Origin {
          uint32 srcEid;
          bytes32 sender;
          uint64 nonce;
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity >=0.8.0;
      import "./IMessageLibManager.sol";
      import "./IMessagingComposer.sol";
      import "./IMessagingChannel.sol";
      import "./IMessagingContext.sol";
      import {Origin} from "../MessagingStructs.sol";
      struct MessagingParams {
          uint32 dstEid;
          bytes32 receiver;
          bytes message;
          bytes options;
      }
      struct MessagingReceipt {
          bytes32 guid;
          uint64 nonce;
          MessagingFee fee;
      }
      struct MessagingFee {
          uint nativeFee;
          uint lzTokenFee;
      }
      interface ILayerZeroEndpointV2 is IMessageLibManager, IMessagingComposer, IMessagingChannel, IMessagingContext {
          event PacketSent(bytes encodedPayload, bytes options, address sendLibrary);
          event PacketDelivered(Origin origin, address receiver, bytes32 payloadHash);
          event PacketReceived(Origin origin, address receiver);
          event LzReceiveFailed(Origin origin, address receiver, bytes reason);
          event LayerZeroTokenSet(address token);
          function quote(
              address _sender,
              uint32 _dstEid,
              bytes calldata _message,
              bool _payInLzToken,
              bytes calldata _options
          ) external view returns (MessagingFee memory);
          function send(
              MessagingParams calldata _params,
              uint _lzTokenFee,
              address payable _refundAddress
          ) external payable returns (MessagingReceipt memory);
          function sendWithAlt(
              MessagingParams calldata _params,
              uint _lzTokenFee,
              uint _altTokenFee
          ) external returns (MessagingReceipt memory);
          function deliver(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external;
          function deliverable(Origin calldata _origin, address _receiveLib, address _receiver) external view returns (bool);
          function lzReceive(
              Origin calldata _origin,
              address _receiver,
              bytes32 _guid,
              bytes calldata _message,
              bytes calldata _extraData
          ) external payable returns (bool, bytes memory);
          // oapp can burn messages partially by calling this function with its own business logic if messages are delivered in order
          function clear(Origin calldata _origin, bytes32 _guid, bytes calldata _message) external;
          function setLayerZeroToken(address _layerZeroToken) external;
          function layerZeroToken() external view returns (address);
          function altFeeToken() external view returns (address);
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity >=0.8.0;
      import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
      import {MessagingFee, SetConfigParam} from "./ILayerZeroEndpointV2.sol";
      import {Packet, PacketForQuote} from "../MessagingStructs.sol";
      interface IMessageLib is IERC165 {
          function send(
              Packet calldata _packet,
              bytes calldata _options,
              bool _payInLzToken
          ) external returns (MessagingFee memory, bytes memory encodedPacket);
          function quote(
              PacketForQuote calldata _packet,
              bool _payInLzToken,
              bytes calldata _options
          ) external view returns (MessagingFee memory);
          function setTreasury(address _treasury) external;
          function setConfig(address _oapp, uint32 _eid, SetConfigParam[] calldata _config) external;
          function snapshotConfig(uint32[] calldata _eids, address _oapp) external;
          function resetConfig(uint32[] calldata _eids, address _oapp) external;
          function getConfig(
              uint32 _eid,
              address _oapp,
              uint32 _configType
          ) external view returns (bytes memory config, bool isDefault);
          function getDefaultConfig(uint32 _eid, uint32 _configType) external view returns (bytes memory);
          function isSupportedEid(uint32 _eid) external view returns (bool);
          function withdrawFee(address _to, uint _amount) external;
          function withdrawLzTokenFee(address _lzToken, address _to, uint _amount) external;
          // message libs of same major version are compatible
          function version() external view returns (uint64 major, uint8 minor, uint8 endpointVersion);
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity >=0.8.0;
      struct SetConfigParam {
          uint32 configType;
          bytes config;
      }
      interface IMessageLibManager {
          struct Timeout {
              address lib;
              uint expiry;
          }
          event LibraryRegistered(address newLib);
          event DefaultSendLibrarySet(uint32 eid, address newLib);
          event DefaultReceiveLibrarySet(uint32 eid, address oldLib, address newLib);
          event DefaultReceiveLibraryTimeoutSet(uint32 eid, address oldLib, uint expiry);
          event SendLibrarySet(address sender, uint32 eid, address newLib);
          event ReceiveLibrarySet(address receiver, uint32 eid, address oldLib, address newLib);
          event ReceiveLibraryTimoutSet(address receiver, uint32 eid, address oldLib, uint timeout);
          function registerLibrary(address _lib) external;
          function isRegisteredLibrary(address _lib) external view returns (bool);
          function getRegisteredLibraries() external view returns (address[] memory);
          function setDefaultSendLibrary(uint32 _eid, address _newLib) external;
          function defaultSendLibrary(uint32 _eid) external view returns (address);
          function setDefaultReceiveLibrary(uint32 _eid, address _newLib, uint _timeout) external;
          function defaultReceiveLibrary(uint32 _eid) external view returns (address);
          function setDefaultReceiveLibraryTimeout(uint32 _eid, address _lib, uint _expiry) external;
          function defaultReceiveLibraryTimeout(uint32 _eid) external view returns (address lib, uint expiry);
          function defaultConfig(address _lib, uint32 _eid, uint32 _configType) external view returns (bytes memory);
          function isSupportedEid(uint32 _eid) external view returns (bool);
          /// ------------------- OApp interfaces -------------------
          function setSendLibrary(uint32 _eid, address _newLib) external;
          function getSendLibrary(address _sender, uint32 _eid) external view returns (address lib);
          function isDefaultSendLibrary(address _sender, uint32 _eid) external view returns (bool);
          function setReceiveLibrary(uint32 _eid, address _newLib, uint _gracePeriod) external;
          function getReceiveLibrary(address _receiver, uint32 _eid) external view returns (address lib, bool isDefault);
          function setReceiveLibraryTimeout(uint32 _eid, address _lib, uint _gracePeriod) external;
          function receiveLibraryTimeout(address _receiver, uint32 _eid) external view returns (address lib, uint expiry);
          function setConfig(address _lib, uint32 _eid, SetConfigParam[] calldata _params) external;
          function getConfig(
              address _oapp,
              address _lib,
              uint32 _eid,
              uint32 _configType
          ) external view returns (bytes memory config, bool isDefault);
          function snapshotConfig(address _lib, uint32[] calldata _eids) external;
          function resetConfig(address _lib, uint32[] calldata _eids) external;
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity >=0.8.0;
      interface IMessagingChannel {
          event InboundNonceSkipped(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce);
          function eid() external view returns (uint32);
          // this is an emergency function if a message can not be delivered for some reasons
          // required to provide _nextNonce to avoid race condition
          function skip(uint32 _srcEid, bytes32 _sender, uint64 _nonce) external;
          function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32);
          function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
          function outboundNonce(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (uint64);
          function inboundPayloadHash(
              address _receiver,
              uint32 _srcEid,
              bytes32 _sender,
              uint64 _nonce
          ) external view returns (bytes32);
          function hasPayloadHash(
              address _receiver,
              uint32 _srcEid,
              bytes32 _sender,
              uint64 _nonce
          ) external view returns (bool);
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity >=0.8.0;
      interface IMessagingComposer {
          event ComposedMessageDelivered(address receiver, address composer, bytes32 guid, bytes message);
          event ComposedMessageReceived(address receiver, address composer, bytes32 guid);
          event LzComposeFailed(address receiver, address composer, bytes32 guid, bytes reason);
          function deliverComposedMessage(address _composer, bytes32 _guid, bytes calldata _message) external;
          function lzCompose(
              address _receiver,
              address _composer,
              bytes32 _guid,
              bytes calldata _message,
              bytes calldata _extraData
          ) external payable returns (bool, bytes memory);
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity >=0.8.0;
      interface IMessagingContext {
          function isSendingMessage() external view returns (bool);
          function getSendContext() external view returns (uint32, address);
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity ^0.8.0;
      library Errors {
          // Invalid Argument (http: 400)
          string internal constant INVALID_ARGUMENT = "LZ10000";
          string internal constant ONLY_REGISTERED = "LZ10001";
          string internal constant ONLY_REGISTERED_OR_DEFAULT = "LZ10002";
          string internal constant INVALID_AMOUNT = "LZ10003";
          string internal constant INVALID_NONCE = "LZ10004";
          string internal constant SAME_VALUE = "LZ10005";
          string internal constant UNSORTED = "LZ10006";
          string internal constant INVALID_VERSION = "LZ10007";
          string internal constant INVALID_EID = "LZ10008";
          string internal constant INVALID_SIZE = "LZ10009";
          string internal constant ONLY_NON_DEFAULT = "LZ10010";
          string internal constant INVALID_VERIFIERS = "LZ10011";
          string internal constant INVALID_WORKER_ID = "LZ10012";
          string internal constant DUPLICATED_OPTION = "LZ10013";
          string internal constant INVALID_LEGACY_OPTION = "LZ10014";
          string internal constant INVALID_VERIFIER_OPTION = "LZ10015";
          string internal constant INVALID_WORKER_OPTIONS = "LZ10016";
          string internal constant INVALID_EXECUTOR_OPTION = "LZ10017";
          string internal constant INVALID_ADDRESS = "LZ10018";
          // Out of Range (http: 400)
          string internal constant OUT_OF_RANGE = "LZ20000";
          // Invalid State (http: 400)
          string internal constant INVALID_STATE = "LZ30000";
          string internal constant SEND_REENTRANCY = "LZ30001";
          string internal constant RECEIVE_REENTRANCY = "LZ30002";
          string internal constant COMPOSE_REENTRANCY = "LZ30003";
          // Permission Denied (http: 403)
          string internal constant PERMISSION_DENIED = "LZ50000";
          // Not Found (http: 404)
          string internal constant NOT_FOUND = "LZ60000";
          // Already Exists (http: 409)
          string internal constant ALREADY_EXISTS = "LZ80000";
          // Not Implemented (http: 501)
          string internal constant NOT_IMPLEMENTED = "LZC0000";
          string internal constant UNSUPPORTED_INTERFACE = "LZC0001";
          string internal constant UNSUPPORTED_OPTION_TYPE = "LZC0002";
          // Unavailable (http: 503)
          string internal constant UNAVAILABLE = "LZD0000";
          string internal constant NATIVE_COIN_UNAVAILABLE = "LZD0001";
          string internal constant TOKEN_UNAVAILABLE = "LZD0002";
          string internal constant DEFAULT_LIBRARY_UNAVAILABLE = "LZD0003";
          string internal constant VERIFIERS_UNAVAILABLE = "LZD0004";
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity >=0.8.0;
      interface ILayerZeroUltraLightNodeV2 {
          // Relayer functions
          function validateTransactionProof(
              uint16 _srcChainId,
              address _dstAddress,
              uint _gasLimit,
              bytes32 _lookupHash,
              bytes32 _blockData,
              bytes calldata _transactionProof
          ) external;
          // an Oracle delivers the block data using updateHash()
          function updateHash(uint16 _srcChainId, bytes32 _lookupHash, uint _confirmations, bytes32 _blockData) external;
          // can only withdraw the receivable of the msg.sender
          function withdrawNative(address payable _to, uint _amount) external;
          function withdrawZRO(address _to, uint _amount) external;
          // view functions
          function getAppConfig(
              uint16 _remoteChainId,
              address _userApplicationAddress
          ) external view returns (ApplicationConfiguration memory);
          function accruedNativeFee(address _address) external view returns (uint);
          struct ApplicationConfiguration {
              uint16 inboundProofLibraryVersion;
              uint64 inboundBlockConfirmations;
              address relayer;
              uint16 outboundProofType;
              uint64 outboundBlockConfirmations;
              address oracle;
          }
          event HashReceived(
              uint16 indexed srcChainId,
              address indexed oracle,
              bytes32 lookupHash,
              bytes32 blockData,
              uint confirmations
          );
          event RelayerParams(bytes adapterParams, uint16 outboundProofType);
          event Packet(bytes payload);
          event InvalidDst(
              uint16 indexed srcChainId,
              bytes srcAddress,
              address indexed dstAddress,
              uint64 nonce,
              bytes32 payloadHash
          );
          event PacketReceived(
              uint16 indexed srcChainId,
              bytes srcAddress,
              address indexed dstAddress,
              uint64 nonce,
              bytes32 payloadHash
          );
          event AppConfigUpdated(address indexed userApplication, uint indexed configType, bytes newConfig);
          event AddInboundProofLibraryForChain(uint16 indexed chainId, address lib);
          event EnableSupportedOutboundProof(uint16 indexed chainId, uint16 proofType);
          event SetChainAddressSize(uint16 indexed chainId, uint size);
          event SetDefaultConfigForChainId(
              uint16 indexed chainId,
              uint16 inboundProofLib,
              uint64 inboundBlockConfirm,
              address relayer,
              uint16 outboundProofType,
              uint64 outboundBlockConfirm,
              address oracle
          );
          event SetDefaultAdapterParamsForChainId(uint16 indexed chainId, uint16 indexed proofType, bytes adapterParams);
          event SetLayerZeroToken(address indexed tokenAddress);
          event SetRemoteUln(uint16 indexed chainId, bytes32 uln);
          event SetTreasury(address indexed treasuryAddress);
          event WithdrawZRO(address indexed msgSender, address indexed to, uint amount);
          event WithdrawNative(address indexed msgSender, address indexed to, uint amount);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)
      pragma solidity ^0.8.0;
      import "./IAccessControl.sol";
      import "../utils/Context.sol";
      import "../utils/Strings.sol";
      import "../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 => bool) members;
              bytes32 adminRole;
          }
          mapping(bytes32 => RoleData) private _roles;
          bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
          /**
           * @dev Modifier that checks that an account has a specific role. Reverts
           * with a standardized message including the required role.
           *
           * The format of the revert reason is given by the following regular expression:
           *
           *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
           *
           * _Available since v4.1._
           */
          modifier onlyRole(bytes32 role) {
              _checkRole(role);
              _;
          }
          /**
           * @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 override returns (bool) {
              return _roles[role].members[account];
          }
          /**
           * @dev Revert with a standard message if `_msgSender()` is missing `role`.
           * Overriding this function changes the behavior of the {onlyRole} modifier.
           *
           * Format of the revert message is described in {_checkRole}.
           *
           * _Available since v4.6._
           */
          function _checkRole(bytes32 role) internal view virtual {
              _checkRole(role, _msgSender());
          }
          /**
           * @dev Revert with a standard message if `account` is missing `role`.
           *
           * The format of the revert reason is given by the following regular expression:
           *
           *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
           */
          function _checkRole(bytes32 role, address account) internal view virtual {
              if (!hasRole(role, account)) {
                  revert(
                      string(
                          abi.encodePacked(
                              "AccessControl: account ",
                              Strings.toHexString(account),
                              " is missing role ",
                              Strings.toHexString(uint256(role), 32)
                          )
                      )
                  );
              }
          }
          /**
           * @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 override 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 override 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 override 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 `account`.
           *
           * May emit a {RoleRevoked} event.
           */
          function renounceRole(bytes32 role, address account) public virtual override {
              require(account == _msgSender(), "AccessControl: can only renounce roles for self");
              _revokeRole(role, account);
          }
          /**
           * @dev Grants `role` to `account`.
           *
           * If `account` had not been already granted `role`, emits a {RoleGranted}
           * event. Note that unlike {grantRole}, this function doesn't perform any
           * checks on the calling account.
           *
           * May emit a {RoleGranted} event.
           *
           * [WARNING]
           * ====
           * This function should only be called from the constructor when setting
           * up the initial roles for the system.
           *
           * Using this function in any other way is effectively circumventing the admin
           * system imposed by {AccessControl}.
           * ====
           *
           * NOTE: This function is deprecated in favor of {_grantRole}.
           */
          function _setupRole(bytes32 role, address account) internal virtual {
              _grantRole(role, account);
          }
          /**
           * @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 Grants `role` to `account`.
           *
           * Internal function without access restriction.
           *
           * May emit a {RoleGranted} event.
           */
          function _grantRole(bytes32 role, address account) internal virtual {
              if (!hasRole(role, account)) {
                  _roles[role].members[account] = true;
                  emit RoleGranted(role, account, _msgSender());
              }
          }
          /**
           * @dev Revokes `role` from `account`.
           *
           * Internal function without access restriction.
           *
           * May emit a {RoleRevoked} event.
           */
          function _revokeRole(bytes32 role, address account) internal virtual {
              if (hasRole(role, account)) {
                  _roles[role].members[account] = false;
                  emit RoleRevoked(role, account, _msgSender());
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev External interface of AccessControl declared to support ERC165 detection.
       */
      interface IAccessControl {
          /**
           * @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 signaling this.
           *
           * _Available since v3.1._
           */
          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, an admin role
           * bearer except when using {AccessControl-_setupRole}.
           */
          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 `account`.
           */
          function renounceRole(bytes32 role, address account) external;
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
      pragma solidity ^0.8.0;
      import "../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.
       *
       * By default, the owner account will be the one that deploys the contract. 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;
          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
          /**
           * @dev Initializes the contract setting the deployer as the initial owner.
           */
          constructor() {
              _transferOwnership(_msgSender());
          }
          /**
           * @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 {
              require(owner() == _msgSender(), "Ownable: caller is not the owner");
          }
          /**
           * @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 {
              require(newOwner != address(0), "Ownable: new owner is the zero address");
              _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);
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
      pragma solidity ^0.8.0;
      import "../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 {
          /**
           * @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);
          bool private _paused;
          /**
           * @dev Initializes the contract in unpaused state.
           */
          constructor() {
              _paused = false;
          }
          /**
           * @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 {
              require(!paused(), "Pausable: paused");
          }
          /**
           * @dev Throws if the contract is not paused.
           */
          function _requirePaused() internal view virtual {
              require(paused(), "Pausable: not paused");
          }
          /**
           * @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());
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
      pragma solidity ^0.8.0;
      /**
       * @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;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
      pragma solidity ^0.8.0;
      import "./math/Math.sol";
      import "./math/SignedMath.sol";
      /**
       * @dev String operations.
       */
      library Strings {
          bytes16 private constant _SYMBOLS = "0123456789abcdef";
          uint8 private constant _ADDRESS_LENGTH = 20;
          /**
           * @dev Converts a `uint256` to its ASCII `string` decimal representation.
           */
          function toString(uint256 value) internal pure returns (string memory) {
              unchecked {
                  uint256 length = Math.log10(value) + 1;
                  string memory buffer = new string(length);
                  uint256 ptr;
                  /// @solidity memory-safe-assembly
                  assembly {
                      ptr := add(buffer, add(32, length))
                  }
                  while (true) {
                      ptr--;
                      /// @solidity memory-safe-assembly
                      assembly {
                          mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                      }
                      value /= 10;
                      if (value == 0) break;
                  }
                  return buffer;
              }
          }
          /**
           * @dev Converts a `int256` to its ASCII `string` decimal representation.
           */
          function toString(int256 value) internal pure returns (string memory) {
              return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
          }
          /**
           * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
           */
          function toHexString(uint256 value) internal pure returns (string memory) {
              unchecked {
                  return toHexString(value, Math.log256(value) + 1);
              }
          }
          /**
           * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
           */
          function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
              bytes memory buffer = new bytes(2 * length + 2);
              buffer[0] = "0";
              buffer[1] = "x";
              for (uint256 i = 2 * length + 1; i > 1; --i) {
                  buffer[i] = _SYMBOLS[value & 0xf];
                  value >>= 4;
              }
              require(value == 0, "Strings: hex length insufficient");
              return string(buffer);
          }
          /**
           * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
           */
          function toHexString(address addr) internal pure returns (string memory) {
              return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
          }
          /**
           * @dev Returns true if the two strings are equal.
           */
          function equal(string memory a, string memory b) internal pure returns (bool) {
              return keccak256(bytes(a)) == keccak256(bytes(b));
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
      pragma solidity ^0.8.0;
      import "../Strings.sol";
      /**
       * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
       *
       * These functions can be used to verify that a message was signed by the holder
       * of the private keys of a given address.
       */
      library ECDSA {
          enum RecoverError {
              NoError,
              InvalidSignature,
              InvalidSignatureLength,
              InvalidSignatureS,
              InvalidSignatureV // Deprecated in v4.8
          }
          function _throwError(RecoverError error) private pure {
              if (error == RecoverError.NoError) {
                  return; // no error: do nothing
              } else if (error == RecoverError.InvalidSignature) {
                  revert("ECDSA: invalid signature");
              } else if (error == RecoverError.InvalidSignatureLength) {
                  revert("ECDSA: invalid signature length");
              } else if (error == RecoverError.InvalidSignatureS) {
                  revert("ECDSA: invalid signature 's' value");
              }
          }
          /**
           * @dev Returns the address that signed a hashed message (`hash`) with
           * `signature` or error string. This address can then be used for verification purposes.
           *
           * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
           * this function rejects them by requiring the `s` value to be in the lower
           * half order, and the `v` value to be either 27 or 28.
           *
           * IMPORTANT: `hash` _must_ be the result of a hash operation for the
           * verification to be secure: it is possible to craft signatures that
           * recover to arbitrary addresses for non-hashed data. A safe way to ensure
           * this is by receiving a hash of the original message (which may otherwise
           * be too long), and then calling {toEthSignedMessageHash} on it.
           *
           * Documentation for signature generation:
           * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
           * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
           *
           * _Available since v4.3._
           */
          function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
              if (signature.length == 65) {
                  bytes32 r;
                  bytes32 s;
                  uint8 v;
                  // ecrecover takes the signature parameters, and the only way to get them
                  // currently is to use assembly.
                  /// @solidity memory-safe-assembly
                  assembly {
                      r := mload(add(signature, 0x20))
                      s := mload(add(signature, 0x40))
                      v := byte(0, mload(add(signature, 0x60)))
                  }
                  return tryRecover(hash, v, r, s);
              } else {
                  return (address(0), RecoverError.InvalidSignatureLength);
              }
          }
          /**
           * @dev Returns the address that signed a hashed message (`hash`) with
           * `signature`. This address can then be used for verification purposes.
           *
           * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
           * this function rejects them by requiring the `s` value to be in the lower
           * half order, and the `v` value to be either 27 or 28.
           *
           * IMPORTANT: `hash` _must_ be the result of a hash operation for the
           * verification to be secure: it is possible to craft signatures that
           * recover to arbitrary addresses for non-hashed data. A safe way to ensure
           * this is by receiving a hash of the original message (which may otherwise
           * be too long), and then calling {toEthSignedMessageHash} on it.
           */
          function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
              (address recovered, RecoverError error) = tryRecover(hash, signature);
              _throwError(error);
              return recovered;
          }
          /**
           * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
           *
           * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
           *
           * _Available since v4.3._
           */
          function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
              bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
              uint8 v = uint8((uint256(vs) >> 255) + 27);
              return tryRecover(hash, v, r, s);
          }
          /**
           * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
           *
           * _Available since v4.2._
           */
          function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
              (address recovered, RecoverError error) = tryRecover(hash, r, vs);
              _throwError(error);
              return recovered;
          }
          /**
           * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
           * `r` and `s` signature fields separately.
           *
           * _Available since v4.3._
           */
          function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
              // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
              // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
              // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
              // signatures from current libraries generate a unique signature with an s-value in the lower half order.
              //
              // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
              // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
              // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
              // these malleable signatures as well.
              if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
                  return (address(0), RecoverError.InvalidSignatureS);
              }
              // If the signature is valid (and not malleable), return the signer address
              address signer = ecrecover(hash, v, r, s);
              if (signer == address(0)) {
                  return (address(0), RecoverError.InvalidSignature);
              }
              return (signer, RecoverError.NoError);
          }
          /**
           * @dev Overload of {ECDSA-recover} that receives the `v`,
           * `r` and `s` signature fields separately.
           */
          function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
              (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
              _throwError(error);
              return recovered;
          }
          /**
           * @dev Returns an Ethereum Signed Message, created from a `hash`. This
           * produces hash corresponding to the one signed with the
           * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
           * JSON-RPC method as part of EIP-191.
           *
           * See {recover}.
           */
          function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
              // 32 is the length in bytes of hash,
              // enforced by the type signature above
              /// @solidity memory-safe-assembly
              assembly {
                  mstore(0x00, "\\x19Ethereum Signed Message:\
      32")
                  mstore(0x1c, hash)
                  message := keccak256(0x00, 0x3c)
              }
          }
          /**
           * @dev Returns an Ethereum Signed Message, created from `s`. This
           * produces hash corresponding to the one signed with the
           * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
           * JSON-RPC method as part of EIP-191.
           *
           * See {recover}.
           */
          function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
              return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
      ", Strings.toString(s.length), s));
          }
          /**
           * @dev Returns an Ethereum Signed Typed Data, created from a
           * `domainSeparator` and a `structHash`. This produces hash corresponding
           * to the one signed with the
           * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
           * JSON-RPC method as part of EIP-712.
           *
           * See {recover}.
           */
          function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
              /// @solidity memory-safe-assembly
              assembly {
                  let ptr := mload(0x40)
                  mstore(ptr, "\\x19\\x01")
                  mstore(add(ptr, 0x02), domainSeparator)
                  mstore(add(ptr, 0x22), structHash)
                  data := keccak256(ptr, 0x42)
              }
          }
          /**
           * @dev Returns an Ethereum Signed Data with intended validator, created from a
           * `validator` and `data` according to the version 0 of EIP-191.
           *
           * See {recover}.
           */
          function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
              return keccak256(abi.encodePacked("\\x19\\x00", validator, data));
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
      pragma solidity ^0.8.0;
      import "./IERC165.sol";
      /**
       * @dev Implementation of the {IERC165} interface.
       *
       * Contracts that want to implement ERC165 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);
       * }
       * ```
       *
       * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
       */
      abstract contract ERC165 is IERC165 {
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
              return interfaceId == type(IERC165).interfaceId;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC165 standard, as defined in the
       * https://eips.ethereum.org/EIPS/eip-165[EIP].
       *
       * 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[EIP 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);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Standard math utilities missing in the Solidity language.
       */
      library Math {
          enum Rounding {
              Down, // Toward negative infinity
              Up, // Toward infinity
              Zero // Toward zero
          }
          /**
           * @dev Returns the largest of two numbers.
           */
          function max(uint256 a, uint256 b) internal pure returns (uint256) {
              return a > b ? a : b;
          }
          /**
           * @dev Returns the smallest of two numbers.
           */
          function min(uint256 a, uint256 b) internal pure returns (uint256) {
              return a < b ? a : b;
          }
          /**
           * @dev Returns the average of two numbers. The result is rounded towards
           * zero.
           */
          function average(uint256 a, uint256 b) internal pure returns (uint256) {
              // (a + b) / 2 can overflow.
              return (a & b) + (a ^ b) / 2;
          }
          /**
           * @dev Returns the ceiling of the division of two numbers.
           *
           * This differs from standard division with `/` in that it rounds up instead
           * of rounding down.
           */
          function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
              // (a + b - 1) / b can overflow on addition, so we distribute.
              return a == 0 ? 0 : (a - 1) / b + 1;
          }
          /**
           * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
           * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
           * with further edits by Uniswap Labs also under MIT license.
           */
          function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
              unchecked {
                  // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                  // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                  // variables such that product = prod1 * 2^256 + prod0.
                  uint256 prod0; // Least significant 256 bits of the product
                  uint256 prod1; // Most significant 256 bits of the product
                  assembly {
                      let mm := mulmod(x, y, not(0))
                      prod0 := mul(x, y)
                      prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                  }
                  // Handle non-overflow cases, 256 by 256 division.
                  if (prod1 == 0) {
                      // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                      // The surrounding unchecked block does not change this fact.
                      // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                      return prod0 / denominator;
                  }
                  // Make sure the result is less than 2^256. Also prevents denominator == 0.
                  require(denominator > prod1, "Math: mulDiv overflow");
                  ///////////////////////////////////////////////
                  // 512 by 256 division.
                  ///////////////////////////////////////////////
                  // Make division exact by subtracting the remainder from [prod1 prod0].
                  uint256 remainder;
                  assembly {
                      // Compute remainder using mulmod.
                      remainder := mulmod(x, y, denominator)
                      // Subtract 256 bit number from 512 bit number.
                      prod1 := sub(prod1, gt(remainder, prod0))
                      prod0 := sub(prod0, remainder)
                  }
                  // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                  // See https://cs.stackexchange.com/q/138556/92363.
                  // Does not overflow because the denominator cannot be zero at this stage in the function.
                  uint256 twos = denominator & (~denominator + 1);
                  assembly {
                      // Divide denominator by twos.
                      denominator := div(denominator, twos)
                      // Divide [prod1 prod0] by twos.
                      prod0 := div(prod0, twos)
                      // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                      twos := add(div(sub(0, twos), twos), 1)
                  }
                  // Shift in bits from prod1 into prod0.
                  prod0 |= prod1 * twos;
                  // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                  // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                  // four bits. That is, denominator * inv = 1 mod 2^4.
                  uint256 inverse = (3 * denominator) ^ 2;
                  // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                  // in modular arithmetic, doubling the correct bits in each step.
                  inverse *= 2 - denominator * inverse; // inverse mod 2^8
                  inverse *= 2 - denominator * inverse; // inverse mod 2^16
                  inverse *= 2 - denominator * inverse; // inverse mod 2^32
                  inverse *= 2 - denominator * inverse; // inverse mod 2^64
                  inverse *= 2 - denominator * inverse; // inverse mod 2^128
                  inverse *= 2 - denominator * inverse; // inverse mod 2^256
                  // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                  // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                  // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                  // is no longer required.
                  result = prod0 * inverse;
                  return result;
              }
          }
          /**
           * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
           */
          function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
              uint256 result = mulDiv(x, y, denominator);
              if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                  result += 1;
              }
              return result;
          }
          /**
           * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
           *
           * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
           */
          function sqrt(uint256 a) internal pure returns (uint256) {
              if (a == 0) {
                  return 0;
              }
              // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
              //
              // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
              // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
              //
              // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
              // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
              // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
              //
              // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
              uint256 result = 1 << (log2(a) >> 1);
              // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
              // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
              // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
              // into the expected uint128 result.
              unchecked {
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  return min(result, a / result);
              }
          }
          /**
           * @notice Calculates sqrt(a), following the selected rounding direction.
           */
          function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
              unchecked {
                  uint256 result = sqrt(a);
                  return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
              }
          }
          /**
           * @dev Return the log in base 2, rounded down, of a positive value.
           * Returns 0 if given 0.
           */
          function log2(uint256 value) internal pure returns (uint256) {
              uint256 result = 0;
              unchecked {
                  if (value >> 128 > 0) {
                      value >>= 128;
                      result += 128;
                  }
                  if (value >> 64 > 0) {
                      value >>= 64;
                      result += 64;
                  }
                  if (value >> 32 > 0) {
                      value >>= 32;
                      result += 32;
                  }
                  if (value >> 16 > 0) {
                      value >>= 16;
                      result += 16;
                  }
                  if (value >> 8 > 0) {
                      value >>= 8;
                      result += 8;
                  }
                  if (value >> 4 > 0) {
                      value >>= 4;
                      result += 4;
                  }
                  if (value >> 2 > 0) {
                      value >>= 2;
                      result += 2;
                  }
                  if (value >> 1 > 0) {
                      result += 1;
                  }
              }
              return result;
          }
          /**
           * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
           * Returns 0 if given 0.
           */
          function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
              unchecked {
                  uint256 result = log2(value);
                  return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
              }
          }
          /**
           * @dev Return the log in base 10, rounded down, of a positive value.
           * Returns 0 if given 0.
           */
          function log10(uint256 value) internal pure returns (uint256) {
              uint256 result = 0;
              unchecked {
                  if (value >= 10 ** 64) {
                      value /= 10 ** 64;
                      result += 64;
                  }
                  if (value >= 10 ** 32) {
                      value /= 10 ** 32;
                      result += 32;
                  }
                  if (value >= 10 ** 16) {
                      value /= 10 ** 16;
                      result += 16;
                  }
                  if (value >= 10 ** 8) {
                      value /= 10 ** 8;
                      result += 8;
                  }
                  if (value >= 10 ** 4) {
                      value /= 10 ** 4;
                      result += 4;
                  }
                  if (value >= 10 ** 2) {
                      value /= 10 ** 2;
                      result += 2;
                  }
                  if (value >= 10 ** 1) {
                      result += 1;
                  }
              }
              return result;
          }
          /**
           * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
           * Returns 0 if given 0.
           */
          function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
              unchecked {
                  uint256 result = log10(value);
                  return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
              }
          }
          /**
           * @dev Return the log in base 256, rounded down, of a positive value.
           * Returns 0 if given 0.
           *
           * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
           */
          function log256(uint256 value) internal pure returns (uint256) {
              uint256 result = 0;
              unchecked {
                  if (value >> 128 > 0) {
                      value >>= 128;
                      result += 16;
                  }
                  if (value >> 64 > 0) {
                      value >>= 64;
                      result += 8;
                  }
                  if (value >> 32 > 0) {
                      value >>= 32;
                      result += 4;
                  }
                  if (value >> 16 > 0) {
                      value >>= 16;
                      result += 2;
                  }
                  if (value >> 8 > 0) {
                      result += 1;
                  }
              }
              return result;
          }
          /**
           * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
           * Returns 0 if given 0.
           */
          function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
              unchecked {
                  uint256 result = log256(value);
                  return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Standard signed math utilities missing in the Solidity language.
       */
      library SignedMath {
          /**
           * @dev Returns the largest of two signed numbers.
           */
          function max(int256 a, int256 b) internal pure returns (int256) {
              return a > b ? a : b;
          }
          /**
           * @dev Returns the smallest of two signed numbers.
           */
          function min(int256 a, int256 b) internal pure returns (int256) {
              return a < b ? a : b;
          }
          /**
           * @dev Returns the average of two signed numbers without overflow.
           * The result is rounded towards zero.
           */
          function average(int256 a, int256 b) internal pure returns (int256) {
              // Formula from the book "Hacker's Delight"
              int256 x = (a & b) + ((a ^ b) >> 1);
              return x + (int256(uint256(x) >> 255) & (a ^ b));
          }
          /**
           * @dev Returns the absolute unsigned value of a signed value.
           */
          function abs(int256 n) internal pure returns (uint256) {
              unchecked {
                  // must be unchecked in order to support `n = type(int256).min`
                  return uint256(n >= 0 ? n : -n);
              }
          }
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity ^0.8.19;
      import "@openzeppelin/contracts/access/Ownable.sol";
      import "@layerzerolabs/lz-evm-protocol-v2/contracts/libs/Errors.sol";
      import "./interfaces/ILayerZeroExecutor.sol";
      import "./interfaces/ILayerZeroTreasury.sol";
      struct WorkerOptions {
          uint8 workerId;
          bytes options;
      }
      enum DeliveryState {
          Signing,
          Deliverable,
          Delivered,
          Waiting
      }
      abstract contract MessageLibBase is Ownable {
          address internal immutable endpoint;
          uint32 internal immutable localEid;
          uint internal immutable treasuryGasCap;
          // config
          address public treasury;
          // accumulated fees for workers and treasury
          mapping(address worker => uint) public fees;
          event ExecutorFeePaid(address executor, uint fee);
          event TreasurySet(address treasury);
          // only the endpoint can call SEND() and setConfig()
          modifier onlyEndpoint() {
              require(endpoint == msg.sender, Errors.PERMISSION_DENIED);
              _;
          }
          constructor(address _endpoint, uint32 _localEid, uint _treasuryGasCap) {
              endpoint = _endpoint;
              localEid = _localEid;
              treasuryGasCap = _treasuryGasCap;
          }
          // ======================= Internal =======================
          function _assertMessageSize(uint _actual, uint _max) internal pure {
              require(_actual <= _max, Errors.INVALID_SIZE);
          }
          function _sendToExecutor(
              address _executor,
              uint32 _dstEid,
              address _sender,
              uint _msgSize,
              bytes memory _executorOptions
          ) internal returns (uint executorFee) {
              executorFee = ILayerZeroExecutor(_executor).assignJob(_dstEid, _sender, _msgSize, _executorOptions);
              if (executorFee > 0) {
                  fees[_executor] += executorFee;
              }
              emit ExecutorFeePaid(_executor, executorFee);
          }
          function _sendToTreasury(
              address _sender,
              uint32 _dstEid,
              uint _totalNativeFee,
              bool _payInLzToken
          ) internal returns (uint treasuryNativeFee, uint lzTokenFee) {
              // fee should be in lzTokenFee if payInLzToken, otherwise in native
              (treasuryNativeFee, lzTokenFee) = _quoteTreasuryFee(_sender, _dstEid, _totalNativeFee, _payInLzToken);
              // if payInLzToken, handle in messagelib / endpoint
              if (treasuryNativeFee > 0) {
                  fees[treasury] += treasuryNativeFee;
              }
          }
          function _quote(
              address _sender,
              uint32 _dstEid,
              uint _msgSize,
              bool _payInLzToken,
              bytes calldata _options
          ) internal view returns (uint, uint) {
              require(_options.length > 0, Errors.INVALID_ARGUMENT);
              (bytes memory executorOptions, WorkerOptions[] memory otherWorkerOptions) = _getExecutorAndOtherOptions(
                  _options
              );
              // quote other workers
              (uint nativeFee, address executor, uint maxMsgSize) = _quoteWorkers(_sender, _dstEid, otherWorkerOptions);
              // assert msg size
              _assertMessageSize(_msgSize, maxMsgSize);
              // quote executor
              nativeFee += ILayerZeroExecutor(executor).getFee(_dstEid, _sender, _msgSize, executorOptions);
              // quote treasury
              (uint treasuryNativeFee, uint lzTokenFee) = _quoteTreasuryFee(_sender, _dstEid, nativeFee, _payInLzToken);
              if (treasuryNativeFee > 0) {
                  nativeFee += treasuryNativeFee;
              }
              return (nativeFee, lzTokenFee);
          }
          function _quoteTreasuryFee(
              address _sender,
              uint32 _eid,
              uint _totalFee,
              bool _payInLzToken
          ) internal view returns (uint nativeFee, uint lzTokenFee) {
              if (treasury != address(0x0)) {
                  try ILayerZeroTreasury(treasury).getFee(_sender, _eid, _totalFee, _payInLzToken) returns (
                      uint treasuryFee
                  ) {
                      // success
                      if (_payInLzToken) {
                          lzTokenFee = treasuryFee;
                      } else {
                          // pay in native, make sure that the treasury fee is not higher than the cap
                          uint gasFeeEstimate = tx.gasprice * treasuryGasCap;
                          // cap is the max of total fee and gasFeeEstimate. this is to prevent apps from forcing the cap to 0.
                          uint nativeFeeCap = _totalFee > gasFeeEstimate ? _totalFee : gasFeeEstimate;
                          // to prevent the treasury from returning an overly high value to break the path
                          nativeFee = treasuryFee > nativeFeeCap ? nativeFeeCap : treasuryFee;
                      }
                  } catch {
                      // failure, something wrong with treasury contract, charge nothing and continue
                  }
              }
          }
          function _transferNative(address _to, uint _amount) internal {
              (bool success, ) = _to.call{value: _amount}("");
              require(success, Errors.INVALID_STATE);
          }
          // for msg.sender only
          function _assertAndDebitAmount(address _to, uint _amount) internal {
              uint fee = fees[msg.sender];
              require(_to != address(0x0) && _amount <= fee, Errors.INVALID_ARGUMENT);
              unchecked {
                  fees[msg.sender] = fee - _amount;
              }
          }
          function _setTreasury(address _treasury) internal {
              treasury = _treasury;
              emit TreasurySet(_treasury);
          }
          // ======================= Virtual =======================
          // For implementation to override
          function _quoteWorkers(
              address _oapp,
              uint32 _eid,
              WorkerOptions[] memory _options
          ) internal view virtual returns (uint nativeFee, address executor, uint maxMsgSize);
          function _getExecutorAndOtherOptions(
              bytes calldata _options
          ) internal view virtual returns (bytes memory executorOptions, WorkerOptions[] memory otherWorkerOptions);
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity ^0.8.19;
      import "@openzeppelin/contracts/security/Pausable.sol";
      import "@openzeppelin/contracts/access/AccessControl.sol";
      import "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessageLib.sol";
      import "./interfaces/IWorker.sol";
      abstract contract Worker is AccessControl, Pausable, IWorker {
          bytes32 internal constant MESSAGE_LIB_ROLE = keccak256("MESSAGE_LIB_ROLE");
          bytes32 internal constant ALLOWLIST = keccak256("ALLOWLIST");
          bytes32 internal constant DENYLIST = keccak256("DENYLIST");
          bytes32 internal constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
          address public workerFeeLib;
          uint64 public allowlistSize;
          uint16 public defaultMultiplierBps;
          address public priceFeed;
          // ========================= Constructor =========================
          /// @param _messageLibs array of message lib addresses that are granted the MESSAGE_LIB_ROLE
          /// @param _priceFeed price feed address
          /// @param _defaultMultiplierBps default multiplier for worker fee
          /// @param _roleAdmin address that is granted the DEFAULT_ADMIN_ROLE (can grant and revoke all roles)
          /// @param _admins array of admin addresses that are granted the ADMIN_ROLE
          constructor(
              address[] memory _messageLibs,
              address _priceFeed,
              uint16 _defaultMultiplierBps,
              address _roleAdmin,
              address[] memory _admins
          ) {
              defaultMultiplierBps = _defaultMultiplierBps;
              priceFeed = _priceFeed;
              if (_roleAdmin != address(0x0)) {
                  _grantRole(DEFAULT_ADMIN_ROLE, _roleAdmin); // _roleAdmin can grant and revoke all roles
              }
              for (uint i = 0; i < _messageLibs.length; ++i) {
                  _grantRole(MESSAGE_LIB_ROLE, _messageLibs[i]);
              }
              for (uint i = 0; i < _admins.length; ++i) {
                  _grantRole(ADMIN_ROLE, _admins[i]);
              }
          }
          // ========================= Modifier =========================
          modifier onlyAcl(address _sender) {
              require(hasAcl(_sender), "Worker: not allowed");
              _;
          }
          /// @dev Access control list using allowlist and denylist
          /// @dev 1) if one address is in the denylist -> deny
          /// @dev 2) else if address in the allowlist OR allowlist is empty (allows everyone)-> allow
          /// @dev 3) else deny
          /// @param _sender address to check
          function hasAcl(address _sender) public view returns (bool) {
              if (hasRole(DENYLIST, _sender)) {
                  return false;
              } else if (allowlistSize == 0 || hasRole(ALLOWLIST, _sender)) {
                  return true;
              } else {
                  return false;
              }
          }
          // ========================= OnyDefaultAdmin =========================
          /// @dev flag to pause execution of workers (if used with whenNotPaused modifier)
          /// @param _paused true to pause, false to unpause
          function setPaused(bool _paused) external onlyRole(DEFAULT_ADMIN_ROLE) {
              if (_paused) {
                  _pause();
              } else {
                  _unpause();
              }
          }
          // ========================= OnlyAdmin =========================
          /// @param _priceFeed price feed address
          function setPriceFeed(address _priceFeed) external onlyRole(ADMIN_ROLE) {
              priceFeed = _priceFeed;
              emit SetPriceFeed(_priceFeed);
          }
          /// @param _workerFeeLib worker fee lib address
          function setWorkerFeeLib(address _workerFeeLib) external onlyRole(ADMIN_ROLE) {
              workerFeeLib = _workerFeeLib;
              emit SetWorkerLib(_workerFeeLib);
          }
          /// @param _multiplierBps default multiplier for worker fee
          function setDefaultMultiplierBps(uint16 _multiplierBps) external onlyRole(ADMIN_ROLE) {
              defaultMultiplierBps = _multiplierBps;
              emit SetDefaultMultiplierBps(_multiplierBps);
          }
          /// @dev supports withdrawing fee from ULN301, ULN302 and more
          /// @param _lib message lib address
          /// @param _to address to withdraw fee to
          /// @param _amount amount to withdraw
          function withdrawFee(address _lib, address _to, uint _amount) external onlyRole(ADMIN_ROLE) {
              require(hasRole(MESSAGE_LIB_ROLE, _lib), "Worker: Invalid message lib");
              IMessageLib(_lib).withdrawFee(_to, _amount);
              emit Withdraw(_lib, _to, _amount);
          }
          // ========================= Internal Functions =========================
          /// @dev overrides AccessControl to allow for counting of allowlistSize
          /// @param _role role to grant
          /// @param _account address to grant role to
          function _grantRole(bytes32 _role, address _account) internal override {
              if (_role == ALLOWLIST && !hasRole(_role, _account)) {
                  ++allowlistSize;
              }
              super._grantRole(_role, _account);
          }
          /// @dev overrides AccessControl to allow for counting of allowlistSize
          /// @param _role role to revoke
          /// @param _account address to revoke role from
          function _revokeRole(bytes32 _role, address _account) internal override {
              if (_role == ALLOWLIST && hasRole(_role, _account)) {
                  --allowlistSize;
              }
              super._revokeRole(_role, _account);
          }
          /// @dev overrides AccessControl to disable renouncing of roles
          function renounceRole(bytes32 /*role*/, address /*account*/) public pure override {
              revert("Worker: cannot renounce role");
          }
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity >=0.8.0;
      interface ILayerZeroExecutor {
          // @notice query price and assign jobs at the same time
          // @param _dstEid - the destination endpoint identifier
          // @param _sender - the source sending contract address. executors may apply price discrimination to senders
          // @param _calldataSize - dynamic data size of message + caller params
          // @param _options - optional parameters for extra service plugins, e.g. sending dust tokens at the destination chain
          function assignJob(
              uint32 _dstEid,
              address _sender,
              uint _calldataSize,
              bytes calldata _options
          ) external payable returns (uint price);
          // @notice query the executor price for relaying the payload and its proof to the destination chain
          // @param _dstEid - the destination endpoint identifier
          // @param _sender - the source sending contract address. executors may apply price discrimination to senders
          // @param _calldataSize - dynamic data size of message + caller params
          // @param _options - optional parameters for extra service plugins, e.g. sending dust tokens at the destination chain
          function getFee(
              uint32 _dstEid,
              address _sender,
              uint _calldataSize,
              bytes calldata _options
          ) external view returns (uint price);
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity >=0.8.0;
      interface ILayerZeroTreasury {
          function getFee(address _sender, uint32 _eid, uint _totalFee, bool _payInLzToken) external view returns (uint);
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity >=0.8.0;
      interface IWorker {
          event SetWorkerLib(address workerLib);
          event SetPriceFeed(address priceFeed);
          event SetDefaultMultiplierBps(uint16 multiplierBps);
          event Withdraw(address lib, address to, uint amount);
          function setPriceFeed(address _priceFeed) external;
          function priceFeed() external view returns (address);
          function setDefaultMultiplierBps(uint16 _multiplierBps) external;
          function defaultMultiplierBps() external view returns (uint16);
          function withdrawFee(address _lib, address _to, uint _amount) external;
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity ^0.8.19;
      import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
      abstract contract MultiSig {
          enum Errors {
              NoError,
              SignatureError,
              DuplicatedSigner,
              SignerNotInCommittee
          }
          mapping(address signer => bool active) public signers;
          uint64 public signerSize;
          uint64 public quorum;
          event UpdateSigner(address _signer, bool _active);
          event UpdateQuorum(uint64 _quorum);
          modifier onlySigner() {
              require(signers[msg.sender], "MultiSig: caller must be signer");
              _;
          }
          constructor(address[] memory _signers, uint64 _quorum) {
              require(_signers.length >= _quorum && _quorum > 0, "MultiSig: signers too few");
              address lastSigner = address(0);
              for (uint i = 0; i < _signers.length; i++) {
                  address signer = _signers[i];
                  require(signer > lastSigner, "MultiSig: signers not sorted"); // to ensure no duplicates
                  signers[signer] = true;
                  lastSigner = signer;
              }
              signerSize = uint64(_signers.length);
              quorum = _quorum;
          }
          function _setSigner(address _signer, bool _active) internal {
              require(signers[_signer] != _active, "MultiSig: signer already in that state");
              signers[_signer] = _active;
              signerSize = _active ? signerSize + 1 : signerSize - 1;
              require(signerSize >= quorum, "MultiSig: committee size < threshold");
              emit UpdateSigner(_signer, _active);
          }
          function _setQuorum(uint64 _quorum) internal {
              require(_quorum <= signerSize && _quorum > 0, "MultiSig: invalid quorum");
              quorum = _quorum;
              emit UpdateQuorum(_quorum);
          }
          function verifySignatures(bytes32 _hash, bytes calldata _signatures) public view returns (bool, Errors) {
              if (_signatures.length != uint(quorum) * 65) {
                  return (false, Errors.SignatureError);
              }
              bytes32 messageDigest = _getEthSignedMessageHash(_hash);
              address lastSigner = address(0); // There cannot be a signer with address 0.
              for (uint i = 0; i < quorum; i++) {
                  bytes calldata signature = _signatures[i * 65:(i + 1) * 65];
                  (address currentSigner, ECDSA.RecoverError error) = ECDSA.tryRecover(messageDigest, signature);
                  if (error != ECDSA.RecoverError.NoError) return (false, Errors.SignatureError);
                  if (currentSigner <= lastSigner) return (false, Errors.DuplicatedSigner); // prevent duplicate signatures
                  if (!signers[currentSigner]) return (false, Errors.SignerNotInCommittee); // signature is not in committee
                  lastSigner = currentSigner;
              }
              return (true, Errors.NoError);
          }
          function _getEthSignedMessageHash(bytes32 _messageHash) internal pure returns (bytes32) {
              return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
      32", _messageHash));
          }
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity ^0.8.19;
      import "@layerzerolabs/lz-evm-v1-0.8/contracts/interfaces/ILayerZeroUltraLightNodeV2.sol";
      import "../Worker.sol";
      import "./MultiSig.sol";
      import "./interfaces/IVerifier.sol";
      import "./interfaces/IVerifierFeeLib.sol";
      import "./interfaces/IUltraLightNode.sol";
      import {DeliveryState} from "../MessageLibBase.sol";
      struct ExecuteParam {
          uint32 vid;
          address target;
          bytes callData;
          uint expiration;
          bytes signatures;
      }
      contract VerifierNetwork is Worker, MultiSig, IVerifier {
          // to uniquely identify this VerifierNetwork instance
          // set to endpoint v1 eid if available OR endpoint v2 eid % 30_000
          uint32 public immutable vid;
          mapping(uint32 dstEid => DstConfig) public dstConfig;
          mapping(bytes32 executableHash => bool used) public usedHashes;
          event VerifySignaturesFailed(uint idx);
          event ExecuteFailed(uint _index, bytes _data);
          event HashAlreadyUsed(ExecuteParam param, bytes32 _hash);
          event VerifierFeePaid(uint fee);
          // ========================= Constructor =========================
          /// @dev VerifierNetwork doesn't have a roleAdmin (address(0x0))
          /// @dev Supports all of ULNv2, ULN301, ULN302 and more
          /// @param _messageLibs array of message lib addresses that are granted the MESSAGE_LIB_ROLE
          /// @param _priceFeed price feed address
          /// @param _signers array of signer addresses for multisig
          /// @param _quorum quorum for multisig
          /// @param _admins array of admin addresses that are granted the ADMIN_ROLE
          constructor(
              uint32 _vid,
              address[] memory _messageLibs,
              address _priceFeed,
              address[] memory _signers,
              uint64 _quorum,
              address[] memory _admins
          ) Worker(_messageLibs, _priceFeed, 12000, address(0x0), _admins) MultiSig(_signers, _quorum) {
              vid = _vid;
          }
          // ========================= Modifier =========================
          /// @dev depending on role, restrict access to only self or admin
          /// @dev ALLOWLIST, DENYLIST, MESSAGE_LIB_ROLE can only be granted/revoked by self
          /// @dev ADMIN_ROLE can only be granted/revoked by admin
          /// @dev reverts if not one of the above roles
          /// @param _role role to check
          modifier onlySelfOrAdmin(bytes32 _role) {
              if (_role == ALLOWLIST || _role == DENYLIST || _role == MESSAGE_LIB_ROLE) {
                  // self required
                  require(address(this) == msg.sender, "Verifier: caller must be self");
              } else if (_role == ADMIN_ROLE) {
                  // admin required
                  _checkRole(ADMIN_ROLE);
              } else {
                  revert("Verifier: invalid role");
              }
              _;
          }
          modifier onlySelf() {
              require(address(this) == msg.sender, "Verifier: caller must be self");
              _;
          }
          // ========================= OnlySelf =========================
          /// @dev set signers for multisig
          /// @dev function sig 0x31cb6105
          /// @param _signer signer address
          /// @param _active true to add, false to remove
          function setSigner(address _signer, bool _active) external onlySelf {
              _setSigner(_signer, _active);
          }
          /// @dev set quorum for multisig
          /// @dev function sig 0x8585c945
          /// @param _quorum to set
          function setQuorum(uint64 _quorum) external onlySelf {
              _setQuorum(_quorum);
          }
          /// @dev one function to verify and deliver to ULN302 and more (does not support ULN301)
          /// @dev if last verifier, can use this function to save overhead gas on deliver
          /// @dev function sig 0xb724b133
          /// @param _uln IUltraLightNode compatible contract
          /// @param _packetHeader packet header
          /// @param _payloadHash payload hash
          /// @param _confirmations block confirmations
          function verifyAndDeliver(
              IUltraLightNode _uln,
              bytes calldata _packetHeader,
              bytes32 _payloadHash,
              uint64 _confirmations
          ) external onlySelf {
              require(hasRole(MESSAGE_LIB_ROLE, address(_uln)), "Verifier: invalid uln");
              _uln.verify(_packetHeader, _payloadHash, _confirmations);
              // if deliverable, deliver. else, skip or it will revert in uln
              if (_uln.deliverable(_packetHeader, _payloadHash) == DeliveryState.Deliverable) {
                  _uln.deliver(_packetHeader, _payloadHash);
              }
          }
          // ========================= OnlySelf / OnlyAdmin =========================
          /// @dev overrides AccessControl to allow self/admin to grant role'
          /// @dev function sig 0x2f2ff15d
          /// @param _role role to grant
          /// @param _account account to grant role to
          function grantRole(bytes32 _role, address _account) public override onlySelfOrAdmin(_role) {
              _grantRole(_role, _account);
          }
          /// @dev overrides AccessControl to allow self/admin to revoke role
          /// @dev function sig 0xd547741f
          /// @param _role role to revoke
          /// @param _account account to revoke role from
          function revokeRole(bytes32 _role, address _account) public override onlySelfOrAdmin(_role) {
              _revokeRole(_role, _account);
          }
          // ========================= OnlyQuorum =========================
          // @notice function for quorum to change admin without going through execute function
          // @dev calldata in the case is abi.encode new admin address
          function quorumChangeAdmin(ExecuteParam calldata _param) external {
              require(_param.expiration > block.timestamp, "Verifier: expired");
              require(_param.target == address(this), "Verifier: invalid target");
              require(_param.vid == vid, "Verifier: invalid vid");
              // generate and validate hash
              bytes32 hash = hashCallData(_param.vid, _param.target, _param.callData, _param.expiration);
              (bool sigsValid, ) = verifySignatures(hash, _param.signatures);
              require(sigsValid, "Verifier: invalid signatures");
              require(!usedHashes[hash], "Verifier: hash already used");
              usedHashes[hash] = true;
              _grantRole(ADMIN_ROLE, abi.decode(_param.callData, (address)));
          }
          // ========================= OnlyAdmin =========================
          /// @param _params array of DstConfigParam
          function setDstConfig(DstConfigParam[] calldata _params) external onlyRole(ADMIN_ROLE) {
              for (uint i = 0; i < _params.length; ++i) {
                  DstConfigParam calldata param = _params[i];
                  dstConfig[param.dstEid] = DstConfig(param.gas, param.multiplierBps, param.floorMarginUSD);
              }
              emit SetDstConfig(_params);
          }
          /// @dev takes a list of instructions and executes them in order
          /// @dev if any of the instructions fail, it will emit an error event and continue to execute the rest of the instructions
          /// @param _params array of ExecuteParam, includes target, callData, expiration, signatures
          function execute(ExecuteParam[] calldata _params) external onlyRole(ADMIN_ROLE) {
              for (uint i = 0; i < _params.length; ++i) {
                  ExecuteParam calldata param = _params[i];
                  // 1. skip if invalid vid
                  if (param.vid != vid) {
                      continue;
                  }
                  // 2. skip if expired
                  if (param.expiration <= block.timestamp) {
                      continue;
                  }
                  // generate and validate hash
                  bytes32 hash = hashCallData(param.vid, param.target, param.callData, param.expiration);
                  // 3. check signatures
                  (bool sigsValid, ) = verifySignatures(hash, param.signatures);
                  if (!sigsValid) {
                      emit VerifySignaturesFailed(i);
                      continue;
                  }
                  // 4. should check hash
                  bool shouldCheckHash = _shouldCheckHash(bytes4(param.callData));
                  if (shouldCheckHash) {
                      if (usedHashes[hash]) {
                          emit HashAlreadyUsed(param, hash);
                          continue;
                      } else {
                          usedHashes[hash] = true; // prevent reentry and replay attack
                      }
                  }
                  (bool success, bytes memory rtnData) = param.target.call(param.callData);
                  if (!success) {
                      if (shouldCheckHash) {
                          // need to unset the usedHash otherwise it cant be used
                          usedHashes[hash] = false;
                      }
                      // emit an event in any case
                      emit ExecuteFailed(i, rtnData);
                  }
              }
          }
          /// @dev to support ULNv2
          /// @dev the withdrawFee function for ULN30X is built in the Worker contract
          /// @param _lib message lib address
          /// @param _to address to withdraw to
          /// @param _amount amount to withdraw
          function withdrawFeeFromUlnV2(address _lib, address payable _to, uint _amount) external onlyRole(ADMIN_ROLE) {
              require(hasRole(MESSAGE_LIB_ROLE, _lib), "Verifier: Invalid message lib");
              ILayerZeroUltraLightNodeV2(_lib).withdrawNative(_to, _amount);
          }
          // ========================= OnlyMessageLib =========================
          /// @dev for ULN301, ULN302 and more to assign job
          /// @dev verifier network can reject job from _sender by adding/removing them from allowlist/denylist
          /// @param _param assign job param
          /// @param _options verifier options
          function assignJob(
              AssignJobParam calldata _param,
              bytes calldata _options
          ) external payable onlyRole(MESSAGE_LIB_ROLE) onlyAcl(_param.sender) returns (uint totalFee) {
              IVerifierFeeLib.FeeParams memory feeParams = IVerifierFeeLib.FeeParams(
                  priceFeed,
                  _param.dstEid,
                  _param.confirmations,
                  _param.sender,
                  quorum,
                  defaultMultiplierBps
              );
              totalFee = IVerifierFeeLib(workerFeeLib).getFeeOnSend(feeParams, dstConfig[_param.dstEid], _options);
          }
          /// @dev to support ULNv2
          /// @dev verifier network can reject job from _sender by adding/removing them from allowlist/denylist
          /// @param _dstEid destination EndpointId
          /// @param //_outboundProofType outbound proof type
          /// @param _confirmations block confirmations
          /// @param _sender message sender address
          function assignJob(
              uint16 _dstEid,
              uint16 /*_outboundProofType*/,
              uint64 _confirmations,
              address _sender
          ) external onlyRole(MESSAGE_LIB_ROLE) onlyAcl(_sender) returns (uint totalFee) {
              IVerifierFeeLib.FeeParams memory params = IVerifierFeeLib.FeeParams(
                  priceFeed,
                  _dstEid,
                  _confirmations,
                  _sender,
                  quorum,
                  defaultMultiplierBps
              );
              // ULNV2 does not have verifier options
              totalFee = IVerifierFeeLib(workerFeeLib).getFeeOnSend(params, dstConfig[_dstEid], bytes(""));
              emit VerifierFeePaid(totalFee);
          }
          // ========================= View =========================
          /// @dev getFee can revert if _sender doesn't pass ACL
          /// @param _dstEid destination EndpointId
          /// @param _confirmations block confirmations
          /// @param _sender message sender address
          /// @param _options verifier options
          /// @return fee fee in native amount
          function getFee(
              uint32 _dstEid,
              uint64 _confirmations,
              address _sender,
              bytes calldata _options
          ) external view onlyAcl(_sender) returns (uint fee) {
              IVerifierFeeLib.FeeParams memory params = IVerifierFeeLib.FeeParams(
                  priceFeed,
                  _dstEid,
                  _confirmations,
                  _sender,
                  quorum,
                  defaultMultiplierBps
              );
              return IVerifierFeeLib(workerFeeLib).getFee(params, dstConfig[_dstEid], _options);
          }
          /// @dev to support ULNv2
          /// @dev getFee can revert if _sender doesn't pass ACL
          /// @param _dstEid destination EndpointId
          /// @param //_outboundProofType outbound proof type
          /// @param _confirmations block confirmations
          /// @param _sender message sender address
          function getFee(
              uint16 _dstEid,
              uint16 /*_outboundProofType*/,
              uint64 _confirmations,
              address _sender
          ) public view onlyAcl(_sender) returns (uint fee) {
              IVerifierFeeLib.FeeParams memory params = IVerifierFeeLib.FeeParams(
                  priceFeed,
                  _dstEid,
                  _confirmations,
                  _sender,
                  quorum,
                  defaultMultiplierBps
              );
              return IVerifierFeeLib(workerFeeLib).getFee(params, dstConfig[_dstEid], bytes(""));
          }
          /// @param _target target address
          /// @param _callData call data
          /// @param _expiration expiration timestamp
          /// @return hash of above
          function hashCallData(
              uint32 _vid,
              address _target,
              bytes calldata _callData,
              uint _expiration
          ) public pure returns (bytes32) {
              return keccak256(abi.encodePacked(_vid, _target, _expiration, _callData));
          }
          // ========================= Internal =========================
          /// @dev to save gas, we don't check hash for some functions (where replaying won't change the state)
          /// @dev for example, some administrative functions like changing signers, the contract should check hash to double spending
          /// @dev should ensure that all onlySelf functions have unique functionSig
          /// @param _functionSig function signature
          /// @return true if should check hash
          function _shouldCheckHash(bytes4 _functionSig) internal pure returns (bool) {
              // never check for these selectors to save gas
              return
                  _functionSig != IUltraLightNode.verify.selector && // 0x0223536e, replaying won't change the state
                  _functionSig != this.verifyAndDeliver.selector && // 0xb724b133, replaying calls deliver on top of verify, which will be rejected at uln if not deliverable
                  _functionSig != ILayerZeroUltraLightNodeV2.updateHash.selector; // 0x704316e5, replaying will be revert at uln
          }
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity >=0.8.0;
      interface ILayerZeroVerifier {
          struct AssignJobParam {
              uint32 dstEid;
              bytes packetHeader;
              bytes32 payloadHash;
              uint64 confirmations;
              address sender;
          }
          // @notice query price and assign jobs at the same time
          // @param _dstEid - the destination endpoint identifier
          // @param _packetHeader - version + nonce + path
          // @param _payloadHash - hash of guid + message
          // @param _confirmations - block confirmation delay before relaying blocks
          // @param _sender - the source sending contract address
          // @param _options - options
          function assignJob(AssignJobParam calldata _param, bytes calldata _options) external payable returns (uint fee);
          // @notice query the verifier fee for relaying block information to the destination chain
          // @param _dstEid the destination endpoint identifier
          // @param _confirmations - block confirmation delay before relaying blocks
          // @param _sender - the source sending contract address
          // @param _options - options
          function getFee(
              uint32 _dstEid,
              uint64 _confirmations,
              address _sender,
              bytes calldata _options
          ) external view returns (uint fee);
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity >=0.8.0;
      import {DeliveryState} from "../../MessageLibBase.sol";
      interface IUltraLightNode {
          function verify(bytes calldata _packetHeader, bytes32 _payloadHash, uint64 _confirmations) external;
          function deliver(bytes calldata _packetHeader, bytes32 _payloadHash) external;
          function deliverable(bytes calldata _packetHeader, bytes32 _payloadHash) external view returns (DeliveryState);
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity >=0.8.0;
      import "../../interfaces/IWorker.sol";
      import "./ILayerZeroVerifier.sol";
      interface IVerifier is IWorker, ILayerZeroVerifier {
          struct DstConfigParam {
              uint32 dstEid;
              uint64 gas;
              uint16 multiplierBps;
              uint128 floorMarginUSD;
          }
          struct DstConfig {
              uint64 gas;
              uint16 multiplierBps;
              uint128 floorMarginUSD; // uses priceFeed PRICE_RATIO_DENOMINATOR
          }
          event SetDstConfig(DstConfigParam[] params);
          function dstConfig(uint32 _dstEid) external view returns (uint64, uint16, uint128);
      }
      // SPDX-License-Identifier: BUSL-1.1
      pragma solidity >=0.8.0;
      import "./IVerifier.sol";
      interface IVerifierFeeLib {
          struct FeeParams {
              address priceFeed;
              uint32 dstEid;
              uint64 confirmations;
              address sender;
              uint64 quorum;
              uint16 defaultMultiplierBps;
          }
          function getFeeOnSend(
              FeeParams memory _params,
              IVerifier.DstConfig memory _dstConfig,
              bytes memory _options
          ) external payable returns (uint fee);
          function getFee(
              FeeParams calldata _params,
              IVerifier.DstConfig calldata _dstConfig,
              bytes calldata _options
          ) external view returns (uint fee);
      }
      

      File 2 of 3: SendUln302
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      import { IMessageLibManager } from "./IMessageLibManager.sol";
      import { IMessagingComposer } from "./IMessagingComposer.sol";
      import { IMessagingChannel } from "./IMessagingChannel.sol";
      import { IMessagingContext } from "./IMessagingContext.sol";
      struct MessagingParams {
          uint32 dstEid;
          bytes32 receiver;
          bytes message;
          bytes options;
          bool payInLzToken;
      }
      struct MessagingReceipt {
          bytes32 guid;
          uint64 nonce;
          MessagingFee fee;
      }
      struct MessagingFee {
          uint256 nativeFee;
          uint256 lzTokenFee;
      }
      struct Origin {
          uint32 srcEid;
          bytes32 sender;
          uint64 nonce;
      }
      interface ILayerZeroEndpointV2 is IMessageLibManager, IMessagingComposer, IMessagingChannel, IMessagingContext {
          event PacketSent(bytes encodedPayload, bytes options, address sendLibrary);
          event PacketVerified(Origin origin, address receiver, bytes32 payloadHash);
          event PacketDelivered(Origin origin, address receiver);
          event LzReceiveAlert(
              address indexed receiver,
              address indexed executor,
              Origin origin,
              bytes32 guid,
              uint256 gas,
              uint256 value,
              bytes message,
              bytes extraData,
              bytes reason
          );
          event LzTokenSet(address token);
          event DelegateSet(address sender, address delegate);
          function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory);
          function send(
              MessagingParams calldata _params,
              address _refundAddress
          ) external payable returns (MessagingReceipt memory);
          function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external;
          function verifiable(Origin calldata _origin, address _receiver) external view returns (bool);
          function initializable(Origin calldata _origin, address _receiver) external view returns (bool);
          function lzReceive(
              Origin calldata _origin,
              address _receiver,
              bytes32 _guid,
              bytes calldata _message,
              bytes calldata _extraData
          ) external payable;
          // oapp can burn messages partially by calling this function with its own business logic if messages are verified in order
          function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external;
          function setLzToken(address _lzToken) external;
          function lzToken() external view returns (address);
          function nativeToken() external view returns (address);
          function setDelegate(address _delegate) external;
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
      import { SetConfigParam } from "./IMessageLibManager.sol";
      enum MessageLibType {
          Send,
          Receive,
          SendAndReceive
      }
      interface IMessageLib is IERC165 {
          function setConfig(address _oapp, SetConfigParam[] calldata _config) external;
          function getConfig(uint32 _eid, address _oapp, uint32 _configType) external view returns (bytes memory config);
          function isSupportedEid(uint32 _eid) external view returns (bool);
          // message libs of same major version are compatible
          function version() external view returns (uint64 major, uint8 minor, uint8 endpointVersion);
          function messageLibType() external view returns (MessageLibType);
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      struct SetConfigParam {
          uint32 eid;
          uint32 configType;
          bytes config;
      }
      interface IMessageLibManager {
          struct Timeout {
              address lib;
              uint256 expiry;
          }
          event LibraryRegistered(address newLib);
          event DefaultSendLibrarySet(uint32 eid, address newLib);
          event DefaultReceiveLibrarySet(uint32 eid, address newLib);
          event DefaultReceiveLibraryTimeoutSet(uint32 eid, address oldLib, uint256 expiry);
          event SendLibrarySet(address sender, uint32 eid, address newLib);
          event ReceiveLibrarySet(address receiver, uint32 eid, address newLib);
          event ReceiveLibraryTimeoutSet(address receiver, uint32 eid, address oldLib, uint256 timeout);
          function registerLibrary(address _lib) external;
          function isRegisteredLibrary(address _lib) external view returns (bool);
          function getRegisteredLibraries() external view returns (address[] memory);
          function setDefaultSendLibrary(uint32 _eid, address _newLib) external;
          function defaultSendLibrary(uint32 _eid) external view returns (address);
          function setDefaultReceiveLibrary(uint32 _eid, address _newLib, uint256 _timeout) external;
          function defaultReceiveLibrary(uint32 _eid) external view returns (address);
          function setDefaultReceiveLibraryTimeout(uint32 _eid, address _lib, uint256 _expiry) external;
          function defaultReceiveLibraryTimeout(uint32 _eid) external view returns (address lib, uint256 expiry);
          function isSupportedEid(uint32 _eid) external view returns (bool);
          function isValidReceiveLibrary(address _receiver, uint32 _eid, address _lib) external view returns (bool);
          /// ------------------- OApp interfaces -------------------
          function setSendLibrary(address _oapp, uint32 _eid, address _newLib) external;
          function getSendLibrary(address _sender, uint32 _eid) external view returns (address lib);
          function isDefaultSendLibrary(address _sender, uint32 _eid) external view returns (bool);
          function setReceiveLibrary(address _oapp, uint32 _eid, address _newLib, uint256 _gracePeriod) external;
          function getReceiveLibrary(address _receiver, uint32 _eid) external view returns (address lib, bool isDefault);
          function setReceiveLibraryTimeout(address _oapp, uint32 _eid, address _lib, uint256 _gracePeriod) external;
          function receiveLibraryTimeout(address _receiver, uint32 _eid) external view returns (address lib, uint256 expiry);
          function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external;
          function getConfig(
              address _oapp,
              address _lib,
              uint32 _eid,
              uint32 _configType
          ) external view returns (bytes memory config);
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      interface IMessagingChannel {
          event InboundNonceSkipped(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce);
          event PacketNilified(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);
          event PacketBurnt(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);
          function eid() external view returns (uint32);
          // this is an emergency function if a message cannot be verified for some reasons
          // required to provide _nextNonce to avoid race condition
          function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external;
          function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;
          function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;
          function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32);
          function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
          function outboundNonce(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (uint64);
          function inboundPayloadHash(
              address _receiver,
              uint32 _srcEid,
              bytes32 _sender,
              uint64 _nonce
          ) external view returns (bytes32);
          function lazyInboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      interface IMessagingComposer {
          event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message);
          event ComposeDelivered(address from, address to, bytes32 guid, uint16 index);
          event LzComposeAlert(
              address indexed from,
              address indexed to,
              address indexed executor,
              bytes32 guid,
              uint16 index,
              uint256 gas,
              uint256 value,
              bytes message,
              bytes extraData,
              bytes reason
          );
          function composeQueue(
              address _from,
              address _to,
              bytes32 _guid,
              uint16 _index
          ) external view returns (bytes32 messageHash);
          function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external;
          function lzCompose(
              address _from,
              address _to,
              bytes32 _guid,
              uint16 _index,
              bytes calldata _message,
              bytes calldata _extraData
          ) external payable;
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      interface IMessagingContext {
          function isSendingMessage() external view returns (bool);
          function getSendContext() external view returns (uint32 dstEid, address sender);
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      import { MessagingFee } from "./ILayerZeroEndpointV2.sol";
      import { IMessageLib } from "./IMessageLib.sol";
      struct Packet {
          uint64 nonce;
          uint32 srcEid;
          address sender;
          uint32 dstEid;
          bytes32 receiver;
          bytes32 guid;
          bytes message;
      }
      interface ISendLib is IMessageLib {
          function send(
              Packet calldata _packet,
              bytes calldata _options,
              bool _payInLzToken
          ) external returns (MessagingFee memory, bytes memory encodedPacket);
          function quote(
              Packet calldata _packet,
              bytes calldata _options,
              bool _payInLzToken
          ) external view returns (MessagingFee memory);
          function setTreasury(address _treasury) external;
          function withdrawFee(address _to, uint256 _amount) external;
          function withdrawLzTokenFee(address _lzToken, address _to, uint256 _amount) external;
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      library AddressCast {
          error AddressCast_InvalidSizeForAddress();
          error AddressCast_InvalidAddress();
          function toBytes32(bytes calldata _addressBytes) internal pure returns (bytes32 result) {
              if (_addressBytes.length > 32) revert AddressCast_InvalidAddress();
              result = bytes32(_addressBytes);
              unchecked {
                  uint256 offset = 32 - _addressBytes.length;
                  result = result >> (offset * 8);
              }
          }
          function toBytes32(address _address) internal pure returns (bytes32 result) {
              result = bytes32(uint256(uint160(_address)));
          }
          function toBytes(bytes32 _addressBytes32, uint256 _size) internal pure returns (bytes memory result) {
              if (_size == 0 || _size > 32) revert AddressCast_InvalidSizeForAddress();
              result = new bytes(_size);
              unchecked {
                  uint256 offset = 256 - _size * 8;
                  assembly {
                      mstore(add(result, 32), shl(offset, _addressBytes32))
                  }
              }
          }
          function toAddress(bytes32 _addressBytes32) internal pure returns (address result) {
              result = address(uint160(uint256(_addressBytes32)));
          }
          function toAddress(bytes calldata _addressBytes) internal pure returns (address result) {
              if (_addressBytes.length != 20) revert AddressCast_InvalidAddress();
              result = address(bytes20(_addressBytes));
          }
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      library CalldataBytesLib {
          function toU8(bytes calldata _bytes, uint256 _start) internal pure returns (uint8) {
              return uint8(_bytes[_start]);
          }
          function toU16(bytes calldata _bytes, uint256 _start) internal pure returns (uint16) {
              unchecked {
                  uint256 end = _start + 2;
                  return uint16(bytes2(_bytes[_start:end]));
              }
          }
          function toU32(bytes calldata _bytes, uint256 _start) internal pure returns (uint32) {
              unchecked {
                  uint256 end = _start + 4;
                  return uint32(bytes4(_bytes[_start:end]));
              }
          }
          function toU64(bytes calldata _bytes, uint256 _start) internal pure returns (uint64) {
              unchecked {
                  uint256 end = _start + 8;
                  return uint64(bytes8(_bytes[_start:end]));
              }
          }
          function toU128(bytes calldata _bytes, uint256 _start) internal pure returns (uint128) {
              unchecked {
                  uint256 end = _start + 16;
                  return uint128(bytes16(_bytes[_start:end]));
              }
          }
          function toU256(bytes calldata _bytes, uint256 _start) internal pure returns (uint256) {
              unchecked {
                  uint256 end = _start + 32;
                  return uint256(bytes32(_bytes[_start:end]));
              }
          }
          function toAddr(bytes calldata _bytes, uint256 _start) internal pure returns (address) {
              unchecked {
                  uint256 end = _start + 20;
                  return address(bytes20(_bytes[_start:end]));
              }
          }
          function toB32(bytes calldata _bytes, uint256 _start) internal pure returns (bytes32) {
              unchecked {
                  uint256 end = _start + 32;
                  return bytes32(_bytes[_start:end]);
              }
          }
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
      import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
      library Transfer {
          using SafeERC20 for IERC20;
          address internal constant ADDRESS_ZERO = address(0);
          error Transfer_NativeFailed(address _to, uint256 _value);
          error Transfer_ToAddressIsZero();
          function native(address _to, uint256 _value) internal {
              if (_to == ADDRESS_ZERO) revert Transfer_ToAddressIsZero();
              (bool success, ) = _to.call{ value: _value }("");
              if (!success) revert Transfer_NativeFailed(_to, _value);
          }
          function token(address _token, address _to, uint256 _value) internal {
              if (_to == ADDRESS_ZERO) revert Transfer_ToAddressIsZero();
              IERC20(_token).safeTransfer(_to, _value);
          }
          function nativeOrToken(address _token, address _to, uint256 _value) internal {
              if (_token == ADDRESS_ZERO) {
                  native(_to, _value);
              } else {
                  token(_token, _to, _value);
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // modified from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/structs/BitMaps.sol
      pragma solidity ^0.8.20;
      type BitMap256 is uint256;
      using BitMaps for BitMap256 global;
      library BitMaps {
          /**
           * @dev Returns whether the bit at `index` is set.
           */
          function get(BitMap256 bitmap, uint8 index) internal pure returns (bool) {
              uint256 mask = 1 << index;
              return BitMap256.unwrap(bitmap) & mask != 0;
          }
          /**
           * @dev Sets the bit at `index`.
           */
          function set(BitMap256 bitmap, uint8 index) internal pure returns (BitMap256) {
              uint256 mask = 1 << index;
              return BitMap256.wrap(BitMap256.unwrap(bitmap) | mask);
          }
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { CalldataBytesLib } from "../../libs/CalldataBytesLib.sol";
      library ExecutorOptions {
          using CalldataBytesLib for bytes;
          uint8 internal constant WORKER_ID = 1;
          uint8 internal constant OPTION_TYPE_LZRECEIVE = 1;
          uint8 internal constant OPTION_TYPE_NATIVE_DROP = 2;
          uint8 internal constant OPTION_TYPE_LZCOMPOSE = 3;
          uint8 internal constant OPTION_TYPE_ORDERED_EXECUTION = 4;
          error Executor_InvalidLzReceiveOption();
          error Executor_InvalidNativeDropOption();
          error Executor_InvalidLzComposeOption();
          /// @dev decode the next executor option from the options starting from the specified cursor
          /// @param _options [executor_id][executor_option][executor_id][executor_option]...
          ///        executor_option = [option_size][option_type][option]
          ///        option_size = len(option_type) + len(option)
          ///        executor_id: uint8, option_size: uint16, option_type: uint8, option: bytes
          /// @param _cursor the cursor to start decoding from
          /// @return optionType the type of the option
          /// @return option the option of the executor
          /// @return cursor the cursor to start decoding the next executor option
          function nextExecutorOption(
              bytes calldata _options,
              uint256 _cursor
          ) internal pure returns (uint8 optionType, bytes calldata option, uint256 cursor) {
              unchecked {
                  // skip worker id
                  cursor = _cursor + 1;
                  // read option size
                  uint16 size = _options.toU16(cursor);
                  cursor += 2;
                  // read option type
                  optionType = _options.toU8(cursor);
                  // startCursor and endCursor are used to slice the option from _options
                  uint256 startCursor = cursor + 1; // skip option type
                  uint256 endCursor = cursor + size;
                  option = _options[startCursor:endCursor];
                  cursor += size;
              }
          }
          function decodeLzReceiveOption(bytes calldata _option) internal pure returns (uint128 gas, uint128 value) {
              if (_option.length != 16 && _option.length != 32) revert Executor_InvalidLzReceiveOption();
              gas = _option.toU128(0);
              value = _option.length == 32 ? _option.toU128(16) : 0;
          }
          function decodeNativeDropOption(bytes calldata _option) internal pure returns (uint128 amount, bytes32 receiver) {
              if (_option.length != 48) revert Executor_InvalidNativeDropOption();
              amount = _option.toU128(0);
              receiver = _option.toB32(16);
          }
          function decodeLzComposeOption(
              bytes calldata _option
          ) internal pure returns (uint16 index, uint128 gas, uint128 value) {
              if (_option.length != 18 && _option.length != 34) revert Executor_InvalidLzComposeOption();
              index = _option.toU16(0);
              gas = _option.toU128(2);
              value = _option.length == 34 ? _option.toU128(18) : 0;
          }
          function encodeLzReceiveOption(uint128 _gas, uint128 _value) internal pure returns (bytes memory) {
              return _value == 0 ? abi.encodePacked(_gas) : abi.encodePacked(_gas, _value);
          }
          function encodeNativeDropOption(uint128 _amount, bytes32 _receiver) internal pure returns (bytes memory) {
              return abi.encodePacked(_amount, _receiver);
          }
          function encodeLzComposeOption(uint16 _index, uint128 _gas, uint128 _value) internal pure returns (bytes memory) {
              return _value == 0 ? abi.encodePacked(_index, _gas) : abi.encodePacked(_index, _gas, _value);
          }
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { Packet } from "../../interfaces/ISendLib.sol";
      import { AddressCast } from "../../libs/AddressCast.sol";
      library PacketV1Codec {
          using AddressCast for address;
          using AddressCast for bytes32;
          uint8 internal constant PACKET_VERSION = 1;
          // header (version + nonce + path)
          // version
          uint256 private constant PACKET_VERSION_OFFSET = 0;
          //    nonce
          uint256 private constant NONCE_OFFSET = 1;
          //    path
          uint256 private constant SRC_EID_OFFSET = 9;
          uint256 private constant SENDER_OFFSET = 13;
          uint256 private constant DST_EID_OFFSET = 45;
          uint256 private constant RECEIVER_OFFSET = 49;
          // payload (guid + message)
          uint256 private constant GUID_OFFSET = 81; // keccak256(nonce + path)
          uint256 private constant MESSAGE_OFFSET = 113;
          function encode(Packet memory _packet) internal pure returns (bytes memory encodedPacket) {
              encodedPacket = abi.encodePacked(
                  PACKET_VERSION,
                  _packet.nonce,
                  _packet.srcEid,
                  _packet.sender.toBytes32(),
                  _packet.dstEid,
                  _packet.receiver,
                  _packet.guid,
                  _packet.message
              );
          }
          function encodePacketHeader(Packet memory _packet) internal pure returns (bytes memory) {
              return
                  abi.encodePacked(
                      PACKET_VERSION,
                      _packet.nonce,
                      _packet.srcEid,
                      _packet.sender.toBytes32(),
                      _packet.dstEid,
                      _packet.receiver
                  );
          }
          function encodePayload(Packet memory _packet) internal pure returns (bytes memory) {
              return abi.encodePacked(_packet.guid, _packet.message);
          }
          function header(bytes calldata _packet) internal pure returns (bytes calldata) {
              return _packet[0:GUID_OFFSET];
          }
          function version(bytes calldata _packet) internal pure returns (uint8) {
              return uint8(bytes1(_packet[PACKET_VERSION_OFFSET:NONCE_OFFSET]));
          }
          function nonce(bytes calldata _packet) internal pure returns (uint64) {
              return uint64(bytes8(_packet[NONCE_OFFSET:SRC_EID_OFFSET]));
          }
          function srcEid(bytes calldata _packet) internal pure returns (uint32) {
              return uint32(bytes4(_packet[SRC_EID_OFFSET:SENDER_OFFSET]));
          }
          function sender(bytes calldata _packet) internal pure returns (bytes32) {
              return bytes32(_packet[SENDER_OFFSET:DST_EID_OFFSET]);
          }
          function senderAddressB20(bytes calldata _packet) internal pure returns (address) {
              return sender(_packet).toAddress();
          }
          function dstEid(bytes calldata _packet) internal pure returns (uint32) {
              return uint32(bytes4(_packet[DST_EID_OFFSET:RECEIVER_OFFSET]));
          }
          function receiver(bytes calldata _packet) internal pure returns (bytes32) {
              return bytes32(_packet[RECEIVER_OFFSET:GUID_OFFSET]);
          }
          function receiverB20(bytes calldata _packet) internal pure returns (address) {
              return receiver(_packet).toAddress();
          }
          function guid(bytes calldata _packet) internal pure returns (bytes32) {
              return bytes32(_packet[GUID_OFFSET:MESSAGE_OFFSET]);
          }
          function message(bytes calldata _packet) internal pure returns (bytes calldata) {
              return bytes(_packet[MESSAGE_OFFSET:]);
          }
          function payload(bytes calldata _packet) internal pure returns (bytes calldata) {
              return bytes(_packet[GUID_OFFSET:]);
          }
          function payloadHash(bytes calldata _packet) internal pure returns (bytes32) {
              return keccak256(payload(_packet));
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
      pragma solidity ^0.8.0;
      import "../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.
       *
       * By default, the owner account will be the one that deploys the contract. 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;
          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
          /**
           * @dev Initializes the contract setting the deployer as the initial owner.
           */
          constructor() {
              _transferOwnership(_msgSender());
          }
          /**
           * @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 {
              require(owner() == _msgSender(), "Ownable: caller is not the owner");
          }
          /**
           * @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 {
              require(newOwner != address(0), "Ownable: new owner is the zero address");
              _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);
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC20 standard as defined in the EIP.
       */
      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 amount of tokens in existence.
           */
          function totalSupply() external view returns (uint256);
          /**
           * @dev Returns the amount of tokens owned by `account`.
           */
          function balanceOf(address account) external view returns (uint256);
          /**
           * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
          /**
           * @dev Moves `amount` tokens from `from` to `to` using the
           * allowance mechanism. `amount` 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 amount) external returns (bool);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
       * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
       *
       * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
       * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
       * need to send a transaction, and thus is not required to hold Ether at all.
       *
       * ==== Security Considerations
       *
       * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
       * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
       * considered as an intention to spend the allowance in any specific way. The second is that because permits have
       * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
       * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
       * generally recommended is:
       *
       * ```solidity
       * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
       *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
       *     doThing(..., value);
       * }
       *
       * function doThing(..., uint256 value) public {
       *     token.safeTransferFrom(msg.sender, address(this), value);
       *     ...
       * }
       * ```
       *
       * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
       * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
       * {SafeERC20-safeTransferFrom}).
       *
       * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
       * contracts should have entry points that don't rely on permit.
       */
      interface IERC20Permit {
          /**
           * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
           * given ``owner``'s signed approval.
           *
           * IMPORTANT: The same issues {IERC20-approve} has related to transaction
           * ordering also apply here.
           *
           * Emits an {Approval} event.
           *
           * Requirements:
           *
           * - `spender` cannot be the zero address.
           * - `deadline` must be a timestamp in the future.
           * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
           * over the EIP712-formatted function arguments.
           * - the signature must use ``owner``'s current nonce (see {nonces}).
           *
           * For more information on the signature format, see the
           * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
           * section].
           *
           * CAUTION: See Security Considerations above.
           */
          function permit(
              address owner,
              address spender,
              uint256 value,
              uint256 deadline,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) external;
          /**
           * @dev Returns the current nonce for `owner`. This value must be
           * included whenever a signature is generated for {permit}.
           *
           * Every successful call to {permit} increases ``owner``'s nonce by one. This
           * prevents a signature from being used multiple times.
           */
          function nonces(address owner) external view returns (uint256);
          /**
           * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
           */
          // solhint-disable-next-line func-name-mixedcase
          function DOMAIN_SEPARATOR() external view returns (bytes32);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
      pragma solidity ^0.8.0;
      import "../IERC20.sol";
      import "../extensions/IERC20Permit.sol";
      import "../../../utils/Address.sol";
      /**
       * @title SafeERC20
       * @dev Wrappers around ERC20 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 {
          using Address for address;
          /**
           * @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.encodeWithSelector(token.transfer.selector, 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.encodeWithSelector(token.transferFrom.selector, from, to, value));
          }
          /**
           * @dev Deprecated. This function has issues similar to the ones found in
           * {IERC20-approve}, and its usage is discouraged.
           *
           * Whenever possible, use {safeIncreaseAllowance} and
           * {safeDecreaseAllowance} instead.
           */
          function safeApprove(IERC20 token, address spender, uint256 value) internal {
              // safeApprove should only be called when setting an initial allowance,
              // or when resetting it to zero. To increase and decrease it, use
              // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
              require(
                  (value == 0) || (token.allowance(address(this), spender) == 0),
                  "SafeERC20: approve from non-zero to non-zero allowance"
              );
              _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 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.
           */
          function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
              uint256 oldAllowance = token.allowance(address(this), spender);
              _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
          }
          /**
           * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
           * non-reverting calls are assumed to be successful.
           */
          function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
              unchecked {
                  uint256 oldAllowance = token.allowance(address(this), spender);
                  require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                  _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
              }
          }
          /**
           * @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.
           */
          function forceApprove(IERC20 token, address spender, uint256 value) internal {
              bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
              if (!_callOptionalReturnBool(token, approvalCall)) {
                  _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
                  _callOptionalReturn(token, approvalCall);
              }
          }
          /**
           * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
           * Revert on invalid signature.
           */
          function safePermit(
              IERC20Permit token,
              address owner,
              address spender,
              uint256 value,
              uint256 deadline,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) internal {
              uint256 nonceBefore = token.nonces(owner);
              token.permit(owner, spender, value, deadline, v, r, s);
              uint256 nonceAfter = token.nonces(owner);
              require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
          }
          /**
           * @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).
           */
          function _callOptionalReturn(IERC20 token, bytes memory data) private {
              // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
              // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
              // the target address contains contract code and also asserts for success in the low-level call.
              bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
              require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
          }
          /**
           * @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 silents catches all reverts and returns a bool instead.
           */
          function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
              // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
              // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
              // and not revert is the subcall reverts.
              (bool success, bytes memory returndata) = address(token).call(data);
              return
                  success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
      pragma solidity ^0.8.1;
      /**
       * @dev Collection of functions related to the address type
       */
      library Address {
          /**
           * @dev Returns true if `account` is a contract.
           *
           * [IMPORTANT]
           * ====
           * It is unsafe to assume that an address for which this function returns
           * false is an externally-owned account (EOA) and not a contract.
           *
           * Among others, `isContract` will return false for the following
           * types of addresses:
           *
           *  - an externally-owned account
           *  - a contract in construction
           *  - an address where a contract will be created
           *  - an address where a contract lived, but was destroyed
           *
           * Furthermore, `isContract` will also return true if the target contract within
           * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
           * which only has an effect at the end of a transaction.
           * ====
           *
           * [IMPORTANT]
           * ====
           * You shouldn't rely on `isContract` to protect against flash loan attacks!
           *
           * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
           * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
           * constructor.
           * ====
           */
          function isContract(address account) internal view returns (bool) {
              // This method relies on extcodesize/address.code.length, which returns 0
              // for contracts in construction, since the code is only stored at the end
              // of the constructor execution.
              return account.code.length > 0;
          }
          /**
           * @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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
           */
          function sendValue(address payable recipient, uint256 amount) internal {
              require(address(this).balance >= amount, "Address: insufficient balance");
              (bool success, ) = recipient.call{value: amount}("");
              require(success, "Address: unable to send value, recipient may have reverted");
          }
          /**
           * @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, it is bubbled up by this
           * function (like regular Solidity function calls).
           *
           * 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.
           *
           * _Available since v3.1._
           */
          function functionCall(address target, bytes memory data) internal returns (bytes memory) {
              return functionCallWithValue(target, data, 0, "Address: low-level call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
           * `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal returns (bytes memory) {
              return functionCallWithValue(target, data, 0, errorMessage);
          }
          /**
           * @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`.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
              return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
          }
          /**
           * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
           * with `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(
              address target,
              bytes memory data,
              uint256 value,
              string memory errorMessage
          ) internal returns (bytes memory) {
              require(address(this).balance >= value, "Address: insufficient balance for call");
              (bool success, bytes memory returndata) = target.call{value: value}(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
              return functionStaticCall(target, data, "Address: low-level static call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal view returns (bytes memory) {
              (bool success, bytes memory returndata) = target.staticcall(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but performing a delegate call.
           *
           * _Available since v3.4._
           */
          function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
              return functionDelegateCall(target, data, "Address: low-level delegate call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
           * but performing a delegate call.
           *
           * _Available since v3.4._
           */
          function functionDelegateCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal returns (bytes memory) {
              (bool success, bytes memory returndata) = target.delegatecall(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
           * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
           *
           * _Available since v4.8._
           */
          function verifyCallResultFromTarget(
              address target,
              bool success,
              bytes memory returndata,
              string memory errorMessage
          ) internal view returns (bytes memory) {
              if (success) {
                  if (returndata.length == 0) {
                      // only check isContract if the call was successful and the return data is empty
                      // otherwise we already know that it was a contract
                      require(isContract(target), "Address: call to non-contract");
                  }
                  return returndata;
              } else {
                  _revert(returndata, errorMessage);
              }
          }
          /**
           * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
           * revert reason or using the provided one.
           *
           * _Available since v4.3._
           */
          function verifyCallResult(
              bool success,
              bytes memory returndata,
              string memory errorMessage
          ) internal pure returns (bytes memory) {
              if (success) {
                  return returndata;
              } else {
                  _revert(returndata, errorMessage);
              }
          }
          function _revert(bytes memory returndata, string memory errorMessage) 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
                  /// @solidity memory-safe-assembly
                  assembly {
                      let returndata_size := mload(returndata)
                      revert(add(32, returndata), returndata_size)
                  }
              } else {
                  revert(errorMessage);
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
      pragma solidity ^0.8.0;
      /**
       * @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;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
      pragma solidity ^0.8.0;
      import "./IERC165.sol";
      /**
       * @dev Implementation of the {IERC165} interface.
       *
       * Contracts that want to implement ERC165 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);
       * }
       * ```
       *
       * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
       */
      abstract contract ERC165 is IERC165 {
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
              return interfaceId == type(IERC165).interfaceId;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC165 standard, as defined in the
       * https://eips.ethereum.org/EIPS/eip-165[EIP].
       *
       * 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[EIP 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);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
      // This file was procedurally generated from scripts/generate/templates/SafeCast.js.
      pragma solidity ^0.8.0;
      /**
       * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
       * checks.
       *
       * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
       * easily result in undesired exploitation or bugs, since developers usually
       * assume that overflows raise errors. `SafeCast` restores this intuition by
       * reverting the transaction when such an operation overflows.
       *
       * Using this library instead of the unchecked operations eliminates an entire
       * class of bugs, so it's recommended to use it always.
       *
       * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
       * all math on `uint256` and `int256` and then downcasting.
       */
      library SafeCast {
          /**
           * @dev Returns the downcasted uint248 from uint256, reverting on
           * overflow (when the input is greater than largest uint248).
           *
           * Counterpart to Solidity's `uint248` operator.
           *
           * Requirements:
           *
           * - input must fit into 248 bits
           *
           * _Available since v4.7._
           */
          function toUint248(uint256 value) internal pure returns (uint248) {
              require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
              return uint248(value);
          }
          /**
           * @dev Returns the downcasted uint240 from uint256, reverting on
           * overflow (when the input is greater than largest uint240).
           *
           * Counterpart to Solidity's `uint240` operator.
           *
           * Requirements:
           *
           * - input must fit into 240 bits
           *
           * _Available since v4.7._
           */
          function toUint240(uint256 value) internal pure returns (uint240) {
              require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
              return uint240(value);
          }
          /**
           * @dev Returns the downcasted uint232 from uint256, reverting on
           * overflow (when the input is greater than largest uint232).
           *
           * Counterpart to Solidity's `uint232` operator.
           *
           * Requirements:
           *
           * - input must fit into 232 bits
           *
           * _Available since v4.7._
           */
          function toUint232(uint256 value) internal pure returns (uint232) {
              require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
              return uint232(value);
          }
          /**
           * @dev Returns the downcasted uint224 from uint256, reverting on
           * overflow (when the input is greater than largest uint224).
           *
           * Counterpart to Solidity's `uint224` operator.
           *
           * Requirements:
           *
           * - input must fit into 224 bits
           *
           * _Available since v4.2._
           */
          function toUint224(uint256 value) internal pure returns (uint224) {
              require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
              return uint224(value);
          }
          /**
           * @dev Returns the downcasted uint216 from uint256, reverting on
           * overflow (when the input is greater than largest uint216).
           *
           * Counterpart to Solidity's `uint216` operator.
           *
           * Requirements:
           *
           * - input must fit into 216 bits
           *
           * _Available since v4.7._
           */
          function toUint216(uint256 value) internal pure returns (uint216) {
              require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
              return uint216(value);
          }
          /**
           * @dev Returns the downcasted uint208 from uint256, reverting on
           * overflow (when the input is greater than largest uint208).
           *
           * Counterpart to Solidity's `uint208` operator.
           *
           * Requirements:
           *
           * - input must fit into 208 bits
           *
           * _Available since v4.7._
           */
          function toUint208(uint256 value) internal pure returns (uint208) {
              require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
              return uint208(value);
          }
          /**
           * @dev Returns the downcasted uint200 from uint256, reverting on
           * overflow (when the input is greater than largest uint200).
           *
           * Counterpart to Solidity's `uint200` operator.
           *
           * Requirements:
           *
           * - input must fit into 200 bits
           *
           * _Available since v4.7._
           */
          function toUint200(uint256 value) internal pure returns (uint200) {
              require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
              return uint200(value);
          }
          /**
           * @dev Returns the downcasted uint192 from uint256, reverting on
           * overflow (when the input is greater than largest uint192).
           *
           * Counterpart to Solidity's `uint192` operator.
           *
           * Requirements:
           *
           * - input must fit into 192 bits
           *
           * _Available since v4.7._
           */
          function toUint192(uint256 value) internal pure returns (uint192) {
              require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
              return uint192(value);
          }
          /**
           * @dev Returns the downcasted uint184 from uint256, reverting on
           * overflow (when the input is greater than largest uint184).
           *
           * Counterpart to Solidity's `uint184` operator.
           *
           * Requirements:
           *
           * - input must fit into 184 bits
           *
           * _Available since v4.7._
           */
          function toUint184(uint256 value) internal pure returns (uint184) {
              require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
              return uint184(value);
          }
          /**
           * @dev Returns the downcasted uint176 from uint256, reverting on
           * overflow (when the input is greater than largest uint176).
           *
           * Counterpart to Solidity's `uint176` operator.
           *
           * Requirements:
           *
           * - input must fit into 176 bits
           *
           * _Available since v4.7._
           */
          function toUint176(uint256 value) internal pure returns (uint176) {
              require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
              return uint176(value);
          }
          /**
           * @dev Returns the downcasted uint168 from uint256, reverting on
           * overflow (when the input is greater than largest uint168).
           *
           * Counterpart to Solidity's `uint168` operator.
           *
           * Requirements:
           *
           * - input must fit into 168 bits
           *
           * _Available since v4.7._
           */
          function toUint168(uint256 value) internal pure returns (uint168) {
              require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
              return uint168(value);
          }
          /**
           * @dev Returns the downcasted uint160 from uint256, reverting on
           * overflow (when the input is greater than largest uint160).
           *
           * Counterpart to Solidity's `uint160` operator.
           *
           * Requirements:
           *
           * - input must fit into 160 bits
           *
           * _Available since v4.7._
           */
          function toUint160(uint256 value) internal pure returns (uint160) {
              require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
              return uint160(value);
          }
          /**
           * @dev Returns the downcasted uint152 from uint256, reverting on
           * overflow (when the input is greater than largest uint152).
           *
           * Counterpart to Solidity's `uint152` operator.
           *
           * Requirements:
           *
           * - input must fit into 152 bits
           *
           * _Available since v4.7._
           */
          function toUint152(uint256 value) internal pure returns (uint152) {
              require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
              return uint152(value);
          }
          /**
           * @dev Returns the downcasted uint144 from uint256, reverting on
           * overflow (when the input is greater than largest uint144).
           *
           * Counterpart to Solidity's `uint144` operator.
           *
           * Requirements:
           *
           * - input must fit into 144 bits
           *
           * _Available since v4.7._
           */
          function toUint144(uint256 value) internal pure returns (uint144) {
              require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
              return uint144(value);
          }
          /**
           * @dev Returns the downcasted uint136 from uint256, reverting on
           * overflow (when the input is greater than largest uint136).
           *
           * Counterpart to Solidity's `uint136` operator.
           *
           * Requirements:
           *
           * - input must fit into 136 bits
           *
           * _Available since v4.7._
           */
          function toUint136(uint256 value) internal pure returns (uint136) {
              require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
              return uint136(value);
          }
          /**
           * @dev Returns the downcasted uint128 from uint256, reverting on
           * overflow (when the input is greater than largest uint128).
           *
           * Counterpart to Solidity's `uint128` operator.
           *
           * Requirements:
           *
           * - input must fit into 128 bits
           *
           * _Available since v2.5._
           */
          function toUint128(uint256 value) internal pure returns (uint128) {
              require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
              return uint128(value);
          }
          /**
           * @dev Returns the downcasted uint120 from uint256, reverting on
           * overflow (when the input is greater than largest uint120).
           *
           * Counterpart to Solidity's `uint120` operator.
           *
           * Requirements:
           *
           * - input must fit into 120 bits
           *
           * _Available since v4.7._
           */
          function toUint120(uint256 value) internal pure returns (uint120) {
              require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
              return uint120(value);
          }
          /**
           * @dev Returns the downcasted uint112 from uint256, reverting on
           * overflow (when the input is greater than largest uint112).
           *
           * Counterpart to Solidity's `uint112` operator.
           *
           * Requirements:
           *
           * - input must fit into 112 bits
           *
           * _Available since v4.7._
           */
          function toUint112(uint256 value) internal pure returns (uint112) {
              require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
              return uint112(value);
          }
          /**
           * @dev Returns the downcasted uint104 from uint256, reverting on
           * overflow (when the input is greater than largest uint104).
           *
           * Counterpart to Solidity's `uint104` operator.
           *
           * Requirements:
           *
           * - input must fit into 104 bits
           *
           * _Available since v4.7._
           */
          function toUint104(uint256 value) internal pure returns (uint104) {
              require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
              return uint104(value);
          }
          /**
           * @dev Returns the downcasted uint96 from uint256, reverting on
           * overflow (when the input is greater than largest uint96).
           *
           * Counterpart to Solidity's `uint96` operator.
           *
           * Requirements:
           *
           * - input must fit into 96 bits
           *
           * _Available since v4.2._
           */
          function toUint96(uint256 value) internal pure returns (uint96) {
              require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
              return uint96(value);
          }
          /**
           * @dev Returns the downcasted uint88 from uint256, reverting on
           * overflow (when the input is greater than largest uint88).
           *
           * Counterpart to Solidity's `uint88` operator.
           *
           * Requirements:
           *
           * - input must fit into 88 bits
           *
           * _Available since v4.7._
           */
          function toUint88(uint256 value) internal pure returns (uint88) {
              require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
              return uint88(value);
          }
          /**
           * @dev Returns the downcasted uint80 from uint256, reverting on
           * overflow (when the input is greater than largest uint80).
           *
           * Counterpart to Solidity's `uint80` operator.
           *
           * Requirements:
           *
           * - input must fit into 80 bits
           *
           * _Available since v4.7._
           */
          function toUint80(uint256 value) internal pure returns (uint80) {
              require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
              return uint80(value);
          }
          /**
           * @dev Returns the downcasted uint72 from uint256, reverting on
           * overflow (when the input is greater than largest uint72).
           *
           * Counterpart to Solidity's `uint72` operator.
           *
           * Requirements:
           *
           * - input must fit into 72 bits
           *
           * _Available since v4.7._
           */
          function toUint72(uint256 value) internal pure returns (uint72) {
              require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
              return uint72(value);
          }
          /**
           * @dev Returns the downcasted uint64 from uint256, reverting on
           * overflow (when the input is greater than largest uint64).
           *
           * Counterpart to Solidity's `uint64` operator.
           *
           * Requirements:
           *
           * - input must fit into 64 bits
           *
           * _Available since v2.5._
           */
          function toUint64(uint256 value) internal pure returns (uint64) {
              require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
              return uint64(value);
          }
          /**
           * @dev Returns the downcasted uint56 from uint256, reverting on
           * overflow (when the input is greater than largest uint56).
           *
           * Counterpart to Solidity's `uint56` operator.
           *
           * Requirements:
           *
           * - input must fit into 56 bits
           *
           * _Available since v4.7._
           */
          function toUint56(uint256 value) internal pure returns (uint56) {
              require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
              return uint56(value);
          }
          /**
           * @dev Returns the downcasted uint48 from uint256, reverting on
           * overflow (when the input is greater than largest uint48).
           *
           * Counterpart to Solidity's `uint48` operator.
           *
           * Requirements:
           *
           * - input must fit into 48 bits
           *
           * _Available since v4.7._
           */
          function toUint48(uint256 value) internal pure returns (uint48) {
              require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
              return uint48(value);
          }
          /**
           * @dev Returns the downcasted uint40 from uint256, reverting on
           * overflow (when the input is greater than largest uint40).
           *
           * Counterpart to Solidity's `uint40` operator.
           *
           * Requirements:
           *
           * - input must fit into 40 bits
           *
           * _Available since v4.7._
           */
          function toUint40(uint256 value) internal pure returns (uint40) {
              require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
              return uint40(value);
          }
          /**
           * @dev Returns the downcasted uint32 from uint256, reverting on
           * overflow (when the input is greater than largest uint32).
           *
           * Counterpart to Solidity's `uint32` operator.
           *
           * Requirements:
           *
           * - input must fit into 32 bits
           *
           * _Available since v2.5._
           */
          function toUint32(uint256 value) internal pure returns (uint32) {
              require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
              return uint32(value);
          }
          /**
           * @dev Returns the downcasted uint24 from uint256, reverting on
           * overflow (when the input is greater than largest uint24).
           *
           * Counterpart to Solidity's `uint24` operator.
           *
           * Requirements:
           *
           * - input must fit into 24 bits
           *
           * _Available since v4.7._
           */
          function toUint24(uint256 value) internal pure returns (uint24) {
              require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
              return uint24(value);
          }
          /**
           * @dev Returns the downcasted uint16 from uint256, reverting on
           * overflow (when the input is greater than largest uint16).
           *
           * Counterpart to Solidity's `uint16` operator.
           *
           * Requirements:
           *
           * - input must fit into 16 bits
           *
           * _Available since v2.5._
           */
          function toUint16(uint256 value) internal pure returns (uint16) {
              require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
              return uint16(value);
          }
          /**
           * @dev Returns the downcasted uint8 from uint256, reverting on
           * overflow (when the input is greater than largest uint8).
           *
           * Counterpart to Solidity's `uint8` operator.
           *
           * Requirements:
           *
           * - input must fit into 8 bits
           *
           * _Available since v2.5._
           */
          function toUint8(uint256 value) internal pure returns (uint8) {
              require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
              return uint8(value);
          }
          /**
           * @dev Converts a signed int256 into an unsigned uint256.
           *
           * Requirements:
           *
           * - input must be greater than or equal to 0.
           *
           * _Available since v3.0._
           */
          function toUint256(int256 value) internal pure returns (uint256) {
              require(value >= 0, "SafeCast: value must be positive");
              return uint256(value);
          }
          /**
           * @dev Returns the downcasted int248 from int256, reverting on
           * overflow (when the input is less than smallest int248 or
           * greater than largest int248).
           *
           * Counterpart to Solidity's `int248` operator.
           *
           * Requirements:
           *
           * - input must fit into 248 bits
           *
           * _Available since v4.7._
           */
          function toInt248(int256 value) internal pure returns (int248 downcasted) {
              downcasted = int248(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
          }
          /**
           * @dev Returns the downcasted int240 from int256, reverting on
           * overflow (when the input is less than smallest int240 or
           * greater than largest int240).
           *
           * Counterpart to Solidity's `int240` operator.
           *
           * Requirements:
           *
           * - input must fit into 240 bits
           *
           * _Available since v4.7._
           */
          function toInt240(int256 value) internal pure returns (int240 downcasted) {
              downcasted = int240(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
          }
          /**
           * @dev Returns the downcasted int232 from int256, reverting on
           * overflow (when the input is less than smallest int232 or
           * greater than largest int232).
           *
           * Counterpart to Solidity's `int232` operator.
           *
           * Requirements:
           *
           * - input must fit into 232 bits
           *
           * _Available since v4.7._
           */
          function toInt232(int256 value) internal pure returns (int232 downcasted) {
              downcasted = int232(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
          }
          /**
           * @dev Returns the downcasted int224 from int256, reverting on
           * overflow (when the input is less than smallest int224 or
           * greater than largest int224).
           *
           * Counterpart to Solidity's `int224` operator.
           *
           * Requirements:
           *
           * - input must fit into 224 bits
           *
           * _Available since v4.7._
           */
          function toInt224(int256 value) internal pure returns (int224 downcasted) {
              downcasted = int224(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
          }
          /**
           * @dev Returns the downcasted int216 from int256, reverting on
           * overflow (when the input is less than smallest int216 or
           * greater than largest int216).
           *
           * Counterpart to Solidity's `int216` operator.
           *
           * Requirements:
           *
           * - input must fit into 216 bits
           *
           * _Available since v4.7._
           */
          function toInt216(int256 value) internal pure returns (int216 downcasted) {
              downcasted = int216(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
          }
          /**
           * @dev Returns the downcasted int208 from int256, reverting on
           * overflow (when the input is less than smallest int208 or
           * greater than largest int208).
           *
           * Counterpart to Solidity's `int208` operator.
           *
           * Requirements:
           *
           * - input must fit into 208 bits
           *
           * _Available since v4.7._
           */
          function toInt208(int256 value) internal pure returns (int208 downcasted) {
              downcasted = int208(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
          }
          /**
           * @dev Returns the downcasted int200 from int256, reverting on
           * overflow (when the input is less than smallest int200 or
           * greater than largest int200).
           *
           * Counterpart to Solidity's `int200` operator.
           *
           * Requirements:
           *
           * - input must fit into 200 bits
           *
           * _Available since v4.7._
           */
          function toInt200(int256 value) internal pure returns (int200 downcasted) {
              downcasted = int200(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
          }
          /**
           * @dev Returns the downcasted int192 from int256, reverting on
           * overflow (when the input is less than smallest int192 or
           * greater than largest int192).
           *
           * Counterpart to Solidity's `int192` operator.
           *
           * Requirements:
           *
           * - input must fit into 192 bits
           *
           * _Available since v4.7._
           */
          function toInt192(int256 value) internal pure returns (int192 downcasted) {
              downcasted = int192(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
          }
          /**
           * @dev Returns the downcasted int184 from int256, reverting on
           * overflow (when the input is less than smallest int184 or
           * greater than largest int184).
           *
           * Counterpart to Solidity's `int184` operator.
           *
           * Requirements:
           *
           * - input must fit into 184 bits
           *
           * _Available since v4.7._
           */
          function toInt184(int256 value) internal pure returns (int184 downcasted) {
              downcasted = int184(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
          }
          /**
           * @dev Returns the downcasted int176 from int256, reverting on
           * overflow (when the input is less than smallest int176 or
           * greater than largest int176).
           *
           * Counterpart to Solidity's `int176` operator.
           *
           * Requirements:
           *
           * - input must fit into 176 bits
           *
           * _Available since v4.7._
           */
          function toInt176(int256 value) internal pure returns (int176 downcasted) {
              downcasted = int176(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
          }
          /**
           * @dev Returns the downcasted int168 from int256, reverting on
           * overflow (when the input is less than smallest int168 or
           * greater than largest int168).
           *
           * Counterpart to Solidity's `int168` operator.
           *
           * Requirements:
           *
           * - input must fit into 168 bits
           *
           * _Available since v4.7._
           */
          function toInt168(int256 value) internal pure returns (int168 downcasted) {
              downcasted = int168(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
          }
          /**
           * @dev Returns the downcasted int160 from int256, reverting on
           * overflow (when the input is less than smallest int160 or
           * greater than largest int160).
           *
           * Counterpart to Solidity's `int160` operator.
           *
           * Requirements:
           *
           * - input must fit into 160 bits
           *
           * _Available since v4.7._
           */
          function toInt160(int256 value) internal pure returns (int160 downcasted) {
              downcasted = int160(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
          }
          /**
           * @dev Returns the downcasted int152 from int256, reverting on
           * overflow (when the input is less than smallest int152 or
           * greater than largest int152).
           *
           * Counterpart to Solidity's `int152` operator.
           *
           * Requirements:
           *
           * - input must fit into 152 bits
           *
           * _Available since v4.7._
           */
          function toInt152(int256 value) internal pure returns (int152 downcasted) {
              downcasted = int152(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
          }
          /**
           * @dev Returns the downcasted int144 from int256, reverting on
           * overflow (when the input is less than smallest int144 or
           * greater than largest int144).
           *
           * Counterpart to Solidity's `int144` operator.
           *
           * Requirements:
           *
           * - input must fit into 144 bits
           *
           * _Available since v4.7._
           */
          function toInt144(int256 value) internal pure returns (int144 downcasted) {
              downcasted = int144(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
          }
          /**
           * @dev Returns the downcasted int136 from int256, reverting on
           * overflow (when the input is less than smallest int136 or
           * greater than largest int136).
           *
           * Counterpart to Solidity's `int136` operator.
           *
           * Requirements:
           *
           * - input must fit into 136 bits
           *
           * _Available since v4.7._
           */
          function toInt136(int256 value) internal pure returns (int136 downcasted) {
              downcasted = int136(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
          }
          /**
           * @dev Returns the downcasted int128 from int256, reverting on
           * overflow (when the input is less than smallest int128 or
           * greater than largest int128).
           *
           * Counterpart to Solidity's `int128` operator.
           *
           * Requirements:
           *
           * - input must fit into 128 bits
           *
           * _Available since v3.1._
           */
          function toInt128(int256 value) internal pure returns (int128 downcasted) {
              downcasted = int128(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
          }
          /**
           * @dev Returns the downcasted int120 from int256, reverting on
           * overflow (when the input is less than smallest int120 or
           * greater than largest int120).
           *
           * Counterpart to Solidity's `int120` operator.
           *
           * Requirements:
           *
           * - input must fit into 120 bits
           *
           * _Available since v4.7._
           */
          function toInt120(int256 value) internal pure returns (int120 downcasted) {
              downcasted = int120(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
          }
          /**
           * @dev Returns the downcasted int112 from int256, reverting on
           * overflow (when the input is less than smallest int112 or
           * greater than largest int112).
           *
           * Counterpart to Solidity's `int112` operator.
           *
           * Requirements:
           *
           * - input must fit into 112 bits
           *
           * _Available since v4.7._
           */
          function toInt112(int256 value) internal pure returns (int112 downcasted) {
              downcasted = int112(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
          }
          /**
           * @dev Returns the downcasted int104 from int256, reverting on
           * overflow (when the input is less than smallest int104 or
           * greater than largest int104).
           *
           * Counterpart to Solidity's `int104` operator.
           *
           * Requirements:
           *
           * - input must fit into 104 bits
           *
           * _Available since v4.7._
           */
          function toInt104(int256 value) internal pure returns (int104 downcasted) {
              downcasted = int104(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
          }
          /**
           * @dev Returns the downcasted int96 from int256, reverting on
           * overflow (when the input is less than smallest int96 or
           * greater than largest int96).
           *
           * Counterpart to Solidity's `int96` operator.
           *
           * Requirements:
           *
           * - input must fit into 96 bits
           *
           * _Available since v4.7._
           */
          function toInt96(int256 value) internal pure returns (int96 downcasted) {
              downcasted = int96(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
          }
          /**
           * @dev Returns the downcasted int88 from int256, reverting on
           * overflow (when the input is less than smallest int88 or
           * greater than largest int88).
           *
           * Counterpart to Solidity's `int88` operator.
           *
           * Requirements:
           *
           * - input must fit into 88 bits
           *
           * _Available since v4.7._
           */
          function toInt88(int256 value) internal pure returns (int88 downcasted) {
              downcasted = int88(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
          }
          /**
           * @dev Returns the downcasted int80 from int256, reverting on
           * overflow (when the input is less than smallest int80 or
           * greater than largest int80).
           *
           * Counterpart to Solidity's `int80` operator.
           *
           * Requirements:
           *
           * - input must fit into 80 bits
           *
           * _Available since v4.7._
           */
          function toInt80(int256 value) internal pure returns (int80 downcasted) {
              downcasted = int80(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
          }
          /**
           * @dev Returns the downcasted int72 from int256, reverting on
           * overflow (when the input is less than smallest int72 or
           * greater than largest int72).
           *
           * Counterpart to Solidity's `int72` operator.
           *
           * Requirements:
           *
           * - input must fit into 72 bits
           *
           * _Available since v4.7._
           */
          function toInt72(int256 value) internal pure returns (int72 downcasted) {
              downcasted = int72(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
          }
          /**
           * @dev Returns the downcasted int64 from int256, reverting on
           * overflow (when the input is less than smallest int64 or
           * greater than largest int64).
           *
           * Counterpart to Solidity's `int64` operator.
           *
           * Requirements:
           *
           * - input must fit into 64 bits
           *
           * _Available since v3.1._
           */
          function toInt64(int256 value) internal pure returns (int64 downcasted) {
              downcasted = int64(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
          }
          /**
           * @dev Returns the downcasted int56 from int256, reverting on
           * overflow (when the input is less than smallest int56 or
           * greater than largest int56).
           *
           * Counterpart to Solidity's `int56` operator.
           *
           * Requirements:
           *
           * - input must fit into 56 bits
           *
           * _Available since v4.7._
           */
          function toInt56(int256 value) internal pure returns (int56 downcasted) {
              downcasted = int56(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
          }
          /**
           * @dev Returns the downcasted int48 from int256, reverting on
           * overflow (when the input is less than smallest int48 or
           * greater than largest int48).
           *
           * Counterpart to Solidity's `int48` operator.
           *
           * Requirements:
           *
           * - input must fit into 48 bits
           *
           * _Available since v4.7._
           */
          function toInt48(int256 value) internal pure returns (int48 downcasted) {
              downcasted = int48(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
          }
          /**
           * @dev Returns the downcasted int40 from int256, reverting on
           * overflow (when the input is less than smallest int40 or
           * greater than largest int40).
           *
           * Counterpart to Solidity's `int40` operator.
           *
           * Requirements:
           *
           * - input must fit into 40 bits
           *
           * _Available since v4.7._
           */
          function toInt40(int256 value) internal pure returns (int40 downcasted) {
              downcasted = int40(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
          }
          /**
           * @dev Returns the downcasted int32 from int256, reverting on
           * overflow (when the input is less than smallest int32 or
           * greater than largest int32).
           *
           * Counterpart to Solidity's `int32` operator.
           *
           * Requirements:
           *
           * - input must fit into 32 bits
           *
           * _Available since v3.1._
           */
          function toInt32(int256 value) internal pure returns (int32 downcasted) {
              downcasted = int32(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
          }
          /**
           * @dev Returns the downcasted int24 from int256, reverting on
           * overflow (when the input is less than smallest int24 or
           * greater than largest int24).
           *
           * Counterpart to Solidity's `int24` operator.
           *
           * Requirements:
           *
           * - input must fit into 24 bits
           *
           * _Available since v4.7._
           */
          function toInt24(int256 value) internal pure returns (int24 downcasted) {
              downcasted = int24(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
          }
          /**
           * @dev Returns the downcasted int16 from int256, reverting on
           * overflow (when the input is less than smallest int16 or
           * greater than largest int16).
           *
           * Counterpart to Solidity's `int16` operator.
           *
           * Requirements:
           *
           * - input must fit into 16 bits
           *
           * _Available since v3.1._
           */
          function toInt16(int256 value) internal pure returns (int16 downcasted) {
              downcasted = int16(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
          }
          /**
           * @dev Returns the downcasted int8 from int256, reverting on
           * overflow (when the input is less than smallest int8 or
           * greater than largest int8).
           *
           * Counterpart to Solidity's `int8` operator.
           *
           * Requirements:
           *
           * - input must fit into 8 bits
           *
           * _Available since v3.1._
           */
          function toInt8(int256 value) internal pure returns (int8 downcasted) {
              downcasted = int8(value);
              require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
          }
          /**
           * @dev Converts an unsigned uint256 into a signed int256.
           *
           * Requirements:
           *
           * - input must be less than or equal to maxInt256.
           *
           * _Available since v3.0._
           */
          function toInt256(uint256 value) internal pure returns (int256) {
              // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
              require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
              return int256(value);
          }
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      /// @dev simply a container of endpoint address and local eid
      abstract contract MessageLibBase {
          address internal immutable endpoint;
          uint32 internal immutable localEid;
          error LZ_MessageLib_OnlyEndpoint();
          modifier onlyEndpoint() {
              if (endpoint != msg.sender) revert LZ_MessageLib_OnlyEndpoint();
              _;
          }
          constructor(address _endpoint, uint32 _localEid) {
              endpoint = _endpoint;
              localEid = _localEid;
          }
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
      import { Transfer } from "@layerzerolabs/lz-evm-protocol-v2/contracts/libs/Transfer.sol";
      import { ILayerZeroExecutor } from "./interfaces/ILayerZeroExecutor.sol";
      import { ILayerZeroTreasury } from "./interfaces/ILayerZeroTreasury.sol";
      import { SafeCall } from "./libs/SafeCall.sol";
      import { MessageLibBase } from "./MessageLibBase.sol";
      struct WorkerOptions {
          uint8 workerId;
          bytes options;
      }
      struct SetDefaultExecutorConfigParam {
          uint32 eid;
          ExecutorConfig config;
      }
      struct ExecutorConfig {
          uint32 maxMessageSize;
          address executor;
      }
      /// @dev base contract for both SendLibBaseE1 and SendLibBaseE2
      abstract contract SendLibBase is MessageLibBase, Ownable {
          using SafeCall for address;
          address private constant DEFAULT_CONFIG = address(0);
          uint16 internal constant TREASURY_MAX_COPY = 32;
          uint256 internal immutable treasuryGasLimit;
          uint256 internal treasuryNativeFeeCap;
          // config
          address public treasury;
          mapping(address oapp => mapping(uint32 eid => ExecutorConfig)) public executorConfigs;
          // accumulated fees for workers and treasury
          mapping(address worker => uint256) public fees;
          event ExecutorFeePaid(address executor, uint256 fee);
          event TreasurySet(address treasury);
          event DefaultExecutorConfigsSet(SetDefaultExecutorConfigParam[] params);
          event ExecutorConfigSet(address oapp, uint32 eid, ExecutorConfig config);
          event TreasuryNativeFeeCapSet(uint256 newTreasuryNativeFeeCap);
          error LZ_MessageLib_InvalidMessageSize(uint256 actual, uint256 max);
          error LZ_MessageLib_InvalidAmount(uint256 requested, uint256 available);
          error LZ_MessageLib_TransferFailed();
          error LZ_MessageLib_InvalidExecutor();
          error LZ_MessageLib_ZeroMessageSize();
          constructor(
              address _endpoint,
              uint32 _localEid,
              uint256 _treasuryGasLimit,
              uint256 _treasuryNativeFeeCap
          ) MessageLibBase(_endpoint, _localEid) {
              treasuryGasLimit = _treasuryGasLimit;
              treasuryNativeFeeCap = _treasuryNativeFeeCap;
          }
          function setDefaultExecutorConfigs(SetDefaultExecutorConfigParam[] calldata _params) external onlyOwner {
              for (uint256 i = 0; i < _params.length; ++i) {
                  SetDefaultExecutorConfigParam calldata param = _params[i];
                  if (param.config.executor == address(0x0)) revert LZ_MessageLib_InvalidExecutor();
                  if (param.config.maxMessageSize == 0) revert LZ_MessageLib_ZeroMessageSize();
                  executorConfigs[DEFAULT_CONFIG][param.eid] = param.config;
              }
              emit DefaultExecutorConfigsSet(_params);
          }
          /// @dev the new value can not be greater than the old value, i.e. down only
          function setTreasuryNativeFeeCap(uint256 _newTreasuryNativeFeeCap) external onlyOwner {
              // assert the new value is no greater than the old value
              if (_newTreasuryNativeFeeCap > treasuryNativeFeeCap)
                  revert LZ_MessageLib_InvalidAmount(_newTreasuryNativeFeeCap, treasuryNativeFeeCap);
              treasuryNativeFeeCap = _newTreasuryNativeFeeCap;
              emit TreasuryNativeFeeCapSet(_newTreasuryNativeFeeCap);
          }
          // ============================ View ===================================
          // @dev get the executor config and if not set, return the default config
          function getExecutorConfig(address _oapp, uint32 _remoteEid) public view returns (ExecutorConfig memory rtnConfig) {
              ExecutorConfig storage defaultConfig = executorConfigs[DEFAULT_CONFIG][_remoteEid];
              ExecutorConfig storage customConfig = executorConfigs[_oapp][_remoteEid];
              uint32 maxMessageSize = customConfig.maxMessageSize;
              rtnConfig.maxMessageSize = maxMessageSize != 0 ? maxMessageSize : defaultConfig.maxMessageSize;
              address executor = customConfig.executor;
              rtnConfig.executor = executor != address(0x0) ? executor : defaultConfig.executor;
          }
          // ======================= Internal =======================
          function _assertMessageSize(uint256 _actual, uint256 _max) internal pure {
              if (_actual > _max) revert LZ_MessageLib_InvalidMessageSize(_actual, _max);
          }
          function _payExecutor(
              address _executor,
              uint32 _dstEid,
              address _sender,
              uint256 _msgSize,
              bytes memory _executorOptions
          ) internal returns (uint256 executorFee) {
              executorFee = ILayerZeroExecutor(_executor).assignJob(_dstEid, _sender, _msgSize, _executorOptions);
              if (executorFee > 0) {
                  fees[_executor] += executorFee;
              }
              emit ExecutorFeePaid(_executor, executorFee);
          }
          function _payTreasury(
              address _sender,
              uint32 _dstEid,
              uint256 _totalNativeFee,
              bool _payInLzToken
          ) internal returns (uint256 treasuryNativeFee, uint256 lzTokenFee) {
              if (treasury != address(0x0)) {
                  bytes memory callData = abi.encodeCall(
                      ILayerZeroTreasury.payFee,
                      (_sender, _dstEid, _totalNativeFee, _payInLzToken)
                  );
                  (bool success, bytes memory result) = treasury.safeCall(treasuryGasLimit, 0, TREASURY_MAX_COPY, callData);
                  (treasuryNativeFee, lzTokenFee) = _parseTreasuryResult(_totalNativeFee, _payInLzToken, success, result);
                  // fee should be in lzTokenFee if payInLzToken, otherwise in native
                  if (treasuryNativeFee > 0) {
                      fees[treasury] += treasuryNativeFee;
                  }
              }
          }
          /// @dev the abstract process for quote() is:
          /// 0/ split out the executor options and options of other workers
          /// 1/ quote workers
          /// 2/ quote executor
          /// 3/ quote treasury
          /// @return nativeFee, lzTokenFee
          function _quote(
              address _sender,
              uint32 _dstEid,
              uint256 _msgSize,
              bool _payInLzToken,
              bytes calldata _options
          ) internal view returns (uint256, uint256) {
              (bytes memory executorOptions, WorkerOptions[] memory validationOptions) = _splitOptions(_options);
              // quote the verifier used in the library. for ULN, it is a list of DVNs
              uint256 nativeFee = _quoteVerifier(_sender, _dstEid, validationOptions);
              // quote executor
              ExecutorConfig memory config = getExecutorConfig(_sender, _dstEid);
              // assert msg size
              _assertMessageSize(_msgSize, config.maxMessageSize);
              nativeFee += ILayerZeroExecutor(config.executor).getFee(_dstEid, _sender, _msgSize, executorOptions);
              // quote treasury
              (uint256 treasuryNativeFee, uint256 lzTokenFee) = _quoteTreasury(_sender, _dstEid, nativeFee, _payInLzToken);
              nativeFee += treasuryNativeFee;
              return (nativeFee, lzTokenFee);
          }
          /// @dev this interface should be DoS-free if the user is paying with native. properties
          /// 1/ treasury can return an overly high lzToken fee
          /// 2/ if treasury returns an overly high native fee, it will be capped by maxNativeFee,
          ///    which can be reasoned with the configurations
          /// 3/ the owner can not configure the treasury in a way that force this function to revert
          function _quoteTreasury(
              address _sender,
              uint32 _dstEid,
              uint256 _totalNativeFee,
              bool _payInLzToken
          ) internal view returns (uint256 nativeFee, uint256 lzTokenFee) {
              // treasury must be set, and it has to be a contract
              if (treasury != address(0x0)) {
                  bytes memory callData = abi.encodeCall(
                      ILayerZeroTreasury.getFee,
                      (_sender, _dstEid, _totalNativeFee, _payInLzToken)
                  );
                  (bool success, bytes memory result) = treasury.safeStaticCall(
                      treasuryGasLimit,
                      TREASURY_MAX_COPY,
                      callData
                  );
                  return _parseTreasuryResult(_totalNativeFee, _payInLzToken, success, result);
              }
          }
          function _parseTreasuryResult(
              uint256 _totalNativeFee,
              bool _payInLzToken,
              bool _success,
              bytes memory _result
          ) internal view returns (uint256 nativeFee, uint256 lzTokenFee) {
              // failure, charges nothing
              if (!_success || _result.length < TREASURY_MAX_COPY) return (0, 0);
              // parse the result
              uint256 treasureFeeQuote = abi.decode(_result, (uint256));
              if (_payInLzToken) {
                  lzTokenFee = treasureFeeQuote;
              } else {
                  // pay in native
                  // we must prevent high-treasuryFee Dos attack
                  // nativeFee = min(treasureFeeQuote, maxNativeFee)
                  // opportunistically raise the maxNativeFee to be the same as _totalNativeFee
                  // can't use the _totalNativeFee alone because the oapp can use custom workers to force the fee to 0.
                  // maxNativeFee = max (_totalNativeFee, treasuryNativeFeeCap)
                  uint256 maxNativeFee = _totalNativeFee > treasuryNativeFeeCap ? _totalNativeFee : treasuryNativeFeeCap;
                  // min (treasureFeeQuote, nativeFeeCap)
                  nativeFee = treasureFeeQuote > maxNativeFee ? maxNativeFee : treasureFeeQuote;
              }
          }
          /// @dev authenticated by msg.sender only
          function _debitFee(uint256 _amount) internal {
              uint256 fee = fees[msg.sender];
              if (_amount > fee) revert LZ_MessageLib_InvalidAmount(_amount, fee);
              unchecked {
                  fees[msg.sender] = fee - _amount;
              }
          }
          function _setTreasury(address _treasury) internal {
              treasury = _treasury;
              emit TreasurySet(_treasury);
          }
          function _setExecutorConfig(uint32 _remoteEid, address _oapp, ExecutorConfig memory _config) internal {
              executorConfigs[_oapp][_remoteEid] = _config;
              emit ExecutorConfigSet(_oapp, _remoteEid, _config);
          }
          // ======================= Virtual =======================
          /// @dev these two functions will be overridden with specific logics of the library function
          function _quoteVerifier(
              address _oapp,
              uint32 _eid,
              WorkerOptions[] memory _options
          ) internal view virtual returns (uint256 nativeFee);
          /// @dev this function will split the options into executorOptions and validationOptions
          function _splitOptions(
              bytes calldata _options
          ) internal view virtual returns (bytes memory executorOptions, WorkerOptions[] memory validationOptions);
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
      import { ERC165 } from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
      import { ILayerZeroEndpointV2, MessagingFee } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
      import { IMessageLib, MessageLibType } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessageLib.sol";
      import { ISendLib, Packet } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ISendLib.sol";
      import { Transfer } from "@layerzerolabs/lz-evm-protocol-v2/contracts/libs/Transfer.sol";
      import { SendLibBase, WorkerOptions, ExecutorConfig } from "./SendLibBase.sol";
      /// @dev send-side message library base contract on endpoint v2.
      /// design: the high level logic is the same as SendLibBaseE1
      /// 1/ with added interfaces
      /// 2/ adapt the functions to the new types, like uint32 for eid, address for sender.
      abstract contract SendLibBaseE2 is SendLibBase, ERC165, ISendLib {
          event NativeFeeWithdrawn(address worker, address receiver, uint256 amount);
          event LzTokenFeeWithdrawn(address lzToken, address receiver, uint256 amount);
          error LZ_MessageLib_NotTreasury();
          error LZ_MessageLib_CannotWithdrawAltToken();
          constructor(
              address _endpoint,
              uint256 _treasuryGasLimit,
              uint256 _treasuryNativeFeeCap
          ) SendLibBase(_endpoint, ILayerZeroEndpointV2(_endpoint).eid(), _treasuryGasLimit, _treasuryNativeFeeCap) {}
          function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
              return
                  _interfaceId == type(IMessageLib).interfaceId ||
                  _interfaceId == type(ISendLib).interfaceId ||
                  super.supportsInterface(_interfaceId);
          }
          // ========================= OnlyEndpoint =========================
          // @dev this function is marked as virtual and public for testing purpose
          function send(
              Packet calldata _packet,
              bytes calldata _options,
              bool _payInLzToken
          ) public virtual onlyEndpoint returns (MessagingFee memory, bytes memory) {
              (bytes memory encodedPacket, uint256 totalNativeFee) = _payWorkers(_packet, _options);
              (uint256 treasuryNativeFee, uint256 lzTokenFee) = _payTreasury(
                  _packet.sender,
                  _packet.dstEid,
                  totalNativeFee,
                  _payInLzToken
              );
              totalNativeFee += treasuryNativeFee;
              return (MessagingFee(totalNativeFee, lzTokenFee), encodedPacket);
          }
          // ========================= OnlyOwner =========================
          function setTreasury(address _treasury) external onlyOwner {
              _setTreasury(_treasury);
          }
          // ========================= External =========================
          /// @dev E2 only
          function withdrawFee(address _to, uint256 _amount) external {
              _debitFee(_amount);
              address nativeToken = ILayerZeroEndpointV2(endpoint).nativeToken();
              // transfers native if nativeToken == address(0x0)
              Transfer.nativeOrToken(nativeToken, _to, _amount);
              emit NativeFeeWithdrawn(msg.sender, _to, _amount);
          }
          /// @dev _lzToken is a user-supplied value because lzToken might change in the endpoint before all lzToken can be taken out
          /// @dev E2 only
          /// @dev treasury only function
          function withdrawLzTokenFee(address _lzToken, address _to, uint256 _amount) external {
              if (msg.sender != treasury) revert LZ_MessageLib_NotTreasury();
              // lz token cannot be the same as the native token
              if (ILayerZeroEndpointV2(endpoint).nativeToken() == _lzToken) revert LZ_MessageLib_CannotWithdrawAltToken();
              Transfer.token(_lzToken, _to, _amount);
              emit LzTokenFeeWithdrawn(_lzToken, _to, _amount);
          }
          // ========================= View =========================
          function quote(
              Packet calldata _packet,
              bytes calldata _options,
              bool _payInLzToken
          ) external view returns (MessagingFee memory) {
              (uint256 nativeFee, uint256 lzTokenFee) = _quote(
                  _packet.sender,
                  _packet.dstEid,
                  _packet.message.length,
                  _payInLzToken,
                  _options
              );
              return MessagingFee(nativeFee, lzTokenFee);
          }
          function messageLibType() external pure virtual override returns (MessageLibType) {
              return MessageLibType.Send;
          }
          // ========================= Internal =========================
          /// 1/ handle executor
          /// 2/ handle other workers
          function _payWorkers(
              Packet calldata _packet,
              bytes calldata _options
          ) internal returns (bytes memory encodedPacket, uint256 totalNativeFee) {
              // split workers options
              (bytes memory executorOptions, WorkerOptions[] memory validationOptions) = _splitOptions(_options);
              // handle executor
              ExecutorConfig memory config = getExecutorConfig(_packet.sender, _packet.dstEid);
              uint256 msgSize = _packet.message.length;
              _assertMessageSize(msgSize, config.maxMessageSize);
              totalNativeFee += _payExecutor(config.executor, _packet.dstEid, _packet.sender, msgSize, executorOptions);
              // handle other workers
              (uint256 verifierFee, bytes memory packetBytes) = _payVerifier(_packet, validationOptions); //for ULN, it will be dvns
              totalNativeFee += verifierFee;
              encodedPacket = packetBytes;
          }
          // ======================= Virtual =======================
          // For implementation to override
          function _payVerifier(
              Packet calldata _packet,
              WorkerOptions[] memory _options
          ) internal virtual returns (uint256 otherWorkerFees, bytes memory encodedPacket);
          // receive native token from endpoint
          receive() external payable virtual {}
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      interface ILayerZeroExecutor {
          // @notice query price and assign jobs at the same time
          // @param _dstEid - the destination endpoint identifier
          // @param _sender - the source sending contract address. executors may apply price discrimination to senders
          // @param _calldataSize - dynamic data size of message + caller params
          // @param _options - optional parameters for extra service plugins, e.g. sending dust tokens at the destination chain
          function assignJob(
              uint32 _dstEid,
              address _sender,
              uint256 _calldataSize,
              bytes calldata _options
          ) external returns (uint256 price);
          // @notice query the executor price for relaying the payload and its proof to the destination chain
          // @param _dstEid - the destination endpoint identifier
          // @param _sender - the source sending contract address. executors may apply price discrimination to senders
          // @param _calldataSize - dynamic data size of message + caller params
          // @param _options - optional parameters for extra service plugins, e.g. sending dust tokens at the destination chain
          function getFee(
              uint32 _dstEid,
              address _sender,
              uint256 _calldataSize,
              bytes calldata _options
          ) external view returns (uint256 price);
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      interface ILayerZeroTreasury {
          function getFee(
              address _sender,
              uint32 _dstEid,
              uint256 _totalNativeFee,
              bool _payInLzToken
          ) external view returns (uint256 fee);
          function payFee(
              address _sender,
              uint32 _dstEid,
              uint256 _totalNativeFee,
              bool _payInLzToken
          ) external payable returns (uint256 fee);
      }
      // SPDX-License-Identifier: MIT OR Apache-2.0
      pragma solidity ^0.8.20;
      /// @dev copied from https://github.com/nomad-xyz/ExcessivelySafeCall/blob/main/src/ExcessivelySafeCall.sol.
      library SafeCall {
          /// @notice calls a contract with a specified gas limit and value and captures the return data
          /// @param _target The address to call
          /// @param _gas The amount of gas to forward to the remote contract
          /// @param _value The value in wei to send to the remote contract
          /// to memory.
          /// @param _maxCopy The maximum number of bytes of returndata to copy
          /// to memory.
          /// @param _calldata The data to send to the remote contract
          /// @return success and returndata, as `.call()`. Returndata is capped to
          /// `_maxCopy` bytes.
          function safeCall(
              address _target,
              uint256 _gas,
              uint256 _value,
              uint16 _maxCopy,
              bytes memory _calldata
          ) internal returns (bool, bytes memory) {
              // check that target has code
              uint size;
              assembly {
                  size := extcodesize(_target)
              }
              if (size == 0) {
                  return (false, new bytes(0));
              }
              // set up for assembly call
              uint256 _toCopy;
              bool _success;
              bytes memory _returnData = new bytes(_maxCopy);
              // dispatch message to recipient
              // by assembly calling "handle" function
              // we call via assembly to avoid memcopying a very large returndata
              // returned by a malicious contract
              assembly {
                  _success := call(
                      _gas, // gas
                      _target, // recipient
                      _value, // ether value
                      add(_calldata, 0x20), // inloc
                      mload(_calldata), // inlen
                      0, // outloc
                      0 // outlen
                  )
                  // limit our copy to 100 bytes
                  _toCopy := returndatasize()
                  if gt(_toCopy, _maxCopy) {
                      _toCopy := _maxCopy
                  }
                  // Store the length of the copied bytes
                  mstore(_returnData, _toCopy)
                  // copy the bytes from returndata[0:_toCopy]
                  returndatacopy(add(_returnData, 0x20), 0, _toCopy)
              }
              return (_success, _returnData);
          }
          /// @notice Use when you _really_ really _really_ don't trust the called
          /// contract. This prevents the called contract from causing reversion of
          /// the caller in as many ways as we can.
          /// @dev The main difference between this and a solidity low-level call is
          /// that we limit the number of bytes that the callee can cause to be
          /// copied to caller memory. This prevents stupid things like malicious
          /// contracts returning 10,000,000 bytes causing a local OOG when copying
          /// to memory.
          /// @param _target The address to call
          /// @param _gas The amount of gas to forward to the remote contract
          /// @param _maxCopy The maximum number of bytes of returndata to copy
          /// to memory.
          /// @param _calldata The data to send to the remote contract
          /// @return success and returndata, as `.call()`. Returndata is capped to
          /// `_maxCopy` bytes.
          function safeStaticCall(
              address _target,
              uint256 _gas,
              uint16 _maxCopy,
              bytes memory _calldata
          ) internal view returns (bool, bytes memory) {
              // check that target has code
              uint size;
              assembly {
                  size := extcodesize(_target)
              }
              if (size == 0) {
                  return (false, new bytes(0));
              }
              // set up for assembly call
              uint256 _toCopy;
              bool _success;
              bytes memory _returnData = new bytes(_maxCopy);
              // dispatch message to recipient
              // by assembly calling "handle" function
              // we call via assembly to avoid memcopying a very large returndata
              // returned by a malicious contract
              assembly {
                  _success := staticcall(
                      _gas, // gas
                      _target, // recipient
                      add(_calldata, 0x20), // inloc
                      mload(_calldata), // inlen
                      0, // outloc
                      0 // outlen
                  )
                  // limit our copy to 256 bytes
                  _toCopy := returndatasize()
                  if gt(_toCopy, _maxCopy) {
                      _toCopy := _maxCopy
                  }
                  // Store the length of the copied bytes
                  mstore(_returnData, _toCopy)
                  // copy the bytes from returndata[0:_toCopy]
                  returndatacopy(add(_returnData, 0x20), 0, _toCopy)
              }
              return (_success, _returnData);
          }
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { Packet } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ISendLib.sol";
      import { PacketV1Codec } from "@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/PacketV1Codec.sol";
      import { ILayerZeroDVN } from "./interfaces/ILayerZeroDVN.sol";
      import { DVNOptions } from "./libs/DVNOptions.sol";
      import { UlnOptions } from "./libs/UlnOptions.sol";
      import { WorkerOptions } from "../SendLibBase.sol";
      import { UlnConfig, UlnBase } from "./UlnBase.sol";
      /// @dev includes the utility functions for checking ULN states and logics
      abstract contract SendUlnBase is UlnBase {
          event DVNFeePaid(address[] requiredDVNs, address[] optionalDVNs, uint256[] fees);
          function _splitUlnOptions(bytes calldata _options) internal pure returns (bytes memory, WorkerOptions[] memory) {
              (bytes memory executorOpts, bytes memory dvnOpts) = UlnOptions.decode(_options);
              if (dvnOpts.length == 0) {
                  return (executorOpts, new WorkerOptions[](0));
              }
              WorkerOptions[] memory workerOpts = new WorkerOptions[](1);
              workerOpts[0] = WorkerOptions(DVNOptions.WORKER_ID, dvnOpts);
              return (executorOpts, workerOpts);
          }
          /// ---------- pay and assign jobs ----------
          function _payDVNs(
              mapping(address => uint256) storage _fees,
              Packet memory _packet,
              WorkerOptions[] memory _options
          ) internal returns (uint256 totalFee, bytes memory encodedPacket) {
              bytes memory packetHeader = PacketV1Codec.encodePacketHeader(_packet);
              bytes memory payload = PacketV1Codec.encodePayload(_packet);
              bytes32 payloadHash = keccak256(payload);
              uint32 dstEid = _packet.dstEid;
              address sender = _packet.sender;
              UlnConfig memory config = getUlnConfig(sender, dstEid);
              // if options is not empty, it must be dvn options
              bytes memory dvnOptions = _options.length == 0 ? bytes("") : _options[0].options;
              uint256[] memory dvnFees;
              (totalFee, dvnFees) = _assignJobs(
                  _fees,
                  config,
                  ILayerZeroDVN.AssignJobParam(dstEid, packetHeader, payloadHash, config.confirmations, sender),
                  dvnOptions
              );
              encodedPacket = abi.encodePacked(packetHeader, payload);
              emit DVNFeePaid(config.requiredDVNs, config.optionalDVNs, dvnFees);
          }
          function _assignJobs(
              mapping(address => uint256) storage _fees,
              UlnConfig memory _ulnConfig,
              ILayerZeroDVN.AssignJobParam memory _param,
              bytes memory dvnOptions
          ) internal returns (uint256 totalFee, uint256[] memory dvnFees) {
              (bytes[] memory optionsArray, uint8[] memory dvnIds) = DVNOptions.groupDVNOptionsByIdx(dvnOptions);
              uint8 dvnsLength = _ulnConfig.requiredDVNCount + _ulnConfig.optionalDVNCount;
              dvnFees = new uint256[](dvnsLength);
              for (uint8 i = 0; i < dvnsLength; ++i) {
                  address dvn = i < _ulnConfig.requiredDVNCount
                      ? _ulnConfig.requiredDVNs[i]
                      : _ulnConfig.optionalDVNs[i - _ulnConfig.requiredDVNCount];
                  bytes memory options = "";
                  for (uint256 j = 0; j < dvnIds.length; ++j) {
                      if (dvnIds[j] == i) {
                          options = optionsArray[j];
                          break;
                      }
                  }
                  dvnFees[i] = ILayerZeroDVN(dvn).assignJob(_param, options);
                  if (dvnFees[i] > 0) {
                      _fees[dvn] += dvnFees[i];
                      totalFee += dvnFees[i];
                  }
              }
          }
          /// ---------- quote ----------
          function _quoteDVNs(
              address _sender,
              uint32 _dstEid,
              WorkerOptions[] memory _options
          ) internal view returns (uint256 totalFee) {
              UlnConfig memory config = getUlnConfig(_sender, _dstEid);
              // if options is not empty, it must be dvn options
              bytes memory dvnOptions = _options.length == 0 ? bytes("") : _options[0].options;
              (bytes[] memory optionsArray, uint8[] memory dvnIndices) = DVNOptions.groupDVNOptionsByIdx(dvnOptions);
              totalFee = _getFees(config, _dstEid, _sender, optionsArray, dvnIndices);
          }
          function _getFees(
              UlnConfig memory _config,
              uint32 _dstEid,
              address _sender,
              bytes[] memory _optionsArray,
              uint8[] memory _dvnIds
          ) internal view returns (uint256 totalFee) {
              // here we merge 2 list of dvns into 1 to allocate the indexed dvn options to the right dvn
              uint8 dvnsLength = _config.requiredDVNCount + _config.optionalDVNCount;
              for (uint8 i = 0; i < dvnsLength; ++i) {
                  address dvn = i < _config.requiredDVNCount
                      ? _config.requiredDVNs[i]
                      : _config.optionalDVNs[i - _config.requiredDVNCount];
                  bytes memory options = "";
                  // it is a double loop here. however, if the list is short, the cost is very acceptable.
                  for (uint256 j = 0; j < _dvnIds.length; ++j) {
                      if (_dvnIds[j] == i) {
                          options = _optionsArray[j];
                          break;
                      }
                  }
                  totalFee += ILayerZeroDVN(dvn).getFee(_dstEid, _config.confirmations, _sender, options);
              }
          }
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
      // the formal properties are documented in the setter functions
      struct UlnConfig {
          uint64 confirmations;
          // we store the length of required DVNs and optional DVNs instead of using DVN.length directly to save gas
          uint8 requiredDVNCount; // 0 indicate DEFAULT, NIL_DVN_COUNT indicate NONE (to override the value of default)
          uint8 optionalDVNCount; // 0 indicate DEFAULT, NIL_DVN_COUNT indicate NONE (to override the value of default)
          uint8 optionalDVNThreshold; // (0, optionalDVNCount]
          address[] requiredDVNs; // no duplicates. sorted an an ascending order. allowed overlap with optionalDVNs
          address[] optionalDVNs; // no duplicates. sorted an an ascending order. allowed overlap with requiredDVNs
      }
      struct SetDefaultUlnConfigParam {
          uint32 eid;
          UlnConfig config;
      }
      /// @dev includes the utility functions for checking ULN states and logics
      abstract contract UlnBase is Ownable {
          address private constant DEFAULT_CONFIG = address(0);
          // reserved values for
          uint8 internal constant DEFAULT = 0;
          uint8 internal constant NIL_DVN_COUNT = type(uint8).max;
          uint64 internal constant NIL_CONFIRMATIONS = type(uint64).max;
          // 127 to prevent total number of DVNs (127 * 2) exceeding uint8.max (255)
          // by limiting the total size, it would help constraint the design of DVNOptions
          uint8 private constant MAX_COUNT = (type(uint8).max - 1) / 2;
          mapping(address oapp => mapping(uint32 eid => UlnConfig)) internal ulnConfigs;
          error LZ_ULN_Unsorted();
          error LZ_ULN_InvalidRequiredDVNCount();
          error LZ_ULN_InvalidOptionalDVNCount();
          error LZ_ULN_AtLeastOneDVN();
          error LZ_ULN_InvalidOptionalDVNThreshold();
          error LZ_ULN_InvalidConfirmations();
          error LZ_ULN_UnsupportedEid(uint32 eid);
          event DefaultUlnConfigsSet(SetDefaultUlnConfigParam[] params);
          event UlnConfigSet(address oapp, uint32 eid, UlnConfig config);
          // ============================ OnlyOwner ===================================
          /// @dev about the DEFAULT ULN config
          /// 1) its values are all LITERAL (e.g. 0 is 0). whereas in the oapp ULN config, 0 (default value) points to the default ULN config
          ///     this design enables the oapp to point to DEFAULT config without explicitly setting the config
          /// 2) its configuration is more restrictive than the oapp ULN config that
          ///     a) it must not use NIL value, where NIL is used only by oapps to indicate the LITERAL 0
          ///     b) it must have at least one DVN
          function setDefaultUlnConfigs(SetDefaultUlnConfigParam[] calldata _params) external onlyOwner {
              for (uint256 i = 0; i < _params.length; ++i) {
                  SetDefaultUlnConfigParam calldata param = _params[i];
                  // 2.a must not use NIL
                  if (param.config.requiredDVNCount == NIL_DVN_COUNT) revert LZ_ULN_InvalidRequiredDVNCount();
                  if (param.config.optionalDVNCount == NIL_DVN_COUNT) revert LZ_ULN_InvalidOptionalDVNCount();
                  if (param.config.confirmations == NIL_CONFIRMATIONS) revert LZ_ULN_InvalidConfirmations();
                  // 2.b must have at least one dvn
                  _assertAtLeastOneDVN(param.config);
                  _setConfig(DEFAULT_CONFIG, param.eid, param.config);
              }
              emit DefaultUlnConfigsSet(_params);
          }
          // ============================ View ===================================
          // @dev assuming most oapps use default, we get default as memory and custom as storage to save gas
          function getUlnConfig(address _oapp, uint32 _remoteEid) public view returns (UlnConfig memory rtnConfig) {
              UlnConfig storage defaultConfig = ulnConfigs[DEFAULT_CONFIG][_remoteEid];
              UlnConfig storage customConfig = ulnConfigs[_oapp][_remoteEid];
              // if confirmations is 0, use default
              uint64 confirmations = customConfig.confirmations;
              if (confirmations == DEFAULT) {
                  rtnConfig.confirmations = defaultConfig.confirmations;
              } else if (confirmations != NIL_CONFIRMATIONS) {
                  // if confirmations is uint64.max, no block confirmations required
                  rtnConfig.confirmations = confirmations;
              } // else do nothing, rtnConfig.confirmation is 0
              if (customConfig.requiredDVNCount == DEFAULT) {
                  if (defaultConfig.requiredDVNCount > 0) {
                      // copy only if count > 0. save gas
                      rtnConfig.requiredDVNs = defaultConfig.requiredDVNs;
                      rtnConfig.requiredDVNCount = defaultConfig.requiredDVNCount;
                  } // else, do nothing
              } else {
                  if (customConfig.requiredDVNCount != NIL_DVN_COUNT) {
                      rtnConfig.requiredDVNs = customConfig.requiredDVNs;
                      rtnConfig.requiredDVNCount = customConfig.requiredDVNCount;
                  } // else, do nothing
              }
              if (customConfig.optionalDVNCount == DEFAULT) {
                  if (defaultConfig.optionalDVNCount > 0) {
                      // copy only if count > 0. save gas
                      rtnConfig.optionalDVNs = defaultConfig.optionalDVNs;
                      rtnConfig.optionalDVNCount = defaultConfig.optionalDVNCount;
                      rtnConfig.optionalDVNThreshold = defaultConfig.optionalDVNThreshold;
                  }
              } else {
                  if (customConfig.optionalDVNCount != NIL_DVN_COUNT) {
                      rtnConfig.optionalDVNs = customConfig.optionalDVNs;
                      rtnConfig.optionalDVNCount = customConfig.optionalDVNCount;
                      rtnConfig.optionalDVNThreshold = customConfig.optionalDVNThreshold;
                  }
              }
              // the final value must have at least one dvn
              // it is possible that some default config result into 0 dvns
              _assertAtLeastOneDVN(rtnConfig);
          }
          /// @dev Get the uln config without the default config for the given remoteEid.
          function getAppUlnConfig(address _oapp, uint32 _remoteEid) external view returns (UlnConfig memory) {
              return ulnConfigs[_oapp][_remoteEid];
          }
          // ============================ Internal ===================================
          function _setUlnConfig(uint32 _remoteEid, address _oapp, UlnConfig memory _param) internal {
              _setConfig(_oapp, _remoteEid, _param);
              // get ULN config again as a catch all to ensure the config is valid
              getUlnConfig(_oapp, _remoteEid);
              emit UlnConfigSet(_oapp, _remoteEid, _param);
          }
          /// @dev a supported Eid must have a valid default uln config, which has at least one dvn
          function _isSupportedEid(uint32 _remoteEid) internal view returns (bool) {
              UlnConfig storage defaultConfig = ulnConfigs[DEFAULT_CONFIG][_remoteEid];
              return defaultConfig.requiredDVNCount > 0 || defaultConfig.optionalDVNThreshold > 0;
          }
          function _assertSupportedEid(uint32 _remoteEid) internal view {
              if (!_isSupportedEid(_remoteEid)) revert LZ_ULN_UnsupportedEid(_remoteEid);
          }
          // ============================ Private ===================================
          function _assertAtLeastOneDVN(UlnConfig memory _config) private pure {
              if (_config.requiredDVNCount == 0 && _config.optionalDVNThreshold == 0) revert LZ_ULN_AtLeastOneDVN();
          }
          /// @dev this private function is used in both setDefaultUlnConfigs and setUlnConfig
          function _setConfig(address _oapp, uint32 _eid, UlnConfig memory _param) private {
              // @dev required dvns
              // if dvnCount == NONE, dvns list must be empty
              // if dvnCount == DEFAULT, dvn list must be empty
              // otherwise, dvnList.length == dvnCount and assert the list is valid
              if (_param.requiredDVNCount == NIL_DVN_COUNT || _param.requiredDVNCount == DEFAULT) {
                  if (_param.requiredDVNs.length != 0) revert LZ_ULN_InvalidRequiredDVNCount();
              } else {
                  if (_param.requiredDVNs.length != _param.requiredDVNCount || _param.requiredDVNCount > MAX_COUNT)
                      revert LZ_ULN_InvalidRequiredDVNCount();
                  _assertNoDuplicates(_param.requiredDVNs);
              }
              // @dev optional dvns
              // if optionalDVNCount == NONE, optionalDVNs list must be empty and threshold must be 0
              // if optionalDVNCount == DEFAULT, optionalDVNs list must be empty and threshold must be 0
              // otherwise, optionalDVNs.length == optionalDVNCount, threshold > 0 && threshold <= optionalDVNCount and assert the list is valid
              // example use case: an oapp uses the DEFAULT 'required' but
              //     a) use a custom 1/1 dvn (practically a required dvn), or
              //     b) use a custom 2/3 dvn
              if (_param.optionalDVNCount == NIL_DVN_COUNT || _param.optionalDVNCount == DEFAULT) {
                  if (_param.optionalDVNs.length != 0) revert LZ_ULN_InvalidOptionalDVNCount();
                  if (_param.optionalDVNThreshold != 0) revert LZ_ULN_InvalidOptionalDVNThreshold();
              } else {
                  if (_param.optionalDVNs.length != _param.optionalDVNCount || _param.optionalDVNCount > MAX_COUNT)
                      revert LZ_ULN_InvalidOptionalDVNCount();
                  if (_param.optionalDVNThreshold == 0 || _param.optionalDVNThreshold > _param.optionalDVNCount)
                      revert LZ_ULN_InvalidOptionalDVNThreshold();
                  _assertNoDuplicates(_param.optionalDVNs);
              }
              // don't assert valid count here, as it needs to be validated along side default config
              ulnConfigs[_oapp][_eid] = _param;
          }
          function _assertNoDuplicates(address[] memory _dvns) private pure {
              address lastDVN = address(0);
              for (uint256 i = 0; i < _dvns.length; i++) {
                  address dvn = _dvns[i];
                  if (dvn <= lastDVN) revert LZ_ULN_Unsorted(); // to ensure no duplicates
                  lastDVN = dvn;
              }
          }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      interface ILayerZeroDVN {
          struct AssignJobParam {
              uint32 dstEid;
              bytes packetHeader;
              bytes32 payloadHash;
              uint64 confirmations;
              address sender;
          }
          // @notice query price and assign jobs at the same time
          // @param _dstEid - the destination endpoint identifier
          // @param _packetHeader - version + nonce + path
          // @param _payloadHash - hash of guid + message
          // @param _confirmations - block confirmation delay before relaying blocks
          // @param _sender - the source sending contract address
          // @param _options - options
          function assignJob(AssignJobParam calldata _param, bytes calldata _options) external payable returns (uint256 fee);
          // @notice query the dvn fee for relaying block information to the destination chain
          // @param _dstEid the destination endpoint identifier
          // @param _confirmations - block confirmation delay before relaying blocks
          // @param _sender - the source sending contract address
          // @param _options - options
          function getFee(
              uint32 _dstEid,
              uint64 _confirmations,
              address _sender,
              bytes calldata _options
          ) external view returns (uint256 fee);
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { BytesLib } from "solidity-bytes-utils/contracts/BytesLib.sol";
      import { BitMap256 } from "@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/BitMaps.sol";
      import { CalldataBytesLib } from "@layerzerolabs/lz-evm-protocol-v2/contracts/libs/CalldataBytesLib.sol";
      library DVNOptions {
          using CalldataBytesLib for bytes;
          using BytesLib for bytes;
          uint8 internal constant WORKER_ID = 2;
          uint8 internal constant OPTION_TYPE_PRECRIME = 1;
          error DVN_InvalidDVNIdx();
          error DVN_InvalidDVNOptions(uint256 cursor);
          /// @dev group dvn options by its idx
          /// @param _options [dvn_id][dvn_option][dvn_id][dvn_option]...
          ///        dvn_option = [option_size][dvn_idx][option_type][option]
          ///        option_size = len(dvn_idx) + len(option_type) + len(option)
          ///        dvn_id: uint8, dvn_idx: uint8, option_size: uint16, option_type: uint8, option: bytes
          /// @return dvnOptions the grouped options, still share the same format of _options
          /// @return dvnIndices the dvn indices
          function groupDVNOptionsByIdx(
              bytes memory _options
          ) internal pure returns (bytes[] memory dvnOptions, uint8[] memory dvnIndices) {
              if (_options.length == 0) return (dvnOptions, dvnIndices);
              uint8 numDVNs = getNumDVNs(_options);
              // if there is only 1 dvn, we can just return the whole options
              if (numDVNs == 1) {
                  dvnOptions = new bytes[](1);
                  dvnOptions[0] = _options;
                  dvnIndices = new uint8[](1);
                  dvnIndices[0] = _options.toUint8(3); // dvn idx
                  return (dvnOptions, dvnIndices);
              }
              // otherwise, we need to group the options by dvn_idx
              dvnIndices = new uint8[](numDVNs);
              dvnOptions = new bytes[](numDVNs);
              unchecked {
                  uint256 cursor = 0;
                  uint256 start = 0;
                  uint8 lastDVNIdx = 255; // 255 is an invalid dvn_idx
                  while (cursor < _options.length) {
                      ++cursor; // skip worker_id
                      // optionLength asserted in getNumDVNs (skip check)
                      uint16 optionLength = _options.toUint16(cursor);
                      cursor += 2;
                      // dvnIdx asserted in getNumDVNs (skip check)
                      uint8 dvnIdx = _options.toUint8(cursor);
                      // dvnIdx must equal to the lastDVNIdx for the first option
                      // so it is always skipped in the first option
                      // this operation slices out options whenever the scan finds a different lastDVNIdx
                      if (lastDVNIdx == 255) {
                          lastDVNIdx = dvnIdx;
                      } else if (dvnIdx != lastDVNIdx) {
                          uint256 len = cursor - start - 3; // 3 is for worker_id and option_length
                          bytes memory opt = _options.slice(start, len);
                          _insertDVNOptions(dvnOptions, dvnIndices, lastDVNIdx, opt);
                          // reset the start and lastDVNIdx
                          start += len;
                          lastDVNIdx = dvnIdx;
                      }
                      cursor += optionLength;
                  }
                  // skip check the cursor here because the cursor is asserted in getNumDVNs
                  // if we have reached the end of the options, we need to process the last dvn
                  uint256 size = cursor - start;
                  bytes memory op = _options.slice(start, size);
                  _insertDVNOptions(dvnOptions, dvnIndices, lastDVNIdx, op);
                  // revert dvnIndices to start from 0
                  for (uint8 i = 0; i < numDVNs; ++i) {
                      --dvnIndices[i];
                  }
              }
          }
          function _insertDVNOptions(
              bytes[] memory _dvnOptions,
              uint8[] memory _dvnIndices,
              uint8 _dvnIdx,
              bytes memory _newOptions
          ) internal pure {
              // dvnIdx starts from 0 but default value of dvnIndices is 0,
              // so we tell if the slot is empty by adding 1 to dvnIdx
              if (_dvnIdx == 255) revert DVN_InvalidDVNIdx();
              uint8 dvnIdxAdj = _dvnIdx + 1;
              for (uint256 j = 0; j < _dvnIndices.length; ++j) {
                  uint8 index = _dvnIndices[j];
                  if (dvnIdxAdj == index) {
                      _dvnOptions[j] = abi.encodePacked(_dvnOptions[j], _newOptions);
                      break;
                  } else if (index == 0) {
                      // empty slot, that means it is the first time we see this dvn
                      _dvnIndices[j] = dvnIdxAdj;
                      _dvnOptions[j] = _newOptions;
                      break;
                  }
              }
          }
          /// @dev get the number of unique dvns
          /// @param _options the format is the same as groupDVNOptionsByIdx
          function getNumDVNs(bytes memory _options) internal pure returns (uint8 numDVNs) {
              uint256 cursor = 0;
              BitMap256 bitmap;
              // find number of unique dvn_idx
              unchecked {
                  while (cursor < _options.length) {
                      ++cursor; // skip worker_id
                      uint16 optionLength = _options.toUint16(cursor);
                      cursor += 2;
                      if (optionLength < 2) revert DVN_InvalidDVNOptions(cursor); // at least 1 byte for dvn_idx and 1 byte for option_type
                      uint8 dvnIdx = _options.toUint8(cursor);
                      // if dvnIdx is not set, increment numDVNs
                      // max num of dvns is 255, 255 is an invalid dvn_idx
                      // The order of the dvnIdx is not required to be sequential, as enforcing the order may weaken
                      // the composability of the options. e.g. if we refrain from enforcing the order, an OApp that has
                      // already enforced certain options can append additional options to the end of the enforced
                      // ones without restrictions.
                      if (dvnIdx == 255) revert DVN_InvalidDVNIdx();
                      if (!bitmap.get(dvnIdx)) {
                          ++numDVNs;
                          bitmap = bitmap.set(dvnIdx);
                      }
                      cursor += optionLength;
                  }
              }
              if (cursor != _options.length) revert DVN_InvalidDVNOptions(cursor);
          }
          /// @dev decode the next dvn option from _options starting from the specified cursor
          /// @param _options the format is the same as groupDVNOptionsByIdx
          /// @param _cursor the cursor to start decoding
          /// @return optionType the type of the option
          /// @return option the option
          /// @return cursor the cursor to start decoding the next option
          function nextDVNOption(
              bytes calldata _options,
              uint256 _cursor
          ) internal pure returns (uint8 optionType, bytes calldata option, uint256 cursor) {
              unchecked {
                  // skip worker id
                  cursor = _cursor + 1;
                  // read option size
                  uint16 size = _options.toU16(cursor);
                  cursor += 2;
                  // read option type
                  optionType = _options.toU8(cursor + 1); // skip dvn_idx
                  // startCursor and endCursor are used to slice the option from _options
                  uint256 startCursor = cursor + 2; // skip option type and dvn_idx
                  uint256 endCursor = cursor + size;
                  option = _options[startCursor:endCursor];
                  cursor += size;
              }
          }
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
      import { ExecutorOptions } from "@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/ExecutorOptions.sol";
      import { DVNOptions } from "./DVNOptions.sol";
      library UlnOptions {
          using SafeCast for uint256;
          uint16 internal constant TYPE_1 = 1; // legacy options type 1
          uint16 internal constant TYPE_2 = 2; // legacy options type 2
          uint16 internal constant TYPE_3 = 3;
          error LZ_ULN_InvalidWorkerOptions(uint256 cursor);
          error LZ_ULN_InvalidWorkerId(uint8 workerId);
          error LZ_ULN_InvalidLegacyType1Option();
          error LZ_ULN_InvalidLegacyType2Option();
          error LZ_ULN_UnsupportedOptionType(uint16 optionType);
          /// @dev decode the options into executorOptions and dvnOptions
          /// @param _options the options can be either legacy options (type 1 or 2) or type 3 options
          /// @return executorOptions the executor options, share the same format of type 3 options
          /// @return dvnOptions the dvn options, share the same format of type 3 options
          function decode(
              bytes calldata _options
          ) internal pure returns (bytes memory executorOptions, bytes memory dvnOptions) {
              // at least 2 bytes for the option type, but can have no options
              if (_options.length < 2) revert LZ_ULN_InvalidWorkerOptions(0);
              uint16 optionsType = uint16(bytes2(_options[0:2]));
              uint256 cursor = 2;
              // type3 options: [worker_option][worker_option]...
              // worker_option: [worker_id][option_size][option]
              // worker_id: uint8, option_size: uint16, option: bytes
              if (optionsType == TYPE_3) {
                  unchecked {
                      uint256 start = cursor;
                      uint8 lastWorkerId; // worker_id starts from 1, so 0 is an invalid worker_id
                      // heuristic: we assume that the options are mostly EXECUTOR options only
                      // checking the workerID can reduce gas usage for most cases
                      while (cursor < _options.length) {
                          uint8 workerId = uint8(bytes1(_options[cursor:cursor + 1]));
                          if (workerId == 0) revert LZ_ULN_InvalidWorkerId(0);
                          // workerId must equal to the lastWorkerId for the first option
                          // so it is always skipped in the first option
                          // this operation slices out options whenever the the scan finds a different workerId
                          if (lastWorkerId == 0) {
                              lastWorkerId = workerId;
                          } else if (workerId != lastWorkerId) {
                              bytes calldata op = _options[start:cursor]; // slice out the last worker's options
                              (executorOptions, dvnOptions) = _insertWorkerOptions(
                                  executorOptions,
                                  dvnOptions,
                                  lastWorkerId,
                                  op
                              );
                              // reset the start cursor and lastWorkerId
                              start = cursor;
                              lastWorkerId = workerId;
                          }
                          ++cursor; // for workerId
                          uint16 size = uint16(bytes2(_options[cursor:cursor + 2]));
                          if (size == 0) revert LZ_ULN_InvalidWorkerOptions(cursor);
                          cursor += size + 2;
                      }
                      // the options length must be the same as the cursor at the end
                      if (cursor != _options.length) revert LZ_ULN_InvalidWorkerOptions(cursor);
                      // if we have reached the end of the options and the options are not empty
                      // we need to process the last worker's options
                      if (_options.length > 2) {
                          bytes calldata op = _options[start:cursor];
                          (executorOptions, dvnOptions) = _insertWorkerOptions(executorOptions, dvnOptions, lastWorkerId, op);
                      }
                  }
              } else {
                  executorOptions = decodeLegacyOptions(optionsType, _options);
              }
          }
          function _insertWorkerOptions(
              bytes memory _executorOptions,
              bytes memory _dvnOptions,
              uint8 _workerId,
              bytes calldata _newOptions
          ) private pure returns (bytes memory, bytes memory) {
              if (_workerId == ExecutorOptions.WORKER_ID) {
                  _executorOptions = _executorOptions.length == 0
                      ? _newOptions
                      : abi.encodePacked(_executorOptions, _newOptions);
              } else if (_workerId == DVNOptions.WORKER_ID) {
                  _dvnOptions = _dvnOptions.length == 0 ? _newOptions : abi.encodePacked(_dvnOptions, _newOptions);
              } else {
                  revert LZ_ULN_InvalidWorkerId(_workerId);
              }
              return (_executorOptions, _dvnOptions);
          }
          /// @dev decode the legacy options (type 1 or 2) into executorOptions
          /// @param _optionType the legacy option type
          /// @param _options the legacy options, which still has the option type in the first 2 bytes
          /// @return executorOptions the executor options, share the same format of type 3 options
          /// Data format:
          /// legacy type 1: [extraGas]
          /// legacy type 2: [extraGas][dstNativeAmt][dstNativeAddress]
          /// extraGas: uint256, dstNativeAmt: uint256, dstNativeAddress: bytes
          function decodeLegacyOptions(
              uint16 _optionType,
              bytes calldata _options
          ) internal pure returns (bytes memory executorOptions) {
              if (_optionType == TYPE_1) {
                  if (_options.length != 34) revert LZ_ULN_InvalidLegacyType1Option();
                  // execution gas
                  uint128 executionGas = uint256(bytes32(_options[2:2 + 32])).toUint128();
                  // dont use the encode function in the ExecutorOptions lib for saving gas by calling abi.encodePacked once
                  // the result is a lzReceive option: [executor_id][option_size][option_type][execution_gas]
                  // option_type: uint8, execution_gas: uint128
                  // option_size = len(option_type) + len(execution_gas) = 1 + 16 = 17
                  executorOptions = abi.encodePacked(
                      ExecutorOptions.WORKER_ID,
                      uint16(17), // 16 + 1, 16 for option_length, + 1 for option_type
                      ExecutorOptions.OPTION_TYPE_LZRECEIVE,
                      executionGas
                  );
              } else if (_optionType == TYPE_2) {
                  // receiver size <= 32
                  if (_options.length <= 66 || _options.length > 98) revert LZ_ULN_InvalidLegacyType2Option();
                  // execution gas
                  uint128 executionGas = uint256(bytes32(_options[2:2 + 32])).toUint128();
                  // nativeDrop (amount + receiver)
                  uint128 amount = uint256(bytes32(_options[34:34 + 32])).toUint128(); // offset 2 + 32
                  bytes32 receiver;
                  unchecked {
                      uint256 receiverLen = _options.length - 66; // offset 2 + 32 + 32
                      receiver = bytes32(_options[66:]);
                      receiver = receiver >> (8 * (32 - receiverLen)); // padding 0 to the left
                  }
                  // dont use the encode function in the ExecutorOptions lib for saving gas by calling abi.encodePacked once
                  // the result has one lzReceive option and one nativeDrop option:
                  //      [executor_id][lzReceive_option_size][option_type][execution_gas] +
                  //      [executor_id][nativeDrop_option_size][option_type][nativeDrop_amount][receiver]
                  // option_type: uint8, execution_gas: uint128, nativeDrop_amount: uint128, receiver: bytes32
                  // lzReceive_option_size = len(option_type) + len(execution_gas) = 1 + 16 = 17
                  // nativeDrop_option_size = len(option_type) + len(nativeDrop_amount) + len(receiver) = 1 + 16 + 32 = 49
                  executorOptions = abi.encodePacked(
                      ExecutorOptions.WORKER_ID,
                      uint16(17), // 16 + 1, 16 for option_length, + 1 for option_type
                      ExecutorOptions.OPTION_TYPE_LZRECEIVE,
                      executionGas,
                      ExecutorOptions.WORKER_ID,
                      uint16(49), // 48 + 1, 32 + 16 for option_length, + 1 for option_type
                      ExecutorOptions.OPTION_TYPE_NATIVE_DROP,
                      amount,
                      receiver
                  );
              } else {
                  revert LZ_ULN_UnsupportedOptionType(_optionType);
              }
          }
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { Packet } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ISendLib.sol";
      import { SetConfigParam } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessageLibManager.sol";
      import { ExecutorConfig } from "../../SendLibBase.sol";
      import { SendLibBaseE2, WorkerOptions } from "../../SendLibBaseE2.sol";
      import { UlnConfig } from "../UlnBase.sol";
      import { SendUlnBase } from "../SendUlnBase.sol";
      /// @dev This is a gluing contract. It simply parses the requests and forward to the super.impl() accordingly.
      /// @dev In this case, it combines the logic of SendUlnBase and SendLibBaseE2
      contract SendUln302 is SendUlnBase, SendLibBaseE2 {
          uint32 internal constant CONFIG_TYPE_EXECUTOR = 1;
          uint32 internal constant CONFIG_TYPE_ULN = 2;
          error LZ_ULN_InvalidConfigType(uint32 configType);
          constructor(
              address _endpoint,
              uint256 _treasuryGasLimit,
              uint256 _treasuryGasForFeeCap
          ) SendLibBaseE2(_endpoint, _treasuryGasLimit, _treasuryGasForFeeCap) {}
          // ============================ OnlyEndpoint ===================================
          // on the send side the user can config both the executor and the ULN
          function setConfig(address _oapp, SetConfigParam[] calldata _params) external override onlyEndpoint {
              for (uint256 i = 0; i < _params.length; i++) {
                  SetConfigParam calldata param = _params[i];
                  _assertSupportedEid(param.eid);
                  if (param.configType == CONFIG_TYPE_EXECUTOR) {
                      _setExecutorConfig(param.eid, _oapp, abi.decode(param.config, (ExecutorConfig)));
                  } else if (param.configType == CONFIG_TYPE_ULN) {
                      _setUlnConfig(param.eid, _oapp, abi.decode(param.config, (UlnConfig)));
                  } else {
                      revert LZ_ULN_InvalidConfigType(param.configType);
                  }
              }
          }
          // ============================ View ===================================
          function getConfig(uint32 _eid, address _oapp, uint32 _configType) external view override returns (bytes memory) {
              if (_configType == CONFIG_TYPE_EXECUTOR) {
                  return abi.encode(getExecutorConfig(_oapp, _eid));
              } else if (_configType == CONFIG_TYPE_ULN) {
                  return abi.encode(getUlnConfig(_oapp, _eid));
              } else {
                  revert LZ_ULN_InvalidConfigType(_configType);
              }
          }
          function version() external pure override returns (uint64 major, uint8 minor, uint8 endpointVersion) {
              return (3, 0, 2);
          }
          function isSupportedEid(uint32 _eid) external view override returns (bool) {
              return _isSupportedEid(_eid);
          }
          // ============================ Internal ===================================
          function _quoteVerifier(
              address _sender,
              uint32 _dstEid,
              WorkerOptions[] memory _options
          ) internal view override returns (uint256) {
              return _quoteDVNs(_sender, _dstEid, _options);
          }
          function _payVerifier(
              Packet calldata _packet,
              WorkerOptions[] memory _options
          ) internal override returns (uint256 otherWorkerFees, bytes memory encodedPacket) {
              (otherWorkerFees, encodedPacket) = _payDVNs(fees, _packet, _options);
          }
          function _splitOptions(
              bytes calldata _options
          ) internal pure override returns (bytes memory, WorkerOptions[] memory) {
              return _splitUlnOptions(_options);
          }
      }
      // SPDX-License-Identifier: Unlicense
      /*
       * @title Solidity Bytes Arrays Utils
       * @author Gonçalo Sá <[email protected]>
       *
       * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
       *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
       */
      pragma solidity >=0.8.0 <0.9.0;
      library BytesLib {
          function concat(
              bytes memory _preBytes,
              bytes memory _postBytes
          )
              internal
              pure
              returns (bytes memory)
          {
              bytes memory tempBytes;
              assembly {
                  // Get a location of some free memory and store it in tempBytes as
                  // Solidity does for memory variables.
                  tempBytes := mload(0x40)
                  // Store the length of the first bytes array at the beginning of
                  // the memory for tempBytes.
                  let length := mload(_preBytes)
                  mstore(tempBytes, length)
                  // Maintain a memory counter for the current write location in the
                  // temp bytes array by adding the 32 bytes for the array length to
                  // the starting location.
                  let mc := add(tempBytes, 0x20)
                  // Stop copying when the memory counter reaches the length of the
                  // first bytes array.
                  let end := add(mc, length)
                  for {
                      // Initialize a copy counter to the start of the _preBytes data,
                      // 32 bytes into its memory.
                      let cc := add(_preBytes, 0x20)
                  } lt(mc, end) {
                      // Increase both counters by 32 bytes each iteration.
                      mc := add(mc, 0x20)
                      cc := add(cc, 0x20)
                  } {
                      // Write the _preBytes data into the tempBytes memory 32 bytes
                      // at a time.
                      mstore(mc, mload(cc))
                  }
                  // Add the length of _postBytes to the current length of tempBytes
                  // and store it as the new length in the first 32 bytes of the
                  // tempBytes memory.
                  length := mload(_postBytes)
                  mstore(tempBytes, add(length, mload(tempBytes)))
                  // Move the memory counter back from a multiple of 0x20 to the
                  // actual end of the _preBytes data.
                  mc := end
                  // Stop copying when the memory counter reaches the new combined
                  // length of the arrays.
                  end := add(mc, length)
                  for {
                      let cc := add(_postBytes, 0x20)
                  } lt(mc, end) {
                      mc := add(mc, 0x20)
                      cc := add(cc, 0x20)
                  } {
                      mstore(mc, mload(cc))
                  }
                  // Update the free-memory pointer by padding our last write location
                  // to 32 bytes: add 31 bytes to the end of tempBytes to move to the
                  // next 32 byte block, then round down to the nearest multiple of
                  // 32. If the sum of the length of the two arrays is zero then add
                  // one before rounding down to leave a blank 32 bytes (the length block with 0).
                  mstore(0x40, and(
                    add(add(end, iszero(add(length, mload(_preBytes)))), 31),
                    not(31) // Round down to the nearest 32 bytes.
                  ))
              }
              return tempBytes;
          }
          function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
              assembly {
                  // Read the first 32 bytes of _preBytes storage, which is the length
                  // of the array. (We don't need to use the offset into the slot
                  // because arrays use the entire slot.)
                  let fslot := sload(_preBytes.slot)
                  // Arrays of 31 bytes or less have an even value in their slot,
                  // while longer arrays have an odd value. The actual length is
                  // the slot divided by two for odd values, and the lowest order
                  // byte divided by two for even values.
                  // If the slot is even, bitwise and the slot with 255 and divide by
                  // two to get the length. If the slot is odd, bitwise and the slot
                  // with -1 and divide by two.
                  let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                  let mlength := mload(_postBytes)
                  let newlength := add(slength, mlength)
                  // slength can contain both the length and contents of the array
                  // if length < 32 bytes so let's prepare for that
                  // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                  switch add(lt(slength, 32), lt(newlength, 32))
                  case 2 {
                      // Since the new array still fits in the slot, we just need to
                      // update the contents of the slot.
                      // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
                      sstore(
                          _preBytes.slot,
                          // all the modifications to the slot are inside this
                          // next block
                          add(
                              // we can just add to the slot contents because the
                              // bytes we want to change are the LSBs
                              fslot,
                              add(
                                  mul(
                                      div(
                                          // load the bytes from memory
                                          mload(add(_postBytes, 0x20)),
                                          // zero all bytes to the right
                                          exp(0x100, sub(32, mlength))
                                      ),
                                      // and now shift left the number of bytes to
                                      // leave space for the length in the slot
                                      exp(0x100, sub(32, newlength))
                                  ),
                                  // increase length by the double of the memory
                                  // bytes length
                                  mul(mlength, 2)
                              )
                          )
                      )
                  }
                  case 1 {
                      // The stored value fits in the slot, but the combined value
                      // will exceed it.
                      // get the keccak hash to get the contents of the array
                      mstore(0x0, _preBytes.slot)
                      let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                      // save new length
                      sstore(_preBytes.slot, add(mul(newlength, 2), 1))
                      // The contents of the _postBytes array start 32 bytes into
                      // the structure. Our first read should obtain the `submod`
                      // bytes that can fit into the unused space in the last word
                      // of the stored array. To get this, we read 32 bytes starting
                      // from `submod`, so the data we read overlaps with the array
                      // contents by `submod` bytes. Masking the lowest-order
                      // `submod` bytes allows us to add that value directly to the
                      // stored value.
                      let submod := sub(32, slength)
                      let mc := add(_postBytes, submod)
                      let end := add(_postBytes, mlength)
                      let mask := sub(exp(0x100, submod), 1)
                      sstore(
                          sc,
                          add(
                              and(
                                  fslot,
                                  0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
                              ),
                              and(mload(mc), mask)
                          )
                      )
                      for {
                          mc := add(mc, 0x20)
                          sc := add(sc, 1)
                      } lt(mc, end) {
                          sc := add(sc, 1)
                          mc := add(mc, 0x20)
                      } {
                          sstore(sc, mload(mc))
                      }
                      mask := exp(0x100, sub(mc, end))
                      sstore(sc, mul(div(mload(mc), mask), mask))
                  }
                  default {
                      // get the keccak hash to get the contents of the array
                      mstore(0x0, _preBytes.slot)
                      // Start copying to the last used word of the stored array.
                      let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                      // save new length
                      sstore(_preBytes.slot, add(mul(newlength, 2), 1))
                      // Copy over the first `submod` bytes of the new data as in
                      // case 1 above.
                      let slengthmod := mod(slength, 32)
                      let mlengthmod := mod(mlength, 32)
                      let submod := sub(32, slengthmod)
                      let mc := add(_postBytes, submod)
                      let end := add(_postBytes, mlength)
                      let mask := sub(exp(0x100, submod), 1)
                      sstore(sc, add(sload(sc), and(mload(mc), mask)))
                      for {
                          sc := add(sc, 1)
                          mc := add(mc, 0x20)
                      } lt(mc, end) {
                          sc := add(sc, 1)
                          mc := add(mc, 0x20)
                      } {
                          sstore(sc, mload(mc))
                      }
                      mask := exp(0x100, sub(mc, end))
                      sstore(sc, mul(div(mload(mc), mask), mask))
                  }
              }
          }
          function slice(
              bytes memory _bytes,
              uint256 _start,
              uint256 _length
          )
              internal
              pure
              returns (bytes memory)
          {
              require(_length + 31 >= _length, "slice_overflow");
              require(_bytes.length >= _start + _length, "slice_outOfBounds");
              bytes memory tempBytes;
              assembly {
                  switch iszero(_length)
                  case 0 {
                      // Get a location of some free memory and store it in tempBytes as
                      // Solidity does for memory variables.
                      tempBytes := mload(0x40)
                      // The first word of the slice result is potentially a partial
                      // word read from the original array. To read it, we calculate
                      // the length of that partial word and start copying that many
                      // bytes into the array. The first word we copy will start with
                      // data we don't care about, but the last `lengthmod` bytes will
                      // land at the beginning of the contents of the new array. When
                      // we're done copying, we overwrite the full first word with
                      // the actual length of the slice.
                      let lengthmod := and(_length, 31)
                      // The multiplication in the next line is necessary
                      // because when slicing multiples of 32 bytes (lengthmod == 0)
                      // the following copy loop was copying the origin's length
                      // and then ending prematurely not copying everything it should.
                      let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                      let end := add(mc, _length)
                      for {
                          // The multiplication in the next line has the same exact purpose
                          // as the one above.
                          let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                      } lt(mc, end) {
                          mc := add(mc, 0x20)
                          cc := add(cc, 0x20)
                      } {
                          mstore(mc, mload(cc))
                      }
                      mstore(tempBytes, _length)
                      //update free-memory pointer
                      //allocating the array padded to 32 bytes like the compiler does now
                      mstore(0x40, and(add(mc, 31), not(31)))
                  }
                  //if we want a zero-length slice let's just return a zero-length array
                  default {
                      tempBytes := mload(0x40)
                      //zero out the 32 bytes slice we are about to return
                      //we need to do it because Solidity does not garbage collect
                      mstore(tempBytes, 0)
                      mstore(0x40, add(tempBytes, 0x20))
                  }
              }
              return tempBytes;
          }
          function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
              require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
              address tempAddress;
              assembly {
                  tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
              }
              return tempAddress;
          }
          function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
              require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
              uint8 tempUint;
              assembly {
                  tempUint := mload(add(add(_bytes, 0x1), _start))
              }
              return tempUint;
          }
          function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
              require(_bytes.length >= _start + 2, "toUint16_outOfBounds");
              uint16 tempUint;
              assembly {
                  tempUint := mload(add(add(_bytes, 0x2), _start))
              }
              return tempUint;
          }
          function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
              require(_bytes.length >= _start + 4, "toUint32_outOfBounds");
              uint32 tempUint;
              assembly {
                  tempUint := mload(add(add(_bytes, 0x4), _start))
              }
              return tempUint;
          }
          function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
              require(_bytes.length >= _start + 8, "toUint64_outOfBounds");
              uint64 tempUint;
              assembly {
                  tempUint := mload(add(add(_bytes, 0x8), _start))
              }
              return tempUint;
          }
          function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {
              require(_bytes.length >= _start + 12, "toUint96_outOfBounds");
              uint96 tempUint;
              assembly {
                  tempUint := mload(add(add(_bytes, 0xc), _start))
              }
              return tempUint;
          }
          function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
              require(_bytes.length >= _start + 16, "toUint128_outOfBounds");
              uint128 tempUint;
              assembly {
                  tempUint := mload(add(add(_bytes, 0x10), _start))
              }
              return tempUint;
          }
          function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
              require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
              uint256 tempUint;
              assembly {
                  tempUint := mload(add(add(_bytes, 0x20), _start))
              }
              return tempUint;
          }
          function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
              require(_bytes.length >= _start + 32, "toBytes32_outOfBounds");
              bytes32 tempBytes32;
              assembly {
                  tempBytes32 := mload(add(add(_bytes, 0x20), _start))
              }
              return tempBytes32;
          }
          function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
              bool success = true;
              assembly {
                  let length := mload(_preBytes)
                  // if lengths don't match the arrays are not equal
                  switch eq(length, mload(_postBytes))
                  case 1 {
                      // cb is a circuit breaker in the for loop since there's
                      //  no said feature for inline assembly loops
                      // cb = 1 - don't breaker
                      // cb = 0 - break
                      let cb := 1
                      let mc := add(_preBytes, 0x20)
                      let end := add(mc, length)
                      for {
                          let cc := add(_postBytes, 0x20)
                      // the next line is the loop condition:
                      // while(uint256(mc < end) + cb == 2)
                      } eq(add(lt(mc, end), cb), 2) {
                          mc := add(mc, 0x20)
                          cc := add(cc, 0x20)
                      } {
                          // if any of these checks fails then arrays are not equal
                          if iszero(eq(mload(mc), mload(cc))) {
                              // unsuccess:
                              success := 0
                              cb := 0
                          }
                      }
                  }
                  default {
                      // unsuccess:
                      success := 0
                  }
              }
              return success;
          }
          function equalStorage(
              bytes storage _preBytes,
              bytes memory _postBytes
          )
              internal
              view
              returns (bool)
          {
              bool success = true;
              assembly {
                  // we know _preBytes_offset is 0
                  let fslot := sload(_preBytes.slot)
                  // Decode the length of the stored array like in concatStorage().
                  let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                  let mlength := mload(_postBytes)
                  // if lengths don't match the arrays are not equal
                  switch eq(slength, mlength)
                  case 1 {
                      // slength can contain both the length and contents of the array
                      // if length < 32 bytes so let's prepare for that
                      // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                      if iszero(iszero(slength)) {
                          switch lt(slength, 32)
                          case 1 {
                              // blank the last byte which is the length
                              fslot := mul(div(fslot, 0x100), 0x100)
                              if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
                                  // unsuccess:
                                  success := 0
                              }
                          }
                          default {
                              // cb is a circuit breaker in the for loop since there's
                              //  no said feature for inline assembly loops
                              // cb = 1 - don't breaker
                              // cb = 0 - break
                              let cb := 1
                              // get the keccak hash to get the contents of the array
                              mstore(0x0, _preBytes.slot)
                              let sc := keccak256(0x0, 0x20)
                              let mc := add(_postBytes, 0x20)
                              let end := add(mc, mlength)
                              // the next line is the loop condition:
                              // while(uint256(mc < end) + cb == 2)
                              for {} eq(add(lt(mc, end), cb), 2) {
                                  sc := add(sc, 1)
                                  mc := add(mc, 0x20)
                              } {
                                  if iszero(eq(sload(sc), mload(mc))) {
                                      // unsuccess:
                                      success := 0
                                      cb := 0
                                  }
                              }
                          }
                      }
                  }
                  default {
                      // unsuccess:
                      success := 0
                  }
              }
              return success;
          }
      }
      

      File 3 of 3: EndpointV2
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
      pragma solidity ^0.8.0;
      import "../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.
       *
       * By default, the owner account will be the one that deploys the contract. 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;
          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
          /**
           * @dev Initializes the contract setting the deployer as the initial owner.
           */
          constructor() {
              _transferOwnership(_msgSender());
          }
          /**
           * @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 {
              require(owner() == _msgSender(), "Ownable: caller is not the owner");
          }
          /**
           * @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 {
              require(newOwner != address(0), "Ownable: new owner is the zero address");
              _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);
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC20 standard as defined in the EIP.
       */
      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 amount of tokens in existence.
           */
          function totalSupply() external view returns (uint256);
          /**
           * @dev Returns the amount of tokens owned by `account`.
           */
          function balanceOf(address account) external view returns (uint256);
          /**
           * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
          /**
           * @dev Moves `amount` tokens from `from` to `to` using the
           * allowance mechanism. `amount` 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 amount) external returns (bool);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
       * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
       *
       * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
       * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
       * need to send a transaction, and thus is not required to hold Ether at all.
       *
       * ==== Security Considerations
       *
       * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
       * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
       * considered as an intention to spend the allowance in any specific way. The second is that because permits have
       * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
       * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
       * generally recommended is:
       *
       * ```solidity
       * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
       *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
       *     doThing(..., value);
       * }
       *
       * function doThing(..., uint256 value) public {
       *     token.safeTransferFrom(msg.sender, address(this), value);
       *     ...
       * }
       * ```
       *
       * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
       * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
       * {SafeERC20-safeTransferFrom}).
       *
       * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
       * contracts should have entry points that don't rely on permit.
       */
      interface IERC20Permit {
          /**
           * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
           * given ``owner``'s signed approval.
           *
           * IMPORTANT: The same issues {IERC20-approve} has related to transaction
           * ordering also apply here.
           *
           * Emits an {Approval} event.
           *
           * Requirements:
           *
           * - `spender` cannot be the zero address.
           * - `deadline` must be a timestamp in the future.
           * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
           * over the EIP712-formatted function arguments.
           * - the signature must use ``owner``'s current nonce (see {nonces}).
           *
           * For more information on the signature format, see the
           * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
           * section].
           *
           * CAUTION: See Security Considerations above.
           */
          function permit(
              address owner,
              address spender,
              uint256 value,
              uint256 deadline,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) external;
          /**
           * @dev Returns the current nonce for `owner`. This value must be
           * included whenever a signature is generated for {permit}.
           *
           * Every successful call to {permit} increases ``owner``'s nonce by one. This
           * prevents a signature from being used multiple times.
           */
          function nonces(address owner) external view returns (uint256);
          /**
           * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
           */
          // solhint-disable-next-line func-name-mixedcase
          function DOMAIN_SEPARATOR() external view returns (bytes32);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
      pragma solidity ^0.8.0;
      import "../IERC20.sol";
      import "../extensions/IERC20Permit.sol";
      import "../../../utils/Address.sol";
      /**
       * @title SafeERC20
       * @dev Wrappers around ERC20 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 {
          using Address for address;
          /**
           * @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.encodeWithSelector(token.transfer.selector, 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.encodeWithSelector(token.transferFrom.selector, from, to, value));
          }
          /**
           * @dev Deprecated. This function has issues similar to the ones found in
           * {IERC20-approve}, and its usage is discouraged.
           *
           * Whenever possible, use {safeIncreaseAllowance} and
           * {safeDecreaseAllowance} instead.
           */
          function safeApprove(IERC20 token, address spender, uint256 value) internal {
              // safeApprove should only be called when setting an initial allowance,
              // or when resetting it to zero. To increase and decrease it, use
              // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
              require(
                  (value == 0) || (token.allowance(address(this), spender) == 0),
                  "SafeERC20: approve from non-zero to non-zero allowance"
              );
              _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 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.
           */
          function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
              uint256 oldAllowance = token.allowance(address(this), spender);
              _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
          }
          /**
           * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
           * non-reverting calls are assumed to be successful.
           */
          function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
              unchecked {
                  uint256 oldAllowance = token.allowance(address(this), spender);
                  require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                  _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
              }
          }
          /**
           * @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.
           */
          function forceApprove(IERC20 token, address spender, uint256 value) internal {
              bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
              if (!_callOptionalReturnBool(token, approvalCall)) {
                  _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
                  _callOptionalReturn(token, approvalCall);
              }
          }
          /**
           * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
           * Revert on invalid signature.
           */
          function safePermit(
              IERC20Permit token,
              address owner,
              address spender,
              uint256 value,
              uint256 deadline,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) internal {
              uint256 nonceBefore = token.nonces(owner);
              token.permit(owner, spender, value, deadline, v, r, s);
              uint256 nonceAfter = token.nonces(owner);
              require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
          }
          /**
           * @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).
           */
          function _callOptionalReturn(IERC20 token, bytes memory data) private {
              // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
              // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
              // the target address contains contract code and also asserts for success in the low-level call.
              bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
              require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
          }
          /**
           * @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 silents catches all reverts and returns a bool instead.
           */
          function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
              // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
              // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
              // and not revert is the subcall reverts.
              (bool success, bytes memory returndata) = address(token).call(data);
              return
                  success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
      pragma solidity ^0.8.1;
      /**
       * @dev Collection of functions related to the address type
       */
      library Address {
          /**
           * @dev Returns true if `account` is a contract.
           *
           * [IMPORTANT]
           * ====
           * It is unsafe to assume that an address for which this function returns
           * false is an externally-owned account (EOA) and not a contract.
           *
           * Among others, `isContract` will return false for the following
           * types of addresses:
           *
           *  - an externally-owned account
           *  - a contract in construction
           *  - an address where a contract will be created
           *  - an address where a contract lived, but was destroyed
           *
           * Furthermore, `isContract` will also return true if the target contract within
           * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
           * which only has an effect at the end of a transaction.
           * ====
           *
           * [IMPORTANT]
           * ====
           * You shouldn't rely on `isContract` to protect against flash loan attacks!
           *
           * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
           * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
           * constructor.
           * ====
           */
          function isContract(address account) internal view returns (bool) {
              // This method relies on extcodesize/address.code.length, which returns 0
              // for contracts in construction, since the code is only stored at the end
              // of the constructor execution.
              return account.code.length > 0;
          }
          /**
           * @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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
           */
          function sendValue(address payable recipient, uint256 amount) internal {
              require(address(this).balance >= amount, "Address: insufficient balance");
              (bool success, ) = recipient.call{value: amount}("");
              require(success, "Address: unable to send value, recipient may have reverted");
          }
          /**
           * @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, it is bubbled up by this
           * function (like regular Solidity function calls).
           *
           * 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.
           *
           * _Available since v3.1._
           */
          function functionCall(address target, bytes memory data) internal returns (bytes memory) {
              return functionCallWithValue(target, data, 0, "Address: low-level call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
           * `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal returns (bytes memory) {
              return functionCallWithValue(target, data, 0, errorMessage);
          }
          /**
           * @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`.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
              return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
          }
          /**
           * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
           * with `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(
              address target,
              bytes memory data,
              uint256 value,
              string memory errorMessage
          ) internal returns (bytes memory) {
              require(address(this).balance >= value, "Address: insufficient balance for call");
              (bool success, bytes memory returndata) = target.call{value: value}(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
              return functionStaticCall(target, data, "Address: low-level static call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal view returns (bytes memory) {
              (bool success, bytes memory returndata) = target.staticcall(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but performing a delegate call.
           *
           * _Available since v3.4._
           */
          function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
              return functionDelegateCall(target, data, "Address: low-level delegate call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
           * but performing a delegate call.
           *
           * _Available since v3.4._
           */
          function functionDelegateCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal returns (bytes memory) {
              (bool success, bytes memory returndata) = target.delegatecall(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
           * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
           *
           * _Available since v4.8._
           */
          function verifyCallResultFromTarget(
              address target,
              bool success,
              bytes memory returndata,
              string memory errorMessage
          ) internal view returns (bytes memory) {
              if (success) {
                  if (returndata.length == 0) {
                      // only check isContract if the call was successful and the return data is empty
                      // otherwise we already know that it was a contract
                      require(isContract(target), "Address: call to non-contract");
                  }
                  return returndata;
              } else {
                  _revert(returndata, errorMessage);
              }
          }
          /**
           * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
           * revert reason or using the provided one.
           *
           * _Available since v4.3._
           */
          function verifyCallResult(
              bool success,
              bytes memory returndata,
              string memory errorMessage
          ) internal pure returns (bytes memory) {
              if (success) {
                  return returndata;
              } else {
                  _revert(returndata, errorMessage);
              }
          }
          function _revert(bytes memory returndata, string memory errorMessage) 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
                  /// @solidity memory-safe-assembly
                  assembly {
                      let returndata_size := mload(returndata)
                      revert(add(32, returndata), returndata_size)
                  }
              } else {
                  revert(errorMessage);
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
      pragma solidity ^0.8.0;
      /**
       * @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;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
      pragma solidity ^0.8.0;
      import "./IERC165.sol";
      /**
       * @dev Implementation of the {IERC165} interface.
       *
       * Contracts that want to implement ERC165 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);
       * }
       * ```
       *
       * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
       */
      abstract contract ERC165 is IERC165 {
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
              return interfaceId == type(IERC165).interfaceId;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC165 standard, as defined in the
       * https://eips.ethereum.org/EIPS/eip-165[EIP].
       *
       * 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[EIP 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);
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
      import { MessagingFee, MessagingParams, MessagingReceipt, Origin, ILayerZeroEndpointV2 } from "./interfaces/ILayerZeroEndpointV2.sol";
      import { ISendLib, Packet } from "./interfaces/ISendLib.sol";
      import { ILayerZeroReceiver } from "./interfaces/ILayerZeroReceiver.sol";
      import { Errors } from "./libs/Errors.sol";
      import { GUID } from "./libs/GUID.sol";
      import { Transfer } from "./libs/Transfer.sol";
      import { MessagingChannel } from "./MessagingChannel.sol";
      import { MessagingComposer } from "./MessagingComposer.sol";
      import { MessageLibManager } from "./MessageLibManager.sol";
      import { MessagingContext } from "./MessagingContext.sol";
      // LayerZero EndpointV2 is fully backward compatible with LayerZero Endpoint(V1), but it also supports additional
      // features that Endpoint(V1) does not support now and may not in the future. We have also changed some terminology
      // to clarify pre-existing language that might have been confusing.
      //
      // The following is a list of terminology changes:
      //     -chainId -> eid
      //          - Rationale: chainId was a term we initially used to describe an endpoint on a specific chain. Since
      //          LayerZero supports non-EVMs we could not map the classic EVM chainIds to the LayerZero chainIds, making it
      //          confusing for developers. With the addition of EndpointV2 and its backward compatible nature, we would have
      //          two chainIds per chain that has Endpoint(V1), further confusing developers. We have decided to change the
      //          name to Endpoint Id, or eid, for simplicity and clarity.
      //     -adapterParams -> options
      //     -userApplication -> oapp. Omnichain Application
      //     -srcAddress -> sender
      //     -dstAddress -> receiver
      //          - Rationale: The sender/receiver on EVM is the address. However, on non-EVM chains, the sender/receiver could
      //          represented as a public key, or some other identifier. The term sender/receiver is more generic
      //     -payload -> message.
      //          - Rationale: The term payload is used in the context of a packet, which is a combination of the message and GUID
      contract EndpointV2 is ILayerZeroEndpointV2, MessagingChannel, MessageLibManager, MessagingComposer, MessagingContext {
          address public lzToken;
          mapping(address oapp => address delegate) public delegates;
          /// @param _eid the unique Endpoint Id for this deploy that all other Endpoints can use to send to it
          constructor(uint32 _eid, address _owner) MessagingChannel(_eid) {
              _transferOwnership(_owner);
          }
          /// @dev MESSAGING STEP 0
          /// @notice This view function gives the application built on top of LayerZero the ability to requests a quote
          /// with the same parameters as they would to send their message. Since the quotes are given on chain there is a
          /// race condition in which the prices could change between the time the user gets their quote and the time they
          /// submit their message. If the price moves up and the user doesn't send enough funds the transaction will revert,
          /// if the price goes down the _refundAddress provided by the app will be refunded the difference.
          /// @param _params the messaging parameters
          /// @param _sender the sender of the message
          function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory) {
              // lzToken must be set to support payInLzToken
              if (_params.payInLzToken && lzToken == address(0x0)) revert Errors.LZ_LzTokenUnavailable();
              // get the correct outbound nonce
              uint64 nonce = outboundNonce[_sender][_params.dstEid][_params.receiver] + 1;
              // construct the packet with a GUID
              Packet memory packet = Packet({
                  nonce: nonce,
                  srcEid: eid,
                  sender: _sender,
                  dstEid: _params.dstEid,
                  receiver: _params.receiver,
                  guid: GUID.generate(nonce, eid, _sender, _params.dstEid, _params.receiver),
                  message: _params.message
              });
              // get the send library by sender and dst eid
              // use _ to avoid variable shadowing
              address _sendLibrary = getSendLibrary(_sender, _params.dstEid);
              return ISendLib(_sendLibrary).quote(packet, _params.options, _params.payInLzToken);
          }
          /// @dev MESSAGING STEP 1 - OApp need to transfer the fees to the endpoint before sending the message
          /// @param _params the messaging parameters
          /// @param _refundAddress the address to refund both the native and lzToken
          function send(
              MessagingParams calldata _params,
              address _refundAddress
          ) external payable sendContext(_params.dstEid, msg.sender) returns (MessagingReceipt memory) {
              if (_params.payInLzToken && lzToken == address(0x0)) revert Errors.LZ_LzTokenUnavailable();
              // send message
              (MessagingReceipt memory receipt, address _sendLibrary) = _send(msg.sender, _params);
              // OApp can simulate with 0 native value it will fail with error including the required fee, which can be provided in the actual call
              // this trick can be used to avoid the need to write the quote() function
              // however, without the quote view function it will be hard to compose an oapp on chain
              uint256 suppliedNative = _suppliedNative();
              uint256 suppliedLzToken = _suppliedLzToken(_params.payInLzToken);
              _assertMessagingFee(receipt.fee, suppliedNative, suppliedLzToken);
              // handle lz token fees
              _payToken(lzToken, receipt.fee.lzTokenFee, suppliedLzToken, _sendLibrary, _refundAddress);
              // handle native fees
              _payNative(receipt.fee.nativeFee, suppliedNative, _sendLibrary, _refundAddress);
              return receipt;
          }
          /// @dev internal function for sending the messages used by all external send methods
          /// @param _sender the address of the application sending the message to the destination chain
          /// @param _params the messaging parameters
          function _send(
              address _sender,
              MessagingParams calldata _params
          ) internal returns (MessagingReceipt memory, address) {
              // get the correct outbound nonce
              uint64 latestNonce = _outbound(_sender, _params.dstEid, _params.receiver);
              // construct the packet with a GUID
              Packet memory packet = Packet({
                  nonce: latestNonce,
                  srcEid: eid,
                  sender: _sender,
                  dstEid: _params.dstEid,
                  receiver: _params.receiver,
                  guid: GUID.generate(latestNonce, eid, _sender, _params.dstEid, _params.receiver),
                  message: _params.message
              });
              // get the send library by sender and dst eid
              address _sendLibrary = getSendLibrary(_sender, _params.dstEid);
              // messageLib always returns encodedPacket with guid
              (MessagingFee memory fee, bytes memory encodedPacket) = ISendLib(_sendLibrary).send(
                  packet,
                  _params.options,
                  _params.payInLzToken
              );
              // Emit packet information for DVNs, Executors, and any other offchain infrastructure to only listen
              // for this one event to perform their actions.
              emit PacketSent(encodedPacket, _params.options, _sendLibrary);
              return (MessagingReceipt(packet.guid, latestNonce, fee), _sendLibrary);
          }
          /// @dev MESSAGING STEP 2 - on the destination chain
          /// @dev configured receive library verifies a message
          /// @param _origin a struct holding the srcEid, nonce, and sender of the message
          /// @param _receiver the receiver of the message
          /// @param _payloadHash the payload hash of the message
          function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external {
              if (!isValidReceiveLibrary(_receiver, _origin.srcEid, msg.sender)) revert Errors.LZ_InvalidReceiveLibrary();
              uint64 lazyNonce = lazyInboundNonce[_receiver][_origin.srcEid][_origin.sender];
              if (!_initializable(_origin, _receiver, lazyNonce)) revert Errors.LZ_PathNotInitializable();
              if (!_verifiable(_origin, _receiver, lazyNonce)) revert Errors.LZ_PathNotVerifiable();
              // insert the message into the message channel
              _inbound(_receiver, _origin.srcEid, _origin.sender, _origin.nonce, _payloadHash);
              emit PacketVerified(_origin, _receiver, _payloadHash);
          }
          /// @dev MESSAGING STEP 3 - the last step
          /// @dev execute a verified message to the designated receiver
          /// @dev the execution provides the execution context (caller, extraData) to the receiver. the receiver can optionally assert the caller and validate the untrusted extraData
          /// @dev cant reentrant because the payload is cleared before execution
          /// @param _origin the origin of the message
          /// @param _receiver the receiver of the message
          /// @param _guid the guid of the message
          /// @param _message the message
          /// @param _extraData the extra data provided by the executor. this data is untrusted and should be validated.
          function lzReceive(
              Origin calldata _origin,
              address _receiver,
              bytes32 _guid,
              bytes calldata _message,
              bytes calldata _extraData
          ) external payable {
              // clear the payload first to prevent reentrancy, and then execute the message
              _clearPayload(_receiver, _origin.srcEid, _origin.sender, _origin.nonce, abi.encodePacked(_guid, _message));
              ILayerZeroReceiver(_receiver).lzReceive{ value: msg.value }(_origin, _guid, _message, msg.sender, _extraData);
              emit PacketDelivered(_origin, _receiver);
          }
          /// @param _origin the origin of the message
          /// @param _receiver the receiver of the message
          /// @param _guid the guid of the message
          /// @param _message the message
          /// @param _extraData the extra data provided by the executor.
          /// @param _reason the reason for failure
          function lzReceiveAlert(
              Origin calldata _origin,
              address _receiver,
              bytes32 _guid,
              uint256 _gas,
              uint256 _value,
              bytes calldata _message,
              bytes calldata _extraData,
              bytes calldata _reason
          ) external {
              emit LzReceiveAlert(_receiver, msg.sender, _origin, _guid, _gas, _value, _message, _extraData, _reason);
          }
          /// @dev Oapp uses this interface to clear a message.
          /// @dev this is a PULL mode versus the PUSH mode of lzReceive
          /// @dev the cleared message can be ignored by the app (effectively burnt)
          /// @dev authenticated by oapp
          /// @param _origin the origin of the message
          /// @param _guid the guid of the message
          /// @param _message the message
          function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external {
              _assertAuthorized(_oapp);
              bytes memory payload = abi.encodePacked(_guid, _message);
              _clearPayload(_oapp, _origin.srcEid, _origin.sender, _origin.nonce, payload);
              emit PacketDelivered(_origin, _oapp);
          }
          /// @dev allows reconfiguration to recover from wrong configurations
          /// @dev users should never approve the EndpointV2 contract to spend their non-layerzero tokens
          /// @dev override this function if the endpoint is charging ERC20 tokens as native
          /// @dev only owner
          /// @param _lzToken the new layer zero token address
          function setLzToken(address _lzToken) public virtual onlyOwner {
              lzToken = _lzToken;
              emit LzTokenSet(_lzToken);
          }
          /// @dev recover the token sent to this contract by mistake
          /// @dev only owner
          /// @param _token the token to recover. if 0x0 then it is native token
          /// @param _to the address to send the token to
          /// @param _amount the amount to send
          function recoverToken(address _token, address _to, uint256 _amount) external onlyOwner {
              Transfer.nativeOrToken(_token, _to, _amount);
          }
          /// @dev handling token payments on endpoint. the sender must approve the endpoint to spend the token
          /// @dev internal function
          /// @param _token the token to pay
          /// @param _required the amount required
          /// @param _supplied the amount supplied
          /// @param _receiver the receiver of the token
          function _payToken(
              address _token,
              uint256 _required,
              uint256 _supplied,
              address _receiver,
              address _refundAddress
          ) internal {
              if (_required > 0) {
                  Transfer.token(_token, _receiver, _required);
              }
              if (_required < _supplied) {
                  unchecked {
                      // refund the excess
                      Transfer.token(_token, _refundAddress, _supplied - _required);
                  }
              }
          }
          /// @dev handling native token payments on endpoint
          /// @dev override this if the endpoint is charging ERC20 tokens as native
          /// @dev internal function
          /// @param _required the amount required
          /// @param _supplied the amount supplied
          /// @param _receiver the receiver of the native token
          /// @param _refundAddress the address to refund the excess to
          function _payNative(
              uint256 _required,
              uint256 _supplied,
              address _receiver,
              address _refundAddress
          ) internal virtual {
              if (_required > 0) {
                  Transfer.native(_receiver, _required);
              }
              if (_required < _supplied) {
                  unchecked {
                      // refund the excess
                      Transfer.native(_refundAddress, _supplied - _required);
                  }
              }
          }
          /// @dev get the balance of the lzToken as the supplied lzToken fee if payInLzToken is true
          function _suppliedLzToken(bool _payInLzToken) internal view returns (uint256 supplied) {
              if (_payInLzToken) {
                  supplied = IERC20(lzToken).balanceOf(address(this));
                  // if payInLzToken is true, the supplied fee must be greater than 0 to prevent a race condition
                  // in which an oapp sending a message with lz token and the lz token is set to a new token between the tx
                  // being sent and the tx being mined. if the required lz token fee is 0 and the old lz token would be
                  // locked in the contract instead of being refunded
                  if (supplied == 0) revert Errors.LZ_ZeroLzTokenFee();
              }
          }
          /// @dev override this if the endpoint is charging ERC20 tokens as native
          function _suppliedNative() internal view virtual returns (uint256) {
              return msg.value;
          }
          /// @dev Assert the required fees and the supplied fees are enough
          function _assertMessagingFee(
              MessagingFee memory _required,
              uint256 _suppliedNativeFee,
              uint256 _suppliedLzTokenFee
          ) internal pure {
              if (_required.nativeFee > _suppliedNativeFee || _required.lzTokenFee > _suppliedLzTokenFee) {
                  revert Errors.LZ_InsufficientFee(
                      _required.nativeFee,
                      _suppliedNativeFee,
                      _required.lzTokenFee,
                      _suppliedLzTokenFee
                  );
              }
          }
          /// @dev override this if the endpoint is charging ERC20 tokens as native
          /// @return 0x0 if using native. otherwise the address of the native ERC20 token
          function nativeToken() external view virtual returns (address) {
              return address(0x0);
          }
          /// @notice delegate is authorized by the oapp to configure anything in layerzero
          function setDelegate(address _delegate) external {
              delegates[msg.sender] = _delegate;
              emit DelegateSet(msg.sender, _delegate);
          }
          // ========================= Internal =========================
          function _initializable(
              Origin calldata _origin,
              address _receiver,
              uint64 _lazyInboundNonce
          ) internal view returns (bool) {
              return
                  _lazyInboundNonce > 0 || // allowInitializePath already checked
                  ILayerZeroReceiver(_receiver).allowInitializePath(_origin);
          }
          /// @dev bytes(0) payloadHash can never be submitted
          function _verifiable(
              Origin calldata _origin,
              address _receiver,
              uint64 _lazyInboundNonce
          ) internal view returns (bool) {
              return
                  _origin.nonce > _lazyInboundNonce || // either initializing an empty slot or reverifying
                  inboundPayloadHash[_receiver][_origin.srcEid][_origin.sender][_origin.nonce] != EMPTY_PAYLOAD_HASH; // only allow reverifying if it hasn't been executed
          }
          /// @dev assert the caller to either be the oapp or the delegate
          function _assertAuthorized(address _oapp) internal view override(MessagingChannel, MessageLibManager) {
              if (msg.sender != _oapp && msg.sender != delegates[_oapp]) revert Errors.LZ_Unauthorized();
          }
          // ========================= VIEW FUNCTIONS FOR OFFCHAIN ONLY =========================
          // Not involved in any state transition function.
          // ====================================================================================
          function initializable(Origin calldata _origin, address _receiver) external view returns (bool) {
              return _initializable(_origin, _receiver, lazyInboundNonce[_receiver][_origin.srcEid][_origin.sender]);
          }
          function verifiable(Origin calldata _origin, address _receiver) external view returns (bool) {
              return _verifiable(_origin, _receiver, lazyInboundNonce[_receiver][_origin.srcEid][_origin.sender]);
          }
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
      import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
      import { IMessageLib, MessageLibType } from "./interfaces/IMessageLib.sol";
      import { IMessageLibManager, SetConfigParam } from "./interfaces/IMessageLibManager.sol";
      import { Errors } from "./libs/Errors.sol";
      import { BlockedMessageLib } from "./messagelib/BlockedMessageLib.sol";
      abstract contract MessageLibManager is Ownable, IMessageLibManager {
          address private constant DEFAULT_LIB = address(0);
          // the library that reverts both on send and quote
          // must be configured on construction and be immutable
          address public immutable blockedLibrary;
          // only registered libraries all valid libraries
          // the blockedLibrary will be registered on construction
          address[] internal registeredLibraries;
          mapping(address lib => bool) public isRegisteredLibrary;
          // both sendLibrary and receiveLibrary config can be lazily resolved
          mapping(address sender => mapping(uint32 dstEid => address lib)) internal sendLibrary;
          mapping(address receiver => mapping(uint32 srcEid => address lib)) internal receiveLibrary;
          mapping(address receiver => mapping(uint32 srcEid => Timeout)) public receiveLibraryTimeout;
          mapping(uint32 dstEid => address lib) public defaultSendLibrary;
          mapping(uint32 srcEid => address lib) public defaultReceiveLibrary;
          mapping(uint32 srcEid => Timeout) public defaultReceiveLibraryTimeout;
          constructor() {
              blockedLibrary = address(new BlockedMessageLib());
              registerLibrary(blockedLibrary);
          }
          modifier onlyRegistered(address _lib) {
              if (!isRegisteredLibrary[_lib]) revert Errors.LZ_OnlyRegisteredLib();
              _;
          }
          modifier isSendLib(address _lib) {
              if (_lib != DEFAULT_LIB) {
                  if (IMessageLib(_lib).messageLibType() == MessageLibType.Receive) revert Errors.LZ_OnlySendLib();
              }
              _;
          }
          modifier isReceiveLib(address _lib) {
              if (_lib != DEFAULT_LIB) {
                  if (IMessageLib(_lib).messageLibType() == MessageLibType.Send) revert Errors.LZ_OnlyReceiveLib();
              }
              _;
          }
          modifier onlyRegisteredOrDefault(address _lib) {
              if (!isRegisteredLibrary[_lib] && _lib != DEFAULT_LIB) revert Errors.LZ_OnlyRegisteredOrDefaultLib();
              _;
          }
          /// @dev check if the library supported the eid.
          modifier onlySupportedEid(address _lib, uint32 _eid) {
              /// @dev doesnt need to check for default lib, because when they are initially added they get passed through this modifier
              if (_lib != DEFAULT_LIB) {
                  if (!IMessageLib(_lib).isSupportedEid(_eid)) revert Errors.LZ_UnsupportedEid();
              }
              _;
          }
          function getRegisteredLibraries() external view returns (address[] memory) {
              return registeredLibraries;
          }
          /// @notice The Send Library is the Oapp specified library that will be used to send the message to the destination
          /// endpoint. If the Oapp does not specify a Send Library, the default Send Library will be used.
          /// @dev If the Oapp does not have a selected Send Library, this function will resolve to the default library
          /// configured by LayerZero
          /// @return lib address of the Send Library
          /// @param _sender The address of the Oapp that is sending the message
          /// @param _dstEid The destination endpoint id
          function getSendLibrary(address _sender, uint32 _dstEid) public view returns (address lib) {
              lib = sendLibrary[_sender][_dstEid];
              if (lib == DEFAULT_LIB) {
                  lib = defaultSendLibrary[_dstEid];
                  if (lib == address(0x0)) revert Errors.LZ_DefaultSendLibUnavailable();
              }
          }
          function isDefaultSendLibrary(address _sender, uint32 _dstEid) public view returns (bool) {
              return sendLibrary[_sender][_dstEid] == DEFAULT_LIB;
          }
          /// @dev the receiveLibrary can be lazily resolved that if not set it will point to the default configured by LayerZero
          function getReceiveLibrary(address _receiver, uint32 _srcEid) public view returns (address lib, bool isDefault) {
              lib = receiveLibrary[_receiver][_srcEid];
              if (lib == DEFAULT_LIB) {
                  lib = defaultReceiveLibrary[_srcEid];
                  if (lib == address(0x0)) revert Errors.LZ_DefaultReceiveLibUnavailable();
                  isDefault = true;
              }
          }
          /// @dev called when the endpoint checks if the msgLib attempting to verify the msg is the configured msgLib of the Oapp
          /// @dev this check provides the ability for Oapp to lock in a trusted msgLib
          /// @dev it will fist check if the msgLib is the currently configured one. then check if the msgLib is the one in grace period of msgLib versioning upgrade
          function isValidReceiveLibrary(
              address _receiver,
              uint32 _srcEid,
              address _actualReceiveLib
          ) public view returns (bool) {
              // early return true if the _actualReceiveLib is the currently configured one
              (address expectedReceiveLib, bool isDefault) = getReceiveLibrary(_receiver, _srcEid);
              if (_actualReceiveLib == expectedReceiveLib) {
                  return true;
              }
              // check the timeout condition otherwise
              // if the Oapp is using defaultReceiveLibrary, use the default Timeout config
              // otherwise, use the Timeout configured by the Oapp
              Timeout memory timeout = isDefault
                  ? defaultReceiveLibraryTimeout[_srcEid]
                  : receiveLibraryTimeout[_receiver][_srcEid];
              // requires the _actualReceiveLib to be the same as the one in grace period and the grace period has not expired
              // block.number is uint256 so timeout.expiry must > 0, which implies a non-ZERO value
              if (timeout.lib == _actualReceiveLib && timeout.expiry > block.number) {
                  // timeout lib set and has not expired
                  return true;
              }
              // returns false by default
              return false;
          }
          //------- Owner interfaces
          /// @dev all libraries have to implement the erc165 interface to prevent wrong configurations
          /// @dev only owner
          function registerLibrary(address _lib) public onlyOwner {
              // must have the right interface
              if (!IERC165(_lib).supportsInterface(type(IMessageLib).interfaceId)) revert Errors.LZ_UnsupportedInterface();
              // must have not been registered
              if (isRegisteredLibrary[_lib]) revert Errors.LZ_AlreadyRegistered();
              // insert into both the map and the list
              isRegisteredLibrary[_lib] = true;
              registeredLibraries.push(_lib);
              emit LibraryRegistered(_lib);
          }
          /// @dev owner setting the defaultSendLibrary
          /// @dev can set to the blockedLibrary, which is a registered library
          /// @dev the msgLib must enable the support before they can be registered to the endpoint as the default
          /// @dev only owner
          function setDefaultSendLibrary(
              uint32 _eid,
              address _newLib
          ) external onlyOwner onlyRegistered(_newLib) isSendLib(_newLib) onlySupportedEid(_newLib, _eid) {
              // must provide a different value
              if (defaultSendLibrary[_eid] == _newLib) revert Errors.LZ_SameValue();
              defaultSendLibrary[_eid] = _newLib;
              emit DefaultSendLibrarySet(_eid, _newLib);
          }
          /// @dev owner setting the defaultSendLibrary
          /// @dev must be a registered library (including blockLibrary) with the eid support enabled
          /// @dev in version migration, it can add a grace period to the old library. if the grace period is 0, it will delete the timeout configuration.
          /// @dev only owner
          function setDefaultReceiveLibrary(
              uint32 _eid,
              address _newLib,
              uint256 _gracePeriod
          ) external onlyOwner onlyRegistered(_newLib) isReceiveLib(_newLib) onlySupportedEid(_newLib, _eid) {
              address oldLib = defaultReceiveLibrary[_eid];
              // must provide a different value
              if (oldLib == _newLib) revert Errors.LZ_SameValue();
              defaultReceiveLibrary[_eid] = _newLib;
              emit DefaultReceiveLibrarySet(_eid, _newLib);
              if (_gracePeriod > 0) {
                  // override the current default timeout to the [old_lib + new expiry]
                  Timeout storage timeout = defaultReceiveLibraryTimeout[_eid];
                  timeout.lib = oldLib;
                  timeout.expiry = block.number + _gracePeriod;
                  emit DefaultReceiveLibraryTimeoutSet(_eid, oldLib, timeout.expiry);
              } else {
                  // otherwise, remove the old configuration.
                  delete defaultReceiveLibraryTimeout[_eid];
                  emit DefaultReceiveLibraryTimeoutSet(_eid, oldLib, 0);
              }
          }
          /// @dev owner setting the defaultSendLibrary
          /// @dev must be a registered library (including blockLibrary) with the eid support enabled
          /// @dev can used to (1) extend the current configuration (2) force remove the current configuration (3) change to a new configuration
          /// @param _expiry the block number when lib expires
          function setDefaultReceiveLibraryTimeout(
              uint32 _eid,
              address _lib,
              uint256 _expiry
          ) external onlyRegistered(_lib) isReceiveLib(_lib) onlySupportedEid(_lib, _eid) onlyOwner {
              if (_expiry == 0) {
                  // force remove the current configuration
                  delete defaultReceiveLibraryTimeout[_eid];
              } else {
                  // override it with new configuration
                  if (_expiry <= block.number) revert Errors.LZ_InvalidExpiry();
                  Timeout storage timeout = defaultReceiveLibraryTimeout[_eid];
                  timeout.lib = _lib;
                  timeout.expiry = _expiry;
              }
              emit DefaultReceiveLibraryTimeoutSet(_eid, _lib, _expiry);
          }
          /// @dev returns true only if both the default send/receive libraries are set
          function isSupportedEid(uint32 _eid) external view returns (bool) {
              return defaultSendLibrary[_eid] != address(0) && defaultReceiveLibrary[_eid] != address(0);
          }
          //------- OApp interfaces
          /// @dev Oapp setting the sendLibrary
          /// @dev must be a registered library (including blockLibrary) with the eid support enabled
          /// @dev authenticated by the Oapp
          function setSendLibrary(
              address _oapp,
              uint32 _eid,
              address _newLib
          ) external onlyRegisteredOrDefault(_newLib) isSendLib(_newLib) onlySupportedEid(_newLib, _eid) {
              _assertAuthorized(_oapp);
              // must provide a different value
              if (sendLibrary[_oapp][_eid] == _newLib) revert Errors.LZ_SameValue();
              sendLibrary[_oapp][_eid] = _newLib;
              emit SendLibrarySet(_oapp, _eid, _newLib);
          }
          /// @dev Oapp setting the receiveLibrary
          /// @dev must be a registered library (including blockLibrary) with the eid support enabled
          /// @dev in version migration, it can add a grace period to the old library. if the grace period is 0, it will delete the timeout configuration.
          /// @dev authenticated by the Oapp
          /// @param _gracePeriod the number of blocks from now until oldLib expires
          function setReceiveLibrary(
              address _oapp,
              uint32 _eid,
              address _newLib,
              uint256 _gracePeriod
          ) external onlyRegisteredOrDefault(_newLib) isReceiveLib(_newLib) onlySupportedEid(_newLib, _eid) {
              _assertAuthorized(_oapp);
              address oldLib = receiveLibrary[_oapp][_eid];
              // must provide new values
              if (oldLib == _newLib) revert Errors.LZ_SameValue();
              receiveLibrary[_oapp][_eid] = _newLib;
              emit ReceiveLibrarySet(_oapp, _eid, _newLib);
              if (_gracePeriod > 0) {
                  // to simplify the logic, we only allow to set timeout if neither the new lib nor old lib is DEFAULT_LIB, which would should read the default timeout configurations
                  // (1) if the Oapp wants to fall back to the DEFAULT, then set the newLib to DEFAULT with grace period == 0
                  // (2) if the Oapp wants to change to a non DEFAULT from DEFAULT, then set the newLib to 'non-default' with _gracePeriod == 0, then use setReceiveLibraryTimeout() interface
                  if (oldLib == DEFAULT_LIB || _newLib == DEFAULT_LIB) revert Errors.LZ_OnlyNonDefaultLib();
                  // write to storage
                  Timeout memory timeout = Timeout({ lib: oldLib, expiry: block.number + _gracePeriod });
                  receiveLibraryTimeout[_oapp][_eid] = timeout;
                  emit ReceiveLibraryTimeoutSet(_oapp, _eid, oldLib, timeout.expiry);
              } else {
                  delete receiveLibraryTimeout[_oapp][_eid];
                  emit ReceiveLibraryTimeoutSet(_oapp, _eid, oldLib, 0);
              }
          }
          /// @dev Oapp setting the defaultSendLibrary
          /// @dev must be a registered library (including blockLibrary) with the eid support enabled
          /// @dev can used to (1) extend the current configuration (2)  force remove the current configuration (3) change to a new configuration
          /// @param _expiry the block number when lib expires
          function setReceiveLibraryTimeout(
              address _oapp,
              uint32 _eid,
              address _lib,
              uint256 _expiry
          ) external onlyRegistered(_lib) isReceiveLib(_lib) onlySupportedEid(_lib, _eid) {
              _assertAuthorized(_oapp);
              (, bool isDefault) = getReceiveLibrary(_oapp, _eid);
              // if current library is DEFAULT, Oapp cant set the timeout
              if (isDefault) revert Errors.LZ_OnlyNonDefaultLib();
              if (_expiry == 0) {
                  // force remove the current configuration
                  delete receiveLibraryTimeout[_oapp][_eid];
              } else {
                  // override it with new configuration
                  if (_expiry <= block.number) revert Errors.LZ_InvalidExpiry();
                  Timeout storage timeout = receiveLibraryTimeout[_oapp][_eid];
                  timeout.lib = _lib;
                  timeout.expiry = _expiry;
              }
              emit ReceiveLibraryTimeoutSet(_oapp, _eid, _lib, _expiry);
          }
          //------- library config setter/getter. all pass-through functions to the msgLib
          /// @dev authenticated by the _oapp
          function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external onlyRegistered(_lib) {
              _assertAuthorized(_oapp);
              IMessageLib(_lib).setConfig(_oapp, _params);
          }
          /// @dev a view function to query the current configuration of the OApp
          function getConfig(
              address _oapp,
              address _lib,
              uint32 _eid,
              uint32 _configType
          ) external view onlyRegistered(_lib) returns (bytes memory config) {
              return IMessageLib(_lib).getConfig(_eid, _oapp, _configType);
          }
          function _assertAuthorized(address _oapp) internal virtual;
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { IMessagingChannel } from "./interfaces/IMessagingChannel.sol";
      import { Errors } from "./libs/Errors.sol";
      import { GUID } from "./libs/GUID.sol";
      abstract contract MessagingChannel is IMessagingChannel {
          bytes32 public constant EMPTY_PAYLOAD_HASH = bytes32(0);
          bytes32 public constant NIL_PAYLOAD_HASH = bytes32(type(uint256).max);
          // The universally unique id (UUID) of this deployed Endpoint
          uint32 public immutable eid;
          mapping(address receiver => mapping(uint32 srcEid => mapping(bytes32 sender => uint64 nonce)))
              public lazyInboundNonce;
          mapping(address receiver => mapping(uint32 srcEid => mapping(bytes32 sender => mapping(uint64 inboundNonce => bytes32 payloadHash))))
              public inboundPayloadHash;
          mapping(address sender => mapping(uint32 dstEid => mapping(bytes32 receiver => uint64 nonce))) public outboundNonce;
          /// @param _eid is the universally unique id (UUID) of this deployed Endpoint
          constructor(uint32 _eid) {
              eid = _eid;
          }
          /// @dev increase and return the next outbound nonce
          function _outbound(address _sender, uint32 _dstEid, bytes32 _receiver) internal returns (uint64 nonce) {
              unchecked {
                  nonce = ++outboundNonce[_sender][_dstEid][_receiver];
              }
          }
          /// @dev inbound won't update the nonce eagerly to allow unordered verification
          /// @dev instead, it will update the nonce lazily when the message is received
          /// @dev messages can only be cleared in order to preserve censorship-resistance
          function _inbound(
              address _receiver,
              uint32 _srcEid,
              bytes32 _sender,
              uint64 _nonce,
              bytes32 _payloadHash
          ) internal {
              if (_payloadHash == EMPTY_PAYLOAD_HASH) revert Errors.LZ_InvalidPayloadHash();
              inboundPayloadHash[_receiver][_srcEid][_sender][_nonce] = _payloadHash;
          }
          /// @dev returns the max index of the longest gapless sequence of verified msg nonces.
          /// @dev the uninitialized value is 0. the first nonce is always 1
          /// @dev it starts from the lazyInboundNonce (last checkpoint) and iteratively check if the next nonce has been verified
          /// @dev this function can OOG if too many backlogs, but it can be trivially fixed by just clearing some prior messages
          /// @dev NOTE: Oapp explicitly skipped nonces count as "verified" for these purposes
          /// @dev eg. [1,2,3,4,6,7] => 4, [1,2,6,8,10] => 2, [1,3,4,5,6] => 1
          function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) public view returns (uint64) {
              uint64 nonceCursor = lazyInboundNonce[_receiver][_srcEid][_sender];
              // find the effective inbound currentNonce
              unchecked {
                  while (_hasPayloadHash(_receiver, _srcEid, _sender, nonceCursor + 1)) {
                      ++nonceCursor;
                  }
              }
              return nonceCursor;
          }
          /// @dev checks if the storage slot is not initialized. Assumes computationally infeasible that payload can hash to 0
          function _hasPayloadHash(
              address _receiver,
              uint32 _srcEid,
              bytes32 _sender,
              uint64 _nonce
          ) internal view returns (bool) {
              return inboundPayloadHash[_receiver][_srcEid][_sender][_nonce] != EMPTY_PAYLOAD_HASH;
          }
          /// @dev the caller must provide _nonce to prevent skipping the unintended nonce
          /// @dev it could happen in some race conditions, e.g. to skip nonce 3, but nonce 3 was consumed first
          /// @dev usage: skipping the next nonce to prevent message verification, e.g. skip a message when Precrime throws alerts
          /// @dev if the Oapp wants to skip a verified message, it should call the clear() function instead
          /// @dev after skipping, the lazyInboundNonce is set to the provided nonce, which makes the inboundNonce also the provided nonce
          /// @dev ie. allows the Oapp to increment the lazyInboundNonce without having had that corresponding msg be verified
          function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external {
              _assertAuthorized(_oapp);
              if (_nonce != inboundNonce(_oapp, _srcEid, _sender) + 1) revert Errors.LZ_InvalidNonce(_nonce);
              lazyInboundNonce[_oapp][_srcEid][_sender] = _nonce;
              emit InboundNonceSkipped(_srcEid, _sender, _oapp, _nonce);
          }
          /// @dev Marks a packet as verified, but disallows execution until it is re-verified.
          /// @dev Reverts if the provided _payloadHash does not match the currently verified payload hash.
          /// @dev A non-verified nonce can be nilified by passing EMPTY_PAYLOAD_HASH for _payloadHash.
          /// @dev Assumes the computational intractability of finding a payload that hashes to bytes32.max.
          /// @dev Authenticated by the caller
          function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external {
              _assertAuthorized(_oapp);
              bytes32 curPayloadHash = inboundPayloadHash[_oapp][_srcEid][_sender][_nonce];
              if (curPayloadHash != _payloadHash) revert Errors.LZ_PayloadHashNotFound(curPayloadHash, _payloadHash);
              if (_nonce <= lazyInboundNonce[_oapp][_srcEid][_sender] && curPayloadHash == EMPTY_PAYLOAD_HASH)
                  revert Errors.LZ_InvalidNonce(_nonce);
              // set it to nil
              inboundPayloadHash[_oapp][_srcEid][_sender][_nonce] = NIL_PAYLOAD_HASH;
              emit PacketNilified(_srcEid, _sender, _oapp, _nonce, _payloadHash);
          }
          /// @dev Marks a nonce as unexecutable and un-verifiable. The nonce can never be re-verified or executed.
          /// @dev Reverts if the provided _payloadHash does not match the currently verified payload hash.
          /// @dev Only packets with nonces less than or equal to the lazy inbound nonce can be burned.
          /// @dev Reverts if the nonce has already been executed.
          /// @dev Authenticated by the caller
          function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external {
              _assertAuthorized(_oapp);
              bytes32 curPayloadHash = inboundPayloadHash[_oapp][_srcEid][_sender][_nonce];
              if (curPayloadHash != _payloadHash) revert Errors.LZ_PayloadHashNotFound(curPayloadHash, _payloadHash);
              if (curPayloadHash == EMPTY_PAYLOAD_HASH || _nonce > lazyInboundNonce[_oapp][_srcEid][_sender])
                  revert Errors.LZ_InvalidNonce(_nonce);
              delete inboundPayloadHash[_oapp][_srcEid][_sender][_nonce];
              emit PacketBurnt(_srcEid, _sender, _oapp, _nonce, _payloadHash);
          }
          /// @dev calling this function will clear the stored message and increment the lazyInboundNonce to the provided nonce
          /// @dev if a lot of messages are queued, the messages can be cleared with a smaller step size to prevent OOG
          /// @dev NOTE: this function does not change inboundNonce, it only changes the lazyInboundNonce up to the provided nonce
          function _clearPayload(
              address _receiver,
              uint32 _srcEid,
              bytes32 _sender,
              uint64 _nonce,
              bytes memory _payload
          ) internal returns (bytes32 actualHash) {
              uint64 currentNonce = lazyInboundNonce[_receiver][_srcEid][_sender];
              if (_nonce > currentNonce) {
                  unchecked {
                      // try to lazily update the inboundNonce till the _nonce
                      for (uint64 i = currentNonce + 1; i <= _nonce; ++i) {
                          if (!_hasPayloadHash(_receiver, _srcEid, _sender, i)) revert Errors.LZ_InvalidNonce(i);
                      }
                      lazyInboundNonce[_receiver][_srcEid][_sender] = _nonce;
                  }
              }
              // check the hash of the payload to verify the executor has given the proper payload that has been verified
              actualHash = keccak256(_payload);
              bytes32 expectedHash = inboundPayloadHash[_receiver][_srcEid][_sender][_nonce];
              if (expectedHash != actualHash) revert Errors.LZ_PayloadHashNotFound(expectedHash, actualHash);
              // remove it from the storage
              delete inboundPayloadHash[_receiver][_srcEid][_sender][_nonce];
          }
          /// @dev returns the GUID for the next message given the path
          /// @dev the Oapp might want to include the GUID into the message in some cases
          function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32) {
              uint64 nextNonce = outboundNonce[_sender][_dstEid][_receiver] + 1;
              return GUID.generate(nextNonce, eid, _sender, _dstEid, _receiver);
          }
          function _assertAuthorized(address _oapp) internal virtual;
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { IMessagingComposer } from "./interfaces/IMessagingComposer.sol";
      import { ILayerZeroComposer } from "./interfaces/ILayerZeroComposer.sol";
      import { Errors } from "./libs/Errors.sol";
      abstract contract MessagingComposer is IMessagingComposer {
          bytes32 private constant NO_MESSAGE_HASH = bytes32(0);
          bytes32 private constant RECEIVED_MESSAGE_HASH = bytes32(uint256(1));
          mapping(address from => mapping(address to => mapping(bytes32 guid => mapping(uint16 index => bytes32 messageHash))))
              public composeQueue;
          /// @dev the Oapp sends the lzCompose message to the endpoint
          /// @dev the composer MUST assert the sender because anyone can send compose msg with this function
          /// @dev with the same GUID, the Oapp can send compose to multiple _composer at the same time
          /// @dev authenticated by the msg.sender
          /// @param _to the address which will receive the composed message
          /// @param _guid the message guid
          /// @param _message the message
          function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external {
              // must have not been sent before
              if (composeQueue[msg.sender][_to][_guid][_index] != NO_MESSAGE_HASH) revert Errors.LZ_ComposeExists();
              composeQueue[msg.sender][_to][_guid][_index] = keccak256(_message);
              emit ComposeSent(msg.sender, _to, _guid, _index, _message);
          }
          /// @dev execute a composed messages from the sender to the composer (receiver)
          /// @dev the execution provides the execution context (caller, extraData) to the receiver.
          ///      the receiver can optionally assert the caller and validate the untrusted extraData
          /// @dev can not re-entrant
          /// @param _from the address which sends the composed message. in most cases, it is the Oapp's address.
          /// @param _to the address which receives the composed message
          /// @param _guid the message guid
          /// @param _message the message
          /// @param _extraData the extra data provided by the executor. this data is untrusted and should be validated.
          function lzCompose(
              address _from,
              address _to,
              bytes32 _guid,
              uint16 _index,
              bytes calldata _message,
              bytes calldata _extraData
          ) external payable {
              // assert the validity
              bytes32 expectedHash = composeQueue[_from][_to][_guid][_index];
              bytes32 actualHash = keccak256(_message);
              if (expectedHash != actualHash) revert Errors.LZ_ComposeNotFound(expectedHash, actualHash);
              // marks the message as received to prevent reentrancy
              // cannot just delete the value, otherwise the message can be sent again and could result in some undefined behaviour
              // even though the sender(composing Oapp) is implicitly fully trusted by the composer.
              // eg. sender may not even realize it has such a bug
              composeQueue[_from][_to][_guid][_index] = RECEIVED_MESSAGE_HASH;
              ILayerZeroComposer(_to).lzCompose{ value: msg.value }(_from, _guid, _message, msg.sender, _extraData);
              emit ComposeDelivered(_from, _to, _guid, _index);
          }
          /// @param _from the address which sends the composed message
          /// @param _to the address which receives the composed message
          /// @param _guid the message guid
          /// @param _message the message
          /// @param _extraData the extra data provided by the executor
          /// @param _reason the reason why the message is not received
          function lzComposeAlert(
              address _from,
              address _to,
              bytes32 _guid,
              uint16 _index,
              uint256 _gas,
              uint256 _value,
              bytes calldata _message,
              bytes calldata _extraData,
              bytes calldata _reason
          ) external {
              emit LzComposeAlert(_from, _to, msg.sender, _guid, _index, _gas, _value, _message, _extraData, _reason);
          }
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { IMessagingContext } from "./interfaces/IMessagingContext.sol";
      import { Errors } from "./libs/Errors.sol";
      /// this contract acts as a non-reentrancy guard and a source of messaging context
      /// the context includes the remote eid and the sender address
      /// it separates the send and receive context to allow messaging receipts (send back on receive())
      abstract contract MessagingContext is IMessagingContext {
          uint256 private constant NOT_ENTERED = 1;
          uint256 private _sendContext = NOT_ENTERED;
          /// @dev the sendContext is set to 8 bytes 0s + 4 bytes eid + 20 bytes sender
          modifier sendContext(uint32 _dstEid, address _sender) {
              if (_sendContext != NOT_ENTERED) revert Errors.LZ_SendReentrancy();
              _sendContext = (uint256(_dstEid) << 160) | uint160(_sender);
              _;
              _sendContext = NOT_ENTERED;
          }
          /// @dev returns true if sending message
          function isSendingMessage() public view returns (bool) {
              return _sendContext != NOT_ENTERED;
          }
          /// @dev returns (eid, sender) if sending message, (0, 0) otherwise
          function getSendContext() external view returns (uint32, address) {
              return isSendingMessage() ? _getSendContext(_sendContext) : (0, address(0));
          }
          function _getSendContext(uint256 _context) internal pure returns (uint32, address) {
              return (uint32(_context >> 160), address(uint160(_context)));
          }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      /**
       * @title ILayerZeroComposer
       */
      interface ILayerZeroComposer {
          /**
           * @notice Composes a LayerZero message from an OApp.
           * @param _from The address initiating the composition, typically the OApp where the lzReceive was called.
           * @param _guid The unique identifier for the corresponding LayerZero src/dst tx.
           * @param _message The composed message payload in bytes. NOT necessarily the same payload passed via lzReceive.
           * @param _executor The address of the executor for the composed message.
           * @param _extraData Additional arbitrary data in bytes passed by the entity who executes the lzCompose.
           */
          function lzCompose(
              address _from,
              bytes32 _guid,
              bytes calldata _message,
              address _executor,
              bytes calldata _extraData
          ) external payable;
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      import { IMessageLibManager } from "./IMessageLibManager.sol";
      import { IMessagingComposer } from "./IMessagingComposer.sol";
      import { IMessagingChannel } from "./IMessagingChannel.sol";
      import { IMessagingContext } from "./IMessagingContext.sol";
      struct MessagingParams {
          uint32 dstEid;
          bytes32 receiver;
          bytes message;
          bytes options;
          bool payInLzToken;
      }
      struct MessagingReceipt {
          bytes32 guid;
          uint64 nonce;
          MessagingFee fee;
      }
      struct MessagingFee {
          uint256 nativeFee;
          uint256 lzTokenFee;
      }
      struct Origin {
          uint32 srcEid;
          bytes32 sender;
          uint64 nonce;
      }
      interface ILayerZeroEndpointV2 is IMessageLibManager, IMessagingComposer, IMessagingChannel, IMessagingContext {
          event PacketSent(bytes encodedPayload, bytes options, address sendLibrary);
          event PacketVerified(Origin origin, address receiver, bytes32 payloadHash);
          event PacketDelivered(Origin origin, address receiver);
          event LzReceiveAlert(
              address indexed receiver,
              address indexed executor,
              Origin origin,
              bytes32 guid,
              uint256 gas,
              uint256 value,
              bytes message,
              bytes extraData,
              bytes reason
          );
          event LzTokenSet(address token);
          event DelegateSet(address sender, address delegate);
          function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory);
          function send(
              MessagingParams calldata _params,
              address _refundAddress
          ) external payable returns (MessagingReceipt memory);
          function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external;
          function verifiable(Origin calldata _origin, address _receiver) external view returns (bool);
          function initializable(Origin calldata _origin, address _receiver) external view returns (bool);
          function lzReceive(
              Origin calldata _origin,
              address _receiver,
              bytes32 _guid,
              bytes calldata _message,
              bytes calldata _extraData
          ) external payable;
          // oapp can burn messages partially by calling this function with its own business logic if messages are verified in order
          function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external;
          function setLzToken(address _lzToken) external;
          function lzToken() external view returns (address);
          function nativeToken() external view returns (address);
          function setDelegate(address _delegate) external;
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      import { Origin } from "./ILayerZeroEndpointV2.sol";
      interface ILayerZeroReceiver {
          function allowInitializePath(Origin calldata _origin) external view returns (bool);
          function nextNonce(uint32 _eid, bytes32 _sender) external view returns (uint64);
          function lzReceive(
              Origin calldata _origin,
              bytes32 _guid,
              bytes calldata _message,
              address _executor,
              bytes calldata _extraData
          ) external payable;
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
      import { SetConfigParam } from "./IMessageLibManager.sol";
      enum MessageLibType {
          Send,
          Receive,
          SendAndReceive
      }
      interface IMessageLib is IERC165 {
          function setConfig(address _oapp, SetConfigParam[] calldata _config) external;
          function getConfig(uint32 _eid, address _oapp, uint32 _configType) external view returns (bytes memory config);
          function isSupportedEid(uint32 _eid) external view returns (bool);
          // message libs of same major version are compatible
          function version() external view returns (uint64 major, uint8 minor, uint8 endpointVersion);
          function messageLibType() external view returns (MessageLibType);
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      struct SetConfigParam {
          uint32 eid;
          uint32 configType;
          bytes config;
      }
      interface IMessageLibManager {
          struct Timeout {
              address lib;
              uint256 expiry;
          }
          event LibraryRegistered(address newLib);
          event DefaultSendLibrarySet(uint32 eid, address newLib);
          event DefaultReceiveLibrarySet(uint32 eid, address newLib);
          event DefaultReceiveLibraryTimeoutSet(uint32 eid, address oldLib, uint256 expiry);
          event SendLibrarySet(address sender, uint32 eid, address newLib);
          event ReceiveLibrarySet(address receiver, uint32 eid, address newLib);
          event ReceiveLibraryTimeoutSet(address receiver, uint32 eid, address oldLib, uint256 timeout);
          function registerLibrary(address _lib) external;
          function isRegisteredLibrary(address _lib) external view returns (bool);
          function getRegisteredLibraries() external view returns (address[] memory);
          function setDefaultSendLibrary(uint32 _eid, address _newLib) external;
          function defaultSendLibrary(uint32 _eid) external view returns (address);
          function setDefaultReceiveLibrary(uint32 _eid, address _newLib, uint256 _timeout) external;
          function defaultReceiveLibrary(uint32 _eid) external view returns (address);
          function setDefaultReceiveLibraryTimeout(uint32 _eid, address _lib, uint256 _expiry) external;
          function defaultReceiveLibraryTimeout(uint32 _eid) external view returns (address lib, uint256 expiry);
          function isSupportedEid(uint32 _eid) external view returns (bool);
          function isValidReceiveLibrary(address _receiver, uint32 _eid, address _lib) external view returns (bool);
          /// ------------------- OApp interfaces -------------------
          function setSendLibrary(address _oapp, uint32 _eid, address _newLib) external;
          function getSendLibrary(address _sender, uint32 _eid) external view returns (address lib);
          function isDefaultSendLibrary(address _sender, uint32 _eid) external view returns (bool);
          function setReceiveLibrary(address _oapp, uint32 _eid, address _newLib, uint256 _gracePeriod) external;
          function getReceiveLibrary(address _receiver, uint32 _eid) external view returns (address lib, bool isDefault);
          function setReceiveLibraryTimeout(address _oapp, uint32 _eid, address _lib, uint256 _gracePeriod) external;
          function receiveLibraryTimeout(address _receiver, uint32 _eid) external view returns (address lib, uint256 expiry);
          function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external;
          function getConfig(
              address _oapp,
              address _lib,
              uint32 _eid,
              uint32 _configType
          ) external view returns (bytes memory config);
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      interface IMessagingChannel {
          event InboundNonceSkipped(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce);
          event PacketNilified(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);
          event PacketBurnt(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);
          function eid() external view returns (uint32);
          // this is an emergency function if a message cannot be verified for some reasons
          // required to provide _nextNonce to avoid race condition
          function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external;
          function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;
          function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;
          function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32);
          function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
          function outboundNonce(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (uint64);
          function inboundPayloadHash(
              address _receiver,
              uint32 _srcEid,
              bytes32 _sender,
              uint64 _nonce
          ) external view returns (bytes32);
          function lazyInboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      interface IMessagingComposer {
          event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message);
          event ComposeDelivered(address from, address to, bytes32 guid, uint16 index);
          event LzComposeAlert(
              address indexed from,
              address indexed to,
              address indexed executor,
              bytes32 guid,
              uint16 index,
              uint256 gas,
              uint256 value,
              bytes message,
              bytes extraData,
              bytes reason
          );
          function composeQueue(
              address _from,
              address _to,
              bytes32 _guid,
              uint16 _index
          ) external view returns (bytes32 messageHash);
          function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external;
          function lzCompose(
              address _from,
              address _to,
              bytes32 _guid,
              uint16 _index,
              bytes calldata _message,
              bytes calldata _extraData
          ) external payable;
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      interface IMessagingContext {
          function isSendingMessage() external view returns (bool);
          function getSendContext() external view returns (uint32 dstEid, address sender);
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.0;
      import { MessagingFee } from "./ILayerZeroEndpointV2.sol";
      import { IMessageLib } from "./IMessageLib.sol";
      struct Packet {
          uint64 nonce;
          uint32 srcEid;
          address sender;
          uint32 dstEid;
          bytes32 receiver;
          bytes32 guid;
          bytes message;
      }
      interface ISendLib is IMessageLib {
          function send(
              Packet calldata _packet,
              bytes calldata _options,
              bool _payInLzToken
          ) external returns (MessagingFee memory, bytes memory encodedPacket);
          function quote(
              Packet calldata _packet,
              bytes calldata _options,
              bool _payInLzToken
          ) external view returns (MessagingFee memory);
          function setTreasury(address _treasury) external;
          function withdrawFee(address _to, uint256 _amount) external;
          function withdrawLzTokenFee(address _lzToken, address _to, uint256 _amount) external;
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      library AddressCast {
          error AddressCast_InvalidSizeForAddress();
          error AddressCast_InvalidAddress();
          function toBytes32(bytes calldata _addressBytes) internal pure returns (bytes32 result) {
              if (_addressBytes.length > 32) revert AddressCast_InvalidAddress();
              result = bytes32(_addressBytes);
              unchecked {
                  uint256 offset = 32 - _addressBytes.length;
                  result = result >> (offset * 8);
              }
          }
          function toBytes32(address _address) internal pure returns (bytes32 result) {
              result = bytes32(uint256(uint160(_address)));
          }
          function toBytes(bytes32 _addressBytes32, uint256 _size) internal pure returns (bytes memory result) {
              if (_size == 0 || _size > 32) revert AddressCast_InvalidSizeForAddress();
              result = new bytes(_size);
              unchecked {
                  uint256 offset = 256 - _size * 8;
                  assembly {
                      mstore(add(result, 32), shl(offset, _addressBytes32))
                  }
              }
          }
          function toAddress(bytes32 _addressBytes32) internal pure returns (address result) {
              result = address(uint160(uint256(_addressBytes32)));
          }
          function toAddress(bytes calldata _addressBytes) internal pure returns (address result) {
              if (_addressBytes.length != 20) revert AddressCast_InvalidAddress();
              result = address(bytes20(_addressBytes));
          }
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      library Errors {
          error LZ_LzTokenUnavailable();
          error LZ_InvalidReceiveLibrary();
          error LZ_InvalidNonce(uint64 nonce);
          error LZ_InvalidArgument();
          error LZ_InvalidExpiry();
          error LZ_InvalidAmount(uint256 required, uint256 supplied);
          error LZ_OnlyRegisteredOrDefaultLib();
          error LZ_OnlyRegisteredLib();
          error LZ_OnlyNonDefaultLib();
          error LZ_Unauthorized();
          error LZ_DefaultSendLibUnavailable();
          error LZ_DefaultReceiveLibUnavailable();
          error LZ_PathNotInitializable();
          error LZ_PathNotVerifiable();
          error LZ_OnlySendLib();
          error LZ_OnlyReceiveLib();
          error LZ_UnsupportedEid();
          error LZ_UnsupportedInterface();
          error LZ_AlreadyRegistered();
          error LZ_SameValue();
          error LZ_InvalidPayloadHash();
          error LZ_PayloadHashNotFound(bytes32 expected, bytes32 actual);
          error LZ_ComposeNotFound(bytes32 expected, bytes32 actual);
          error LZ_ComposeExists();
          error LZ_SendReentrancy();
          error LZ_NotImplemented();
          error LZ_InsufficientFee(
              uint256 requiredNative,
              uint256 suppliedNative,
              uint256 requiredLzToken,
              uint256 suppliedLzToken
          );
          error LZ_ZeroLzTokenFee();
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { AddressCast } from "./AddressCast.sol";
      library GUID {
          using AddressCast for address;
          function generate(
              uint64 _nonce,
              uint32 _srcEid,
              address _sender,
              uint32 _dstEid,
              bytes32 _receiver
          ) internal pure returns (bytes32) {
              return keccak256(abi.encodePacked(_nonce, _srcEid, _sender.toBytes32(), _dstEid, _receiver));
          }
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
      import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
      library Transfer {
          using SafeERC20 for IERC20;
          address internal constant ADDRESS_ZERO = address(0);
          error Transfer_NativeFailed(address _to, uint256 _value);
          error Transfer_ToAddressIsZero();
          function native(address _to, uint256 _value) internal {
              if (_to == ADDRESS_ZERO) revert Transfer_ToAddressIsZero();
              (bool success, ) = _to.call{ value: _value }("");
              if (!success) revert Transfer_NativeFailed(_to, _value);
          }
          function token(address _token, address _to, uint256 _value) internal {
              if (_to == ADDRESS_ZERO) revert Transfer_ToAddressIsZero();
              IERC20(_token).safeTransfer(_to, _value);
          }
          function nativeOrToken(address _token, address _to, uint256 _value) internal {
              if (_token == ADDRESS_ZERO) {
                  native(_to, _value);
              } else {
                  token(_token, _to, _value);
              }
          }
      }
      // SPDX-License-Identifier: LZBL-1.2
      pragma solidity ^0.8.20;
      import { ERC165 } from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
      import { IMessageLib, MessageLibType } from "../interfaces/IMessageLib.sol";
      import { Errors } from "../libs/Errors.sol";
      contract BlockedMessageLib is ERC165 {
          function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
              return interfaceId == type(IMessageLib).interfaceId || super.supportsInterface(interfaceId);
          }
          function version() external pure returns (uint64 major, uint8 minor, uint8 endpointVersion) {
              return (type(uint64).max, type(uint8).max, 2);
          }
          function messageLibType() external pure returns (MessageLibType) {
              return MessageLibType.SendAndReceive;
          }
          function isSupportedEid(uint32) external pure returns (bool) {
              return true;
          }
          fallback() external {
              revert Errors.LZ_NotImplemented();
          }
      }