{"sources":{"@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/IMessageLib.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\nimport { IERC165 } from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\n\nimport { SetConfigParam } from \"./IMessageLibManager.sol\";\n\nenum MessageLibType {\n    Send,\n    Receive,\n    SendAndReceive\n}\n\ninterface IMessageLib is IERC165 {\n    function setConfig(address _oapp, SetConfigParam[] calldata _config) external;\n\n    function getConfig(uint32 _eid, address _oapp, uint32 _configType) external view returns (bytes memory config);\n\n    function isSupportedEid(uint32 _eid) external view returns (bool);\n\n    // message libs of same major version are compatible\n    function version() external view returns (uint64 major, uint8 minor, uint8 endpointVersion);\n\n    function messageLibType() external view returns (MessageLibType);\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/interfaces/ISendLib.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\nimport { MessagingFee } from \"./ILayerZeroEndpointV2.sol\";\nimport { IMessageLib } from \"./IMessageLib.sol\";\n\nstruct Packet {\n    uint64 nonce;\n    uint32 srcEid;\n    address sender;\n    uint32 dstEid;\n    bytes32 receiver;\n    bytes32 guid;\n    bytes message;\n}\n\ninterface ISendLib is IMessageLib {\n    function send(\n        Packet calldata _packet,\n        bytes calldata _options,\n        bool _payInLzToken\n    ) external returns (MessagingFee memory, bytes memory encodedPacket);\n\n    function quote(\n        Packet calldata _packet,\n        bytes calldata _options,\n        bool _payInLzToken\n    ) external view returns (MessagingFee memory);\n\n    function setTreasury(address _treasury) external;\n\n    function withdrawFee(address _to, uint256 _amount) external;\n\n    function withdrawLzTokenFee(address _lzToken, address _to, uint256 _amount) external;\n}\n"},"@layerzerolabs/lz-evm-protocol-v2/contracts/libs/AddressCast.sol":{"content":"// SPDX-License-Identifier: LZBL-1.2\n\npragma solidity ^0.8.20;\n\nlibrary AddressCast {\n    error AddressCast_InvalidSizeForAddress();\n    error AddressCast_InvalidAddress();\n\n    function toBytes32(bytes calldata _addressBytes) internal pure returns (bytes32 result) {\n        if (_addressBytes.length > 32) revert AddressCast_InvalidAddress();\n        result = bytes32(_addressBytes);\n        unchecked {\n            uint256 offset = 32 - _addressBytes.length;\n            result = result >> (offset * 8);\n        }\n    }\n\n    function toBytes32(address _address) internal pure returns (bytes32 result) {\n        result = bytes32(uint256(uint160(_address)));\n    }\n\n    function toBytes(bytes32 _addressBytes32, uint256 _size) internal pure returns (bytes memory result) {\n        if (_size == 0 || _size > 32) revert AddressCast_InvalidSizeForAddress();\n        result = new bytes(_size);\n        unchecked {\n            uint256 offset = 256 - _size * 8;\n            assembly {\n                mstore(add(result, 32), shl(offset, _addressBytes32))\n            }\n        }\n    }\n\n    function toAddress(bytes32 _addressBytes32) internal pure returns (address result) {\n        result = address(uint160(uint256(_addressBytes32)));\n    }\n\n    function toAddress(bytes calldata _addressBytes) internal pure returns (address result) {\n        if (_addressBytes.length != 20) revert AddressCast_InvalidAddress();\n        result = address(bytes20(_addressBytes));\n    }\n}\n"},"@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/PacketV1Codec.sol":{"content":"// SPDX-License-Identifier: LZBL-1.2\n\npragma solidity ^0.8.20;\n\nimport { Packet } from \"../../interfaces/ISendLib.sol\";\nimport { AddressCast } from \"../../libs/AddressCast.sol\";\n\nlibrary PacketV1Codec {\n    using AddressCast for address;\n    using AddressCast for bytes32;\n\n    uint8 internal constant PACKET_VERSION = 1;\n\n    // header (version + nonce + path)\n    // version\n    uint256 private constant PACKET_VERSION_OFFSET = 0;\n    //    nonce\n    uint256 private constant NONCE_OFFSET = 1;\n    //    path\n    uint256 private constant SRC_EID_OFFSET = 9;\n    uint256 private constant SENDER_OFFSET = 13;\n    uint256 private constant DST_EID_OFFSET = 45;\n    uint256 private constant RECEIVER_OFFSET = 49;\n    // payload (guid + message)\n    uint256 private constant GUID_OFFSET = 81; // keccak256(nonce + path)\n    uint256 private constant MESSAGE_OFFSET = 113;\n\n    function encode(Packet memory _packet) internal pure returns (bytes memory encodedPacket) {\n        encodedPacket = abi.encodePacked(\n            PACKET_VERSION,\n            _packet.nonce,\n            _packet.srcEid,\n            _packet.sender.toBytes32(),\n            _packet.dstEid,\n            _packet.receiver,\n            _packet.guid,\n            _packet.message\n        );\n    }\n\n    function encodePacketHeader(Packet memory _packet) internal pure returns (bytes memory) {\n        return\n            abi.encodePacked(\n                PACKET_VERSION,\n                _packet.nonce,\n                _packet.srcEid,\n                _packet.sender.toBytes32(),\n                _packet.dstEid,\n                _packet.receiver\n            );\n    }\n\n    function encodePayload(Packet memory _packet) internal pure returns (bytes memory) {\n        return abi.encodePacked(_packet.guid, _packet.message);\n    }\n\n    function header(bytes calldata _packet) internal pure returns (bytes calldata) {\n        return _packet[0:GUID_OFFSET];\n    }\n\n    function version(bytes calldata _packet) internal pure returns (uint8) {\n        return uint8(bytes1(_packet[PACKET_VERSION_OFFSET:NONCE_OFFSET]));\n    }\n\n    function nonce(bytes calldata _packet) internal pure returns (uint64) {\n        return uint64(bytes8(_packet[NONCE_OFFSET:SRC_EID_OFFSET]));\n    }\n\n    function srcEid(bytes calldata _packet) internal pure returns (uint32) {\n        return uint32(bytes4(_packet[SRC_EID_OFFSET:SENDER_OFFSET]));\n    }\n\n    function sender(bytes calldata _packet) internal pure returns (bytes32) {\n        return bytes32(_packet[SENDER_OFFSET:DST_EID_OFFSET]);\n    }\n\n    function senderAddressB20(bytes calldata _packet) internal pure returns (address) {\n        return sender(_packet).toAddress();\n    }\n\n    function dstEid(bytes calldata _packet) internal pure returns (uint32) {\n        return uint32(bytes4(_packet[DST_EID_OFFSET:RECEIVER_OFFSET]));\n    }\n\n    function receiver(bytes calldata _packet) internal pure returns (bytes32) {\n        return bytes32(_packet[RECEIVER_OFFSET:GUID_OFFSET]);\n    }\n\n    function receiverB20(bytes calldata _packet) internal pure returns (address) {\n        return receiver(_packet).toAddress();\n    }\n\n    function guid(bytes calldata _packet) internal pure returns (bytes32) {\n        return bytes32(_packet[GUID_OFFSET:MESSAGE_OFFSET]);\n    }\n\n    function message(bytes calldata _packet) internal pure returns (bytes calldata) {\n        return bytes(_packet[MESSAGE_OFFSET:]);\n    }\n\n    function payload(bytes calldata _packet) internal pure returns (bytes calldata) {\n        return bytes(_packet[GUID_OFFSET:]);\n    }\n\n    function payloadHash(bytes calldata _packet) internal pure returns (bytes32) {\n        return keccak256(payload(_packet));\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/IOAppMsgInspector.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\n/**\n * @title IOAppMsgInspector\n * @dev Interface for the OApp Message Inspector, allowing examination of message and options contents.\n */\ninterface IOAppMsgInspector {\n    // Custom error message for inspection failure\n    error InspectionFailed(bytes message, bytes options);\n\n    /**\n     * @notice Allows the inspector to examine LayerZero message contents and optionally throw a revert if invalid.\n     * @param _message The message payload to be inspected.\n     * @param _options Additional options or parameters for inspection.\n     * @return valid A boolean indicating whether the inspection passed (true) or failed (false).\n     *\n     * @dev Optionally done as a revert, OR use the boolean provided to handle the failure.\n     */\n    function inspect(bytes calldata _message, bytes calldata _options) external view returns (bool valid);\n}\n"},"@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppOptionsType3.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Struct representing enforced option parameters.\n */\nstruct EnforcedOptionParam {\n    uint32 eid; // Endpoint ID\n    uint16 msgType; // Message Type\n    bytes options; // Additional options\n}\n\n/**\n * @title IOAppOptionsType3\n * @dev Interface for the OApp with Type 3 Options, allowing the setting and combining of enforced options.\n */\ninterface IOAppOptionsType3 {\n    // Custom error message for invalid options\n    error InvalidOptions(bytes options);\n\n    // Event emitted when enforced options are set\n    event EnforcedOptionSet(EnforcedOptionParam[] _enforcedOptions);\n\n    /**\n     * @notice Sets enforced options for specific endpoint and message type combinations.\n     * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.\n     */\n    function setEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) external;\n\n    /**\n     * @notice Combines options for a given endpoint and message type.\n     * @param _eid The endpoint ID.\n     * @param _msgType The OApp message type.\n     * @param _extraOptions Additional options passed by the caller.\n     * @return options The combination of caller specified options AND enforced options.\n     */\n    function combineOptions(\n        uint32 _eid,\n        uint16 _msgType,\n        bytes calldata _extraOptions\n    ) external view returns (bytes memory options);\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/OAppOptionsType3.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { IOAppOptionsType3, EnforcedOptionParam } from \"../interfaces/IOAppOptionsType3.sol\";\n\n/**\n * @title OAppOptionsType3\n * @dev Abstract contract implementing the IOAppOptionsType3 interface with type 3 options.\n */\nabstract contract OAppOptionsType3 is IOAppOptionsType3, Ownable {\n    uint16 internal constant OPTION_TYPE_3 = 3;\n\n    // @dev The \"msgType\" should be defined in the child contract.\n    mapping(uint32 eid => mapping(uint16 msgType => bytes enforcedOption)) public enforcedOptions;\n\n    /**\n     * @dev Sets the enforced options for specific endpoint and message type combinations.\n     * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.\n     *\n     * @dev Only the owner/admin of the OApp can call this function.\n     * @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc.\n     * @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType.\n     * eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay\n     * if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose().\n     */\n    function setEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) public virtual onlyOwner {\n        _setEnforcedOptions(_enforcedOptions);\n    }\n\n    /**\n     * @dev Sets the enforced options for specific endpoint and message type combinations.\n     * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.\n     *\n     * @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc.\n     * @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType.\n     * eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay\n     * if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose().\n     */\n    function _setEnforcedOptions(EnforcedOptionParam[] memory _enforcedOptions) internal virtual {\n        for (uint256 i = 0; i < _enforcedOptions.length; i++) {\n            // @dev Enforced options are only available for optionType 3, as type 1 and 2 dont support combining.\n            _assertOptionsType3(_enforcedOptions[i].options);\n            enforcedOptions[_enforcedOptions[i].eid][_enforcedOptions[i].msgType] = _enforcedOptions[i].options;\n        }\n\n        emit EnforcedOptionSet(_enforcedOptions);\n    }\n\n    /**\n     * @notice Combines options for a given endpoint and message type.\n     * @param _eid The endpoint ID.\n     * @param _msgType The OAPP message type.\n     * @param _extraOptions Additional options passed by the caller.\n     * @return options The combination of caller specified options AND enforced options.\n     *\n     * @dev If there is an enforced lzReceive option:\n     * - {gasLimit: 200k, msg.value: 1 ether} AND a caller supplies a lzReceive option: {gasLimit: 100k, msg.value: 0.5 ether}\n     * - The resulting options will be {gasLimit: 300k, msg.value: 1.5 ether} when the message is executed on the remote lzReceive() function.\n     * @dev This presence of duplicated options is handled off-chain in the verifier/executor.\n     */\n    function combineOptions(\n        uint32 _eid,\n        uint16 _msgType,\n        bytes calldata _extraOptions\n    ) public view virtual returns (bytes memory) {\n        bytes memory enforced = enforcedOptions[_eid][_msgType];\n\n        // No enforced options, pass whatever the caller supplied, even if it's empty or legacy type 1/2 options.\n        if (enforced.length == 0) return _extraOptions;\n\n        // No caller options, return enforced\n        if (_extraOptions.length == 0) return enforced;\n\n        // @dev If caller provided _extraOptions, must be type 3 as its the ONLY type that can be combined.\n        if (_extraOptions.length >= 2) {\n            _assertOptionsType3(_extraOptions);\n            // @dev Remove the first 2 bytes containing the type from the _extraOptions and combine with enforced.\n            return bytes.concat(enforced, _extraOptions[2:]);\n        }\n\n        // No valid set of options was found.\n        revert InvalidOptions(_extraOptions);\n    }\n\n    /**\n     * @dev Internal function to assert that options are of type 3.\n     * @param _options The options to be checked.\n     */\n    function _assertOptionsType3(bytes memory _options) internal pure virtual {\n        uint16 optionsType;\n        assembly {\n            optionsType := mload(add(_options, 2))\n        }\n        if (optionsType != OPTION_TYPE_3) revert InvalidOptions(_options);\n    }\n}\n"},"@layerzerolabs/oapp-evm/contracts/oapp/OApp.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\n// @dev Import the 'MessagingFee' and 'MessagingReceipt' so it's exposed to OApp implementers\n// solhint-disable-next-line no-unused-import\nimport { OAppSender, MessagingFee, MessagingReceipt } from \"./OAppSender.sol\";\n// @dev Import the 'Origin' so it's exposed to OApp implementers\n// solhint-disable-next-line no-unused-import\nimport { OAppReceiver, Origin } from \"./OAppReceiver.sol\";\nimport { OAppCore } from \"./OAppCore.sol\";\n\n/**\n * @title OApp\n * @dev Abstract contract serving as the base for OApp implementation, combining OAppSender and OAppReceiver functionality.\n */\nabstract contract OApp is OAppSender, OAppReceiver {\n    /**\n     * @dev Constructor to initialize the OApp with the provided endpoint and owner.\n     * @param _endpoint The address of the LOCAL LayerZero endpoint.\n     * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.\n     */\n    constructor(address _endpoint, address _delegate) OAppCore(_endpoint, _delegate) {}\n\n    /**\n     * @notice Retrieves the OApp version information.\n     * @return senderVersion The version of the OAppSender.sol implementation.\n     * @return receiverVersion The version of the OAppReceiver.sol implementation.\n     */\n    function oAppVersion()\n        public\n        pure\n        virtual\n        override(OAppSender, OAppReceiver)\n        returns (uint64 senderVersion, uint64 receiverVersion)\n    {\n        return (SENDER_VERSION, RECEIVER_VERSION);\n    }\n}\n"},"@layerzerolabs/oapp-evm/contracts/oapp/OAppCore.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { IOAppCore, ILayerZeroEndpointV2 } from \"./interfaces/IOAppCore.sol\";\n\n/**\n * @title OAppCore\n * @dev Abstract contract implementing the IOAppCore interface with basic OApp configurations.\n */\nabstract contract OAppCore is IOAppCore, Ownable {\n    // The LayerZero endpoint associated with the given OApp\n    ILayerZeroEndpointV2 public immutable endpoint;\n\n    // Mapping to store peers associated with corresponding endpoints\n    mapping(uint32 eid => bytes32 peer) public peers;\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     * @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     */\n    constructor(address _endpoint, address _delegate) {\n        endpoint = ILayerZeroEndpointV2(_endpoint);\n\n        if (_delegate == address(0)) revert InvalidDelegate();\n        endpoint.setDelegate(_delegate);\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        _setPeer(_eid, _peer);\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 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) internal virtual {\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        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/contracts/oapp/OAppReceiver.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { IOAppReceiver, Origin } from \"./interfaces/IOAppReceiver.sol\";\nimport { OAppCore } from \"./OAppCore.sol\";\n\n/**\n * @title OAppReceiver\n * @dev Abstract contract implementing the ILayerZeroReceiver interface and extending OAppCore for OApp receivers.\n */\nabstract contract OAppReceiver is IOAppReceiver, OAppCore {\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     * @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/contracts/oapp/OAppSender.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 { OAppCore } from \"./OAppCore.sol\";\n\n/**\n * @title OAppSender\n * @dev Abstract contract implementing the OAppSender functionality for sending messages to a LayerZero endpoint.\n */\nabstract contract OAppSender is OAppCore {\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     * @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/precrime/interfaces/IOAppPreCrimeSimulator.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\n// @dev Import the Origin so it's exposed to OAppPreCrimeSimulator implementers.\n// solhint-disable-next-line no-unused-import\nimport { InboundPacket, Origin } from \"../libs/Packet.sol\";\n\n/**\n * @title IOAppPreCrimeSimulator Interface\n * @dev Interface for the preCrime simulation functionality in an OApp.\n */\ninterface IOAppPreCrimeSimulator {\n    // @dev simulation result used in PreCrime implementation\n    error SimulationResult(bytes result);\n    error OnlySelf();\n\n    /**\n     * @dev Emitted when the preCrime contract address is set.\n     * @param preCrimeAddress The address of the preCrime contract.\n     */\n    event PreCrimeSet(address preCrimeAddress);\n\n    /**\n     * @dev Retrieves the address of the preCrime contract implementation.\n     * @return The address of the preCrime contract.\n     */\n    function preCrime() external view returns (address);\n\n    /**\n     * @dev Retrieves the address of the OApp contract.\n     * @return The address of the OApp contract.\n     */\n    function oApp() external view returns (address);\n\n    /**\n     * @dev Sets the preCrime contract address.\n     * @param _preCrime The address of the preCrime contract.\n     */\n    function setPreCrime(address _preCrime) external;\n\n    /**\n     * @dev Mocks receiving a packet, then reverts with a series of data to infer the state/result.\n     * @param _packets An array of LayerZero InboundPacket objects representing received packets.\n     */\n    function lzReceiveAndRevert(InboundPacket[] calldata _packets) external payable;\n\n    /**\n     * @dev checks if the specified peer is considered 'trusted' by the OApp.\n     * @param _eid The endpoint Id to check.\n     * @param _peer The peer to check.\n     * @return Whether the peer passed is considered 'trusted' by the OApp.\n     */\n    function isPeer(uint32 _eid, bytes32 _peer) external view returns (bool);\n}\n"},"@layerzerolabs/oapp-evm/contracts/precrime/interfaces/IPreCrime.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\nstruct PreCrimePeer {\n    uint32 eid;\n    bytes32 preCrime;\n    bytes32 oApp;\n}\n\n// TODO not done yet\ninterface IPreCrime {\n    error OnlyOffChain();\n\n    // for simulate()\n    error PacketOversize(uint256 max, uint256 actual);\n    error PacketUnsorted();\n    error SimulationFailed(bytes reason);\n\n    // for preCrime()\n    error SimulationResultNotFound(uint32 eid);\n    error InvalidSimulationResult(uint32 eid, bytes reason);\n    error CrimeFound(bytes crime);\n\n    function getConfig(bytes[] calldata _packets, uint256[] calldata _packetMsgValues) external returns (bytes memory);\n\n    function simulate(\n        bytes[] calldata _packets,\n        uint256[] calldata _packetMsgValues\n    ) external payable returns (bytes memory);\n\n    function buildSimulationResult() external view returns (bytes memory);\n\n    function preCrime(\n        bytes[] calldata _packets,\n        uint256[] calldata _packetMsgValues,\n        bytes[] calldata _simulations\n    ) external;\n\n    function version() external view returns (uint64 major, uint8 minor);\n}\n"},"@layerzerolabs/oapp-evm/contracts/precrime/libs/Packet.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { Origin } from \"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol\";\nimport { PacketV1Codec } from \"@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/PacketV1Codec.sol\";\n\n/**\n * @title InboundPacket\n * @dev Structure representing an inbound packet received by the contract.\n */\nstruct InboundPacket {\n    Origin origin; // Origin information of the packet.\n    uint32 dstEid; // Destination endpointId of the packet.\n    address receiver; // Receiver address for the packet.\n    bytes32 guid; // Unique identifier of the packet.\n    uint256 value; // msg.value of the packet.\n    address executor; // Executor address for the packet.\n    bytes message; // Message payload of the packet.\n    bytes extraData; // Additional arbitrary data for the packet.\n}\n\n/**\n * @title PacketDecoder\n * @dev Library for decoding LayerZero packets.\n */\nlibrary PacketDecoder {\n    using PacketV1Codec for bytes;\n\n    /**\n     * @dev Decode an inbound packet from the given packet data.\n     * @param _packet The packet data to decode.\n     * @return packet An InboundPacket struct representing the decoded packet.\n     */\n    function decode(bytes calldata _packet) internal pure returns (InboundPacket memory packet) {\n        packet.origin = Origin(_packet.srcEid(), _packet.sender(), _packet.nonce());\n        packet.dstEid = _packet.dstEid();\n        packet.receiver = _packet.receiverB20();\n        packet.guid = _packet.guid();\n        packet.message = _packet.message();\n    }\n\n    /**\n     * @dev Decode multiple inbound packets from the given packet data and associated message values.\n     * @param _packets An array of packet data to decode.\n     * @param _packetMsgValues An array of associated message values for each packet.\n     * @return packets An array of InboundPacket structs representing the decoded packets.\n     */\n    function decode(\n        bytes[] calldata _packets,\n        uint256[] memory _packetMsgValues\n    ) internal pure returns (InboundPacket[] memory packets) {\n        packets = new InboundPacket[](_packets.length);\n        for (uint256 i = 0; i < _packets.length; i++) {\n            bytes calldata packet = _packets[i];\n            packets[i] = PacketDecoder.decode(packet);\n            // @dev Allows the verifier to specify the msg.value that gets passed in lzReceive.\n            packets[i].value = _packetMsgValues[i];\n        }\n    }\n}\n"},"@layerzerolabs/oapp-evm/contracts/precrime/OAppPreCrimeSimulator.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { IPreCrime } from \"./interfaces/IPreCrime.sol\";\nimport { IOAppPreCrimeSimulator, InboundPacket, Origin } from \"./interfaces/IOAppPreCrimeSimulator.sol\";\n\n/**\n * @title OAppPreCrimeSimulator\n * @dev Abstract contract serving as the base for preCrime simulation functionality in an OApp.\n */\nabstract contract OAppPreCrimeSimulator is IOAppPreCrimeSimulator, Ownable {\n    // The address of the preCrime implementation.\n    address public preCrime;\n\n    /**\n     * @dev Retrieves the address of the OApp contract.\n     * @return The address of the OApp contract.\n     *\n     * @dev The simulator contract is the base contract for the OApp by default.\n     * @dev If the simulator is a separate contract, override this function.\n     */\n    function oApp() external view virtual returns (address) {\n        return address(this);\n    }\n\n    /**\n     * @dev Sets the preCrime contract address.\n     * @param _preCrime The address of the preCrime contract.\n     */\n    function setPreCrime(address _preCrime) public virtual onlyOwner {\n        preCrime = _preCrime;\n        emit PreCrimeSet(_preCrime);\n    }\n\n    /**\n     * @dev Interface for pre-crime simulations. Always reverts at the end with the simulation results.\n     * @param _packets An array of InboundPacket objects representing received packets to be delivered.\n     *\n     * @dev WARNING: MUST revert at the end with the simulation results.\n     * @dev Gives the preCrime implementation the ability to mock sending packets to the lzReceive function,\n     * WITHOUT actually executing them.\n     */\n    function lzReceiveAndRevert(InboundPacket[] calldata _packets) public payable virtual {\n        for (uint256 i = 0; i < _packets.length; i++) {\n            InboundPacket calldata packet = _packets[i];\n\n            // Ignore packets that are not from trusted peers.\n            if (!isPeer(packet.origin.srcEid, packet.origin.sender)) continue;\n\n            // @dev Because a verifier is calling this function, it doesnt have access to executor params:\n            //  - address _executor\n            //  - bytes calldata _extraData\n            // preCrime will NOT work for OApps that rely on these two parameters inside of their _lzReceive().\n            // They are instead stubbed to default values, address(0) and bytes(\"\")\n            // @dev Calling this.lzReceiveSimulate removes ability for assembly return 0 callstack exit,\n            // which would cause the revert to be ignored.\n            this.lzReceiveSimulate{ value: packet.value }(\n                packet.origin,\n                packet.guid,\n                packet.message,\n                packet.executor,\n                packet.extraData\n            );\n        }\n\n        // @dev Revert with the simulation results. msg.sender must implement IPreCrime.buildSimulationResult().\n        revert SimulationResult(IPreCrime(msg.sender).buildSimulationResult());\n    }\n\n    /**\n     * @dev Is effectively an internal function because msg.sender must be address(this).\n     * Allows resetting the call stack for 'internal' calls.\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 of the packet.\n     * @param _message The message payload of the packet.\n     * @param _executor The executor address for the packet.\n     * @param _extraData Additional data for the packet.\n     */\n    function lzReceiveSimulate(\n        Origin calldata _origin,\n        bytes32 _guid,\n        bytes calldata _message,\n        address _executor,\n        bytes calldata _extraData\n    ) external payable virtual {\n        // @dev Ensure ONLY can be called 'internally'.\n        if (msg.sender != address(this)) revert OnlySelf();\n        _lzReceiveSimulate(_origin, _guid, _message, _executor, _extraData);\n    }\n\n    /**\n     * @dev Internal function to handle the OAppPreCrimeSimulator simulated receive.\n     * @param _origin The origin information.\n     *  - srcEid: The source chain endpoint ID.\n     *  - sender: The sender address from the src chain.\n     *  - nonce: The nonce of the LayerZero message.\n     * @param _guid The GUID of the LayerZero message.\n     * @param _message The LayerZero message.\n     * @param _executor The address of the off-chain executor.\n     * @param _extraData Arbitrary data passed by the msg executor.\n     *\n     * @dev Enables the preCrime simulator to mock sending lzReceive() messages,\n     * routes the msg down from the OAppPreCrimeSimulator, and back up to the OAppReceiver.\n     */\n    function _lzReceiveSimulate(\n        Origin calldata _origin,\n        bytes32 _guid,\n        bytes calldata _message,\n        address _executor,\n        bytes calldata _extraData\n    ) internal virtual;\n\n    /**\n     * @dev checks if the specified peer is considered 'trusted' by the OApp.\n     * @param _eid The endpoint Id to check.\n     * @param _peer The peer to check.\n     * @return Whether the peer passed is considered 'trusted' by the OApp.\n     */\n    function isPeer(uint32 _eid, bytes32 _peer) public view virtual returns (bool);\n}\n"},"@layerzerolabs/oft-evm/contracts/interfaces/IOFT.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { MessagingReceipt, MessagingFee } from \"@layerzerolabs/oapp-evm/contracts/oapp/OAppSender.sol\";\n\n/**\n * @dev Struct representing token parameters for the OFT send() operation.\n */\nstruct SendParam {\n    uint32 dstEid; // Destination endpoint ID.\n    bytes32 to; // Recipient address.\n    uint256 amountLD; // Amount to send in local decimals.\n    uint256 minAmountLD; // Minimum amount to send in local decimals.\n    bytes extraOptions; // Additional options supplied by the caller to be used in the LayerZero message.\n    bytes composeMsg; // The composed message for the send() operation.\n    bytes oftCmd; // The OFT command to be executed, unused in default OFT implementations.\n}\n\n/**\n * @dev Struct representing OFT limit information.\n * @dev These amounts can change dynamically and are up the specific oft implementation.\n */\nstruct OFTLimit {\n    uint256 minAmountLD; // Minimum amount in local decimals that can be sent to the recipient.\n    uint256 maxAmountLD; // Maximum amount in local decimals that can be sent to the recipient.\n}\n\n/**\n * @dev Struct representing OFT receipt information.\n */\nstruct OFTReceipt {\n    uint256 amountSentLD; // Amount of tokens ACTUALLY debited from the sender in local decimals.\n    // @dev In non-default implementations, the amountReceivedLD COULD differ from this value.\n    uint256 amountReceivedLD; // Amount of tokens to be received on the remote side.\n}\n\n/**\n * @dev Struct representing OFT fee details.\n * @dev Future proof mechanism to provide a standardized way to communicate fees to things like a UI.\n */\nstruct OFTFeeDetail {\n    int256 feeAmountLD; // Amount of the fee in local decimals.\n    string description; // Description of the fee.\n}\n\n/**\n * @title IOFT\n * @dev Interface for the OftChain (OFT) token.\n * @dev Does not inherit ERC20 to accommodate usage by OFTAdapter as well.\n * @dev This specific interface ID is '0x02e49c2c'.\n */\ninterface IOFT {\n    // Custom error messages\n    error InvalidLocalDecimals();\n    error SlippageExceeded(uint256 amountLD, uint256 minAmountLD);\n\n    // Events\n    event OFTSent(\n        bytes32 indexed guid, // GUID of the OFT message.\n        uint32 dstEid, // Destination Endpoint ID.\n        address indexed fromAddress, // Address of the sender on the src chain.\n        uint256 amountSentLD, // Amount of tokens sent in local decimals.\n        uint256 amountReceivedLD // Amount of tokens received in local decimals.\n    );\n    event OFTReceived(\n        bytes32 indexed guid, // GUID of the OFT message.\n        uint32 srcEid, // Source Endpoint ID.\n        address indexed toAddress, // Address of the recipient on the dst chain.\n        uint256 amountReceivedLD // Amount of tokens received in local decimals.\n    );\n\n    /**\n     * @notice Retrieves interfaceID and the version of the OFT.\n     * @return interfaceId The interface ID.\n     * @return version The version.\n     *\n     * @dev interfaceId: This specific interface ID is '0x02e49c2c'.\n     * @dev version: Indicates a cross-chain compatible msg encoding with other OFTs.\n     * @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented.\n     * ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1)\n     */\n    function oftVersion() external view returns (bytes4 interfaceId, uint64 version);\n\n    /**\n     * @notice Retrieves the address of the token associated with the OFT.\n     * @return token The address of the ERC20 token implementation.\n     */\n    function token() external view returns (address);\n\n    /**\n     * @notice Indicates whether the OFT contract requires approval of the 'token()' to send.\n     * @return requiresApproval Needs approval of the underlying token implementation.\n     *\n     * @dev Allows things like wallet implementers to determine integration requirements,\n     * without understanding the underlying token implementation.\n     */\n    function approvalRequired() external view returns (bool);\n\n    /**\n     * @notice Retrieves the shared decimals of the OFT.\n     * @return sharedDecimals The shared decimals of the OFT.\n     */\n    function sharedDecimals() external view returns (uint8);\n\n    /**\n     * @notice Provides a quote for OFT-related operations.\n     * @param _sendParam The parameters for the send operation.\n     * @return limit The OFT limit information.\n     * @return oftFeeDetails The details of OFT fees.\n     * @return receipt The OFT receipt information.\n     */\n    function quoteOFT(\n        SendParam calldata _sendParam\n    ) external view returns (OFTLimit memory, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory);\n\n    /**\n     * @notice Provides a quote for the send() operation.\n     * @param _sendParam The parameters for the send() operation.\n     * @param _payInLzToken Flag indicating whether the caller is paying in the LZ token.\n     * @return fee The calculated LayerZero messaging fee from the send() operation.\n     *\n     * @dev MessagingFee: LayerZero msg fee\n     *  - nativeFee: The native fee.\n     *  - lzTokenFee: The lzToken fee.\n     */\n    function quoteSend(SendParam calldata _sendParam, bool _payInLzToken) external view returns (MessagingFee memory);\n\n    /**\n     * @notice Executes the send() operation.\n     * @param _sendParam The parameters for the send operation.\n     * @param _fee The fee information supplied by the caller.\n     *      - nativeFee: The native fee.\n     *      - lzTokenFee: The lzToken fee.\n     * @param _refundAddress The address to receive any excess funds from fees etc. on the src.\n     * @return receipt The LayerZero messaging receipt from the send() operation.\n     * @return oftReceipt The OFT receipt information.\n     *\n     * @dev MessagingReceipt: LayerZero msg receipt\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 send(\n        SendParam calldata _sendParam,\n        MessagingFee calldata _fee,\n        address _refundAddress\n    ) external payable returns (MessagingReceipt memory, OFTReceipt memory);\n}\n"},"@layerzerolabs/oft-evm/contracts/libs/OFTComposeMsgCodec.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nlibrary OFTComposeMsgCodec {\n    // Offset constants for decoding composed messages\n    uint8 private constant NONCE_OFFSET = 8;\n    uint8 private constant SRC_EID_OFFSET = 12;\n    uint8 private constant AMOUNT_LD_OFFSET = 44;\n    uint8 private constant COMPOSE_FROM_OFFSET = 76;\n\n    /**\n     * @dev Encodes a OFT composed message.\n     * @param _nonce The nonce value.\n     * @param _srcEid The source endpoint ID.\n     * @param _amountLD The amount in local decimals.\n     * @param _composeMsg The composed message.\n     * @return _msg The encoded Composed message.\n     */\n    function encode(\n        uint64 _nonce,\n        uint32 _srcEid,\n        uint256 _amountLD,\n        bytes memory _composeMsg // 0x[composeFrom][composeMsg]\n    ) internal pure returns (bytes memory _msg) {\n        _msg = abi.encodePacked(_nonce, _srcEid, _amountLD, _composeMsg);\n    }\n\n    /**\n     * @dev Retrieves the nonce for the composed message.\n     * @param _msg The message.\n     * @return The nonce value.\n     */\n    function nonce(bytes calldata _msg) internal pure returns (uint64) {\n        return uint64(bytes8(_msg[:NONCE_OFFSET]));\n    }\n\n    /**\n     * @dev Retrieves the source endpoint ID for the composed message.\n     * @param _msg The message.\n     * @return The source endpoint ID.\n     */\n    function srcEid(bytes calldata _msg) internal pure returns (uint32) {\n        return uint32(bytes4(_msg[NONCE_OFFSET:SRC_EID_OFFSET]));\n    }\n\n    /**\n     * @dev Retrieves the amount in local decimals from the composed message.\n     * @param _msg The message.\n     * @return The amount in local decimals.\n     */\n    function amountLD(bytes calldata _msg) internal pure returns (uint256) {\n        return uint256(bytes32(_msg[SRC_EID_OFFSET:AMOUNT_LD_OFFSET]));\n    }\n\n    /**\n     * @dev Retrieves the composeFrom value from the composed message.\n     * @param _msg The message.\n     * @return The composeFrom value.\n     */\n    function composeFrom(bytes calldata _msg) internal pure returns (bytes32) {\n        return bytes32(_msg[AMOUNT_LD_OFFSET:COMPOSE_FROM_OFFSET]);\n    }\n\n    /**\n     * @dev Retrieves the composed message.\n     * @param _msg The message.\n     * @return The composed message.\n     */\n    function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) {\n        return _msg[COMPOSE_FROM_OFFSET:];\n    }\n\n    /**\n     * @dev Converts an address to bytes32.\n     * @param _addr The address to convert.\n     * @return The bytes32 representation of the address.\n     */\n    function addressToBytes32(address _addr) internal pure returns (bytes32) {\n        return bytes32(uint256(uint160(_addr)));\n    }\n\n    /**\n     * @dev Converts bytes32 to an address.\n     * @param _b The bytes32 value to convert.\n     * @return The address representation of bytes32.\n     */\n    function bytes32ToAddress(bytes32 _b) internal pure returns (address) {\n        return address(uint160(uint256(_b)));\n    }\n}\n"},"@layerzerolabs/oft-evm/contracts/libs/OFTMsgCodec.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nlibrary OFTMsgCodec {\n    // Offset constants for encoding and decoding OFT messages\n    uint8 private constant SEND_TO_OFFSET = 32;\n    uint8 private constant SEND_AMOUNT_SD_OFFSET = 40;\n\n    /**\n     * @dev Encodes an OFT LayerZero message.\n     * @param _sendTo The recipient address.\n     * @param _amountShared The amount in shared decimals.\n     * @param _composeMsg The composed message.\n     * @return _msg The encoded message.\n     * @return hasCompose A boolean indicating whether the message has a composed payload.\n     */\n    function encode(\n        bytes32 _sendTo,\n        uint64 _amountShared,\n        bytes memory _composeMsg\n    ) internal view returns (bytes memory _msg, bool hasCompose) {\n        hasCompose = _composeMsg.length > 0;\n        // @dev Remote chains will want to know the composed function caller ie. msg.sender on the src.\n        _msg = hasCompose\n            ? abi.encodePacked(_sendTo, _amountShared, addressToBytes32(msg.sender), _composeMsg)\n            : abi.encodePacked(_sendTo, _amountShared);\n    }\n\n    /**\n     * @dev Checks if the OFT message is composed.\n     * @param _msg The OFT message.\n     * @return A boolean indicating whether the message is composed.\n     */\n    function isComposed(bytes calldata _msg) internal pure returns (bool) {\n        return _msg.length > SEND_AMOUNT_SD_OFFSET;\n    }\n\n    /**\n     * @dev Retrieves the recipient address from the OFT message.\n     * @param _msg The OFT message.\n     * @return The recipient address.\n     */\n    function sendTo(bytes calldata _msg) internal pure returns (bytes32) {\n        return bytes32(_msg[:SEND_TO_OFFSET]);\n    }\n\n    /**\n     * @dev Retrieves the amount in shared decimals from the OFT message.\n     * @param _msg The OFT message.\n     * @return The amount in shared decimals.\n     */\n    function amountSD(bytes calldata _msg) internal pure returns (uint64) {\n        return uint64(bytes8(_msg[SEND_TO_OFFSET:SEND_AMOUNT_SD_OFFSET]));\n    }\n\n    /**\n     * @dev Retrieves the composed message from the OFT message.\n     * @param _msg The OFT message.\n     * @return The composed message.\n     */\n    function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) {\n        return _msg[SEND_AMOUNT_SD_OFFSET:];\n    }\n\n    /**\n     * @dev Converts an address to bytes32.\n     * @param _addr The address to convert.\n     * @return The bytes32 representation of the address.\n     */\n    function addressToBytes32(address _addr) internal pure returns (bytes32) {\n        return bytes32(uint256(uint160(_addr)));\n    }\n\n    /**\n     * @dev Converts bytes32 to an address.\n     * @param _b The bytes32 value to convert.\n     * @return The address representation of bytes32.\n     */\n    function bytes32ToAddress(bytes32 _b) internal pure returns (address) {\n        return address(uint160(uint256(_b)));\n    }\n}\n"},"@layerzerolabs/oft-evm/contracts/OFTAdapter.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { IERC20Metadata, IERC20 } from \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { IOFT, OFTCore } from \"./OFTCore.sol\";\n\n/**\n * @title OFTAdapter Contract\n * @dev OFTAdapter is a contract that adapts an ERC-20 token to the OFT functionality.\n *\n * @dev For existing ERC20 tokens, this can be used to convert the token to crosschain compatibility.\n * @dev WARNING: ONLY 1 of these should exist for a given global mesh,\n * unless you make a NON-default implementation of OFT and needs to be done very carefully.\n * @dev WARNING: The default OFTAdapter implementation assumes LOSSLESS transfers, ie. 1 token in, 1 token out.\n * IF the 'innerToken' applies something like a transfer fee, the default will NOT work...\n * a pre/post balance check will need to be done to calculate the amountSentLD/amountReceivedLD.\n */\nabstract contract OFTAdapter is OFTCore {\n    using SafeERC20 for IERC20;\n\n    IERC20 internal immutable innerToken;\n\n    /**\n     * @dev Constructor for the OFTAdapter contract.\n     * @param _token The address of the ERC-20 token to be adapted.\n     * @param _lzEndpoint The LayerZero endpoint address.\n     * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.\n     */\n    constructor(\n        address _token,\n        address _lzEndpoint,\n        address _delegate\n    ) OFTCore(IERC20Metadata(_token).decimals(), _lzEndpoint, _delegate) {\n        innerToken = IERC20(_token);\n    }\n\n    /**\n     * @dev Retrieves the address of the underlying ERC20 implementation.\n     * @return The address of the adapted ERC-20 token.\n     *\n     * @dev In the case of OFTAdapter, address(this) and erc20 are NOT the same contract.\n     */\n    function token() public view returns (address) {\n        return address(innerToken);\n    }\n\n    /**\n     * @notice Indicates whether the OFT contract requires approval of the 'token()' to send.\n     * @return requiresApproval Needs approval of the underlying token implementation.\n     *\n     * @dev In the case of default OFTAdapter, approval is required.\n     * @dev In non-default OFTAdapter contracts with something like mint and burn privileges, it would NOT need approval.\n     */\n    function approvalRequired() external pure virtual returns (bool) {\n        return true;\n    }\n\n    /**\n     * @dev Locks tokens from the sender's specified balance in this contract.\n     * @param _from The address to debit from.\n     * @param _amountLD The amount of tokens to send in local decimals.\n     * @param _minAmountLD The minimum amount to send in local decimals.\n     * @param _dstEid The destination chain ID.\n     * @return amountSentLD The amount sent in local decimals.\n     * @return amountReceivedLD The amount received in local decimals on the remote.\n     *\n     * @dev msg.sender will need to approve this _amountLD of tokens to be locked inside of the contract.\n     * @dev WARNING: The default OFTAdapter implementation assumes LOSSLESS transfers, ie. 1 token in, 1 token out.\n     * IF the 'innerToken' applies something like a transfer fee, the default will NOT work...\n     * a pre/post balance check will need to be done to calculate the amountReceivedLD.\n     */\n    function _debit(\n        address _from,\n        uint256 _amountLD,\n        uint256 _minAmountLD,\n        uint32 _dstEid\n    ) internal virtual override returns (uint256 amountSentLD, uint256 amountReceivedLD) {\n        (amountSentLD, amountReceivedLD) = _debitView(_amountLD, _minAmountLD, _dstEid);\n        // @dev Lock tokens by moving them into this contract from the caller.\n        innerToken.safeTransferFrom(_from, address(this), amountSentLD);\n    }\n\n    /**\n     * @dev Credits tokens to the specified address.\n     * @param _to The address to credit the tokens to.\n     * @param _amountLD The amount of tokens to credit in local decimals.\n     * @dev _srcEid The source chain ID.\n     * @return amountReceivedLD The amount of tokens ACTUALLY received in local decimals.\n     *\n     * @dev WARNING: The default OFTAdapter implementation assumes LOSSLESS transfers, ie. 1 token in, 1 token out.\n     * IF the 'innerToken' applies something like a transfer fee, the default will NOT work...\n     * a pre/post balance check will need to be done to calculate the amountReceivedLD.\n     */\n    function _credit(\n        address _to,\n        uint256 _amountLD,\n        uint32 /*_srcEid*/\n    ) internal virtual override returns (uint256 amountReceivedLD) {\n        // @dev Unlock the tokens and transfer to the recipient.\n        innerToken.safeTransfer(_to, _amountLD);\n        // @dev In the case of NON-default OFTAdapter, the amountLD MIGHT not be == amountReceivedLD.\n        return _amountLD;\n    }\n}\n"},"@layerzerolabs/oft-evm/contracts/OFTCore.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { OApp, Origin } from \"@layerzerolabs/oapp-evm/contracts/oapp/OApp.sol\";\nimport { OAppOptionsType3 } from \"@layerzerolabs/oapp-evm/contracts/oapp/libs/OAppOptionsType3.sol\";\nimport { IOAppMsgInspector } from \"@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppMsgInspector.sol\";\n\nimport { OAppPreCrimeSimulator } from \"@layerzerolabs/oapp-evm/contracts/precrime/OAppPreCrimeSimulator.sol\";\n\nimport { IOFT, SendParam, OFTLimit, OFTReceipt, OFTFeeDetail, MessagingReceipt, MessagingFee } from \"./interfaces/IOFT.sol\";\nimport { OFTMsgCodec } from \"./libs/OFTMsgCodec.sol\";\nimport { OFTComposeMsgCodec } from \"./libs/OFTComposeMsgCodec.sol\";\n\n/**\n * @title OFTCore\n * @dev Abstract contract for the OftChain (OFT) token.\n */\nabstract contract OFTCore is IOFT, OApp, OAppPreCrimeSimulator, OAppOptionsType3 {\n    using OFTMsgCodec for bytes;\n    using OFTMsgCodec for bytes32;\n\n    // @notice Provides a conversion rate when swapping between denominations of SD and LD\n    //      - shareDecimals == SD == shared Decimals\n    //      - localDecimals == LD == local decimals\n    // @dev Considers that tokens have different decimal amounts on various chains.\n    // @dev eg.\n    //  For a token\n    //      - locally with 4 decimals --> 1.2345 => uint(12345)\n    //      - remotely with 2 decimals --> 1.23 => uint(123)\n    //      - The conversion rate would be 10 ** (4 - 2) = 100\n    //  @dev If you want to send 1.2345 -> (uint 12345), you CANNOT represent that value on the remote,\n    //  you can only display 1.23 -> uint(123).\n    //  @dev To preserve the dust that would otherwise be lost on that conversion,\n    //  we need to unify a denomination that can be represented on ALL chains inside of the OFT mesh\n    uint256 public immutable decimalConversionRate;\n\n    // @notice Msg types that are used to identify the various OFT operations.\n    // @dev This can be extended in child contracts for non-default oft operations\n    // @dev These values are used in things like combineOptions() in OAppOptionsType3.sol.\n    uint16 public constant SEND = 1;\n    uint16 public constant SEND_AND_CALL = 2;\n\n    // Address of an optional contract to inspect both 'message' and 'options'\n    address public msgInspector;\n    event MsgInspectorSet(address inspector);\n\n    /**\n     * @dev Constructor.\n     * @param _localDecimals The decimals of the token on the local chain (this chain).\n     * @param _endpoint The address of the LayerZero endpoint.\n     * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.\n     */\n    constructor(uint8 _localDecimals, address _endpoint, address _delegate) OApp(_endpoint, _delegate) {\n        if (_localDecimals < sharedDecimals()) revert InvalidLocalDecimals();\n        decimalConversionRate = 10 ** (_localDecimals - sharedDecimals());\n    }\n\n    /**\n     * @notice Retrieves interfaceID and the version of the OFT.\n     * @return interfaceId The interface ID.\n     * @return version The version.\n     *\n     * @dev interfaceId: This specific interface ID is '0x02e49c2c'.\n     * @dev version: Indicates a cross-chain compatible msg encoding with other OFTs.\n     * @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented.\n     * ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1)\n     */\n    function oftVersion() external pure virtual returns (bytes4 interfaceId, uint64 version) {\n        return (type(IOFT).interfaceId, 1);\n    }\n\n    /**\n     * @dev Retrieves the shared decimals of the OFT.\n     * @return The shared decimals of the OFT.\n     *\n     * @dev Sets an implicit cap on the amount of tokens, over uint64.max() will need some sort of outbound cap / totalSupply cap\n     * Lowest common decimal denominator between chains.\n     * Defaults to 6 decimal places to provide up to 18,446,744,073,709.551615 units (max uint64).\n     * For tokens exceeding this totalSupply(), they will need to override the sharedDecimals function with something smaller.\n     * ie. 4 sharedDecimals would be 1,844,674,407,370,955.1615\n     */\n    function sharedDecimals() public view virtual returns (uint8) {\n        return 6;\n    }\n\n    /**\n     * @dev Sets the message inspector address for the OFT.\n     * @param _msgInspector The address of the message inspector.\n     *\n     * @dev This is an optional contract that can be used to inspect both 'message' and 'options'.\n     * @dev Set it to address(0) to disable it, or set it to a contract address to enable it.\n     */\n    function setMsgInspector(address _msgInspector) public virtual onlyOwner {\n        msgInspector = _msgInspector;\n        emit MsgInspectorSet(_msgInspector);\n    }\n\n    /**\n     * @notice Provides a quote for OFT-related operations.\n     * @param _sendParam The parameters for the send operation.\n     * @return oftLimit The OFT limit information.\n     * @return oftFeeDetails The details of OFT fees.\n     * @return oftReceipt The OFT receipt information.\n     */\n    function quoteOFT(\n        SendParam calldata _sendParam\n    )\n        external\n        view\n        virtual\n        returns (OFTLimit memory oftLimit, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory oftReceipt)\n    {\n        uint256 minAmountLD = 0; // Unused in the default implementation.\n        uint256 maxAmountLD = type(uint64).max; // Unused in the default implementation.\n        oftLimit = OFTLimit(minAmountLD, maxAmountLD);\n\n        // Unused in the default implementation; reserved for future complex fee details.\n        oftFeeDetails = new OFTFeeDetail[](0);\n\n        // @dev This is the same as the send() operation, but without the actual send.\n        // - amountSentLD is the amount in local decimals that would be sent from the sender.\n        // - amountReceivedLD is the amount in local decimals that will be credited to the recipient on the remote OFT instance.\n        // @dev The amountSentLD MIGHT not equal the amount the user actually receives. HOWEVER, the default does.\n        (uint256 amountSentLD, uint256 amountReceivedLD) = _debitView(\n            _sendParam.amountLD,\n            _sendParam.minAmountLD,\n            _sendParam.dstEid\n        );\n        oftReceipt = OFTReceipt(amountSentLD, amountReceivedLD);\n    }\n\n    /**\n     * @notice Provides a quote for the send() operation.\n     * @param _sendParam The parameters for the send() operation.\n     * @param _payInLzToken Flag indicating whether the caller is paying in the LZ token.\n     * @return msgFee The calculated LayerZero messaging fee from the send() operation.\n     *\n     * @dev MessagingFee: LayerZero msg fee\n     *  - nativeFee: The native fee.\n     *  - lzTokenFee: The lzToken fee.\n     */\n    function quoteSend(\n        SendParam calldata _sendParam,\n        bool _payInLzToken\n    ) external view virtual returns (MessagingFee memory msgFee) {\n        // @dev mock the amount to receive, this is the same operation used in the send().\n        // The quote is as similar as possible to the actual send() operation.\n        (, uint256 amountReceivedLD) = _debitView(_sendParam.amountLD, _sendParam.minAmountLD, _sendParam.dstEid);\n\n        // @dev Builds the options and OFT message to quote in the endpoint.\n        (bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam, amountReceivedLD);\n\n        // @dev Calculates the LayerZero fee for the send() operation.\n        return _quote(_sendParam.dstEid, message, options, _payInLzToken);\n    }\n\n    /**\n     * @dev Executes the send operation.\n     * @param _sendParam The parameters for the send operation.\n     * @param _fee The calculated fee for the send() operation.\n     *      - nativeFee: The native fee.\n     *      - lzTokenFee: The lzToken fee.\n     * @param _refundAddress The address to receive any excess funds.\n     * @return msgReceipt The receipt for the send operation.\n     * @return oftReceipt The OFT receipt information.\n     *\n     * @dev MessagingReceipt: LayerZero msg receipt\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 send(\n        SendParam calldata _sendParam,\n        MessagingFee calldata _fee,\n        address _refundAddress\n    ) external payable virtual returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt) {\n        return _send(_sendParam, _fee, _refundAddress);\n    }\n\n    /**\n     * @dev Internal function to execute the send operation.\n     * @param _sendParam The parameters for the send operation.\n     * @param _fee The calculated fee for the send() operation.\n     *      - nativeFee: The native fee.\n     *      - lzTokenFee: The lzToken fee.\n     * @param _refundAddress The address to receive any excess funds.\n     * @return msgReceipt The receipt for the send operation.\n     * @return oftReceipt The OFT receipt information.\n     *\n     * @dev MessagingReceipt: LayerZero msg receipt\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 _send(\n        SendParam calldata _sendParam,\n        MessagingFee calldata _fee,\n        address _refundAddress\n    ) internal virtual returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt) {\n        // @dev Applies the token transfers regarding this send() operation.\n        // - amountSentLD is the amount in local decimals that was ACTUALLY sent/debited from the sender.\n        // - amountReceivedLD is the amount in local decimals that will be received/credited to the recipient on the remote OFT instance.\n        (uint256 amountSentLD, uint256 amountReceivedLD) = _debit(\n            msg.sender,\n            _sendParam.amountLD,\n            _sendParam.minAmountLD,\n            _sendParam.dstEid\n        );\n\n        // @dev Builds the options and OFT message to quote in the endpoint.\n        (bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam, amountReceivedLD);\n\n        // @dev Sends the message to the LayerZero endpoint and returns the LayerZero msg receipt.\n        msgReceipt = _lzSend(_sendParam.dstEid, message, options, _fee, _refundAddress);\n        // @dev Formulate the OFT receipt.\n        oftReceipt = OFTReceipt(amountSentLD, amountReceivedLD);\n\n        emit OFTSent(msgReceipt.guid, _sendParam.dstEid, msg.sender, amountSentLD, amountReceivedLD);\n    }\n\n    /**\n     * @dev Internal function to build the message and options.\n     * @param _sendParam The parameters for the send() operation.\n     * @param _amountLD The amount in local decimals.\n     * @return message The encoded message.\n     * @return options The encoded options.\n     */\n    function _buildMsgAndOptions(\n        SendParam calldata _sendParam,\n        uint256 _amountLD\n    ) internal view virtual returns (bytes memory message, bytes memory options) {\n        bool hasCompose;\n        // @dev This generated message has the msg.sender encoded into the payload so the remote knows who the caller is.\n        (message, hasCompose) = OFTMsgCodec.encode(\n            _sendParam.to,\n            _toSD(_amountLD),\n            // @dev Must be include a non empty bytes if you want to compose, EVEN if you dont need it on the remote.\n            // EVEN if you dont require an arbitrary payload to be sent... eg. '0x01'\n            _sendParam.composeMsg\n        );\n        // @dev Change the msg type depending if its composed or not.\n        uint16 msgType = hasCompose ? SEND_AND_CALL : SEND;\n        // @dev Combine the callers _extraOptions with the enforced options via the OAppOptionsType3.\n        options = combineOptions(_sendParam.dstEid, msgType, _sendParam.extraOptions);\n\n        // @dev Optionally inspect the message and options depending if the OApp owner has set a msg inspector.\n        // @dev If it fails inspection, needs to revert in the implementation. ie. does not rely on return boolean\n        address inspector = msgInspector; // caches the msgInspector to avoid potential double storage read\n        if (inspector != address(0)) IOAppMsgInspector(inspector).inspect(message, options);\n    }\n\n    /**\n     * @dev Internal function to handle the receive on the LayerZero endpoint.\n     * @param _origin The origin information.\n     *  - srcEid: The source chain endpoint ID.\n     *  - sender: The sender address from the src chain.\n     *  - nonce: The nonce of the LayerZero message.\n     * @param _guid The unique identifier for the received LayerZero message.\n     * @param _message The encoded message.\n     * @dev _executor The address of the executor.\n     * @dev _extraData Additional data.\n     */\n    function _lzReceive(\n        Origin calldata _origin,\n        bytes32 _guid,\n        bytes calldata _message,\n        address /*_executor*/, // @dev unused in the default implementation.\n        bytes calldata /*_extraData*/ // @dev unused in the default implementation.\n    ) internal virtual override {\n        // @dev The src sending chain doesnt know the address length on this chain (potentially non-evm)\n        // Thus everything is bytes32() encoded in flight.\n        address toAddress = _message.sendTo().bytes32ToAddress();\n        // @dev Credit the amountLD to the recipient and return the ACTUAL amount the recipient received in local decimals\n        uint256 amountReceivedLD = _credit(toAddress, _toLD(_message.amountSD()), _origin.srcEid);\n\n        if (_message.isComposed()) {\n            // @dev Proprietary composeMsg format for the OFT.\n            bytes memory composeMsg = OFTComposeMsgCodec.encode(\n                _origin.nonce,\n                _origin.srcEid,\n                amountReceivedLD,\n                _message.composeMsg()\n            );\n\n            // @dev Stores the lzCompose payload that will be executed in a separate tx.\n            // Standardizes functionality for executing arbitrary contract invocation on some non-evm chains.\n            // @dev The off-chain executor will listen and process the msg based on the src-chain-callers compose options passed.\n            // @dev The index is used when a OApp needs to compose multiple msgs on lzReceive.\n            // For default OFT implementation there is only 1 compose msg per lzReceive, thus its always 0.\n            endpoint.sendCompose(toAddress, _guid, 0 /* the index of the composed message*/, composeMsg);\n        }\n\n        emit OFTReceived(_guid, _origin.srcEid, toAddress, amountReceivedLD);\n    }\n\n    /**\n     * @dev Internal function to handle the OAppPreCrimeSimulator simulated receive.\n     * @param _origin The origin information.\n     *  - srcEid: The source chain endpoint ID.\n     *  - sender: The sender address from the src chain.\n     *  - nonce: The nonce of the LayerZero message.\n     * @param _guid The unique identifier for the received LayerZero message.\n     * @param _message The LayerZero message.\n     * @param _executor The address of the off-chain executor.\n     * @param _extraData Arbitrary data passed by the msg executor.\n     *\n     * @dev Enables the preCrime simulator to mock sending lzReceive() messages,\n     * routes the msg down from the OAppPreCrimeSimulator, and back up to the OAppReceiver.\n     */\n    function _lzReceiveSimulate(\n        Origin calldata _origin,\n        bytes32 _guid,\n        bytes calldata _message,\n        address _executor,\n        bytes calldata _extraData\n    ) internal virtual override {\n        _lzReceive(_origin, _guid, _message, _executor, _extraData);\n    }\n\n    /**\n     * @dev Check if the peer is considered 'trusted' by the OApp.\n     * @param _eid The endpoint ID to check.\n     * @param _peer The peer to check.\n     * @return Whether the peer passed is considered 'trusted' by the OApp.\n     *\n     * @dev Enables OAppPreCrimeSimulator to check whether a potential Inbound Packet is from a trusted source.\n     */\n    function isPeer(uint32 _eid, bytes32 _peer) public view virtual override returns (bool) {\n        return peers[_eid] == _peer;\n    }\n\n    /**\n     * @dev Internal function to remove dust from the given local decimal amount.\n     * @param _amountLD The amount in local decimals.\n     * @return amountLD The amount after removing dust.\n     *\n     * @dev Prevents the loss of dust when moving amounts between chains with different decimals.\n     * @dev eg. uint(123) with a conversion rate of 100 becomes uint(100).\n     */\n    function _removeDust(uint256 _amountLD) internal view virtual returns (uint256 amountLD) {\n        return (_amountLD / decimalConversionRate) * decimalConversionRate;\n    }\n\n    /**\n     * @dev Internal function to convert an amount from shared decimals into local decimals.\n     * @param _amountSD The amount in shared decimals.\n     * @return amountLD The amount in local decimals.\n     */\n    function _toLD(uint64 _amountSD) internal view virtual returns (uint256 amountLD) {\n        return _amountSD * decimalConversionRate;\n    }\n\n    /**\n     * @dev Internal function to convert an amount from local decimals into shared decimals.\n     * @param _amountLD The amount in local decimals.\n     * @return amountSD The amount in shared decimals.\n     */\n    function _toSD(uint256 _amountLD) internal view virtual returns (uint64 amountSD) {\n        return uint64(_amountLD / decimalConversionRate);\n    }\n\n    /**\n     * @dev Internal function to mock the amount mutation from a OFT debit() operation.\n     * @param _amountLD The amount to send in local decimals.\n     * @param _minAmountLD The minimum amount to send in local decimals.\n     * @dev _dstEid The destination endpoint ID.\n     * @return amountSentLD The amount sent, in local decimals.\n     * @return amountReceivedLD The amount to be received on the remote chain, in local decimals.\n     *\n     * @dev This is where things like fees would be calculated and deducted from the amount to be received on the remote.\n     */\n    function _debitView(\n        uint256 _amountLD,\n        uint256 _minAmountLD,\n        uint32 /*_dstEid*/\n    ) internal view virtual returns (uint256 amountSentLD, uint256 amountReceivedLD) {\n        // @dev Remove the dust so nothing is lost on the conversion between chains with different decimals for the token.\n        amountSentLD = _removeDust(_amountLD);\n        // @dev The amount to send is the same as amount received in the default implementation.\n        amountReceivedLD = amountSentLD;\n\n        // @dev Check for slippage.\n        if (amountReceivedLD < _minAmountLD) {\n            revert SlippageExceeded(amountReceivedLD, _minAmountLD);\n        }\n    }\n\n    /**\n     * @dev Internal function to perform a debit operation.\n     * @param _from The address to debit.\n     * @param _amountLD The amount to send in local decimals.\n     * @param _minAmountLD The minimum amount to send in local decimals.\n     * @param _dstEid The destination endpoint ID.\n     * @return amountSentLD The amount sent in local decimals.\n     * @return amountReceivedLD The amount received in local decimals on the remote.\n     *\n     * @dev Defined here but are intended to be overriden depending on the OFT implementation.\n     * @dev Depending on OFT implementation the _amountLD could differ from the amountReceivedLD.\n     */\n    function _debit(\n        address _from,\n        uint256 _amountLD,\n        uint256 _minAmountLD,\n        uint32 _dstEid\n    ) internal virtual returns (uint256 amountSentLD, uint256 amountReceivedLD);\n\n    /**\n     * @dev Internal function to perform a credit operation.\n     * @param _to The address to credit.\n     * @param _amountLD The amount to credit in local decimals.\n     * @param _srcEid The source endpoint ID.\n     * @return amountReceivedLD The amount ACTUALLY received in local decimals.\n     *\n     * @dev Defined here but are intended to be overriden depending on the OFT implementation.\n     * @dev Depending on OFT implementation the _amountLD could differ from the amountReceivedLD.\n     */\n    function _credit(\n        address _to,\n        uint256 _amountLD,\n        uint32 _srcEid\n    ) internal virtual returns (uint256 amountReceivedLD);\n}\n"},"@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.20;\n\nimport {IAccessControl} from \"@openzeppelin/contracts/access/IAccessControl.sol\";\nimport {ContextUpgradeable} from \"../utils/ContextUpgradeable.sol\";\nimport {ERC165Upgradeable} from \"../utils/introspection/ERC165Upgradeable.sol\";\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```solidity\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```solidity\n * function foo() public {\n *     require(hasRole(MY_ROLE, msg.sender));\n *     ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}\n * to enforce additional security measures for this role.\n */\nabstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {\n    struct RoleData {\n        mapping(address account => bool) hasRole;\n        bytes32 adminRole;\n    }\n\n    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n\n    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl\n    struct AccessControlStorage {\n        mapping(bytes32 role => RoleData) _roles;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.AccessControl\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;\n\n    function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {\n        assembly {\n            $.slot := AccessControlStorageLocation\n        }\n    }\n\n    /**\n     * @dev Modifier that checks that an account has a specific role. Reverts\n     * with an {AccessControlUnauthorizedAccount} error including the required role.\n     */\n    modifier onlyRole(bytes32 role) {\n        _checkRole(role);\n        _;\n    }\n\n    function __AccessControl_init() internal onlyInitializing {\n    }\n\n    function __AccessControl_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) public view virtual returns (bool) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        return $._roles[role].hasRole[account];\n    }\n\n    /**\n     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`\n     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.\n     */\n    function _checkRole(bytes32 role) internal view virtual {\n        _checkRole(role, _msgSender());\n    }\n\n    /**\n     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`\n     * is missing `role`.\n     */\n    function _checkRole(bytes32 role, address account) internal view virtual {\n        if (!hasRole(role, account)) {\n            revert AccessControlUnauthorizedAccount(account, role);\n        }\n    }\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 {_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        return $._roles[role].adminRole;\n    }\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     * May emit a {RoleGranted} event.\n     */\n    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {\n        _grantRole(role, account);\n    }\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     * May emit a {RoleRevoked} event.\n     */\n    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {\n        _revokeRole(role, account);\n    }\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 revoked `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `callerConfirmation`.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function renounceRole(bytes32 role, address callerConfirmation) public virtual {\n        if (callerConfirmation != _msgSender()) {\n            revert AccessControlBadConfirmation();\n        }\n\n        _revokeRole(role, callerConfirmation);\n    }\n\n    /**\n     * @dev Sets `adminRole` as ``role``'s admin role.\n     *\n     * Emits a {RoleAdminChanged} event.\n     */\n    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        bytes32 previousAdminRole = getRoleAdmin(role);\n        $._roles[role].adminRole = adminRole;\n        emit RoleAdminChanged(role, previousAdminRole, adminRole);\n    }\n\n    /**\n     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleGranted} event.\n     */\n    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        if (!hasRole(role, account)) {\n            $._roles[role].hasRole[account] = true;\n            emit RoleGranted(role, account, _msgSender());\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        if (hasRole(role, account)) {\n            $._roles[role].hasRole[account] = false;\n            emit RoleRevoked(role, account, _msgSender());\n            return true;\n        } else {\n            return false;\n        }\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {ContextUpgradeable} from \"../utils/ContextUpgradeable.sol\";\nimport {Initializable} from \"../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 * The initial owner is set to the address provided by the deployer. This can\n * 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    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable\n    struct OwnableStorage {\n        address _owner;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Ownable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;\n\n    function _getOwnableStorage() private pure returns (OwnableStorage storage $) {\n        assembly {\n            $.slot := OwnableStorageLocation\n        }\n    }\n\n    /**\n     * @dev The caller account is not authorized to perform an operation.\n     */\n    error OwnableUnauthorizedAccount(address account);\n\n    /**\n     * @dev The owner is not a valid owner account. (eg. `address(0)`)\n     */\n    error OwnableInvalidOwner(address owner);\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n     */\n    function __Ownable_init(address initialOwner) internal onlyInitializing {\n        __Ownable_init_unchained(initialOwner);\n    }\n\n    function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {\n        if (initialOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(initialOwner);\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        OwnableStorage storage $ = _getOwnableStorage();\n        return $._owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        if (owner() != _msgSender()) {\n            revert OwnableUnauthorizedAccount(_msgSender());\n        }\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling 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        if (newOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\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        OwnableStorage storage $ = _getOwnableStorage();\n        address oldOwner = $._owner;\n        $._owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.20;\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 * ```solidity\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\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 Storage of the initializable contract.\n     *\n     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions\n     * when using with upgradeable contracts.\n     *\n     * @custom:storage-location erc7201:openzeppelin.storage.Initializable\n     */\n    struct InitializableStorage {\n        /**\n         * @dev Indicates that the contract has been initialized.\n         */\n        uint64 _initialized;\n        /**\n         * @dev Indicates that the contract is in the process of being initialized.\n         */\n        bool _initializing;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Initializable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;\n\n    /**\n     * @dev The contract is already initialized.\n     */\n    error InvalidInitialization();\n\n    /**\n     * @dev The contract is not initializing.\n     */\n    error NotInitializing();\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint64 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 in the context of a constructor an `initializer` may be invoked any\n     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in\n     * production.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        // Cache values to avoid duplicated sloads\n        bool isTopLevelCall = !$._initializing;\n        uint64 initialized = $._initialized;\n\n        // Allowed calls:\n        // - initialSetup: the contract is not in the initializing state and no previous version was\n        //                 initialized\n        // - construction: the contract is initialized at version 1 (no reininitialization) and the\n        //                 current contract is just being deployed\n        bool initialSetup = initialized == 0 && isTopLevelCall;\n        bool construction = initialized == 1 && address(this).code.length == 0;\n\n        if (!initialSetup && !construction) {\n            revert InvalidInitialization();\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 2**64 - 1 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint64 version) {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing || $._initialized >= version) {\n            revert InvalidInitialization();\n        }\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        _checkInitializing();\n        _;\n    }\n\n    /**\n     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.\n     */\n    function _checkInitializing() internal view virtual {\n        if (!_isInitializing()) {\n            revert NotInitializing();\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        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing) {\n            revert InvalidInitialization();\n        }\n        if ($._initialized != type(uint64).max) {\n            $._initialized = type(uint64).max;\n            emit Initialized(type(uint64).max);\n        }\n    }\n\n    /**\n     * @dev Returns the highest version that has been initialized. See {reinitializer}.\n     */\n    function _getInitializedVersion() internal view returns (uint64) {\n        return _getInitializableStorage()._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 _getInitializableStorage()._initializing;\n    }\n\n    /**\n     * @dev Returns a pointer to the storage namespace.\n     */\n    // solhint-disable-next-line var-name-mixedcase\n    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {\n        assembly {\n            $.slot := INITIALIZABLE_STORAGE\n        }\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (proxy/utils/UUPSUpgradeable.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC1822Proxiable} from \"@openzeppelin/contracts/interfaces/draft-IERC1822.sol\";\nimport {ERC1967Utils} from \"@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol\";\nimport {Initializable} from \"./Initializable.sol\";\n\n/**\n * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an\n * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.\n *\n * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is\n * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing\n * `UUPSUpgradeable` with a custom implementation of upgrades.\n *\n * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.\n */\nabstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {\n    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n    address private immutable __self = address(this);\n\n    /**\n     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`\n     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,\n     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.\n     * If the getter returns `\"5.0.0\"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must\n     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function\n     * during an upgrade.\n     */\n    string public constant UPGRADE_INTERFACE_VERSION = \"5.0.0\";\n\n    /**\n     * @dev The call is from an unauthorized context.\n     */\n    error UUPSUnauthorizedCallContext();\n\n    /**\n     * @dev The storage `slot` is unsupported as a UUID.\n     */\n    error UUPSUnsupportedProxiableUUID(bytes32 slot);\n\n    /**\n     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is\n     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case\n     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a\n     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to\n     * fail.\n     */\n    modifier onlyProxy() {\n        _checkProxy();\n        _;\n    }\n\n    /**\n     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be\n     * callable on the implementing contract but not through proxies.\n     */\n    modifier notDelegated() {\n        _checkNotDelegated();\n        _;\n    }\n\n    function __UUPSUpgradeable_init() internal onlyInitializing {\n    }\n\n    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the\n     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.\n     *\n     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.\n     */\n    function proxiableUUID() external view virtual notDelegated returns (bytes32) {\n        return ERC1967Utils.IMPLEMENTATION_SLOT;\n    }\n\n    /**\n     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call\n     * encoded in `data`.\n     *\n     * Calls {_authorizeUpgrade}.\n     *\n     * Emits an {Upgraded} event.\n     *\n     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall\n     */\n    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {\n        _authorizeUpgrade(newImplementation);\n        _upgradeToAndCallUUPS(newImplementation, data);\n    }\n\n    /**\n     * @dev Reverts if the execution is not performed via delegatecall or the execution\n     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.\n     * See {_onlyProxy}.\n     */\n    function _checkProxy() internal view virtual {\n        if (\n            address(this) == __self || // Must be called through delegatecall\n            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy\n        ) {\n            revert UUPSUnauthorizedCallContext();\n        }\n    }\n\n    /**\n     * @dev Reverts if the execution is performed via delegatecall.\n     * See {notDelegated}.\n     */\n    function _checkNotDelegated() internal view virtual {\n        if (address(this) != __self) {\n            // Must not be called through delegatecall\n            revert UUPSUnauthorizedCallContext();\n        }\n    }\n\n    /**\n     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by\n     * {upgradeToAndCall}.\n     *\n     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.\n     *\n     * ```solidity\n     * function _authorizeUpgrade(address) internal onlyOwner {}\n     * ```\n     */\n    function _authorizeUpgrade(address newImplementation) internal virtual;\n\n    /**\n     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.\n     *\n     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value\n     * is expected to be the implementation slot in ERC-1967.\n     *\n     * Emits an {IERC1967-Upgraded} event.\n     */\n    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {\n        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {\n                revert UUPSUnsupportedProxiableUUID(slot);\n            }\n            ERC1967Utils.upgradeToAndCall(newImplementation, data);\n        } catch {\n            // The implementation is not UUPS\n            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);\n        }\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IERC20Metadata} from \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport {ContextUpgradeable} from \"../../utils/ContextUpgradeable.sol\";\nimport {IERC20Errors} from \"@openzeppelin/contracts/interfaces/draft-IERC6093.sol\";\nimport {Initializable} from \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * The default value of {decimals} is 18. To change this, you should override\n * this function so it returns a different value.\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC-20\n * applications.\n */\nabstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {\n    /// @custom:storage-location erc7201:openzeppelin.storage.ERC20\n    struct ERC20Storage {\n        mapping(address account => uint256) _balances;\n\n        mapping(address account => mapping(address spender => uint256)) _allowances;\n\n        uint256 _totalSupply;\n\n        string _name;\n        string _symbol;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC20\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;\n\n    function _getERC20Storage() private pure returns (ERC20Storage storage $) {\n        assembly {\n            $.slot := ERC20StorageLocation\n        }\n    }\n\n    /**\n     * @dev Sets the values for {name} and {symbol}.\n     *\n     * All two of these values are immutable: they can only be set once during\n     * construction.\n     */\n    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {\n        __ERC20_init_unchained(name_, symbol_);\n    }\n\n    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n        ERC20Storage storage $ = _getERC20Storage();\n        $._name = name_;\n        $._symbol = symbol_;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view virtual returns (string memory) {\n        ERC20Storage storage $ = _getERC20Storage();\n        return $._name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view virtual returns (string memory) {\n        ERC20Storage storage $ = _getERC20Storage();\n        return $._symbol;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the default value returned by this function, unless\n     * it's overridden.\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view virtual returns (uint8) {\n        return 18;\n    }\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view virtual returns (uint256) {\n        ERC20Storage storage $ = _getERC20Storage();\n        return $._totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view virtual returns (uint256) {\n        ERC20Storage storage $ = _getERC20Storage();\n        return $._balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - the caller must have a balance of at least `value`.\n     */\n    function transfer(address to, uint256 value) public virtual returns (bool) {\n        address owner = _msgSender();\n        _transfer(owner, to, value);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual returns (uint256) {\n        ERC20Storage storage $ = _getERC20Storage();\n        return $._allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on\n     * `transferFrom`. This is semantically equivalent to an infinite approval.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function approve(address spender, uint256 value) public virtual returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, value);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Skips emitting an {Approval} event indicating an allowance update. This is not\n     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].\n     *\n     * NOTE: Does not update the allowance if the current allowance\n     * is the maximum `uint256`.\n     *\n     * Requirements:\n     *\n     * - `from` and `to` cannot be the zero address.\n     * - `from` must have a balance of at least `value`.\n     * - the caller must have allowance for ``from``'s tokens of at least\n     * `value`.\n     */\n    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {\n        address spender = _msgSender();\n        _spendAllowance(from, spender, value);\n        _transfer(from, to, value);\n        return true;\n    }\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to`.\n     *\n     * This internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\n     */\n    function _transfer(address from, address to, uint256 value) internal {\n        if (from == address(0)) {\n            revert ERC20InvalidSender(address(0));\n        }\n        if (to == address(0)) {\n            revert ERC20InvalidReceiver(address(0));\n        }\n        _update(from, to, value);\n    }\n\n    /**\n     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`\n     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding\n     * this function.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _update(address from, address to, uint256 value) internal virtual {\n        ERC20Storage storage $ = _getERC20Storage();\n        if (from == address(0)) {\n            // Overflow check required: The rest of the code assumes that totalSupply never overflows\n            $._totalSupply += value;\n        } else {\n            uint256 fromBalance = $._balances[from];\n            if (fromBalance < value) {\n                revert ERC20InsufficientBalance(from, fromBalance, value);\n            }\n            unchecked {\n                // Overflow not possible: value <= fromBalance <= totalSupply.\n                $._balances[from] = fromBalance - value;\n            }\n        }\n\n        if (to == address(0)) {\n            unchecked {\n                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.\n                $._totalSupply -= value;\n            }\n        } else {\n            unchecked {\n                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.\n                $._balances[to] += value;\n            }\n        }\n\n        emit Transfer(from, to, value);\n    }\n\n    /**\n     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).\n     * Relies on the `_update` mechanism\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\n     */\n    function _mint(address account, uint256 value) internal {\n        if (account == address(0)) {\n            revert ERC20InvalidReceiver(address(0));\n        }\n        _update(address(0), account, value);\n    }\n\n    /**\n     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.\n     * Relies on the `_update` mechanism.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead\n     */\n    function _burn(address account, uint256 value) internal {\n        if (account == address(0)) {\n            revert ERC20InvalidSender(address(0));\n        }\n        _update(account, address(0), value);\n    }\n\n    /**\n     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.\n     *\n     * This internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     *\n     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n     */\n    function _approve(address owner, address spender, uint256 value) internal {\n        _approve(owner, spender, value, true);\n    }\n\n    /**\n     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.\n     *\n     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by\n     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any\n     * `Approval` event during `transferFrom` operations.\n     *\n     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to\n     * true using the following override:\n     *\n     * ```solidity\n     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {\n     *     super._approve(owner, spender, value, true);\n     * }\n     * ```\n     *\n     * Requirements are the same as {_approve}.\n     */\n    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {\n        ERC20Storage storage $ = _getERC20Storage();\n        if (owner == address(0)) {\n            revert ERC20InvalidApprover(address(0));\n        }\n        if (spender == address(0)) {\n            revert ERC20InvalidSpender(address(0));\n        }\n        $._allowances[owner][spender] = value;\n        if (emitEvent) {\n            emit Approval(owner, spender, value);\n        }\n    }\n\n    /**\n     * @dev Updates `owner` s allowance for `spender` based on spent `value`.\n     *\n     * Does not update the allowance value in case of infinite allowance.\n     * Revert if not enough allowance is available.\n     *\n     * Does not emit an {Approval} event.\n     */\n    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {\n        uint256 currentAllowance = allowance(owner, spender);\n        if (currentAllowance != type(uint256).max) {\n            if (currentAllowance < value) {\n                revert ERC20InsufficientAllowance(spender, currentAllowance, value);\n            }\n            unchecked {\n                _approve(owner, spender, currentAllowance - value, false);\n            }\n        }\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Burnable.sol)\n\npragma solidity ^0.8.20;\n\nimport {ERC20Upgradeable} from \"../ERC20Upgradeable.sol\";\nimport {ContextUpgradeable} from \"../../../utils/ContextUpgradeable.sol\";\nimport {Initializable} from \"../../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Extension of {ERC20} that allows token holders to destroy both their own\n * tokens and those that they have an allowance for, in a way that can be\n * recognized off-chain (via event analysis).\n */\nabstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable {\n    function __ERC20Burnable_init() internal onlyInitializing {\n    }\n\n    function __ERC20Burnable_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev Destroys a `value` amount of tokens from the caller.\n     *\n     * See {ERC20-_burn}.\n     */\n    function burn(uint256 value) public virtual {\n        _burn(_msgSender(), value);\n    }\n\n    /**\n     * @dev Destroys a `value` amount of tokens from `account`, deducting from\n     * the caller's allowance.\n     *\n     * See {ERC20-_burn} and {ERC20-allowance}.\n     *\n     * Requirements:\n     *\n     * - the caller must have allowance for ``accounts``'s tokens of at least\n     * `value`.\n     */\n    function burnFrom(address account, uint256 value) public virtual {\n        _spendAllowance(account, _msgSender(), value);\n        _burn(account, value);\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\nimport {IERC721Metadata} from \"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol\";\nimport {ERC721Utils} from \"@openzeppelin/contracts/token/ERC721/utils/ERC721Utils.sol\";\nimport {ContextUpgradeable} from \"../../utils/ContextUpgradeable.sol\";\nimport {Strings} from \"@openzeppelin/contracts/utils/Strings.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {ERC165Upgradeable} from \"../../utils/introspection/ERC165Upgradeable.sol\";\nimport {IERC721Errors} from \"@openzeppelin/contracts/interfaces/draft-IERC6093.sol\";\nimport {Initializable} from \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC-721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\nabstract contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721, IERC721Metadata, IERC721Errors {\n    using Strings for uint256;\n\n    /// @custom:storage-location erc7201:openzeppelin.storage.ERC721\n    struct ERC721Storage {\n        // Token name\n        string _name;\n\n        // Token symbol\n        string _symbol;\n\n        mapping(uint256 tokenId => address) _owners;\n\n        mapping(address owner => uint256) _balances;\n\n        mapping(uint256 tokenId => address) _tokenApprovals;\n\n        mapping(address owner => mapping(address operator => bool)) _operatorApprovals;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC721\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ERC721StorageLocation = 0x80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab0079300;\n\n    function _getERC721Storage() private pure returns (ERC721Storage storage $) {\n        assembly {\n            $.slot := ERC721StorageLocation\n        }\n    }\n\n    /**\n     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n     */\n    function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {\n        __ERC721_init_unchained(name_, symbol_);\n    }\n\n    function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n        ERC721Storage storage $ = _getERC721Storage();\n        $._name = name_;\n        $._symbol = symbol_;\n    }\n\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165) returns (bool) {\n        return\n            interfaceId == type(IERC721).interfaceId ||\n            interfaceId == type(IERC721Metadata).interfaceId ||\n            super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev See {IERC721-balanceOf}.\n     */\n    function balanceOf(address owner) public view virtual returns (uint256) {\n        ERC721Storage storage $ = _getERC721Storage();\n        if (owner == address(0)) {\n            revert ERC721InvalidOwner(address(0));\n        }\n        return $._balances[owner];\n    }\n\n    /**\n     * @dev See {IERC721-ownerOf}.\n     */\n    function ownerOf(uint256 tokenId) public view virtual returns (address) {\n        return _requireOwned(tokenId);\n    }\n\n    /**\n     * @dev See {IERC721Metadata-name}.\n     */\n    function name() public view virtual returns (string memory) {\n        ERC721Storage storage $ = _getERC721Storage();\n        return $._name;\n    }\n\n    /**\n     * @dev See {IERC721Metadata-symbol}.\n     */\n    function symbol() public view virtual returns (string memory) {\n        ERC721Storage storage $ = _getERC721Storage();\n        return $._symbol;\n    }\n\n    /**\n     * @dev See {IERC721Metadata-tokenURI}.\n     */\n    function tokenURI(uint256 tokenId) public view virtual returns (string memory) {\n        _requireOwned(tokenId);\n\n        string memory baseURI = _baseURI();\n        return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : \"\";\n    }\n\n    /**\n     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n     * by default, can be overridden in child contracts.\n     */\n    function _baseURI() internal view virtual returns (string memory) {\n        return \"\";\n    }\n\n    /**\n     * @dev See {IERC721-approve}.\n     */\n    function approve(address to, uint256 tokenId) public virtual {\n        _approve(to, tokenId, _msgSender());\n    }\n\n    /**\n     * @dev See {IERC721-getApproved}.\n     */\n    function getApproved(uint256 tokenId) public view virtual returns (address) {\n        _requireOwned(tokenId);\n\n        return _getApproved(tokenId);\n    }\n\n    /**\n     * @dev See {IERC721-setApprovalForAll}.\n     */\n    function setApprovalForAll(address operator, bool approved) public virtual {\n        _setApprovalForAll(_msgSender(), operator, approved);\n    }\n\n    /**\n     * @dev See {IERC721-isApprovedForAll}.\n     */\n    function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {\n        ERC721Storage storage $ = _getERC721Storage();\n        return $._operatorApprovals[owner][operator];\n    }\n\n    /**\n     * @dev See {IERC721-transferFrom}.\n     */\n    function transferFrom(address from, address to, uint256 tokenId) public virtual {\n        if (to == address(0)) {\n            revert ERC721InvalidReceiver(address(0));\n        }\n        // Setting an \"auth\" arguments enables the `_isAuthorized` check which verifies that the token exists\n        // (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.\n        address previousOwner = _update(to, tokenId, _msgSender());\n        if (previousOwner != from) {\n            revert ERC721IncorrectOwner(from, tokenId, previousOwner);\n        }\n    }\n\n    /**\n     * @dev See {IERC721-safeTransferFrom}.\n     */\n    function safeTransferFrom(address from, address to, uint256 tokenId) public {\n        safeTransferFrom(from, to, tokenId, \"\");\n    }\n\n    /**\n     * @dev See {IERC721-safeTransferFrom}.\n     */\n    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {\n        transferFrom(from, to, tokenId);\n        ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);\n    }\n\n    /**\n     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n     *\n     * IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the\n     * core ERC-721 logic MUST be matched with the use of {_increaseBalance} to keep balances\n     * consistent with ownership. The invariant to preserve is that for any address `a` the value returned by\n     * `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.\n     */\n    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n        ERC721Storage storage $ = _getERC721Storage();\n        return $._owners[tokenId];\n    }\n\n    /**\n     * @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.\n     */\n    function _getApproved(uint256 tokenId) internal view virtual returns (address) {\n        ERC721Storage storage $ = _getERC721Storage();\n        return $._tokenApprovals[tokenId];\n    }\n\n    /**\n     * @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in\n     * particular (ignoring whether it is owned by `owner`).\n     *\n     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this\n     * assumption.\n     */\n    function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {\n        return\n            spender != address(0) &&\n            (owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);\n    }\n\n    /**\n     * @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.\n     * Reverts if:\n     * - `spender` does not have approval from `owner` for `tokenId`.\n     * - `spender` does not have approval to manage all of `owner`'s assets.\n     *\n     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this\n     * assumption.\n     */\n    function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {\n        if (!_isAuthorized(owner, spender, tokenId)) {\n            if (owner == address(0)) {\n                revert ERC721NonexistentToken(tokenId);\n            } else {\n                revert ERC721InsufficientApproval(spender, tokenId);\n            }\n        }\n    }\n\n    /**\n     * @dev Unsafe write access to the balances, used by extensions that \"mint\" tokens using an {ownerOf} override.\n     *\n     * NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that\n     * a uint256 would ever overflow from increments when these increments are bounded to uint128 values.\n     *\n     * WARNING: Increasing an account's balance using this function tends to be paired with an override of the\n     * {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership\n     * remain consistent with one another.\n     */\n    function _increaseBalance(address account, uint128 value) internal virtual {\n        ERC721Storage storage $ = _getERC721Storage();\n        unchecked {\n            $._balances[account] += value;\n        }\n    }\n\n    /**\n     * @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner\n     * (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.\n     *\n     * The `auth` argument is optional. If the value passed is non 0, then this function will check that\n     * `auth` is either the owner of the token, or approved to operate on the token (by the owner).\n     *\n     * Emits a {Transfer} event.\n     *\n     * NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.\n     */\n    function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {\n        ERC721Storage storage $ = _getERC721Storage();\n        address from = _ownerOf(tokenId);\n\n        // Perform (optional) operator check\n        if (auth != address(0)) {\n            _checkAuthorized(from, auth, tokenId);\n        }\n\n        // Execute the update\n        if (from != address(0)) {\n            // Clear approval. No need to re-authorize or emit the Approval event\n            _approve(address(0), tokenId, address(0), false);\n\n            unchecked {\n                $._balances[from] -= 1;\n            }\n        }\n\n        if (to != address(0)) {\n            unchecked {\n                $._balances[to] += 1;\n            }\n        }\n\n        $._owners[tokenId] = to;\n\n        emit Transfer(from, to, tokenId);\n\n        return from;\n    }\n\n    /**\n     * @dev Mints `tokenId` and transfers it to `to`.\n     *\n     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n     *\n     * Requirements:\n     *\n     * - `tokenId` must not exist.\n     * - `to` cannot be the zero address.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _mint(address to, uint256 tokenId) internal {\n        if (to == address(0)) {\n            revert ERC721InvalidReceiver(address(0));\n        }\n        address previousOwner = _update(to, tokenId, address(0));\n        if (previousOwner != address(0)) {\n            revert ERC721InvalidSender(address(0));\n        }\n    }\n\n    /**\n     * @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must not exist.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _safeMint(address to, uint256 tokenId) internal {\n        _safeMint(to, tokenId, \"\");\n    }\n\n    /**\n     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n     */\n    function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {\n        _mint(to, tokenId);\n        ERC721Utils.checkOnERC721Received(_msgSender(), address(0), to, tokenId, data);\n    }\n\n    /**\n     * @dev Destroys `tokenId`.\n     * The approval is cleared when the token is burned.\n     * This is an internal function that does not check if the sender is authorized to operate on the token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _burn(uint256 tokenId) internal {\n        address previousOwner = _update(address(0), tokenId, address(0));\n        if (previousOwner == address(0)) {\n            revert ERC721NonexistentToken(tokenId);\n        }\n    }\n\n    /**\n     * @dev Transfers `tokenId` from `from` to `to`.\n     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must be owned by `from`.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _transfer(address from, address to, uint256 tokenId) internal {\n        if (to == address(0)) {\n            revert ERC721InvalidReceiver(address(0));\n        }\n        address previousOwner = _update(to, tokenId, address(0));\n        if (previousOwner == address(0)) {\n            revert ERC721NonexistentToken(tokenId);\n        } else if (previousOwner != from) {\n            revert ERC721IncorrectOwner(from, tokenId, previousOwner);\n        }\n    }\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients\n     * are aware of the ERC-721 standard to prevent tokens from being forever locked.\n     *\n     * `data` is additional data, it has no specified format and it is sent in call to `to`.\n     *\n     * This internal function is like {safeTransferFrom} in the sense that it invokes\n     * {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.\n     * implement alternative mechanisms to perform token transfer, such as signature-based.\n     *\n     * Requirements:\n     *\n     * - `tokenId` token must exist and be owned by `from`.\n     * - `to` cannot be the zero address.\n     * - `from` cannot be the zero address.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _safeTransfer(address from, address to, uint256 tokenId) internal {\n        _safeTransfer(from, to, tokenId, \"\");\n    }\n\n    /**\n     * @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is\n     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n     */\n    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {\n        _transfer(from, to, tokenId);\n        ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);\n    }\n\n    /**\n     * @dev Approve `to` to operate on `tokenId`\n     *\n     * The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is\n     * either the owner of the token, or approved to operate on all tokens held by this owner.\n     *\n     * Emits an {Approval} event.\n     *\n     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n     */\n    function _approve(address to, uint256 tokenId, address auth) internal {\n        _approve(to, tokenId, auth, true);\n    }\n\n    /**\n     * @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not\n     * emitted in the context of transfers.\n     */\n    function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {\n        ERC721Storage storage $ = _getERC721Storage();\n        // Avoid reading the owner unless necessary\n        if (emitEvent || auth != address(0)) {\n            address owner = _requireOwned(tokenId);\n\n            // We do not use _isAuthorized because single-token approvals should not be able to call approve\n            if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {\n                revert ERC721InvalidApprover(auth);\n            }\n\n            if (emitEvent) {\n                emit Approval(owner, to, tokenId);\n            }\n        }\n\n        $._tokenApprovals[tokenId] = to;\n    }\n\n    /**\n     * @dev Approve `operator` to operate on all of `owner` tokens\n     *\n     * Requirements:\n     * - operator can't be the address zero.\n     *\n     * Emits an {ApprovalForAll} event.\n     */\n    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {\n        ERC721Storage storage $ = _getERC721Storage();\n        if (operator == address(0)) {\n            revert ERC721InvalidOperator(operator);\n        }\n        $._operatorApprovals[owner][operator] = approved;\n        emit ApprovalForAll(owner, operator, approved);\n    }\n\n    /**\n     * @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).\n     * Returns the owner.\n     *\n     * Overrides to ownership logic should be done to {_ownerOf}.\n     */\n    function _requireOwned(uint256 tokenId) internal view returns (address) {\n        address owner = _ownerOf(tokenId);\n        if (owner == address(0)) {\n            revert ERC721NonexistentToken(tokenId);\n        }\n        return owner;\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/extensions/ERC721Enumerable.sol)\n\npragma solidity ^0.8.20;\n\nimport {ERC721Upgradeable} from \"../ERC721Upgradeable.sol\";\nimport {IERC721Enumerable} from \"@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {Initializable} from \"../../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev This implements an optional extension of {ERC721} defined in the ERC that adds enumerability\n * of all the token ids in the contract as well as all token ids owned by each account.\n *\n * CAUTION: {ERC721} extensions that implement custom `balanceOf` logic, such as {ERC721Consecutive},\n * interfere with enumerability and should not be used together with {ERC721Enumerable}.\n */\nabstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721Enumerable {\n    /// @custom:storage-location erc7201:openzeppelin.storage.ERC721Enumerable\n    struct ERC721EnumerableStorage {\n        mapping(address owner => mapping(uint256 index => uint256)) _ownedTokens;\n        mapping(uint256 tokenId => uint256) _ownedTokensIndex;\n\n        uint256[] _allTokens;\n        mapping(uint256 tokenId => uint256) _allTokensIndex;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC721Enumerable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ERC721EnumerableStorageLocation = 0x645e039705490088daad89bae25049a34f4a9072d398537b1ab2425f24cbed00;\n\n    function _getERC721EnumerableStorage() private pure returns (ERC721EnumerableStorage storage $) {\n        assembly {\n            $.slot := ERC721EnumerableStorageLocation\n        }\n    }\n\n    /**\n     * @dev An `owner`'s token query was out of bounds for `index`.\n     *\n     * NOTE: The owner being `address(0)` indicates a global out of bounds index.\n     */\n    error ERC721OutOfBoundsIndex(address owner, uint256 index);\n\n    /**\n     * @dev Batch mint is not allowed.\n     */\n    error ERC721EnumerableForbiddenBatchMint();\n\n    function __ERC721Enumerable_init() internal onlyInitializing {\n    }\n\n    function __ERC721Enumerable_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721Upgradeable) returns (bool) {\n        return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.\n     */\n    function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) {\n        ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n        if (index >= balanceOf(owner)) {\n            revert ERC721OutOfBoundsIndex(owner, index);\n        }\n        return $._ownedTokens[owner][index];\n    }\n\n    /**\n     * @dev See {IERC721Enumerable-totalSupply}.\n     */\n    function totalSupply() public view virtual returns (uint256) {\n        ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n        return $._allTokens.length;\n    }\n\n    /**\n     * @dev See {IERC721Enumerable-tokenByIndex}.\n     */\n    function tokenByIndex(uint256 index) public view virtual returns (uint256) {\n        ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n        if (index >= totalSupply()) {\n            revert ERC721OutOfBoundsIndex(address(0), index);\n        }\n        return $._allTokens[index];\n    }\n\n    /**\n     * @dev See {ERC721-_update}.\n     */\n    function _update(address to, uint256 tokenId, address auth) internal virtual override returns (address) {\n        address previousOwner = super._update(to, tokenId, auth);\n\n        if (previousOwner == address(0)) {\n            _addTokenToAllTokensEnumeration(tokenId);\n        } else if (previousOwner != to) {\n            _removeTokenFromOwnerEnumeration(previousOwner, tokenId);\n        }\n        if (to == address(0)) {\n            _removeTokenFromAllTokensEnumeration(tokenId);\n        } else if (previousOwner != to) {\n            _addTokenToOwnerEnumeration(to, tokenId);\n        }\n\n        return previousOwner;\n    }\n\n    /**\n     * @dev Private function to add a token to this extension's ownership-tracking data structures.\n     * @param to address representing the new owner of the given token ID\n     * @param tokenId uint256 ID of the token to be added to the tokens list of the given address\n     */\n    function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {\n        ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n        uint256 length = balanceOf(to) - 1;\n        $._ownedTokens[to][length] = tokenId;\n        $._ownedTokensIndex[tokenId] = length;\n    }\n\n    /**\n     * @dev Private function to add a token to this extension's token tracking data structures.\n     * @param tokenId uint256 ID of the token to be added to the tokens list\n     */\n    function _addTokenToAllTokensEnumeration(uint256 tokenId) private {\n        ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n        $._allTokensIndex[tokenId] = $._allTokens.length;\n        $._allTokens.push(tokenId);\n    }\n\n    /**\n     * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that\n     * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for\n     * gas optimizations e.g. when performing a transfer operation (avoiding double writes).\n     * This has O(1) time complexity, but alters the order of the _ownedTokens array.\n     * @param from address representing the previous owner of the given token ID\n     * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address\n     */\n    function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {\n        ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and\n        // then delete the last slot (swap and pop).\n\n        uint256 lastTokenIndex = balanceOf(from);\n        uint256 tokenIndex = $._ownedTokensIndex[tokenId];\n\n        mapping(uint256 index => uint256) storage _ownedTokensByOwner = $._ownedTokens[from];\n\n        // When the token to delete is the last token, the swap operation is unnecessary\n        if (tokenIndex != lastTokenIndex) {\n            uint256 lastTokenId = _ownedTokensByOwner[lastTokenIndex];\n\n            _ownedTokensByOwner[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n            $._ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\n        }\n\n        // This also deletes the contents at the last position of the array\n        delete $._ownedTokensIndex[tokenId];\n        delete _ownedTokensByOwner[lastTokenIndex];\n    }\n\n    /**\n     * @dev Private function to remove a token from this extension's token tracking data structures.\n     * This has O(1) time complexity, but alters the order of the _allTokens array.\n     * @param tokenId uint256 ID of the token to be removed from the tokens list\n     */\n    function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {\n        ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and\n        // then delete the last slot (swap and pop).\n\n        uint256 lastTokenIndex = $._allTokens.length - 1;\n        uint256 tokenIndex = $._allTokensIndex[tokenId];\n\n        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so\n        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding\n        // an 'if' statement (like in _removeTokenFromOwnerEnumeration)\n        uint256 lastTokenId = $._allTokens[lastTokenIndex];\n\n        $._allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n        $._allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\n\n        // This also deletes the contents at the last position of the array\n        delete $._allTokensIndex[tokenId];\n        $._allTokens.pop();\n    }\n\n    /**\n     * See {ERC721-_increaseBalance}. We need that to account tokens that were minted in batch\n     */\n    function _increaseBalance(address account, uint128 amount) internal virtual override {\n        if (amount > 0) {\n            revert ERC721EnumerableForbiddenBatchMint();\n        }\n        super._increaseBalance(account, amount);\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/extensions/ERC721URIStorage.sol)\n\npragma solidity ^0.8.20;\n\nimport {ERC721Upgradeable} from \"../ERC721Upgradeable.sol\";\nimport {Strings} from \"@openzeppelin/contracts/utils/Strings.sol\";\nimport {IERC4906} from \"@openzeppelin/contracts/interfaces/IERC4906.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {Initializable} from \"../../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev ERC-721 token with storage based token URI management.\n */\nabstract contract ERC721URIStorageUpgradeable is Initializable, IERC4906, ERC721Upgradeable {\n    using Strings for uint256;\n\n    // Interface ID as defined in ERC-4906. This does not correspond to a traditional interface ID as ERC-4906 only\n    // defines events and does not include any external function.\n    bytes4 private constant ERC4906_INTERFACE_ID = bytes4(0x49064906);\n\n    /// @custom:storage-location erc7201:openzeppelin.storage.ERC721URIStorage\n    struct ERC721URIStorageStorage {\n        // Optional mapping for token URIs\n        mapping(uint256 tokenId => string) _tokenURIs;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC721URIStorage\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ERC721URIStorageStorageLocation = 0x0542a41881ee128a365a727b282c86fa859579490b9bb45aab8503648c8e7900;\n\n    function _getERC721URIStorageStorage() private pure returns (ERC721URIStorageStorage storage $) {\n        assembly {\n            $.slot := ERC721URIStorageStorageLocation\n        }\n    }\n\n    function __ERC721URIStorage_init() internal onlyInitializing {\n    }\n\n    function __ERC721URIStorage_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev See {IERC165-supportsInterface}\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Upgradeable, IERC165) returns (bool) {\n        return interfaceId == ERC4906_INTERFACE_ID || super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev See {IERC721Metadata-tokenURI}.\n     */\n    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n        ERC721URIStorageStorage storage $ = _getERC721URIStorageStorage();\n        _requireOwned(tokenId);\n\n        string memory _tokenURI = $._tokenURIs[tokenId];\n        string memory base = _baseURI();\n\n        // If there is no base URI, return the token URI.\n        if (bytes(base).length == 0) {\n            return _tokenURI;\n        }\n        // If both are set, concatenate the baseURI and tokenURI (via string.concat).\n        if (bytes(_tokenURI).length > 0) {\n            return string.concat(base, _tokenURI);\n        }\n\n        return super.tokenURI(tokenId);\n    }\n\n    /**\n     * @dev Sets `_tokenURI` as the tokenURI of `tokenId`.\n     *\n     * Emits {MetadataUpdate}.\n     */\n    function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {\n        ERC721URIStorageStorage storage $ = _getERC721URIStorageStorage();\n        $._tokenURIs[tokenId] = _tokenURI;\n        emit MetadataUpdate(tokenId);\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../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    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {Initializable} from \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165 {\n    function __ERC165_init() internal onlyInitializing {\n    }\n\n    function __ERC165_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,\n * consider using {ReentrancyGuardTransient} instead.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant NOT_ENTERED = 1;\n    uint256 private constant ENTERED = 2;\n\n    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard\n    struct ReentrancyGuardStorage {\n        uint256 _status;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ReentrancyGuard\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;\n\n    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {\n        assembly {\n            $.slot := ReentrancyGuardStorageLocation\n        }\n    }\n\n    /**\n     * @dev Unauthorized reentrant call.\n     */\n    error ReentrancyGuardReentrantCall();\n\n    function __ReentrancyGuard_init() internal onlyInitializing {\n        __ReentrancyGuard_init_unchained();\n    }\n\n    function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        $._status = NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        // On the first call to nonReentrant, _status will be NOT_ENTERED\n        if ($._status == ENTERED) {\n            revert ReentrancyGuardReentrantCall();\n        }\n\n        // Any calls to nonReentrant after this point will fail\n        $._status = ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        $._status = NOT_ENTERED;\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        return $._status == ENTERED;\n    }\n}\n"},"@openzeppelin/contracts/access/IAccessControl.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (access/IAccessControl.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev External interface of AccessControl declared to support ERC-165 detection.\n */\ninterface IAccessControl {\n    /**\n     * @dev The `account` is missing a role.\n     */\n    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);\n\n    /**\n     * @dev The caller of a function is not the expected one.\n     *\n     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.\n     */\n    error AccessControlBadConfirmation();\n\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    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. This account bears the admin role (for the granted role).\n     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.\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 `callerConfirmation`.\n     */\n    function renounceRole(bytes32 role, address callerConfirmation) external;\n}\n"},"@openzeppelin/contracts/access/Ownable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {Context} from \"../utils/Context.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 * The initial owner is set to the address provided by the deployer. This can\n * 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 Ownable is Context {\n    address private _owner;\n\n    /**\n     * @dev The caller account is not authorized to perform an operation.\n     */\n    error OwnableUnauthorizedAccount(address account);\n\n    /**\n     * @dev The owner is not a valid owner account. (eg. `address(0)`)\n     */\n    error OwnableInvalidOwner(address owner);\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n     */\n    constructor(address initialOwner) {\n        if (initialOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(initialOwner);\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        if (owner() != _msgSender()) {\n            revert OwnableUnauthorizedAccount(_msgSender());\n        }\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling 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        if (newOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\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"},"@openzeppelin/contracts/interfaces/draft-IERC1822.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n    /**\n     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n     * address.\n     *\n     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n     * function revert if invoked through a proxy.\n     */\n    function proxiableUUID() external view returns (bytes32);\n}\n"},"@openzeppelin/contracts/interfaces/draft-IERC6093.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard ERC-20 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.\n */\ninterface IERC20Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC20InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC20InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     * @param allowance Amount of tokens a `spender` is allowed to operate with.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC20InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC20InvalidSpender(address spender);\n}\n\n/**\n * @dev Standard ERC-721 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.\n */\ninterface IERC721Errors {\n    /**\n     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.\n     * Used in balance queries.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721InvalidOwner(address owner);\n\n    /**\n     * @dev Indicates a `tokenId` whose `owner` is the zero address.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721NonexistentToken(uint256 tokenId);\n\n    /**\n     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param tokenId Identifier number of a token.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC721InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC721InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721InsufficientApproval(address operator, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC721InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC721InvalidOperator(address operator);\n}\n\n/**\n * @dev Standard ERC-1155 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.\n */\ninterface IERC1155Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC1155InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC1155InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC1155MissingApprovalForAll(address operator, address owner);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC1155InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC1155InvalidOperator(address operator);\n\n    /**\n     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\n     * Used in batch transfers.\n     * @param idsLength Length of the array of token identifiers\n     * @param valuesLength Length of the array of token amounts\n     */\n    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\n}\n"},"@openzeppelin/contracts/interfaces/IERC1363.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {IERC165} from \"./IERC165.sol\";\n\n/**\n * @title IERC1363\n * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].\n *\n * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract\n * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.\n */\ninterface IERC1363 is IERC20, IERC165 {\n    /*\n     * Note: the ERC-165 identifier for this interface is 0xb0202a11.\n     * 0xb0202a11 ===\n     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^\n     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^\n     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^\n     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^\n     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^\n     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))\n     */\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferAndCall(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @param data Additional data with no specified format, sent in call to `to`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param from The address which you want to send tokens from.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param from The address which you want to send tokens from.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @param data Additional data with no specified format, sent in call to `to`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.\n     * @param spender The address which will spend the funds.\n     * @param value The amount of tokens to be spent.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function approveAndCall(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.\n     * @param spender The address which will spend the funds.\n     * @param value The amount of tokens to be spent.\n     * @param data Additional data with no specified format, sent in call to `spender`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);\n}\n"},"@openzeppelin/contracts/interfaces/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"../utils/introspection/IERC165.sol\";\n"},"@openzeppelin/contracts/interfaces/IERC1967.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.\n */\ninterface IERC1967 {\n    /**\n     * @dev Emitted when the implementation is upgraded.\n     */\n    event Upgraded(address indexed implementation);\n\n    /**\n     * @dev Emitted when the admin account has changed.\n     */\n    event AdminChanged(address previousAdmin, address newAdmin);\n\n    /**\n     * @dev Emitted when the beacon is changed.\n     */\n    event BeaconUpgraded(address indexed beacon);\n}\n"},"@openzeppelin/contracts/interfaces/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../token/ERC20/IERC20.sol\";\n"},"@openzeppelin/contracts/interfaces/IERC4906.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC4906.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"./IERC165.sol\";\nimport {IERC721} from \"./IERC721.sol\";\n\n/// @title ERC-721 Metadata Update Extension\ninterface IERC4906 is IERC165, IERC721 {\n    /// @dev This event emits when the metadata of a token is changed.\n    /// So that the third-party platforms such as NFT market could\n    /// timely update the images and related attributes of the NFT.\n    event MetadataUpdate(uint256 _tokenId);\n\n    /// @dev This event emits when the metadata of a range of tokens is changed.\n    /// So that the third-party platforms such as NFT market could\n    /// timely update the images and related attributes of the NFTs.\n    event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);\n}\n"},"@openzeppelin/contracts/interfaces/IERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"../token/ERC721/IERC721.sol\";\n"},"@openzeppelin/contracts/proxy/beacon/IBeacon.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n    /**\n     * @dev Must return an address that can be used as a delegate call target.\n     *\n     * {UpgradeableBeacon} will check that this address is a contract.\n     */\n    function implementation() external view returns (address);\n}\n"},"@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (proxy/ERC1967/ERC1967Utils.sol)\n\npragma solidity ^0.8.21;\n\nimport {IBeacon} from \"../beacon/IBeacon.sol\";\nimport {IERC1967} from \"../../interfaces/IERC1967.sol\";\nimport {Address} from \"../../utils/Address.sol\";\nimport {StorageSlot} from \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This library provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.\n */\nlibrary ERC1967Utils {\n    /**\n     * @dev Storage slot with the address of the current implementation.\n     * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n    /**\n     * @dev The `implementation` of the proxy is invalid.\n     */\n    error ERC1967InvalidImplementation(address implementation);\n\n    /**\n     * @dev The `admin` of the proxy is invalid.\n     */\n    error ERC1967InvalidAdmin(address admin);\n\n    /**\n     * @dev The `beacon` of the proxy is invalid.\n     */\n    error ERC1967InvalidBeacon(address beacon);\n\n    /**\n     * @dev An upgrade function sees `msg.value > 0` that may be lost.\n     */\n    error ERC1967NonPayable();\n\n    /**\n     * @dev Returns the current implementation address.\n     */\n    function getImplementation() internal view returns (address) {\n        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new address in the ERC-1967 implementation slot.\n     */\n    function _setImplementation(address newImplementation) private {\n        if (newImplementation.code.length == 0) {\n            revert ERC1967InvalidImplementation(newImplementation);\n        }\n        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;\n    }\n\n    /**\n     * @dev Performs implementation upgrade with additional setup call if data is nonempty.\n     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n     * to avoid stuck value in the contract.\n     *\n     * Emits an {IERC1967-Upgraded} event.\n     */\n    function upgradeToAndCall(address newImplementation, bytes memory data) internal {\n        _setImplementation(newImplementation);\n        emit IERC1967.Upgraded(newImplementation);\n\n        if (data.length > 0) {\n            Address.functionDelegateCall(newImplementation, data);\n        } else {\n            _checkNonPayable();\n        }\n    }\n\n    /**\n     * @dev Storage slot with the admin of the contract.\n     * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n    /**\n     * @dev Returns the current admin.\n     *\n     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\n     */\n    function getAdmin() internal view returns (address) {\n        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new address in the ERC-1967 admin slot.\n     */\n    function _setAdmin(address newAdmin) private {\n        if (newAdmin == address(0)) {\n            revert ERC1967InvalidAdmin(address(0));\n        }\n        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;\n    }\n\n    /**\n     * @dev Changes the admin of the proxy.\n     *\n     * Emits an {IERC1967-AdminChanged} event.\n     */\n    function changeAdmin(address newAdmin) internal {\n        emit IERC1967.AdminChanged(getAdmin(), newAdmin);\n        _setAdmin(newAdmin);\n    }\n\n    /**\n     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n     * This is the keccak-256 hash of \"eip1967.proxy.beacon\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n    /**\n     * @dev Returns the current beacon.\n     */\n    function getBeacon() internal view returns (address) {\n        return StorageSlot.getAddressSlot(BEACON_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new beacon in the ERC-1967 beacon slot.\n     */\n    function _setBeacon(address newBeacon) private {\n        if (newBeacon.code.length == 0) {\n            revert ERC1967InvalidBeacon(newBeacon);\n        }\n\n        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;\n\n        address beaconImplementation = IBeacon(newBeacon).implementation();\n        if (beaconImplementation.code.length == 0) {\n            revert ERC1967InvalidImplementation(beaconImplementation);\n        }\n    }\n\n    /**\n     * @dev Change the beacon and trigger a setup call if data is nonempty.\n     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n     * to avoid stuck value in the contract.\n     *\n     * Emits an {IERC1967-BeaconUpgraded} event.\n     *\n     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since\n     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for\n     * efficiency.\n     */\n    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {\n        _setBeacon(newBeacon);\n        emit IERC1967.BeaconUpgraded(newBeacon);\n\n        if (data.length > 0) {\n            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n        } else {\n            _checkNonPayable();\n        }\n    }\n\n    /**\n     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract\n     * if an upgrade doesn't perform an initialization call.\n     */\n    function _checkNonPayable() private {\n        if (msg.value > 0) {\n            revert ERC1967NonPayable();\n        }\n    }\n}\n"},"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC-20 standard.\n */\ninterface IERC20Metadata is IERC20 {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"},"@openzeppelin/contracts/token/ERC20/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC-20 standard as defined in the ERC.\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 value of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the value of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens as the allowance of `spender` over the\n     * 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 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\n     * allowance mechanism. `value` 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 value) external returns (bool);\n}\n"},"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\nimport {IERC1363} from \"../../../interfaces/IERC1363.sol\";\nimport {Address} from \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC-20 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    /**\n     * @dev An operation with an ERC-20 token failed.\n     */\n    error SafeERC20FailedOperation(address token);\n\n    /**\n     * @dev Indicates a failed `decreaseAllowance` request.\n     */\n    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\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.encodeCall(token.transfer, (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.encodeCall(token.transferFrom, (from, to, 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     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n     * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        forceApprove(token, spender, oldAllowance + value);\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n     * value, non-reverting calls are assumed to be successful.\n     *\n     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n     * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n        unchecked {\n            uint256 currentAllowance = token.allowance(address(this), spender);\n            if (currentAllowance < requestedDecrease) {\n                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n            }\n            forceApprove(token, spender, currentAllowance - requestedDecrease);\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     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function\n     * only sets the \"standard\" allowance. Any temporary allowance will remain active, in addition to the value being\n     * set here.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no\n     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {\n        if (to.code.length == 0) {\n            safeTransfer(token, to, value);\n        } else if (!token.transferAndCall(to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target\n     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function transferFromAndCallRelaxed(\n        IERC1363 token,\n        address from,\n        address to,\n        uint256 value,\n        bytes memory data\n    ) internal {\n        if (to.code.length == 0) {\n            safeTransferFrom(token, from, to, value);\n        } else if (!token.transferFromAndCall(from, to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no\n     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.\n     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}\n     * once without retrying, and relies on the returned value to be true.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {\n        if (to.code.length == 0) {\n            forceApprove(token, to, value);\n        } else if (!token.approveAndCall(to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        uint256 returnSize;\n        uint256 returnValue;\n        assembly (\"memory-safe\") {\n            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n            // bubble errors\n            if iszero(success) {\n                let ptr := mload(0x40)\n                returndatacopy(ptr, 0, returndatasize())\n                revert(ptr, returndatasize())\n            }\n            returnSize := returndatasize()\n            returnValue := mload(0)\n        }\n\n        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {\n            revert SafeERC20FailedOperation(address(token));\n        }\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 silently catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        bool success;\n        uint256 returnSize;\n        uint256 returnValue;\n        assembly (\"memory-safe\") {\n            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n            returnSize := returndatasize()\n            returnValue := mload(0)\n        }\n        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);\n    }\n}\n"},"@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Enumerable.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Enumerable is IERC721 {\n    /**\n     * @dev Returns the total amount of tokens stored by the contract.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.\n     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.\n     */\n    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);\n\n    /**\n     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.\n     * Use along with {totalSupply} to enumerate all tokens.\n     */\n    function tokenByIndex(uint256 index) external view returns (uint256);\n}\n"},"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n    /**\n     * @dev Returns the token collection name.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the token collection symbol.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n     */\n    function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"},"@openzeppelin/contracts/token/ERC721/IERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC-721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n    /**\n     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n     */\n    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n     */\n    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n    /**\n     * @dev Returns the number of tokens in ``owner``'s account.\n     */\n    function balanceOf(address owner) external view returns (uint256 balance);\n\n    /**\n     * @dev Returns the owner of the `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function ownerOf(uint256 tokenId) external view returns (address owner);\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n     *   a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n     * are aware of the ERC-721 protocol to prevent tokens from being forever locked.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or\n     *   {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n     *   a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n    /**\n     * @dev Transfers `tokenId` token from `from` to `to`.\n     *\n     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721\n     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n     * understand this adds an external call which potentially creates a reentrancy vulnerability.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 tokenId) external;\n\n    /**\n     * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n     * The approval is cleared when the token is transferred.\n     *\n     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n     *\n     * Requirements:\n     *\n     * - The caller must own the token or be an approved operator.\n     * - `tokenId` must exist.\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address to, uint256 tokenId) external;\n\n    /**\n     * @dev Approve or remove `operator` as an operator for the caller.\n     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n     *\n     * Requirements:\n     *\n     * - The `operator` cannot be the address zero.\n     *\n     * Emits an {ApprovalForAll} event.\n     */\n    function setApprovalForAll(address operator, bool approved) external;\n\n    /**\n     * @dev Returns the account approved for `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function getApproved(uint256 tokenId) external view returns (address operator);\n\n    /**\n     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n     *\n     * See {setApprovalForAll}\n     */\n    function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"},"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @title ERC-721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC-721 asset contracts.\n */\ninterface IERC721Receiver {\n    /**\n     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n     * by `operator` from `from`, this function is called.\n     *\n     * It must return its Solidity selector to confirm the token transfer.\n     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be\n     * reverted.\n     *\n     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n     */\n    function onERC721Received(\n        address operator,\n        address from,\n        uint256 tokenId,\n        bytes calldata data\n    ) external returns (bytes4);\n}\n"},"@openzeppelin/contracts/token/ERC721/utils/ERC721Utils.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/utils/ERC721Utils.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721Receiver} from \"../IERC721Receiver.sol\";\nimport {IERC721Errors} from \"../../../interfaces/draft-IERC6093.sol\";\n\n/**\n * @dev Library that provide common ERC-721 utility functions.\n *\n * See https://eips.ethereum.org/EIPS/eip-721[ERC-721].\n *\n * _Available since v5.1._\n */\nlibrary ERC721Utils {\n    /**\n     * @dev Performs an acceptance check for the provided `operator` by calling {IERC721-onERC721Received}\n     * on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).\n     *\n     * The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).\n     * Otherwise, the recipient must implement {IERC721Receiver-onERC721Received} and return the acceptance magic value to accept\n     * the transfer.\n     */\n    function checkOnERC721Received(\n        address operator,\n        address from,\n        address to,\n        uint256 tokenId,\n        bytes memory data\n    ) internal {\n        if (to.code.length > 0) {\n            try IERC721Receiver(to).onERC721Received(operator, from, tokenId, data) returns (bytes4 retval) {\n                if (retval != IERC721Receiver.onERC721Received.selector) {\n                    // Token rejected\n                    revert IERC721Errors.ERC721InvalidReceiver(to);\n                }\n            } catch (bytes memory reason) {\n                if (reason.length == 0) {\n                    // non-IERC721Receiver implementer\n                    revert IERC721Errors.ERC721InvalidReceiver(to);\n                } else {\n                    assembly (\"memory-safe\") {\n                        revert(add(32, reason), mload(reason))\n                    }\n                }\n            }\n        }\n    }\n}\n"},"@openzeppelin/contracts/utils/Address.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\nimport {Errors} from \"./Errors.sol\";\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev There's no code at `target` (it is not a contract).\n     */\n    error AddressEmptyCode(address target);\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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        if (address(this).balance < amount) {\n            revert Errors.InsufficientBalance(address(this).balance, amount);\n        }\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        if (!success) {\n            revert Errors.FailedCall();\n        }\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 or custom error, it is bubbled\n     * up by this function (like regular Solidity function calls). However, if\n     * the call reverted with no returned reason, this function reverts with a\n     * {Errors.FailedCall} error.\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    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0);\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    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        if (address(this).balance < value) {\n            revert Errors.InsufficientBalance(address(this).balance, value);\n        }\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case\n     * of an unsuccessful call.\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata\n    ) internal view returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            // only check if target is a contract if the call was successful and the return data is empty\n            // otherwise we already know that it was a contract\n            if (returndata.length == 0 && target.code.length == 0) {\n                revert AddressEmptyCode(target);\n            }\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n     * revert reason or with a default {Errors.FailedCall} error.\n     */\n    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.\n     */\n    function _revert(bytes memory returndata) 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            assembly (\"memory-safe\") {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n}\n"},"@openzeppelin/contracts/utils/Context.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\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 Context {\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    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"},"@openzeppelin/contracts/utils/Errors.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of common custom errors used in multiple contracts\n *\n * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.\n * It is recommended to avoid relying on the error API for critical functionality.\n *\n * _Available since v5.1._\n */\nlibrary Errors {\n    /**\n     * @dev The ETH balance of the account is not enough to perform the operation.\n     */\n    error InsufficientBalance(uint256 balance, uint256 needed);\n\n    /**\n     * @dev A call to an address target failed. The target may have reverted.\n     */\n    error FailedCall();\n\n    /**\n     * @dev The deployment failed.\n     */\n    error FailedDeployment();\n\n    /**\n     * @dev A necessary precompile is missing.\n     */\n    error MissingPrecompile(address);\n}\n"},"@openzeppelin/contracts/utils/introspection/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC-165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[ERC].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},"@openzeppelin/contracts/utils/math/Math.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\nimport {Panic} from \"../Panic.sol\";\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    enum Rounding {\n        Floor, // Toward negative infinity\n        Ceil, // Toward positive infinity\n        Trunc, // Toward zero\n        Expand // Away from zero\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, with an success flag (no overflow).\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a + b;\n            if (c < a) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            if (b > a) return (false, 0);\n            return (true, a - b);\n        }\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n            // benefit is lost if 'b' is also tested.\n            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n            if (a == 0) return (true, 0);\n            uint256 c = a * b;\n            if (c / a != b) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a / b);\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a % b);\n        }\n    }\n\n    /**\n     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.\n     *\n     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.\n     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute\n     * one branch when needed, making this function more expensive.\n     */\n    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {\n        unchecked {\n            // branchless ternary works because:\n            // b ^ (a ^ b) == a\n            // b ^ 0 == b\n            return b ^ ((a ^ b) * SafeCast.toUint(condition));\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return ternary(a > b, a, b);\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return ternary(a < b, a, b);\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds towards infinity instead\n     * of rounding towards zero.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        if (b == 0) {\n            // Guarantee the same behavior as in a regular Solidity division.\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n\n        // The following calculation ensures accurate ceiling division without overflow.\n        // Since a is non-zero, (a - 1) / b will not overflow.\n        // The largest possible result occurs when (a - 1) / b is type(uint256).max,\n        // but the largest value we can obtain is type(uint256).max - 1, which happens\n        // when a = type(uint256).max and b = 1.\n        unchecked {\n            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);\n        }\n    }\n\n    /**\n     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n     * denominator == 0.\n     *\n     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n     * Uniswap Labs also under MIT license.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use\n            // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2²⁵⁶ + prod0.\n            uint256 prod0 = x * y; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (prod1 == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.\n            if (denominator <= prod1) {\n                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));\n            }\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0].\n            uint256 remainder;\n            assembly {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n            uint256 twos = denominator & (0 - denominator);\n            assembly {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [prod1 prod0] by twos.\n                prod0 := div(prod0, twos)\n\n                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from prod1 into prod0.\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such\n            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n            // works in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2⁸\n            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶\n            inverse *= 2 - denominator * inverse; // inverse mod 2³²\n            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴\n            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸\n            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is\n            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);\n    }\n\n    /**\n     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.\n     *\n     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.\n     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.\n     *\n     * If the input value is not inversible, 0 is returned.\n     *\n     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the\n     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.\n     */\n    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {\n        unchecked {\n            if (n == 0) return 0;\n\n            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)\n            // Used to compute integers x and y such that: ax + ny = gcd(a, n).\n            // When the gcd is 1, then the inverse of a modulo n exists and it's x.\n            // ax + ny = 1\n            // ax = 1 + (-y)n\n            // ax ≡ 1 (mod n) # x is the inverse of a modulo n\n\n            // If the remainder is 0 the gcd is n right away.\n            uint256 remainder = a % n;\n            uint256 gcd = n;\n\n            // Therefore the initial coefficients are:\n            // ax + ny = gcd(a, n) = n\n            // 0a + 1n = n\n            int256 x = 0;\n            int256 y = 1;\n\n            while (remainder != 0) {\n                uint256 quotient = gcd / remainder;\n\n                (gcd, remainder) = (\n                    // The old remainder is the next gcd to try.\n                    remainder,\n                    // Compute the next remainder.\n                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd\n                    // where gcd is at most n (capped to type(uint256).max)\n                    gcd - remainder * quotient\n                );\n\n                (x, y) = (\n                    // Increment the coefficient of a.\n                    y,\n                    // Decrement the coefficient of n.\n                    // Can overflow, but the result is casted to uint256 so that the\n                    // next value of y is \"wrapped around\" to a value between 0 and n - 1.\n                    x - y * int256(quotient)\n                );\n            }\n\n            if (gcd != 1) return 0; // No inverse exists.\n            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.\n        }\n    }\n\n    /**\n     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.\n     *\n     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is\n     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that\n     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.\n     *\n     * NOTE: this function does NOT check that `p` is a prime greater than `2`.\n     */\n    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {\n        unchecked {\n            return Math.modExp(a, p - 2, p);\n        }\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)\n     *\n     * Requirements:\n     * - modulus can't be zero\n     * - underlying staticcall to precompile must succeed\n     *\n     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make\n     * sure the chain you're using it on supports the precompiled contract for modular exponentiation\n     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,\n     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly\n     * interpreted as 0.\n     */\n    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {\n        (bool success, uint256 result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).\n     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying\n     * to operate modulo 0 or if the underlying precompile reverted.\n     *\n     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain\n     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in\n     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack\n     * of a revert, but the result may be incorrectly interpreted as 0.\n     */\n    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {\n        if (m == 0) return (false, 0);\n        assembly (\"memory-safe\") {\n            let ptr := mload(0x40)\n            // | Offset    | Content    | Content (Hex)                                                      |\n            // |-----------|------------|--------------------------------------------------------------------|\n            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x60:0x7f | value of b | 0x<.............................................................b> |\n            // | 0x80:0x9f | value of e | 0x<.............................................................e> |\n            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |\n            mstore(ptr, 0x20)\n            mstore(add(ptr, 0x20), 0x20)\n            mstore(add(ptr, 0x40), 0x20)\n            mstore(add(ptr, 0x60), b)\n            mstore(add(ptr, 0x80), e)\n            mstore(add(ptr, 0xa0), m)\n\n            // Given the result < m, it's guaranteed to fit in 32 bytes,\n            // so we can use the memory scratch space located at offset 0.\n            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)\n            result := mload(0x00)\n        }\n    }\n\n    /**\n     * @dev Variant of {modExp} that supports inputs of arbitrary length.\n     */\n    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {\n        (bool success, bytes memory result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.\n     */\n    function tryModExp(\n        bytes memory b,\n        bytes memory e,\n        bytes memory m\n    ) internal view returns (bool success, bytes memory result) {\n        if (_zeroBytes(m)) return (false, new bytes(0));\n\n        uint256 mLen = m.length;\n\n        // Encode call args in result and move the free memory pointer\n        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);\n\n        assembly (\"memory-safe\") {\n            let dataPtr := add(result, 0x20)\n            // Write result on top of args to avoid allocating extra memory.\n            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)\n            // Overwrite the length.\n            // result.length > returndatasize() is guaranteed because returndatasize() == m.length\n            mstore(result, mLen)\n            // Set the memory pointer after the returned data.\n            mstore(0x40, add(dataPtr, mLen))\n        }\n    }\n\n    /**\n     * @dev Returns whether the provided byte array is zero.\n     */\n    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {\n        for (uint256 i = 0; i < byteArray.length; ++i) {\n            if (byteArray[i] != 0) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n     * towards zero.\n     *\n     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only\n     * using integer operations.\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        unchecked {\n            // Take care of easy edge cases when a == 0 or a == 1\n            if (a <= 1) {\n                return a;\n            }\n\n            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a\n            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between\n            // the current value as `ε_n = | x_n - sqrt(a) |`.\n            //\n            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root\n            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is\n            // bigger than any uint256.\n            //\n            // By noticing that\n            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`\n            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar\n            // to the msb function.\n            uint256 aa = a;\n            uint256 xn = 1;\n\n            if (aa >= (1 << 128)) {\n                aa >>= 128;\n                xn <<= 64;\n            }\n            if (aa >= (1 << 64)) {\n                aa >>= 64;\n                xn <<= 32;\n            }\n            if (aa >= (1 << 32)) {\n                aa >>= 32;\n                xn <<= 16;\n            }\n            if (aa >= (1 << 16)) {\n                aa >>= 16;\n                xn <<= 8;\n            }\n            if (aa >= (1 << 8)) {\n                aa >>= 8;\n                xn <<= 4;\n            }\n            if (aa >= (1 << 4)) {\n                aa >>= 4;\n                xn <<= 2;\n            }\n            if (aa >= (1 << 2)) {\n                xn <<= 1;\n            }\n\n            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).\n            //\n            // We can refine our estimation by noticing that the middle of that interval minimizes the error.\n            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).\n            // This is going to be our x_0 (and ε_0)\n            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)\n\n            // From here, Newton's method give us:\n            // x_{n+1} = (x_n + a / x_n) / 2\n            //\n            // One should note that:\n            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a\n            //              = ((x_n² + a) / (2 * x_n))² - a\n            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a\n            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)\n            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)\n            //              = (x_n² - a)² / (2 * x_n)²\n            //              = ((x_n² - a) / (2 * x_n))²\n            //              ≥ 0\n            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n\n            //\n            // This gives us the proof of quadratic convergence of the sequence:\n            // ε_{n+1} = | x_{n+1} - sqrt(a) |\n            //         = | (x_n + a / x_n) / 2 - sqrt(a) |\n            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |\n            //         = | (x_n - sqrt(a))² / (2 * x_n) |\n            //         = | ε_n² / (2 * x_n) |\n            //         = ε_n² / | (2 * x_n) |\n            //\n            // For the first iteration, we have a special case where x_0 is known:\n            // ε_1 = ε_0² / | (2 * x_0) |\n            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))\n            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))\n            //     ≤ 2**(e-3) / 3\n            //     ≤ 2**(e-3-log2(3))\n            //     ≤ 2**(e-4.5)\n            //\n            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:\n            // ε_{n+1} = ε_n² / | (2 * x_n) |\n            //         ≤ (2**(e-k))² / (2 * 2**(e-1))\n            //         ≤ 2**(2*e-2*k) / 2**e\n            //         ≤ 2**(e-2*k)\n            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above\n            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5\n            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9\n            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18\n            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36\n            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72\n\n            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision\n            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either\n            // sqrt(a) or sqrt(a) + 1.\n            return xn - SafeCast.toUint(xn > a / xn);\n        }\n    }\n\n    /**\n     * @dev Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        uint256 exp;\n        unchecked {\n            exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);\n            value >>= exp;\n            result += exp;\n\n            result += SafeCast.toUint(value > 1);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        uint256 isGt;\n        unchecked {\n            isGt = SafeCast.toUint(value > (1 << 128) - 1);\n            value >>= isGt * 128;\n            result += isGt * 16;\n\n            isGt = SafeCast.toUint(value > (1 << 64) - 1);\n            value >>= isGt * 64;\n            result += isGt * 8;\n\n            isGt = SafeCast.toUint(value > (1 << 32) - 1);\n            value >>= isGt * 32;\n            result += isGt * 4;\n\n            isGt = SafeCast.toUint(value > (1 << 16) - 1);\n            value >>= isGt * 16;\n            result += isGt * 2;\n\n            result += SafeCast.toUint(value > (1 << 8) - 1);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);\n        }\n    }\n\n    /**\n     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n     */\n    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n        return uint8(rounding) % 2 == 1;\n    }\n}\n"},"@openzeppelin/contracts/utils/math/SafeCast.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX/bool 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 */\nlibrary SafeCast {\n    /**\n     * @dev Value doesn't fit in an uint of `bits` size.\n     */\n    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);\n\n    /**\n     * @dev An int value doesn't fit in an uint of `bits` size.\n     */\n    error SafeCastOverflowedIntToUint(int256 value);\n\n    /**\n     * @dev Value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);\n\n    /**\n     * @dev An uint value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedUintToInt(uint256 value);\n\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    function toUint248(uint256 value) internal pure returns (uint248) {\n        if (value > type(uint248).max) {\n            revert SafeCastOverflowedUintDowncast(248, value);\n        }\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    function toUint240(uint256 value) internal pure returns (uint240) {\n        if (value > type(uint240).max) {\n            revert SafeCastOverflowedUintDowncast(240, value);\n        }\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    function toUint232(uint256 value) internal pure returns (uint232) {\n        if (value > type(uint232).max) {\n            revert SafeCastOverflowedUintDowncast(232, value);\n        }\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    function toUint224(uint256 value) internal pure returns (uint224) {\n        if (value > type(uint224).max) {\n            revert SafeCastOverflowedUintDowncast(224, value);\n        }\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    function toUint216(uint256 value) internal pure returns (uint216) {\n        if (value > type(uint216).max) {\n            revert SafeCastOverflowedUintDowncast(216, value);\n        }\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    function toUint208(uint256 value) internal pure returns (uint208) {\n        if (value > type(uint208).max) {\n            revert SafeCastOverflowedUintDowncast(208, value);\n        }\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    function toUint200(uint256 value) internal pure returns (uint200) {\n        if (value > type(uint200).max) {\n            revert SafeCastOverflowedUintDowncast(200, value);\n        }\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    function toUint192(uint256 value) internal pure returns (uint192) {\n        if (value > type(uint192).max) {\n            revert SafeCastOverflowedUintDowncast(192, value);\n        }\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    function toUint184(uint256 value) internal pure returns (uint184) {\n        if (value > type(uint184).max) {\n            revert SafeCastOverflowedUintDowncast(184, value);\n        }\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    function toUint176(uint256 value) internal pure returns (uint176) {\n        if (value > type(uint176).max) {\n            revert SafeCastOverflowedUintDowncast(176, value);\n        }\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    function toUint168(uint256 value) internal pure returns (uint168) {\n        if (value > type(uint168).max) {\n            revert SafeCastOverflowedUintDowncast(168, value);\n        }\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    function toUint160(uint256 value) internal pure returns (uint160) {\n        if (value > type(uint160).max) {\n            revert SafeCastOverflowedUintDowncast(160, value);\n        }\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    function toUint152(uint256 value) internal pure returns (uint152) {\n        if (value > type(uint152).max) {\n            revert SafeCastOverflowedUintDowncast(152, value);\n        }\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    function toUint144(uint256 value) internal pure returns (uint144) {\n        if (value > type(uint144).max) {\n            revert SafeCastOverflowedUintDowncast(144, value);\n        }\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    function toUint136(uint256 value) internal pure returns (uint136) {\n        if (value > type(uint136).max) {\n            revert SafeCastOverflowedUintDowncast(136, value);\n        }\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    function toUint128(uint256 value) internal pure returns (uint128) {\n        if (value > type(uint128).max) {\n            revert SafeCastOverflowedUintDowncast(128, value);\n        }\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    function toUint120(uint256 value) internal pure returns (uint120) {\n        if (value > type(uint120).max) {\n            revert SafeCastOverflowedUintDowncast(120, value);\n        }\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    function toUint112(uint256 value) internal pure returns (uint112) {\n        if (value > type(uint112).max) {\n            revert SafeCastOverflowedUintDowncast(112, value);\n        }\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    function toUint104(uint256 value) internal pure returns (uint104) {\n        if (value > type(uint104).max) {\n            revert SafeCastOverflowedUintDowncast(104, value);\n        }\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    function toUint96(uint256 value) internal pure returns (uint96) {\n        if (value > type(uint96).max) {\n            revert SafeCastOverflowedUintDowncast(96, value);\n        }\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    function toUint88(uint256 value) internal pure returns (uint88) {\n        if (value > type(uint88).max) {\n            revert SafeCastOverflowedUintDowncast(88, value);\n        }\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    function toUint80(uint256 value) internal pure returns (uint80) {\n        if (value > type(uint80).max) {\n            revert SafeCastOverflowedUintDowncast(80, value);\n        }\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    function toUint72(uint256 value) internal pure returns (uint72) {\n        if (value > type(uint72).max) {\n            revert SafeCastOverflowedUintDowncast(72, value);\n        }\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    function toUint64(uint256 value) internal pure returns (uint64) {\n        if (value > type(uint64).max) {\n            revert SafeCastOverflowedUintDowncast(64, value);\n        }\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    function toUint56(uint256 value) internal pure returns (uint56) {\n        if (value > type(uint56).max) {\n            revert SafeCastOverflowedUintDowncast(56, value);\n        }\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    function toUint48(uint256 value) internal pure returns (uint48) {\n        if (value > type(uint48).max) {\n            revert SafeCastOverflowedUintDowncast(48, value);\n        }\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    function toUint40(uint256 value) internal pure returns (uint40) {\n        if (value > type(uint40).max) {\n            revert SafeCastOverflowedUintDowncast(40, value);\n        }\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    function toUint32(uint256 value) internal pure returns (uint32) {\n        if (value > type(uint32).max) {\n            revert SafeCastOverflowedUintDowncast(32, value);\n        }\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    function toUint24(uint256 value) internal pure returns (uint24) {\n        if (value > type(uint24).max) {\n            revert SafeCastOverflowedUintDowncast(24, value);\n        }\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    function toUint16(uint256 value) internal pure returns (uint16) {\n        if (value > type(uint16).max) {\n            revert SafeCastOverflowedUintDowncast(16, value);\n        }\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    function toUint8(uint256 value) internal pure returns (uint8) {\n        if (value > type(uint8).max) {\n            revert SafeCastOverflowedUintDowncast(8, value);\n        }\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    function toUint256(int256 value) internal pure returns (uint256) {\n        if (value < 0) {\n            revert SafeCastOverflowedIntToUint(value);\n        }\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    function toInt248(int256 value) internal pure returns (int248 downcasted) {\n        downcasted = int248(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(248, value);\n        }\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    function toInt240(int256 value) internal pure returns (int240 downcasted) {\n        downcasted = int240(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(240, value);\n        }\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    function toInt232(int256 value) internal pure returns (int232 downcasted) {\n        downcasted = int232(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(232, value);\n        }\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    function toInt224(int256 value) internal pure returns (int224 downcasted) {\n        downcasted = int224(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(224, value);\n        }\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    function toInt216(int256 value) internal pure returns (int216 downcasted) {\n        downcasted = int216(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(216, value);\n        }\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    function toInt208(int256 value) internal pure returns (int208 downcasted) {\n        downcasted = int208(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(208, value);\n        }\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    function toInt200(int256 value) internal pure returns (int200 downcasted) {\n        downcasted = int200(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(200, value);\n        }\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    function toInt192(int256 value) internal pure returns (int192 downcasted) {\n        downcasted = int192(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(192, value);\n        }\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    function toInt184(int256 value) internal pure returns (int184 downcasted) {\n        downcasted = int184(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(184, value);\n        }\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    function toInt176(int256 value) internal pure returns (int176 downcasted) {\n        downcasted = int176(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(176, value);\n        }\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    function toInt168(int256 value) internal pure returns (int168 downcasted) {\n        downcasted = int168(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(168, value);\n        }\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    function toInt160(int256 value) internal pure returns (int160 downcasted) {\n        downcasted = int160(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(160, value);\n        }\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    function toInt152(int256 value) internal pure returns (int152 downcasted) {\n        downcasted = int152(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(152, value);\n        }\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    function toInt144(int256 value) internal pure returns (int144 downcasted) {\n        downcasted = int144(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(144, value);\n        }\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    function toInt136(int256 value) internal pure returns (int136 downcasted) {\n        downcasted = int136(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(136, value);\n        }\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    function toInt128(int256 value) internal pure returns (int128 downcasted) {\n        downcasted = int128(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(128, value);\n        }\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    function toInt120(int256 value) internal pure returns (int120 downcasted) {\n        downcasted = int120(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(120, value);\n        }\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    function toInt112(int256 value) internal pure returns (int112 downcasted) {\n        downcasted = int112(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(112, value);\n        }\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    function toInt104(int256 value) internal pure returns (int104 downcasted) {\n        downcasted = int104(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(104, value);\n        }\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    function toInt96(int256 value) internal pure returns (int96 downcasted) {\n        downcasted = int96(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(96, value);\n        }\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    function toInt88(int256 value) internal pure returns (int88 downcasted) {\n        downcasted = int88(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(88, value);\n        }\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    function toInt80(int256 value) internal pure returns (int80 downcasted) {\n        downcasted = int80(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(80, value);\n        }\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    function toInt72(int256 value) internal pure returns (int72 downcasted) {\n        downcasted = int72(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(72, value);\n        }\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    function toInt64(int256 value) internal pure returns (int64 downcasted) {\n        downcasted = int64(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(64, value);\n        }\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    function toInt56(int256 value) internal pure returns (int56 downcasted) {\n        downcasted = int56(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(56, value);\n        }\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    function toInt48(int256 value) internal pure returns (int48 downcasted) {\n        downcasted = int48(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(48, value);\n        }\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    function toInt40(int256 value) internal pure returns (int40 downcasted) {\n        downcasted = int40(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(40, value);\n        }\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    function toInt32(int256 value) internal pure returns (int32 downcasted) {\n        downcasted = int32(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(32, value);\n        }\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    function toInt24(int256 value) internal pure returns (int24 downcasted) {\n        downcasted = int24(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(24, value);\n        }\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    function toInt16(int256 value) internal pure returns (int16 downcasted) {\n        downcasted = int16(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(16, value);\n        }\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    function toInt8(int256 value) internal pure returns (int8 downcasted) {\n        downcasted = int8(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(8, value);\n        }\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    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        if (value > uint256(type(int256).max)) {\n            revert SafeCastOverflowedUintToInt(value);\n        }\n        return int256(value);\n    }\n\n    /**\n     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.\n     */\n    function toUint(bool b) internal pure returns (uint256 u) {\n        assembly (\"memory-safe\") {\n            u := iszero(iszero(b))\n        }\n    }\n}\n"},"@openzeppelin/contracts/utils/math/SignedMath.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.20;\n\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n    /**\n     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.\n     *\n     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.\n     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute\n     * one branch when needed, making this function more expensive.\n     */\n    function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {\n        unchecked {\n            // branchless ternary works because:\n            // b ^ (a ^ b) == a\n            // b ^ 0 == b\n            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two signed numbers.\n     */\n    function max(int256 a, int256 b) internal pure returns (int256) {\n        return ternary(a > b, a, b);\n    }\n\n    /**\n     * @dev Returns the smallest of two signed numbers.\n     */\n    function min(int256 a, int256 b) internal pure returns (int256) {\n        return ternary(a < b, a, b);\n    }\n\n    /**\n     * @dev Returns the average of two signed numbers without overflow.\n     * The result is rounded towards zero.\n     */\n    function average(int256 a, int256 b) internal pure returns (int256) {\n        // Formula from the book \"Hacker's Delight\"\n        int256 x = (a & b) + ((a ^ b) >> 1);\n        return x + (int256(uint256(x) >> 255) & (a ^ b));\n    }\n\n    /**\n     * @dev Returns the absolute unsigned value of a signed value.\n     */\n    function abs(int256 n) internal pure returns (uint256) {\n        unchecked {\n            // Formula from the \"Bit Twiddling Hacks\" by Sean Eron Anderson.\n            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,\n            // taking advantage of the most significant (or \"sign\" bit) in two's complement representation.\n            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,\n            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).\n            int256 mask = n >> 255;\n\n            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.\n            return uint256((n + mask) ^ mask);\n        }\n    }\n}\n"},"@openzeppelin/contracts/utils/Panic.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Helper library for emitting standardized panic codes.\n *\n * ```solidity\n * contract Example {\n *      using Panic for uint256;\n *\n *      // Use any of the declared internal constants\n *      function foo() { Panic.GENERIC.panic(); }\n *\n *      // Alternatively\n *      function foo() { Panic.panic(Panic.GENERIC); }\n * }\n * ```\n *\n * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].\n *\n * _Available since v5.1._\n */\n// slither-disable-next-line unused-state\nlibrary Panic {\n    /// @dev generic / unspecified error\n    uint256 internal constant GENERIC = 0x00;\n    /// @dev used by the assert() builtin\n    uint256 internal constant ASSERT = 0x01;\n    /// @dev arithmetic underflow or overflow\n    uint256 internal constant UNDER_OVERFLOW = 0x11;\n    /// @dev division or modulo by zero\n    uint256 internal constant DIVISION_BY_ZERO = 0x12;\n    /// @dev enum conversion error\n    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;\n    /// @dev invalid encoding in storage\n    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;\n    /// @dev empty array pop\n    uint256 internal constant EMPTY_ARRAY_POP = 0x31;\n    /// @dev array out of bounds access\n    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;\n    /// @dev resource error (too large allocation or too large array)\n    uint256 internal constant RESOURCE_ERROR = 0x41;\n    /// @dev calling invalid internal function\n    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;\n\n    /// @dev Reverts with a panic code. Recommended to use with\n    /// the internal constants with predefined codes.\n    function panic(uint256 code) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0x00, 0x4e487b71)\n            mstore(0x20, code)\n            revert(0x1c, 0x24)\n        }\n    }\n}\n"},"@openzeppelin/contracts/utils/StorageSlot.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC-1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.\n *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n *     function _getImplementation() internal view returns (address) {\n *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n *     }\n *\n *     function _setImplementation(address newImplementation) internal {\n *         require(newImplementation.code.length > 0);\n *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n *     }\n * }\n * ```\n *\n * TIP: Consider using this library along with {SlotDerivation}.\n */\nlibrary StorageSlot {\n    struct AddressSlot {\n        address value;\n    }\n\n    struct BooleanSlot {\n        bool value;\n    }\n\n    struct Bytes32Slot {\n        bytes32 value;\n    }\n\n    struct Uint256Slot {\n        uint256 value;\n    }\n\n    struct Int256Slot {\n        int256 value;\n    }\n\n    struct StringSlot {\n        string value;\n    }\n\n    struct BytesSlot {\n        bytes value;\n    }\n\n    /**\n     * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n     */\n    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.\n     */\n    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.\n     */\n    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.\n     */\n    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Int256Slot` with member `value` located at `slot`.\n     */\n    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `StringSlot` with member `value` located at `slot`.\n     */\n    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n     */\n    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := store.slot\n        }\n    }\n\n    /**\n     * @dev Returns a `BytesSlot` with member `value` located at `slot`.\n     */\n    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n     */\n    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := store.slot\n        }\n    }\n}\n"},"@openzeppelin/contracts/utils/Strings.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Strings.sol)\n\npragma solidity ^0.8.20;\n\nimport {Math} from \"./math/Math.sol\";\nimport {SignedMath} from \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    bytes16 private constant HEX_DIGITS = \"0123456789abcdef\";\n    uint8 private constant ADDRESS_LENGTH = 20;\n\n    /**\n     * @dev The `value` string doesn't fit in the specified `length`.\n     */\n    error StringsInsufficientHexLength(uint256 value, uint256 length);\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            uint256 length = Math.log10(value) + 1;\n            string memory buffer = new string(length);\n            uint256 ptr;\n            assembly (\"memory-safe\") {\n                ptr := add(buffer, add(32, length))\n            }\n            while (true) {\n                ptr--;\n                assembly (\"memory-safe\") {\n                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))\n                }\n                value /= 10;\n                if (value == 0) break;\n            }\n            return buffer;\n        }\n    }\n\n    /**\n     * @dev Converts a `int256` to its ASCII `string` decimal representation.\n     */\n    function toStringSigned(int256 value) internal pure returns (string memory) {\n        return string.concat(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value)));\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            return toHexString(value, Math.log256(value) + 1);\n        }\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        uint256 localValue = value;\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = HEX_DIGITS[localValue & 0xf];\n            localValue >>= 4;\n        }\n        if (localValue != 0) {\n            revert StringsInsufficientHexLength(value, length);\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal\n     * representation.\n     */\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal\n     * representation, according to EIP-55.\n     */\n    function toChecksumHexString(address addr) internal pure returns (string memory) {\n        bytes memory buffer = bytes(toHexString(addr));\n\n        // hash the hex part of buffer (skip length + 2 bytes, length 40)\n        uint256 hashValue;\n        assembly (\"memory-safe\") {\n            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))\n        }\n\n        for (uint256 i = 41; i > 1; --i) {\n            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)\n            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {\n                // case shift by xoring with 0x20\n                buffer[i] ^= 0x20;\n            }\n            hashValue >>= 4;\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Returns true if the two strings are equal.\n     */\n    function equal(string memory a, string memory b) internal pure returns (bool) {\n        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));\n    }\n}\n"},"contracts/errors/ICollateralVaultErrors.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.23;\r\n\r\n/**\r\n * @title Collateral Vault Errors Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Defines error types specific to CollateralVault operations\r\n * @dev Interface containing CollateralVault-specific error definitions\r\n */\r\ninterface ICollateralVaultErrors {\r\n    /**\r\n     * @notice Thrown when an unauthorized address attempts router operations\r\n     * @param caller Address attempting the operation\r\n     * @dev Used to protect router-only functions\r\n     */\r\n    error UnauthorizedRouter(address caller);\r\n\r\n    /**\r\n     * @notice Thrown when an invalid (usually zero) address is provided\r\n     * @param addr The invalid address\r\n     * @dev Basic input validation error\r\n     */\r\n    error InvalidAddress(address addr);\r\n\r\n    /**\r\n     * @notice Thrown when invalid parameters are provided\r\n     * @param message Descriptive error message\r\n     * @dev Used for general parameter validation failures\r\n     */\r\n    error InvalidParameters(string message);\r\n\r\n    /**\r\n     * @notice Thrown when an invalid price is provided (usually zero)\r\n     * @dev Price validation error\r\n     */\r\n    error InvalidPrice();\r\n\r\n    /**\r\n     * @notice Thrown when an invalid LTV value is provided\r\n     * @dev LTV must be between 0 and 100\r\n     */\r\n    error InvalidLTV();\r\n\r\n    /**\r\n     * @notice Thrown when attempting to register a duplicate subvault\r\n     * @param collateral Address of the collateral\r\n     * @param existingSubVault Address of the existing subvault\r\n     * @dev Prevents duplicate subvault registrations\r\n     */\r\n    error SubVaultAlreadyRegistered(address collateral, address existingSubVault);\r\n\r\n    /**\r\n     * @notice Thrown when an unsupported asset is used\r\n     * @param asset Address of the unsupported asset\r\n     * @dev Asset validation error\r\n     */\r\n    error AssetNotSupported(address asset);\r\n\r\n    /**\r\n     * @notice Thrown when attempting to use an inactive subvault\r\n     * @dev State validation error\r\n     */\r\n    error SubVaultNotActive();\r\n\r\n    /**\r\n     * @notice Thrown when an unauthorized subvault attempts an operation\r\n     * @param subVault Address of the unauthorized subvault\r\n     * @dev Subvault authorization error\r\n     */\r\n    error UnauthorizedSubVault(address subVault);\r\n\r\n    /**\r\n     * @notice Thrown when an invalid amount is provided\r\n     * @dev Amount validation error (usually zero)\r\n     */\r\n    error InvalidAmount();\r\n\r\n    /**\r\n     * @notice Thrown when a calculation results in overflow\r\n     * @dev Mathematical safety error\r\n     */\r\n    error CalculationOverflow();\r\n\r\n    /**\r\n     * @notice Thrown when a requested deposit cannot be found\r\n     * @param depositId ID of the missing deposit\r\n     * @dev Deposit lookup error\r\n     */\r\n    error DepositNotFound(uint256 depositId);\r\n\r\n    /**\r\n     * @notice Thrown when attempting to operate on an inactive deposit\r\n     * @dev Deposit state validation error\r\n     */\r\n    error DepositNotActive();\r\n}\r\n"},"contracts/errors/ISubVaultErrors.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.23;\r\n\r\n/**\r\n * @title SubVault Errors Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Defines error types specific to SubVault operations\r\n * @dev Interface containing SubVault-specific error definitions\r\n */\r\ninterface ISubVaultErrors {\r\n    /**\r\n     * @notice Thrown when caller is not authorized\r\n     * @param caller Address of unauthorized caller\r\n     */\r\n    error UnauthorizedCaller(address caller);\r\n\r\n    /**\r\n     * @notice Thrown when asset operation is unsupported\r\n     * @param asset Address of unsupported asset\r\n     */\r\n    error UnsupportedAsset(address asset);\r\n\r\n    /**\r\n     * @notice Thrown when asset is already configured\r\n     * @param asset Address of already supported asset\r\n     */\r\n    error AssetAlreadySupported(address asset);\r\n\r\n    /**\r\n     * @notice Thrown when address is invalid (usually zero)\r\n     * @param addr The invalid address\r\n     */\r\n    error InvalidAddress(address addr);\r\n\r\n    /**\r\n     * @notice Thrown when amount is invalid (usually zero)\r\n     */\r\n    error InvalidAmount();\r\n\r\n    /**\r\n     * @notice Thrown when deposit operation fails\r\n     * @param reason Description of failure\r\n     */\r\n    error DepositFailed(string reason);\r\n\r\n    /**\r\n     * @notice Thrown when withdrawal operation fails\r\n     * @param reason Description of failure\r\n     */\r\n    error WithdrawFailed(string reason);\r\n\r\n    /**\r\n     * @notice Thrown when emergency delay period hasn't passed\r\n     */\r\n    error EmergencyDelayNotPassed();\r\n\r\n    /**\r\n     * @notice Thrown when emergency mode is active\r\n     * @param timestamp Time when emergency mode was enabled\r\n     */\r\n    error EmergencyModeEnabled(uint256 timestamp);\r\n\r\n    /**\r\n     * @notice Thrown when emergency mode is not active\r\n     */\r\n    error EmergencyModeNotEnabled();\r\n\r\n    /**\r\n     * @notice Thrown when balance is insufficient\r\n     * @param requested Amount requested\r\n     * @param available Amount available\r\n     */\r\n    error InsufficientBalance(uint256 requested, uint256 available);\r\n\r\n    /**\r\n     * @notice Thrown when approval operation fails\r\n     * @param asset Asset for which approval failed\r\n     * @param spender Address that was to be approved\r\n     */\r\n    error ApprovalFailed(address asset, address spender);\r\n\r\n    /**\r\n     * @notice Thrown when attempting to remove primary asset\r\n     */\r\n    error CannotRemovePrimaryAsset();\r\n\r\n    /**\r\n     * @notice Thrown when primary asset operation fails\r\n     * @param reason Description of failure\r\n     */\r\n    error PrimaryAssetOperationFailed(string reason);\r\n\r\n    /**\r\n     * @notice Thrown when secondary asset operation fails\r\n     * @param reason Description of failure\r\n     */\r\n    error SecondaryAssetOperationFailed(string reason);\r\n\r\n    /**\r\n     * @notice Thrown when usual not initialized\r\n     */\r\n    error NotInitialized();\r\n\r\n    /**\r\n     * @notice Thrown when array length mismatch\r\n     */\r\n    error ArrayLengthMismatch();\r\n\r\n    /**\r\n     * @notice Thrown when an asset is not supported\r\n     * @param asset The unsupported asset address\r\n     * @dev Asset validation error\r\n     */\r\n    error AssetNotSupported(address asset);\r\n\r\n    /**\r\n     * @notice Thrown when a non-zero balance is found on an asset\r\n     * @param asset The asset with a non-zero balance\r\n     * @param balance The non-zero balance amount\r\n     * @dev Balance validation error\r\n     */\r\n    error NonZeroBalance(address asset, uint256 balance);\r\n\r\n    /**\r\n     * @notice Thrown when user has no yield to claim\r\n     * @dev Yield claim validation error\r\n     */\r\n    error NoYieldToClaim();\r\n\r\n    /**\r\n     * @notice Thrown when vault has insufficient balance for operation\r\n     * @dev Balance validation error\r\n     */\r\n    error InsufficientVaultBalance();\r\n}\r\n"},"contracts/errors/ISystemErrors.sol":{"content":"// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.23;\r\n\r\n/**\r\n * @title System Errors Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Defines standard error types used across the protocol\r\n * @dev Interface containing common error definitions\r\n */\r\ninterface ISystemErrors {\r\n    /**\r\n     * @notice Error thrown for invalid address inputs\r\n     * @param addr The invalid address\r\n     */\r\n    error InvalidAddress(address addr);\r\n\r\n    /**\r\n     * @notice Error thrown for unauthorized operations\r\n     * @param message Error description\r\n     */\r\n    error Unauthorized(string message);\r\n\r\n    /**\r\n     * @notice Error thrown for invalid role operations\r\n     * @param role Role identifier that caused the error\r\n     */\r\n    error InvalidRole(bytes32 role);\r\n\r\n    /**\r\n     * @notice Error thrown for invalid configuration parameters\r\n     * @param message Error description\r\n     */\r\n    error InvalidConfig(string message);\r\n\r\n    /**\r\n     * @notice Error thrown when an operation fails\r\n     * @param message Error description\r\n     */\r\n    error OperationFailed(string message);\r\n\r\n    /**\r\n     * @notice Error thrown for invalid array lengths in batch operations\r\n     */\r\n    error InvalidArrayLength();\r\n\r\n    /**\r\n     * @notice Error thrown when router is not properly set\r\n     * @param message Error description\r\n     */\r\n    error RouterNotSet(string message);\r\n\r\n    /**\r\n     * @notice Error thrown when caller is not the router\r\n     * @param message Error description\r\n     */\r\n    error NotRouter(string message);\r\n\r\n    /**\r\n     * @notice Error thrown for initial approval issues\r\n     * @param message Error description\r\n     */\r\n    error InitialApproval(string message);\r\n\r\n    /**\r\n     * @notice Error thrown when contract not found in registry\r\n     * @param id Contract identifier\r\n     */\r\n    error ContractNotFound(bytes32 id);\r\n\r\n    /**\r\n     * @notice Error thrown when trying to grant a role to the zero address\r\n     */\r\n    error ZeroAddress();\r\n\r\n    /**\r\n     * @notice Error thrown when version doesn't match expected\r\n     * @param expected Expected version\r\n     * @param actual Actual version\r\n     */\r\n    error InvalidVersion(uint256 expected, uint256 actual);\r\n\r\n    /**\r\n     * @notice Error thrown when contract already exists in registry\r\n     * @param id Contract identifier\r\n     */\r\n    error ContractExists(bytes32 id);\r\n}\r\n"},"contracts/errors/IWithdrawalSystemErrors.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.23;\r\n\r\n/**\r\n * @title Withdrawal System Errors Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Defines error types specific to WithdrawalSystem operations\r\n * @dev Interface containing WithdrawalSystem-specific error definitions\r\n */\r\ninterface IWithdrawalSystemErrors {\r\n    /**\r\n     * @notice Thrown when withdrawal request is not found\r\n     * @param requestId ID of the missing request\r\n     * @dev Request lookup error\r\n     */\r\n    error RequestNotFound(uint256 requestId);\r\n\r\n    /**\r\n     * @notice Thrown when request is in invalid state for operation\r\n     * @param currentStatus Current status of the request\r\n     * @dev State validation error\r\n     */\r\n    error InvalidRequestStatus(uint8 currentStatus);\r\n\r\n    /**\r\n     * @notice Thrown when caller is not authorized for operation\r\n     * @param caller Address attempting the operation\r\n     * @dev Authorization error\r\n     */\r\n    error UnauthorizedCaller(address caller);\r\n\r\n    /**\r\n     * @notice Thrown when request has expired\r\n     * @param expiryTime Timestamp when request expired\r\n     * @dev Time validation error\r\n     */\r\n    error RequestExpired(uint256 expiryTime);\r\n\r\n    /**\r\n     * @notice Thrown when processing cooldown period hasn't elapsed\r\n     * @param lastProcessingTime Last processing timestamp\r\n     * @param cooldownPeriod Required cooldown period\r\n     * @dev Timing constraint error\r\n     */\r\n    error ProcessingCooldownNotElapsed(uint256 lastProcessingTime, uint256 cooldownPeriod);\r\n\r\n    /**\r\n     * @notice Thrown when insufficient balance for withdrawal\r\n     * @param requested Amount requested\r\n     * @param available Amount available\r\n     * @dev Balance validation error\r\n     */\r\n    error InsufficientBalance(uint256 requested, uint256 available);\r\n\r\n    /**\r\n     * @notice Thrown when asset configuration is invalid\r\n     * @param asset Address of asset with invalid config\r\n     * @dev Configuration validation error\r\n     */\r\n    error InvalidAssetConfig(address asset);\r\n\r\n    /**\r\n     * @notice Thrown when withdrawal amount exceeds limits\r\n     * @param amount Requested amount\r\n     * @param limit Maximum allowed amount\r\n     * @dev Amount validation error\r\n     */\r\n    error WithdrawalLimitExceeded(uint256 amount, uint256 limit);\r\n\r\n    /**\r\n     * @notice Thrown when withdrawal processing fails\r\n     * @param reason Description of failure\r\n     * @dev Processing error\r\n     */\r\n    error ProcessingFailed(string reason);\r\n\r\n    /**\r\n     * @notice Thrown when claim operation fails\r\n     * @param reason Description of failure\r\n     * @dev Claim error\r\n     */\r\n    error ClaimFailed(string reason);\r\n\r\n    /**\r\n     * @notice Thrown when batch processing fails\r\n     * @param reason Description of failure\r\n     * @dev Batch operation error\r\n     */\r\n    error BatchProcessingFailed(string reason);\r\n\r\n    /**\r\n     * @notice Thrown when an unauthorized address attempts router operations\r\n     * @param caller Address attempting the operation\r\n     */\r\n    error UnauthorizedRouter(address caller);\r\n\r\n    /**\r\n     * @notice Thrown when an invalid (usually zero) address is provided\r\n     * @param addr The invalid address\r\n     * @dev Basic input validation error\r\n     */\r\n    error InvalidAddress(address addr);\r\n    /**\r\n     * @notice Thrown when an invalid amount is provided\r\n     * @dev Basic input validation error\r\n     */\r\n    error InvalidAmount();\r\n\r\n    /**\r\n     * @notice Thrown when withdrawal fails due to withdrawal system error\r\n     * @dev General withdrawal error\r\n     */\r\n    error WithdrawalFailed();\r\n}\r\n"},"contracts/errors/IZeUSDErrors.sol":{"content":"// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.23;\r\n\r\n/**\r\n * @title ZeUSD Errors Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Contains all custom errors used by the ZeUSD contract\r\n * @dev Interface containing ZeUSD-specific error definitions\r\n * @custom:security-contact paras@zoth.io\r\n */\r\ninterface IZeUSDErrors {\r\n    /**\r\n     * @notice Error thrown when router is not set\r\n     * @param _message Error message\r\n     * @dev Critical configuration error\r\n     */\r\n    error RouterNotSet(string _message);\r\n\r\n    /**\r\n     * @notice Error thrown when caller is not the router\r\n     * @param _message Error message\r\n     * @dev Authorization error for router-only functions\r\n     */\r\n    error NotRouter(string _message);\r\n\r\n    /**\r\n     * @notice Error thrown when an unauthorized operation is attempted\r\n     * @param _message Error message\r\n     * @dev General authorization error\r\n     */\r\n    error Unauthorized(string _message);\r\n\r\n    /**\r\n     * @notice Error thrown when address is invalid (zero address)\r\n     * @param addr The invalid address\r\n     * @dev Input validation error\r\n     */\r\n    error InvalidAddress(address addr);\r\n}\r\n"},"contracts/errors/IZeUSDRouterErrors.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.23;\r\n\r\n/**\r\n * @title ZeUSD Router Error Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Contains all error definitions for the ZeUSD Router contract\r\n * @dev Custom errors for better gas efficiency and more descriptive revert messages\r\n * @custom:security-contact paras@zoth.io\r\n */\r\ninterface IZeUSDRouterErrors {\r\n    /**\r\n     * @notice Thrown when an invalid (usually zero) address is provided\r\n     * @param addr The invalid address provided\r\n     * @dev Basic input validation error\r\n     */\r\n    error InvalidAddress(address addr);\r\n\r\n    /**\r\n     * @notice Thrown when operation involves an unsupported asset\r\n     * @param asset Address of the unsupported asset\r\n     * @dev Asset validation error\r\n     */\r\n    error AssetNotSupported(address asset);\r\n\r\n    /**\r\n     * @notice Thrown when trying to access non-existent integration\r\n     * @param integrationId ID of the integration that wasn't found\r\n     * @dev Integration lookup error\r\n     */\r\n    error IntegrationNotFound(bytes32 integrationId);\r\n\r\n    /**\r\n     * @notice Thrown when attempting to register an existing integration\r\n     * @param integrationId ID of the integration that already exists\r\n     * @dev Duplicate integration error\r\n     */\r\n    error IntegrationAlreadyExists(bytes32 integrationId);\r\n\r\n    /**\r\n     * @notice Thrown when attempting to use an inactive integration\r\n     * @param integrationId ID of the inactive integration\r\n     * @dev Integration state error\r\n     */\r\n    error IntegrationNotActive(bytes32 integrationId);\r\n\r\n    /**\r\n     * @notice Thrown when trying to perform operations while deposits are paused\r\n     * @dev System state error\r\n     */\r\n    error DepositsArePaused();\r\n\r\n    /**\r\n     * @notice Thrown when trying to use a paused subvault\r\n     * @param subVault Address of the paused subvault\r\n     * @dev SubVault state error\r\n     */\r\n    error SubVaultPaused(address subVault);\r\n\r\n    /**\r\n     * @notice Thrown when admin privileges are required but caller lacks them\r\n     * @dev Authorization error\r\n     */\r\n    error AdminRequired();\r\n\r\n    /**\r\n     * @notice Thrown when non-whitelisted account attempts restricted operation\r\n     * @param account Address of the non-whitelisted account\r\n     * @dev Access control error\r\n     */\r\n    error NotWhitelisted(address account);\r\n\r\n    /**\r\n     * @notice Thrown when blacklisted account attempts any operation\r\n     * @param account Address of the blacklisted account\r\n     * @dev Compliance restriction error\r\n     */\r\n    error Blacklisted(address account);\r\n\r\n    /**\r\n     * @notice Thrown when zero amount is provided for operations\r\n     * @dev Amount validation error\r\n     */\r\n    error ZeroAmount();\r\n\r\n    /**\r\n     * @notice Thrown when array lengths don't match in batch operations\r\n     * @dev Input validation error\r\n     */\r\n    error InvalidArrayLength();\r\n\r\n    /**\r\n     * @notice Thrown when deposit operation fails\r\n     * @param reason Description of why the deposit failed\r\n     * @dev Operation failure error\r\n     */\r\n    error DepositFailed(string reason);\r\n\r\n    /**\r\n     * @notice Thrown when bridge operation fails\r\n     * @param reason Description of why the bridge operation failed\r\n     * @dev Bridge operation error\r\n     */\r\n    error BridgeFailed(string reason);\r\n\r\n    /**\r\n     * @notice Thrown when withdrawal operation fails\r\n     * @param reason Description of why the withdrawal failed\r\n     * @dev Withdrawal operation error\r\n     */\r\n    error WithdrawFailed(string reason);\r\n\r\n    /**\r\n     * @notice Thrown when user has no locked assets for specified asset\r\n     * @param asset Address of the asset checked\r\n     * @dev Balance validation error\r\n     */\r\n    error NoLockedAssets(address asset);\r\n\r\n    /**\r\n     * @notice Thrown when insufficient locked assets available for operation\r\n     * @param requested Amount requested\r\n     * @param available Amount actually available\r\n     * @dev Balance validation error\r\n     */\r\n    error InsufficientLockedAssets(uint256 requested, uint256 available);\r\n\r\n    /**\r\n     * @notice Thrown when balance is insufficient for operation\r\n     * @param token Description of the token type lacking balance\r\n     * @dev Balance validation error\r\n     */\r\n    error InsufficientBalance(string token);\r\n\r\n    /**\r\n     * @notice Thrown when initial approval setup is required\r\n     * @param message Error description\r\n     * @dev Configuration error\r\n     */\r\n    error InitialApproval(string message);\r\n\r\n    /**\r\n     * @notice Thrown when registering an already registered asset\r\n     * @param asset The asset address\r\n     * @dev Duplicate asset error\r\n     */\r\n    error AssetAlreadyRegistered(address asset);\r\n\r\n    /**\r\n     * @notice Thrown when a subvault is already registered\r\n     * @param asset The associated asset\r\n     * @dev Duplicate subvault error\r\n     */\r\n    error SubvaultAlreadyRegistered(address asset);\r\n\r\n    /**\r\n     * @notice Thrown when attempting to operate on an inactive deposit\r\n     * @dev Deposit state validation error\r\n     */\r\n    error DepositNotActive();\r\n\r\n    /**\r\n     * @notice Error thrown when insufficient native fee is provided for LayerZero\r\n     * @param provided Amount of native token provided\r\n     * @param required Amount of native token required\r\n     */\r\n    error InsufficientNativeFee(uint256 provided, uint256 required);\r\n\r\n    /**\r\n     * @notice Error thrown when an invalid timestamp is provided\r\n     */\r\n    error InvalidTimestamp();\r\n\r\n    /**\r\n     * @notice Error thrown when an invalid amount is provided\r\n     */\r\n    error InvalidAmount();\r\n}\r\n"},"contracts/events/ICollateralVaultEvents.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.23;\r\n\r\nimport '../libraries/DataTypes.sol';\r\n\r\n/**\r\n * @title Collateral Vault Events Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Defines all events emitted by the CollateralVault contract\r\n * @dev Events are used for off-chain tracking and monitoring of vault activities\r\n */\r\ninterface ICollateralVaultEvents {\r\n    /**\r\n     * @notice Emitted when admin role is changed\r\n     * @param caller Address that initiated the admin change\r\n     * @param newAdmin Address of the new admin\r\n     * @dev Critical event for tracking administrative changes\r\n     */\r\n    event AdminChanged(address indexed caller, address indexed newAdmin);\r\n\r\n    /**\r\n     * @notice Emitted when router address is set\r\n     * @param router Address of the newly set router contract\r\n     * @dev Router can only be set once and is critical for deposit operations\r\n     */\r\n    event RouterSet(address indexed router);\r\n\r\n    /**\r\n     * @notice Emitted when a subvault is registered or updated\r\n     * @param collateralAddress Address of the collateral token being registered\r\n     * @param subVaultAddress Address of the subvault managing the collateral\r\n     * @param integrationType Type of integration (e.g., \"Aave\", \"Compound\")\r\n     * @param price Initial/updated price of the collateral\r\n     * @param ltv Initial/updated Loan-to-Value ratio\r\n     * @param isActive Whether the subvault is active\r\n     * @param tokenType Type classification of the collateral token\r\n     * @dev Used to track subvault registration and configuration changes\r\n     */\r\n    event SubVaultRegistered(\r\n        address indexed collateralAddress,\r\n        address indexed subVaultAddress,\r\n        string integrationType,\r\n        uint256 price,\r\n        uint256 ltv,\r\n        bool isActive,\r\n        DataTypes.TokenType tokenType\r\n    );\r\n\r\n    /**\r\n     * @notice Emitted when subvault configuration is updated\r\n     * @param collateralAddress Address of the collateral token\r\n     * @param subVaultAddress Address of the affected subvault\r\n     * @param price Updated price of the collateral\r\n     * @param ltv Updated Loan-to-Value ratio\r\n     * @param isActive Updated active status\r\n     * @dev Tracks changes to existing subvault configurations\r\n     */\r\n    event SubVaultUpdated(\r\n        address indexed collateralAddress,\r\n        address indexed subVaultAddress,\r\n        uint256 price,\r\n        uint256 ltv,\r\n        bool isActive\r\n    );\r\n\r\n    /**\r\n     * @notice Emitted when a subvault is removed from the system\r\n     * @param collateralAddress Address of the removed collateral token\r\n     * @param subVaultAddress Address of the removed subvault\r\n     * @dev Important for tracking decommissioned subvaults\r\n     */\r\n    event SubVaultRemoved(address indexed collateralAddress, address indexed subVaultAddress);\r\n\r\n    /**\r\n     * @notice Emitted when a new deposit is recorded\r\n     * @param user Address of the depositor\r\n     * @param asset Address of the deposited asset\r\n     * @param amount Amount of asset deposited\r\n     * @param depositId Unique identifier for the deposit\r\n     * @param subVault Address of the subvault processing the deposit\r\n     * @param integrationType Integration type used for the deposit\r\n     * @param isPrimary Whether this is a primary deposit\r\n     * @param mintAmount Amount of ZeUSD minted against this deposit\r\n     * @param tokenType Type classification of the deposited token\r\n     * @dev Comprehensive tracking of new deposits and their parameters\r\n     */\r\n    event DepositRecorded(\r\n        address indexed user,\r\n        address indexed asset,\r\n        uint256 amount,\r\n        uint256 depositId,\r\n        address subVault,\r\n        string integrationType,\r\n        bool isPrimary,\r\n        uint256 mintAmount,\r\n        DataTypes.TokenType tokenType\r\n    );\r\n\r\n    /**\r\n     * @notice Emitted when a deposit is deactivated\r\n     * @param user Address of the deposit owner\r\n     * @param depositId ID of the deactivated deposit\r\n     * @param asset Address of the deposited asset\r\n     * @param amount Original deposit amount\r\n     * @param mintedAmount Amount of ZeUSD that was minted\r\n     * @param subVault Address of the associated subvault\r\n     * @dev Tracks deposit deactivations and final state\r\n     */\r\n    event DepositDeactivated(\r\n        address indexed user,\r\n        uint256 indexed depositId,\r\n        address asset,\r\n        uint256 amount,\r\n        uint256 mintedAmount,\r\n        address subVault\r\n    );\r\n\r\n    /**\r\n     * @notice Emitted when a deposit record is permanently removed\r\n     * @param user Address of the deposit owner\r\n     * @param depositId ID of the removed deposit\r\n     * @param asset Address of the deposited asset\r\n     * @param amount Original deposit amount\r\n     * @param zeusdMinted Amount of ZeUSD that was minted\r\n     * @param subVault Address of the associated subvault\r\n     * @dev Tracks permanent removal of deposit records\r\n     */\r\n    event DepositRemoved(\r\n        address indexed user,\r\n        uint256 indexed depositId,\r\n        address asset,\r\n        uint256 amount,\r\n        uint256 zeusdMinted,\r\n        address subVault\r\n    );\r\n\r\n    /**\r\n     * @notice Emitted when a user deposit is updated\r\n     * @param user Address of the deposit owner\r\n     * @param depositId ID of the updated deposit\r\n     * @param collateralAddress Updated collateral address\r\n     * @param asset Updated asset address\r\n     * @param amount Updated amount\r\n     * @param zeusdMinted Updated ZeUSD minted amount\r\n     * @param active Updated active status\r\n     * @param isPrimary Updated primary status\r\n     * @dev Tracks changes to deposit parameters\r\n     */\r\n    event UserDepositUpdated(\r\n        address indexed user,\r\n        uint256 indexed depositId,\r\n        address collateralAddress,\r\n        address asset,\r\n        uint256 amount,\r\n        uint256 zeusdMinted,\r\n        bool active,\r\n        bool isPrimary\r\n    );\r\n\r\n    /**\r\n     * @notice Emitted when router address is updated\r\n     * @param newRouter Address of the new router\r\n     * @dev Tracks router address changes\r\n     */\r\n    event RouterUpdated(address indexed newRouter);\r\n}\r\n"},"contracts/events/ISubVaultEvents.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.23;\r\n\r\n/**\r\n * @title SubVault Events Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Events emitted by subvault operations\r\n * @dev All events that can be emitted by SubVault\r\n */\r\ninterface ISubVaultEvents {\r\n    /**\r\n     * @notice Emitted when router address is set\r\n     * @param router Address of the newly set router contract\r\n     * @dev Router can only be set once and is critical for deposit operations\r\n     */\r\n    event RouterSet(address indexed router);\r\n\r\n    /**\r\n     * @notice Emitted when oracle is set for an asset\r\n     * @param asset Asset address\r\n     * @param oracle Oracle address\r\n     * @dev Price oracle configuration event\r\n     */\r\n    event AssetOracleSet(address indexed asset, address indexed oracle);\r\n\r\n    /**\r\n     * @notice Emitted when an asset is added to supported assets\r\n     * @param asset Address of added asset\r\n     * @param reason Reason for adding\r\n     * @dev Asset support tracking event\r\n     */\r\n    event AssetAdded(address indexed asset, string reason);\r\n\r\n    /**\r\n     * @notice Emitted when an asset is removed from supported assets\r\n     * @param asset Address of removed asset\r\n     * @param reason Reason for removal\r\n     * @dev Asset removal tracking event\r\n     */\r\n    event AssetRemoved(address indexed asset, string reason);\r\n\r\n    /**\r\n     * @notice Emitted when a deposit is processed\r\n     * @param user User who deposited\r\n     * @param asset Asset deposited\r\n     * @param amount Amount deposited\r\n     * @param shares Shares minted\r\n     * @dev Deposit tracking event\r\n     */\r\n    event DepositProcessed(\r\n        address indexed user,\r\n        address indexed asset,\r\n        uint256 amount,\r\n        uint256 shares\r\n    );\r\n\r\n    /**\r\n     * @notice Emitted when a withdrawal is processed\r\n     * @param user User who withdrew\r\n     * @param asset Asset withdrawn\r\n     * @param amount Amount withdrawn\r\n     * @dev Withdrawal tracking event\r\n     */\r\n    event WithdrawProcessed(address indexed user, address indexed asset, uint256 amount);\r\n\r\n    /**\r\n     * @notice Emitted when emergency withdrawal is executed\r\n     * @param asset Asset withdrawn\r\n     * @param to Recipient address\r\n     * @param amount Amount withdrawn\r\n     * @param reason Reason for withdrawal\r\n     * @dev Emergency operation tracking event\r\n     */\r\n    event EmergencyWithdrawalExecuted(\r\n        address indexed asset,\r\n        address indexed to,\r\n        uint256 amount,\r\n        string reason\r\n    );\r\n\r\n    /**\r\n     * @notice Emitted when emergency mode status changes\r\n     * @param timestamp Time of change\r\n     * @param enabled New status\r\n     * @dev Emergency state tracking event\r\n     */\r\n    event EmergencyModeSet(uint256 timestamp, bool enabled);\r\n\r\n    /**\r\n     * @notice Emitted when admin role changes\r\n     * @param oldAdmin Previous admin address\r\n     * @param newAdmin New admin address\r\n     * @dev Administrative change tracking event\r\n     */\r\n    event AdminChanged(address indexed oldAdmin, address indexed newAdmin);\r\n\r\n    /**\r\n     * @notice Emitted when approval is granted\r\n     * @param asset Asset approved\r\n     * @param spender Address approved to spend\r\n     * @param amount Amount approved\r\n     * @dev Asset approval tracking event\r\n     */\r\n    event ApprovalGranted(address indexed asset, address indexed spender, uint256 amount);\r\n\r\n    /**\r\n     * @notice Emitted when approval is revoked\r\n     * @param asset Asset for which approval was revoked\r\n     * @param spender Address whose approval was revoked\r\n     * @dev Asset approval revocation tracking event\r\n     */\r\n    event ApprovalRevoked(address indexed asset, address indexed spender);\r\n\r\n    /**\r\n     * @notice Emitted when primary asset operation occurs\r\n     * @param user User involved in operation\r\n     * @param amount Amount involved\r\n     * @param isDeposit Whether operation was deposit\r\n     * @dev Primary asset operation tracking event\r\n     */\r\n    event PrimaryAssetOperation(address indexed user, uint256 amount, bool isDeposit);\r\n\r\n    /**\r\n     * @notice Emitted when secondary asset operation occurs\r\n     * @param asset Secondary asset involved\r\n     * @param user User involved in operation\r\n     * @param amount Amount involved\r\n     * @param isDeposit Whether operation was deposit\r\n     * @dev Secondary asset operation tracking event\r\n     */\r\n    event SecondaryAssetOperation(\r\n        address indexed asset,\r\n        address indexed user,\r\n        uint256 amount,\r\n        bool isDeposit\r\n    );\r\n\r\n    /**\r\n     * @notice Emitted when stable whitelist status changes\r\n     * @param user Address that was affected\r\n     * @param status New whitelist status\r\n     */\r\n    event StableWhitelistStatusChanged(address indexed user, bool status);\r\n}\r\n"},"contracts/events/IWithdrawalSystemEvents.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.23;\r\n\r\nimport '../libraries/WithdrawalSystemTypes.sol';\r\n\r\n/**\r\n * @title Withdrawal System Events Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Contains all events emitted by the Withdrawal System\r\n * @dev Events are used for tracking state changes and important operations in the withdrawal process\r\n */\r\ninterface IWithdrawalSystemEvents {\r\n    /**\r\n     * @notice Emitted when a new withdrawal request is created\r\n     * @dev This event should be monitored for tracking new withdrawal requests\r\n     * @param requestId Unique identifier for the withdrawal request\r\n     * @param user Address of the user initiating the withdrawal\r\n     * @param asset Contract address of the asset being withdrawn\r\n     * @param amount Amount of asset requested for withdrawal\r\n     * @param nftTokenId ID of the deposit NFT being used for withdrawal\r\n     * @param isStable Boolean indicating if the asset is a stablecoin\r\n     */\r\n    event WithdrawalRequested(\r\n        uint256 indexed requestId,\r\n        address indexed user,\r\n        address asset,\r\n        uint256 amount,\r\n        uint256 nftTokenId,\r\n        bool isStable\r\n    );\r\n\r\n    /**\r\n     * @notice Emitted when a withdrawal request's status changes\r\n     * @dev Used to track the lifecycle of withdrawal requests\r\n     * @param requestId ID of the withdrawal request being updated\r\n     * @param newStatus Updated status from WithdrawalSystemTypes.RequestStatus enum\r\n     */\r\n    event RequestStatusUpdated(\r\n        uint256 indexed requestId,\r\n        WithdrawalSystemTypes.RequestStatus newStatus\r\n    );\r\n\r\n    /**\r\n     * @notice Emitted when a withdrawal request is successfully processed\r\n     * @dev Indicates successful completion of withdrawal processing\r\n     * @param requestId ID of the processed withdrawal request\r\n     * @param user Address of the user receiving the withdrawal\r\n     * @param amount Final amount processed for withdrawal\r\n     */\r\n    event WithdrawalProcessed(uint256 indexed requestId, address user, uint256 amount);\r\n\r\n    /**\r\n     * @notice Emitted when a withdrawal request enters the processing queue\r\n     * @dev Used for tracking requests that are ready for batch processing\r\n     * @param requestId ID of the queued withdrawal request\r\n     */\r\n    event WithdrawalQueued(uint256 indexed requestId);\r\n\r\n    /**\r\n     * @notice Emitted when an asset's withdrawal configuration is updated\r\n     * @dev Used to track changes in asset-specific withdrawal parameters\r\n     * @param asset Address of the asset whose configuration was updated\r\n     * @param config New configuration parameters for the asset\r\n     */\r\n    event AssetConfigUpdated(address asset, WithdrawalSystemTypes.AssetConfig config);\r\n\r\n    /**\r\n     * @notice Emitted when the router address is set\r\n     * @dev Used to track the router address\r\n     * @param router Address of the router\r\n     */\r\n    event RouterSet(address indexed router);\r\n\r\n    /**\r\n     * @notice Emitted when router address is updated\r\n     * @param newRouter Address of the new router\r\n     * @dev Tracks router address changes\r\n     */\r\n    event RouterUpdated(address indexed newRouter);\r\n\r\n    /**\r\n     * @notice Emitted when the TBill subvault address is updated\r\n     * @param newTBillSubVault Address of the new TBill subvault\r\n     */\r\n    event TBillSubVaultUpdated(address indexed newTBillSubVault);\r\n\r\n    /**\r\n     * @notice Emitted when the USYC subvault address is updated\r\n     * @param newUSYCSubVault Address of the new USYC subvault\r\n     */\r\n    event USYCSubVaultUpdated(address indexed newUSYCSubVault);\r\n\r\n    /**\r\n     * @notice Emitted when the USDC address is updated\r\n     * @param newUSDC Address of the new USDC address\r\n     */\r\n    event USDCUpdated(address indexed newUSDC);\r\n\r\n    /**\r\n     * @notice Emitted when a withdrawal request is updated\r\n     * @dev Used to track updates to withdrawal requests\r\n     * @param requestId ID of the withdrawal request being updated\r\n     * @param asset Address of the asset being updated\r\n     * @param amount New amount for the withdrawal request\r\n     */\r\n    event RequestUpdated(uint256 requestId, address asset, uint256 amount);\r\n}\r\n"},"contracts/events/IZeUSDEvents.sol":{"content":"// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.23;\r\n\r\n/**\r\n * @title ZeUSD Events Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Defines events specific to the ZeUSD token contract\r\n * @dev Interface containing ZeUSD-specific event definitions\r\n */\r\ninterface IZeUSDEvents {\r\n    /**\r\n     * @notice Emitted when router address is updated\r\n     * @param newRouter Address of the new router\r\n     * @dev Critical configuration change event\r\n     */\r\n    event RouterUpdated(address indexed newRouter);\r\n\r\n    /**\r\n     * @notice Emitted when an account's blacklist status changes\r\n     * @param account Address that was affected\r\n     * @param status New blacklist status (true = blacklisted)\r\n     * @dev Compliance tracking event\r\n     */\r\n    event Blacklisted(address indexed account, bool status);\r\n\r\n    /**\r\n     * @notice Emitted when V2 initialization is completed\r\n     * @param accessController Address of the access controller contract\r\n     * @dev Upgrade tracking event\r\n     */\r\n    event V2Initialized(address indexed accessController);\r\n}\r\n"},"contracts/events/IZeUSDRouterEvents.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.23;\r\n\r\nimport '../libraries/DataTypes.sol';\r\n\r\n/**\r\n * @title ZeUSD Router Event Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Contains all events emitted by the ZeUSD Router contract\r\n * @dev Events for tracking state changes and important operations\r\n * @custom:security Events should be monitored for system activity\r\n */\r\ninterface IZeUSDRouterEvents {\r\n    /**\r\n     * @notice Emitted when a new integration is registered\r\n     * @dev Tracks addition of new protocol integrations\r\n     * @param integrationId Unique identifier for the integration\r\n     * @param integrationType Type of integration being registered (e.g., \"AAVE\", \"Compound\")\r\n     * @param subVault Address of the associated subvault\r\n     */\r\n    event IntegrationRegistered(\r\n        bytes32 indexed integrationId,\r\n        string integrationType,\r\n        address subVault\r\n    );\r\n\r\n    /**\r\n     * @notice Emitted when an integration is updated\r\n     * @dev Tracks changes to existing integrations\r\n     * @param integrationId ID of the updated integration\r\n     * @param newSubVault New subvault address\r\n     * @param isActive New active status\r\n     */\r\n    event IntegrationUpdated(bytes32 indexed integrationId, address newSubVault, bool isActive);\r\n\r\n    /**\r\n     * @notice Emitted when asset support is added to an integration\r\n     * @dev Tracks expansion of supported assets\r\n     * @param integrationId ID of the integration\r\n     * @param asset Address of the newly supported asset\r\n     */\r\n    event AssetSupportAdded(bytes32 indexed integrationId, address indexed asset);\r\n\r\n    /**\r\n     * @notice Emitted when a deposit is processed\r\n     * @dev Tracks successful deposit operations\r\n     * @param user Address of the depositing user\r\n     * @param depositId Unique identifier for the deposit\r\n     * @param asset Address of the deposited asset\r\n     * @param amount Amount of asset deposited\r\n     * @param zeusdMinted Amount of zeUSD minted\r\n     * @param subVault Address of the subvault used\r\n     */\r\n    event Deposit(\r\n        address indexed user,\r\n        uint256 depositId,\r\n        address indexed asset,\r\n        uint256 amount,\r\n        uint256 zeusdMinted,\r\n        address indexed subVault\r\n    );\r\n\r\n    /**\r\n     * @notice Emitted when a cross-chain bridge transfer is initiated\r\n     * @dev Tracks start of bridge operations\r\n     * @param user Address initiating the bridge\r\n     * @param asset Address of the bridged asset\r\n     * @param amount Amount being bridged\r\n     */\r\n    event BridgeInitiated(address indexed user, address indexed asset, uint256 amount);\r\n\r\n    /**\r\n     * @notice Emitted when zeUSD is burned\r\n     * @dev Tracks token burning operations\r\n     * @param user Address burning zeUSD\r\n     * @param asset Address of the released asset\r\n     * @param amount Amount burned\r\n     * @param subVault Address of the subvault\r\n     */\r\n    event Burned(\r\n        address indexed user,\r\n        address indexed asset,\r\n        uint256 amount,\r\n        address indexed subVault\r\n    );\r\n\r\n    /**\r\n     * @notice Emitted when global deposit status changes\r\n     * @dev Tracks changes to deposit pause status\r\n     * @param paused New pause status\r\n     */\r\n    event DepositsStatusChanged(bool paused);\r\n\r\n    /**\r\n     * @notice Emitted when subvault status changes\r\n     * @param subVault Address of the subvault\r\n     * @param paused New pause status\r\n     */\r\n    event SubVaultStatusChanged(address indexed subVault, bool paused);\r\n\r\n    /**\r\n     * @notice Emitted when account whitelist status changes\r\n     * @param account Address affected\r\n     * @param status New whitelist status\r\n     */\r\n    event WhitelistStatusChanged(address indexed account, bool status);\r\n\r\n    /**\r\n     * @notice Emitted when account blacklist status changes\r\n     * @param account Address affected\r\n     * @param status New blacklist status\r\n     */\r\n    event BlacklistStatusChanged(address indexed account, bool status);\r\n\r\n    /**\r\n     * @notice Emitted when multiple whitelist statuses are updated\r\n     * @param accounts Array of addresses affected\r\n     * @param statuses Array of new whitelist statuses\r\n     */\r\n    event MultipleWhitelistStatusChanged(address[] accounts, bool[] statuses);\r\n\r\n    /**\r\n     * @notice Emitted when admin address changes\r\n     * @param newAdmin Address of new admin\r\n     */\r\n    event AdminChanged(address indexed newAdmin);\r\n\r\n    /**\r\n     * @notice Emitted when LayerZero adapter is updated\r\n     * @param oldAdapter Address of previous adapter\r\n     * @param newAdapter Address of new adapter\r\n     */\r\n    event LZAdapterUpdated(address indexed oldAdapter, address indexed newAdapter);\r\n\r\n    /**\r\n     * @notice Emitted when USDC address is updated\r\n     * @param oldUSDC Previous USDC address\r\n     * @param newUSDC New USDC address\r\n     */\r\n    event USDCUpdated(address indexed oldUSDC, address indexed newUSDC);\r\n\r\n    /**\r\n     * @notice Emitted when a primary asset is registered\r\n     * @param asset Primary asset address\r\n     * @param subvault Dedicated subvault address\r\n     */\r\n    event PrimaryAssetRegistered(address indexed asset, address indexed subvault);\r\n\r\n    /**\r\n     * @notice Emitted when ZTLNPrime subvault is updated\r\n     * @param oldSubvault Previous subvault address\r\n     * @param newSubvault New subvault address\r\n     */\r\n    event ZTLNPrimeSubvaultUpdated(address indexed oldSubvault, address indexed newSubvault);\r\n\r\n    /**\r\n     * @notice Emitted when protocol addresses are updated\r\n     * @param collateralVault New address of the collateral vault contract (indexed)\r\n     * @param zeusdToken New address of the ZeUSD token contract (indexed)\r\n     * @param lzAdapter New address of the LayerZero adapter contract\r\n     */\r\n    event AddressesUpdated(\r\n        address indexed collateralVault,\r\n        address indexed zeusdToken,\r\n        address lzAdapter\r\n    );\r\n\r\n    /**\r\n     * @notice Emitted when V2 is initialized\r\n     * @param accessController New address of the access controller contract\r\n     * @param withdrawalSystem New address of the withdrawal system contract\r\n     * @param depositNFT New address of the deposit NFT contract\r\n     */\r\n    event V2Initialized(address accessController, address withdrawalSystem, address depositNFT);\r\n    /**\r\n     * @notice Emitted when a deposit is processed\r\n     * @param user Address of the depositor\r\n     * @param tokenId ID of the minted NFT\r\n     * @param asset Address of the deposited asset\r\n     * @param amount Amount of asset deposited\r\n     * @param zeusdMinted Amount of ZeUSD minted\r\n     */\r\n    event DepositProcessed(\r\n        address indexed user,\r\n        uint256 indexed tokenId,\r\n        address indexed asset,\r\n        uint256 amount,\r\n        uint256 zeusdMinted\r\n    );\r\n\r\n    /**\r\n     * @notice Emitted when a historical NFT is issued\r\n     * @param issuer Address of the user who issued the NFT\r\n     * @param tokenId ID of the minted NFT\r\n     * @param collateralAddress Address of the collateral asset\r\n     * @param asset Address of the deposited asset\r\n     * @param amount Amount of asset deposited\r\n     * @param zeusdMinted Amount of ZeUSD minted\r\n     * @param depositTimestamp Timestamp of the deposit\r\n     * @param collateralPrice Price of collateral at deposit time\r\n     * @param subVault Address of the subvault\r\n     * @param tokenType Type of token deposited\r\n     */\r\n    event HistoricalNFTIssued(\r\n        address indexed issuer,\r\n        uint256 indexed tokenId,\r\n        address indexed collateralAddress,\r\n        address asset,\r\n        uint256 amount,\r\n        uint256 zeusdMinted,\r\n        uint256 depositTimestamp,\r\n        uint256 collateralPrice,\r\n        address subVault,\r\n        DataTypes.TokenType tokenType\r\n    );\r\n}\r\n"},"contracts/implementations/LZAdapter.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.23;\r\n\r\nimport { OFTAdapter } from '@layerzerolabs/oft-evm/contracts/OFTAdapter.sol';\r\nimport { Ownable } from '@openzeppelin/contracts/access/Ownable.sol';\r\n\r\n/// @notice OFTAdapter uses a deployed ERC-20 token and safeERC20 to interact with the OFTCore contract.\r\ncontract LZAdapter is OFTAdapter {\r\n    constructor(\r\n        address _token,\r\n        address _lzEndpoint,\r\n        address _owner\r\n    ) OFTAdapter(_token, _lzEndpoint, _owner) Ownable(_owner) {}\r\n}\r\n"},"contracts/implementations/ZeUSD_CDP.sol":{"content":"// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.23;\r\n\r\nimport '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol';\r\nimport '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol';\r\nimport '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol';\r\nimport '../interfaces/access/IAccessController.sol';\r\nimport '../interfaces/access/IRegistry.sol';\r\nimport '../libraries/DataTypes.sol';\r\nimport '../utils/AccessChecker.sol';\r\nimport '../utils/Constants.sol';\r\nimport '../libraries/SystemRoles.sol';\r\nimport '../interfaces/IZeUSD_CDP.sol';\r\nimport '@openzeppelin/contracts/interfaces/IERC165.sol';\r\n\r\n/**\r\n * @title Deposit NFT\r\n * @author ZeUSD Protocol Team\r\n * @notice NFT contract representing user deposits in the protocol\r\n * @dev Implements UUPS upgradeable pattern with ERC721 extensions\r\n * @custom:security-contact paras@zoth.io\r\n *\r\n * Core Features:\r\n * - ERC721 token standard\r\n * - URI storage for metadata\r\n * - Enumerable extension for tracking\r\n * - Deposit metadata storage\r\n * - Role-based access control\r\n *\r\n * Security Considerations:\r\n * - Only router can mint/burn\r\n * - Admin-controlled URI updates\r\n * - Protected upgrade mechanism\r\n * - Token ID uniqueness\r\n * - Metadata integrity\r\n *\r\n * Storage Layout:\r\n * - Token metadata\r\n * - Deposit details\r\n * - URI configuration\r\n * - Access control state\r\n *\r\n * Role Requirements:\r\n * DEFAULT_ADMIN_ROLE:\r\n * - Can update base URI\r\n * - Can upgrade contract\r\n *\r\n * UPGRADER_ROLE:\r\n * - Can perform contract upgrades\r\n */\r\ncontract ZeUSD_CDP is\r\n    ERC721URIStorageUpgradeable,\r\n    ERC721EnumerableUpgradeable,\r\n    UUPSUpgradeable,\r\n    IZeUSD_CDP\r\n{\r\n    /// @notice Access controller contract reference\r\n    /// @dev Used for role checks\r\n    IAccessController public accessController;\r\n\r\n    /// @notice Router contract that can mint/burn NFTs\r\n    /// @dev Only address allowed to mint and burn\r\n    address public router;\r\n\r\n    /// @notice Base URI for token metadata\r\n    /// @dev Used as prefix for all token URIs\r\n    string public baseURI;\r\n\r\n    /// @notice Auto-incrementing token ID counter\r\n    /// @dev Ensures unique token IDs\r\n    uint256 private _tokenIdCounter;\r\n\r\n    /// @notice Deposit details mapped to token ID\r\n    /// @dev Stores deposit metadata for each token\r\n    mapping(uint256 => DataTypes.DepositMetadata) public depositDetails;\r\n\r\n    /// @notice Next token ID counter\r\n    /// @dev Used to get the next token ID without incrementing\r\n    uint256 private _nextTokenId;\r\n\r\n    /**\r\n     * @notice Emitted when a deposit NFT is minted\r\n     * @param tokenId ID of minted token\r\n     * @param owner Address receiving the token\r\n     * @param metadata Associated deposit metadata\r\n     */\r\n    event ZeUSD_CDPMinted(\r\n        uint256 indexed tokenId,\r\n        address indexed owner,\r\n        DataTypes.DepositMetadata metadata\r\n    );\r\n\r\n    /**\r\n     * @notice Emitted when a deposit NFT is burned\r\n     * @param tokenId ID of burned token\r\n     * @param owner Last owner of the token\r\n     */\r\n    event ZeUSD_CDPBurned(uint256 indexed tokenId, address indexed owner);\r\n\r\n    /**\r\n     * @notice Emitted when base URI is updated\r\n     * @param newBaseURI New base URI value\r\n     */\r\n    event BaseURIUpdated(string newBaseURI);\r\n\r\n    /**\r\n     * @notice Emitted when deposit metadata is updated\r\n     * @param tokenId ID of the token whose metadata was updated\r\n     * @param metadata Updated deposit metadata\r\n     */\r\n    event DepositMetadataUpdated(uint256 indexed tokenId, DataTypes.DepositMetadata metadata);\r\n\r\n    /**\r\n     * @notice Error thrown for invalid address inputs\r\n     * @param addr The invalid address\r\n     */\r\n    error InvalidAddress(address addr);\r\n\r\n    /**\r\n     * @notice Error thrown for unauthorized operations\r\n     * @param message Error description\r\n     */\r\n    error Unauthorized(string message);\r\n\r\n    /**\r\n     * @notice Error thrown when token doesn't exist\r\n     * @param tokenId ID of non-existent token\r\n     */\r\n    error TokenNotExists(uint256 tokenId);\r\n\r\n    function initialize(\r\n        string memory name,\r\n        string memory symbol,\r\n        string memory initialBaseURI,\r\n        address _router,\r\n        address registryContract\r\n    ) public initializer {\r\n        __ERC721_init(name, symbol);\r\n        __ERC721URIStorage_init();\r\n        __ERC721Enumerable_init();\r\n        __UUPSUpgradeable_init();\r\n\r\n        if (_router == address(0)) revert InvalidAddress(_router);\r\n        if (registryContract == address(0)) revert InvalidAddress(registryContract);\r\n\r\n        router = _router;\r\n        baseURI = initialBaseURI;\r\n        accessController = IAccessController(\r\n            IRegistry(registryContract).getContract(Constants.CONTRACT_ACCESS_CONTROLLER)\r\n        );\r\n    }\r\n\r\n    /**\r\n     * @notice Gets the next token ID without incrementing\r\n     * @return The next token ID that will be used\r\n     */\r\n    function getNextTokenId() external view returns (uint256) {\r\n        return _nextTokenId;\r\n    }\r\n\r\n    /**\r\n     * @notice Mints a new deposit NFT\r\n     * @dev Only callable by router\r\n     * @param to Address to mint the NFT to\r\n     * @param metadata Deposit metadata to store\r\n     * @return tokenId The ID of the minted token\r\n     * @custom:security Validates router and recipient\r\n     * @custom:emits ZeUSD_CDPMinted\r\n     */\r\n    function mint(\r\n        address to,\r\n        DataTypes.DepositMetadata calldata metadata\r\n    ) external returns (uint256 tokenId) {\r\n        if (msg.sender != router) revert Unauthorized('Only router can mint');\r\n        if (to == address(0)) revert InvalidAddress(to);\r\n\r\n        tokenId = _nextTokenId++;\r\n        _safeMint(to, tokenId);\r\n        depositDetails[tokenId] = metadata;\r\n\r\n        emit ZeUSD_CDPMinted(tokenId, to, metadata);\r\n        return tokenId;\r\n    }\r\n\r\n    /**\r\n     * @notice Burns a deposit NFT\r\n     * @dev Can be called by router or token owner\r\n     * @param tokenId ID of token to burn\r\n     * @custom:security Validates caller authorization\r\n     * @custom:emits ZeUSD_CDPBurned\r\n     */\r\n    function burn(uint256 tokenId) external {\r\n        if (!_exists(tokenId)) revert TokenNotExists(tokenId);\r\n        if (msg.sender != router && msg.sender != ownerOf(tokenId))\r\n            revert Unauthorized('Not authorized to burn');\r\n\r\n        address owner = ownerOf(tokenId);\r\n        _burn(tokenId);\r\n        delete depositDetails[tokenId];\r\n\r\n        emit ZeUSD_CDPBurned(tokenId, owner);\r\n    }\r\n\r\n    /**\r\n     * @notice Burns a deposit NFT from an user's address\r\n     * @dev Only callable by DEFAULT_ADMIN_ROLE\r\n     * @param tokenId ID of token to burn\r\n     * @param user Address of the attacker\r\n     * @custom:security Validates admin role and token ownership\r\n     * @custom:emits ZeUSD_CDPBurned\r\n     */\r\n    function burnFromUser(uint256 tokenId, address user) external {\r\n        AccessChecker.checkRole(accessController, SystemRoles.DEFAULT_ADMIN_ROLE, msg.sender);\r\n\r\n        if (!_exists(tokenId)) revert TokenNotExists(tokenId);\r\n        if (ownerOf(tokenId) != user) revert Unauthorized('Token not owned by user');\r\n\r\n        _burn(tokenId);\r\n        delete depositDetails[tokenId];\r\n\r\n        emit ZeUSD_CDPBurned(tokenId, user);\r\n    }\r\n\r\n    /**\r\n     * @notice Updates the base URI for token metadata\r\n     * @dev Only callable by admin\r\n     * @param newBaseURI New base URI to set\r\n     * @custom:security Requires DEFAULT_ADMIN_ROLE\r\n     * @custom:emits BaseURIUpdated\r\n     */\r\n    function setBaseURI(string memory newBaseURI) external {\r\n        AccessChecker.checkRole(accessController, SystemRoles.DEFAULT_ADMIN_ROLE, msg.sender);\r\n        baseURI = newBaseURI;\r\n        emit BaseURIUpdated(newBaseURI);\r\n    }\r\n\r\n    /**\r\n     * @notice Returns the base URI for token metadata\r\n     * @return string Base URI\r\n     */\r\n    function _baseURI() internal view override returns (string memory) {\r\n        return baseURI;\r\n    }\r\n\r\n    /**\r\n     * @notice Generates the token URI combining base URI and token ID\r\n     * @param tokenId Token ID to get URI for\r\n     * @return Full token URI\r\n     * @custom:security Validates token existence\r\n     */\r\n    function tokenURI(\r\n        uint256 tokenId\r\n    ) public view override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) {\r\n        if (!_exists(tokenId)) revert TokenNotExists(tokenId);\r\n\r\n        string memory baseTokenURI = _baseURI();\r\n        if (bytes(baseTokenURI).length == 0) {\r\n            return '';\r\n        }\r\n\r\n        return string(abi.encodePacked(baseTokenURI, _toString(tokenId)));\r\n    }\r\n\r\n    /**\r\n     * @notice Gets deposit details for a specific token ID\r\n     * @param tokenId ID of the token to query\r\n     * @return metadata Deposit metadata associated with the token\r\n     * @custom:security Validates token existence\r\n     */\r\n    function getDepositDetails(\r\n        uint256 tokenId\r\n    ) external view override returns (DataTypes.DepositMetadata memory metadata) {\r\n        require(_exists(tokenId), 'Token does not exist');\r\n        return depositDetails[tokenId];\r\n    }\r\n\r\n    /**\r\n     * @notice Gets all token IDs owned by a specific address\r\n     * @param owner Address to query tokens for\r\n     * @return Array of token IDs\r\n     */\r\n    function getTokensByOwner(address owner) external view returns (uint256[] memory) {\r\n        uint256 balance = balanceOf(owner);\r\n        uint256[] memory tokenIds = new uint256[](balance);\r\n\r\n        for (uint256 i = 0; i < balance; i++) {\r\n            tokenIds[i] = tokenOfOwnerByIndex(owner, i);\r\n        }\r\n\r\n        return tokenIds;\r\n    }\r\n\r\n    /**\r\n     * @notice Converts uint256 to string\r\n     * @param value Number to convert\r\n     * @return string String representation\r\n     */\r\n    function _toString(uint256 value) internal pure returns (string memory) {\r\n        if (value == 0) {\r\n            return '0';\r\n        }\r\n        uint256 temp = value;\r\n        uint256 digits;\r\n        while (temp != 0) {\r\n            digits++;\r\n            temp /= 10;\r\n        }\r\n        bytes memory buffer = new bytes(digits);\r\n        while (value != 0) {\r\n            digits -= 1;\r\n            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\r\n            value /= 10;\r\n        }\r\n        return string(buffer);\r\n    }\r\n\r\n    /**\r\n     * @notice Authorizes contract upgrades\r\n     * @dev Only UPGRADER_ROLE can upgrade the contract\r\n     * @custom:security Critical upgrade operation\r\n     */\r\n    function _authorizeUpgrade(address /*newImplementation*/) internal view override {\r\n        AccessChecker.checkRole(accessController, SystemRoles.UPGRADER_ROLE, msg.sender);\r\n    }\r\n\r\n    /**\r\n     * @notice Interface support check\r\n     * @dev ERC165 interface detection\r\n     * @param interfaceId Interface identifier to check\r\n     * @return bool True if interface is supported\r\n     */\r\n    function supportsInterface(\r\n        bytes4 interfaceId\r\n    )\r\n        public\r\n        view\r\n        virtual\r\n        override(ERC721URIStorageUpgradeable, ERC721EnumerableUpgradeable, IERC165)\r\n        returns (bool)\r\n    {\r\n        return super.supportsInterface(interfaceId);\r\n    }\r\n\r\n    /**\r\n     * @notice Checks if a token exists\r\n     * @param tokenId Token ID to check\r\n     * @return bool True if token exists\r\n     */\r\n    function _exists(uint256 tokenId) internal view returns (bool) {\r\n        try this.ownerOf(tokenId) returns (address) {\r\n            return true;\r\n        } catch {\r\n            return false;\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @notice Increases balance for enumerable extension\r\n     * @dev Required override for ERC721Enumerable\r\n     * @param account Address to increase balance for\r\n     * @param amount Amount to increase by\r\n     */\r\n    function _increaseBalance(\r\n        address account,\r\n        uint128 amount\r\n    ) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable) {\r\n        super._increaseBalance(account, amount);\r\n    }\r\n\r\n    /**\r\n     * @notice Updates token ownership\r\n     * @dev Required override for ERC721Enumerable\r\n     * @param to New owner address\r\n     * @param tokenId Token ID to update\r\n     * @param auth Address authorized for transfer\r\n     * @return address Previous owner\r\n     */\r\n    function _update(\r\n        address to,\r\n        uint256 tokenId,\r\n        address auth\r\n    ) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable) returns (address) {\r\n        return super._update(to, tokenId, auth);\r\n    }\r\n\r\n    /**\r\n     * @notice Sets the router contract address\r\n     * @dev Only callable by DEFAULT_ADMIN_ROLE\r\n     * @param _router New router address\r\n     */\r\n    function setRouter(address _router) external {\r\n        AccessChecker.checkRole(accessController, SystemRoles.DEFAULT_ADMIN_ROLE, msg.sender);\r\n        if (_router == address(0)) revert InvalidAddress(_router);\r\n        router = _router;\r\n    }\r\n\r\n    /**\r\n     * @notice Updates deposit metadata for a specific token\r\n     * @dev Only callable by DEFAULT_ADMIN_ROLE\r\n     * @param tokenId ID of the token to update\r\n     * @param params Parameters for updating deposit metadata\r\n     * @custom:security Validates caller authorization and token existence\r\n     * @custom:emits DepositMetadataUpdated\r\n     */\r\n    function updateDepositMetadata(\r\n        uint256 tokenId,\r\n        DataTypes.MetadataUpdateParams calldata params\r\n    ) external {\r\n        AccessChecker.checkRole(accessController, SystemRoles.DEFAULT_ADMIN_ROLE, msg.sender);\r\n        if (!_exists(tokenId)) revert TokenNotExists(tokenId);\r\n\r\n        DataTypes.DepositMetadata storage metadata = depositDetails[tokenId];\r\n\r\n        if (params.updateIssuer) {\r\n            if (params.issuer == address(0)) revert InvalidAddress(params.issuer);\r\n            metadata.issuer = params.issuer;\r\n        }\r\n\r\n        if (params.updateCollateralAddress) {\r\n            if (params.collateralAddress == address(0))\r\n                revert InvalidAddress(params.collateralAddress);\r\n            metadata.collateralAddress = params.collateralAddress;\r\n        }\r\n\r\n        if (params.updateAsset) {\r\n            if (params.asset == address(0)) revert InvalidAddress(params.asset);\r\n            metadata.asset = params.asset;\r\n        }\r\n\r\n        if (params.updateAmount) {\r\n            metadata.amount = params.amount;\r\n        }\r\n\r\n        if (params.updateZeusdMinted) {\r\n            metadata.zeusdMinted = params.zeusdMinted;\r\n        }\r\n\r\n        if (params.updateDepositTimestamp) {\r\n            metadata.depositTimestamp = params.depositTimestamp;\r\n        }\r\n\r\n        if (params.updateCollateralPrice) {\r\n            metadata.collateralPrice = params.collateralPrice;\r\n        }\r\n\r\n        if (params.updateSubVault) {\r\n            if (params.subVault == address(0)) revert InvalidAddress(params.subVault);\r\n            metadata.subVault = params.subVault;\r\n        }\r\n\r\n        if (params.updateIntegrationType) {\r\n            metadata.integrationType = params.integrationType;\r\n        }\r\n\r\n        if (params.updateTokenType) {\r\n            metadata.tokenType = params.tokenType;\r\n        }\r\n\r\n        emit DepositMetadataUpdated(tokenId, metadata);\r\n    }\r\n\r\n    /**\r\n     * @notice Updates collateral prices for multiple tokens in batch\r\n     * @dev Only callable by DEFAULT_ADMIN_ROLE\r\n     * @param tokenIds Array of token IDs to update\r\n     * @param collateralPrice New collateral price to set for all tokens\r\n     * @custom:security Validates caller authorization and token existence\r\n     * @custom:emits DepositMetadataUpdated for each token\r\n     */\r\n    function updateBatchCollateralPrices(\r\n        uint256[] calldata tokenIds,\r\n        uint256 collateralPrice\r\n    ) external {\r\n        AccessChecker.checkRole(accessController, SystemRoles.DEFAULT_ADMIN_ROLE, msg.sender);\r\n\r\n        for (uint256 i = 0; i < tokenIds.length; i++) {\r\n            uint256 tokenId = tokenIds[i];\r\n            if (!_exists(tokenId)) revert TokenNotExists(tokenId);\r\n\r\n            DataTypes.DepositMetadata storage metadata = depositDetails[tokenId];\r\n            metadata.collateralPrice = collateralPrice;\r\n\r\n            emit DepositMetadataUpdated(tokenId, metadata);\r\n        }\r\n    }\r\n}\r\n"},"contracts/implementations/ZeUSD.sol":{"content":"// ZeUSD.sol\r\n// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.23;\r\n\r\nimport '@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol';\r\nimport '@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol';\r\nimport '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';\r\nimport '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';\r\nimport '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol';\r\nimport '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol';\r\nimport '../interfaces/IZeUSD.sol';\r\n\r\n/// @title ZeUSD Token Implementation\r\n/// @notice Implementation of the ZeUSD stablecoin with upgradeability and access control\r\n/// @dev Implements UUPS upgradeable pattern and OpenZeppelin standard token features\r\n/// @custom:security-contact paras@zoth.io\r\ncontract ZeUSD is\r\n    IZeUSD,\r\n    Initializable,\r\n    AccessControlUpgradeable,\r\n    ERC20Upgradeable,\r\n    ERC20BurnableUpgradeable,\r\n    OwnableUpgradeable,\r\n    UUPSUpgradeable\r\n{\r\n    /// @notice Role for admin access\r\n    /// @dev Has authority to manage blacklist and other admin functions\r\n    bytes32 public constant ADMIN_ROLE = keccak256('ADMIN_ROLE');\r\n\r\n    /// @notice Router contract address with minting privileges\r\n    /// @dev Critical for token minting control\r\n    /// @custom:security Only trusted addresses should be set as router\r\n    address public router;\r\n\r\n    /// @notice Mapping to track blacklisted addresses\r\n    /// @dev true = blacklisted, false = not blacklisted\r\n    /// @custom:security This mapping is critical for compliance and security measures\r\n    mapping(address => bool) private _blacklist;\r\n\r\n    /// @custom:oz-upgrades-unsafe-allow constructor\r\n    constructor() {\r\n        _disableInitializers();\r\n    }\r\n\r\n    /// @notice Initializes the ZeUSD token\r\n    /// @dev Sets up initial state of the contract\r\n    /// @param tokenName Name of the token\r\n    /// @param tokenSymbol Symbol of the token\r\n    /// @param _admin Address of the initial admin\r\n    /// @custom:security Critical initialization function - can only be called once\r\n    function initialize(\r\n        string memory tokenName,\r\n        string memory tokenSymbol,\r\n        address _admin\r\n    ) public initializer {\r\n        if (_admin == address(0)) revert InvalidAddress(_admin);\r\n        __ERC20_init(tokenName, tokenSymbol);\r\n        __Ownable_init(_admin);\r\n        __UUPSUpgradeable_init();\r\n\r\n        _grantRole(DEFAULT_ADMIN_ROLE, _admin);\r\n        _grantRole(ADMIN_ROLE, _admin);\r\n        _setRoleAdmin(ADMIN_ROLE, DEFAULT_ADMIN_ROLE);\r\n    }\r\n\r\n    function decimals() public view virtual override returns (uint8) {\r\n        return 6;\r\n    }\r\n\r\n    /// @notice Updates the router address\r\n    /// @dev Only callable by admin\r\n    /// @param newRouter Address of the new router\r\n    /// @custom:security Router has minting privileges - verify carefully\r\n    function setRouter(address newRouter) external override onlyRole(ADMIN_ROLE) {\r\n        if (newRouter == address(0)) revert InvalidAddress(newRouter);\r\n        router = newRouter;\r\n        emit RouterUpdated(newRouter);\r\n    }\r\n\r\n    /**\r\n     * @notice Burns tokens from a blacklisted address\r\n     * @dev Only callable by admin\r\n     * @param amount Amount of tokens to burn\r\n     * @param blacklistedUser Address of the blacklisted user to burn from\r\n     * @custom:security Critical function affecting user balances\r\n     */\r\n    function burnFromBlacklist(\r\n        uint256 amount,\r\n        address blacklistedUser\r\n    ) external onlyRole(ADMIN_ROLE) {\r\n        _burn(blacklistedUser, amount);\r\n    }\r\n\r\n    /// @notice Mints new tokens\r\n    /// @dev Only callable by router\r\n    /// @param to Recipient of the minted tokens\r\n    /// @param amount Amount of tokens to mint\r\n    /// @custom:security Critical function affecting total supply\r\n    function mint(address to, uint256 amount) public override onlyRouter {\r\n        _mint(to, amount);\r\n    }\r\n\r\n    /// @notice Burns tokens from caller\r\n    /// @dev Only callable by router\r\n    /// @param amount Amount of tokens to burn\r\n    /// @custom:security Critical function affecting total supply\r\n    function burn(\r\n        uint256 amount\r\n    ) public virtual override(IZeUSD, ERC20BurnableUpgradeable) onlyRouter {\r\n        _burn(msg.sender, amount);\r\n    }\r\n\r\n    /// @notice Burns tokens from specified account\r\n    /// @dev Only callable by router, requires approval\r\n    /// @param account Address to burn from\r\n    /// @param amount Amount of tokens to burn\r\n    /// @custom:security Critical function affecting user balances\r\n    function burnFrom(\r\n        address account,\r\n        uint256 amount\r\n    ) public virtual override(IZeUSD, ERC20BurnableUpgradeable) onlyRouter {\r\n        _spendAllowance(account, msg.sender, amount);\r\n        _burn(account, amount);\r\n    }\r\n\r\n    /// @notice Updates token balances\r\n    /// @dev Internal override of ERC20 _update\r\n    /// @param from Address tokens are transferred from\r\n    /// @param to Address tokens are transferred to\r\n    /// @param amount Amount of tokens to transfer\r\n    /// @custom:security Core transfer functionality\r\n    function _update(\r\n        address from,\r\n        address to,\r\n        uint256 amount\r\n    ) internal override notBlacklisted(from, to) {\r\n        super._update(from, to, amount);\r\n    }\r\n\r\n    /// @notice Sets the blacklist status for an account\r\n    /// @dev Only callable by admin role\r\n    /// @param account Address to update blacklist status for\r\n    /// @param status New blacklist status (true = blacklisted)\r\n    /// @custom:security This function can significantly impact user access\r\n    function setBlacklistStatus(address account, bool status) public override onlyRole(ADMIN_ROLE) {\r\n        _blacklist[account] = status;\r\n        emit Blacklisted(account, status);\r\n    }\r\n\r\n    /// @notice Checks if an account is blacklisted\r\n    /// @dev Public view function to check blacklist status\r\n    /// @param account Address to check\r\n    /// @return bool True if account is blacklisted, false otherwise\r\n    /// @custom:security Critical for compliance checks\r\n    function isBlacklisted(address account) public view override returns (bool) {\r\n        return _blacklist[account];\r\n    }\r\n\r\n    /// @notice Prevents blacklisted addresses from transferring tokens\r\n    /// @dev Checks both sender and receiver addresses, allows burning for blacklisted users\r\n    /// @param from Address sending tokens\r\n    /// @param to Address receiving tokens\r\n    /// @custom:security Critical modifier for enforcing compliance\r\n    modifier notBlacklisted(address from, address to) {\r\n        // Allow burning (transfer to address(0)) even for blacklisted users\r\n        if (to != address(0)) {\r\n            if (isBlacklisted(from) || isBlacklisted(to))\r\n                revert Unauthorized('ZeUSD: from or to user is blacklisted');\r\n        }\r\n        _;\r\n    }\r\n\r\n    /// @notice Restricts access to router address\r\n    /// @dev Throws if router not set or caller is not the router\r\n    /// @custom:security Core modifier for minting/burning functions\r\n    modifier onlyRouter() {\r\n        if (router == address(0)) revert RouterNotSet('ZeUSD: Router address is not set');\r\n        if (msg.sender != router) revert NotRouter('ZeUSD: Only router can call this function');\r\n        _;\r\n    }\r\n\r\n    /// @notice Internal function to authorize upgrades\r\n    /// @dev Only callable by owner\r\n    /// @param newImplementation Address of new implementation\r\n    /// @custom:security Critical for contract upgrades\r\n    function _authorizeUpgrade(\r\n        address newImplementation\r\n    ) internal override onlyRole(DEFAULT_ADMIN_ROLE) {}\r\n}\r\n"},"contracts/interfaces/access/IAccessController.sol":{"content":"// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.23;\r\n\r\nimport '../../libraries/SystemRoles.sol';\r\n\r\n/**\r\n * @title Access Controller Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Interface for managing role-based access control across the protocol\r\n * @dev Combines standard role management with custom role configuration\r\n * @custom:security-contact paras@zoth.io\r\n */\r\ninterface IAccessController {\r\n    /**\r\n     * @notice Checks if an account has a specific role\r\n     * @param role Role identifier to check\r\n     * @param account Account to verify\r\n     * @return bool True if account has the role\r\n     * @dev Core function for role verification\r\n     */\r\n    function hasRole(bytes32 role, address account) external view returns (bool);\r\n\r\n    /**\r\n     * @notice Grants a role to an account\r\n     * @param role Role to grant\r\n     * @param account Account to receive the role\r\n     * @dev Only callable by role admin\r\n     */\r\n    function grantRole(bytes32 role, address account) external;\r\n\r\n    /**\r\n     * @notice Revokes a role from an account\r\n     * @param role Role to revoke\r\n     * @param account Account to revoke from\r\n     * @dev Only callable by role admin\r\n     */\r\n    function revokeRole(bytes32 role, address account) external;\r\n\r\n    /**\r\n     * @notice Gets configuration for a specific role\r\n     * @param role Role identifier\r\n     * @return RoleConfig Configuration struct for the role\r\n     * @dev Returns role settings and constraints\r\n     */\r\n    function getRoleConfig(bytes32 role) external view returns (SystemRoles.RoleConfig memory);\r\n\r\n    /**\r\n     * @notice Initializes a new role with configuration\r\n     * @param role Role identifier to initialize\r\n     * @param config Role configuration settings\r\n     * @param adminRole Role that will administer this role\r\n     * @dev Sets up new role with specified parameters\r\n     */\r\n    function initializeRole(\r\n        bytes32 role,\r\n        SystemRoles.RoleConfig memory config,\r\n        bytes32 adminRole\r\n    ) external;\r\n\r\n    /**\r\n     * @notice Gets the admin role for a role\r\n     * @param role Role to query\r\n     * @return bytes32 Admin role identifier\r\n     * @dev Returns role that can manage the queried role\r\n     */\r\n    function getRoleAdmin(bytes32 role) external view returns (bytes32);\r\n\r\n    /**\r\n     * @notice Sets the admin role for a role\r\n     * @param role Role to modify\r\n     * @param adminRole New admin role\r\n     * @dev Changes which role can manage the specified role\r\n     */\r\n    function setRoleAdmin(bytes32 role, bytes32 adminRole) external;\r\n\r\n    /**\r\n     * @notice Gets all members with a specific role\r\n     * @param role Role to query\r\n     * @return address[] Array of addresses with the role\r\n     * @dev Returns complete list of role members\r\n     */\r\n    function getRoleMembers(bytes32 role) external view returns (address[] memory);\r\n\r\n    /**\r\n     * @notice Checks if a role has been initialized\r\n     * @param role Role to check\r\n     * @return bool True if role is initialized\r\n     * @dev Verifies role existence and setup\r\n     */\r\n    function isRoleInitialized(bytes32 role) external view returns (bool);\r\n}\r\n"},"contracts/interfaces/access/IRegistry.sol":{"content":"// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.23;\r\n\r\n/**\r\n * @title Registry Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Interface for the main registry contract that manages protocol contract addresses\r\n * @dev All contract references in the protocol are managed through this registry\r\n */\r\ninterface IRegistry {\r\n    /**\r\n     * @notice Registers a new contract in the registry\r\n     * @param id Contract identifier\r\n     * @param addr Contract address\r\n     * @param version Contract version\r\n     */\r\n    function registerContract(bytes32 id, address addr, uint256 version) external;\r\n\r\n    /**\r\n     * @notice Updates an existing contract address\r\n     * @param id Contract identifier\r\n     * @param newAddr New contract address\r\n     * @param newVersion New version number\r\n     */\r\n    function updateContract(bytes32 id, address newAddr, uint256 newVersion) external;\r\n\r\n    /**\r\n     * @notice Retrieves a contract address\r\n     * @param id Contract identifier\r\n     * @return addr Contract address\r\n     */\r\n    function getContract(bytes32 id) external view returns (address addr);\r\n\r\n    /**\r\n     * @notice Gets contract details\r\n     * @param id Contract identifier\r\n     * @return addr Contract address\r\n     * @return version Contract version\r\n     * @return active Whether contract is active\r\n     */\r\n    function getContractInfo(\r\n        bytes32 id\r\n    ) external view returns (address addr, uint256 version, bool active);\r\n}\r\n"},"contracts/interfaces/ICollateralVault.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.23;\r\n\r\nimport '../events/ICollateralVaultEvents.sol';\r\nimport '../errors/ICollateralVaultErrors.sol';\r\nimport '../libraries/DataTypes.sol';\r\n\r\n/**\r\n * @title Collateral Vault Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Main interface for the CollateralVault contract defining all external functions\r\n * @dev Implements UUPS upgradeable pattern functionality\r\n */\r\ninterface ICollateralVault is ICollateralVaultEvents, ICollateralVaultErrors {\r\n    /**\r\n     * @notice Sets the router contract address\r\n     * @param _router Address of the router contract\r\n     * @dev Can only be set once by admin\r\n     */\r\n    function setRouter(address _router) external;\r\n\r\n    /**\r\n     * @notice Registers or updates a subvault configuration\r\n     * @param integrationType Type of integration\r\n     * @param collateralAddress Address of the collateral asset\r\n     * @param subVaultAddress Address of the subvault\r\n     * @param price Price of the collateral\r\n     * @param ltv Loan-to-Value ratio\r\n     * @param isActive Active status of the subvault\r\n     * @param tokenType Token classification\r\n     * @dev Only callable by ADMIN_ROLE\r\n     */\r\n    function registerSubVault(\r\n        string calldata integrationType,\r\n        address collateralAddress,\r\n        address subVaultAddress,\r\n        uint256 price,\r\n        uint256 ltv,\r\n        bool isActive,\r\n        DataTypes.TokenType tokenType\r\n    ) external;\r\n\r\n    /**\r\n     * @notice Updates specific parameters of a subvault\r\n     * @param collateralAddress Address of the collateral asset\r\n     * @param params Update parameters struct\r\n     * @dev Only callable by ADMIN_ROLE\r\n     */\r\n    function updateSubVaultConfig(\r\n        address collateralAddress,\r\n        DataTypes.SubVaultUpdateParams calldata params\r\n    ) external;\r\n\r\n    /**\r\n     * @notice Calculates the amount of ZeUSD that can be minted for a given collateral amount\r\n     * @param collateralAddress Address of the collateral asset\r\n     * @param asset Address of the specific asset being used\r\n     * @param tokenType Type classification of the token\r\n     * @param amount Amount of collateral being considered\r\n     * @return mintAmount Amount of ZeUSD that can be minted\r\n     */\r\n    function calculateMintAmount(\r\n        address collateralAddress,\r\n        address asset,\r\n        DataTypes.TokenType tokenType,\r\n        uint256 amount\r\n    ) external view returns (uint256 mintAmount);\r\n\r\n    /**\r\n     * @notice Retrieves all registered subvaults and their details\r\n     * @return collaterals Array of collateral addresses\r\n     * @return details Array of corresponding CollateralDetails structs\r\n     */\r\n    function getAllSubVaults()\r\n        external\r\n        view\r\n        returns (address[] memory collaterals, DataTypes.CollateralDetails[] memory details);\r\n\r\n    /**\r\n     * @notice Retrieves all active subvaults and their details\r\n     * @return collaterals Array of active collateral addresses\r\n     * @return details Array of corresponding CollateralDetails structs\r\n     */\r\n    function getActiveSubVaults()\r\n        external\r\n        view\r\n        returns (address[] memory collaterals, DataTypes.CollateralDetails[] memory details);\r\n\r\n    /**\r\n     * @notice Gets the subvault address for a given collateral\r\n     * @param collateralAddress Address of the collateral asset\r\n     * @return subVaultAddress Address of the corresponding subvault\r\n     */\r\n    function getSubVaultAddress(\r\n        address collateralAddress\r\n    ) external view returns (address subVaultAddress);\r\n\r\n    /**\r\n     * @notice Gets full configuration details for a collateral's subvault\r\n     * @param collateralAddress Address of the collateral asset\r\n     * @return details Full configuration details struct\r\n     */\r\n    function getSubVaultDetails(\r\n        address collateralAddress\r\n    ) external view returns (DataTypes.CollateralDetails memory details);\r\n\r\n    /**\r\n     * @notice Gets count of registered and active subvaults\r\n     * @return total Total number of registered subvaults\r\n     * @return active Number of active subvaults\r\n     */\r\n    function getSubVaultCounts() external view returns (uint256 total, uint256 active);\r\n\r\n    /**\r\n     * @notice Removes a subvault registration\r\n     * @param collateralAddress Address of the collateral asset\r\n     * @dev Only callable by ADMIN_ROLE\r\n     */\r\n    function removeSubVault(address collateralAddress) external;\r\n\r\n    /**\r\n     * @notice Pauses all vault operations\r\n     * @dev Only callable by ADMIN_ROLE\r\n     */\r\n    function pause() external;\r\n\r\n    /**\r\n     * @notice Unpauses vault operations\r\n     * @dev Only callable by ADMIN_ROLE\r\n     */\r\n    function unpause() external;\r\n\r\n    /**\r\n     * @notice Validates and prepares deposit parameters\r\n     * @param user Address of the depositor\r\n     * @param collateralAddress Address of the collateral asset\r\n     * @param asset Address of the specific asset being deposited\r\n     * @param amount Amount being deposited\r\n     * @param tokenId ID of the NFT\r\n     * @return metadata Deposit metadata for NFT\r\n     */\r\n    function validateAndPrepareDeposit(\r\n        address user,\r\n        address collateralAddress,\r\n        address asset,\r\n        uint256 amount,\r\n        uint256 tokenId\r\n    ) external view returns (DataTypes.DepositMetadata memory metadata);\r\n\r\n    /**\r\n     * @notice Gets user active positions for a specific subvault\r\n     * @param user Address to query positions for\r\n     * @param subVault Subvault to filter by\r\n     * @return metadata Array of active deposit metadata\r\n     */\r\n    function getUserActivePositionsBySubVault(\r\n        address user,\r\n        address subVault\r\n    ) external view returns (DataTypes.DepositMetadata[] memory metadata);\r\n}\r\n"},"contracts/interfaces/ISubVault.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.23;\r\n\r\nimport '../events/ISubVaultEvents.sol';\r\nimport '../errors/ISubVaultErrors.sol';\r\n\r\n/**\r\n * @title Asset Specific SubVault Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Interface for specialized vaults handling primary and secondary assets\r\n * @dev Implements deposit/withdrawal functionality with primary asset focus\r\n * @custom:security-contact paras@zoth.io\r\n */\r\ninterface ISubVault is ISubVaultEvents, ISubVaultErrors {\r\n    /// @notice SECURITY CONSIDERATIONS:\r\n    /// - Primary asset operations must be validated separately\r\n    /// - Secondary assets require additional validation\r\n    /// - Balance checks before all operations\r\n    /// - Emergency mode restrictions\r\n    /// - Proper approval management for FundVaultV2\r\n    /// - Asset-specific transfer validations\r\n    ///\r\n    /// STATE MANAGEMENT:\r\n    /// - Normal: Full functionality for all assets\r\n    /// - Paused: No operations allowed\r\n    /// - Emergency: Only emergency withdrawals\r\n    /// - Primary Asset: Always supported\r\n    /// - Secondary Assets: Can be added/removed\r\n    ///\r\n    /// INTEGRATION REQUIREMENTS:\r\n    /// - Must validate primary asset operations first\r\n    /// - Must implement separate flows for primary/secondary assets\r\n    /// - Must maintain accurate balances for all assets\r\n    /// - Must emit appropriate events for tracking\r\n    /// - Must handle FundVaultV2 interactions safely\r\n    /// - Must implement proper access control\r\n    ///\r\n    /// ASSET HANDLING:\r\n    /// Primary Asset:\r\n    /// - Cannot be removed\r\n    /// - Direct integration with FundVaultV2\r\n    /// - Specialized event emission\r\n    ///\r\n    /// Secondary Assets:\r\n    /// - Can be added/removed by admin\r\n    /// - May require conversion logic\r\n    /// - Separate event emission\r\n\r\n    /**\r\n     * @notice Handles deposit of any supported asset\r\n     * @param user Address of the depositing user\r\n     * @param asset Address of the asset being deposited\r\n     * @param amount Amount to deposit\r\n     * @return success Whether the deposit was successful\r\n     * @dev Different handling for primary vs secondary assets\r\n     */\r\n    function handleDeposit(address user, address asset, uint256 amount) external returns (bool);\r\n\r\n    /**\r\n     * @notice Handles withdrawal of any supported asset\r\n     * @param user Address of the withdrawing user\r\n     * @param asset Address of the asset to withdraw\r\n     * @param amount Amount to withdraw\r\n     * @return success Whether the withdrawal was successful\r\n     * @dev Different handling for primary vs secondary assets\r\n     */\r\n    function handleWithdraw(address user, address asset, uint256 amount) external returns (bool);\r\n\r\n    /**\r\n     * @notice Gets the current oracle price for the asset if available\r\n     * @param asset Address of the asset to get price for\r\n     * @return price Current oracle price (0 if not available)\r\n     * @return success Whether oracle price was successfully fetched\r\n     */\r\n    function getOraclePrice(address asset) external view returns (uint256 price, bool success);\r\n\r\n    /**\r\n     * @notice Executes emergency withdrawal for any supported asset\r\n     * @param asset Address of the asset to withdraw\r\n     * @param to Recipient address\r\n     * @param amount Amount to withdraw\r\n     * @param reason Reason for emergency withdrawal\r\n     * @return success Whether the withdrawal was successful\r\n     * @dev Available in emergency mode only, special handling for primary asset\r\n     */\r\n    function withdrawEmergency(\r\n        address asset,\r\n        address to,\r\n        uint256 amount,\r\n        string calldata reason\r\n    ) external returns (bool);\r\n\r\n    /**\r\n     * @notice Adds support for a secondary asset\r\n     * @param asset Address of the asset to add\r\n     * @param reason Reason for adding the asset\r\n     * @dev Cannot add primary asset, reverts if asset already supported\r\n     */\r\n    function addAsset(address asset, string calldata reason) external;\r\n\r\n    /**\r\n     * @notice Removes support for a secondary asset\r\n     * @param asset Address of the asset to remove\r\n     * @param reason Reason for removing the asset\r\n     * @dev Cannot remove primary asset, reverts if asset not supported\r\n     */\r\n    function removeAsset(address asset, string calldata reason) external;\r\n\r\n    /**\r\n     * @notice Gets complete list of supported assets\r\n     * @return Array of supported asset addresses\r\n     * @dev Primary asset is always first in the array\r\n     */\r\n    function getSupportedAssets() external view returns (address[] memory);\r\n\r\n    /**\r\n     * @notice Gets true for supported asset\r\n     * @param asset Address of the asset to check\r\n     * @return Whether the asset is supported\r\n     */\r\n    function isAssetSupported(address asset) external view returns (bool);\r\n\r\n    /**\r\n     * @notice Gets current emergency status\r\n     * @return isEmergencyMode Whether emergency mode is active\r\n     * @return isPaused Whether vault is paused\r\n     * @return timeUntilNextAction Time until next emergency action allowed\r\n     * @dev Used to check vault status before operations\r\n     */\r\n    function getEmergencyStatus()\r\n        external\r\n        view\r\n        returns (bool isEmergencyMode, bool isPaused, uint256 timeUntilNextAction);\r\n\r\n    /**\r\n     * @notice Checks if an asset is the primary asset\r\n     * @param asset Asset address to check\r\n     * @return bool True if asset is primary asset\r\n     * @dev Used to determine asset handling flow\r\n     */\r\n    function isPrimaryAsset(address asset) external view returns (bool);\r\n\r\n    /**\r\n     * @notice Gets the primary asset address\r\n     * @return address Address of primary asset\r\n     * @dev Primary asset cannot be changed after deployment\r\n     */\r\n    function getPrimaryAsset() external view returns (address);\r\n\r\n    /**\r\n     * @notice Enables emergency mode\r\n     * @dev Pauses operations and starts emergency delay timer\r\n     */\r\n    function enableEmergencyMode() external;\r\n\r\n    /**\r\n     * @notice Disables emergency mode\r\n     * @dev Can only be called after emergency delay period\r\n     */\r\n    function disableEmergencyMode() external;\r\n\r\n    /**\r\n     * @notice Pauses all vault operations\r\n     * @dev Separate from emergency mode\r\n     */\r\n    function pause() external;\r\n\r\n    /**\r\n     * @notice Unpauses vault operations\r\n     * @dev Cannot unpause if in emergency mode\r\n     */\r\n    function unpause() external;\r\n}\r\n"},"contracts/interfaces/IWithdrawalSystem.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.23;\r\n\r\nimport '../events/IWithdrawalSystemEvents.sol';\r\nimport '../errors/IWithdrawalSystemErrors.sol';\r\nimport '../libraries/WithdrawalSystemTypes.sol';\r\nimport '../libraries/DataTypes.sol';\r\n\r\n/**\r\n * @title Withdrawal System Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Interface for managing withdrawal requests and processing in the ZeUSD protocol\r\n * @dev Handles the complete lifecycle of withdrawal requests from initiation to claim\r\n */\r\ninterface IWithdrawalSystem is IWithdrawalSystemEvents, IWithdrawalSystemErrors {\r\n    /**\r\n     * @notice Initiates a withdrawal request for a deposit NFT\r\n     * @param nftTokenId The ID of the deposit NFT to withdraw against\r\n     * @param user Address of the user requesting withdrawal\r\n     * @param amount Amount of asset to withdraw\r\n     * @param metadata Original deposit metadata associated with the NFT\r\n     * @return requestId Unique identifier for the withdrawal request\r\n     * @custom:security Requires NFT ownership verification\r\n     * @custom:emits WithdrawalRequested\r\n     */\r\n    function initiateWithdrawal(\r\n        uint256 nftTokenId,\r\n        address user,\r\n        uint256 amount,\r\n        DataTypes.DepositMetadata calldata metadata\r\n    ) external returns (uint256 requestId);\r\n\r\n    /**\r\n     * @notice Processes a batch of pending withdrawal requests\r\n     * @dev Groups and processes requests by asset and subvault\r\n     * @custom:security Only callable by authorized operators\r\n     * @custom:emits WithdrawalProcessed for each request\r\n     */\r\n    function processBatch() external;\r\n\r\n    /**\r\n     * @notice Claims a processed withdrawal\r\n     * @param requestId ID of the withdrawal request to claim\r\n     * @custom:security Only callable by request owner when status is READY\r\n     * @custom:emits WithdrawalClaimed\r\n     */\r\n    function claimWithdrawal(uint256 requestId) external;\r\n\r\n    /**\r\n     * @notice Sets configuration for an asset's withdrawal parameters\r\n     * @param asset Address of the asset to configure\r\n     * @param config New configuration parameters for the asset\r\n     * @custom:security Only callable by admin\r\n     */\r\n    function setAssetConfig(\r\n        address asset,\r\n        WithdrawalSystemTypes.AssetConfig calldata config\r\n    ) external;\r\n\r\n    /**\r\n     * @notice Gets groups of requests ready for processing\r\n     * @return subVaults Array of subvault addresses\r\n     * @return assets Array of asset addresses\r\n     * @return totalAmounts Array of total amounts per group\r\n     * @return availableBalances Array of available balances per group\r\n     * @dev Used to determine which requests can be processed\r\n     */\r\n    function getProcessableGroups()\r\n        external\r\n        view\r\n        returns (\r\n            address[] memory subVaults,\r\n            address[] memory assets,\r\n            uint256[] memory totalAmounts,\r\n            uint256[] memory availableBalances\r\n        );\r\n\r\n    /**\r\n     * @notice Checks if a withdrawal request is ready for claiming\r\n     * @param requestId ID of the withdrawal request to check\r\n     * @return isClaimable Whether the request can be claimed\r\n     * @return status Current status of the request\r\n     * @return expiryTime Timestamp when request expires\r\n     */\r\n    function isRequestClaimable(\r\n        uint256 requestId\r\n    )\r\n        external\r\n        view\r\n        returns (bool isClaimable, WithdrawalSystemTypes.RequestStatus status, uint256 expiryTime);\r\n\r\n    /**\r\n     * @notice Processes a specific withdrawal request\r\n     * @param requestId ID of the request to process\r\n     */\r\n    function processRequest(uint256 requestId) external;\r\n\r\n    /**\r\n     * @notice Gets all withdrawal requests for a user\r\n     * @param user Address of the user\r\n     * @return requestIds Array of request IDs belonging to the user\r\n     * @return requests Array of corresponding request details\r\n     */\r\n    function getUserRequests(\r\n        address user\r\n    )\r\n        external\r\n        view\r\n        returns (\r\n            uint256[] memory requestIds,\r\n            WithdrawalSystemTypes.WithdrawalRequest[] memory requests\r\n        );\r\n\r\n    /**\r\n     * @notice Gets all active withdrawal requests for a user\r\n     * @param user Address of the user\r\n     * @return requestIds Array of active request IDs\r\n     * @return requests Array of corresponding request details\r\n     * @dev Returns only IN_QUEUE and READY requests that haven't expired\r\n     */\r\n    function getUserActiveRequests(\r\n        address user\r\n    )\r\n        external\r\n        view\r\n        returns (\r\n            uint256[] memory requestIds,\r\n            WithdrawalSystemTypes.WithdrawalRequest[] memory requests\r\n        );\r\n}\r\n"},"contracts/interfaces/IZeUSD_CDP.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.23;\r\n\r\nimport '../libraries/DataTypes.sol';\r\nimport '@openzeppelin/contracts/token/ERC721/IERC721.sol';\r\nimport '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';\r\n\r\n/**\r\n * @title Deposit NFT Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Interface for managing deposit NFTs in the ZeUSD protocol\r\n * @dev Extends ERC721 functionality with deposit-specific features\r\n */\r\ninterface IZeUSD_CDP is IERC721Enumerable {\r\n    /**\r\n     * @notice Gets all token IDs owned by a specific address\r\n     * @dev Used for retrieving user's deposit positions\r\n     * @param owner Address to query\r\n     * @return Array of token IDs owned by the address\r\n     * @custom:security No access control required, public view\r\n     */\r\n    function getTokensByOwner(address owner) external view returns (uint256[] memory);\r\n\r\n    /**\r\n     * @notice Gets deposit details for a specific token ID\r\n     * @dev Retrieves the original deposit metadata associated with the NFT\r\n     * @param tokenId ID of the token to query\r\n     * @return metadata Deposit metadata for NFT\r\n     * @custom:security Token must exist\r\n     */\r\n    function getDepositDetails(\r\n        uint256 tokenId\r\n    ) external view returns (DataTypes.DepositMetadata memory metadata);\r\n\r\n    /**\r\n     * @notice Mints a new NFT with deposit details\r\n     * @dev Creates a new deposit NFT and stores associated metadata\r\n     * @param to Address to mint the NFT to\r\n     * @param metadata Deposit metadata to associate with the NFT\r\n     * @return tokenId ID of the newly minted NFT\r\n     * @custom:security Only callable by router\r\n     * @custom:emits Transfer\r\n     */\r\n    function mint(\r\n        address to,\r\n        DataTypes.DepositMetadata calldata metadata\r\n    ) external returns (uint256);\r\n\r\n    /**\r\n     * @notice Burns an NFT\r\n     * @dev Permanently removes an NFT and its associated metadata\r\n     * @param tokenId ID of the token to burn\r\n     * @custom:security Only callable by authorized contracts\r\n     * @custom:emits Transfer to zero address\r\n     */\r\n    function burn(uint256 tokenId) external;\r\n\r\n    /**\r\n     * @notice Gets the next token ID without incrementing\r\n     * @return The next token ID that will be used\r\n     */\r\n    function getNextTokenId() external view returns (uint256);\r\n}\r\n"},"contracts/interfaces/IZeUSD.sol":{"content":"// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.23;\r\n\r\nimport '../events/IZeUSDEvents.sol';\r\nimport '../errors/IZeUSDErrors.sol';\r\n\r\n/**\r\n * @title ZeUSD Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Main interface for the ZeUSD token contract\r\n * @dev Extends standard ERC20 functionality with protocol-specific features\r\n * @custom:security-contact paras@zoth.io\r\n */\r\ninterface IZeUSD is IZeUSDEvents, IZeUSDErrors {\r\n    /**\r\n     * @notice Returns the router address\r\n     * @return address Current router contract address\r\n     * @dev Critical for protocol operations\r\n     */\r\n    function router() external view returns (address);\r\n\r\n    /**\r\n     * @notice Sets the blacklist status for an account\r\n     * @param account Address to update blacklist status for\r\n     * @param status New blacklist status (true = blacklisted)\r\n     * @dev Only callable by admin role\r\n     * @custom:emits Blacklisted\r\n     */\r\n    function setBlacklistStatus(address account, bool status) external;\r\n\r\n    /**\r\n     * @notice Checks if an account is blacklisted\r\n     * @param account Address to check\r\n     * @return bool True if account is blacklisted\r\n     * @dev Used for compliance checks\r\n     */\r\n    function isBlacklisted(address account) external view returns (bool);\r\n\r\n    /**\r\n     * @notice Updates the router address\r\n     * @param newRouter Address of the new router\r\n     * @dev Only callable by admin role\r\n     * @custom:emits RouterUpdated\r\n     */\r\n    function setRouter(address newRouter) external;\r\n\r\n    /**\r\n     * @notice Mints new tokens to a specified address\r\n     * @param to Address to mint tokens to\r\n     * @param amount Amount of tokens to mint\r\n     * @dev Only callable by router\r\n     * @custom:emits Transfer\r\n     */\r\n    function mint(address to, uint256 amount) external;\r\n\r\n    /**\r\n     * @notice Burns tokens from the caller's address\r\n     * @param amount Amount of tokens to burn\r\n     * @dev Requires sufficient balance\r\n     * @custom:emits Transfer\r\n     */\r\n    function burn(uint256 amount) external;\r\n\r\n    /**\r\n     * @notice Burns tokens from a specified address\r\n     * @param account Address to burn tokens from\r\n     * @param amount Amount of tokens to burn\r\n     * @dev Requires approval if caller != account\r\n     * @custom:emits Transfer\r\n     */\r\n    function burnFrom(address account, uint256 amount) external;\r\n}\r\n"},"contracts/interfaces/IZeUSDRouter.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.23;\r\n\r\nimport { SendParam, MessagingFee, MessagingReceipt, OFTReceipt } from '@layerzerolabs/oft-evm/contracts/interfaces/IOFT.sol';\r\nimport '../events/IZeUSDRouterEvents.sol';\r\nimport '../errors/IZeUSDRouterErrors.sol';\r\nimport '../libraries/DataTypes.sol';\r\n\r\n/**\r\n * @title ZeUSD Router Main Interface\r\n * @author ZeUSD Protocol Team\r\n * @notice Main interface for interacting with the ZeUSD protocol\r\n * @dev Combines all protocol functionality including minting, burning, and bridging\r\n * @custom:security Implements access control and validation checks\r\n */\r\ninterface IZeUSDRouter is IZeUSDRouterEvents, IZeUSDRouterErrors {\r\n    /**\r\n     * @notice Mints ZeUSD tokens against deposited assets\r\n     * @dev Creates NFT representing the deposit position\r\n     * @param asset Address of asset to deposit\r\n     * @param amount Amount to deposit\r\n     * @return tokenId ID of the minted NFT\r\n     * @custom:security Requires prior token approval\r\n     * @custom:emits DepositProcessed\r\n     */\r\n    function mintWithCollateral(address asset, uint256 amount) external returns (uint256 tokenId);\r\n\r\n    /**\r\n     * @notice Mints ZeUSD tokens with Stable Coins\r\n     * @dev Specialized function for Stable deposits with different collateral\r\n     * @param collateralAddress Address of collateral asset\r\n     * @param asset Address of Stable Coins\r\n     * @param amount Amount of Stable to deposit\r\n     * @return tokenId ID of the minted NFT\r\n     * @custom:security Requires prior token approval\r\n     * @custom:emits DepositProcessed\r\n     */\r\n    function mintWithStable(\r\n        address collateralAddress,\r\n        address asset,\r\n        uint256 amount\r\n    ) external returns (uint256 tokenId);\r\n\r\n    /**\r\n     * @notice Burns ZeUSD tokens to reclaim deposited assets\r\n     * @dev Initiates withdrawal process through WithdrawalSystem\r\n     * @param depositId User's deposit NFT ID\r\n     * @custom:security Requires NFT ownership and sufficient zeUSD balance\r\n     * @custom:emits Burned\r\n     */\r\n    function burn(uint256 depositId) external;\r\n\r\n    /**\r\n     * @notice Mints and bridges ZeUSD via LayerZero\r\n     * @dev Combines minting and cross-chain transfer\r\n     * @param asset Address of asset to deposit\r\n     * @param amount Amount to deposit\r\n     * @param sendParam LayerZero send parameters\r\n     * @param nativeFee LayerZero messaging fee\r\n     * @return tokenId ID of the minted NFT\r\n     * @custom:security Requires sufficient native token for bridge fee\r\n     * @custom:emits DepositProcessed, BridgeInitiated\r\n     */\r\n    function mintWithCollateralAndBridge(\r\n        address asset,\r\n        uint256 amount,\r\n        SendParam memory sendParam,\r\n        MessagingFee memory nativeFee\r\n    ) external payable returns (uint256 tokenId);\r\n\r\n    /**\r\n     * @notice Mints and bridges Stables via LayerZero\r\n     * @dev Combines stable deposit and cross-chain transfer\r\n     * @param collateralAddress Address of collateral asset\r\n     * @param asset Address of Stable to deposit\r\n     * @param amount Amount to deposit\r\n     * @param sendParam LayerZero send parameters\r\n     * @param nativeFee LayerZero messaging fee\r\n     * @return tokenId ID of the minted NFT\r\n     * @custom:security Requires sufficient native token for bridge fee\r\n     * @custom:emits DepositProcessed, BridgeInitiated\r\n     */\r\n    function mintWithStableAndBridge(\r\n        address collateralAddress,\r\n        address asset,\r\n        uint256 amount,\r\n        SendParam memory sendParam,\r\n        MessagingFee memory nativeFee\r\n    ) external payable returns (uint256 tokenId);\r\n\r\n    /**\r\n     * @notice Sets global deposit pause status\r\n     * @param paused New pause status\r\n     * @dev Admin only function\r\n     */\r\n    function setDepositsPaused(bool paused) external;\r\n\r\n    /**\r\n     * @notice Gets LayerZero fee quote\r\n     * @param sendParam Send parameters\r\n     * @return MessagingFee Fee details\r\n     */\r\n    function getQuoteFee(SendParam memory sendParam) external view returns (MessagingFee memory);\r\n\r\n    /**\r\n     * @notice Gets all active positions for a user\r\n     * @param user Address to query positions for\r\n     * @return tokenIds Array of active token IDs\r\n     * @return metadata Array of corresponding deposit metadata\r\n     */\r\n    function getUserActivePositions(\r\n        address user\r\n    )\r\n        external\r\n        view\r\n        returns (uint256[] memory tokenIds, DataTypes.DepositMetadata[] memory metadata);\r\n\r\n    /**\r\n     * @notice Gets details for a specific active position\r\n     * @param tokenId NFT token ID to query\r\n     * @return metadata Deposit metadata for the active position\r\n     */\r\n    function getActivePositionDetails(\r\n        uint256 tokenId\r\n    ) external view returns (DataTypes.DepositMetadata memory metadata);\r\n}\r\n"},"contracts/libraries/DataTypes.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.23;\r\n\r\n/// @title Data Types Library\r\n/// @notice Centralizes type definitions used across the protocol\r\n/// @dev Contains all shared data structures and enums for protocol-wide use\r\n/// @custom:security-contact paras@zoth.io\r\nlibrary DataTypes {\r\n    /// @notice Defines the type classification for tokens in the protocol\r\n    /// @dev Uses uint8 internally for gas optimization since enum is stored as uint8\r\n    /// @custom:usage Used for token classification and validation in deposit/withdrawal flows\r\n    enum TokenType {\r\n        /// @notice Represents non-stablecoin tokens (e.g., ETH, BTC)\r\n        /// @dev Value = 0, optimized for gas when checking non-stable status\r\n        NotStableCoin,\r\n        /// @notice Represents stablecoins (e.g., USDC, DAI)\r\n        /// @dev Value = 1, optimized for gas when checking stable status\r\n        StableCoin\r\n    }\r\n\r\n    /// @notice Configuration for supported assets\r\n    /// @dev Struct is packed to optimize gas usage\r\n    /// @param isSupported Whether the asset is currently supported\r\n    /// @param integrationType The type of integration used for this asset\r\n    /// @param tokenType Classification of the token (stable/non-stable)\r\n    struct AssetConfig {\r\n        bool isSupported;\r\n        string integrationType;\r\n        TokenType tokenType; // Added enum field\r\n    }\r\n\r\n    // /// @notice Stores information about user deposits\r\n    // /// @dev Struct ordering optimized for packing into storage slots\r\n    // /// @param depositId Unique identifier for this deposit\r\n    // /// @param asset Address of the deposited asset\r\n    // /// @param amount Amount of asset deposited\r\n    // /// @param zeusdMinted Amount of zeUSD minted for this deposit\r\n    // /// @param timestamp When the deposit was made\r\n    // /// @param subVault Address of the subvault holding the deposit\r\n    // /// @param integrationType Type of integration used for this deposit\r\n    // /// @param active Whether this deposit is still active\r\n    // /// @param isPrimary Indicates if this is a primary asset deposit\r\n    // /// @param tokenType Classification of the deposited token\r\n    // struct UserDeposit {\r\n    //     uint256 depositId;\r\n    //     address collateralAddress;\r\n    //     address asset;\r\n    //     uint256 amount;\r\n    //     uint256 zeusdMinted;\r\n    //     uint256 timestamp;\r\n    //     address subVault;\r\n    //     string integrationType;\r\n    //     bool active;\r\n    //     bool isPrimary;\r\n    //     TokenType tokenType; // Added enum field\r\n    // }\r\n\r\n    /// @notice Configuration for protocol integrations\r\n    /// @dev Uses mapping for efficient asset support lookups\r\n    /// @param subVault Address of the subvault\r\n    /// @param isActive Whether the integration is currently active\r\n    /// @param registeredAt When the integration was first registered\r\n    /// @param lastUpdated When the integration was last updated\r\n    /// @param supportedAssets Mapping of supported assets for this integration\r\n    struct Integration {\r\n        address subVault;\r\n        bool isActive;\r\n        uint256 registeredAt;\r\n        uint256 lastUpdated;\r\n        mapping(address => bool) supportedAssets;\r\n    }\r\n\r\n    /// @notice Detailed information about collateral assets\r\n    /// @dev Struct ordering optimized for packing into storage slots\r\n    /// @param integrationType Type of integration used\r\n    /// @param collateralAddress Address of the collateral token\r\n    /// @param subVaultAddress Address of the associated subvault\r\n    /// @param price Current price of the collateral\r\n    /// @param ltv Loan-to-Value ratio for the collateral\r\n    /// @param isActive Whether this collateral is currently active\r\n    /// @param registeredAt Timestamp of collateral registration\r\n    /// @param lastUpdatedAt Timestamp of last update\r\n    /// @param tokenType Classification of the collateral token\r\n    struct CollateralDetails {\r\n        string integrationType;\r\n        address collateralAddress;\r\n        address subVaultAddress;\r\n        uint256 price;\r\n        uint256 ltv;\r\n        bool isActive;\r\n        uint256 registeredAt;\r\n        uint256 lastUpdatedAt;\r\n        TokenType tokenType; // Added enum field\r\n    }\r\n\r\n    /// @notice Parameters for updating subvault configuration\r\n    /// @dev Boolean flags used to selectively update specific parameters\r\n    /// @param price New price value\r\n    /// @param ltv New LTV value\r\n    /// @param isActive New active status\r\n    /// @param updatePrice Whether to update the price\r\n    /// @param updateLTV Whether to update the LTV\r\n    /// @param updateActive Whether to update the active status\r\n    struct SubVaultUpdateParams {\r\n        uint256 price;\r\n        uint256 ltv;\r\n        bool isActive;\r\n        bool updatePrice;\r\n        bool updateLTV;\r\n        bool updateActive;\r\n    }\r\n\r\n    /// @notice Parameters for updating protocol addresses\r\n    /// @dev Used in updateAddresses function to specify which addresses to update\r\n    /// @param updateCollateralVault If true, update collateralVault address\r\n    /// @param updateZeusdToken If true, update zeusdToken address\r\n    /// @param updateLzAdapter If true, update lzAdapter address\r\n    /// @param collateralVault New collateral vault contract address (only used if updateCollateralVault is true)\r\n    /// @param zeusdToken New ZeUSD token contract address (only used if updateZeusdToken is true)\r\n    /// @param lzAdapter New LayerZero adapter contract address (only used if updateLzAdapter is true)\r\n    struct AddressUpdateParams {\r\n        bool updateCollateralVault;\r\n        bool updateZeusdToken;\r\n        bool updateLzAdapter;\r\n        address collateralVault;\r\n        address zeusdToken;\r\n        address lzAdapter;\r\n    }\r\n\r\n    /// @notice Parameters for updating user deposit configuration\r\n    /// @dev Boolean flags used to selectively update specific parameters\r\n    /// @param collateralAddress New collateral address value\r\n    /// @param asset New asset address value\r\n    /// @param amount New amount value for the deposit\r\n    /// @param zeusdMinted New minted ZeUSD value\r\n    /// @param active New active status\r\n    /// @param isPrimary New primary status flag\r\n    /// @param updateCollateralAddress Whether to update the collateral address\r\n    /// @param updateAsset Whether to update the asset address\r\n    /// @param updateAmount Whether to update the amount\r\n    /// @param updateZeusdMinted Whether to update the minted ZeUSD amount\r\n    /// @param updateActive Whether to update the active status\r\n    /// @param updateIsPrimary Whether to update the primary status\r\n    struct UserDepositUpdateParams {\r\n        address collateralAddress;\r\n        address asset;\r\n        uint256 amount;\r\n        uint256 zeusdMinted;\r\n        bool active;\r\n        bool isPrimary;\r\n        bool updateCollateralAddress;\r\n        bool updateAsset;\r\n        bool updateAmount;\r\n        bool updateZeusdMinted;\r\n        bool updateActive;\r\n        bool updateIsPrimary;\r\n    }\r\n\r\n    /// @notice Metadata for deposits\r\n    /// @dev Struct to store deposit-related information\r\n    /// @param issuer Original depositor\r\n    /// @param collateralAddress Address of the collateral\r\n    /// @param asset Address of the deposited asset\r\n    /// @param amount Amount of the deposit\r\n    /// @param zeusdMinted Amount of zeUSD minted for this deposit\r\n    /// @param depositTimestamp Timestamp of the deposit\r\n    /// @param collateralPrice Price of the collateral at the time of deposit\r\n    /// @param subVault Address of the subvault\r\n    /// @param integrationType Type of integration used for this deposit\r\n    /// @param tokenType Classification of the deposited token\r\n    /// @param tokenId NFT token ID representing this deposit\r\n    struct DepositMetadata {\r\n        address issuer; // Address of the depositor\r\n        address collateralAddress;\r\n        address asset; // Address of the deposited asset\r\n        uint256 amount; // Amount of asset deposited\r\n        uint256 zeusdMinted; // Amount of ZeUSD minted\r\n        uint256 depositTimestamp;\r\n        uint256 tokenId; // NFT token ID representing this deposit\r\n        uint256 collateralPrice; // Price at deposit time\r\n        address subVault;\r\n        string integrationType;\r\n        TokenType tokenType; // Type of token deposited\r\n    }\r\n\r\n    /// @notice Stores information about user deposits\r\n    /// @dev Struct ordering optimized for packing into storage slots\r\n    /// @param depositId Unique identifier for this deposit\r\n    /// @param asset Address of the deposited asset\r\n    /// @param amount Amount of asset deposited\r\n    /// @param zeusdMinted Amount of zeUSD minted for this deposit\r\n    /// @param timestamp When the deposit was made\r\n    /// @param subVault Address of the subvault holding the deposit\r\n    /// @param integrationType Type of integration used for this deposit\r\n    /// @param active Whether this deposit is still active\r\n    /// @param isPrimary Indicates if this is a primary asset deposit\r\n    /// @param tokenType Classification of the deposited token\r\n    struct UserDeposit {\r\n        uint256 depositId;\r\n        address collateralAddress;\r\n        address asset;\r\n        uint256 amount;\r\n        uint256 zeusdMinted;\r\n        uint256 timestamp;\r\n        address subVault;\r\n        string integrationType;\r\n        bool active;\r\n        bool isPrimary;\r\n        TokenType tokenType; // Added enum field\r\n    }\r\n\r\n    /// @notice Parameters for updating deposit metadata\r\n    /// @dev Boolean flags used to selectively update specific parameters\r\n    /// @param updateIssuer Whether to update the issuer address\r\n    /// @param issuer New issuer address\r\n    /// @param updateCollateralAddress Whether to update the collateral address\r\n    /// @param collateralAddress New collateral address\r\n    struct MetadataUpdateParams {\r\n        bool updateIssuer;\r\n        address issuer;\r\n        bool updateCollateralAddress;\r\n        address collateralAddress;\r\n        bool updateAsset;\r\n        address asset;\r\n        bool updateAmount;\r\n        uint256 amount;\r\n        bool updateZeusdMinted;\r\n        uint256 zeusdMinted;\r\n        bool updateDepositTimestamp;\r\n        uint256 depositTimestamp;\r\n        bool updateCollateralPrice;\r\n        uint256 collateralPrice;\r\n        bool updateSubVault;\r\n        address subVault;\r\n        bool updateIntegrationType;\r\n        string integrationType;\r\n        bool updateTokenType;\r\n        TokenType tokenType;\r\n    }\r\n}\r\n"},"contracts/libraries/SystemRoles.sol":{"content":"// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.23;\r\nimport '../utils/Constants.sol';\r\n\r\n/**\r\n * @title System Roles\r\n * @notice Defines roles and their configurations\r\n * @dev Uses constants from main Constants library\r\n * @author ZeUSD Protocol Team\r\n * @custom:security-contact paras@zoth.io\r\n */\r\nlibrary SystemRoles {\r\n    // Core Administrative Roles\r\n    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\r\n    bytes32 public constant EMERGENCY_ROLE = keccak256('EMERGENCY_ROLE');\r\n    bytes32 public constant UPGRADER_ROLE = keccak256('UPGRADER_ROLE');\r\n    bytes32 public constant WITHDRAWAL_MANAGER_ROLE = keccak256('WITHDRAWAL_MANAGER_ROLE');\r\n\r\n    // Vault Management Roles\r\n    bytes32 public constant VAULT_ADMIN_ROLE = keccak256('VAULT_ADMIN_ROLE');\r\n    bytes32 public constant ASSET_MANAGER_ROLE = keccak256('ASSET_MANAGER_ROLE');\r\n\r\n    // Risk & Control Roles\r\n    bytes32 public constant RISK_CONTROLLER_ROLE = keccak256('RISK_CONTROLLER_ROLE');\r\n    bytes32 public constant LIQUIDATOR_ROLE = keccak256('LIQUIDATOR_ROLE');\r\n    bytes32 public constant PRICE_ADMIN_ROLE = keccak256('PRICE_ADMIN_ROLE');\r\n\r\n    // Rewards & Incentives\r\n    bytes32 public constant REWARD_MANAGER_ROLE = keccak256('REWARD_MANAGER_ROLE');\r\n\r\n    /**\r\n     * @notice Role configuration data structure\r\n     * @param adminRole Role that can grant/revoke this role\r\n     * @param timelock Required delay for critical operations\r\n     * @param requiresConsensus Whether consensus is required\r\n     * @param revocable Whether role can be revoked\r\n     * @param pausable Whether role can be paused\r\n     */\r\n    struct RoleConfig {\r\n        bytes32 adminRole;\r\n        uint256 timelock;\r\n        bool requiresConsensus;\r\n        bool revocable;\r\n        bool pausable;\r\n    }\r\n\r\n    /**\r\n     * @notice Permission configuration data structure\r\n     * @param role Role identifier\r\n     * @param functionSig Function signature\r\n     * @param enabled Whether permission is active\r\n     * @param restrictions Additional restrictions (bitmap)\r\n     */\r\n    struct Permission {\r\n        bytes32 role;\r\n        bytes4 functionSig;\r\n        bool enabled;\r\n        uint256 restrictions;\r\n    }\r\n\r\n    /**\r\n     * @notice Returns DEFAULT_ADMIN_ROLE configuration\r\n     * @dev Highest authority, requires consensus and delay\r\n     */\r\n    function getDefaultAdminConfig() internal pure returns (RoleConfig memory) {\r\n        return\r\n            RoleConfig({\r\n                adminRole: DEFAULT_ADMIN_ROLE,\r\n                timelock: Constants.TWO_DAYS,\r\n                requiresConsensus: true,\r\n                revocable: false,\r\n                pausable: false\r\n            });\r\n    }\r\n\r\n    /**\r\n     * @notice Returns EMERGENCY_ROLE configuration\r\n     * @dev Quick response role, no delay but revocable\r\n     */\r\n    function getEmergencyConfig() internal pure returns (RoleConfig memory) {\r\n        return\r\n            RoleConfig({\r\n                adminRole: DEFAULT_ADMIN_ROLE,\r\n                timelock: 0,\r\n                requiresConsensus: false,\r\n                revocable: true,\r\n                pausable: true\r\n            });\r\n    }\r\n\r\n    /**\r\n     * @notice Returns UPGRADER_ROLE configuration\r\n     * @dev Contract upgrade role, requires consensus\r\n     */\r\n    function getWithdrawalManagerConfig() internal pure returns (RoleConfig memory) {\r\n        return\r\n            RoleConfig({\r\n                adminRole: DEFAULT_ADMIN_ROLE,\r\n                timelock: Constants.ONE_DAY,\r\n                requiresConsensus: true,\r\n                revocable: true,\r\n                pausable: true\r\n            });\r\n    }\r\n\r\n    /**\r\n     * @notice Returns UPGRADER_ROLE configuration\r\n     * @dev Contract upgrade role, requires consensus\r\n     */\r\n    function getUpgraderConfig() internal pure returns (RoleConfig memory) {\r\n        return\r\n            RoleConfig({\r\n                adminRole: DEFAULT_ADMIN_ROLE,\r\n                timelock: Constants.ONE_DAY,\r\n                requiresConsensus: true,\r\n                revocable: true,\r\n                pausable: true\r\n            });\r\n    }\r\n\r\n    /**\r\n     * @notice Returns VAULT_ADMIN_ROLE configuration\r\n     * @dev Vault management role with delay\r\n     */\r\n    function getVaultAdminConfig() internal pure returns (RoleConfig memory) {\r\n        return\r\n            RoleConfig({\r\n                adminRole: DEFAULT_ADMIN_ROLE,\r\n                timelock: Constants.ONE_DAY,\r\n                requiresConsensus: true,\r\n                revocable: true,\r\n                pausable: true\r\n            });\r\n    }\r\n\r\n    /**\r\n     * @notice Returns ASSET_MANAGER_ROLE configuration\r\n     * @dev Asset management under vault admin\r\n     */\r\n    function getAssetManagerConfig() internal pure returns (RoleConfig memory) {\r\n        return\r\n            RoleConfig({\r\n                adminRole: VAULT_ADMIN_ROLE,\r\n                timelock: Constants.TWELVE_HOURS,\r\n                requiresConsensus: true,\r\n                revocable: true,\r\n                pausable: true\r\n            });\r\n    }\r\n\r\n    /**\r\n     * @notice Returns RISK_CONTROLLER_ROLE configuration\r\n     * @dev Risk parameter management role\r\n     */\r\n    function getRiskControllerConfig() internal pure returns (RoleConfig memory) {\r\n        return\r\n            RoleConfig({\r\n                adminRole: DEFAULT_ADMIN_ROLE,\r\n                timelock: Constants.TWELVE_HOURS,\r\n                requiresConsensus: true,\r\n                revocable: true,\r\n                pausable: true\r\n            });\r\n    }\r\n\r\n    /**\r\n     * @notice Returns LIQUIDATOR_ROLE configuration\r\n     * @dev Liquidation execution role, no delay\r\n     */\r\n    function getLiquidatorConfig() internal pure returns (RoleConfig memory) {\r\n        return\r\n            RoleConfig({\r\n                adminRole: RISK_CONTROLLER_ROLE,\r\n                timelock: 0,\r\n                requiresConsensus: false,\r\n                revocable: true,\r\n                pausable: true\r\n            });\r\n    }\r\n\r\n    /**\r\n     * @notice Returns PRICE_ADMIN_ROLE configuration\r\n     * @dev Oracle management role\r\n     */\r\n    function getPriceAdminConfig() internal pure returns (RoleConfig memory) {\r\n        return\r\n            RoleConfig({\r\n                adminRole: DEFAULT_ADMIN_ROLE,\r\n                timelock: Constants.TWELVE_HOURS,\r\n                requiresConsensus: true,\r\n                revocable: true,\r\n                pausable: true\r\n            });\r\n    }\r\n\r\n    /**\r\n     * @notice Returns REWARD_MANAGER_ROLE configuration\r\n     * @dev Rewards management role\r\n     */\r\n    function getRewardManagerConfig() internal pure returns (RoleConfig memory) {\r\n        return\r\n            RoleConfig({\r\n                adminRole: DEFAULT_ADMIN_ROLE,\r\n                timelock: Constants.ONE_DAY,\r\n                requiresConsensus: true,\r\n                revocable: true,\r\n                pausable: true\r\n            });\r\n    }\r\n}\r\n"},"contracts/libraries/WithdrawalSystemTypes.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.23;\r\n\r\n/**\r\n * @title Withdrawal System Types Library\r\n * @author ZeUSD Protocol Team\r\n * @notice Contains all type definitions used in the withdrawal system\r\n * @dev Central location for withdrawal-related data structures\r\n */\r\nlibrary WithdrawalSystemTypes {\r\n    /**\r\n     * @notice Status of a withdrawal request\r\n     * @dev Represents the lifecycle states of a withdrawal\r\n     * State transitions:\r\n     * PENDING -> IN_QUEUE -> PROCESSING -> READY -> COMPLETED\r\n     *                    -> EXPIRED\r\n     *                    -> FAILED\r\n     */\r\n    enum RequestStatus {\r\n        PENDING, // Initial request received\r\n        IN_QUEUE, // Validated and queued for processing\r\n        PROCESSING, // Under active processing by operators\r\n        READY, // Processed and ready for claim\r\n        COMPLETED, // Successfully claimed by user\r\n        FAILED, // Processing failed, needs review\r\n        EXPIRED // Past claim window, needs resubmission\r\n    }\r\n\r\n    /**\r\n     * @notice Configuration parameters for asset withdrawals\r\n     * @dev Controls withdrawal behavior per asset\r\n     * @param settlementTime Time required for withdrawal settlement (in seconds)\r\n     * @param maxBatchSize Maximum requests per batch for gas optimization\r\n     * @param isInstant Whether instant withdrawals are allowed\r\n     * @param dailyLimit Maximum daily withdrawal amount (in asset's smallest unit)\r\n     */\r\n    struct AssetConfig {\r\n        uint256 settlementTime;\r\n        uint256 maxBatchSize;\r\n        bool isInstant;\r\n        uint256 dailyLimit;\r\n    }\r\n\r\n    /**\r\n     * @notice Information about a withdrawal request\r\n     * @dev Stores all relevant data for a withdrawal\r\n     * @param requestId Unique identifier for the request\r\n     * @param user Address of the requesting user\r\n     * @param asset Contract address of the asset to withdraw\r\n     * @param amount Amount requested (in asset's smallest unit)\r\n     * @param timestamp Request creation time\r\n     * @param status Current status of the request\r\n     * @param nftTokenId Associated deposit NFT ID\r\n     * @param subVault Source subvault address\r\n     * @param expiryTime Time when request expires\r\n     * @param isStable Whether the asset is a stablecoin\r\n     */\r\n    struct WithdrawalRequest {\r\n        uint256 requestId;\r\n        address user;\r\n        address asset;\r\n        uint256 amount;\r\n        uint256 timestamp;\r\n        RequestStatus status;\r\n        uint256 nftTokenId;\r\n        address subVault;\r\n        uint256 expiryTime;\r\n        bool isStable;\r\n    }\r\n\r\n    /**\r\n     * @notice Information about a withdrawal request\r\n     * @dev Stores all relevant data for a withdrawal\r\n     * @param requestId Unique identifier for the request\r\n     * @param user Address of the requesting user\r\n     * @param asset Contract address of the asset to withdraw\r\n     * @param amount Amount requested (in asset's smallest unit)\r\n     * @param timestamp Request creation time\r\n     * @param status Current status of the request\r\n     * @param nftTokenId Associated deposit NFT ID\r\n     * @param subVault Source subvault address\r\n     * @param expiryTime Time when request expires\r\n     * @param isStable Whether the asset is a stablecoin\r\n     */\r\n    struct WithdrawalRequestUpdate {\r\n        uint256 requestId;\r\n        bool updateAsset;\r\n        address asset;\r\n        bool updateAmount;\r\n        uint256 amount;\r\n    }\r\n\r\n    /**\r\n     * @notice Information about a batch of withdrawals\r\n     * @dev Used for batch processing operations\r\n     * @param subVault Address of the subvault to process from\r\n     * @param asset Address of the asset being processed\r\n     * @param totalAmount Total amount in the batch\r\n     * @param requestIds Array of request IDs in the batch\r\n     */\r\n    struct BatchProcessInfo {\r\n        address subVault;\r\n        address asset;\r\n        uint256 totalAmount;\r\n        uint256[] requestIds;\r\n    }\r\n}\r\n"},"contracts/utils/AccessChecker.sol":{"content":"// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.23;\r\n\r\nimport '../interfaces/access/IAccessController.sol';\r\nimport '../errors/ISystemErrors.sol';\r\n\r\n/**\r\n * @title Access Checker Library\r\n * @notice Utility functions for access control checks\r\n * @dev Provides reusable access control functionality\r\n */\r\nlibrary AccessChecker {\r\n    /**\r\n     * @notice Verifies caller has required role\r\n     * @param accessController Access controller contract\r\n     * @param role Required role\r\n     * @param account Account to check\r\n     */\r\n    function checkRole(\r\n        IAccessController accessController,\r\n        bytes32 role,\r\n        address account\r\n    ) internal view {\r\n        if (!accessController.hasRole(role, account)) {\r\n            revert ISystemErrors.Unauthorized(string(abi.encodePacked('Missing role: ', role)));\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @notice Verifies caller has one of required roles\r\n     * @param accessController Access controller contract\r\n     * @param roles Array of acceptable roles\r\n     * @param account Account to check\r\n     */\r\n    function checkRoles(\r\n        IAccessController accessController,\r\n        bytes32[] memory roles,\r\n        address account\r\n    ) internal view {\r\n        for (uint i = 0; i < roles.length; i++) {\r\n            if (accessController.hasRole(roles[i], account)) {\r\n                return;\r\n            }\r\n        }\r\n        revert ISystemErrors.Unauthorized('Missing required roles');\r\n    }\r\n\r\n    /**\r\n     * @notice Validates contract address\r\n     * @param addr Address to validate\r\n     */\r\n    function validateAddress(address addr) internal pure {\r\n        if (addr == address(0)) {\r\n            revert ISystemErrors.InvalidAddress(addr);\r\n        }\r\n    }\r\n}\r\n"},"contracts/utils/Constants.sol":{"content":"// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.23;\r\n\r\n/**\r\n * @title Protocol Constants\r\n * @author ZeUSD Protocol Team\r\n * @notice Central source for all protocol constants\r\n * @dev Single source of truth for contract identifiers and constants\r\n * @custom:security Constants should never be modified after deployment\r\n */\r\nlibrary Constants {\r\n    /**\r\n     * @notice Protocol Contract Identifiers\r\n     * @dev Unique identifiers for protocol contracts in registry\r\n     */\r\n    bytes32 public constant CONTRACT_ACCESS_CONTROLLER = keccak256('CONTRACT_ACCESS_CONTROLLER');\r\n    bytes32 public constant CONTRACT_REGISTRY = keccak256('CONTRACT_REGISTRY');\r\n    bytes32 public constant CONTRACT_ZEUSD = keccak256('CONTRACT_ZEUSD');\r\n    bytes32 public constant CONTRACT_ROUTER = keccak256('CONTRACT_ROUTER');\r\n    bytes32 public constant CONTRACT_TREASURY = keccak256('CONTRACT_TREASURY');\r\n    bytes32 public constant CONTRACT_ORACLE = keccak256('CONTRACT_ORACLE');\r\n    bytes32 public constant CONTRACT_DEPOSIT_NFT = keccak256('CONTRACT_DEPOSIT_NFT');\r\n    bytes32 public constant CONTRACT_WITHDRAWAL_SYSTEM = keccak256('CONTRACT_WITHDRAWAL_SYSTEM');\r\n\r\n    /**\r\n     * @notice Time Constants\r\n     * @dev Standard time periods used throughout the protocol\r\n     */\r\n    uint256 public constant ONE_HOUR = 1 hours;\r\n    uint256 public constant ONE_DAY = 1 days;\r\n    uint256 public constant ONE_WEEK = 7 days;\r\n    uint256 public constant TWO_DAYS = 2 days;\r\n    uint256 public constant TWELVE_HOURS = 12 hours;\r\n\r\n    /**\r\n     * @notice Protocol Parameters\r\n     * @dev Governance and operational limits\r\n     */\r\n    /// @notice Maximum number of roles a single account can hold\r\n    uint256 public constant MAX_ROLES_PER_ACCOUNT = 10;\r\n\r\n    /// @notice Maximum number of members that can be assigned to a role\r\n    uint256 public constant MAX_MEMBERS_PER_ROLE = 50;\r\n\r\n    /// @notice Percentage threshold required for consensus decisions (66%)\r\n    uint256 public constant CONSENSUS_THRESHOLD = 66;\r\n\r\n    /// @notice Delay period for emergency actions\r\n    uint256 public constant EMERGENCY_DELAY = 1 hours;\r\n}\r\n"},"contracts/ZeUSD_Router.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.23;\r\n\r\nimport '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol';\r\nimport '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol';\r\nimport '@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol';\r\nimport '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';\r\nimport '@openzeppelin/contracts/utils/math/Math.sol';\r\nimport { SendParam, MessagingFee, MessagingReceipt, OFTReceipt } from '@layerzerolabs/oft-evm/contracts/interfaces/IOFT.sol';\r\nimport './implementations/LZAdapter.sol';\r\nimport './interfaces/IZeUSDRouter.sol';\r\nimport './interfaces/ISubVault.sol';\r\nimport './interfaces/ICollateralVault.sol';\r\nimport './interfaces/access/IAccessController.sol';\r\nimport './implementations/ZeUSD.sol';\r\nimport './libraries/DataTypes.sol';\r\nimport './libraries/SystemRoles.sol';\r\nimport './utils/AccessChecker.sol';\r\nimport './utils/Constants.sol';\r\nimport './implementations/ZeUSD_CDP.sol';\r\nimport './interfaces/IWithdrawalSystem.sol';\r\nimport './interfaces/access/IRegistry.sol';\r\nimport './interfaces/IZeUSD_CDP.sol';\r\n\r\n/**\r\n * @title ZeUSD Router Implementation\r\n * @author ZeUSD Protocol Team\r\n * @notice Main entry point for ZeUSD protocol operations\r\n * @dev Implements UUPS upgradeable pattern with role-based access control\r\n * @custom:security-contact paras@zoth.io\r\n *\r\n * Security Considerations:\r\n * - Reentrancy protection on all state-modifying functions\r\n * - Role-based access control for admin functions\r\n * - Asset validation sequences\r\n * - LayerZero bridge security assumptions\r\n * - Proper upgrade pattern implementation\r\n *\r\n * Role Capabilities:\r\n * DEFAULT_ADMIN_ROLE:\r\n * - Can grant/revoke all roles\r\n * - Can upgrade contract\r\n * - Can perform all admin functions\r\n *\r\n * ADMIN_ROLE:\r\n * - Can configure assets\r\n * - Can manage whitelist/blacklist\r\n * - Can pause/unpause operations\r\n *\r\n * State Management:\r\n * - Active: All operations allowed\r\n * - Paused: No mints/burns\r\n * - Emergency: Only admin functions\r\n */\r\ncontract ZeUSD_Router is IZeUSDRouter, Initializable, UUPSUpgradeable, ReentrancyGuardUpgradeable {\r\n    using Math for uint256;\r\n    using SafeERC20 for IERC20;\r\n\r\n    /// @dev SECURITY CONSIDERATIONS:\r\n    /// - Reentrancy protection in mint/burn operations\r\n    /// - Asset validation sequences\r\n    /// - Proper order of operations (burn before transfer, etc.)\r\n    /// - LayerZero bridge security assumptions\r\n    /// - Role-based access control for admin functions\r\n    /// - Proper upgrade pattern implementation\r\n\r\n    /// @dev ROLE CAPABILITIES:\r\n    /// DEFAULT_DEFAULT_ADMIN_ROLE:\r\n    /// - Can grant/revoke all roles\r\n    /// - Can upgrade contract\r\n    /// - Can perform all admin functions\r\n    /// - Super admin capabilities\r\n    ///\r\n    /// DEFAULT_ADMIN_ROLE:\r\n    /// - Can configure assets\r\n    /// - Can manage whitelist/blacklist\r\n    /// - Can pause/unpause operations\r\n    /// - Cannot grant/revoke roles\r\n\r\n    /// @dev ERROR HANDLING STRATEGY:\r\n    /// - All operations revert on failure\r\n    /// - Detailed error messages for debugging\r\n    /// - Proper error propagation from sub-contracts\r\n    /// - Emergency pause functionality available\r\n\r\n    /// @dev MATHEMATICAL CONSIDERATIONS:\r\n    /// - 1:1 ratio maintained for all mints/burns\r\n    /// - No precision loss in calculations\r\n    /// - Proper balance checks before operations\r\n    /// - Dust amount considerations\r\n\r\n    /// @dev STATE TRANSITIONS:\r\n    /// Valid states:\r\n    /// - Active: All operations allowed\r\n    /// - Paused: No mints/burns\r\n    /// - Emergency: Only admin functions\r\n    /// State changes require proper authorization\r\n\r\n    /// @dev GAS OPTIMIZATION NOTES:\r\n    /// - Storage access optimized\r\n    /// - Batch operations where possible\r\n    /// - Memory vs Storage usage optimized\r\n    /// - Loop optimizations in deposit checks\r\n\r\n    /// @dev ACCESS CONTROL MATRIX:\r\n    /// Role              | Mint | Burn | Admin | Emergency\r\n    /// DEFAULT_ADMIN     |  No  |  No  |  Yes  |   Yes\r\n    /// ADMIN             |  No  |  No  |  Yes  |   Yes\r\n    /// Whitelisted       |  Yes |  Yes |  No   |   No\r\n    /// Blacklisted       |  No  |  No  |  No   |   No\r\n\r\n    /// @dev EVENT USAGE GUIDE:\r\n    /// Critical Events (Monitor These):\r\n    /// - Mint/Burn operations\r\n    /// - Role changes\r\n    /// - Emergency actions\r\n    /// - Integration updates\r\n    /// Informational Events:\r\n    /// - Whitelist changes\r\n    /// - Parameter updates\r\n\r\n    /// @dev Role definitions\r\n    bytes32 public constant DEFAULT_ADMIN_ROLE = keccak256('DEFAULT_ADMIN_ROLE');\r\n\r\n    /// @notice Whitelist mapping\r\n    /// @dev Tracks addresses that are allowed to use the protocol\r\n    mapping(address => bool) private _whitelisted;\r\n\r\n    /// @notice Protocol contracts\r\n    ICollateralVault public collateralVault;\r\n    ZeUSD public zeusdToken;\r\n    LZAdapter public lzAdapter;\r\n    IZeUSD_CDP public depositNFT;\r\n\r\n    /// @notice Global pause status\r\n    bool public depositsPaused;\r\n\r\n    bool private isInitialApprovalSet;\r\n\r\n    /// @notice Access controller contract reference\r\n    IAccessController public accessController;\r\n\r\n    IWithdrawalSystem public withdrawalSystem;\r\n\r\n    /// @dev Add this mapping with other state variables\r\n    mapping(address => DataTypes.DepositMetadata[]) private userPositions;\r\n\r\n    /**\r\n     * @notice Ensures caller is not blacklisted\r\n     * @dev Additional security layer to block malicious addresses\r\n     * @custom:security Access control check\r\n     */\r\n    modifier notBlacklisted() {\r\n        if (zeusdToken.isBlacklisted(msg.sender)) revert Blacklisted(msg.sender);\r\n        _;\r\n    }\r\n\r\n    /**\r\n     * @notice Ensures operations are not paused\r\n     * @dev Global pause check for emergency situations\r\n     * @custom:security System state check\r\n     */\r\n    modifier whenNotPaused() {\r\n        if (depositsPaused) revert DepositsArePaused();\r\n        _;\r\n    }\r\n\r\n    /**\r\n     * @notice Ensures amount is not zero\r\n     * @dev Prevents zero-value transactions\r\n     * @param amount Amount to validate\r\n     * @custom:security Input validation\r\n     */\r\n    modifier validAmount(uint256 amount) {\r\n        if (amount == 0) revert ZeroAmount();\r\n        _;\r\n    }\r\n\r\n    /**\r\n     * @dev Prevents initialization of implementation contract\r\n     */\r\n    constructor() {\r\n        _disableInitializers();\r\n    }\r\n\r\n    /**\r\n     * @notice Initializes the router contract\r\n     * @dev Sets up initial contract references\r\n     * @param _collateralVault CollateralVault address\r\n     * @param _zeusdToken ZeUSD token address\r\n     * @param _lzAdapter LayerZero adapter address\r\n     * @param _admin Admin address\r\n     * @custom:security Only callable once\r\n     */\r\n    function initialize(\r\n        address _collateralVault,\r\n        address _zeusdToken,\r\n        address _lzAdapter,\r\n        address _admin\r\n    ) external initializer {\r\n        __UUPSUpgradeable_init();\r\n\r\n        if (_collateralVault == address(0)) revert InvalidAddress(_collateralVault);\r\n        if (_zeusdToken == address(0)) revert InvalidAddress(_zeusdToken);\r\n        if (_lzAdapter == address(0)) revert InvalidAddress(_lzAdapter);\r\n        if (_admin == address(0)) revert InvalidAddress(_admin);\r\n\r\n        collateralVault = ICollateralVault(_collateralVault);\r\n        zeusdToken = ZeUSD(_zeusdToken);\r\n        lzAdapter = LZAdapter(_lzAdapter);\r\n    }\r\n\r\n    /**\r\n     * @notice Initializes V2 of the router contract\r\n     * @dev Sets up registry connections and additional contracts\r\n     * @param registryContract Registry contract address\r\n     * @custom:security Only callable during V2 upgrade\r\n     */\r\n    function initializeV2(address registryContract) public reinitializer(2) {\r\n        if (registryContract == address(0)) revert InvalidAddress(registryContract);\r\n\r\n        IRegistry registry = IRegistry(registryContract);\r\n\r\n        accessController = IAccessController(\r\n            registry.getContract(Constants.CONTRACT_ACCESS_CONTROLLER)\r\n        );\r\n\r\n        withdrawalSystem = IWithdrawalSystem(\r\n            registry.getContract(Constants.CONTRACT_WITHDRAWAL_SYSTEM)\r\n        );\r\n\r\n        depositNFT = IZeUSD_CDP(registry.getContract(Constants.CONTRACT_DEPOSIT_NFT));\r\n\r\n        if (address(accessController) == address(0))\r\n            revert InvalidAddress(address(accessController));\r\n        if (address(withdrawalSystem) == address(0))\r\n            revert InvalidAddress(address(withdrawalSystem));\r\n        if (address(depositNFT) == address(0)) revert InvalidAddress(address(depositNFT));\r\n\r\n        emit V2Initialized(\r\n            address(accessController),\r\n            address(withdrawalSystem),\r\n            address(depositNFT)\r\n        );\r\n    }\r\n\r\n    /**\r\n     * @notice Internal mint function for all mint operations\r\n     * @dev Handles asset transfers and NFT minting\r\n     * @param collateralAddress Primary collateral asset address\r\n     * @param asset Asset being deposited\r\n     * @param amount Amount to deposit\r\n     * @param nftRecipient Address to receive minted NFT\r\n     * @param zeusdRecipient Address to receive minted ZeUSD\r\n     * @return tokenId Minted NFT token ID\r\n     * @return msgReceipt LayerZero messaging receipt\r\n     * @return oftReceipt LayerZero OFT receipt\r\n     * @custom:security Validates assets and amounts\r\n     */\r\n    function _mint(\r\n        address collateralAddress,\r\n        address asset,\r\n        uint256 amount,\r\n        address nftRecipient,\r\n        address zeusdRecipient\r\n    )\r\n        internal\r\n        returns (uint256 tokenId, MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt)\r\n    {\r\n        address subvault = collateralVault.getSubVaultAddress(collateralAddress);\r\n        if (subvault == address(0)) revert AssetNotSupported(collateralAddress);\r\n        if (!ISubVault(subvault).isAssetSupported(asset)) revert AssetNotSupported(asset);\r\n\r\n        IERC20(asset).safeTransferFrom(msg.sender, subvault, amount);\r\n\r\n        bool result = ISubVault(subvault).handleDeposit(msg.sender, asset, amount);\r\n        if (!result) revert DepositFailed('SubVault operation failed');\r\n\r\n        // Get next token ID and metadata\r\n        tokenId = depositNFT.getNextTokenId();\r\n        DataTypes.DepositMetadata memory metadata = collateralVault.validateAndPrepareDeposit(\r\n            nftRecipient, // Use NFT recipient here\r\n            collateralAddress,\r\n            asset,\r\n            amount,\r\n            tokenId\r\n        );\r\n\r\n        // Mint NFT and tokens to different recipients\r\n        tokenId = depositNFT.mint(nftRecipient, metadata);\r\n        zeusdToken.mint(zeusdRecipient, metadata.zeusdMinted);\r\n\r\n        // Record position using metadata directly\r\n        userPositions[nftRecipient].push(metadata);\r\n\r\n        emit DepositProcessed(nftRecipient, tokenId, asset, amount, metadata.zeusdMinted);\r\n    }\r\n\r\n    /**\r\n     * @notice Mints ZeUSD using collateral asset\r\n     * @dev Direct deposit of primary collateral\r\n     * @param collateralAddress Collateral asset address\r\n     * @param amount Amount to deposit\r\n     * @return tokenId Minted NFT token ID\r\n     * @custom:security Multiple access controls and validations\r\n     */\r\n    function mintWithCollateral(\r\n        address collateralAddress,\r\n        uint256 amount\r\n    )\r\n        external\r\n        override\r\n        nonReentrant\r\n        whenNotPaused\r\n        notBlacklisted\r\n        validAmount(amount)\r\n        returns (uint256 tokenId)\r\n    {\r\n        (tokenId, , ) = _mint(collateralAddress, collateralAddress, amount, msg.sender, msg.sender);\r\n    }\r\n\r\n    /**\r\n     * @notice Mints ZeUSD using stable asset\r\n     * @dev Deposit of supported stable asset\r\n     * @param collateralAddress Primary collateral asset address\r\n     * @param asset Stable asset address\r\n     * @param amount Amount to deposit\r\n     * @return tokenId Minted NFT token ID\r\n     * @custom:security Multiple access controls and validations\r\n     */\r\n\r\n    function mintWithStable(\r\n        address collateralAddress,\r\n        address asset,\r\n        uint256 amount\r\n    )\r\n        external\r\n        override\r\n        nonReentrant\r\n        whenNotPaused\r\n        notBlacklisted\r\n        validAmount(amount)\r\n        returns (uint256 tokenId)\r\n    {\r\n        (tokenId, , ) = _mint(collateralAddress, asset, amount, msg.sender, msg.sender);\r\n    }\r\n\r\n    /**\r\n     * @notice Mints and bridges ZeUSD via LayerZero\r\n     * @dev Routes to appropriate subvault based on collateral\r\n     * @param collateralAddress Primary collateral asset address\r\n     * @param amount Amount to deposit\r\n     * @param sendParam LayerZero send parameters\r\n     * @param nativeFee LayerZero message fee\r\n     * @return tokenId Minted NFT token ID\r\n     * @custom:security Validates bridge setup and fees\r\n     */\r\n    function mintWithCollateralAndBridge(\r\n        address collateralAddress,\r\n        uint256 amount,\r\n        SendParam memory sendParam,\r\n        MessagingFee memory nativeFee\r\n    )\r\n        external\r\n        payable\r\n        override\r\n        nonReentrant\r\n        whenNotPaused\r\n        notBlacklisted\r\n        validAmount(amount)\r\n        returns (uint256 tokenId)\r\n    {\r\n        if (!isInitialApprovalSet) revert InitialApproval('Initial approval not set');\r\n\r\n        // Mint NFT to user, ZeUSD to router\r\n        (tokenId, , ) = _mint(\r\n            collateralAddress,\r\n            collateralAddress,\r\n            amount,\r\n            msg.sender,\r\n            address(this)\r\n        );\r\n\r\n        // Bridge ZeUSD\r\n        try lzAdapter.send{ value: msg.value }(sendParam, nativeFee, msg.sender) returns (\r\n            MessagingReceipt memory _msgReceipt,\r\n            OFTReceipt memory _oftReceipt\r\n        ) {\r\n            emit BridgeInitiated(msg.sender, collateralAddress, amount);\r\n            return tokenId;\r\n        } catch Error(string memory reason) {\r\n            revert BridgeFailed(reason);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @notice Mints and bridges stables via LayerZero\r\n     * @dev Routes to appropriate subvault based on asset\r\n     * @param collateralAddress Primary collateral asset address\r\n     * @param asset Stable asset address\r\n     * @param amount Amount to deposit\r\n     * @param sendParam LayerZero send parameters\r\n     * @param nativeFee LayerZero message fee\r\n     * @return tokenId Minted NFT token ID\r\n     * @custom:security Validates bridge setup and fees\r\n     */\r\n    function mintWithStableAndBridge(\r\n        address collateralAddress,\r\n        address asset,\r\n        uint256 amount,\r\n        SendParam memory sendParam,\r\n        MessagingFee memory nativeFee\r\n    )\r\n        external\r\n        payable\r\n        override\r\n        nonReentrant\r\n        whenNotPaused\r\n        notBlacklisted\r\n        validAmount(amount)\r\n        returns (uint256 tokenId)\r\n    {\r\n        if (!isInitialApprovalSet) revert InitialApproval('Initial approval not set');\r\n\r\n        // Mint NFT to user, ZeUSD to router\r\n        (tokenId, , ) = _mint(collateralAddress, asset, amount, msg.sender, address(this));\r\n\r\n        // Bridge ZeUSD\r\n        try lzAdapter.send{ value: msg.value }(sendParam, nativeFee, msg.sender) returns (\r\n            MessagingReceipt memory _msgReceipt,\r\n            OFTReceipt memory _oftReceipt\r\n        ) {\r\n            emit BridgeInitiated(msg.sender, asset, amount);\r\n            return tokenId;\r\n        } catch Error(string memory reason) {\r\n            revert BridgeFailed(reason);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @notice Burns ZeUSD tokens to reclaim assets\r\n     * @dev Initiates withdrawal through withdrawal system\r\n     * @param nftTokenId User's deposit NFT ID\r\n     * @custom:security Validates NFT ownership and burn amount\r\n     */\r\n    function burn(uint256 nftTokenId) external nonReentrant whenNotPaused {\r\n        // Verify NFT ownership\r\n        require(depositNFT.ownerOf(nftTokenId) == msg.sender, 'Not NFT owner');\r\n\r\n        // Get deposit details from NFT\r\n        DataTypes.DepositMetadata memory metadata = depositNFT.getDepositDetails(nftTokenId);\r\n\r\n        // Burn zeUSD equivalent to the deposited amount\r\n        zeusdToken.burnFrom(msg.sender, metadata.zeusdMinted);\r\n\r\n        // Burn NFT\r\n        depositNFT.burn(nftTokenId);\r\n\r\n        // Initiate withdrawal through withdrawal system\r\n        withdrawalSystem.initiateWithdrawal(nftTokenId, msg.sender, metadata.amount, metadata);\r\n    }\r\n\r\n    /**\r\n     * @notice Sets global deposit pause status\r\n     * @dev Emergency pause functionality\r\n     * @param paused New pause status\r\n     * @custom:security Access controlled operation\r\n     * @custom:emits DepositsStatusChanged\r\n     */\r\n    function setDepositsPaused(bool paused) external override {\r\n        AccessChecker.checkRole(accessController, SystemRoles.RISK_CONTROLLER_ROLE, msg.sender);\r\n        depositsPaused = paused;\r\n        emit DepositsStatusChanged(paused);\r\n    }\r\n\r\n    /**\r\n     * @notice Updates LayerZero adapter\r\n     * @dev Changes bridge adapter address\r\n     * @param newAdapter New adapter address\r\n     * @custom:security Access controlled operation\r\n     * @custom:emits LZAdapterUpdated\r\n     */\r\n    function setLZAdapter(address newAdapter) external {\r\n        AccessChecker.checkRole(accessController, SystemRoles.DEFAULT_ADMIN_ROLE, msg.sender);\r\n        if (newAdapter == address(0)) revert InvalidAddress(newAdapter);\r\n        address oldAdapter = address(lzAdapter);\r\n        lzAdapter = LZAdapter(newAdapter);\r\n        emit LZAdapterUpdated(oldAdapter, newAdapter);\r\n    }\r\n\r\n    /**\r\n     * @notice Sets up initial approval for bridge operations\r\n     * @dev Required before any bridge operations can occur\r\n     * @custom:security Access controlled operation\r\n     */\r\n    function setupInitialApproval() external {\r\n        AccessChecker.checkRole(accessController, SystemRoles.DEFAULT_ADMIN_ROLE, msg.sender);\r\n        if (isInitialApprovalSet)\r\n            revert InitialApproval('ZeUSD_Router: Initial approval already set');\r\n        zeusdToken.approve(address(lzAdapter), type(uint256).max);\r\n        isInitialApprovalSet = true;\r\n    }\r\n\r\n    /**\r\n     * @notice Resets bridge approval\r\n     * @dev Removes approval for bridge operations\r\n     * @custom:security Access controlled operation\r\n     */\r\n    function resetApproval() external {\r\n        AccessChecker.checkRole(accessController, SystemRoles.DEFAULT_ADMIN_ROLE, msg.sender);\r\n        if (!isInitialApprovalSet) revert InitialApproval('ZeUSD_Router: Initial approval not set');\r\n        zeusdToken.approve(address(lzAdapter), 0);\r\n        isInitialApprovalSet = false;\r\n    }\r\n\r\n    /**\r\n     * @notice Gets Layer Zero fee quote\r\n     * @param sendParam Send parameters\r\n     * @return MessagingFee Fee details\r\n     */\r\n    function getQuoteFee(\r\n        SendParam memory sendParam\r\n    ) external view override returns (MessagingFee memory) {\r\n        return lzAdapter.quoteSend(sendParam, false);\r\n    }\r\n\r\n    /**\r\n     * @notice Updates contract addresses\r\n     * @dev Allows updating core contract references\r\n     * @param params Address update parameters\r\n     * @custom:security Access controlled operation\r\n     * @custom:emits AddressesUpdated\r\n     */\r\n    function updateAddresses(DataTypes.AddressUpdateParams calldata params) public {\r\n        AccessChecker.checkRole(accessController, SystemRoles.DEFAULT_ADMIN_ROLE, msg.sender);\r\n\r\n        if (params.updateCollateralVault) {\r\n            if (params.collateralVault == address(0)) revert InvalidAddress(params.collateralVault);\r\n            collateralVault = ICollateralVault(params.collateralVault);\r\n        }\r\n\r\n        if (params.updateZeusdToken) {\r\n            if (params.zeusdToken == address(0)) revert InvalidAddress(params.zeusdToken);\r\n            zeusdToken = ZeUSD(params.zeusdToken);\r\n        }\r\n\r\n        if (params.updateLzAdapter) {\r\n            if (params.lzAdapter == address(0)) revert InvalidAddress(params.lzAdapter);\r\n            lzAdapter = LZAdapter(params.lzAdapter);\r\n        }\r\n\r\n        emit AddressesUpdated(\r\n            params.updateCollateralVault ? params.collateralVault : address(collateralVault),\r\n            params.updateZeusdToken ? params.zeusdToken : address(zeusdToken),\r\n            params.updateLzAdapter ? params.lzAdapter : address(lzAdapter)\r\n        );\r\n    }\r\n\r\n    /**\r\n     * @notice Authorizes contract upgrades\r\n     * @dev Only UPGRADER_ROLE can upgrade the contract\r\n     * @custom:security Critical upgrade operation\r\n     */\r\n    function _authorizeUpgrade(address /*newImplementation*/) internal view override {\r\n        AccessChecker.checkRole(accessController, SystemRoles.UPGRADER_ROLE, msg.sender);\r\n    }\r\n\r\n    /**\r\n     * @notice Gets all positions for a user\r\n     * @param user Address of the user\r\n     * @return positions Array of Position structs\r\n     */\r\n    function getUserPositions(\r\n        address user\r\n    ) external view returns (DataTypes.DepositMetadata[] memory) {\r\n        return userPositions[user];\r\n    }\r\n\r\n    /**\r\n     * @notice Gets all active positions for a user\r\n     * @param user Address to query positions for\r\n     * @return tokenIds Array of active token IDs\r\n     * @return metadata Array of corresponding deposit metadata\r\n     */\r\n    function getUserActivePositions(\r\n        address user\r\n    )\r\n        external\r\n        view\r\n        override\r\n        returns (uint256[] memory tokenIds, DataTypes.DepositMetadata[] memory metadata)\r\n    {\r\n        // Get all token IDs owned by user\r\n        tokenIds = depositNFT.getTokensByOwner(user);\r\n\r\n        // Get metadata for each token\r\n        metadata = new DataTypes.DepositMetadata[](tokenIds.length);\r\n        for (uint256 i = 0; i < tokenIds.length; i++) {\r\n            metadata[i] = depositNFT.getDepositDetails(tokenIds[i]);\r\n        }\r\n\r\n        return (tokenIds, metadata);\r\n    }\r\n\r\n    /**\r\n     * @notice Gets details for a specific active position\r\n     * @param tokenId NFT token ID to query\r\n     * @return metadata Deposit metadata for the active position\r\n     */\r\n    function getActivePositionDetails(\r\n        uint256 tokenId\r\n    ) external view override returns (DataTypes.DepositMetadata memory metadata) {\r\n        require(depositNFT.ownerOf(tokenId) != address(0), 'Token burned or nonexistent');\r\n        return depositNFT.getDepositDetails(tokenId);\r\n    }\r\n\r\n    /**\r\n     * @notice Issues NFTs for historical deposits\r\n     * @dev Admin only function to retroactively create NFTs for deposits made before NFT system\r\n     * @param issuer Original depositor address\r\n     * @param collateralAddress Address of the collateral token\r\n     * @param asset Address of the deposited asset\r\n     * @param amount Amount of asset deposited\r\n     * @param zeusdMinted Amount of ZeUSD minted\r\n     * @param depositTimestamp Original deposit timestamp\r\n     * @param collateralPrice Price of collateral at deposit time\r\n     * @param subVault Address of the subvault\r\n     * @param tokenType Type of token deposited (stable/non-stable)\r\n     */\r\n    function issueHistoricalNFT(\r\n        address issuer,\r\n        address collateralAddress,\r\n        address asset,\r\n        uint256 amount,\r\n        uint256 zeusdMinted,\r\n        uint256 depositTimestamp,\r\n        uint256 collateralPrice,\r\n        address subVault,\r\n        string calldata integrationType,\r\n        DataTypes.TokenType tokenType\r\n    ) public nonReentrant {\r\n        // Check admin role\r\n        AccessChecker.checkRole(accessController, SystemRoles.DEFAULT_ADMIN_ROLE, msg.sender);\r\n\r\n        // Validate inputs\r\n        if (issuer == address(0)) revert InvalidAddress(issuer);\r\n        if (collateralAddress == address(0)) revert InvalidAddress(collateralAddress);\r\n        if (asset == address(0)) revert InvalidAddress(asset);\r\n        if (subVault == address(0)) revert InvalidAddress(subVault);\r\n        if (amount == 0) revert InvalidAmount();\r\n        if (zeusdMinted == 0) revert InvalidAmount();\r\n        if (collateralPrice == 0) revert InvalidAmount();\r\n        if (depositTimestamp >= block.timestamp) revert InvalidTimestamp();\r\n\r\n        // Create metadata\r\n        DataTypes.DepositMetadata memory metadata = DataTypes.DepositMetadata({\r\n            issuer: issuer,\r\n            collateralAddress: collateralAddress,\r\n            asset: asset,\r\n            amount: amount,\r\n            zeusdMinted: zeusdMinted,\r\n            depositTimestamp: depositTimestamp,\r\n            tokenId: depositNFT.getNextTokenId(),\r\n            collateralPrice: collateralPrice,\r\n            subVault: subVault,\r\n            integrationType: integrationType,\r\n            tokenType: tokenType\r\n        });\r\n\r\n        // Mint NFT\r\n        uint256 tokenId = depositNFT.mint(issuer, metadata);\r\n\r\n        // Record position\r\n        userPositions[issuer].push(metadata);\r\n\r\n        emit HistoricalNFTIssued(\r\n            issuer,\r\n            tokenId,\r\n            collateralAddress,\r\n            asset,\r\n            amount,\r\n            zeusdMinted,\r\n            depositTimestamp,\r\n            collateralPrice,\r\n            subVault,\r\n            tokenType\r\n        );\r\n    }\r\n\r\n    function batchIssueHistoricalNFTs(\r\n        address[] calldata issuers,\r\n        address[] calldata collateralAddresses,\r\n        address[] calldata assets,\r\n        uint256[] calldata amounts,\r\n        uint256[] calldata zeusdMinted,\r\n        uint256[] calldata depositTimestamps,\r\n        uint256[] calldata collateralPrices,\r\n        address[] calldata subVaults,\r\n        string[] calldata integrationTypes,\r\n        uint256[] calldata tokenTypes\r\n    ) external {\r\n        require(\r\n            issuers.length == collateralAddresses.length &&\r\n                issuers.length == assets.length &&\r\n                issuers.length == amounts.length &&\r\n                issuers.length == zeusdMinted.length &&\r\n                issuers.length == depositTimestamps.length &&\r\n                issuers.length == collateralPrices.length &&\r\n                issuers.length == subVaults.length &&\r\n                issuers.length == integrationTypes.length &&\r\n                issuers.length == tokenTypes.length,\r\n            'Array lengths mismatch'\r\n        );\r\n\r\n        for (uint i = 0; i < issuers.length; i++) {\r\n            issueHistoricalNFT(\r\n                issuers[i],\r\n                collateralAddresses[i],\r\n                assets[i],\r\n                amounts[i],\r\n                zeusdMinted[i],\r\n                depositTimestamps[i],\r\n                collateralPrices[i],\r\n                subVaults[i],\r\n                integrationTypes[i],\r\n                DataTypes.TokenType(tokenTypes[i])\r\n            );\r\n        }\r\n    }\r\n}\r\n"}},"matchId":"9405566","creationMatch":"exact_match","runtimeMatch":"exact_match","verifiedAt":"2025-10-06T10:50:33Z","match":"exact_match","chainId":"1","address":"0xEA25b537209eC4aefbC7252c6a49B132639Ea677"}