{
  "language": "Solidity",
  "sources": {
    "@layerzerolabs/lz-evm-messagelib-v2/contracts/libs/ExecutorOptions.sol": {
      "content": "// SPDX-License-Identifier: LZBL-1.2\n\npragma solidity ^0.8.20;\n\nimport \"@layerzerolabs/lz-evm-protocol-v2/contracts/libs/CalldataBytesLib.sol\";\n\nlibrary ExecutorOptions {\n    using CalldataBytesLib for bytes;\n\n    uint8 internal constant WORKER_ID = 1;\n\n    uint8 internal constant OPTION_TYPE_LZRECEIVE = 1;\n    uint8 internal constant OPTION_TYPE_NATIVE_DROP = 2;\n    uint8 internal constant OPTION_TYPE_LZCOMPOSE = 3;\n    uint8 internal constant OPTION_TYPE_ORDERED_EXECUTION = 4;\n    uint8 internal constant OPTION_TYPE_LZREAD = 5;\n\n    error Executor_InvalidLzReceiveOption();\n    error Executor_InvalidNativeDropOption();\n    error Executor_InvalidLzComposeOption();\n    error Executor_InvalidLzReadOption();\n\n    /// @dev decode the next executor option from the options starting from the specified cursor\n    /// @param _options [executor_id][executor_option][executor_id][executor_option]...\n    ///        executor_option = [option_size][option_type][option]\n    ///        option_size = len(option_type) + len(option)\n    ///        executor_id: uint8, option_size: uint16, option_type: uint8, option: bytes\n    /// @param _cursor the cursor to start decoding from\n    /// @return optionType the type of the option\n    /// @return option the option of the executor\n    /// @return cursor the cursor to start decoding the next executor option\n    function nextExecutorOption(\n        bytes calldata _options,\n        uint256 _cursor\n    ) internal pure returns (uint8 optionType, bytes calldata option, uint256 cursor) {\n        unchecked {\n            // skip worker id\n            cursor = _cursor + 1;\n\n            // read option size\n            uint16 size = _options.toU16(cursor);\n            cursor += 2;\n\n            // read option type\n            optionType = _options.toU8(cursor);\n\n            // startCursor and endCursor are used to slice the option from _options\n            uint256 startCursor = cursor + 1; // skip option type\n            uint256 endCursor = cursor + size;\n            option = _options[startCursor:endCursor];\n            cursor += size;\n        }\n    }\n\n    function decodeLzReceiveOption(bytes calldata _option) internal pure returns (uint128 gas, uint128 value) {\n        if (_option.length != 16 && _option.length != 32) revert Executor_InvalidLzReceiveOption();\n        gas = _option.toU128(0);\n        value = _option.length == 32 ? _option.toU128(16) : 0;\n    }\n\n    function decodeNativeDropOption(bytes calldata _option) internal pure returns (uint128 amount, bytes32 receiver) {\n        if (_option.length != 48) revert Executor_InvalidNativeDropOption();\n        amount = _option.toU128(0);\n        receiver = _option.toB32(16);\n    }\n\n    function decodeLzComposeOption(\n        bytes calldata _option\n    ) internal pure returns (uint16 index, uint128 gas, uint128 value) {\n        if (_option.length != 18 && _option.length != 34) revert Executor_InvalidLzComposeOption();\n        index = _option.toU16(0);\n        gas = _option.toU128(2);\n        value = _option.length == 34 ? _option.toU128(18) : 0;\n    }\n\n    function decodeLzReadOption(\n        bytes calldata _option\n    ) internal pure returns (uint128 gas, uint32 calldataSize, uint128 value) {\n        if (_option.length != 20 && _option.length != 36) revert Executor_InvalidLzReadOption();\n        gas = _option.toU128(0);\n        calldataSize = _option.toU32(16);\n        value = _option.length == 36 ? _option.toU128(20) : 0;\n    }\n\n    function encodeLzReceiveOption(uint128 _gas, uint128 _value) internal pure returns (bytes memory) {\n        return _value == 0 ? abi.encodePacked(_gas) : abi.encodePacked(_gas, _value);\n    }\n\n    function encodeNativeDropOption(uint128 _amount, bytes32 _receiver) internal pure returns (bytes memory) {\n        return abi.encodePacked(_amount, _receiver);\n    }\n\n    function encodeLzComposeOption(uint16 _index, uint128 _gas, uint128 _value) internal pure returns (bytes memory) {\n        return _value == 0 ? abi.encodePacked(_index, _gas) : abi.encodePacked(_index, _gas, _value);\n    }\n\n    function encodeLzReadOption(\n        uint128 _gas,\n        uint32 _calldataSize,\n        uint128 _value\n    ) internal pure returns (bytes memory) {\n        return _value == 0 ? abi.encodePacked(_gas, _calldataSize) : abi.encodePacked(_gas, _calldataSize, _value);\n    }\n}\n"
    },
    "@layerzerolabs/lz-evm-messagelib-v2/contracts/uln/libs/DVNOptions.sol": {
      "content": "// SPDX-License-Identifier: LZBL-1.2\n\npragma solidity ^0.8.20;\n\nimport { BytesLib } from \"solidity-bytes-utils/contracts/BytesLib.sol\";\n\nimport { BitMap256 } from \"@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/BitMaps.sol\";\nimport { CalldataBytesLib } from \"@layerzerolabs/lz-evm-protocol-v2/contracts/libs/CalldataBytesLib.sol\";\n\nlibrary DVNOptions {\n    using CalldataBytesLib for bytes;\n    using BytesLib for bytes;\n\n    uint8 internal constant WORKER_ID = 2;\n    uint8 internal constant OPTION_TYPE_PRECRIME = 1;\n\n    error DVN_InvalidDVNIdx();\n    error DVN_InvalidDVNOptions(uint256 cursor);\n\n    /// @dev group dvn options by its idx\n    /// @param _options [dvn_id][dvn_option][dvn_id][dvn_option]...\n    ///        dvn_option = [option_size][dvn_idx][option_type][option]\n    ///        option_size = len(dvn_idx) + len(option_type) + len(option)\n    ///        dvn_id: uint8, dvn_idx: uint8, option_size: uint16, option_type: uint8, option: bytes\n    /// @return dvnOptions the grouped options, still share the same format of _options\n    /// @return dvnIndices the dvn indices\n    function groupDVNOptionsByIdx(\n        bytes memory _options\n    ) internal pure returns (bytes[] memory dvnOptions, uint8[] memory dvnIndices) {\n        if (_options.length == 0) return (dvnOptions, dvnIndices);\n\n        uint8 numDVNs = getNumDVNs(_options);\n\n        // if there is only 1 dvn, we can just return the whole options\n        if (numDVNs == 1) {\n            dvnOptions = new bytes[](1);\n            dvnOptions[0] = _options;\n\n            dvnIndices = new uint8[](1);\n            dvnIndices[0] = _options.toUint8(3); // dvn idx\n            return (dvnOptions, dvnIndices);\n        }\n\n        // otherwise, we need to group the options by dvn_idx\n        dvnIndices = new uint8[](numDVNs);\n        dvnOptions = new bytes[](numDVNs);\n        unchecked {\n            uint256 cursor = 0;\n            uint256 start = 0;\n            uint8 lastDVNIdx = 255; // 255 is an invalid dvn_idx\n\n            while (cursor < _options.length) {\n                ++cursor; // skip worker_id\n\n                // optionLength asserted in getNumDVNs (skip check)\n                uint16 optionLength = _options.toUint16(cursor);\n                cursor += 2;\n\n                // dvnIdx asserted in getNumDVNs (skip check)\n                uint8 dvnIdx = _options.toUint8(cursor);\n\n                // dvnIdx must equal to the lastDVNIdx for the first option\n                // so it is always skipped in the first option\n                // this operation slices out options whenever the scan finds a different lastDVNIdx\n                if (lastDVNIdx == 255) {\n                    lastDVNIdx = dvnIdx;\n                } else if (dvnIdx != lastDVNIdx) {\n                    uint256 len = cursor - start - 3; // 3 is for worker_id and option_length\n                    bytes memory opt = _options.slice(start, len);\n                    _insertDVNOptions(dvnOptions, dvnIndices, lastDVNIdx, opt);\n\n                    // reset the start and lastDVNIdx\n                    start += len;\n                    lastDVNIdx = dvnIdx;\n                }\n\n                cursor += optionLength;\n            }\n\n            // skip check the cursor here because the cursor is asserted in getNumDVNs\n            // if we have reached the end of the options, we need to process the last dvn\n            uint256 size = cursor - start;\n            bytes memory op = _options.slice(start, size);\n            _insertDVNOptions(dvnOptions, dvnIndices, lastDVNIdx, op);\n\n            // revert dvnIndices to start from 0\n            for (uint8 i = 0; i < numDVNs; ++i) {\n                --dvnIndices[i];\n            }\n        }\n    }\n\n    function _insertDVNOptions(\n        bytes[] memory _dvnOptions,\n        uint8[] memory _dvnIndices,\n        uint8 _dvnIdx,\n        bytes memory _newOptions\n    ) internal pure {\n        // dvnIdx starts from 0 but default value of dvnIndices is 0,\n        // so we tell if the slot is empty by adding 1 to dvnIdx\n        if (_dvnIdx == 255) revert DVN_InvalidDVNIdx();\n        uint8 dvnIdxAdj = _dvnIdx + 1;\n\n        for (uint256 j = 0; j < _dvnIndices.length; ++j) {\n            uint8 index = _dvnIndices[j];\n            if (dvnIdxAdj == index) {\n                _dvnOptions[j] = abi.encodePacked(_dvnOptions[j], _newOptions);\n                break;\n            } else if (index == 0) {\n                // empty slot, that means it is the first time we see this dvn\n                _dvnIndices[j] = dvnIdxAdj;\n                _dvnOptions[j] = _newOptions;\n                break;\n            }\n        }\n    }\n\n    /// @dev get the number of unique dvns\n    /// @param _options the format is the same as groupDVNOptionsByIdx\n    function getNumDVNs(bytes memory _options) internal pure returns (uint8 numDVNs) {\n        uint256 cursor = 0;\n        BitMap256 bitmap;\n\n        // find number of unique dvn_idx\n        unchecked {\n            while (cursor < _options.length) {\n                ++cursor; // skip worker_id\n\n                uint16 optionLength = _options.toUint16(cursor);\n                cursor += 2;\n                if (optionLength < 2) revert DVN_InvalidDVNOptions(cursor); // at least 1 byte for dvn_idx and 1 byte for option_type\n\n                uint8 dvnIdx = _options.toUint8(cursor);\n\n                // if dvnIdx is not set, increment numDVNs\n                // max num of dvns is 255, 255 is an invalid dvn_idx\n                // The order of the dvnIdx is not required to be sequential, as enforcing the order may weaken\n                // the composability of the options. e.g. if we refrain from enforcing the order, an OApp that has\n                // already enforced certain options can append additional options to the end of the enforced\n                // ones without restrictions.\n                if (dvnIdx == 255) revert DVN_InvalidDVNIdx();\n                if (!bitmap.get(dvnIdx)) {\n                    ++numDVNs;\n                    bitmap = bitmap.set(dvnIdx);\n                }\n\n                cursor += optionLength;\n            }\n        }\n        if (cursor != _options.length) revert DVN_InvalidDVNOptions(cursor);\n    }\n\n    /// @dev decode the next dvn option from _options starting from the specified cursor\n    /// @param _options the format is the same as groupDVNOptionsByIdx\n    /// @param _cursor the cursor to start decoding\n    /// @return optionType the type of the option\n    /// @return option the option\n    /// @return cursor the cursor to start decoding the next option\n    function nextDVNOption(\n        bytes calldata _options,\n        uint256 _cursor\n    ) internal pure returns (uint8 optionType, bytes calldata option, uint256 cursor) {\n        unchecked {\n            // skip worker id\n            cursor = _cursor + 1;\n\n            // read option size\n            uint16 size = _options.toU16(cursor);\n            cursor += 2;\n\n            // read option type\n            optionType = _options.toU8(cursor + 1); // skip dvn_idx\n\n            // startCursor and endCursor are used to slice the option from _options\n            uint256 startCursor = cursor + 2; // skip option type and dvn_idx\n            uint256 endCursor = cursor + size;\n            option = _options[startCursor:endCursor];\n            cursor += size;\n        }\n    }\n}\n"
    },
    "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\nimport { IMessageLibManager } from \"./IMessageLibManager.sol\";\nimport { IMessagingComposer } from \"./IMessagingComposer.sol\";\nimport { IMessagingChannel } from \"./IMessagingChannel.sol\";\nimport { IMessagingContext } from \"./IMessagingContext.sol\";\n\nstruct MessagingParams {\n    uint32 dstEid;\n    bytes32 receiver;\n    bytes message;\n    bytes options;\n    bool payInLzToken;\n}\n\nstruct MessagingReceipt {\n    bytes32 guid;\n    uint64 nonce;\n    MessagingFee fee;\n}\n\nstruct MessagingFee {\n    uint256 nativeFee;\n    uint256 lzTokenFee;\n}\n\nstruct Origin {\n    uint32 srcEid;\n    bytes32 sender;\n    uint64 nonce;\n}\n\ninterface ILayerZeroEndpointV2 is IMessageLibManager, IMessagingComposer, IMessagingChannel, IMessagingContext {\n    event PacketSent(bytes encodedPayload, bytes options, address sendLibrary);\n\n    event PacketVerified(Origin origin, address receiver, bytes32 payloadHash);\n\n    event PacketDelivered(Origin origin, address receiver);\n\n    event LzReceiveAlert(\n        address indexed receiver,\n        address indexed executor,\n        Origin origin,\n        bytes32 guid,\n        uint256 gas,\n        uint256 value,\n        bytes message,\n        bytes extraData,\n        bytes reason\n    );\n\n    event LzTokenSet(address token);\n\n    event DelegateSet(address sender, address delegate);\n\n    function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory);\n\n    function send(\n        MessagingParams calldata _params,\n        address _refundAddress\n    ) external payable returns (MessagingReceipt memory);\n\n    function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external;\n\n    function verifiable(Origin calldata _origin, address _receiver) external view returns (bool);\n\n    function initializable(Origin calldata _origin, address _receiver) external view returns (bool);\n\n    function lzReceive(\n        Origin calldata _origin,\n        address _receiver,\n        bytes32 _guid,\n        bytes calldata _message,\n        bytes calldata _extraData\n    ) external payable;\n\n    // oapp can burn messages partially by calling this function with its own business logic if messages are verified in order\n    function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external;\n\n    function setLzToken(address _lzToken) external;\n\n    function lzToken() external view returns (address);\n\n    function nativeToken() external view returns (address);\n\n    function setDelegate(address _delegate) external;\n}\n"
    },
    "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroReceiver.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\nimport { Origin } from \"./ILayerZeroEndpointV2.sol\";\n\ninterface ILayerZeroReceiver {\n    function allowInitializePath(Origin calldata _origin) external view returns (bool);\n\n    function nextNonce(uint32 _eid, bytes32 _sender) external view returns (uint64);\n\n    function lzReceive(\n        Origin calldata _origin,\n        bytes32 _guid,\n        bytes calldata _message,\n        address _executor,\n        bytes calldata _extraData\n    ) external payable;\n}\n"
    },
    "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessageLibManager.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\nstruct SetConfigParam {\n    uint32 eid;\n    uint32 configType;\n    bytes config;\n}\n\ninterface IMessageLibManager {\n    struct Timeout {\n        address lib;\n        uint256 expiry;\n    }\n\n    event LibraryRegistered(address newLib);\n    event DefaultSendLibrarySet(uint32 eid, address newLib);\n    event DefaultReceiveLibrarySet(uint32 eid, address newLib);\n    event DefaultReceiveLibraryTimeoutSet(uint32 eid, address oldLib, uint256 expiry);\n    event SendLibrarySet(address sender, uint32 eid, address newLib);\n    event ReceiveLibrarySet(address receiver, uint32 eid, address newLib);\n    event ReceiveLibraryTimeoutSet(address receiver, uint32 eid, address oldLib, uint256 timeout);\n\n    function registerLibrary(address _lib) external;\n\n    function isRegisteredLibrary(address _lib) external view returns (bool);\n\n    function getRegisteredLibraries() external view returns (address[] memory);\n\n    function setDefaultSendLibrary(uint32 _eid, address _newLib) external;\n\n    function defaultSendLibrary(uint32 _eid) external view returns (address);\n\n    function setDefaultReceiveLibrary(uint32 _eid, address _newLib, uint256 _gracePeriod) external;\n\n    function defaultReceiveLibrary(uint32 _eid) external view returns (address);\n\n    function setDefaultReceiveLibraryTimeout(uint32 _eid, address _lib, uint256 _expiry) external;\n\n    function defaultReceiveLibraryTimeout(uint32 _eid) external view returns (address lib, uint256 expiry);\n\n    function isSupportedEid(uint32 _eid) external view returns (bool);\n\n    function isValidReceiveLibrary(address _receiver, uint32 _eid, address _lib) external view returns (bool);\n\n    /// ------------------- OApp interfaces -------------------\n    function setSendLibrary(address _oapp, uint32 _eid, address _newLib) external;\n\n    function getSendLibrary(address _sender, uint32 _eid) external view returns (address lib);\n\n    function isDefaultSendLibrary(address _sender, uint32 _eid) external view returns (bool);\n\n    function setReceiveLibrary(address _oapp, uint32 _eid, address _newLib, uint256 _gracePeriod) external;\n\n    function getReceiveLibrary(address _receiver, uint32 _eid) external view returns (address lib, bool isDefault);\n\n    function setReceiveLibraryTimeout(address _oapp, uint32 _eid, address _lib, uint256 _expiry) external;\n\n    function receiveLibraryTimeout(address _receiver, uint32 _eid) external view returns (address lib, uint256 expiry);\n\n    function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external;\n\n    function getConfig(\n        address _oapp,\n        address _lib,\n        uint32 _eid,\n        uint32 _configType\n    ) external view returns (bytes memory config);\n}\n"
    },
    "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessagingChannel.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\ninterface IMessagingChannel {\n    event InboundNonceSkipped(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce);\n    event PacketNilified(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);\n    event PacketBurnt(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);\n\n    function eid() external view returns (uint32);\n\n    // this is an emergency function if a message cannot be verified for some reasons\n    // required to provide _nextNonce to avoid race condition\n    function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external;\n\n    function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;\n\n    function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;\n\n    function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32);\n\n    function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);\n\n    function outboundNonce(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (uint64);\n\n    function inboundPayloadHash(\n        address _receiver,\n        uint32 _srcEid,\n        bytes32 _sender,\n        uint64 _nonce\n    ) external view returns (bytes32);\n\n    function lazyInboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);\n}\n"
    },
    "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessagingComposer.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\ninterface IMessagingComposer {\n    event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message);\n    event ComposeDelivered(address from, address to, bytes32 guid, uint16 index);\n    event LzComposeAlert(\n        address indexed from,\n        address indexed to,\n        address indexed executor,\n        bytes32 guid,\n        uint16 index,\n        uint256 gas,\n        uint256 value,\n        bytes message,\n        bytes extraData,\n        bytes reason\n    );\n\n    function composeQueue(\n        address _from,\n        address _to,\n        bytes32 _guid,\n        uint16 _index\n    ) external view returns (bytes32 messageHash);\n\n    function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external;\n\n    function lzCompose(\n        address _from,\n        address _to,\n        bytes32 _guid,\n        uint16 _index,\n        bytes calldata _message,\n        bytes calldata _extraData\n    ) external payable;\n}\n"
    },
    "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessagingContext.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\ninterface IMessagingContext {\n    function isSendingMessage() external view returns (bool);\n\n    function getSendContext() external view returns (uint32 dstEid, address sender);\n}\n"
    },
    "@layerzerolabs/lz-evm-protocol-v2/contracts/libs/CalldataBytesLib.sol": {
      "content": "// SPDX-License-Identifier: LZBL-1.2\n\npragma solidity ^0.8.20;\n\nlibrary CalldataBytesLib {\n    function toU8(bytes calldata _bytes, uint256 _start) internal pure returns (uint8) {\n        return uint8(_bytes[_start]);\n    }\n\n    function toU16(bytes calldata _bytes, uint256 _start) internal pure returns (uint16) {\n        unchecked {\n            uint256 end = _start + 2;\n            return uint16(bytes2(_bytes[_start:end]));\n        }\n    }\n\n    function toU32(bytes calldata _bytes, uint256 _start) internal pure returns (uint32) {\n        unchecked {\n            uint256 end = _start + 4;\n            return uint32(bytes4(_bytes[_start:end]));\n        }\n    }\n\n    function toU64(bytes calldata _bytes, uint256 _start) internal pure returns (uint64) {\n        unchecked {\n            uint256 end = _start + 8;\n            return uint64(bytes8(_bytes[_start:end]));\n        }\n    }\n\n    function toU128(bytes calldata _bytes, uint256 _start) internal pure returns (uint128) {\n        unchecked {\n            uint256 end = _start + 16;\n            return uint128(bytes16(_bytes[_start:end]));\n        }\n    }\n\n    function toU256(bytes calldata _bytes, uint256 _start) internal pure returns (uint256) {\n        unchecked {\n            uint256 end = _start + 32;\n            return uint256(bytes32(_bytes[_start:end]));\n        }\n    }\n\n    function toAddr(bytes calldata _bytes, uint256 _start) internal pure returns (address) {\n        unchecked {\n            uint256 end = _start + 20;\n            return address(bytes20(_bytes[_start:end]));\n        }\n    }\n\n    function toB32(bytes calldata _bytes, uint256 _start) internal pure returns (bytes32) {\n        unchecked {\n            uint256 end = _start + 32;\n            return bytes32(_bytes[_start:end]);\n        }\n    }\n}\n"
    },
    "@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/BitMaps.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\n// modified from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/structs/BitMaps.sol\npragma solidity ^0.8.20;\n\ntype BitMap256 is uint256;\n\nusing BitMaps for BitMap256 global;\n\nlibrary BitMaps {\n    /**\n     * @dev Returns whether the bit at `index` is set.\n     */\n    function get(BitMap256 bitmap, uint8 index) internal pure returns (bool) {\n        uint256 mask = 1 << index;\n        return BitMap256.unwrap(bitmap) & mask != 0;\n    }\n\n    /**\n     * @dev Sets the bit at `index`.\n     */\n    function set(BitMap256 bitmap, uint8 index) internal pure returns (BitMap256) {\n        uint256 mask = 1 << index;\n        return BitMap256.wrap(BitMap256.unwrap(bitmap) | mask);\n    }\n}\n"
    },
    "@layerzerolabs/oapp-evm-upgradeable/contracts/oapp/OAppCoreUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { OwnableUpgradeable } from \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport { IOAppCore, ILayerZeroEndpointV2 } from \"@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppCore.sol\";\n\n/**\n * @title OAppCore\n * @dev Abstract contract implementing the IOAppCore interface with basic OApp configurations.\n */\nabstract contract OAppCoreUpgradeable is IOAppCore, OwnableUpgradeable {\n    struct OAppCoreStorage {\n        mapping(uint32 => bytes32) peers;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"layerzerov2.storage.oappcore\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant OAPP_CORE_STORAGE_LOCATION =\n        0x72ab1bc1039b79dc4724ffca13de82c96834302d3c7e0d4252232d4b2dd8f900;\n\n    function _getOAppCoreStorage() internal pure returns (OAppCoreStorage storage $) {\n        assembly {\n            $.slot := OAPP_CORE_STORAGE_LOCATION\n        }\n    }\n\n    // The LayerZero endpoint associated with the given OApp\n    ILayerZeroEndpointV2 public immutable endpoint;\n\n    /**\n     * @dev Constructor to initialize the OAppCore with the provided endpoint and delegate.\n     * @param _endpoint The address of the LOCAL Layer Zero endpoint.\n     */\n    constructor(address _endpoint) {\n        endpoint = ILayerZeroEndpointV2(_endpoint);\n    }\n\n    /**\n     * @dev Initializes the OAppCore with the provided delegate.\n     * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.\n     *\n     * @dev The delegate typically should be set as the owner of the contract.\n     * @dev Ownable is not initialized here on purpose. It should be initialized in the child contract to\n     * accommodate the different version of Ownable.\n     */\n    function __OAppCore_init(address _delegate) internal onlyInitializing {\n        __OAppCore_init_unchained(_delegate);\n    }\n\n    function __OAppCore_init_unchained(address _delegate) internal onlyInitializing {\n        if (_delegate == address(0)) revert InvalidDelegate();\n        endpoint.setDelegate(_delegate);\n    }\n\n    /**\n     * @notice Returns the peer address (OApp instance) associated with a specific endpoint.\n     * @param _eid The endpoint ID.\n     * @return peer The address of the peer associated with the specified endpoint.\n     */\n    function peers(uint32 _eid) public view override returns (bytes32) {\n        OAppCoreStorage storage $ = _getOAppCoreStorage();\n        return $.peers[_eid];\n    }\n\n    /**\n     * @notice Sets the peer address (OApp instance) for a corresponding endpoint.\n     * @param _eid The endpoint ID.\n     * @param _peer The address of the peer to be associated with the corresponding endpoint.\n     *\n     * @dev Only the owner/admin of the OApp can call this function.\n     * @dev Indicates that the peer is trusted to send LayerZero messages to this OApp.\n     * @dev Set this to bytes32(0) to remove the peer address.\n     * @dev Peer is a bytes32 to accommodate non-evm chains.\n     */\n    function setPeer(uint32 _eid, bytes32 _peer) public virtual onlyOwner {\n        OAppCoreStorage storage $ = _getOAppCoreStorage();\n        $.peers[_eid] = _peer;\n        emit PeerSet(_eid, _peer);\n    }\n\n    /**\n     * @notice Internal function to get the peer address associated with a specific endpoint; reverts if NOT set.\n     * ie. the peer is set to bytes32(0).\n     * @param _eid The endpoint ID.\n     * @return peer The address of the peer associated with the specified endpoint.\n     */\n    function _getPeerOrRevert(uint32 _eid) internal view virtual returns (bytes32) {\n        OAppCoreStorage storage $ = _getOAppCoreStorage();\n        bytes32 peer = $.peers[_eid];\n        if (peer == bytes32(0)) revert NoPeer(_eid);\n        return peer;\n    }\n\n    /**\n     * @notice Sets the delegate address for the OApp.\n     * @param _delegate The address of the delegate to be set.\n     *\n     * @dev Only the owner/admin of the OApp can call this function.\n     * @dev Provides the ability for a delegate to set configs, on behalf of the OApp, directly on the Endpoint contract.\n     */\n    function setDelegate(address _delegate) public onlyOwner {\n        endpoint.setDelegate(_delegate);\n    }\n}\n"
    },
    "@layerzerolabs/oapp-evm-upgradeable/contracts/oapp/OAppReceiverUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { IOAppReceiver, Origin } from \"@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppReceiver.sol\";\nimport { OAppCoreUpgradeable } from \"./OAppCoreUpgradeable.sol\";\n\n/**\n * @title OAppReceiver\n * @dev Abstract contract implementing the ILayerZeroReceiver interface and extending OAppCore for OApp receivers.\n */\nabstract contract OAppReceiverUpgradeable is IOAppReceiver, OAppCoreUpgradeable {\n    // Custom error message for when the caller is not the registered endpoint/\n    error OnlyEndpoint(address addr);\n\n    // @dev The version of the OAppReceiver implementation.\n    // @dev Version is bumped when changes are made to this contract.\n    uint64 internal constant RECEIVER_VERSION = 2;\n\n    /**\n     * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.\n     * @dev Ownable is not initialized here on purpose. It should be initialized in the child contract to\n     * accommodate the different version of Ownable.\n     */\n    function __OAppReceiver_init(address _delegate) internal onlyInitializing {\n        __OAppCore_init(_delegate);\n    }\n\n    function __OAppReceiver_init_unchained() internal onlyInitializing {}\n\n    /**\n     * @notice Retrieves the OApp version information.\n     * @return senderVersion The version of the OAppSender.sol contract.\n     * @return receiverVersion The version of the OAppReceiver.sol contract.\n     *\n     * @dev Providing 0 as the default for OAppSender version. Indicates that the OAppSender is not implemented.\n     * ie. this is a RECEIVE only OApp.\n     * @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions.\n     */\n    function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) {\n        return (0, RECEIVER_VERSION);\n    }\n\n    /**\n     * @notice Indicates whether an address is an approved composeMsg sender to the Endpoint.\n     * @dev _origin The origin information containing the source endpoint and sender address.\n     *  - srcEid: The source chain endpoint ID.\n     *  - sender: The sender address on the src chain.\n     *  - nonce: The nonce of the message.\n     * @dev _message The lzReceive payload.\n     * @param _sender The sender address.\n     * @return isSender Is a valid sender.\n     *\n     * @dev Applications can optionally choose to implement separate composeMsg senders that are NOT the bridging layer.\n     * @dev The default sender IS the OAppReceiver implementer.\n     */\n    function isComposeMsgSender(\n        Origin calldata /*_origin*/,\n        bytes calldata /*_message*/,\n        address _sender\n    ) public view virtual returns (bool) {\n        return _sender == address(this);\n    }\n\n    /**\n     * @notice Checks if the path initialization is allowed based on the provided origin.\n     * @param origin The origin information containing the source endpoint and sender address.\n     * @return Whether the path has been initialized.\n     *\n     * @dev This indicates to the endpoint that the OApp has enabled msgs for this particular path to be received.\n     * @dev This defaults to assuming if a peer has been set, its initialized.\n     * Can be overridden by the OApp if there is other logic to determine this.\n     */\n    function allowInitializePath(Origin calldata origin) public view virtual returns (bool) {\n        return peers(origin.srcEid) == origin.sender;\n    }\n\n    /**\n     * @notice Retrieves the next nonce for a given source endpoint and sender address.\n     * @dev _srcEid The source endpoint ID.\n     * @dev _sender The sender address.\n     * @return nonce The next nonce.\n     *\n     * @dev The path nonce starts from 1. If 0 is returned it means that there is NO nonce ordered enforcement.\n     * @dev Is required by the off-chain executor to determine the OApp expects msg execution is ordered.\n     * @dev This is also enforced by the OApp.\n     * @dev By default this is NOT enabled. ie. nextNonce is hardcoded to return 0.\n     */\n    function nextNonce(uint32, /*_srcEid*/ bytes32 /*_sender*/) public view virtual returns (uint64 nonce) {\n        return 0;\n    }\n\n    /**\n     * @dev Entry point for receiving messages or packets from the endpoint.\n     * @param _origin The origin information containing the source endpoint and sender address.\n     *  - srcEid: The source chain endpoint ID.\n     *  - sender: The sender address on the src chain.\n     *  - nonce: The nonce of the message.\n     * @param _guid The unique identifier for the received LayerZero message.\n     * @param _message The payload of the received message.\n     * @param _executor The address of the executor for the received message.\n     * @param _extraData Additional arbitrary data provided by the corresponding executor.\n     *\n     * @dev Entry point for receiving msg/packet from the LayerZero endpoint.\n     */\n    function lzReceive(\n        Origin calldata _origin,\n        bytes32 _guid,\n        bytes calldata _message,\n        address _executor,\n        bytes calldata _extraData\n    ) public payable virtual {\n        // Ensures that only the endpoint can attempt to lzReceive() messages to this OApp.\n        if (address(endpoint) != msg.sender) revert OnlyEndpoint(msg.sender);\n\n        // Ensure that the sender matches the expected peer for the source endpoint.\n        if (_getPeerOrRevert(_origin.srcEid) != _origin.sender) revert OnlyPeer(_origin.srcEid, _origin.sender);\n\n        // Call the internal OApp implementation of lzReceive.\n        _lzReceive(_origin, _guid, _message, _executor, _extraData);\n    }\n\n    /**\n     * @dev Internal function to implement lzReceive logic without needing to copy the basic parameter validation.\n     */\n    function _lzReceive(\n        Origin calldata _origin,\n        bytes32 _guid,\n        bytes calldata _message,\n        address _executor,\n        bytes calldata _extraData\n    ) internal virtual;\n}\n"
    },
    "@layerzerolabs/oapp-evm-upgradeable/contracts/oapp/OAppSenderUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { SafeERC20, IERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { MessagingParams, MessagingFee, MessagingReceipt } from \"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol\";\nimport { OAppCoreUpgradeable } from \"./OAppCoreUpgradeable.sol\";\n\n/**\n * @title OAppSender\n * @dev Abstract contract implementing the OAppSender functionality for sending messages to a LayerZero endpoint.\n */\nabstract contract OAppSenderUpgradeable is OAppCoreUpgradeable {\n    using SafeERC20 for IERC20;\n\n    // Custom error messages\n    error NotEnoughNative(uint256 msgValue);\n    error LzTokenUnavailable();\n\n    // @dev The version of the OAppSender implementation.\n    // @dev Version is bumped when changes are made to this contract.\n    uint64 internal constant SENDER_VERSION = 1;\n\n    /**\n     * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.\n     * @dev Ownable is not initialized here on purpose. It should be initialized in the child contract to\n     * accommodate the different version of Ownable.\n     */\n    function __OAppSender_init(address _delegate) internal onlyInitializing {\n        __OAppCore_init(_delegate);\n    }\n\n    function __OAppSender_init_unchained() internal onlyInitializing {}\n\n    /**\n     * @notice Retrieves the OApp version information.\n     * @return senderVersion The version of the OAppSender.sol contract.\n     * @return receiverVersion The version of the OAppReceiver.sol contract.\n     *\n     * @dev Providing 0 as the default for OAppReceiver version. Indicates that the OAppReceiver is not implemented.\n     * ie. this is a SEND only OApp.\n     * @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions\n     */\n    function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) {\n        return (SENDER_VERSION, 0);\n    }\n\n    /**\n     * @dev Internal function to interact with the LayerZero EndpointV2.quote() for fee calculation.\n     * @param _dstEid The destination endpoint ID.\n     * @param _message The message payload.\n     * @param _options Additional options for the message.\n     * @param _payInLzToken Flag indicating whether to pay the fee in LZ tokens.\n     * @return fee The calculated MessagingFee for the message.\n     *      - nativeFee: The native fee for the message.\n     *      - lzTokenFee: The LZ token fee for the message.\n     */\n    function _quote(\n        uint32 _dstEid,\n        bytes memory _message,\n        bytes memory _options,\n        bool _payInLzToken\n    ) internal view virtual returns (MessagingFee memory fee) {\n        return\n            endpoint.quote(\n                MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _payInLzToken),\n                address(this)\n            );\n    }\n\n    /**\n     * @dev Internal function to interact with the LayerZero EndpointV2.send() for sending a message.\n     * @param _dstEid The destination endpoint ID.\n     * @param _message The message payload.\n     * @param _options Additional options for the message.\n     * @param _fee The calculated LayerZero fee for the message.\n     *      - nativeFee: The native fee.\n     *      - lzTokenFee: The lzToken fee.\n     * @param _refundAddress The address to receive any excess fee values sent to the endpoint.\n     * @return receipt The receipt for the sent message.\n     *      - guid: The unique identifier for the sent message.\n     *      - nonce: The nonce of the sent message.\n     *      - fee: The LayerZero fee incurred for the message.\n     */\n    function _lzSend(\n        uint32 _dstEid,\n        bytes memory _message,\n        bytes memory _options,\n        MessagingFee memory _fee,\n        address _refundAddress\n    ) internal virtual returns (MessagingReceipt memory receipt) {\n        // @dev Push corresponding fees to the endpoint, any excess is sent back to the _refundAddress from the endpoint.\n        uint256 messageValue = _payNative(_fee.nativeFee);\n        if (_fee.lzTokenFee > 0) _payLzToken(_fee.lzTokenFee);\n\n        return\n            // solhint-disable-next-line check-send-result\n            endpoint.send{ value: messageValue }(\n                MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _fee.lzTokenFee > 0),\n                _refundAddress\n            );\n    }\n\n    /**\n     * @dev Internal function to pay the native fee associated with the message.\n     * @param _nativeFee The native fee to be paid.\n     * @return nativeFee The amount of native currency paid.\n     *\n     * @dev If the OApp needs to initiate MULTIPLE LayerZero messages in a single transaction,\n     * this will need to be overridden because msg.value would contain multiple lzFees.\n     * @dev Should be overridden in the event the LayerZero endpoint requires a different native currency.\n     * @dev Some EVMs use an ERC20 as a method for paying transactions/gasFees.\n     * @dev The endpoint is EITHER/OR, ie. it will NOT support both types of native payment at a time.\n     */\n    function _payNative(uint256 _nativeFee) internal virtual returns (uint256 nativeFee) {\n        if (msg.value != _nativeFee) revert NotEnoughNative(msg.value);\n        return _nativeFee;\n    }\n\n    /**\n     * @dev Internal function to pay the LZ token fee associated with the message.\n     * @param _lzTokenFee The LZ token fee to be paid.\n     *\n     * @dev If the caller is trying to pay in the specified lzToken, then the lzTokenFee is passed to the endpoint.\n     * @dev Any excess sent, is passed back to the specified _refundAddress in the _lzSend().\n     */\n    function _payLzToken(uint256 _lzTokenFee) internal virtual {\n        // @dev Cannot cache the token because it is not immutable in the endpoint.\n        address lzToken = endpoint.lzToken();\n        if (lzToken == address(0)) revert LzTokenUnavailable();\n\n        // Pay LZ token fee by sending tokens to the endpoint.\n        IERC20(lzToken).safeTransferFrom(msg.sender, address(endpoint), _lzTokenFee);\n    }\n}\n"
    },
    "@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppCore.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { ILayerZeroEndpointV2 } from \"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol\";\n\n/**\n * @title IOAppCore\n */\ninterface IOAppCore {\n    // Custom error messages\n    error OnlyPeer(uint32 eid, bytes32 sender);\n    error NoPeer(uint32 eid);\n    error InvalidEndpointCall();\n    error InvalidDelegate();\n\n    // Event emitted when a peer (OApp) is set for a corresponding endpoint\n    event PeerSet(uint32 eid, bytes32 peer);\n\n    /**\n     * @notice Retrieves the OApp version information.\n     * @return senderVersion The version of the OAppSender.sol contract.\n     * @return receiverVersion The version of the OAppReceiver.sol contract.\n     */\n    function oAppVersion() external view returns (uint64 senderVersion, uint64 receiverVersion);\n\n    /**\n     * @notice Retrieves the LayerZero endpoint associated with the OApp.\n     * @return iEndpoint The LayerZero endpoint as an interface.\n     */\n    function endpoint() external view returns (ILayerZeroEndpointV2 iEndpoint);\n\n    /**\n     * @notice Retrieves the peer (OApp) associated with a corresponding endpoint.\n     * @param _eid The endpoint ID.\n     * @return peer The peer address (OApp instance) associated with the corresponding endpoint.\n     */\n    function peers(uint32 _eid) external view returns (bytes32 peer);\n\n    /**\n     * @notice Sets the peer address (OApp instance) for a corresponding endpoint.\n     * @param _eid The endpoint ID.\n     * @param _peer The address of the peer to be associated with the corresponding endpoint.\n     */\n    function setPeer(uint32 _eid, bytes32 _peer) external;\n\n    /**\n     * @notice Sets the delegate address for the OApp Core.\n     * @param _delegate The address of the delegate to be set.\n     */\n    function setDelegate(address _delegate) external;\n}\n"
    },
    "@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppReceiver.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nimport { ILayerZeroReceiver, Origin } from \"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroReceiver.sol\";\n\ninterface IOAppReceiver is ILayerZeroReceiver {\n    /**\n     * @notice Indicates whether an address is an approved composeMsg sender to the Endpoint.\n     * @param _origin The origin information containing the source endpoint and sender address.\n     *  - srcEid: The source chain endpoint ID.\n     *  - sender: The sender address on the src chain.\n     *  - nonce: The nonce of the message.\n     * @param _message The lzReceive payload.\n     * @param _sender The sender address.\n     * @return isSender Is a valid sender.\n     *\n     * @dev Applications can optionally choose to implement a separate composeMsg sender that is NOT the bridging layer.\n     * @dev The default sender IS the OAppReceiver implementer.\n     */\n    function isComposeMsgSender(\n        Origin calldata _origin,\n        bytes calldata _message,\n        address _sender\n    ) external view returns (bool isSender);\n}\n"
    },
    "@layerzerolabs/oapp-evm/contracts/oapp/libs/OptionsBuilder.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { BytesLib } from \"solidity-bytes-utils/contracts/BytesLib.sol\";\nimport { SafeCast } from \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\n\nimport { ExecutorOptions } from \"@layerzerolabs/lz-evm-messagelib-v2/contracts/libs/ExecutorOptions.sol\";\nimport { DVNOptions } from \"@layerzerolabs/lz-evm-messagelib-v2/contracts/uln/libs/DVNOptions.sol\";\n\n/**\n * @title OptionsBuilder\n * @dev Library for building and encoding various message options.\n */\nlibrary OptionsBuilder {\n    using SafeCast for uint256;\n    using BytesLib for bytes;\n\n    // Constants for options types\n    uint16 internal constant TYPE_1 = 1; // legacy options type 1\n    uint16 internal constant TYPE_2 = 2; // legacy options type 2\n    uint16 internal constant TYPE_3 = 3;\n\n    // Custom error message\n    error InvalidSize(uint256 max, uint256 actual);\n    error InvalidOptionType(uint16 optionType);\n\n    // Modifier to ensure only options of type 3 are used\n    modifier onlyType3(bytes memory _options) {\n        if (_options.toUint16(0) != TYPE_3) revert InvalidOptionType(_options.toUint16(0));\n        _;\n    }\n\n    /**\n     * @dev Creates a new options container with type 3.\n     * @return options The newly created options container.\n     */\n    function newOptions() internal pure returns (bytes memory) {\n        return abi.encodePacked(TYPE_3);\n    }\n\n    /**\n     * @dev Adds an executor LZ receive option to the existing options.\n     * @param _options The existing options container.\n     * @param _gas The gasLimit used on the lzReceive() function in the OApp.\n     * @param _value The msg.value passed to the lzReceive() function in the OApp.\n     * @return options The updated options container.\n     *\n     * @dev When multiples of this option are added, they are summed by the executor\n     * eg. if (_gas: 200k, and _value: 1 ether) AND (_gas: 100k, _value: 0.5 ether) are sent in an option to the LayerZeroEndpoint,\n     * that becomes (300k, 1.5 ether) when the message is executed on the remote lzReceive() function.\n     */\n    function addExecutorLzReceiveOption(\n        bytes memory _options,\n        uint128 _gas,\n        uint128 _value\n    ) internal pure onlyType3(_options) returns (bytes memory) {\n        bytes memory option = ExecutorOptions.encodeLzReceiveOption(_gas, _value);\n        return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_LZRECEIVE, option);\n    }\n\n    /**\n     * @dev Adds an executor native drop option to the existing options.\n     * @param _options The existing options container.\n     * @param _amount The amount for the native value that is airdropped to the 'receiver'.\n     * @param _receiver The receiver address for the native drop option.\n     * @return options The updated options container.\n     *\n     * @dev When multiples of this option are added, they are summed by the executor on the remote chain.\n     */\n    function addExecutorNativeDropOption(\n        bytes memory _options,\n        uint128 _amount,\n        bytes32 _receiver\n    ) internal pure onlyType3(_options) returns (bytes memory) {\n        bytes memory option = ExecutorOptions.encodeNativeDropOption(_amount, _receiver);\n        return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_NATIVE_DROP, option);\n    }\n\n    // /**\n    //  * @dev Adds an executor native drop option to the existing options.\n    //  * @param _options The existing options container.\n    //  * @param _amount The amount for the native value that is airdropped to the 'receiver'.\n    //  * @param _receiver The receiver address for the native drop option.\n    //  * @return options The updated options container.\n    //  *\n    //  * @dev When multiples of this option are added, they are summed by the executor on the remote chain.\n    //  */\n    function addExecutorLzReadOption(\n        bytes memory _options,\n        uint128 _gas,\n        uint32 _size,\n        uint128 _value\n    ) internal pure onlyType3(_options) returns (bytes memory) {\n        bytes memory option = ExecutorOptions.encodeLzReadOption(_gas, _size, _value);\n        return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_LZREAD, option);\n    }\n\n    /**\n     * @dev Adds an executor LZ compose option to the existing options.\n     * @param _options The existing options container.\n     * @param _index The index for the lzCompose() function call.\n     * @param _gas The gasLimit for the lzCompose() function call.\n     * @param _value The msg.value for the lzCompose() function call.\n     * @return options The updated options container.\n     *\n     * @dev When multiples of this option are added, they are summed PER index by the executor on the remote chain.\n     * @dev If the OApp sends N lzCompose calls on the remote, you must provide N incremented indexes starting with 0.\n     * ie. When your remote OApp composes (N = 3) messages, you must set this option for index 0,1,2\n     */\n    function addExecutorLzComposeOption(\n        bytes memory _options,\n        uint16 _index,\n        uint128 _gas,\n        uint128 _value\n    ) internal pure onlyType3(_options) returns (bytes memory) {\n        bytes memory option = ExecutorOptions.encodeLzComposeOption(_index, _gas, _value);\n        return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_LZCOMPOSE, option);\n    }\n\n    /**\n     * @dev Adds an executor ordered execution option to the existing options.\n     * @param _options The existing options container.\n     * @return options The updated options container.\n     */\n    function addExecutorOrderedExecutionOption(\n        bytes memory _options\n    ) internal pure onlyType3(_options) returns (bytes memory) {\n        return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_ORDERED_EXECUTION, bytes(\"\"));\n    }\n\n    /**\n     * @dev Adds a DVN pre-crime option to the existing options.\n     * @param _options The existing options container.\n     * @param _dvnIdx The DVN index for the pre-crime option.\n     * @return options The updated options container.\n     */\n    function addDVNPreCrimeOption(\n        bytes memory _options,\n        uint8 _dvnIdx\n    ) internal pure onlyType3(_options) returns (bytes memory) {\n        return addDVNOption(_options, _dvnIdx, DVNOptions.OPTION_TYPE_PRECRIME, bytes(\"\"));\n    }\n\n    /**\n     * @dev Adds an executor option to the existing options.\n     * @param _options The existing options container.\n     * @param _optionType The type of the executor option.\n     * @param _option The encoded data for the executor option.\n     * @return options The updated options container.\n     */\n    function addExecutorOption(\n        bytes memory _options,\n        uint8 _optionType,\n        bytes memory _option\n    ) internal pure onlyType3(_options) returns (bytes memory) {\n        return\n            abi.encodePacked(\n                _options,\n                ExecutorOptions.WORKER_ID,\n                _option.length.toUint16() + 1, // +1 for optionType\n                _optionType,\n                _option\n            );\n    }\n\n    /**\n     * @dev Adds a DVN option to the existing options.\n     * @param _options The existing options container.\n     * @param _dvnIdx The DVN index for the DVN option.\n     * @param _optionType The type of the DVN option.\n     * @param _option The encoded data for the DVN option.\n     * @return options The updated options container.\n     */\n    function addDVNOption(\n        bytes memory _options,\n        uint8 _dvnIdx,\n        uint8 _optionType,\n        bytes memory _option\n    ) internal pure onlyType3(_options) returns (bytes memory) {\n        return\n            abi.encodePacked(\n                _options,\n                DVNOptions.WORKER_ID,\n                _option.length.toUint16() + 2, // +2 for optionType and dvnIdx\n                _dvnIdx,\n                _optionType,\n                _option\n            );\n    }\n\n    /**\n     * @dev Encodes legacy options of type 1.\n     * @param _executionGas The gasLimit value passed to lzReceive().\n     * @return legacyOptions The encoded legacy options.\n     */\n    function encodeLegacyOptionsType1(uint256 _executionGas) internal pure returns (bytes memory) {\n        if (_executionGas > type(uint128).max) revert InvalidSize(type(uint128).max, _executionGas);\n        return abi.encodePacked(TYPE_1, _executionGas);\n    }\n\n    /**\n     * @dev Encodes legacy options of type 2.\n     * @param _executionGas The gasLimit value passed to lzReceive().\n     * @param _nativeForDst The amount of native air dropped to the receiver.\n     * @param _receiver The _nativeForDst receiver address.\n     * @return legacyOptions The encoded legacy options of type 2.\n     */\n    function encodeLegacyOptionsType2(\n        uint256 _executionGas,\n        uint256 _nativeForDst,\n        bytes memory _receiver // @dev Use bytes instead of bytes32 in legacy type 2 for _receiver.\n    ) internal pure returns (bytes memory) {\n        if (_executionGas > type(uint128).max) revert InvalidSize(type(uint128).max, _executionGas);\n        if (_nativeForDst > type(uint128).max) revert InvalidSize(type(uint128).max, _nativeForDst);\n        if (_receiver.length > 32) revert InvalidSize(32, _receiver.length);\n        return abi.encodePacked(TYPE_2, _executionGas, _nativeForDst, _receiver);\n    }\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (access/Ownable2Step.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./OwnableUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership} and {acceptOwnership}.\n *\n * This module is used through inheritance. It will make available all functions\n * from parent (Ownable).\n */\nabstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {\n    function __Ownable2Step_init() internal onlyInitializing {\n        __Ownable_init_unchained();\n    }\n\n    function __Ownable2Step_init_unchained() internal onlyInitializing {\n    }\n    address private _pendingOwner;\n\n    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Returns the address of the pending owner.\n     */\n    function pendingOwner() public view virtual returns (address) {\n        return _pendingOwner;\n    }\n\n    /**\n     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual override onlyOwner {\n        _pendingOwner = newOwner;\n        emit OwnershipTransferStarted(owner(), newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual override {\n        delete _pendingOwner;\n        super._transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev The new owner accepts the ownership transfer.\n     */\n    function acceptOwnership() external {\n        address sender = _msgSender();\n        require(pendingOwner() == sender, \"Ownable2Step: caller is not the new owner\");\n        _transferOwnership(sender);\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    function __Ownable_init() internal onlyInitializing {\n        __Ownable_init_unchained();\n    }\n\n    function __Ownable_init_unchained() internal onlyInitializing {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions anymore. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby removing any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n *     function initializeV2() reinitializer(2) public {\n *         __ERC20Permit_init(\"MyToken\");\n *     }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n *     _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Indicates that the contract has been initialized.\n     * @custom:oz-retyped-from bool\n     */\n    uint8 private _initialized;\n\n    /**\n     * @dev Indicates that the contract is in the process of being initialized.\n     */\n    bool private _initializing;\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint8 version);\n\n    /**\n     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n     * `onlyInitializing` functions can be used to initialize parent contracts.\n     *\n     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n     * constructor.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        bool isTopLevelCall = !_initializing;\n        require(\n            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n            \"Initializable: contract is already initialized\"\n        );\n        _initialized = 1;\n        if (isTopLevelCall) {\n            _initializing = true;\n        }\n        _;\n        if (isTopLevelCall) {\n            _initializing = false;\n            emit Initialized(1);\n        }\n    }\n\n    /**\n     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n     * used to initialize parent contracts.\n     *\n     * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n     * are added through upgrades and that require initialization.\n     *\n     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n     * cannot be nested. If one is invoked in the context of another, execution will revert.\n     *\n     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n     * a contract, executing them in the right order is up to the developer or operator.\n     *\n     * WARNING: setting the version to 255 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint8 version) {\n        require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n        _initialized = version;\n        _initializing = true;\n        _;\n        _initializing = false;\n        emit Initialized(version);\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} and {reinitializer} modifiers, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        require(_initializing, \"Initializable: contract is not initializing\");\n        _;\n    }\n\n    /**\n     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n     * through proxies.\n     *\n     * Emits an {Initialized} event the first time it is successfully executed.\n     */\n    function _disableInitializers() internal virtual {\n        require(!_initializing, \"Initializable: contract is initializing\");\n        if (_initialized < type(uint8).max) {\n            _initialized = type(uint8).max;\n            emit Initialized(type(uint8).max);\n        }\n    }\n\n    /**\n     * @dev Returns the highest version that has been initialized. See {reinitializer}.\n     */\n    function _getInitializedVersion() internal view returns (uint8) {\n        return _initialized;\n    }\n\n    /**\n     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n     */\n    function _isInitializing() internal view returns (bool) {\n        return _initializing;\n    }\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert(errorMessage);\n        }\n    }\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n    function __Context_init() internal onlyInitializing {\n    }\n\n    function __Context_init_unchained() internal onlyInitializing {\n    }\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[50] private __gap;\n}\n"
    },
    "@openzeppelin/contracts/access/IAccessControl.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n    /**\n     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n     *\n     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n     * {RoleAdminChanged} not being emitted signaling this.\n     *\n     * _Available since v3.1._\n     */\n    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n    /**\n     * @dev Emitted when `account` is granted `role`.\n     *\n     * `sender` is the account that originated the contract call, an admin role\n     * bearer except when using {AccessControl-_setupRole}.\n     */\n    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Emitted when `account` is revoked `role`.\n     *\n     * `sender` is the account that originated the contract call:\n     *   - if using `revokeRole`, it is the admin role bearer\n     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)\n     */\n    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) external view returns (bool);\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function grantRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function revokeRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function's\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been granted `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `account`.\n     */\n    function renounceRole(bytes32 role, address account) external;\n}\n"
    },
    "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n *\n * ==== Security Considerations\n *\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\n * generally recommended is:\n *\n * ```solidity\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\n *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\n *     doThing(..., value);\n * }\n *\n * function doThing(..., uint256 value) public {\n *     token.safeTransferFrom(msg.sender, address(this), value);\n *     ...\n * }\n * ```\n *\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\n * {SafeERC20-safeTransferFrom}).\n *\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\n * contracts should have entry points that don't rely on permit.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     *\n     * CAUTION: See Security Considerations above.\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
    },
    "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 amount) external returns (bool);\n}\n"
    },
    "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using Address for address;\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(IERC20 token, address spender, uint256 value) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n        require(\n            (value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        unchecked {\n            uint256 oldAllowance = token.allowance(address(this), spender);\n            require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.\n     * Revert on invalid signature.\n     */\n    function safePermit(\n        IERC20Permit token,\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal {\n        uint256 nonceBefore = token.nonces(owner);\n        token.permit(owner, spender, value, deadline, v, r, s);\n        uint256 nonceAfter = token.nonces(owner);\n        require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        require(returndata.length == 0 || abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n        // and not revert is the subcall reverts.\n\n        (bool success, bytes memory returndata) = address(token).call(data);\n        return\n            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));\n    }\n}\n"
    },
    "@openzeppelin/contracts/utils/Address.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     *\n     * Furthermore, `isContract` will also return true if the target contract within\n     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n     * which only has an effect at the end of a transaction.\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert(errorMessage);\n        }\n    }\n}\n"
    },
    "@openzeppelin/contracts/utils/math/SafeCast.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCast {\n    /**\n     * @dev Returns the downcasted uint248 from uint256, reverting on\n     * overflow (when the input is greater than largest uint248).\n     *\n     * Counterpart to Solidity's `uint248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint248(uint256 value) internal pure returns (uint248) {\n        require(value <= type(uint248).max, \"SafeCast: value doesn't fit in 248 bits\");\n        return uint248(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint240 from uint256, reverting on\n     * overflow (when the input is greater than largest uint240).\n     *\n     * Counterpart to Solidity's `uint240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint240(uint256 value) internal pure returns (uint240) {\n        require(value <= type(uint240).max, \"SafeCast: value doesn't fit in 240 bits\");\n        return uint240(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint232 from uint256, reverting on\n     * overflow (when the input is greater than largest uint232).\n     *\n     * Counterpart to Solidity's `uint232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint232(uint256 value) internal pure returns (uint232) {\n        require(value <= type(uint232).max, \"SafeCast: value doesn't fit in 232 bits\");\n        return uint232(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint224 from uint256, reverting on\n     * overflow (when the input is greater than largest uint224).\n     *\n     * Counterpart to Solidity's `uint224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     *\n     * _Available since v4.2._\n     */\n    function toUint224(uint256 value) internal pure returns (uint224) {\n        require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n        return uint224(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint216 from uint256, reverting on\n     * overflow (when the input is greater than largest uint216).\n     *\n     * Counterpart to Solidity's `uint216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint216(uint256 value) internal pure returns (uint216) {\n        require(value <= type(uint216).max, \"SafeCast: value doesn't fit in 216 bits\");\n        return uint216(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint208 from uint256, reverting on\n     * overflow (when the input is greater than largest uint208).\n     *\n     * Counterpart to Solidity's `uint208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint208(uint256 value) internal pure returns (uint208) {\n        require(value <= type(uint208).max, \"SafeCast: value doesn't fit in 208 bits\");\n        return uint208(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint200 from uint256, reverting on\n     * overflow (when the input is greater than largest uint200).\n     *\n     * Counterpart to Solidity's `uint200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint200(uint256 value) internal pure returns (uint200) {\n        require(value <= type(uint200).max, \"SafeCast: value doesn't fit in 200 bits\");\n        return uint200(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint192 from uint256, reverting on\n     * overflow (when the input is greater than largest uint192).\n     *\n     * Counterpart to Solidity's `uint192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint192(uint256 value) internal pure returns (uint192) {\n        require(value <= type(uint192).max, \"SafeCast: value doesn't fit in 192 bits\");\n        return uint192(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint184 from uint256, reverting on\n     * overflow (when the input is greater than largest uint184).\n     *\n     * Counterpart to Solidity's `uint184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint184(uint256 value) internal pure returns (uint184) {\n        require(value <= type(uint184).max, \"SafeCast: value doesn't fit in 184 bits\");\n        return uint184(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint176 from uint256, reverting on\n     * overflow (when the input is greater than largest uint176).\n     *\n     * Counterpart to Solidity's `uint176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint176(uint256 value) internal pure returns (uint176) {\n        require(value <= type(uint176).max, \"SafeCast: value doesn't fit in 176 bits\");\n        return uint176(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint168 from uint256, reverting on\n     * overflow (when the input is greater than largest uint168).\n     *\n     * Counterpart to Solidity's `uint168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint168(uint256 value) internal pure returns (uint168) {\n        require(value <= type(uint168).max, \"SafeCast: value doesn't fit in 168 bits\");\n        return uint168(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint160 from uint256, reverting on\n     * overflow (when the input is greater than largest uint160).\n     *\n     * Counterpart to Solidity's `uint160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint160(uint256 value) internal pure returns (uint160) {\n        require(value <= type(uint160).max, \"SafeCast: value doesn't fit in 160 bits\");\n        return uint160(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint152 from uint256, reverting on\n     * overflow (when the input is greater than largest uint152).\n     *\n     * Counterpart to Solidity's `uint152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint152(uint256 value) internal pure returns (uint152) {\n        require(value <= type(uint152).max, \"SafeCast: value doesn't fit in 152 bits\");\n        return uint152(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint144 from uint256, reverting on\n     * overflow (when the input is greater than largest uint144).\n     *\n     * Counterpart to Solidity's `uint144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint144(uint256 value) internal pure returns (uint144) {\n        require(value <= type(uint144).max, \"SafeCast: value doesn't fit in 144 bits\");\n        return uint144(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint136 from uint256, reverting on\n     * overflow (when the input is greater than largest uint136).\n     *\n     * Counterpart to Solidity's `uint136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint136(uint256 value) internal pure returns (uint136) {\n        require(value <= type(uint136).max, \"SafeCast: value doesn't fit in 136 bits\");\n        return uint136(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint128 from uint256, reverting on\n     * overflow (when the input is greater than largest uint128).\n     *\n     * Counterpart to Solidity's `uint128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint128(uint256 value) internal pure returns (uint128) {\n        require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n        return uint128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint120 from uint256, reverting on\n     * overflow (when the input is greater than largest uint120).\n     *\n     * Counterpart to Solidity's `uint120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint120(uint256 value) internal pure returns (uint120) {\n        require(value <= type(uint120).max, \"SafeCast: value doesn't fit in 120 bits\");\n        return uint120(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint112 from uint256, reverting on\n     * overflow (when the input is greater than largest uint112).\n     *\n     * Counterpart to Solidity's `uint112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint112(uint256 value) internal pure returns (uint112) {\n        require(value <= type(uint112).max, \"SafeCast: value doesn't fit in 112 bits\");\n        return uint112(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint104 from uint256, reverting on\n     * overflow (when the input is greater than largest uint104).\n     *\n     * Counterpart to Solidity's `uint104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint104(uint256 value) internal pure returns (uint104) {\n        require(value <= type(uint104).max, \"SafeCast: value doesn't fit in 104 bits\");\n        return uint104(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint96 from uint256, reverting on\n     * overflow (when the input is greater than largest uint96).\n     *\n     * Counterpart to Solidity's `uint96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     *\n     * _Available since v4.2._\n     */\n    function toUint96(uint256 value) internal pure returns (uint96) {\n        require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n        return uint96(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint88 from uint256, reverting on\n     * overflow (when the input is greater than largest uint88).\n     *\n     * Counterpart to Solidity's `uint88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint88(uint256 value) internal pure returns (uint88) {\n        require(value <= type(uint88).max, \"SafeCast: value doesn't fit in 88 bits\");\n        return uint88(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint80 from uint256, reverting on\n     * overflow (when the input is greater than largest uint80).\n     *\n     * Counterpart to Solidity's `uint80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint80(uint256 value) internal pure returns (uint80) {\n        require(value <= type(uint80).max, \"SafeCast: value doesn't fit in 80 bits\");\n        return uint80(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint72 from uint256, reverting on\n     * overflow (when the input is greater than largest uint72).\n     *\n     * Counterpart to Solidity's `uint72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint72(uint256 value) internal pure returns (uint72) {\n        require(value <= type(uint72).max, \"SafeCast: value doesn't fit in 72 bits\");\n        return uint72(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint64 from uint256, reverting on\n     * overflow (when the input is greater than largest uint64).\n     *\n     * Counterpart to Solidity's `uint64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint64(uint256 value) internal pure returns (uint64) {\n        require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n        return uint64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint56 from uint256, reverting on\n     * overflow (when the input is greater than largest uint56).\n     *\n     * Counterpart to Solidity's `uint56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint56(uint256 value) internal pure returns (uint56) {\n        require(value <= type(uint56).max, \"SafeCast: value doesn't fit in 56 bits\");\n        return uint56(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint48 from uint256, reverting on\n     * overflow (when the input is greater than largest uint48).\n     *\n     * Counterpart to Solidity's `uint48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint48(uint256 value) internal pure returns (uint48) {\n        require(value <= type(uint48).max, \"SafeCast: value doesn't fit in 48 bits\");\n        return uint48(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint40 from uint256, reverting on\n     * overflow (when the input is greater than largest uint40).\n     *\n     * Counterpart to Solidity's `uint40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint40(uint256 value) internal pure returns (uint40) {\n        require(value <= type(uint40).max, \"SafeCast: value doesn't fit in 40 bits\");\n        return uint40(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint32 from uint256, reverting on\n     * overflow (when the input is greater than largest uint32).\n     *\n     * Counterpart to Solidity's `uint32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint32(uint256 value) internal pure returns (uint32) {\n        require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n        return uint32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint24 from uint256, reverting on\n     * overflow (when the input is greater than largest uint24).\n     *\n     * Counterpart to Solidity's `uint24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint24(uint256 value) internal pure returns (uint24) {\n        require(value <= type(uint24).max, \"SafeCast: value doesn't fit in 24 bits\");\n        return uint24(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint16 from uint256, reverting on\n     * overflow (when the input is greater than largest uint16).\n     *\n     * Counterpart to Solidity's `uint16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint16(uint256 value) internal pure returns (uint16) {\n        require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n        return uint16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint8 from uint256, reverting on\n     * overflow (when the input is greater than largest uint8).\n     *\n     * Counterpart to Solidity's `uint8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint8(uint256 value) internal pure returns (uint8) {\n        require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n        return uint8(value);\n    }\n\n    /**\n     * @dev Converts a signed int256 into an unsigned uint256.\n     *\n     * Requirements:\n     *\n     * - input must be greater than or equal to 0.\n     *\n     * _Available since v3.0._\n     */\n    function toUint256(int256 value) internal pure returns (uint256) {\n        require(value >= 0, \"SafeCast: value must be positive\");\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int248 from int256, reverting on\n     * overflow (when the input is less than smallest int248 or\n     * greater than largest int248).\n     *\n     * Counterpart to Solidity's `int248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt248(int256 value) internal pure returns (int248 downcasted) {\n        downcasted = int248(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 248 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int240 from int256, reverting on\n     * overflow (when the input is less than smallest int240 or\n     * greater than largest int240).\n     *\n     * Counterpart to Solidity's `int240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt240(int256 value) internal pure returns (int240 downcasted) {\n        downcasted = int240(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 240 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int232 from int256, reverting on\n     * overflow (when the input is less than smallest int232 or\n     * greater than largest int232).\n     *\n     * Counterpart to Solidity's `int232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt232(int256 value) internal pure returns (int232 downcasted) {\n        downcasted = int232(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 232 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int224 from int256, reverting on\n     * overflow (when the input is less than smallest int224 or\n     * greater than largest int224).\n     *\n     * Counterpart to Solidity's `int224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt224(int256 value) internal pure returns (int224 downcasted) {\n        downcasted = int224(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 224 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int216 from int256, reverting on\n     * overflow (when the input is less than smallest int216 or\n     * greater than largest int216).\n     *\n     * Counterpart to Solidity's `int216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt216(int256 value) internal pure returns (int216 downcasted) {\n        downcasted = int216(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 216 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int208 from int256, reverting on\n     * overflow (when the input is less than smallest int208 or\n     * greater than largest int208).\n     *\n     * Counterpart to Solidity's `int208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt208(int256 value) internal pure returns (int208 downcasted) {\n        downcasted = int208(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 208 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int200 from int256, reverting on\n     * overflow (when the input is less than smallest int200 or\n     * greater than largest int200).\n     *\n     * Counterpart to Solidity's `int200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt200(int256 value) internal pure returns (int200 downcasted) {\n        downcasted = int200(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 200 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int192 from int256, reverting on\n     * overflow (when the input is less than smallest int192 or\n     * greater than largest int192).\n     *\n     * Counterpart to Solidity's `int192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt192(int256 value) internal pure returns (int192 downcasted) {\n        downcasted = int192(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 192 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int184 from int256, reverting on\n     * overflow (when the input is less than smallest int184 or\n     * greater than largest int184).\n     *\n     * Counterpart to Solidity's `int184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt184(int256 value) internal pure returns (int184 downcasted) {\n        downcasted = int184(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 184 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int176 from int256, reverting on\n     * overflow (when the input is less than smallest int176 or\n     * greater than largest int176).\n     *\n     * Counterpart to Solidity's `int176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt176(int256 value) internal pure returns (int176 downcasted) {\n        downcasted = int176(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 176 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int168 from int256, reverting on\n     * overflow (when the input is less than smallest int168 or\n     * greater than largest int168).\n     *\n     * Counterpart to Solidity's `int168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt168(int256 value) internal pure returns (int168 downcasted) {\n        downcasted = int168(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 168 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int160 from int256, reverting on\n     * overflow (when the input is less than smallest int160 or\n     * greater than largest int160).\n     *\n     * Counterpart to Solidity's `int160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt160(int256 value) internal pure returns (int160 downcasted) {\n        downcasted = int160(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 160 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int152 from int256, reverting on\n     * overflow (when the input is less than smallest int152 or\n     * greater than largest int152).\n     *\n     * Counterpart to Solidity's `int152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt152(int256 value) internal pure returns (int152 downcasted) {\n        downcasted = int152(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 152 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int144 from int256, reverting on\n     * overflow (when the input is less than smallest int144 or\n     * greater than largest int144).\n     *\n     * Counterpart to Solidity's `int144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt144(int256 value) internal pure returns (int144 downcasted) {\n        downcasted = int144(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 144 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int136 from int256, reverting on\n     * overflow (when the input is less than smallest int136 or\n     * greater than largest int136).\n     *\n     * Counterpart to Solidity's `int136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt136(int256 value) internal pure returns (int136 downcasted) {\n        downcasted = int136(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 136 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt128(int256 value) internal pure returns (int128 downcasted) {\n        downcasted = int128(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 128 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int120 from int256, reverting on\n     * overflow (when the input is less than smallest int120 or\n     * greater than largest int120).\n     *\n     * Counterpart to Solidity's `int120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt120(int256 value) internal pure returns (int120 downcasted) {\n        downcasted = int120(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 120 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int112 from int256, reverting on\n     * overflow (when the input is less than smallest int112 or\n     * greater than largest int112).\n     *\n     * Counterpart to Solidity's `int112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt112(int256 value) internal pure returns (int112 downcasted) {\n        downcasted = int112(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 112 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int104 from int256, reverting on\n     * overflow (when the input is less than smallest int104 or\n     * greater than largest int104).\n     *\n     * Counterpart to Solidity's `int104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt104(int256 value) internal pure returns (int104 downcasted) {\n        downcasted = int104(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 104 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int96 from int256, reverting on\n     * overflow (when the input is less than smallest int96 or\n     * greater than largest int96).\n     *\n     * Counterpart to Solidity's `int96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt96(int256 value) internal pure returns (int96 downcasted) {\n        downcasted = int96(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 96 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int88 from int256, reverting on\n     * overflow (when the input is less than smallest int88 or\n     * greater than largest int88).\n     *\n     * Counterpart to Solidity's `int88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt88(int256 value) internal pure returns (int88 downcasted) {\n        downcasted = int88(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 88 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int80 from int256, reverting on\n     * overflow (when the input is less than smallest int80 or\n     * greater than largest int80).\n     *\n     * Counterpart to Solidity's `int80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt80(int256 value) internal pure returns (int80 downcasted) {\n        downcasted = int80(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 80 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int72 from int256, reverting on\n     * overflow (when the input is less than smallest int72 or\n     * greater than largest int72).\n     *\n     * Counterpart to Solidity's `int72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt72(int256 value) internal pure returns (int72 downcasted) {\n        downcasted = int72(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 72 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt64(int256 value) internal pure returns (int64 downcasted) {\n        downcasted = int64(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 64 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int56 from int256, reverting on\n     * overflow (when the input is less than smallest int56 or\n     * greater than largest int56).\n     *\n     * Counterpart to Solidity's `int56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt56(int256 value) internal pure returns (int56 downcasted) {\n        downcasted = int56(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 56 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int48 from int256, reverting on\n     * overflow (when the input is less than smallest int48 or\n     * greater than largest int48).\n     *\n     * Counterpart to Solidity's `int48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt48(int256 value) internal pure returns (int48 downcasted) {\n        downcasted = int48(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 48 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int40 from int256, reverting on\n     * overflow (when the input is less than smallest int40 or\n     * greater than largest int40).\n     *\n     * Counterpart to Solidity's `int40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt40(int256 value) internal pure returns (int40 downcasted) {\n        downcasted = int40(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 40 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt32(int256 value) internal pure returns (int32 downcasted) {\n        downcasted = int32(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 32 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int24 from int256, reverting on\n     * overflow (when the input is less than smallest int24 or\n     * greater than largest int24).\n     *\n     * Counterpart to Solidity's `int24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt24(int256 value) internal pure returns (int24 downcasted) {\n        downcasted = int24(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 24 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt16(int256 value) internal pure returns (int16 downcasted) {\n        downcasted = int16(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 16 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt8(int256 value) internal pure returns (int8 downcasted) {\n        downcasted = int8(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 8 bits\");\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     *\n     * _Available since v3.0._\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n        require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n        return int256(value);\n    }\n}\n"
    },
    "@venusprotocol/isolated-pools/contracts/InterestRateModel.sol": {
      "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\n/**\n * @title Compound's InterestRateModel Interface\n * @author Compound\n */\nabstract contract InterestRateModel {\n    /**\n     * @notice Calculates the current borrow interest rate per slot (block or second)\n     * @param cash The total amount of cash the market has\n     * @param borrows The total amount of borrows the market has outstanding\n     * @param reserves The total amount of reserves the market has\n     * @param badDebt The amount of badDebt in the market\n     * @return The borrow rate percentage per slot (block or second) as a mantissa (scaled by EXP_SCALE)\n     */\n    function getBorrowRate(\n        uint256 cash,\n        uint256 borrows,\n        uint256 reserves,\n        uint256 badDebt\n    ) external view virtual returns (uint256);\n\n    /**\n     * @notice Calculates the current supply interest rate per slot (block or second)\n     * @param cash The total amount of cash the market has\n     * @param borrows The total amount of borrows the market has outstanding\n     * @param reserves The total amount of reserves the market has\n     * @param reserveFactorMantissa The current reserve factor the market has\n     * @param badDebt The amount of badDebt in the market\n     * @return The supply rate percentage per slot (block or second) as a mantissa (scaled by EXP_SCALE)\n     */\n    function getSupplyRate(\n        uint256 cash,\n        uint256 borrows,\n        uint256 reserves,\n        uint256 reserveFactorMantissa,\n        uint256 badDebt\n    ) external view virtual returns (uint256);\n\n    /**\n     * @notice Indicator that this is an InterestRateModel contract (for inspection)\n     * @return Always true\n     */\n    function isInterestRateModel() external pure virtual returns (bool) {\n        return true;\n    }\n}\n"
    },
    "@venusprotocol/solidity-utilities/contracts/validators.sol": {
      "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\n/// @notice Thrown if the supplied address is a zero address where it is not allowed\nerror ZeroAddressNotAllowed();\n\n/// @notice Thrown if the supplied value is 0 where it is not allowed\nerror ZeroValueNotAllowed();\n\n/// @notice Checks if the provided address is nonzero, reverts otherwise\n/// @param address_ Address to check\n/// @custom:error ZeroAddressNotAllowed is thrown if the provided address is a zero address\nfunction ensureNonzeroAddress(address address_) pure {\n    if (address_ == address(0)) {\n        revert ZeroAddressNotAllowed();\n    }\n}\n\n/// @notice Checks if the provided value is nonzero, reverts otherwise\n/// @param value_ Value to check\n/// @custom:error ZeroValueNotAllowed is thrown if the provided value is 0\nfunction ensureNonzeroValue(uint256 value_) pure {\n    if (value_ == 0) {\n        revert ZeroValueNotAllowed();\n    }\n}\n"
    },
    "@venusprotocol/venus-protocol/contracts/InterestRateModels/InterestRateModelV8.sol": {
      "content": "pragma solidity 0.8.25;\n\n/**\n * @title Venus's InterestRateModelV8 Interface\n * @author Venus\n */\nabstract contract InterestRateModelV8 {\n    /// @notice Indicator that this is an InterestRateModel contract (for inspection)\n    bool public constant isInterestRateModel = true;\n\n    /**\n     * @notice Calculates the current borrow interest rate per block\n     * @param cash The total amount of cash the market has\n     * @param borrows The total amount of borrows the market has outstanding\n     * @param reserves The total amnount of reserves the market has\n     * @return The borrow rate per block (as a percentage, and scaled by 1e18)\n     */\n    function getBorrowRate(uint256 cash, uint256 borrows, uint256 reserves) external view virtual returns (uint256);\n\n    /**\n     * @notice Calculates the current supply interest rate per block\n     * @param cash The total amount of cash the market has\n     * @param borrows The total amount of borrows the market has outstanding\n     * @param reserves The total amnount of reserves the market has\n     * @param reserveFactorMantissa The current reserve factor the market has\n     * @return The supply rate per block (as a percentage, and scaled by 1e18)\n     */\n    function getSupplyRate(\n        uint256 cash,\n        uint256 borrows,\n        uint256 reserves,\n        uint256 reserveFactorMantissa\n    ) external view virtual returns (uint256);\n}\n"
    },
    "contracts/Governance/AccessControlledV8.sol": {
      "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol\";\n\nimport \"./IAccessControlManagerV8.sol\";\n\n/**\n * @title AccessControlledV8\n * @author Venus\n * @notice This contract is helper between access control manager and actual contract. This contract further inherited by other contract (using solidity 0.8.13)\n * to integrate access controlled mechanism. It provides initialise methods and verifying access methods.\n */\nabstract contract AccessControlledV8 is Initializable, Ownable2StepUpgradeable {\n    /// @notice Access control manager contract\n    IAccessControlManagerV8 internal _accessControlManager;\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n\n    /// @notice Emitted when access control manager contract address is changed\n    event NewAccessControlManager(address oldAccessControlManager, address newAccessControlManager);\n\n    /// @notice Thrown when the action is prohibited by AccessControlManager\n    error Unauthorized(address sender, address calledContract, string methodSignature);\n\n    function __AccessControlled_init(address accessControlManager_) internal onlyInitializing {\n        __Ownable2Step_init();\n        __AccessControlled_init_unchained(accessControlManager_);\n    }\n\n    function __AccessControlled_init_unchained(address accessControlManager_) internal onlyInitializing {\n        _setAccessControlManager(accessControlManager_);\n    }\n\n    /**\n     * @notice Sets the address of AccessControlManager\n     * @dev Admin function to set address of AccessControlManager\n     * @param accessControlManager_ The new address of the AccessControlManager\n     * @custom:event Emits NewAccessControlManager event\n     * @custom:access Only Governance\n     */\n    function setAccessControlManager(address accessControlManager_) external onlyOwner {\n        _setAccessControlManager(accessControlManager_);\n    }\n\n    /**\n     * @notice Returns the address of the access control manager contract\n     */\n    function accessControlManager() external view returns (IAccessControlManagerV8) {\n        return _accessControlManager;\n    }\n\n    /**\n     * @dev Internal function to set address of AccessControlManager\n     * @param accessControlManager_ The new address of the AccessControlManager\n     */\n    function _setAccessControlManager(address accessControlManager_) internal {\n        require(address(accessControlManager_) != address(0), \"invalid acess control manager address\");\n        address oldAccessControlManager = address(_accessControlManager);\n        _accessControlManager = IAccessControlManagerV8(accessControlManager_);\n        emit NewAccessControlManager(oldAccessControlManager, accessControlManager_);\n    }\n\n    /**\n     * @notice Reverts if the call is not allowed by AccessControlManager\n     * @param signature Method signature\n     */\n    function _checkAccessAllowed(string memory signature) internal view {\n        bool isAllowedToCall = _accessControlManager.isAllowedToCall(msg.sender, signature);\n\n        if (!isAllowedToCall) {\n            revert Unauthorized(msg.sender, address(this), signature);\n        }\n    }\n}\n"
    },
    "contracts/Governance/IAccessControlManagerV8.sol": {
      "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\nimport \"@openzeppelin/contracts/access/IAccessControl.sol\";\n\n/**\n * @title IAccessControlManagerV8\n * @author Venus\n * @notice Interface implemented by the `AccessControlManagerV8` contract.\n */\ninterface IAccessControlManagerV8 is IAccessControl {\n    function giveCallPermission(address contractAddress, string calldata functionSig, address accountToPermit) external;\n\n    function revokeCallPermission(\n        address contractAddress,\n        string calldata functionSig,\n        address accountToRevoke\n    ) external;\n\n    function isAllowedToCall(address account, string calldata functionSig) external view returns (bool);\n\n    function hasPermission(\n        address account,\n        address contractAddress,\n        string calldata functionSig\n    ) external view returns (bool);\n}\n"
    },
    "contracts/interfaces/ICorePoolComptroller.sol": {
      "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\ninterface ICorePoolComptroller {\n    function borrowCaps(address) external view returns (uint256);\n\n    function supplyCaps(address) external view returns (uint256);\n\n    function _setMarketSupplyCaps(address[] calldata, uint256[] calldata) external;\n\n    function _setMarketBorrowCaps(address[] calldata, uint256[] calldata) external;\n\n    function setMarketSupplyCaps(address[] calldata, uint256[] calldata) external;\n\n    function setMarketBorrowCaps(address[] calldata, uint256[] calldata) external;\n\n    function getAllMarkets() external view returns (address[] memory);\n\n    function setCollateralFactor(\n        uint96 poolId,\n        address vToken,\n        uint256 newCollateralFactorMantissa,\n        uint256 newLiquidizationThresholdMantissa\n    ) external returns (uint256);\n\n    function setCollateralFactor(\n        address vToken,\n        uint256 newCollateralFactorMantissa,\n        uint256 newLiquidationThresholdMantissa\n    ) external returns (uint256);\n\n    function markets(\n        address\n    )\n        external\n        view\n        returns (\n            bool isListed,\n            uint256 collateralFactorMantissa,\n            bool isVenus,\n            uint256 liquidationThresholdMantissa,\n            uint256 liquidationIncentiveMantissa,\n            uint96 marketPoolId,\n            bool isBorrowAllowed\n        );\n\n    function poolMarkets(\n        uint96 poolId,\n        address vToken\n    )\n        external\n        view\n        returns (\n            bool isListed,\n            uint256 collateralFactorMantissa,\n            bool isVenus,\n            uint256 liquidationThresholdMantissa,\n            uint256 liquidationIncentiveMantissa,\n            uint96 marketPoolId,\n            bool isBorrowAllowed\n        );\n}\n"
    },
    "contracts/interfaces/ICorePoolVToken.sol": {
      "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { InterestRateModelV8 } from \"@venusprotocol/venus-protocol/contracts/InterestRateModels/InterestRateModelV8.sol\";\n\ninterface ICorePoolVToken {\n    function comptroller() external view returns (address);\n\n    function interestRateModel() external view returns (address);\n\n    function _setInterestRateModel(InterestRateModelV8 newInterestRateModel) external returns (uint256);\n}\n"
    },
    "contracts/interfaces/IIsolatedPoolsComptroller.sol": {
      "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\ninterface IIsolatedPoolsComptroller {\n    function borrowCaps(address) external view returns (uint256);\n\n    function supplyCaps(address) external view returns (uint256);\n\n    function setMarketSupplyCaps(address[] calldata, uint256[] calldata) external;\n\n    function setMarketBorrowCaps(address[] calldata, uint256[] calldata) external;\n\n    function getAllMarkets() external view returns (address[] memory);\n\n    function setCollateralFactor(\n        address vToken,\n        uint256 newCollateralFactorMantissa,\n        uint256 newLiquidationThresholdMantissa\n    ) external;\n\n    function markets(\n        address vToken\n    ) external view returns (bool isListed, uint256 collateralFactorMantissa, uint256 liquidationThresholdMantissa);\n}\n"
    },
    "contracts/interfaces/IIsolatedPoolVToken.sol": {
      "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { InterestRateModel } from \"@venusprotocol/isolated-pools/contracts/InterestRateModel.sol\";\n\ninterface IIsolatedPoolVToken {\n    function comptroller() external view returns (address);\n\n    function interestRateModel() external view returns (address);\n\n    function setInterestRateModel(InterestRateModel newInterestRateModel) external;\n}\n"
    },
    "contracts/RiskSteward/BaseRiskSteward.sol": {
      "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { AccessControlledV8 } from \"../Governance/AccessControlledV8.sol\";\nimport { IRiskSteward } from \"./Interfaces/IRiskSteward.sol\";\n\n/**\n * @title BaseRiskSteward\n * @author Venus\n * @notice Abstract base contract for Risk Steward contracts providing common functionality\n * @custom:security-contact https://github.com/VenusProtocol/governance-contracts#discussion\n */\nabstract contract BaseRiskSteward is IRiskSteward, AccessControlledV8 {\n    /// @dev Max basis points i.e., 100%\n    uint256 internal constant MAX_BPS = 10000;\n\n    /**\n     * @notice The safe delta threshold in basis points.\n     * @notice Updates within this delta are considered safe and require no timelock. Updates exceeding this delta require timelock.\n     * @dev This is only used by contracts that implement safe delta checks (e.g., MarketCapsRiskSteward, CollateralFactorsRiskSteward)\n     */\n    uint256 public safeDeltaBps;\n\n    /**\n     * @notice Thrown when trying to renounce ownership\n     */\n    error RenounceOwnershipNotAllowed();\n\n    /**\n     * @notice Disables renounceOwnership function\n     * @custom:error Throws RenounceOwnershipNotAllowed\n     */\n    function renounceOwnership() public pure override {\n        revert RenounceOwnershipNotAllowed();\n    }\n\n    /**\n     * @notice Checks if the difference between new and current values is within the safe delta threshold.\n     * @param newValue The new value to check\n     * @param currentValue The current value to compare against\n     * @return True if the difference is within the safe delta, false otherwise\n     */\n    function _isWithinSafeDelta(uint256 newValue, uint256 currentValue) internal view returns (bool) {\n        uint256 diff = newValue > currentValue ? newValue - currentValue : currentValue - newValue;\n        uint256 maxDiff = (safeDeltaBps * currentValue) / MAX_BPS;\n        return diff <= maxDiff;\n    }\n}\n"
    },
    "contracts/RiskSteward/CollateralFactorsRiskSteward.sol": {
      "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { RiskParameterUpdate } from \"./Interfaces/IRiskOracle.sol\";\nimport { ICorePoolVToken } from \"../interfaces/ICorePoolVToken.sol\";\nimport { ICorePoolComptroller } from \"../interfaces/ICorePoolComptroller.sol\";\nimport { IIsolatedPoolsComptroller } from \"../interfaces/IIsolatedPoolsComptroller.sol\";\nimport { IRiskStewardReceiver } from \"./Interfaces/IRiskStewardReceiver.sol\";\nimport { BaseRiskSteward } from \"./BaseRiskSteward.sol\";\nimport { ensureNonzeroAddress } from \"@venusprotocol/solidity-utilities/contracts/validators.sol\";\n\n/**\n * @title CollateralFactorsRiskSteward\n * @author Venus\n * @notice Contract that can update collateral factors and liquidation thresholds received from `RiskStewardReceiver`.\n * @custom:security-contact https://github.com/VenusProtocol/governance-contracts#discussion\n */\ncontract CollateralFactorsRiskSteward is BaseRiskSteward {\n    /**\n     * @notice The update type for collateral factor and liquidation threshold.\n     */\n    string public constant COLLATERAL_FACTORS = \"collateralFactors\";\n\n    /**\n     * @notice The update type key for collateral factors (keccak256 hash of COLLATERAL_FACTORS)\n     */\n    bytes32 public constant COLLATERAL_FACTORS_KEY = keccak256(bytes(COLLATERAL_FACTORS));\n\n    /**\n     * @notice Address of the BNB Core Pool Comptroller.\n     * @dev This comptroller is specific to the BNB Core Pool, which uses a different ABI\n     *      than isolated pools. It is used solely to detect and handle BNB Core Pool\n     *      markets, and would not be used for remote-chain (isolated pool) deployments.\n     */\n    ICorePoolComptroller public immutable CORE_POOL_COMPTROLLER;\n\n    /**\n     * @notice Address of the `RiskStewardReceiver` used to validate and dispatch incoming updates.\n     */\n    IRiskStewardReceiver public immutable RISK_STEWARD_RECEIVER;\n\n    /**\n     * @dev Storage gap for upgradeability.\n     */\n    uint256[49] private __gap;\n\n    /**\n     * @notice Emitted when collateral factors are updated.\n     */\n    event CollateralFactorsUpdated(\n        uint256 indexed updateId,\n        address indexed market,\n        uint256 newCollateralFactor,\n        uint256 newLiquidationThreshold\n    );\n\n    /**\n     * @notice Emitted when the safe delta bps is updated.\n     */\n    event SafeDeltaBpsUpdated(uint256 oldSafeDeltaBps, uint256 newSafeDeltaBps);\n\n    /**\n     * @notice Thrown when a `safeDeltaBps` value is greater than `MAX_BPS`.\n     */\n    error InvalidSafeDeltaBps();\n\n    /**\n     * @notice Thrown when Core Pool Comptroller.setCollateralFactor fails.\n     */\n    error SetCollateralFactorFailed(uint256 errorCode);\n\n    /**\n     * @notice Thrown when an invalid pool configuration is used (non-core comptroller with non-zero poolId).\n     */\n    error InvalidPool();\n\n    /**\n     * @notice Thrown when an update type that is not supported is operated on.\n     */\n    error UnsupportedUpdateType();\n\n    /**\n     * @notice Thrown when the update is not coming from the `RiskStewardReceiver`.\n     */\n    error OnlyRiskStewardReceiver();\n\n    /**\n     * @notice Thrown when the two uint256 data length is invalid\n     */\n    error InvalidTwoUintLength();\n\n    /**\n     * @notice Thrown when attempting to apply a redundant value (no-op change).\n     */\n    error RedundantValue();\n\n    /**\n     * @notice Sets the immutable `CORE_POOL_COMPTROLLER` and `RISK_STEWARD_RECEIVER` addresses and disables initializers.\n     * @param corePoolComptroller_ The address of the Core Pool Comptroller\n     * @param riskStewardReceiver_ The address of the `RiskStewardReceiver`\n     * @custom:error Throws ZeroAddressNotAllowed if any of the addresses are zero\n     * @custom:oz-upgrades-unsafe-allow constructor\n     */\n    constructor(address corePoolComptroller_, address riskStewardReceiver_) {\n        ensureNonzeroAddress(riskStewardReceiver_);\n        CORE_POOL_COMPTROLLER = ICorePoolComptroller(corePoolComptroller_);\n        RISK_STEWARD_RECEIVER = IRiskStewardReceiver(riskStewardReceiver_);\n        _disableInitializers();\n    }\n\n    /**\n     * @notice Initializes the contract as ownable and access controlled.\n     * @param accessControlManager_ The address of the access control manager\n     */\n    function initialize(address accessControlManager_) external initializer {\n        __AccessControlled_init(accessControlManager_);\n    }\n\n    /**\n     * @notice Sets the safe delta bps.\n     * @param safeDeltaBps_ The new safe delta bps\n     * @custom:access Controlled by AccessControlManager\n     * @custom:event Emits SafeDeltaBpsUpdated with the old and new safe delta bps\n     * @custom:error Throws InvalidSafeDeltaBps if the safe delta bps is greater than MAX_BPS\n     * @custom:error Throws RedundantValue if the new safe delta bps is equal to the current value\n     */\n    function setSafeDeltaBps(uint256 safeDeltaBps_) external {\n        _checkAccessAllowed(\"setSafeDeltaBps(uint256)\");\n        if (safeDeltaBps_ > MAX_BPS) {\n            revert InvalidSafeDeltaBps();\n        }\n        uint256 oldSafeDeltaBps = safeDeltaBps;\n\n        if (safeDeltaBps_ == oldSafeDeltaBps) {\n            revert RedundantValue();\n        }\n        safeDeltaBps = safeDeltaBps_;\n        emit SafeDeltaBpsUpdated(oldSafeDeltaBps, safeDeltaBps_);\n    }\n\n    /**\n     * @notice Checks if an update is safe for direct execution (no timelock required).\n     * @param update The update to check.\n     * @return True if update is safe for direct execution, false if timelock is required\n     * @custom:error Throws UnsupportedUpdateType if the update type is not supported\n     * @custom:error Throws RedundantValue if the new collateral factor and liquidation threshold are unchanged\n     */\n    function isSafeForDirectExecution(RiskParameterUpdate calldata update) external view returns (bool) {\n        if (update.updateTypeKey == COLLATERAL_FACTORS_KEY) {\n            // eMode-style updates always require timelock (not safe for direct execution)\n            if (update.poolId != 0) return false;\n\n            address comptroller = ICorePoolVToken(update.market).comptroller();\n\n            (uint256 newCF, uint256 newLT) = _decodeAbiEncodedTwoUint256(update.newValue);\n            (uint256 currCF, uint256 currLT) = _getCurrentCollateralFactors(comptroller, update.market);\n\n            // Revert on redundant updates only when both CF and LT are unchanged.\n            if (newCF == currCF && newLT == currLT) {\n                revert RedundantValue();\n            }\n\n            // If current values are zero, update always requires timelock\n            if (currCF == 0 || currLT == 0) return false;\n\n            return _isWithinSafeDelta(newCF, currCF) && _isWithinSafeDelta(newLT, currLT);\n        }\n\n        revert UnsupportedUpdateType();\n    }\n\n    /**\n     * @notice Applies a collateral parameter update from the `RiskStewardReceiver`.\n     *         Delta validation and timelock checks are already performed by `RiskStewardReceiver` before execution.\n     * @param update RiskParameterUpdate update to apply\n     * @custom:access Only callable by the `RiskStewardReceiver`\n     * @custom:event Emits CollateralFactorsUpdated with updateId\n     * @custom:error Throws OnlyRiskStewardReceiver if the sender is not the `RiskStewardReceiver`\n     * @custom:error Throws UnsupportedUpdateType if the update type is not supported\n     */\n    function applyUpdate(RiskParameterUpdate calldata update) external {\n        if (msg.sender != address(RISK_STEWARD_RECEIVER)) {\n            revert OnlyRiskStewardReceiver();\n        }\n\n        address comptroller = ICorePoolVToken(update.market).comptroller();\n        uint96 poolId = update.poolId;\n\n        if (update.updateTypeKey == COLLATERAL_FACTORS_KEY) {\n            _updateCollateralFactors(update.updateId, comptroller, update.market, poolId, update.newValue);\n        } else {\n            revert UnsupportedUpdateType();\n        }\n    }\n\n    /**\n     * @notice Updates the collateral factors for the given market.\n     * @dev Updates both collateral factor and liquidation threshold together (same setter).\n     * @param updateId The update ID from the Risk Oracle\n     * @param comptroller The comptroller address\n     * @param market The market to update the collateral factors for\n     * @param poolId The pool identifier for eMode updates (0 for regular market updates)\n     * @param newValue Encoded new collateral factors: `abi.encode(uint256 newCollateralFactor, uint256 newLiquidationThreshold)`\n     * @custom:error Throws SetCollateralFactorFailed if the core pool comptroller call to setCollateralFactor returns a non‑zero error code\n     * @custom:error Throws InvalidPool if a non‑core comptroller is used together with a non‑zero poolId\n     * @custom:event Emits CollateralFactorsUpdated with updateId\n     */\n    function _updateCollateralFactors(\n        uint256 updateId,\n        address comptroller,\n        address market,\n        uint96 poolId,\n        bytes memory newValue\n    ) internal {\n        (uint256 newCollateralFactor, uint256 newLiquidationThreshold) = _decodeAbiEncodedTwoUint256(newValue);\n\n        if (comptroller == address(CORE_POOL_COMPTROLLER)) {\n            uint256 errorCode = ICorePoolComptroller(comptroller).setCollateralFactor(\n                poolId,\n                market,\n                newCollateralFactor,\n                newLiquidationThreshold\n            );\n            if (errorCode != 0) revert SetCollateralFactorFailed(errorCode);\n        } else {\n            if (poolId != 0) revert InvalidPool();\n\n            IIsolatedPoolsComptroller(comptroller).setCollateralFactor(\n                market,\n                newCollateralFactor,\n                newLiquidationThreshold\n            );\n        }\n\n        emit CollateralFactorsUpdated(updateId, market, newCollateralFactor, newLiquidationThreshold);\n    }\n\n    /**\n     * @notice Returns the current collateral factors for a market on a given comptroller.\n     * @dev Returns both collateral factor and liquidation threshold (updated together via the same setter).\n     * @param comptroller The comptroller address\n     * @param market The market whose collateral factors are being queried\n     * @return currentCollateralFactor The current collateral factor\n     * @return currentLiquidationThreshold The current liquidation threshold\n     */\n    function _getCurrentCollateralFactors(\n        address comptroller,\n        address market\n    ) internal view returns (uint256 currentCollateralFactor, uint256 currentLiquidationThreshold) {\n        if (comptroller == address(CORE_POOL_COMPTROLLER)) {\n            (, currentCollateralFactor, , currentLiquidationThreshold, , , ) = ICorePoolComptroller(comptroller)\n                .markets(market);\n        } else {\n            (, currentCollateralFactor, currentLiquidationThreshold) = IIsolatedPoolsComptroller(comptroller).markets(\n                market\n            );\n        }\n    }\n\n    /**\n     * @notice Decodes ABI-encoded bytes into two uint256 values.\n     * @dev Expects exactly 64 bytes as produced by abi.encode(uint256,uint256).\n     * @param data ABI-encoded (uint256, uint256) payload\n     * @return a First uint256\n     * @return b Second uint256\n     * @custom:error Throws InvalidTwoUintLength if data length is not 64 bytes\n     */\n    function _decodeAbiEncodedTwoUint256(bytes memory data) internal pure returns (uint256 a, uint256 b) {\n        if (data.length != 64) {\n            revert InvalidTwoUintLength();\n        }\n        (a, b) = abi.decode(data, (uint256, uint256));\n    }\n}\n"
    },
    "contracts/RiskSteward/DestinationStewardReceiver.sol": {
      "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { OwnableUpgradeable } from \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport { Ownable2StepUpgradeable } from \"@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol\";\nimport { IDestinationStewardReceiver } from \"./Interfaces/IDestinationStewardReceiver.sol\";\nimport { RiskParameterUpdate } from \"./Interfaces/IRiskOracle.sol\";\nimport { IRiskSteward } from \"./Interfaces/IRiskSteward.sol\";\nimport { ensureNonzeroAddress } from \"@venusprotocol/solidity-utilities/contracts/validators.sol\";\nimport { AccessControlledV8 } from \"../Governance/AccessControlledV8.sol\";\nimport { IIsolatedPoolsComptroller } from \"../interfaces/IIsolatedPoolsComptroller.sol\";\nimport { OAppReceiverUpgradeable, Origin } from \"@layerzerolabs/oapp-evm-upgradeable/contracts/oapp/OAppReceiverUpgradeable.sol\";\nimport { OAppCoreUpgradeable } from \"@layerzerolabs/oapp-evm-upgradeable/contracts/oapp/OAppCoreUpgradeable.sol\";\n\n/**\n * @title DestinationStewardReceiver\n * @author Venus\n * @notice Destination‑chain contract that receives bridged updates from `RiskStewardReceiver` via LayerZero,\n *         enforces a fixed remote delay, and then executes the updates on the configured `IRiskSteward` contracts.\n * @custom:security-contact https://github.com/VenusProtocol/governance-contracts#discussion\n */\ncontract DestinationStewardReceiver is IDestinationStewardReceiver, AccessControlledV8, OAppReceiverUpgradeable {\n    /**\n     * @notice Time before a bridged update is considered stale on the destination chain\n     */\n    uint256 public constant REMOTE_UPDATE_EXPIRATION_TIME = 2 days;\n\n    /**\n     * @notice Destination chain LayerZero endpoint ID\n     */\n    uint32 public immutable LAYER_ZERO_EID;\n\n    /**\n     * @notice Delay before a bridged update can be executed on the destination chain\n     */\n    uint256 public remoteDelay;\n\n    /**\n     * @notice Mapping of supported risk configurations per update type (hashed updateType string)\n     */\n    mapping(bytes32 => RiskParamConfig) public riskParameterConfigs;\n\n    /**\n     * @notice Master storage of all bridged updates by update ID\n     */\n    mapping(uint256 updateId => DestinationUpdate) public updates;\n\n    /**\n     * @notice Mapping from (updateType, market) to currently registered remote update ID\n     */\n    mapping(bytes32 => mapping(address market => uint256)) public lastRegisteredUpdateId;\n\n    /**\n     * @notice Track last executed update timestamp per (updateType, market)\n     */\n    mapping(bytes32 => mapping(address market => uint256)) public lastExecutedAt;\n\n    /**\n     * @notice Mapping from executor address to whitelist status\n     */\n    mapping(address => bool) public whitelistedExecutors;\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[44] private __gap;\n\n    /**\n     * @notice Modifier that ensures only whitelisted executors can call the function\n     * @custom:error NotAnExecutor if the caller is not a whitelisted executor\n     */\n    modifier onlyWhitelistedExecutors() {\n        if (!whitelistedExecutors[msg.sender]) {\n            revert NotAnExecutor();\n        }\n        _;\n    }\n\n    /**\n     * @notice Disables initializers and sets immutable values.\n     * @param endpoint_ Local LayerZero endpoint on this chain\n     * @param layerZeroEid_ LayerZero endpoint ID for this destination chain\n     * @custom:oz-upgrades-unsafe-allow constructor\n     */\n    constructor(address endpoint_, uint32 layerZeroEid_) OAppCoreUpgradeable(endpoint_) {\n        _disableInitializers();\n        ensureNonzeroAddress(endpoint_);\n        if (layerZeroEid_ == 0) revert InvalidLayerZeroEid();\n\n        LAYER_ZERO_EID = layerZeroEid_;\n    }\n\n    /**\n     * @notice Initializes the contract with the Access Control Manager and owner.\n     * @param accessControlManager_ The address of the access control manager\n     * @param delegate_ The owner (and LayerZero delegate) of this contract\n     */\n    function initialize(address accessControlManager_, address delegate_) external initializer {\n        __AccessControlled_init(accessControlManager_);\n        __OAppReceiver_init(delegate_);\n        remoteDelay = 6 hours; // Default value\n        emit RemoteDelaySet(remoteDelay);\n    }\n\n    /**\n     * @notice Sets the risk parameter config for a given update type on the destination chain.\n     * @param updateType The type of update to configure (e.g., \"supplyCap\", \"borrowCap\")\n     * @param riskSteward The address for the risk steward contract responsible for processing the update\n     * @param debounce The debounce period for updates of this type on the destination (anti‑DoS)\n     * @custom:access Controlled by AccessControlManager\n     * @custom:event Emits RiskParameterConfigUpdated\n     * @custom:error InvalidUpdateType if the update type string is empty\n     * @custom:error InvalidDebounce if the debounce is 0\n     */\n    function setRiskParameterConfig(string calldata updateType, address riskSteward, uint256 debounce) external {\n        _checkAccessAllowed(\"setRiskParameterConfig(string,address,uint256)\");\n        ensureNonzeroAddress(riskSteward);\n\n        if (bytes(updateType).length == 0 || bytes(updateType).length > 64) {\n            revert InvalidUpdateType();\n        }\n\n        if (debounce == 0) {\n            revert InvalidDebounce();\n        }\n\n        bytes32 key = keccak256(bytes(updateType));\n        RiskParamConfig storage previousConfig = riskParameterConfigs[key];\n\n        riskParameterConfigs[key] = RiskParamConfig({ active: true, debounce: debounce, riskSteward: riskSteward });\n\n        emit RiskParameterConfigUpdated(\n            key,\n            updateType,\n            previousConfig.riskSteward,\n            riskSteward,\n            previousConfig.debounce,\n            debounce,\n            previousConfig.active,\n            true\n        );\n    }\n\n    /**\n     * @notice Sets the active status of a risk parameter config\n     * @param updateType The type of update to configure\n     * @param active The active status to set\n     * @custom:access Controlled by AccessControlManager\n     * @custom:event Emits ConfigActiveUpdated with the update type hash, update type, previous active status, and the active status\n     * @custom:error Throws UnsupportedUpdateType if the update type is not supported\n     * @custom:error Throws ConfigStatusUnchanged if the active status is already set to the desired value\n     */\n    function setConfigActive(string calldata updateType, bool active) external {\n        _checkAccessAllowed(\"setConfigActive(string,bool)\");\n        bytes32 key = keccak256(bytes(updateType));\n\n        if (riskParameterConfigs[key].riskSteward == address(0)) {\n            revert UnsupportedUpdateType();\n        }\n\n        bool previousActive = riskParameterConfigs[key].active;\n        if (previousActive == active) {\n            revert ConfigStatusUnchanged();\n        }\n\n        riskParameterConfigs[key].active = active;\n        emit ConfigActiveUpdated(key, updateType, previousActive, active);\n    }\n\n    /**\n     * @notice Sets the remote delay before bridged updates can be executed on the destination chain.\n     * @param newRemoteDelay The new remote delay in seconds\n     * @custom:access Controlled by AccessControlManager\n     * @custom:event Emits RemoteDelaySet with the new remote delay value\n     * @custom:error InvalidRemoteDelay if the delay is 0 or greater than or equal to the remote update expiration time\n     * @custom:error RemoteDelayUnchanged if the new delay is equal to the current delay\n     */\n    function setRemoteDelay(uint256 newRemoteDelay) external {\n        _checkAccessAllowed(\"setRemoteDelay(uint256)\");\n\n        if (newRemoteDelay == 0 || newRemoteDelay >= REMOTE_UPDATE_EXPIRATION_TIME) {\n            revert InvalidRemoteDelay();\n        }\n\n        uint256 previousDelay = remoteDelay;\n        if (previousDelay == newRemoteDelay) {\n            revert RemoteDelayUnchanged();\n        }\n\n        remoteDelay = newRemoteDelay;\n        emit RemoteDelaySet(newRemoteDelay);\n    }\n\n    /**\n     * @notice Sets the whitelist status of an executor on the destination chain.\n     * @param executor The address of the executor\n     * @param approved The whitelist status to set (true to whitelist, false to remove)\n     * @custom:access Controlled by AccessControlManager\n     * @custom:event Emits ExecutorStatusUpdated with the executor address, previous approval status, and new approval status\n     * @custom:error Throws ZeroAddressNotAllowed if the executor address is zero\n     * @custom:error Throws ExecutorStatusUnchanged if the executor whitelist status is already set to the desired value\n     */\n    function setWhitelistedExecutor(address executor, bool approved) external {\n        _checkAccessAllowed(\"setWhitelistedExecutor(address,bool)\");\n        ensureNonzeroAddress(executor);\n        bool previousApproved = whitelistedExecutors[executor];\n        if (previousApproved == approved) {\n            revert ExecutorStatusUnchanged();\n        }\n\n        whitelistedExecutors[executor] = approved;\n        emit ExecutorStatusUpdated(executor, previousApproved, approved);\n    }\n\n    /**\n     * @notice Executes a bridged update after its remote delay has passed.\n     * @param updateId The bridged update ID to execute\n     * @custom:access Only whitelisted executors can execute updates\n     * @custom:event Emits RemoteUpdateExecuted with the executed update ID\n     * @custom:error NotAnExecutor if the caller is not a whitelisted executor\n     * @custom:error ConfigNotActive if the configuration for the update type is not active\n     * @custom:error UpdateNotFound if the update is not pending for the given (updateType, market)\n     * @custom:error UpdateNotUnlocked if the remote delay has not elapsed\n     * @custom:error UpdateIsExpired if the bridged update has expired on the destination\n     * @custom:error UpdateTooFrequent if the debounce period has not passed since the last execution\n     */\n    function executeUpdate(uint256 updateId) external onlyWhitelistedExecutors {\n        DestinationUpdate storage destUpdate = updates[updateId];\n        RiskParameterUpdate memory update = destUpdate.update;\n        bytes32 updateTypeKey = update.updateTypeKey;\n        RiskParamConfig storage config = riskParameterConfigs[updateTypeKey];\n        uint256 currentTime = block.timestamp;\n\n        if (!config.active) {\n            revert ConfigNotActive();\n        }\n\n        if (destUpdate.status != UpdateStatus.Pending) {\n            revert UpdateNotFound();\n        }\n\n        if (currentTime < destUpdate.arrivalTime + remoteDelay) {\n            revert UpdateNotUnlocked();\n        }\n\n        if (update.timestamp + REMOTE_UPDATE_EXPIRATION_TIME < currentTime) {\n            revert UpdateIsExpired();\n        }\n\n        // Destination-side debounce based on last execution for this (updateType, market)\n        uint256 lastExecutionTime = lastExecutedAt[updateTypeKey][update.market];\n        if (lastExecutionTime != 0 && (lastExecutionTime + config.debounce > currentTime)) {\n            revert UpdateTooFrequent();\n        }\n\n        lastExecutedAt[updateTypeKey][update.market] = currentTime;\n        destUpdate.status = UpdateStatus.Executed;\n        destUpdate.executor = msg.sender;\n\n        IRiskSteward(config.riskSteward).applyUpdate(update);\n\n        emit RemoteUpdateExecuted(updateId);\n    }\n\n    /**\n     * @notice Rejects a registered remote update on the destination chain.\n     * @param updateId The oracle update ID of the update to reject\n     * @custom:access Only whitelisted executors can reject updates\n     * @custom:event Emits UpdateRejected with the rejected update ID\n     * @custom:error NotAnExecutor if the caller is not a whitelisted executor\n     * @custom:error UpdateNotFound if there is no pending update with the given ID\n     */\n    function rejectUpdate(uint256 updateId) external onlyWhitelistedExecutors {\n        DestinationUpdate storage destUpdate = updates[updateId];\n\n        if (destUpdate.status != UpdateStatus.Pending) {\n            revert UpdateNotFound();\n        }\n\n        destUpdate.status = UpdateStatus.Rejected;\n        emit UpdateRejected(updateId);\n    }\n\n    /**\n     * @notice Returns executable updates for a given update type and comptroller.\n     * @param updateType The human‑readable identifier of the update type to filter by\n     * @param comptroller The address of the Isolated Pools Comptroller that manages the markets\n     * @return executableUpdates Array of update IDs that are ready to be executed\n     */\n    function getExecutableUpdates(\n        string calldata updateType,\n        address comptroller\n    ) external view returns (uint256[] memory executableUpdates) {\n        bytes32 updateTypeKey = keccak256(bytes(updateType));\n        address[] memory markets = IIsolatedPoolsComptroller(comptroller).getAllMarkets();\n        uint256 maxUpdates = markets.length;\n        uint256[] memory tempArray = new uint256[](maxUpdates);\n        uint256 count = 0;\n        RiskParamConfig storage config = riskParameterConfigs[updateTypeKey];\n\n        if (!config.active) return new uint256[](0);\n\n        for (uint256 i = 0; i < maxUpdates; ++i) {\n            address market = markets[i];\n            uint256 registeredUpdateId = lastRegisteredUpdateId[updateTypeKey][market];\n            DestinationUpdate storage destUpdate = updates[registeredUpdateId];\n\n            if (!_checkPendingUpdate(registeredUpdateId)) continue;\n\n            // Validate Remote Delay\n            if (block.timestamp < destUpdate.arrivalTime + remoteDelay) continue;\n\n            // Debounce: skip if last execution for this (updateType, market) is too recent\n            uint256 lastExecutionTime = lastExecutedAt[updateTypeKey][market];\n            if (lastExecutionTime != 0 && (lastExecutionTime + config.debounce > block.timestamp)) continue;\n\n            tempArray[count] = registeredUpdateId;\n            count++;\n        }\n\n        executableUpdates = new uint256[](count);\n        for (uint256 i = 0; i < count; ++i) {\n            executableUpdates[i] = tempArray[i];\n        }\n    }\n\n    /**\n     * @notice Returns the risk parameter configuration for a given update type\n     * @param updateType The human-readable identifier of the update type\n     * @return The risk parameter configuration\n     */\n    function getRiskParameterConfig(string calldata updateType) external view returns (RiskParamConfig memory) {\n        bytes32 key = keccak256(bytes(updateType));\n        return riskParameterConfigs[key];\n    }\n\n    /**\n     * @notice Returns the registered update for a given update type and market\n     * @param updateType The human-readable identifier of the update type\n     * @param market The address of the market\n     * @return The registered update\n     */\n    function getRegisteredUpdate(\n        string calldata updateType,\n        address market\n    ) external view returns (DestinationUpdate memory) {\n        bytes32 key = keccak256(bytes(updateType));\n        uint256 updateId = lastRegisteredUpdateId[key][market];\n        return updates[updateId];\n    }\n\n    /**\n     * @notice Returns the last executed timestamp for a given update type and market\n     * @param updateType The human-readable identifier of the update type\n     * @param market The address of the market\n     * @return The last executed timestamp\n     */\n    function getLastExecutedAt(string calldata updateType, address market) external view returns (uint256) {\n        bytes32 key = keccak256(bytes(updateType));\n        return lastExecutedAt[key][market];\n    }\n\n    /**\n     * @dev Overrides OwnableUpgradeable and Ownable2StepUpgradeable to resolve\n     *      the multiple inheritance ownership transfer conflict.\n     */\n    function transferOwnership(\n        address newOwner\n    ) public override(OwnableUpgradeable, Ownable2StepUpgradeable) onlyOwner {\n        Ownable2StepUpgradeable.transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Internal hook to finalize ownership transfer, resolving the\n     *      OwnableUpgradeable and Ownable2StepUpgradeable inheritance conflict.\n     */\n    function _transferOwnership(address newOwner) internal override(OwnableUpgradeable, Ownable2StepUpgradeable) {\n        Ownable2StepUpgradeable._transferOwnership(newOwner);\n    }\n\n    /**\n     * @notice Internal LayerZero receive hook that handles bridged updates from the source-chain `RiskStewardReceiver`.\n     * @dev Emits `DuplicateUpdateReceived`, `RegisteredPendingUpdateExist`, or `RemoteUpdateRegistered`\n     *      depending on whether the update ID was already seen or a non‑expired pending update exists.\n     * @param payload Encoded `RiskParameterUpdate` sent from the source chain\n     */\n    function _lzReceive(Origin calldata, bytes32, bytes calldata payload, address, bytes calldata) internal override {\n        RiskParameterUpdate memory update = abi.decode(payload, (RiskParameterUpdate));\n        uint256 newId = update.updateId;\n        uint256 arrivalTime = block.timestamp;\n\n        // If this update ID was already stored, treat as a duplicate and do not overwrite\n        if (updates[newId].status != UpdateStatus.None) {\n            emit DuplicateUpdateReceived(newId, arrivalTime, update.updateType, update.market);\n            return;\n        }\n\n        // If already an update in Process do not override the registered update\n        uint256 currentRegisteredId = lastRegisteredUpdateId[update.updateTypeKey][update.market];\n        if (_checkPendingUpdate(currentRegisteredId)) {\n            emit RegisteredPendingUpdateExist(currentRegisteredId, arrivalTime, update.updateType, update.market);\n            return;\n        }\n\n        DestinationUpdate storage destUpdate = updates[newId];\n        destUpdate.update = update;\n        destUpdate.status = UpdateStatus.Pending;\n        destUpdate.arrivalTime = arrivalTime;\n        lastRegisteredUpdateId[update.updateTypeKey][update.market] = newId;\n        emit RemoteUpdateRegistered(newId, arrivalTime, update.updateType, update.market);\n    }\n\n    /**\n     * @notice Checks whether a given registered update ID corresponds to a pending, non‑expired update.\n     * @param currentRegisteredId The currently registered update ID for a specific (updateType, market) pair\n     * @return True if currentRegisteredId is non‑zero, the update status is Pending, and it has not expired; otherwise false\n     */\n    function _checkPendingUpdate(uint256 currentRegisteredId) internal view returns (bool) {\n        if (currentRegisteredId == 0) return false; // no registered update\n\n        DestinationUpdate storage current = updates[currentRegisteredId];\n\n        if (current.status != UpdateStatus.Pending) return false;\n\n        // Check expiration\n        return current.update.timestamp + REMOTE_UPDATE_EXPIRATION_TIME >= block.timestamp;\n    }\n\n    /**\n     * @notice Disables renounceOwnership function\n     * @custom:error Throws RenounceOwnershipNotAllowed\n     */\n    function renounceOwnership() public pure override {\n        revert RenounceOwnershipNotAllowed();\n    }\n}\n"
    },
    "contracts/RiskSteward/Interfaces/IDestinationStewardReceiver.sol": {
      "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { RiskParameterUpdate } from \"./IRiskOracle.sol\";\n\ninterface IDestinationStewardReceiver {\n    /**\n     * @notice Local status of an update on the destination chain\n     */\n    enum UpdateStatus {\n        None,\n        Pending,\n        Executed,\n        Rejected\n    }\n\n    /**\n     * @notice Configuration for a risk parameter update type on the destination chain.\n     * @param active Whether this update type configuration is currently active\n     * @param debounce Minimum delay between consecutive executions for the same (updateType, market) pair\n     * @param riskSteward Address of the risk steward contract responsible for processing this update type\n     */\n    struct RiskParamConfig {\n        bool active;\n        uint256 debounce;\n        address riskSteward;\n    }\n\n    /**\n     * @notice Destination-side storage for a bridged risk parameter update.\n     * @param update The full risk parameter update payload received from the source chain\n     * @param status Current local status of the bridged update (Pending, Executed, Rejected)\n     * @param arrivalTime Timestamp when the update was received on this chain\n     * @param executor Address of the executor who executed this update on the destination (address(0) not executed yet)\n     * @dev Unlock time is derived as `arrivalTime + remoteDelay` instead of being stored separately.\n     */\n    struct DestinationUpdate {\n        RiskParameterUpdate update;\n        UpdateStatus status;\n        uint256 arrivalTime;\n        address executor;\n    }\n\n    /**\n     * @notice Emitted when a risk parameter config is updated for an update type\n     */\n    event RiskParameterConfigUpdated(\n        bytes32 indexed updateTypeHash,\n        string updateType,\n        address indexed previousRiskSteward,\n        address indexed riskSteward,\n        uint256 previousDebounce,\n        uint256 debounce,\n        bool previousActive,\n        bool active\n    );\n\n    /**\n     * @notice Emitted when a bridged update is registered on the destination\n     */\n    event RemoteUpdateRegistered(\n        uint256 indexed updateId,\n        uint256 arrivalTime,\n        string indexed updateType,\n        address indexed market\n    );\n\n    /**\n     * @notice Emitted when a new bridged update arrives but a pending update is already registered for the same (updateType, market).\n     */\n    event RegisteredPendingUpdateExist(\n        uint256 indexed updateId,\n        uint256 arrivalTime,\n        string indexed updateType,\n        address indexed market\n    );\n\n    /**\n     * @notice Emitted when a duplicate bridged update (same updateId) is received.\n     */\n    event DuplicateUpdateReceived(\n        uint256 indexed updateId,\n        uint256 arrivalTime,\n        string indexed updateType,\n        address indexed market\n    );\n\n    /**\n     * @notice Emitted when a bridged update is executed on the destination\n     */\n    event RemoteUpdateExecuted(uint256 indexed updateId);\n\n    /**\n     * @notice Emitted when an executor status is set on the destination\n     */\n    event ExecutorStatusUpdated(address indexed executor, bool previousApproved, bool approved);\n\n    /**\n     * @notice Emitted when a risk parameter config active status is updated\n     */\n    event ConfigActiveUpdated(\n        bytes32 indexed updateTypeHash,\n        string updateType,\n        bool previousActive,\n        bool indexed active\n    );\n\n    /**\n     * @notice Emitted when an update is rejected on the destination\n     */\n    event UpdateRejected(uint256 indexed updateId);\n\n    /**\n     * @notice Emitted when the remote delay is set in the constructor\n     */\n    event RemoteDelaySet(uint256 remoteDelay);\n\n    /**\n     * @notice Thrown when trying to operate on an update that was never registered\n     */\n    error UpdateNotFound();\n\n    /**\n     * @notice Thrown when trying to execute an update before its unlock time\n     */\n    error UpdateNotUnlocked();\n\n    /**\n     * @notice Thrown when config for an update type is not active or not configured\n     */\n    error ConfigNotActive();\n\n    /**\n     * @notice Thrown when a bridged update has expired on the destination\n     */\n    error UpdateIsExpired();\n\n    /**\n     * @notice Thrown when the debounce period hasn't passed for applying an update to a specific market / update type\n     */\n    error UpdateTooFrequent();\n\n    /**\n     * @notice Thrown when an empty update type string is provided\n     */\n    error InvalidUpdateType();\n\n    /**\n     * @notice Thrown when an update type is not supported\n     */\n    error UnsupportedUpdateType();\n\n    /**\n     * @notice Thrown when a debounce value of 0 is set\n     */\n    error InvalidDebounce();\n\n    /**\n     * @notice Thrown when an address is not a whitelisted executor\n     */\n    error NotAnExecutor();\n\n    /**\n     * @notice Thrown when an invalid LayerZero endpoint ID is provided\n     */\n    error InvalidLayerZeroEid();\n\n    /**\n     * @notice Thrown when an invalid remote delay is provided\n     */\n    error InvalidRemoteDelay();\n\n    /**\n     * @notice Thrown when trying to set the same remote delay value\n     */\n    error RemoteDelayUnchanged();\n\n    /**\n     * @notice Thrown when trying to renounce ownership\n     */\n    error RenounceOwnershipNotAllowed();\n\n    /**\n     * @notice Thrown when trying to set the same config active status\n     */\n    error ConfigStatusUnchanged();\n\n    /**\n     * @notice Thrown when trying to set the same executor whitelist status\n     */\n    error ExecutorStatusUnchanged();\n\n    function setRiskParameterConfig(string calldata updateType, address riskSteward, uint256 debounce) external;\n\n    function setConfigActive(string calldata updateType, bool active) external;\n\n    function setWhitelistedExecutor(address executor, bool approved) external;\n\n    function setRemoteDelay(uint256 newRemoteDelay) external;\n\n    function executeUpdate(uint256 updateId) external;\n\n    function rejectUpdate(uint256 updateId) external;\n\n    function getExecutableUpdates(\n        string calldata updateType,\n        address comptroller\n    ) external view returns (uint256[] memory executableUpdates);\n\n    function getRiskParameterConfig(string calldata updateType) external view returns (RiskParamConfig memory);\n\n    function getRegisteredUpdate(\n        string calldata updateType,\n        address market\n    ) external view returns (DestinationUpdate memory);\n\n    function getLastExecutedAt(string calldata updateType, address market) external view returns (uint256);\n}\n"
    },
    "contracts/RiskSteward/Interfaces/IRiskOracle.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.25;\n\n/**\n * @notice Struct representing a risk parameter update published by the Risk Oracle\n * @param referenceId External reference ID, potentially linking to a document or off-chain data\n * @param updateId Unique identifier for this specific update\n * @param market Address of the market for which the parameter update applies\n * @param updateType Classification of the update type for validation purposes (human-readable)\n * @param updateTypeKey Keccak256 hash of updateType for efficient comparisons\n * @param newValue Encoded new value of the risk parameter, flexible for various data types\n * @param previousValue Previous value of the parameter for historical comparison\n * @param timestamp Block timestamp when the update was published\n * @param publisher Address of the account that published this update\n * @param poolId Pool identifier for eMode-style collateral configuration (0 for regular markets)\n * @param destLzEid LayerZero endpoint ID of the destination chain (0 for local execution)\n * @param additionalData Additional metadata or data associated with the update\n */\nstruct RiskParameterUpdate {\n    string referenceId;\n    uint256 updateId;\n    address market;\n    string updateType;\n    bytes32 updateTypeKey;\n    bytes newValue;\n    bytes previousValue;\n    uint256 timestamp;\n    address publisher;\n    uint96 poolId;\n    uint32 destLzEid;\n    bytes additionalData;\n}\n\n/**\n * @title IRiskOracle\n * @author Venus\n * @notice Interface for Risk Oracle contract that manages and publishes risk parameter updates\n */\ninterface IRiskOracle {\n    /// @notice Event emitted when a risk parameter update is published\n    event UpdatePublished(\n        string referenceId,\n        uint256 indexed updateId,\n        address indexed market,\n        string indexed updateType,\n        bytes newValue,\n        bytes previousValue,\n        uint256 timestamp,\n        address publisher,\n        bytes additionalData\n    );\n\n    /// @notice Event emitted when a new authorized sender is added\n    event AuthorizedSenderAdded(address indexed sender);\n\n    /// @notice Event emitted when an authorized sender is removed\n    event AuthorizedSenderRemoved(address indexed sender);\n\n    /// @notice Event emitted when a new update type is added\n    event UpdateTypeAdded(string indexed updateType);\n\n    /// @notice Event emitted when an update type's active status is changed\n    event UpdateTypeActiveStatusChanged(string indexed updateType, bool previousActive, bool active);\n\n    /// @notice Thrown when sender is not authorized\n    error SenderNotAuthorized();\n\n    /// @notice Thrown when sender is already authorized\n    error SenderAlreadyAuthorized();\n\n    /// @notice Thrown when update type string is invalid\n    error InvalidUpdateTypeString();\n\n    /// @notice Thrown when update type already exists\n    error UpdateTypeAlreadyExists();\n\n    /// @notice Thrown when update type doesn't exist\n    error UpdateTypeNotFound();\n\n    /// @notice Thrown when update type active status is already set to the desired value\n    error UpdateTypeStatusUnchanged();\n\n    /// @notice Thrown when update type is not active\n    error UpdateTypeNotActive();\n\n    /// @notice Thrown when no update is found\n    error NoUpdateFound();\n\n    /// @notice Thrown when update ID is invalid\n    error InvalidUpdateId();\n\n    /// @notice Thrown when array lengths don't match in bulk operations\n    error ArrayLengthMismatch();\n\n    /// @notice Thrown when trying to renounce ownership\n    error RenounceOwnershipNotAllowed();\n\n    /**\n     * @notice Returns the update type string at the given index in the allUpdateTypes array\n     * @param index The index in the allUpdateTypes array\n     * @return The update type string at the specified index\n     */\n    function allUpdateTypes(uint256 index) external view returns (string memory);\n\n    /**\n     * @notice Returns the total number of update types in the allUpdateTypes array\n     * @return The length of the allUpdateTypes array\n     */\n    function allUpdateTypesLength() external view returns (uint256);\n\n    /**\n     * @notice Returns all update types in the allUpdateTypes array\n     * @return An array of all update type strings\n     */\n    function getAllUpdateTypes() external view returns (string[] memory);\n\n    /**\n     * @notice Checks if a given update type is currently active\n     * @param updateType The update type string to check\n     * @return True if the update type is active, false otherwise\n     */\n    function getActiveUpdateTypes(string memory updateType) external view returns (bool);\n\n    /**\n     * @notice Checks if a given update type is currently active\n     * @param updateTypeKey The keccak256 hash of the update type string\n     * @return True if the update type key is active, false otherwise\n     */\n    function activeUpdateTypes(bytes32 updateTypeKey) external view returns (bool);\n\n    /**\n     * @notice Checks if an address is authorized to publish updates\n     * @param sender The address to check for authorization\n     * @return True if the address is authorized, false otherwise\n     */\n    function authorizedSenders(address sender) external view returns (bool);\n\n    /**\n     * @notice Gets the latest update ID for a specific market and update type combination\n     * @param updateTypeKey The keccak256 hash of the update type string\n     * @param market The market address\n     * @return The latest update ID for the given market and update type key, or 0 if none exists\n     */\n    function latestUpdateIdByMarketAndType(bytes32 updateTypeKey, address market) external view returns (uint256);\n\n    /**\n     * @notice Returns the total number of updates that have been published\n     * @return The current update counter value\n     */\n    function updateCounter() external view returns (uint256);\n\n    /**\n     * @notice Fetches the most recent update for a specific parameter type in a specific market\n     * @param updateType The update type identifier\n     * @param market The market address\n     * @return The most recent RiskParameterUpdate for the specified parameter and market\n     * @custom:error NoUpdateFound Thrown if no update exists for the specified parameter and market\n     */\n    function getLatestUpdateByTypeAndMarket(\n        string memory updateType,\n        address market\n    ) external view returns (RiskParameterUpdate memory);\n\n    /**\n     * @notice Gets the latest update ID for a specific market and update type (string) combination\n     * @param updateType The update type identifier\n     * @param market The market address\n     * @return The latest update ID for the given market and update type, or 0 if none exists\n     */\n    function getLatestUpdateIdByTypeAndMarket(string memory updateType, address market) external view returns (uint256);\n\n    /**\n     * @notice Fetches the update for a provided update ID\n     * @param updateId The unique update ID\n     * @return The RiskParameterUpdate struct for the specified update ID\n     * @custom:error InvalidUpdateId Thrown if updateId is 0 or greater than updateCounter\n     */\n    function getUpdateById(uint256 updateId) external view returns (RiskParameterUpdate memory);\n\n    /**\n     * @notice Adds a new address to the list of authorized senders who can publish updates\n     * @param sender Address to be authorized\n     * @custom:error ZeroAddressNotAllowed Thrown if sender is the zero address\n     * @custom:error SenderAlreadyAuthorized Thrown if sender is already authorized\n     * @custom:error Unauthorized Thrown if caller is not allowed by AccessControlManager\n     * @custom:event AuthorizedSenderAdded Emitted when sender is successfully added\n     */\n    function addAuthorizedSender(address sender) external;\n\n    /**\n     * @notice Removes an address from the list of authorized senders\n     * @param sender Address to be removed from authorization\n     * @custom:error SenderNotAuthorized Thrown if sender is not currently authorized\n     * @custom:error Unauthorized Thrown if caller is not allowed by AccessControlManager\n     * @custom:event AuthorizedSenderRemoved Emitted when sender is successfully removed\n     */\n    function removeAuthorizedSender(address sender) external;\n\n    /**\n     * @notice Adds a new update type to the list of authorized update types\n     * @param newUpdateType New update type string to allow (must be non-empty and <= 64 characters)\n     * @custom:error InvalidUpdateTypeString Thrown if update type string is empty or exceeds 64 characters\n     * @custom:error UpdateTypeAlreadyExists Thrown if update type already exists\n     * @custom:error Unauthorized Thrown if caller is not allowed by AccessControlManager\n     * @custom:event UpdateTypeAdded Emitted when update type is successfully added\n     */\n    function addUpdateType(string memory newUpdateType) external;\n\n    /**\n     * @notice Sets the active status of an existing update type\n     * @param updateType The update type to set active status for\n     * @param active True to activate the update type, false to deactivate it\n     * @custom:error UpdateTypeNotFound Thrown if update type doesn't exist\n     * @custom:error UpdateTypeStatusUnchanged Thrown if status is already set to the desired value\n     * @custom:error Unauthorized Thrown if caller is not allowed by AccessControlManager\n     * @custom:event UpdateTypeActiveStatusChanged Emitted when status is successfully changed\n     */\n    function setUpdateTypeActive(string memory updateType, bool active) external;\n\n    /**\n     * @notice Publishes a new risk parameter update.\n     * @param referenceId An external reference ID associated with the update\n     * @param newValue The new value of the risk parameter being updated (encoded as bytes)\n     * @param updateType Type of update performed, must be an active update type\n     * @param market Address of the market for which the parameter update applies\n     * @param poolId Pool identifier for eMode-style collateral configuration (0 for regular markets)\n     * @param dstEid Destination endpoint ID for cross-chain routing\n     * @param additionalData Additional data or metadata for the update\n     * @custom:error SenderNotAuthorized Thrown if caller is not an authorized sender\n     * @custom:error UpdateTypeNotActive Thrown if update type is not active\n     * @custom:error ZeroAddressNotAllowed Thrown if market is the zero address\n     * @custom:event UpdatePublished Emitted when the update is successfully published\n     */\n    function publishRiskParameterUpdate(\n        string memory referenceId,\n        bytes memory newValue,\n        string memory updateType,\n        address market,\n        uint96 poolId,\n        uint32 dstEid,\n        bytes memory additionalData\n    ) external;\n\n    /**\n     * @notice Publishes multiple risk parameter updates in a single transaction.\n     * @param referenceIds Array of external reference IDs, one for each update\n     * @param newValues Array of new values for each update (encoded as bytes)\n     * @param updateTypes Array of update types, all must be active update types\n     * @param markets Array of market addresses for each update\n     * @param poolIds Array of pool identifiers for eMode-style collateral configuration (0 for regular markets)\n     * @param dstEid Array of destination endpoint IDs for cross-chain routing\n     * @param additionalData Array of additional data for each update\n     * @custom:error SenderNotAuthorized Thrown if caller is not an authorized sender\n     * @custom:error ArrayLengthMismatch Thrown if all arrays don't have the same length\n     * @custom:error UpdateTypeNotActive Thrown if any update type is not active\n     * @custom:error ZeroAddressNotAllowed Thrown if any market is the zero address\n     * @custom:event UpdatePublished Emitted for each successfully published update\n     */\n    function publishBulkRiskParameterUpdates(\n        string[] memory referenceIds,\n        bytes[] memory newValues,\n        string[] memory updateTypes,\n        address[] memory markets,\n        uint96[] memory poolIds,\n        uint32[] memory dstEid,\n        bytes[] memory additionalData\n    ) external;\n}\n"
    },
    "contracts/RiskSteward/Interfaces/IRiskSteward.sol": {
      "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { RiskParameterUpdate } from \"./IRiskOracle.sol\";\nimport { IRiskStewardReceiver } from \"./IRiskStewardReceiver.sol\";\n\n/**\n * @title IRiskSteward\n * @author Venus\n * @notice Interface for risk stewards that validate and apply risk parameter updates\n */\ninterface IRiskSteward {\n    /**\n     * @notice Returns the `IRiskStewardReceiver` associated with this steward.\n     * @return The risk steward receiver contract\n     */\n    function RISK_STEWARD_RECEIVER() external view returns (IRiskStewardReceiver);\n\n    /**\n     * @notice Checks whether an update is safe for direct execution (no timelock required).\n     * @param update The risk parameter update to evaluate\n     * @return True if update is safe for direct execution, false if timelock is required\n     */\n    function isSafeForDirectExecution(RiskParameterUpdate calldata update) external view returns (bool);\n\n    /**\n     * @notice Applies a validated risk parameter update.\n     * @param update The risk parameter update to apply\n     */\n    function applyUpdate(RiskParameterUpdate calldata update) external;\n}\n"
    },
    "contracts/RiskSteward/Interfaces/IRiskStewardReceiver.sol": {
      "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\ninterface IRiskStewardReceiver {\n    /**\n     * @notice Status of an update\n     */\n    enum UpdateStatus {\n        None,\n        Pending,\n        Executed,\n        Rejected,\n        Expired,\n        SENT_TO_DESTINATION\n    }\n\n    /**\n     * @notice Configuration for a risk parameter update type\n     * @param active Whether this update type configuration is currently active\n     * @param debounce Minimum delay between consecutive update executions for the same (updateType, market) pair\n     * @param timelock Period that must pass after registration before an update can be executed\n     * @param riskSteward Address of the risk steward contract responsible for processing this update type\n     */\n    struct RiskParamConfig {\n        bool active;\n        uint256 debounce;\n        uint256 timelock;\n        address riskSteward;\n    }\n\n    /**\n     * @notice Registered update structure with timelock and execution information\n     * @param updateId Update ID from the Risk Oracle\n     * @param unlockTime Timestamp when this update can be executed (calculated as registration time + timelock)\n     * @param status Current status of the update (Pending, Executed, Rejected, Expired, etc.)\n     * @param executor Address of the executor who executed this update (address(0) if not executed yet)\n     * @param executedAt Timestamp when this update was executed (0 if not executed yet)\n     */\n    struct RegisteredUpdate {\n        uint256 updateId;\n        uint256 unlockTime;\n        UpdateStatus status;\n        address executor;\n        uint256 executedAt;\n    }\n\n    /**\n     * @notice Event emitted when a risk parameter config is set\n     */\n    event RiskParameterConfigUpdated(\n        bytes32 indexed updateTypeHash,\n        string updateType,\n        address indexed previousRiskSteward,\n        address indexed riskSteward,\n        uint256 previousDebounce,\n        uint256 debounce,\n        uint256 previousTimelock,\n        uint256 timelock,\n        bool previousActive,\n        bool active\n    );\n\n    /**\n     * @notice Event emitted when a risk parameter config active status is set\n     */\n    event ConfigActiveUpdated(bytes32 indexed updateTypeHash, string updateType, bool previousActive, bool active);\n\n    /**\n     * @notice Event emitted when an update is successfully executed\n     */\n    event UpdateExecuted(uint256 indexed updateId);\n\n    /**\n     * @notice Event emitted when an update is rejected\n     */\n    event UpdateRejected(uint256 indexed updateId);\n\n    /**\n     * @notice Event emitted when an update is marked as expired\n     */\n    event UpdateExpired(uint256 indexed updateId);\n\n    /**\n     * @notice Event emitted when an executor status is set\n     */\n    event ExecutorStatusUpdated(address indexed executor, bool previousApproved, bool approved);\n\n    /**\n     * @notice Event emitted when an update is registered\n     */\n    event UpdateRegistered(uint256 indexed updateId, uint256 unlockTime, string updateType, address indexed market);\n\n    /**\n     * @notice Event emitted when an update is sent to a destination chain\n     */\n    event UpdateSentToDestination(\n        uint256 updateId,\n        uint32 indexed destLzEid,\n        string indexed updateType,\n        address indexed market\n    );\n\n    /**\n     * @notice Event emitted when an update is resent to a destination chain\n     */\n    event UpdateResentToDestination(\n        uint256 updateId,\n        uint32 indexed destLzEid,\n        string indexed updateType,\n        address indexed market\n    );\n\n    /**\n     * @notice Emitted when leftover native tokens are swept by owner\n     */\n    event SweepNative(address indexed receiver, uint256 amount);\n\n    /**\n     * @notice Event emitted when the pause status changes\n     * @param previousPaused Previous pause state\n     * @param paused Current pause state\n     */\n    event PauseStatusUpdated(bool previousPaused, bool paused);\n\n    /**\n     * @custom:error TransferFailed\n     */\n    error TransferFailed();\n\n    /**\n     * @notice Thrown if a submitted update is not active and therefore cannot be processed\n     */\n    error ConfigNotActive();\n\n    /**\n     * @notice Thrown when an update was not applied within the required time frame\n     */\n    error UpdateIsExpired();\n\n    /**\n     * @notice Thrown when an update has already been processed\n     */\n    error UpdateAlreadyResolved();\n\n    /**\n     * @notice Thrown when the debounce period hasn't passed for applying an update to a specific market / update type\n     */\n    error UpdateTooFrequent();\n\n    /**\n     * @notice Thrown when an update type that is not supported is operated on\n     */\n    error UnsupportedUpdateType();\n\n    /**\n     * @notice Thrown when an empty update type string is provided\n     */\n    error InvalidUpdateType();\n\n    /**\n     * @notice Thrown when a debounce value of 0 is set\n     */\n    error InvalidDebounce();\n\n    /**\n     * @notice Thrown when a timelock value is greater than or equal to the expiration time\n     */\n    error InvalidTimelock();\n\n    /**\n     * @notice Thrown when update unlock time has not been reached\n     */\n    error UpdateNotUnlocked();\n\n    /**\n     * @notice Thrown when trying to resolve an update that doesn't exist\n     */\n    error UpdateNotFound();\n\n    /**\n     * @notice Thrown when an address is not an executor\n     */\n    error NotAnExecutor();\n\n    /**\n     * @notice Thrown when there is a non-expired pending update of the same type for the market\n     */\n    error RegisteredUpdateTypeExist(uint256);\n\n    /**\n     * @notice Thrown when trying to resend an update that is not in SENT_TO_DESTINATION status\n     */\n    error InvalidUpdateToResend();\n\n    /**\n     * @notice Thrown when trying to execute an update that was never registered\n     */\n    error InvalidRegisteredUpdate();\n\n    /**\n     * @notice Thrown when attempting to call lzSend from an address other than this contract\n     */\n    error InvalidLzSendCaller();\n\n    /**\n     * @notice Thrown when trying to renounce ownership\n     */\n    error RenounceOwnershipNotAllowed();\n\n    /**\n     * @notice Thrown when processUpdate is called while the contract is paused\n     */\n    error PausedError();\n\n    /**\n     * @notice Thrown when an invalid LayerZero endpoint ID is provided\n     */\n    error InvalidLayerZeroEid();\n\n    /**\n     * @notice Thrown when trying to set the same pause status\n     */\n    error PauseStatusUnchanged();\n\n    /**\n     * @notice Thrown when trying to set the same config active status\n     */\n    error ConfigStatusUnchanged();\n\n    /**\n     * @notice Thrown when trying to set the same executor whitelist status\n     */\n    error ExecutorStatusUnchanged();\n\n    /**\n     * @notice Thrown when an update will expire before its timelock unlocks\n     */\n    error UpdateWillExpireBeforeUnlock();\n\n    function getRiskParameterConfig(string calldata updateType) external view returns (RiskParamConfig memory);\n\n    function getLastProcessedUpdate(string calldata updateType, address market) external view returns (uint256);\n\n    function getLastRegisteredUpdate(string calldata updateType, address market) external view returns (uint256);\n\n    function setRiskParameterConfig(\n        string calldata updateType,\n        address riskSteward,\n        uint256 debounce,\n        uint256 timelock\n    ) external;\n\n    function setConfigActive(string calldata updateType, bool active) external;\n\n    function setWhitelistedExecutor(address executor, bool approved) external;\n\n    function processUpdate(uint256 updateId) external;\n\n    function executeRegisteredUpdate(uint256 updateId) external;\n\n    function rejectUpdate(uint256 updateId) external;\n\n    function resendRemoteUpdate(uint256 updateId, bytes calldata options) external payable;\n\n    function getExecutableUpdates(\n        string calldata updateType,\n        address comptroller\n    ) external view returns (uint256[] memory executableUpdates);\n\n    function isUpdateExecutable(uint256 updateId) external view returns (bool);\n}\n"
    },
    "contracts/RiskSteward/IRMRiskSteward.sol": {
      "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { RiskParameterUpdate } from \"./Interfaces/IRiskOracle.sol\";\nimport { ICorePoolVToken } from \"../interfaces/ICorePoolVToken.sol\";\nimport { IIsolatedPoolVToken } from \"../interfaces/IIsolatedPoolVToken.sol\";\nimport { InterestRateModel } from \"@venusprotocol/isolated-pools/contracts/InterestRateModel.sol\";\nimport { InterestRateModelV8 } from \"@venusprotocol/venus-protocol/contracts/InterestRateModels/InterestRateModelV8.sol\";\nimport { ICorePoolComptroller } from \"../interfaces/ICorePoolComptroller.sol\";\nimport { IRiskStewardReceiver } from \"./Interfaces/IRiskStewardReceiver.sol\";\nimport { BaseRiskSteward } from \"./BaseRiskSteward.sol\";\nimport { ensureNonzeroAddress } from \"@venusprotocol/solidity-utilities/contracts/validators.sol\";\n\n/**\n * @title IRMRiskSteward\n * @author Venus\n * @notice Contract that can update interest rate models updates received from RiskStewardReceiver.\n * @custom:security-contact https://github.com/VenusProtocol/governance-contracts#discussion\n */\ncontract IRMRiskSteward is BaseRiskSteward {\n    /**\n     * @notice The update type for interest rate model\n     */\n    string public constant INTEREST_RATE_MODEL = \"interestRateModel\";\n\n    /**\n     * @notice The update type key for interest rate model (keccak256 hash of INTEREST_RATE_MODEL)\n     */\n    bytes32 public constant INTEREST_RATE_MODEL_KEY = keccak256(bytes(INTEREST_RATE_MODEL));\n\n    /**\n     * @notice Address of the BNB Core Pool Comptroller.\n     * @dev This comptroller is specific to the BNB Core Pool, which uses a different ABI\n     *      than isolated pools. It is used solely to detect and handle BNB Core Pool\n     *      markets, and would not be used for remote-chain (isolated pool) deployments.\n     */\n    ICorePoolComptroller public immutable CORE_POOL_COMPTROLLER;\n\n    /**\n     * @notice Address of the RiskStewardReceiver used to validate incoming updates\n     */\n    IRiskStewardReceiver public immutable RISK_STEWARD_RECEIVER;\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n\n    /**\n     * @notice Emitted when an interest rate model is updated\n     */\n    event InterestRateModelUpdated(\n        uint256 indexed updateId,\n        address indexed market,\n        address indexed newInterestRateModel\n    );\n\n    /**\n     * @notice Thrown when an update type that is not supported is operated on\n     */\n    error UnsupportedUpdateType();\n\n    /**\n     * @notice Thrown when attempting to apply a redundant IRM value (no-op change).\n     */\n    error RedundantValue();\n\n    /**\n     * @notice Thrown when the update is not coming from the RiskStewardReceiver\n     */\n    error OnlyRiskStewardReceiver();\n\n    /**\n     * @notice Thrown when the address length is invalid\n     */\n    error InvalidAddressLength();\n\n    /**\n     * @notice Thrown when Core Pool VToken._setInterestRateModel fails.\n     */\n    error SetInterestRateModelFailed(uint256 errorCode);\n\n    /**\n     * @notice Sets the immutable CORE_POOL_COMPTROLLER and RISK_STEWARD_RECEIVER addresses and disables initializers\n     * @param corePoolComptroller_ The address of the Core Pool Comptroller\n     * @param riskStewardReceiver_ The address of the RiskStewardReceiver\n     * @custom:error Throws ZeroAddressNotAllowed if any of the addresses are zero\n     * @custom:oz-upgrades-unsafe-allow constructor\n     */\n    constructor(address corePoolComptroller_, address riskStewardReceiver_) {\n        ensureNonzeroAddress(riskStewardReceiver_);\n        CORE_POOL_COMPTROLLER = ICorePoolComptroller(corePoolComptroller_);\n        RISK_STEWARD_RECEIVER = IRiskStewardReceiver(riskStewardReceiver_);\n        _disableInitializers();\n    }\n\n    /**\n     * @notice Initializes the contract as ownable and access controlled.\n     * @param accessControlManager_ The address of the access control manager\n     */\n    function initialize(address accessControlManager_) external initializer {\n        __AccessControlled_init(accessControlManager_);\n    }\n\n    /**\n     * @notice Applies an interest rate model update from the RiskStewardReceiver.\n     * Directly updates the market interest rate model on the vToken.\n     * @param update RiskParameterUpdate update to apply\n     * @custom:error Throws OnlyRiskStewardReceiver if the sender is not the RiskStewardReceiver\n     * @custom:error Throws UnsupportedUpdateType if the update type is not supported\n     * @custom:event Emits InterestRateModelUpdated with the updateId, market and new IRM address\n     * @custom:access Only callable by the RiskStewardReceiver\n     */\n    function applyUpdate(RiskParameterUpdate calldata update) external {\n        if (msg.sender != address(RISK_STEWARD_RECEIVER)) {\n            revert OnlyRiskStewardReceiver();\n        }\n\n        if (update.updateTypeKey == INTEREST_RATE_MODEL_KEY) {\n            address newIRM = _decodeAbiEncodedAddress(update.newValue);\n            _updateIRM(update.updateId, update.market, newIRM);\n        } else {\n            revert UnsupportedUpdateType();\n        }\n    }\n\n    /**\n     * @notice Checks if an update is safe for direct execution (no timelock required)\n     * @param update The update to check\n     * @return True if update is safe for direct execution, false if timelock is required\n     * @custom:error Throws UnsupportedUpdateType if the update type is not supported\n     * @custom:error Throws RedundantValue if the new IRM address is equal to the current IRM address\n     * @dev For IRM updates, always returns false as we cannot compare IRM values\n     */\n    function isSafeForDirectExecution(RiskParameterUpdate calldata update) external view returns (bool) {\n        if (update.updateTypeKey != INTEREST_RATE_MODEL_KEY) {\n            revert UnsupportedUpdateType();\n        }\n\n        address newIRM = _decodeAbiEncodedAddress(update.newValue);\n        address currentIRM = address(ICorePoolVToken(update.market).interestRateModel());\n\n        // Revert on redundant updates\n        if (newIRM == currentIRM) {\n            revert RedundantValue();\n        }\n\n        // Always require timelock (not safe for direct execution)\n        return false;\n    }\n\n    /**\n     * @notice Updates the interest rate model for the given market.\n     * @param updateId The update ID from the Risk Oracle\n     * @param market The market to update the interest rate model for\n     * @param newIRM The new interest rate model address\n     * @custom:error Throws SetInterestRateModelFailed if the core pool vToken call to _setInterestRateModel returns a non-zero error code\n     * @custom:event Emits InterestRateModelUpdated with the updateId, market and new IRM address\n     */\n    function _updateIRM(uint256 updateId, address market, address newIRM) internal {\n        address comptroller = ICorePoolVToken(market).comptroller();\n\n        if (comptroller == address(CORE_POOL_COMPTROLLER)) {\n            uint256 errorCode = ICorePoolVToken(market)._setInterestRateModel(InterestRateModelV8(newIRM));\n            if (errorCode != 0) revert SetInterestRateModelFailed(errorCode);\n        } else {\n            IIsolatedPoolVToken(market).setInterestRateModel(InterestRateModel(newIRM));\n        }\n\n        emit InterestRateModelUpdated(updateId, market, newIRM);\n    }\n\n    /**\n     * @notice Decodes ABI-encoded bytes into an address.\n     * @dev Expects exactly 32 bytes as produced by abi.encode(address).\n     * @param data ABI-encoded address payload (32 bytes)\n     * @return The decoded address\n     * @custom:error Throws InvalidAddressLength if data length is not 32 bytes\n     */\n    function _decodeAbiEncodedAddress(bytes memory data) internal pure returns (address) {\n        if (data.length != 32) revert InvalidAddressLength();\n        return abi.decode(data, (address));\n    }\n}\n"
    },
    "contracts/RiskSteward/MarketCapsRiskSteward.sol": {
      "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { RiskParameterUpdate } from \"./Interfaces/IRiskOracle.sol\";\nimport { ICorePoolVToken } from \"../interfaces/ICorePoolVToken.sol\";\nimport { ICorePoolComptroller } from \"../interfaces/ICorePoolComptroller.sol\";\nimport { IRiskStewardReceiver } from \"./Interfaces/IRiskStewardReceiver.sol\";\nimport { BaseRiskSteward } from \"./BaseRiskSteward.sol\";\nimport { ensureNonzeroAddress } from \"@venusprotocol/solidity-utilities/contracts/validators.sol\";\n\n/**\n * @title MarketCapsRiskSteward\n * @author Venus\n * @notice Contract that can update supply and borrow caps updates received from RiskStewardReceiver.\n * @custom:security-contact https://github.com/VenusProtocol/governance-contracts#discussion\n */\ncontract MarketCapsRiskSteward is BaseRiskSteward {\n    /**\n     * @notice The update type for supply caps\n     */\n    string public constant SUPPLY_CAP = \"supplyCap\";\n\n    /**\n     * @notice The update type key for supply caps (keccak256 hash of SUPPLY_CAP)\n     */\n    bytes32 public constant SUPPLY_CAP_KEY = keccak256(bytes(SUPPLY_CAP));\n\n    /**\n     * @notice The update type for borrow caps\n     */\n    string public constant BORROW_CAP = \"borrowCap\";\n\n    /**\n     * @notice The update type key for borrow caps (keccak256 hash of BORROW_CAP)\n     */\n    bytes32 public constant BORROW_CAP_KEY = keccak256(bytes(BORROW_CAP));\n\n    /**\n     * @notice Address of the RiskStewardReceiver used to validate incoming updates\n     */\n    IRiskStewardReceiver public immutable RISK_STEWARD_RECEIVER;\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n\n    /**\n     * @notice Emitted when a supply cap is updated\n     */\n    event SupplyCapUpdated(uint256 indexed updateId, address indexed market, uint256 newSupplyCap);\n\n    /**\n     * @notice Emitted when a borrow cap is updated\n     */\n    event BorrowCapUpdated(uint256 indexed updateId, address indexed market, uint256 newBorrowCap);\n\n    /**\n     * @notice Emitted when the safe delta bps is updated\n     */\n    event SafeDeltaBpsUpdated(uint256 oldSafeDeltaBps, uint256 newSafeDeltaBps);\n\n    /**\n     * @notice Thrown when a safeDeltaBps value is greater than MAX_BPS\n     */\n    error InvalidSafeDeltaBps();\n\n    /**\n     * @notice Thrown when an update type that is not supported is operated on\n     */\n    error UnsupportedUpdateType();\n\n    /**\n     * @notice Thrown when the update is not coming from the RiskStewardReceiver\n     */\n    error OnlyRiskStewardReceiver();\n\n    /**\n     * @notice Thrown when the uint256 data length is invalid\n     */\n    error InvalidUintLength();\n\n    /**\n     * @notice Thrown when attempting to apply a redundant value (no-op change).\n     */\n    error RedundantValue();\n\n    /**\n     * @notice Sets the immutable RiskStewardReceiver address and disables initializers\n     * @param riskStewardReceiver_ The address of the RiskStewardReceiver\n     * @custom:error Throws ZeroAddressNotAllowed if the RiskStewardReceiver address is zero\n     * @custom:oz-upgrades-unsafe-allow constructor\n     */\n    constructor(address riskStewardReceiver_) {\n        ensureNonzeroAddress(riskStewardReceiver_);\n        RISK_STEWARD_RECEIVER = IRiskStewardReceiver(riskStewardReceiver_);\n        _disableInitializers();\n    }\n\n    /**\n     * @notice Initializes the contract as ownable and access controlled.\n     * @param accessControlManager_ The address of the access control manager\n     */\n    function initialize(address accessControlManager_) external initializer {\n        __AccessControlled_init(accessControlManager_);\n    }\n\n    /**\n     * @notice Sets the safe delta bps\n     * @param safeDeltaBps_ The new safe delta bps\n     * @custom:access Controlled by AccessControlManager\n     * @custom:event Emits SafeDeltaBpsUpdated with the old and new safe delta bps\n     * @custom:error Throws InvalidSafeDeltaBps if the safe delta bps is greater than MAX_BPS\n     * @custom:error Throws RedundantValue if the new safe delta bps is equal to the current value\n     */\n    function setSafeDeltaBps(uint256 safeDeltaBps_) external {\n        _checkAccessAllowed(\"setSafeDeltaBps(uint256)\");\n        if (safeDeltaBps_ > MAX_BPS) {\n            revert InvalidSafeDeltaBps();\n        }\n        uint256 oldSafeDeltaBps = safeDeltaBps;\n        if (safeDeltaBps_ == oldSafeDeltaBps) {\n            revert RedundantValue();\n        }\n        safeDeltaBps = safeDeltaBps_;\n        emit SafeDeltaBpsUpdated(oldSafeDeltaBps, safeDeltaBps_);\n    }\n\n    /**\n     * @notice Checks if an update is safe for direct execution (no timelock required)\n     * @param update The update to check\n     * @return True if update is safe for direct execution, false if timelock is required\n     * @custom:error Throws UnsupportedUpdateType if the update type is not supported\n     * @custom:error Throws RedundantValue if the new cap value is equal to the current cap value\n     */\n    function isSafeForDirectExecution(RiskParameterUpdate calldata update) external view returns (bool) {\n        uint256 newValue = _decodeAbiEncodedUint256(update.newValue);\n        // Use the core pool comptroller interface here because the getter used below has the same signature for both core and isolated pools.\n        ICorePoolComptroller comptroller = ICorePoolComptroller(ICorePoolVToken(update.market).comptroller());\n        uint256 currentValue;\n\n        if (update.updateTypeKey == SUPPLY_CAP_KEY) {\n            currentValue = comptroller.supplyCaps(update.market);\n        } else if (update.updateTypeKey == BORROW_CAP_KEY) {\n            currentValue = comptroller.borrowCaps(update.market);\n        } else {\n            revert UnsupportedUpdateType();\n        }\n\n        // Revert on redundant updates\n        if (newValue == currentValue) {\n            revert RedundantValue();\n        }\n\n        // If current value is 0, always require timelock (not safe for direct execution)\n        if (currentValue == 0) {\n            return false;\n        }\n\n        // Return true if difference is within safe delta (safe for direct execution)\n        return _isWithinSafeDelta(newValue, currentValue);\n    }\n\n    /**\n     * @notice Applies a market cap update from the RiskStewardReceiver.\n     * Directly updates the market supply or borrow cap on the market's comptroller.\n     * @custom:access Only callable by the RiskStewardReceiver\n     * @param update RiskParameterUpdate update to apply\n     * @custom:event Emits SupplyCapUpdated or BorrowCapUpdated depending on the update with the updateId, market and new cap\n     * @custom:error Throws OnlyRiskStewardReceiver if the sender is not the RiskStewardReceiver\n     * @custom:error Throws UnsupportedUpdateType if the update type is not supported\n     */\n    function applyUpdate(RiskParameterUpdate calldata update) external {\n        if (msg.sender != address(RISK_STEWARD_RECEIVER)) {\n            revert OnlyRiskStewardReceiver();\n        }\n        uint256 newValue = _decodeAbiEncodedUint256(update.newValue);\n\n        if (update.updateTypeKey == SUPPLY_CAP_KEY) {\n            _updateSupplyCaps(update.updateId, update.market, newValue);\n        } else if (update.updateTypeKey == BORROW_CAP_KEY) {\n            _updateBorrowCaps(update.updateId, update.market, newValue);\n        } else {\n            revert UnsupportedUpdateType();\n        }\n    }\n\n    /**\n     * @notice Updates the supply cap for the given market.\n     * @param updateId The update ID from the Risk Oracle\n     * @param market The market to update the supply cap for\n     * @param newValue The new supply cap value\n     * @custom:event Emits SupplyCapUpdated with the updateId, market and new supply cap\n     */\n    function _updateSupplyCaps(uint256 updateId, address market, uint256 newValue) internal {\n        address comptroller = ICorePoolVToken(market).comptroller();\n        address[] memory newSupplyCapMarkets = new address[](1);\n        newSupplyCapMarkets[0] = market;\n        uint256[] memory newSupplyCaps = new uint256[](1);\n        newSupplyCaps[0] = newValue;\n\n        // Core and isolated pools share the same `setMarketSupplyCaps` signature.\n        ICorePoolComptroller(comptroller).setMarketSupplyCaps(newSupplyCapMarkets, newSupplyCaps);\n        emit SupplyCapUpdated(updateId, market, newSupplyCaps[0]);\n    }\n\n    /**\n     * @notice Updates the borrow cap for the given market.\n     * @param updateId The update ID from the Risk Oracle\n     * @param market The market to update the borrow cap for\n     * @param newValue The new borrow cap value\n     * @custom:event Emits BorrowCapUpdated with the updateId, market and new borrow cap\n     */\n    function _updateBorrowCaps(uint256 updateId, address market, uint256 newValue) internal {\n        address comptroller = ICorePoolVToken(market).comptroller();\n        address[] memory newBorrowCapMarkets = new address[](1);\n        newBorrowCapMarkets[0] = market;\n        uint256[] memory newBorrowCaps = new uint256[](1);\n        newBorrowCaps[0] = newValue;\n\n        //Core and isolated pools share the same `setMarketBorrowCaps` signature,\n        ICorePoolComptroller(comptroller).setMarketBorrowCaps(newBorrowCapMarkets, newBorrowCaps);\n        emit BorrowCapUpdated(updateId, market, newBorrowCaps[0]);\n    }\n\n    /**\n     * @notice Decodes ABI-encoded bytes into a uint256.\n     * @dev Expects exactly 32 bytes as produced by abi.encode(uint256).\n     * @param data ABI-encoded uint256 payload (32 bytes)\n     * @return value Decoded uint256\n     * @custom:error Throws InvalidUintLength if data length is not 32 bytes\n     */\n    function _decodeAbiEncodedUint256(bytes memory data) internal pure returns (uint256 value) {\n        if (data.length != 32) {\n            revert InvalidUintLength();\n        }\n        value = abi.decode(data, (uint256));\n    }\n}\n"
    },
    "contracts/RiskSteward/RiskOracle.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.25;\n\nimport { AccessControlledV8 } from \"../Governance/AccessControlledV8.sol\";\nimport { ensureNonzeroAddress } from \"@venusprotocol/solidity-utilities/contracts/validators.sol\";\nimport { IRiskOracle, RiskParameterUpdate } from \"./Interfaces/IRiskOracle.sol\";\n\n/**\n * @title Risk Oracle\n * @author Venus\n * @notice Contract for managing and publishing risk parameter updates for Risk-Steward Updates\n */\ncontract RiskOracle is IRiskOracle, AccessControlledV8 {\n    /// @notice Counter to keep track of the total number of updates\n    uint256 public updateCounter;\n\n    /// @notice Array to store all update types\n    string[] public allUpdateTypes;\n\n    /// @notice Whitelist of valid update type identifiers, keyed by updateType hash\n    mapping(bytes32 => bool) public activeUpdateTypes;\n\n    /// @notice Mapping from unique update ID to the update details\n    mapping(uint256 => RiskParameterUpdate) public updatesById;\n\n    /// @notice Authorized accounts capable of proposing updates\n    mapping(address => bool) public authorizedSenders;\n\n    /// @notice Mapping to store the latest update ID for each combination of update type key and market\n    mapping(bytes32 updateTypeKey => mapping(address market => uint256 updateId)) public latestUpdateIdByMarketAndType;\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[44] private __gap;\n\n    /**\n     * @notice Modifier that restricts function access to authorized senders only\n     */\n    modifier onlyAuthorized() {\n        if (!authorizedSenders[msg.sender]) {\n            revert SenderNotAuthorized();\n        }\n        _;\n    }\n\n    /**\n     * @notice Disables initializers\n     * @custom:oz-upgrades-unsafe-allow constructor\n     */\n    constructor() {\n        _disableInitializers();\n    }\n\n    /**\n     * @notice Initializes the contract with access control manager\n     * @param accessControlManager_ Address of the access control manager\n     * @custom:error Reverts with \"invalid acess control manager address\" if accessControlManager_ is zero address\n     */\n    function initialize(address accessControlManager_) external initializer {\n        __AccessControlled_init(accessControlManager_);\n    }\n\n    /**\n     * @notice Adds a new sender to the list of addresses authorized to perform updates\n     * @param sender Address to be authorized\n     * @custom:access Controlled by AccessControlManager\n     * @custom:error Throws ZeroAddressNotAllowed if sender is zero address\n     * @custom:error Throws SenderAlreadyAuthorized if sender is already authorized\n     * @custom:error Throws Unauthorized if caller is not allowed by AccessControlManager\n     * @custom:event Emits AuthorizedSenderAdded when sender is successfully added\n     */\n    function addAuthorizedSender(address sender) external {\n        _checkAccessAllowed(\"addAuthorizedSender(address)\");\n        ensureNonzeroAddress(sender);\n        if (authorizedSenders[sender]) {\n            revert SenderAlreadyAuthorized();\n        }\n        authorizedSenders[sender] = true;\n        emit AuthorizedSenderAdded(sender);\n    }\n\n    /**\n     * @notice Removes an address from the list of authorized senders\n     * @param sender Address to be unauthorized\n     * @custom:access Controlled by AccessControlManager\n     * @custom:error Throws SenderNotAuthorized if sender is not currently authorized\n     * @custom:error Throws Unauthorized if caller is not allowed by AccessControlManager\n     * @custom:event Emits AuthorizedSenderRemoved when sender is successfully removed\n     */\n    function removeAuthorizedSender(address sender) external {\n        _checkAccessAllowed(\"removeAuthorizedSender(address)\");\n        if (!authorizedSenders[sender]) {\n            revert SenderNotAuthorized();\n        }\n        delete authorizedSenders[sender];\n        emit AuthorizedSenderRemoved(sender);\n    }\n\n    /**\n     * @notice Adds a new type of update to the list of authorized update types\n     * @param newUpdateType New type of update to allow\n     * @custom:access Controlled by AccessControlManager\n     * @custom:error Throws InvalidUpdateTypeString if update type string is empty or exceeds 64 characters\n     * @custom:error Throws UpdateTypeAlreadyExists if update type already exists\n     * @custom:error Throws Unauthorized if caller is not allowed by AccessControlManager\n     * @custom:event Emits UpdateTypeAdded when update type is successfully added\n     */\n    function addUpdateType(string memory newUpdateType) external {\n        _checkAccessAllowed(\"addUpdateType(string)\");\n        if (bytes(newUpdateType).length == 0 || bytes(newUpdateType).length > 64) {\n            revert InvalidUpdateTypeString();\n        }\n        bytes32 key = keccak256(bytes(newUpdateType));\n\n        if (_updateTypeExists(key)) {\n            revert UpdateTypeAlreadyExists();\n        }\n\n        activeUpdateTypes[key] = true;\n        allUpdateTypes.push(newUpdateType);\n        emit UpdateTypeAdded(newUpdateType);\n    }\n\n    /**\n     * @notice Sets the active status of an existing update type\n     * @param updateType The update type to set active status for\n     * @param active True to activate, false to deactivate\n     * @custom:access Controlled by AccessControlManager\n     * @custom:error Throws UpdateTypeNotFound if update type doesn't exist\n     * @custom:error Throws UpdateTypeStatusUnchanged if status is already set to the desired value\n     * @custom:error Throws Unauthorized if caller is not allowed by AccessControlManager\n     * @custom:event Emits UpdateTypeActiveStatusChanged when status is successfully changed\n     */\n    function setUpdateTypeActive(string memory updateType, bool active) external {\n        _checkAccessAllowed(\"setUpdateTypeActive(string,bool)\");\n        bytes32 key = keccak256(bytes(updateType));\n\n        if (!_updateTypeExists(key)) {\n            revert UpdateTypeNotFound();\n        }\n\n        bool previousActive = activeUpdateTypes[key];\n        if (previousActive == active) {\n            revert UpdateTypeStatusUnchanged();\n        }\n\n        activeUpdateTypes[key] = active;\n        emit UpdateTypeActiveStatusChanged(updateType, previousActive, active);\n    }\n\n    /**\n     * @notice Publishes a new risk parameter update\n     * @param referenceId An external reference ID associated with the update\n     * @param newValue The new value of the risk parameter being updated\n     * @param updateType Type of update performed, must be previously authorized\n     * @param market Address for market of the parameter update\n     * @param poolId Pool identifier for eMode-style collateral configuration (0 for regular markets)\n     * @param dstEid Destination endpoint ID for cross-chain routing\n     * @param additionalData Additional data for the update\n     * @custom:error Throws SenderNotAuthorized if caller is not an authorized sender\n     * @custom:error Throws UpdateTypeNotActive if update type is not active\n     * @custom:error Throws ZeroAddressNotAllowed if market is zero address\n     * @custom:event Emits UpdatePublished when update is successfully published\n     */\n    function publishRiskParameterUpdate(\n        string memory referenceId,\n        bytes memory newValue,\n        string memory updateType,\n        address market,\n        uint96 poolId,\n        uint32 dstEid,\n        bytes memory additionalData\n    ) external onlyAuthorized {\n        _publishUpdate(referenceId, newValue, updateType, market, poolId, dstEid, additionalData);\n    }\n\n    /**\n     * @notice Publishes multiple risk parameter updates in a single transaction\n     * @param referenceIds Array of external reference IDs\n     * @param newValues Array of new values for each update\n     * @param updateTypes Array of types for each update, all must be authorized\n     * @param markets Array of addresses for markets of the parameter updates\n     * @param poolIds Array of pool identifiers for eMode-style collateral configuration (0 for regular markets)\n     * @param dstEid Array of destination endpoint IDs for cross-chain routing\n     * @param additionalData Array of additional data for the updates\n     * @custom:error Throws SenderNotAuthorized if caller is not an authorized sender\n     * @custom:error Throws ArrayLengthMismatch if the array lengths do not match or if no updates are provided\n     * @custom:error Throws UpdateTypeNotActive if any update type is not active\n     * @custom:error Throws ZeroAddressNotAllowed if any market is zero address\n     * @custom:event Emits UpdatePublished for each successfully published update\n     */\n    function publishBulkRiskParameterUpdates(\n        string[] memory referenceIds,\n        bytes[] memory newValues,\n        string[] memory updateTypes,\n        address[] memory markets,\n        uint96[] memory poolIds,\n        uint32[] memory dstEid,\n        bytes[] memory additionalData\n    ) external onlyAuthorized {\n        uint256 length = referenceIds.length;\n        if (\n            length == 0 ||\n            length != newValues.length ||\n            length != updateTypes.length ||\n            length != markets.length ||\n            length != poolIds.length ||\n            length != dstEid.length ||\n            length != additionalData.length\n        ) {\n            revert ArrayLengthMismatch();\n        }\n        for (uint256 i = 0; i < length; ++i) {\n            _publishUpdate(\n                referenceIds[i],\n                newValues[i],\n                updateTypes[i],\n                markets[i],\n                poolIds[i],\n                dstEid[i],\n                additionalData[i]\n            );\n        }\n    }\n\n    /**\n     * @notice Fetches the most recent update for a specific parameter in a specific market\n     * @param updateType The identifier for the parameter\n     * @param market The market identifier\n     * @return The most recent RiskParameterUpdate for the specified parameter and market\n     * @custom:error Throws NoUpdateFound if no update exists for the specified parameter and market\n     */\n    function getLatestUpdateByTypeAndMarket(\n        string memory updateType,\n        address market\n    ) external view returns (RiskParameterUpdate memory) {\n        bytes32 updateTypeKey = keccak256(bytes(updateType));\n        uint256 updateId = latestUpdateIdByMarketAndType[updateTypeKey][market];\n        if (updateId == 0) {\n            revert NoUpdateFound();\n        }\n        return updatesById[updateId];\n    }\n\n    /**\n     * @notice Fetches the update for a provided updateId\n     * @param updateId Update ID\n     * @return The RiskParameterUpdate for the specified id\n     * @custom:error Throws InvalidUpdateId if updateId is 0 or greater than updateCounter\n     */\n    function getUpdateById(uint256 updateId) external view returns (RiskParameterUpdate memory) {\n        if (updateId == 0 || updateId > updateCounter) {\n            revert InvalidUpdateId();\n        }\n        return updatesById[updateId];\n    }\n\n    /**\n     * @notice Publishes a new risk parameter update internally\n     * @param referenceId An external reference ID associated with the update\n     * @param newValue The new value of the risk parameter being updated\n     * @param updateType Type of update performed, must be previously authorized\n     * @param market Address for market of the parameter update\n     * @param poolId Pool identifier for eMode-style collateral configuration (0 for regular markets)\n     * @param dstEid Destination endpoint ID for cross-chain routing\n     * @param additionalData Additional data for the update\n     * @custom:error Throws ZeroAddressNotAllowed if market is zero address\n     * @custom:error Throws UpdateTypeNotActive if update type is not active\n     * @custom:event Emits UpdatePublished when update is successfully published\n     */\n    function _publishUpdate(\n        string memory referenceId,\n        bytes memory newValue,\n        string memory updateType,\n        address market,\n        uint96 poolId,\n        uint32 dstEid,\n        bytes memory additionalData\n    ) internal {\n        ensureNonzeroAddress(market);\n        bytes32 updateTypeKey = keccak256(bytes(updateType));\n        if (!activeUpdateTypes[updateTypeKey]) {\n            revert UpdateTypeNotActive();\n        }\n        uint256 newUpdateCounter = ++updateCounter;\n        uint256 previousUpdateId = latestUpdateIdByMarketAndType[updateTypeKey][market];\n        bytes memory previousValue = updatesById[previousUpdateId].newValue;\n\n        RiskParameterUpdate memory newUpdate = RiskParameterUpdate({\n            referenceId: referenceId,\n            updateId: newUpdateCounter,\n            market: market,\n            updateType: updateType,\n            updateTypeKey: updateTypeKey,\n            newValue: newValue,\n            previousValue: previousValue,\n            timestamp: block.timestamp,\n            publisher: msg.sender,\n            poolId: poolId,\n            destLzEid: dstEid,\n            additionalData: additionalData\n        });\n        updatesById[newUpdateCounter] = newUpdate;\n\n        // Update the latest update ID for the (updateTypeKey, market) pair\n        latestUpdateIdByMarketAndType[updateTypeKey][market] = newUpdateCounter;\n\n        emit UpdatePublished(\n            referenceId,\n            newUpdateCounter,\n            market,\n            updateType,\n            newValue,\n            previousValue,\n            block.timestamp,\n            msg.sender,\n            additionalData\n        );\n    }\n\n    /**\n     * @notice Returns the total number of update types in the allUpdateTypes array\n     * @return The length of the allUpdateTypes array\n     */\n    function allUpdateTypesLength() external view returns (uint256) {\n        return allUpdateTypes.length;\n    }\n\n    /**\n     * @notice Gets the latest update ID for a specific market and update type (string) combination\n     * @param updateType The update type string\n     * @param market The market address\n     * @return The latest update ID for the given market and update type, or 0 if none exists\n     */\n    function getLatestUpdateIdByTypeAndMarket(\n        string memory updateType,\n        address market\n    ) external view returns (uint256) {\n        bytes32 updateTypeKey = keccak256(bytes(updateType));\n        return latestUpdateIdByMarketAndType[updateTypeKey][market];\n    }\n\n    /**\n     * @notice Checks if a given update type is currently active.\n     * @param updateType The update type string to check\n     * @return True if the update type is active, false otherwise\n     */\n    function getActiveUpdateTypes(string memory updateType) external view returns (bool) {\n        bytes32 key = keccak256(bytes(updateType));\n        return activeUpdateTypes[key];\n    }\n\n    /**\n     * @notice Returns all update types in the allUpdateTypes array\n     * @return An array of all update type strings\n     */\n    function getAllUpdateTypes() external view returns (string[] memory) {\n        return allUpdateTypes;\n    }\n\n    /**\n     * @notice Checks if an update type exists in the allUpdateTypes array\n     * @param updateTypeKey The keccak256 hash of the update type string\n     * @return True if the update type exists, false otherwise\n     */\n    function _updateTypeExists(bytes32 updateTypeKey) internal view returns (bool) {\n        uint256 length = allUpdateTypes.length;\n        for (uint256 i = 0; i < length; ++i) {\n            if (keccak256(bytes(allUpdateTypes[i])) == updateTypeKey) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    /**\n     * @notice Disables renounceOwnership function\n     * @custom:error Throws RenounceOwnershipNotAllowed\n     */\n    function renounceOwnership() public pure override {\n        revert RenounceOwnershipNotAllowed();\n    }\n}\n"
    },
    "contracts/RiskSteward/RiskStewardReceiver.sol": {
      "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { OwnableUpgradeable } from \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport { Ownable2StepUpgradeable } from \"@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol\";\nimport { IRiskSteward } from \"./Interfaces/IRiskSteward.sol\";\nimport { IRiskOracle, RiskParameterUpdate } from \"./Interfaces/IRiskOracle.sol\";\nimport { IRiskStewardReceiver } from \"./Interfaces/IRiskStewardReceiver.sol\";\nimport { AccessControlledV8 } from \"../Governance/AccessControlledV8.sol\";\nimport { ensureNonzeroAddress } from \"@venusprotocol/solidity-utilities/contracts/validators.sol\";\nimport { ICorePoolComptroller } from \"../interfaces/ICorePoolComptroller.sol\";\nimport { OAppSenderUpgradeable, MessagingFee } from \"@layerzerolabs/oapp-evm-upgradeable/contracts/oapp/OAppSenderUpgradeable.sol\";\nimport { OptionsBuilder } from \"@layerzerolabs/oapp-evm/contracts/oapp/libs/OptionsBuilder.sol\";\nimport { OAppCoreUpgradeable } from \"@layerzerolabs/oapp-evm-upgradeable/contracts/oapp/OAppCoreUpgradeable.sol\";\n\n/**\n * @title RiskStewardReceiver\n * @author Venus\n * @notice Contract that reads updates from a Risk Oracle, validates them with timelock and debounce,\n *         and either executes them locally via the configured RiskSteward or forwards them cross‑chain.\n * @custom:security-contact https://github.com/VenusProtocol/governance-contracts#discussion\n */\ncontract RiskStewardReceiver is IRiskStewardReceiver, AccessControlledV8, OAppSenderUpgradeable {\n    using OptionsBuilder for bytes;\n\n    /**\n     * @notice Period after which a proposed update becomes expired and can no longer be applied\n     */\n    uint256 public constant UPDATE_EXPIRATION_TIME = 2 days;\n\n    /**\n     * @notice Source chain LayerZero endpoint ID\n     */\n    uint32 public immutable LAYER_ZERO_EID;\n\n    /**\n     * @notice The Risk Oracle contract address\n     */\n    IRiskOracle public immutable RISK_ORACLE;\n\n    /**\n     * @notice Pause flag\n     */\n    bool public paused;\n\n    /**\n     * @notice Mapping of supported risk configurations and their validation parameters (keyed by hashed updateType)\n     */\n    mapping(bytes32 => RiskParamConfig) public riskParameterConfigs;\n\n    /**\n     * @notice Master storage of all registered updates by update ID\n     */\n    mapping(uint256 updateId => RegisteredUpdate) public updates;\n\n    /**\n     * @notice Track last processed update ID per (updateTypeKey, market)\n     */\n    mapping(bytes32 => mapping(address market => uint256)) public lastProcessedUpdate;\n\n    /**\n     * @notice Track the current registered update per (updateType, market) to avoid registering multiple updates\n     */\n    mapping(bytes32 => mapping(address market => uint256)) public lastRegisteredUpdate;\n\n    /**\n     * @notice Mapping from executor address to whitelist status\n     */\n    mapping(address => bool) public whitelistedExecutors;\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[44] private __gap;\n\n    /**\n     * @dev Ensures the caller is a whitelisted executor.\n     */\n    modifier onlyWhitelistedExecutors() {\n        if (!whitelistedExecutors[msg.sender]) {\n            revert NotAnExecutor();\n        }\n        _;\n    }\n\n    /**\n     * @dev Ensures the contract is not paused.\n     */\n    modifier whenNotPaused() {\n        if (paused) {\n            revert PausedError();\n        }\n        _;\n    }\n\n    /**\n     * @notice Disables initializers and sets the Risk Oracle and LayerZero configuration.\n     * @param riskOracle_ The address of the Risk Oracle contract.\n     * @param endpoint_ The LayerZero endpoint contract used by the underlying `OAppUpgradeable`.\n     * @param layerZeroLzEid_ The LayerZero endpoint ID (EID) for this chain.\n     * @custom:oz-upgrades-unsafe-allow constructor\n     */\n    constructor(address riskOracle_, address endpoint_, uint32 layerZeroLzEid_) OAppCoreUpgradeable(endpoint_) {\n        _disableInitializers();\n        ensureNonzeroAddress(riskOracle_);\n        ensureNonzeroAddress(endpoint_);\n        if (layerZeroLzEid_ == 0) revert InvalidLayerZeroEid();\n\n        RISK_ORACLE = IRiskOracle(riskOracle_);\n        LAYER_ZERO_EID = layerZeroLzEid_;\n    }\n\n    /**\n     * @notice Initializes the contract with the Access Control Manager and OApp owner.\n     * @param acm_ The address of the Access Control Manager\n     * @param delegate_ The address of the OApp owner passed to `__OApp_init`.\n     */\n    function initialize(address acm_, address delegate_) external initializer {\n        __AccessControlled_init(acm_);\n        __OAppSender_init(delegate_);\n    }\n\n    /**\n     * @notice Accepts native tokens (e.g., BNB) sent to this contract.\n     */\n    receive() external payable {}\n\n    /**\n     * @notice Allows the owner to sweep leftover native tokens (e.g., BNB) from the contract.\n     * @custom:event Emits SweepNative event.\n     */\n    function sweepNative() external onlyOwner {\n        uint256 balance = address(this).balance;\n        if (balance > 0) {\n            (bool success, ) = payable(owner()).call{ value: balance }(\"\");\n            if (!success) revert TransferFailed();\n            emit SweepNative(owner(), balance);\n        }\n    }\n\n    /**\n     * @notice Sets the pause status for `processUpdate`.\n     * @param paused_ True to pause, false to unpause\n     * @custom:access Controlled by AccessControlManager\n     * @custom:event Emits PauseStatusUpdated\n     */\n    function setPaused(bool paused_) external {\n        _checkAccessAllowed(\"setPaused(bool)\");\n        if (paused == paused_) {\n            revert PauseStatusUnchanged();\n        }\n        emit PauseStatusUpdated(paused, paused_);\n        paused = paused_;\n    }\n\n    /**\n     * @notice Sets the risk parameter config for a given update type\n     * @param updateType The type of update to configure\n     * @param riskSteward The address for the risk steward contract responsible for processing the update\n     * @param debounce The debounce period for the update\n     * @param timelock The timelock period before the update can be executed\n     * @custom:access Controlled by AccessControlManager\n     * @custom:event Emits RiskParameterConfigUpdated\n     * @custom:error InvalidUpdateType if the update type string is empty\n     * @custom:error Throws InvalidDebounce if the debounce is 0\n     * @custom:error Throws InvalidTimelock if the timelock is greater than or equal to the expiration time\n     * @custom:error Throws ZeroAddressNotAllowed if the risk steward address is zero\n     */\n    function setRiskParameterConfig(\n        string calldata updateType,\n        address riskSteward,\n        uint256 debounce,\n        uint256 timelock\n    ) external {\n        _checkAccessAllowed(\"setRiskParameterConfig(string,address,uint256,uint256)\");\n        ensureNonzeroAddress(riskSteward);\n\n        if (bytes(updateType).length == 0 || bytes(updateType).length > 64) {\n            revert InvalidUpdateType();\n        }\n        if (debounce == 0) {\n            revert InvalidDebounce();\n        }\n        if (timelock >= UPDATE_EXPIRATION_TIME) {\n            revert InvalidTimelock();\n        }\n\n        bytes32 key = keccak256(bytes(updateType));\n        RiskParamConfig memory previousConfig = riskParameterConfigs[key];\n\n        riskParameterConfigs[key] = RiskParamConfig({\n            active: true,\n            riskSteward: riskSteward,\n            debounce: debounce,\n            timelock: timelock\n        });\n\n        emit RiskParameterConfigUpdated(\n            key,\n            updateType,\n            previousConfig.riskSteward,\n            riskSteward,\n            previousConfig.debounce,\n            debounce,\n            previousConfig.timelock,\n            timelock,\n            previousConfig.active,\n            true\n        );\n    }\n\n    /**\n     * @notice Sets the active status of a risk parameter config\n     * @param updateType The type of update to configure\n     * @param active The active status to set\n     * @custom:access Controlled by AccessControlManager\n     * @custom:event Emits ConfigActiveUpdated with the update type hash, update type, previous active status, and the active status\n     * @custom:error Throws UnsupportedUpdateType if the update type is not supported\n     * @custom:error Throws ConfigStatusUnchanged if the active status is already set to the desired value\n     */\n    function setConfigActive(string calldata updateType, bool active) external {\n        _checkAccessAllowed(\"setConfigActive(string,bool)\");\n        bytes32 key = keccak256(bytes(updateType));\n\n        if (riskParameterConfigs[key].riskSteward == address(0)) {\n            revert UnsupportedUpdateType();\n        }\n\n        bool previousActive = riskParameterConfigs[key].active;\n        if (previousActive == active) {\n            revert ConfigStatusUnchanged();\n        }\n\n        riskParameterConfigs[key].active = active;\n        emit ConfigActiveUpdated(key, updateType, previousActive, active);\n    }\n\n    /**\n     * @notice Manages the whitelist of executors that are allowed to execute timelocked registered updates.\n     * @param executor The address of the executor\n     * @param approved The whitelist status to set (true to whitelist, false to remove)\n     * @custom:access Controlled by AccessControlManager\n     * @custom:event Emits ExecutorStatusUpdated with the executor address, previous approval status, and approval status\n     * @custom:error Throws ZeroAddressNotAllowed if the executor address is zero\n     * @custom:error Throws ExecutorStatusUnchanged if the executor whitelist status is already set to the desired value\n     */\n    function setWhitelistedExecutor(address executor, bool approved) external {\n        _checkAccessAllowed(\"setWhitelistedExecutor(address,bool)\");\n        ensureNonzeroAddress(executor);\n\n        bool previousApproved = whitelistedExecutors[executor];\n        if (previousApproved == approved) {\n            revert ExecutorStatusUnchanged();\n        }\n\n        whitelistedExecutors[executor] = approved;\n        emit ExecutorStatusUpdated(executor, previousApproved, approved);\n    }\n\n    /**\n     * @notice Processes an update from the Risk Oracle. Validates, registers the update,\n     * and either executes immediately, registers with timelock, or forwards cross-chain.\n     * @param updateId The update ID from the oracle's perspective\n     * @custom:event Emits UpdateRegistered, UpdateExecuted, or UpdateSentToDestination depending on the update type\n     * @custom:error Throws UpdateAlreadyResolved if the update was already processed\n     * @custom:error Throws UpdateIsExpired if the update has expired\n     * @custom:error Throws ConfigNotActive if the config is not active\n     * @custom:error Throws UpdateTooFrequent if the debounce period has not passed\n     * @custom:error Throws RegisteredUpdateTypeExist if there is a non-expired pending update of the same type\n     */\n    function processUpdate(uint256 updateId) external whenNotPaused {\n        RiskParameterUpdate memory update = RISK_ORACLE.getUpdateById(updateId);\n        RiskParamConfig storage config = riskParameterConfigs[update.updateTypeKey];\n        bool isRemoteUpdate = update.destLzEid != 0 && update.destLzEid != LAYER_ZERO_EID;\n\n        // Skip active update check for remote updates since they are sent immediately and not registered locally\n        if (!isRemoteUpdate) _ensureNoActiveUpdate(update);\n        _validateRegisterUpdate(update, config, isRemoteUpdate);\n\n        IRiskSteward riskSteward = IRiskSteward(config.riskSteward);\n        bool safeForDirectExecution = isRemoteUpdate ? false : riskSteward.isSafeForDirectExecution(update);\n        _registerUpdate(update, config, safeForDirectExecution || isRemoteUpdate);\n\n        if (isRemoteUpdate) {\n            _sendRemoteUpdate(update, \"\", 0);\n        } else if (safeForDirectExecution) {\n            _executeUpdate(update, riskSteward);\n        }\n    }\n\n    /**\n     * @notice Executes a registered update. Only whitelisted executors can call this function.\n     *         This function can be used for updates that have completed their timelock and are ready to execute.\n     * @param updateId The oracle update ID of the update to execute\n     * @custom:access Only whitelisted executors can call this function\n     * @custom:event Emits UpdateExecuted with the oracle update ID\n     * @custom:error Throws NotAnExecutor if the caller is not a whitelisted executor\n     * @custom:error Throws InvalidRegisteredUpdate if the update was never registered\n     * @custom:error Throws UpdateAlreadyResolved if the update was already executed or rejected\n     * @custom:error Throws UpdateIsExpired if the update has expired\n     * @custom:error Throws ConfigNotActive if the config is not active\n     * @custom:error Throws UpdateNotUnlocked if the unlock time has not passed\n     */\n    function executeRegisteredUpdate(uint256 updateId) external onlyWhitelistedExecutors {\n        RegisteredUpdate storage registeredUpdate = updates[updateId];\n        RiskParameterUpdate memory update = RISK_ORACLE.getUpdateById(updateId);\n        RiskParamConfig storage config = riskParameterConfigs[update.updateTypeKey];\n\n        _validateExecuteUpdate(registeredUpdate, update, config);\n        _executeUpdate(update, IRiskSteward(config.riskSteward));\n    }\n\n    /**\n     * @notice Rejects a registered update\n     * @param updateId The oracle update ID of the update to reject\n     * @custom:access Only whitelisted executors can call this function\n     * @custom:event Emits UpdateRejected with the oracle update ID\n     * @custom:error Throws UpdateAlreadyResolved if the update was already executed or rejected\n     */\n    function rejectUpdate(uint256 updateId) external onlyWhitelistedExecutors {\n        RegisteredUpdate storage registeredUpdate = updates[updateId];\n\n        if (registeredUpdate.status != UpdateStatus.Pending) {\n            revert UpdateAlreadyResolved();\n        }\n\n        registeredUpdate.status = UpdateStatus.Rejected;\n        emit UpdateRejected(updateId);\n    }\n\n    /**\n     * @notice Resends a remote update to the destination chain. This function is useful in case of bridge failures.\n     * @dev Duplicate update rejection is handled in the destination contract itself, so resending\n     *      the same update multiple times is safe and will be deduplicated on the destination side.\n     * @param updateId The oracle update ID to resend\n     * @param options LayerZero message options; if empty, default executor option is used\n     * @custom:access Only whitelisted executors can call this function\n     * @custom:event Emits UpdateResentToDestination with the update ID, destination chain ID, update type, and market\n     * @custom:error Throws NotAnExecutor if the caller is not a whitelisted executor\n     * @custom:error Throws InvalidUpdateToResend if the update status is not SENT_TO_DESTINATION\n     * @custom:error Throws UpdateIsExpired if the update has expired\n     */\n    function resendRemoteUpdate(uint256 updateId, bytes calldata options) external payable onlyWhitelistedExecutors {\n        RegisteredUpdate storage registeredUpdate = updates[updateId];\n        if (registeredUpdate.status != UpdateStatus.SENT_TO_DESTINATION) {\n            revert InvalidUpdateToResend();\n        }\n\n        RiskParameterUpdate memory update = RISK_ORACLE.getUpdateById(updateId);\n\n        // Check if update is expired\n        if (update.timestamp + UPDATE_EXPIRATION_TIME < block.timestamp) {\n            revert UpdateIsExpired();\n        }\n\n        _sendRemoteUpdate(update, options, msg.value);\n        emit UpdateResentToDestination(update.updateId, update.destLzEid, update.updateType, update.market);\n    }\n\n    /**\n     * @notice Returns an array of update IDs for executable registered updates for a given update type and comptroller.\n     * @param updateType The human‑readable identifier of the update type to filter by\n     * @param comptroller The address of the Comptroller (either Core Pool or Isolated Pools) that manages the markets\n     * @return executableUpdates Array of update IDs that are ready to be executed\n     */\n    function getExecutableUpdates(\n        string calldata updateType,\n        address comptroller\n    ) external view returns (uint256[] memory executableUpdates) {\n        bytes32 updateTypeKey = keccak256(bytes(updateType));\n        // Both Core and Isolated Pools comptrollers expose the same signature\n        address[] memory markets = ICorePoolComptroller(comptroller).getAllMarkets();\n        uint256 maxUpdates = markets.length;\n        uint256[] memory tempArray = new uint256[](maxUpdates);\n        uint256 count = 0;\n\n        for (uint256 i = 0; i < maxUpdates; ++i) {\n            uint256 registeredUpdateId = lastRegisteredUpdate[updateTypeKey][markets[i]];\n            if (!_isUpdateExecutable(registeredUpdateId)) continue;\n            tempArray[count] = registeredUpdateId;\n            count++;\n        }\n\n        // shrink array to real size\n        executableUpdates = new uint256[](count);\n        for (uint256 i = 0; i < count; ++i) {\n            executableUpdates[i] = tempArray[i];\n        }\n    }\n\n    /**\n     * @notice Returns whether a registered update is ready to be executed.\n     * @param updateId The oracle update ID to query\n     * @return True if the update is pending, not expired, active, and past its timelock\n     */\n    function isUpdateExecutable(uint256 updateId) external view returns (bool) {\n        return _isUpdateExecutable(updateId);\n    }\n\n    /**\n     * @notice Returns the risk parameter configuration for a given update type\n     * @param updateType The human-readable identifier of the update type\n     * @return The risk parameter configuration\n     */\n    function getRiskParameterConfig(string calldata updateType) external view returns (RiskParamConfig memory) {\n        bytes32 key = keccak256(bytes(updateType));\n        return riskParameterConfigs[key];\n    }\n\n    /**\n     * @notice Returns the last processed update ID for a given update type and market\n     * @param updateType The human-readable identifier of the update type\n     * @param market The address of the market\n     * @return The last processed update ID\n     */\n    function getLastProcessedUpdate(string calldata updateType, address market) external view returns (uint256) {\n        bytes32 key = keccak256(bytes(updateType));\n        return lastProcessedUpdate[key][market];\n    }\n\n    /**\n     * @notice Returns the last registered update ID for a given update type and market\n     * @param updateType The human-readable identifier of the update type\n     * @param market The address of the market\n     * @return The last registered update ID\n     */\n    function getLastRegisteredUpdate(string calldata updateType, address market) external view returns (uint256) {\n        bytes32 key = keccak256(bytes(updateType));\n        return lastRegisteredUpdate[key][market];\n    }\n\n    /**\n     * @notice Quotes the gas fee needed to pay for the full omnichain transaction in native gas or ZRO token.\n     * @param update The risk parameter update payload to be sent\n     * @param options Message execution options (e.g., for sending gas to the destination)\n     * @param payInLzToken Whether to return the fee in ZRO token instead of native gas\n     * @return fee A `MessagingFee` struct containing the calculated gas fee\n     */\n    function quote(\n        RiskParameterUpdate memory update,\n        bytes memory options,\n        bool payInLzToken\n    ) public view returns (MessagingFee memory fee) {\n        bytes memory payload = abi.encode(update);\n        fee = _quote(update.destLzEid, payload, options, payInLzToken);\n    }\n\n    /**\n     * @notice Sends a `RiskParameterUpdate` to a destination chain via LayerZero.\n     * @param dstEid Destination chain endpoint ID\n     * @param update The risk parameter update payload to send\n     * @param options LayerZero message options; if empty, a default executor option is used\n     * @param fee Messaging fee structure returned by `quote`\n     * @param refundAddress Address to receive any surplus fee refunds\n     * @custom:error InvalidLzSendCaller if called by any address other than this contract\n     */\n    function lzSend(\n        uint32 dstEid,\n        RiskParameterUpdate memory update,\n        bytes memory options,\n        MessagingFee memory fee,\n        address refundAddress\n    ) public payable {\n        if (msg.sender != address(this)) {\n            revert InvalidLzSendCaller();\n        }\n\n        bytes memory payload = abi.encode(update);\n        _lzSend(dstEid, payload, options, fee, refundAddress);\n    }\n\n    /**\n     * @dev Overrides OwnableUpgradeable and Ownable2StepUpgradeable to resolve\n     *      the multiple inheritance ownership transfer conflict.\n     */\n    function transferOwnership(\n        address newOwner\n    ) public override(OwnableUpgradeable, Ownable2StepUpgradeable) onlyOwner {\n        Ownable2StepUpgradeable.transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Internal hook to finalize ownership transfer, resolving the\n     *      OwnableUpgradeable and Ownable2StepUpgradeable inheritance conflict.\n     */\n    function _transferOwnership(address newOwner) internal override(OwnableUpgradeable, Ownable2StepUpgradeable) {\n        Ownable2StepUpgradeable._transferOwnership(newOwner);\n    }\n\n    /**\n     * @notice Registers an update from the Risk Oracle with a timelock.\n     * @param update The risk parameter update from the Risk Oracle to register\n     * @param config The risk parameter configuration for this update type containing timelock\n     * @param useImmediateUnlock Whether to unlock the update immediately or use timelock\n     * @custom:event Emits UpdateRegistered with the oracle update ID, unlock time, update type, and market\n     */\n    function _registerUpdate(\n        RiskParameterUpdate memory update,\n        RiskParamConfig memory config,\n        bool useImmediateUnlock\n    ) internal {\n        uint256 updateId = update.updateId;\n        uint256 unlockTime = useImmediateUnlock ? block.timestamp : block.timestamp + config.timelock;\n\n        updates[updateId] = RegisteredUpdate({\n            updateId: updateId,\n            unlockTime: unlockTime,\n            status: UpdateStatus.Pending,\n            executor: address(0),\n            executedAt: 0\n        });\n\n        lastRegisteredUpdate[update.updateTypeKey][update.market] = updateId;\n        emit UpdateRegistered(updateId, unlockTime, update.updateType, update.market);\n    }\n\n    /**\n     * @notice Executes a validated update via the risk steward and records its execution metadata.\n     *         Updates the registered update storage, last processed tracking, and emits the execution event.\n     *         Preserves the unlockTime that was set during registration.\n     * @param update The risk parameter update to execute\n     * @param steward The risk steward contract that will process the update\n     * @custom:event Emits UpdateExecuted with the oracle update ID\n     */\n    function _executeUpdate(RiskParameterUpdate memory update, IRiskSteward steward) internal {\n        uint256 updateId = update.updateId;\n        uint256 timestamp = block.timestamp;\n        RegisteredUpdate storage registeredUpdate = updates[updateId];\n\n        registeredUpdate.status = UpdateStatus.Executed;\n        registeredUpdate.executor = address(msg.sender);\n        registeredUpdate.executedAt = timestamp;\n        lastProcessedUpdate[update.updateTypeKey][update.market] = updateId;\n\n        steward.applyUpdate(update);\n        emit UpdateExecuted(updateId);\n    }\n\n    /**\n     * @notice Sends a risk parameter update to a destination chain via LayerZero and records it as sent.\n     *         The update should already be registered before calling this function.\n     * @param update The risk parameter update to send to the destination chain\n     * @param options LayerZero message options; if empty, default executor option is used\n     * @param nativeFee Native tokens supplied to cover the bridge fee (0 to use the quoted amount)\n     * @custom:event Emits UpdateSentToDestination with the update ID, destination endpoint ID, update type, and market\n     */\n    function _sendRemoteUpdate(RiskParameterUpdate memory update, bytes memory options, uint256 nativeFee) internal {\n        bytes memory option = options.length == 0\n            ? OptionsBuilder.newOptions().addExecutorLzReceiveOption(1_000_000, 0)\n            : options;\n\n        MessagingFee memory fee;\n\n        if (nativeFee == 0) {\n            fee = quote(update, option, false);\n        } else {\n            fee = MessagingFee(nativeFee, 0);\n        }\n\n        this.lzSend{ value: fee.nativeFee }(update.destLzEid, update, option, fee, address(this));\n\n        RegisteredUpdate storage registeredUpdate = updates[update.updateId];\n        registeredUpdate.status = UpdateStatus.SENT_TO_DESTINATION;\n        registeredUpdate.executor = address(msg.sender);\n        registeredUpdate.executedAt = block.timestamp;\n\n        bytes32 updateTypeKey = update.updateTypeKey;\n        lastProcessedUpdate[updateTypeKey][update.market] = update.updateId;\n\n        emit UpdateSentToDestination(update.updateId, update.destLzEid, update.updateType, update.market);\n    }\n\n    /**\n     * @notice Ensures there is no other pending registered update of the same type for the same market.\n     *         If a pending update exists and is expired, it is marked as expired and a new update can proceed.\n     *         If a pending update exists and is not expired, the call reverts to prevent overlapping updates.\n     * @param update The risk parameter update being registered\n     * @custom:event Emits UpdateExpired with the ID of the previously pending update if it is found to be expired\n     * @custom:error RegisteredUpdateTypeExist if there is a non‑expired pending update of the same type for the market\n     */\n    function _ensureNoActiveUpdate(RiskParameterUpdate memory update) internal {\n        uint256 registeredUpdateId = lastRegisteredUpdate[update.updateTypeKey][update.market];\n        if (registeredUpdateId == 0) return; // no prior update of this type for this market\n\n        RegisteredUpdate storage existing = updates[registeredUpdateId];\n        if (existing.status != UpdateStatus.Pending) return;\n\n        // Check expiration\n        RiskParameterUpdate memory existingUpdate = RISK_ORACLE.getUpdateById(registeredUpdateId);\n        bool expired = existingUpdate.timestamp + UPDATE_EXPIRATION_TIME < block.timestamp;\n\n        if (expired) {\n            existing.status = UpdateStatus.Expired;\n            emit UpdateExpired(registeredUpdateId);\n            return;\n        }\n\n        // If still pending & not expired reject new update\n        revert RegisteredUpdateTypeExist(registeredUpdateId);\n    }\n\n    /**\n     * @notice Validates an oracle update before registration.\n     * @param update The risk parameter update to validate\n     * @param config The configuration for this update type\n     * @param isRemoteUpdate Whether the update is destined for a remote chain\n     * @custom:error UpdateAlreadyResolved if the update was already registered\n     * @custom:error ConfigNotActive if the configuration for the update type is not active\n     * @custom:error UpdateIsExpired if the update has expired or is not the latest for the given market and type\n     * @custom:error UpdateWillExpireBeforeUnlock if the update will expire before its timelock unlocks\n     * @custom:error UpdateTooFrequent if the debounce period has not passed for the given market and type (only for local updates)\n     */\n    function _validateRegisterUpdate(\n        RiskParameterUpdate memory update,\n        RiskParamConfig storage config,\n        bool isRemoteUpdate\n    ) internal view {\n        // Check if this update was already registered\n        if (updates[update.updateId].status != UpdateStatus.None) {\n            revert UpdateAlreadyResolved();\n        }\n\n        // Check if config is active\n        if (!config.active) {\n            revert ConfigNotActive();\n        }\n\n        // Check if this is the latest update for this market and type\n        uint256 latestUpdateIdForMarketAndType = RISK_ORACLE.getLatestUpdateIdByTypeAndMarket(\n            update.updateType,\n            update.market\n        );\n        if (latestUpdateIdForMarketAndType != update.updateId) {\n            revert UpdateIsExpired();\n        }\n\n        uint256 currentTime = block.timestamp;\n        uint256 expirationTime = update.timestamp + UPDATE_EXPIRATION_TIME;\n\n        // Check expiration\n        if (expirationTime < currentTime) {\n            revert UpdateIsExpired();\n        }\n\n        // Check if update will still be valid when timelock unlocks\n        if (expirationTime < currentTime + config.timelock) {\n            revert UpdateWillExpireBeforeUnlock();\n        }\n\n        // Check debounce (only for local updates)\n        if (!isRemoteUpdate) {\n            uint256 lastProcessedId = lastProcessedUpdate[update.updateTypeKey][update.market];\n            uint256 lastExecutionTime = updates[lastProcessedId].executedAt;\n            if (lastExecutionTime != 0 && (lastExecutionTime + config.debounce > currentTime)) {\n                revert UpdateTooFrequent();\n            }\n        }\n    }\n\n    /**\n     * @notice Validates a registered update before execution.\n     * @param registeredUpdate The stored registered update metadata\n     * @param update The risk parameter update fetched from the oracle\n     * @param config The configuration for this update type\n     * @custom:error ConfigNotActive if the configuration for the update type is not active\n     * @custom:error InvalidRegisteredUpdate if the update was never registered\n     * @custom:error UpdateAlreadyResolved if the update was already executed or rejected\n     * @custom:error UpdateIsExpired if the update has expired\n     * @custom:error UpdateNotUnlocked if the unlock time has not passed\n     */\n    function _validateExecuteUpdate(\n        RegisteredUpdate storage registeredUpdate,\n        RiskParameterUpdate memory update,\n        RiskParamConfig storage config\n    ) internal view {\n        if (!config.active) {\n            revert ConfigNotActive();\n        }\n\n        if (registeredUpdate.status == UpdateStatus.None) {\n            revert InvalidRegisteredUpdate();\n        }\n\n        if (registeredUpdate.status != UpdateStatus.Pending) {\n            revert UpdateAlreadyResolved();\n        }\n\n        if (update.timestamp + UPDATE_EXPIRATION_TIME < block.timestamp) {\n            revert UpdateIsExpired();\n        }\n\n        if (block.timestamp < registeredUpdate.unlockTime) {\n            revert UpdateNotUnlocked();\n        }\n    }\n\n    /**\n     * @notice Checks if an update has completed all conditions to be executed.\n     * @param updateId The oracle update ID to query\n     * @return True if the update is pending, not expired, active, and past its timelock\n     */\n    function _isUpdateExecutable(uint256 updateId) internal view returns (bool) {\n        RegisteredUpdate storage registeredUpdate = updates[updateId];\n        if (registeredUpdate.status != UpdateStatus.Pending) {\n            return false;\n        }\n\n        RiskParameterUpdate memory update = RISK_ORACLE.getUpdateById(updateId);\n        RiskParamConfig storage config = riskParameterConfigs[update.updateTypeKey];\n\n        if (!config.active) {\n            return false;\n        }\n\n        // Check expiration\n        if (update.timestamp + UPDATE_EXPIRATION_TIME < block.timestamp) {\n            return false;\n        }\n\n        // Check UnlockTime\n        return block.timestamp >= registeredUpdate.unlockTime;\n    }\n\n    /**\n     * @notice Disables renounceOwnership function\n     * @custom:error Throws RenounceOwnershipNotAllowed\n     */\n    function renounceOwnership() public pure override {\n        revert RenounceOwnershipNotAllowed();\n    }\n}\n"
    },
    "solidity-bytes-utils/contracts/BytesLib.sol": {
      "content": "// SPDX-License-Identifier: Unlicense\n/*\n * @title Solidity Bytes Arrays Utils\n * @author Gonçalo Sá <goncalo.sa@consensys.net>\n *\n * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.\n *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.\n */\npragma solidity >=0.8.0 <0.9.0;\n\n\nlibrary BytesLib {\n    function concat(\n        bytes memory _preBytes,\n        bytes memory _postBytes\n    )\n        internal\n        pure\n        returns (bytes memory)\n    {\n        bytes memory tempBytes;\n\n        assembly {\n            // Get a location of some free memory and store it in tempBytes as\n            // Solidity does for memory variables.\n            tempBytes := mload(0x40)\n\n            // Store the length of the first bytes array at the beginning of\n            // the memory for tempBytes.\n            let length := mload(_preBytes)\n            mstore(tempBytes, length)\n\n            // Maintain a memory counter for the current write location in the\n            // temp bytes array by adding the 32 bytes for the array length to\n            // the starting location.\n            let mc := add(tempBytes, 0x20)\n            // Stop copying when the memory counter reaches the length of the\n            // first bytes array.\n            let end := add(mc, length)\n\n            for {\n                // Initialize a copy counter to the start of the _preBytes data,\n                // 32 bytes into its memory.\n                let cc := add(_preBytes, 0x20)\n            } lt(mc, end) {\n                // Increase both counters by 32 bytes each iteration.\n                mc := add(mc, 0x20)\n                cc := add(cc, 0x20)\n            } {\n                // Write the _preBytes data into the tempBytes memory 32 bytes\n                // at a time.\n                mstore(mc, mload(cc))\n            }\n\n            // Add the length of _postBytes to the current length of tempBytes\n            // and store it as the new length in the first 32 bytes of the\n            // tempBytes memory.\n            length := mload(_postBytes)\n            mstore(tempBytes, add(length, mload(tempBytes)))\n\n            // Move the memory counter back from a multiple of 0x20 to the\n            // actual end of the _preBytes data.\n            mc := end\n            // Stop copying when the memory counter reaches the new combined\n            // length of the arrays.\n            end := add(mc, length)\n\n            for {\n                let cc := add(_postBytes, 0x20)\n            } lt(mc, end) {\n                mc := add(mc, 0x20)\n                cc := add(cc, 0x20)\n            } {\n                mstore(mc, mload(cc))\n            }\n\n            // Update the free-memory pointer by padding our last write location\n            // to 32 bytes: add 31 bytes to the end of tempBytes to move to the\n            // next 32 byte block, then round down to the nearest multiple of\n            // 32. If the sum of the length of the two arrays is zero then add\n            // one before rounding down to leave a blank 32 bytes (the length block with 0).\n            mstore(0x40, and(\n              add(add(end, iszero(add(length, mload(_preBytes)))), 31),\n              not(31) // Round down to the nearest 32 bytes.\n            ))\n        }\n\n        return tempBytes;\n    }\n\n    function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {\n        assembly {\n            // Read the first 32 bytes of _preBytes storage, which is the length\n            // of the array. (We don't need to use the offset into the slot\n            // because arrays use the entire slot.)\n            let fslot := sload(_preBytes.slot)\n            // Arrays of 31 bytes or less have an even value in their slot,\n            // while longer arrays have an odd value. The actual length is\n            // the slot divided by two for odd values, and the lowest order\n            // byte divided by two for even values.\n            // If the slot is even, bitwise and the slot with 255 and divide by\n            // two to get the length. If the slot is odd, bitwise and the slot\n            // with -1 and divide by two.\n            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\n            let mlength := mload(_postBytes)\n            let newlength := add(slength, mlength)\n            // slength can contain both the length and contents of the array\n            // if length < 32 bytes so let's prepare for that\n            // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\n            switch add(lt(slength, 32), lt(newlength, 32))\n            case 2 {\n                // Since the new array still fits in the slot, we just need to\n                // update the contents of the slot.\n                // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length\n                sstore(\n                    _preBytes.slot,\n                    // all the modifications to the slot are inside this\n                    // next block\n                    add(\n                        // we can just add to the slot contents because the\n                        // bytes we want to change are the LSBs\n                        fslot,\n                        add(\n                            mul(\n                                div(\n                                    // load the bytes from memory\n                                    mload(add(_postBytes, 0x20)),\n                                    // zero all bytes to the right\n                                    exp(0x100, sub(32, mlength))\n                                ),\n                                // and now shift left the number of bytes to\n                                // leave space for the length in the slot\n                                exp(0x100, sub(32, newlength))\n                            ),\n                            // increase length by the double of the memory\n                            // bytes length\n                            mul(mlength, 2)\n                        )\n                    )\n                )\n            }\n            case 1 {\n                // The stored value fits in the slot, but the combined value\n                // will exceed it.\n                // get the keccak hash to get the contents of the array\n                mstore(0x0, _preBytes.slot)\n                let sc := add(keccak256(0x0, 0x20), div(slength, 32))\n\n                // save new length\n                sstore(_preBytes.slot, add(mul(newlength, 2), 1))\n\n                // The contents of the _postBytes array start 32 bytes into\n                // the structure. Our first read should obtain the `submod`\n                // bytes that can fit into the unused space in the last word\n                // of the stored array. To get this, we read 32 bytes starting\n                // from `submod`, so the data we read overlaps with the array\n                // contents by `submod` bytes. Masking the lowest-order\n                // `submod` bytes allows us to add that value directly to the\n                // stored value.\n\n                let submod := sub(32, slength)\n                let mc := add(_postBytes, submod)\n                let end := add(_postBytes, mlength)\n                let mask := sub(exp(0x100, submod), 1)\n\n                sstore(\n                    sc,\n                    add(\n                        and(\n                            fslot,\n                            0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00\n                        ),\n                        and(mload(mc), mask)\n                    )\n                )\n\n                for {\n                    mc := add(mc, 0x20)\n                    sc := add(sc, 1)\n                } lt(mc, end) {\n                    sc := add(sc, 1)\n                    mc := add(mc, 0x20)\n                } {\n                    sstore(sc, mload(mc))\n                }\n\n                mask := exp(0x100, sub(mc, end))\n\n                sstore(sc, mul(div(mload(mc), mask), mask))\n            }\n            default {\n                // get the keccak hash to get the contents of the array\n                mstore(0x0, _preBytes.slot)\n                // Start copying to the last used word of the stored array.\n                let sc := add(keccak256(0x0, 0x20), div(slength, 32))\n\n                // save new length\n                sstore(_preBytes.slot, add(mul(newlength, 2), 1))\n\n                // Copy over the first `submod` bytes of the new data as in\n                // case 1 above.\n                let slengthmod := mod(slength, 32)\n                let mlengthmod := mod(mlength, 32)\n                let submod := sub(32, slengthmod)\n                let mc := add(_postBytes, submod)\n                let end := add(_postBytes, mlength)\n                let mask := sub(exp(0x100, submod), 1)\n\n                sstore(sc, add(sload(sc), and(mload(mc), mask)))\n\n                for {\n                    sc := add(sc, 1)\n                    mc := add(mc, 0x20)\n                } lt(mc, end) {\n                    sc := add(sc, 1)\n                    mc := add(mc, 0x20)\n                } {\n                    sstore(sc, mload(mc))\n                }\n\n                mask := exp(0x100, sub(mc, end))\n\n                sstore(sc, mul(div(mload(mc), mask), mask))\n            }\n        }\n    }\n\n    function slice(\n        bytes memory _bytes,\n        uint256 _start,\n        uint256 _length\n    )\n        internal\n        pure\n        returns (bytes memory)\n    {\n        // We're using the unchecked block below because otherwise execution ends \n        // with the native overflow error code.\n        unchecked {\n            require(_length + 31 >= _length, \"slice_overflow\");\n        }\n        require(_bytes.length >= _start + _length, \"slice_outOfBounds\");\n\n        bytes memory tempBytes;\n\n        assembly {\n            switch iszero(_length)\n            case 0 {\n                // Get a location of some free memory and store it in tempBytes as\n                // Solidity does for memory variables.\n                tempBytes := mload(0x40)\n\n                // The first word of the slice result is potentially a partial\n                // word read from the original array. To read it, we calculate\n                // the length of that partial word and start copying that many\n                // bytes into the array. The first word we copy will start with\n                // data we don't care about, but the last `lengthmod` bytes will\n                // land at the beginning of the contents of the new array. When\n                // we're done copying, we overwrite the full first word with\n                // the actual length of the slice.\n                let lengthmod := and(_length, 31)\n\n                // The multiplication in the next line is necessary\n                // because when slicing multiples of 32 bytes (lengthmod == 0)\n                // the following copy loop was copying the origin's length\n                // and then ending prematurely not copying everything it should.\n                let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))\n                let end := add(mc, _length)\n\n                for {\n                    // The multiplication in the next line has the same exact purpose\n                    // as the one above.\n                    let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)\n                } lt(mc, end) {\n                    mc := add(mc, 0x20)\n                    cc := add(cc, 0x20)\n                } {\n                    mstore(mc, mload(cc))\n                }\n\n                mstore(tempBytes, _length)\n\n                //update free-memory pointer\n                //allocating the array padded to 32 bytes like the compiler does now\n                mstore(0x40, and(add(mc, 31), not(31)))\n            }\n            //if we want a zero-length slice let's just return a zero-length array\n            default {\n                tempBytes := mload(0x40)\n                //zero out the 32 bytes slice we are about to return\n                //we need to do it because Solidity does not garbage collect\n                mstore(tempBytes, 0)\n\n                mstore(0x40, add(tempBytes, 0x20))\n            }\n        }\n\n        return tempBytes;\n    }\n\n    function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {\n        require(_bytes.length >= _start + 20, \"toAddress_outOfBounds\");\n        address tempAddress;\n\n        assembly {\n            tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\n        }\n\n        return tempAddress;\n    }\n\n    function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {\n        require(_bytes.length >= _start + 1 , \"toUint8_outOfBounds\");\n        uint8 tempUint;\n\n        assembly {\n            tempUint := mload(add(add(_bytes, 0x1), _start))\n        }\n\n        return tempUint;\n    }\n\n    function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {\n        require(_bytes.length >= _start + 2, \"toUint16_outOfBounds\");\n        uint16 tempUint;\n\n        assembly {\n            tempUint := mload(add(add(_bytes, 0x2), _start))\n        }\n\n        return tempUint;\n    }\n\n    function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {\n        require(_bytes.length >= _start + 4, \"toUint32_outOfBounds\");\n        uint32 tempUint;\n\n        assembly {\n            tempUint := mload(add(add(_bytes, 0x4), _start))\n        }\n\n        return tempUint;\n    }\n\n    function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {\n        require(_bytes.length >= _start + 8, \"toUint64_outOfBounds\");\n        uint64 tempUint;\n\n        assembly {\n            tempUint := mload(add(add(_bytes, 0x8), _start))\n        }\n\n        return tempUint;\n    }\n\n    function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {\n        require(_bytes.length >= _start + 12, \"toUint96_outOfBounds\");\n        uint96 tempUint;\n\n        assembly {\n            tempUint := mload(add(add(_bytes, 0xc), _start))\n        }\n\n        return tempUint;\n    }\n\n    function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {\n        require(_bytes.length >= _start + 16, \"toUint128_outOfBounds\");\n        uint128 tempUint;\n\n        assembly {\n            tempUint := mload(add(add(_bytes, 0x10), _start))\n        }\n\n        return tempUint;\n    }\n\n    function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {\n        require(_bytes.length >= _start + 32, \"toUint256_outOfBounds\");\n        uint256 tempUint;\n\n        assembly {\n            tempUint := mload(add(add(_bytes, 0x20), _start))\n        }\n\n        return tempUint;\n    }\n\n    function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {\n        require(_bytes.length >= _start + 32, \"toBytes32_outOfBounds\");\n        bytes32 tempBytes32;\n\n        assembly {\n            tempBytes32 := mload(add(add(_bytes, 0x20), _start))\n        }\n\n        return tempBytes32;\n    }\n\n    function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {\n        bool success = true;\n\n        assembly {\n            let length := mload(_preBytes)\n\n            // if lengths don't match the arrays are not equal\n            switch eq(length, mload(_postBytes))\n            case 1 {\n                // cb is a circuit breaker in the for loop since there's\n                //  no said feature for inline assembly loops\n                // cb = 1 - don't breaker\n                // cb = 0 - break\n                let cb := 1\n\n                let mc := add(_preBytes, 0x20)\n                let end := add(mc, length)\n\n                for {\n                    let cc := add(_postBytes, 0x20)\n                // the next line is the loop condition:\n                // while(uint256(mc < end) + cb == 2)\n                } eq(add(lt(mc, end), cb), 2) {\n                    mc := add(mc, 0x20)\n                    cc := add(cc, 0x20)\n                } {\n                    // if any of these checks fails then arrays are not equal\n                    if iszero(eq(mload(mc), mload(cc))) {\n                        // unsuccess:\n                        success := 0\n                        cb := 0\n                    }\n                }\n            }\n            default {\n                // unsuccess:\n                success := 0\n            }\n        }\n\n        return success;\n    }\n\n    function equalStorage(\n        bytes storage _preBytes,\n        bytes memory _postBytes\n    )\n        internal\n        view\n        returns (bool)\n    {\n        bool success = true;\n\n        assembly {\n            // we know _preBytes_offset is 0\n            let fslot := sload(_preBytes.slot)\n            // Decode the length of the stored array like in concatStorage().\n            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\n            let mlength := mload(_postBytes)\n\n            // if lengths don't match the arrays are not equal\n            switch eq(slength, mlength)\n            case 1 {\n                // slength can contain both the length and contents of the array\n                // if length < 32 bytes so let's prepare for that\n                // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\n                if iszero(iszero(slength)) {\n                    switch lt(slength, 32)\n                    case 1 {\n                        // blank the last byte which is the length\n                        fslot := mul(div(fslot, 0x100), 0x100)\n\n                        if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {\n                            // unsuccess:\n                            success := 0\n                        }\n                    }\n                    default {\n                        // cb is a circuit breaker in the for loop since there's\n                        //  no said feature for inline assembly loops\n                        // cb = 1 - don't breaker\n                        // cb = 0 - break\n                        let cb := 1\n\n                        // get the keccak hash to get the contents of the array\n                        mstore(0x0, _preBytes.slot)\n                        let sc := keccak256(0x0, 0x20)\n\n                        let mc := add(_postBytes, 0x20)\n                        let end := add(mc, mlength)\n\n                        // the next line is the loop condition:\n                        // while(uint256(mc < end) + cb == 2)\n                        for {} eq(add(lt(mc, end), cb), 2) {\n                            sc := add(sc, 1)\n                            mc := add(mc, 0x20)\n                        } {\n                            if iszero(eq(sload(sc), mload(mc))) {\n                                // unsuccess:\n                                success := 0\n                                cb := 0\n                            }\n                        }\n                    }\n                }\n            }\n            default {\n                // unsuccess:\n                success := 0\n            }\n        }\n\n        return success;\n    }\n}\n"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 10000
    },
    "evmVersion": "paris",
    "outputSelection": {
      "*": {
        "*": [
          "storageLayout",
          "abi",
          "evm.bytecode",
          "evm.deployedBytecode",
          "evm.methodIdentifiers",
          "metadata",
          "devdoc",
          "userdoc",
          "evm.gasEstimates"
        ],
        "": ["ast"]
      }
    },
    "metadata": {
      "useLiteralContent": true
    }
  }
}
