creation_sourcecode: {{
    "language": "Solidity",
    "settings": {
      "evmVersion": "paris",
      "optimizer": {
        "enabled": true,
        "runs": 5000
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      }
    },
    "sources": {
      "@layerzerolabs/lz-evm-oapp-v2/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/lz-evm-oapp-v2/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/lz-evm-oapp-v2/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/lz-evm-oapp-v2/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/lz-evm-oapp-v2/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/lz-evm-oapp-v2/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/lz-evm-oapp-v2/contracts/oft/interfaces/IOFT.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { MessagingReceipt, MessagingFee } from \"../../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 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/lz-evm-oapp-v2/contracts/oft/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 from 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 from 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/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\nenum ExecutionState {\n    NotExecutable,\n    Executable,\n    Executed\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    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(\n        Origin calldata _origin,\n        address _receiver,\n        address _receiveLib,\n        bytes32 _payloadHash\n    ) external view returns (bool);\n\n    function executable(Origin calldata _origin, address _receiver) external view returns (ExecutionState);\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    // todo: move to OAppReceiver? it is just convention for executor. we may can change it in a new Receiver version\n    function nextNonce(uint32 _eid, bytes32 _sender) external view returns (uint64);\n\n    function lzReceive(\n        Origin calldata _origin,\n        bytes32 _guid,\n        bytes calldata _message,\n        address _executor,\n        bytes calldata _extraData\n    ) external payable;\n}\n"
      },
      "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessageLibManager.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\nstruct SetConfigParam {\n    uint32 eid;\n    uint32 configType;\n    bytes config;\n}\n\ninterface IMessageLibManager {\n    struct Timeout {\n        address lib;\n        uint256 expiry;\n    }\n\n    event LibraryRegistered(address newLib);\n    event DefaultSendLibrarySet(uint32 eid, address newLib);\n    event DefaultReceiveLibrarySet(uint32 eid, address oldLib, 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 oldLib, 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 _timeout) 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    /// ------------------- 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 _gracePeriod) 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"
      },
      "@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"
      },
      "@openzeppelin/contracts/access/Ownable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../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 * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    constructor() {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. 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        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"
      },
      "@openzeppelin/contracts/interfaces/IERC5267.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)\n\npragma solidity ^0.8.0;\n\ninterface IERC5267 {\n    /**\n     * @dev MAY be emitted to signal that the domain could have changed.\n     */\n    event EIP712DomainChanged();\n\n    /**\n     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712\n     * signature.\n     */\n    function eip712Domain()\n        external\n        view\n        returns (\n            bytes1 fields,\n            string memory name,\n            string memory version,\n            uint256 chainId,\n            address verifyingContract,\n            bytes32 salt,\n            uint256[] memory extensions\n        );\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/ERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.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 * For a generic mechanism see {ERC20PresetMinterPauser}.\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 ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n    mapping(address => uint256) private _balances;\n\n    mapping(address => mapping(address => uint256)) private _allowances;\n\n    uint256 private _totalSupply;\n\n    string private _name;\n    string private _symbol;\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    constructor(string memory name_, string memory symbol_) {\n        _name = name_;\n        _symbol = symbol_;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view virtual override returns (string memory) {\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 override returns (string memory) {\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 override returns (uint8) {\n        return 18;\n    }\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view virtual override returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view virtual override returns (uint256) {\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 `amount`.\n     */\n    function transfer(address to, uint256 amount) public virtual override returns (bool) {\n        address owner = _msgSender();\n        _transfer(owner, to, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual override returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * NOTE: If `amount` 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 amount) public virtual override returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Emits an {Approval} event indicating the updated allowance. This is not\n     * required by the EIP. See the note at the beginning of {ERC20}.\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 `amount`.\n     * - the caller must have allowance for ``from``'s tokens of at least\n     * `amount`.\n     */\n    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {\n        address spender = _msgSender();\n        _spendAllowance(from, spender, amount);\n        _transfer(from, to, amount);\n        return true;\n    }\n\n    /**\n     * @dev Atomically increases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, allowance(owner, spender) + addedValue);\n        return true;\n    }\n\n    /**\n     * @dev Atomically decreases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `spender` must have allowance for the caller of at least\n     * `subtractedValue`.\n     */\n    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n        address owner = _msgSender();\n        uint256 currentAllowance = allowance(owner, spender);\n        require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n        unchecked {\n            _approve(owner, spender, currentAllowance - subtractedValue);\n        }\n\n        return true;\n    }\n\n    /**\n     * @dev Moves `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     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `from` must have a balance of at least `amount`.\n     */\n    function _transfer(address from, address to, uint256 amount) internal virtual {\n        require(from != address(0), \"ERC20: transfer from the zero address\");\n        require(to != address(0), \"ERC20: transfer to the zero address\");\n\n        _beforeTokenTransfer(from, to, amount);\n\n        uint256 fromBalance = _balances[from];\n        require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n        unchecked {\n            _balances[from] = fromBalance - amount;\n            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by\n            // decrementing then incrementing.\n            _balances[to] += amount;\n        }\n\n        emit Transfer(from, to, amount);\n\n        _afterTokenTransfer(from, to, amount);\n    }\n\n    /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n     * the total supply.\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     */\n    function _mint(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: mint to the zero address\");\n\n        _beforeTokenTransfer(address(0), account, amount);\n\n        _totalSupply += amount;\n        unchecked {\n            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.\n            _balances[account] += amount;\n        }\n        emit Transfer(address(0), account, amount);\n\n        _afterTokenTransfer(address(0), account, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, reducing the\n     * total supply.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     * - `account` must have at least `amount` tokens.\n     */\n    function _burn(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: burn from the zero address\");\n\n        _beforeTokenTransfer(account, address(0), amount);\n\n        uint256 accountBalance = _balances[account];\n        require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n        unchecked {\n            _balances[account] = accountBalance - amount;\n            // Overflow not possible: amount <= accountBalance <= totalSupply.\n            _totalSupply -= amount;\n        }\n\n        emit Transfer(account, address(0), amount);\n\n        _afterTokenTransfer(account, address(0), amount);\n    }\n\n    /**\n     * @dev Sets `amount` 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    function _approve(address owner, address spender, uint256 amount) internal virtual {\n        require(owner != address(0), \"ERC20: approve from the zero address\");\n        require(spender != address(0), \"ERC20: approve to the zero address\");\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n\n    /**\n     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n     *\n     * Does not update the allowance amount in case of infinite allowance.\n     * Revert if not enough allowance is available.\n     *\n     * Might emit an {Approval} event.\n     */\n    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {\n        uint256 currentAllowance = allowance(owner, spender);\n        if (currentAllowance != type(uint256).max) {\n            require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n            unchecked {\n                _approve(owner, spender, currentAllowance - amount);\n            }\n        }\n    }\n\n    /**\n     * @dev Hook that is called before any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n     * will be transferred to `to`.\n     * - when `from` is zero, `amount` tokens will be minted for `to`.\n     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}\n\n    /**\n     * @dev Hook that is called after any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n     * has been transferred to `to`.\n     * - when `from` is zero, `amount` tokens have been minted for `to`.\n     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 amount) external returns (bool);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/ERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20Permit.sol\";\nimport \"../ERC20.sol\";\nimport \"../../../utils/cryptography/ECDSA.sol\";\nimport \"../../../utils/cryptography/EIP712.sol\";\nimport \"../../../utils/Counters.sol\";\n\n/**\n * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n *\n * _Available since v3.4._\n */\nabstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {\n    using Counters for Counters.Counter;\n\n    mapping(address => Counters.Counter) private _nonces;\n\n    // solhint-disable-next-line var-name-mixedcase\n    bytes32 private constant _PERMIT_TYPEHASH =\n        keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n    /**\n     * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`.\n     * However, to ensure consistency with the upgradeable transpiler, we will continue\n     * to reserve a slot.\n     * @custom:oz-renamed-from _PERMIT_TYPEHASH\n     */\n    // solhint-disable-next-line var-name-mixedcase\n    bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT;\n\n    /**\n     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `\"1\"`.\n     *\n     * It's a good idea to use the same `name` that is defined as the ERC20 token name.\n     */\n    constructor(string memory name) EIP712(name, \"1\") {}\n\n    /**\n     * @inheritdoc IERC20Permit\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) public virtual override {\n        require(block.timestamp <= deadline, \"ERC20Permit: expired deadline\");\n\n        bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));\n\n        bytes32 hash = _hashTypedDataV4(structHash);\n\n        address signer = ECDSA.recover(hash, v, r, s);\n        require(signer == owner, \"ERC20Permit: invalid signature\");\n\n        _approve(owner, spender, value);\n    }\n\n    /**\n     * @inheritdoc IERC20Permit\n     */\n    function nonces(address owner) public view virtual override returns (uint256) {\n        return _nonces[owner].current();\n    }\n\n    /**\n     * @inheritdoc IERC20Permit\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view override returns (bytes32) {\n        return _domainSeparatorV4();\n    }\n\n    /**\n     * @dev \"Consume a nonce\": return the current value and increment.\n     *\n     * _Available since v4.1._\n     */\n    function _useNonce(address owner) internal virtual returns (uint256 current) {\n        Counters.Counter storage nonce = _nonces[owner];\n        current = nonce.current();\n        nonce.increment();\n    }\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\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/extensions/IERC20Permit.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n *\n * ==== Security Considerations\n *\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\n * generally recommended is:\n *\n * ```solidity\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\n *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\n *     doThing(..., value);\n * }\n *\n * function doThing(..., uint256 value) public {\n *     token.safeTransferFrom(msg.sender, address(this), value);\n *     ...\n * }\n * ```\n *\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\n * {SafeERC20-safeTransferFrom}).\n *\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\n * contracts should have entry points that don't rely on permit.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     *\n     * CAUTION: See Security Considerations above.\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using Address for address;\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(IERC20 token, address spender, uint256 value) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n        require(\n            (value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        unchecked {\n            uint256 oldAllowance = token.allowance(address(this), spender);\n            require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.\n     * Revert on invalid signature.\n     */\n    function safePermit(\n        IERC20Permit token,\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal {\n        uint256 nonceBefore = token.nonces(owner);\n        token.permit(owner, spender, value, deadline, v, r, s);\n        uint256 nonceAfter = token.nonces(owner);\n        require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        require(returndata.length == 0 || abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n        // and not revert is the subcall reverts.\n\n        (bool success, bytes memory returndata) = address(token).call(data);\n        return\n            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     *\n     * Furthermore, `isContract` will also return true if the target contract within\n     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n     * which only has an effect at the end of a transaction.\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert(errorMessage);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)\n\npragma solidity ^0.8.0;\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/Counters.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title Counters\n * @author Matt Condon (@shrugs)\n * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number\n * of elements in a mapping, issuing ERC721 ids, or counting request ids.\n *\n * Include with `using Counters for Counters.Counter;`\n */\nlibrary Counters {\n    struct Counter {\n        // This variable should never be directly accessed by users of the library: interactions must be restricted to\n        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add\n        // this feature: see https://github.com/ethereum/solidity/issues/4637\n        uint256 _value; // default: 0\n    }\n\n    function current(Counter storage counter) internal view returns (uint256) {\n        return counter._value;\n    }\n\n    function increment(Counter storage counter) internal {\n        unchecked {\n            counter._value += 1;\n        }\n    }\n\n    function decrement(Counter storage counter) internal {\n        uint256 value = counter._value;\n        require(value > 0, \"Counter: decrement overflow\");\n        unchecked {\n            counter._value = value - 1;\n        }\n    }\n\n    function reset(Counter storage counter) internal {\n        counter._value = 0;\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/ShortStrings.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol)\n\npragma solidity ^0.8.8;\n\nimport \"./StorageSlot.sol\";\n\n// | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |\n// | length  | 0x                                                              BB |\ntype ShortString is bytes32;\n\n/**\n * @dev This library provides functions to convert short memory strings\n * into a `ShortString` type that can be used as an immutable variable.\n *\n * Strings of arbitrary length can be optimized using this library if\n * they are short enough (up to 31 bytes) by packing them with their\n * length (1 byte) in a single EVM word (32 bytes). Additionally, a\n * fallback mechanism can be used for every other case.\n *\n * Usage example:\n *\n * ```solidity\n * contract Named {\n *     using ShortStrings for *;\n *\n *     ShortString private immutable _name;\n *     string private _nameFallback;\n *\n *     constructor(string memory contractName) {\n *         _name = contractName.toShortStringWithFallback(_nameFallback);\n *     }\n *\n *     function name() external view returns (string memory) {\n *         return _name.toStringWithFallback(_nameFallback);\n *     }\n * }\n * ```\n */\nlibrary ShortStrings {\n    // Used as an identifier for strings longer than 31 bytes.\n    bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;\n\n    error StringTooLong(string str);\n    error InvalidShortString();\n\n    /**\n     * @dev Encode a string of at most 31 chars into a `ShortString`.\n     *\n     * This will trigger a `StringTooLong` error is the input string is too long.\n     */\n    function toShortString(string memory str) internal pure returns (ShortString) {\n        bytes memory bstr = bytes(str);\n        if (bstr.length > 31) {\n            revert StringTooLong(str);\n        }\n        return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));\n    }\n\n    /**\n     * @dev Decode a `ShortString` back to a \"normal\" string.\n     */\n    function toString(ShortString sstr) internal pure returns (string memory) {\n        uint256 len = byteLength(sstr);\n        // using `new string(len)` would work locally but is not memory safe.\n        string memory str = new string(32);\n        /// @solidity memory-safe-assembly\n        assembly {\n            mstore(str, len)\n            mstore(add(str, 0x20), sstr)\n        }\n        return str;\n    }\n\n    /**\n     * @dev Return the length of a `ShortString`.\n     */\n    function byteLength(ShortString sstr) internal pure returns (uint256) {\n        uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;\n        if (result > 31) {\n            revert InvalidShortString();\n        }\n        return result;\n    }\n\n    /**\n     * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.\n     */\n    function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {\n        if (bytes(value).length < 32) {\n            return toShortString(value);\n        } else {\n            StorageSlot.getStringSlot(store).value = value;\n            return ShortString.wrap(_FALLBACK_SENTINEL);\n        }\n    }\n\n    /**\n     * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.\n     */\n    function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {\n        if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {\n            return toString(value);\n        } else {\n            return store;\n        }\n    }\n\n    /**\n     * @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.\n     *\n     * WARNING: This will return the \"byte length\" of the string. This may not reflect the actual length in terms of\n     * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.\n     */\n    function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {\n        if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {\n            return byteLength(value);\n        } else {\n            return bytes(store).length;\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/StorageSlot.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\n\npragma solidity ^0.8.0;\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 ERC1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\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(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n *     }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._\n * _Available since v4.9 for `string`, `bytes`._\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 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        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n     */\n    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n     */\n    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n     */\n    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `StringSlot` with member `value` located at `slot`.\n     */\n    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\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        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := store.slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BytesSlot` with member `value` located at `slot`.\n     */\n    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\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        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := store.slot\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Strings.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./math/Math.sol\";\nimport \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n    uint8 private constant _ADDRESS_LENGTH = 20;\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            /// @solidity memory-safe-assembly\n            assembly {\n                ptr := add(buffer, add(32, length))\n            }\n            while (true) {\n                ptr--;\n                /// @solidity memory-safe-assembly\n                assembly {\n                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\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 toString(int256 value) internal pure returns (string memory) {\n        return string(abi.encodePacked(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        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] = _SYMBOLS[value & 0xf];\n            value >>= 4;\n        }\n        require(value == 0, \"Strings: hex length insufficient\");\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 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 Returns true if the two strings are equal.\n     */\n    function equal(string memory a, string memory b) internal pure returns (bool) {\n        return keccak256(bytes(a)) == keccak256(bytes(b));\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/cryptography/ECDSA.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../Strings.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n    enum RecoverError {\n        NoError,\n        InvalidSignature,\n        InvalidSignatureLength,\n        InvalidSignatureS,\n        InvalidSignatureV // Deprecated in v4.8\n    }\n\n    function _throwError(RecoverError error) private pure {\n        if (error == RecoverError.NoError) {\n            return; // no error: do nothing\n        } else if (error == RecoverError.InvalidSignature) {\n            revert(\"ECDSA: invalid signature\");\n        } else if (error == RecoverError.InvalidSignatureLength) {\n            revert(\"ECDSA: invalid signature length\");\n        } else if (error == RecoverError.InvalidSignatureS) {\n            revert(\"ECDSA: invalid signature 's' value\");\n        }\n    }\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with\n     * `signature` or error string. This address can then be used for verification purposes.\n     *\n     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {toEthSignedMessageHash} on it.\n     *\n     * Documentation for signature generation:\n     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n     *\n     * _Available since v4.3._\n     */\n    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {\n        if (signature.length == 65) {\n            bytes32 r;\n            bytes32 s;\n            uint8 v;\n            // ecrecover takes the signature parameters, and the only way to get them\n            // currently is to use assembly.\n            /// @solidity memory-safe-assembly\n            assembly {\n                r := mload(add(signature, 0x20))\n                s := mload(add(signature, 0x40))\n                v := byte(0, mload(add(signature, 0x60)))\n            }\n            return tryRecover(hash, v, r, s);\n        } else {\n            return (address(0), RecoverError.InvalidSignatureLength);\n        }\n    }\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with\n     * `signature`. This address can then be used for verification purposes.\n     *\n     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {toEthSignedMessageHash} on it.\n     */\n    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n        (address recovered, RecoverError error) = tryRecover(hash, signature);\n        _throwError(error);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n     *\n     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\n     *\n     * _Available since v4.3._\n     */\n    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {\n        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n        uint8 v = uint8((uint256(vs) >> 255) + 27);\n        return tryRecover(hash, v, r, s);\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n     *\n     * _Available since v4.2._\n     */\n    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {\n        (address recovered, RecoverError error) = tryRecover(hash, r, vs);\n        _throwError(error);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     *\n     * _Available since v4.3._\n     */\n    function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {\n        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n        // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n        //\n        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n        // these malleable signatures as well.\n        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n            return (address(0), RecoverError.InvalidSignatureS);\n        }\n\n        // If the signature is valid (and not malleable), return the signer address\n        address signer = ecrecover(hash, v, r, s);\n        if (signer == address(0)) {\n            return (address(0), RecoverError.InvalidSignature);\n        }\n\n        return (signer, RecoverError.NoError);\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     */\n    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {\n        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);\n        _throwError(error);\n        return recovered;\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n     * produces hash corresponding to the one signed with the\n     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n     * JSON-RPC method as part of EIP-191.\n     *\n     * See {recover}.\n     */\n    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {\n        // 32 is the length in bytes of hash,\n        // enforced by the type signature above\n        /// @solidity memory-safe-assembly\n        assembly {\n            mstore(0x00, \"\\x19Ethereum Signed Message:\\n32\")\n            mstore(0x1c, hash)\n            message := keccak256(0x00, 0x3c)\n        }\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Message, created from `s`. This\n     * produces hash corresponding to the one signed with the\n     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n     * JSON-RPC method as part of EIP-191.\n     *\n     * See {recover}.\n     */\n    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n\", Strings.toString(s.length), s));\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Typed Data, created from a\n     * `domainSeparator` and a `structHash`. This produces hash corresponding\n     * to the one signed with the\n     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n     * JSON-RPC method as part of EIP-712.\n     *\n     * See {recover}.\n     */\n    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let ptr := mload(0x40)\n            mstore(ptr, \"\\x19\\x01\")\n            mstore(add(ptr, 0x02), domainSeparator)\n            mstore(add(ptr, 0x22), structHash)\n            data := keccak256(ptr, 0x42)\n        }\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Data with intended validator, created from a\n     * `validator` and `data` according to the version 0 of EIP-191.\n     *\n     * See {recover}.\n     */\n    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(\"\\x19\\x00\", validator, data));\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/cryptography/EIP712.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)\n\npragma solidity ^0.8.8;\n\nimport \"./ECDSA.sol\";\nimport \"../ShortStrings.sol\";\nimport \"../../interfaces/IERC5267.sol\";\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,\n * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding\n * they need in their contracts using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain\n * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the\n * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.\n *\n * _Available since v3.4._\n *\n * @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment\n */\nabstract contract EIP712 is IERC5267 {\n    using ShortStrings for *;\n\n    bytes32 private constant _TYPE_HASH =\n        keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n\n    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to\n    // invalidate the cached domain separator if the chain id changes.\n    bytes32 private immutable _cachedDomainSeparator;\n    uint256 private immutable _cachedChainId;\n    address private immutable _cachedThis;\n\n    bytes32 private immutable _hashedName;\n    bytes32 private immutable _hashedVersion;\n\n    ShortString private immutable _name;\n    ShortString private immutable _version;\n    string private _nameFallback;\n    string private _versionFallback;\n\n    /**\n     * @dev Initializes the domain separator and parameter caches.\n     *\n     * The meaning of `name` and `version` is specified in\n     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:\n     *\n     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n     * - `version`: the current major version of the signing domain.\n     *\n     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n     * contract upgrade].\n     */\n    constructor(string memory name, string memory version) {\n        _name = name.toShortStringWithFallback(_nameFallback);\n        _version = version.toShortStringWithFallback(_versionFallback);\n        _hashedName = keccak256(bytes(name));\n        _hashedVersion = keccak256(bytes(version));\n\n        _cachedChainId = block.chainid;\n        _cachedDomainSeparator = _buildDomainSeparator();\n        _cachedThis = address(this);\n    }\n\n    /**\n     * @dev Returns the domain separator for the current chain.\n     */\n    function _domainSeparatorV4() internal view returns (bytes32) {\n        if (address(this) == _cachedThis && block.chainid == _cachedChainId) {\n            return _cachedDomainSeparator;\n        } else {\n            return _buildDomainSeparator();\n        }\n    }\n\n    function _buildDomainSeparator() private view returns (bytes32) {\n        return keccak256(abi.encode(_TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));\n    }\n\n    /**\n     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n     * function returns the hash of the fully encoded EIP712 message for this domain.\n     *\n     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n     *\n     * ```solidity\n     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n     *     keccak256(\"Mail(address to,string contents)\"),\n     *     mailTo,\n     *     keccak256(bytes(mailContents))\n     * )));\n     * address signer = ECDSA.recover(digest, signature);\n     * ```\n     */\n    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n        return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);\n    }\n\n    /**\n     * @dev See {EIP-5267}.\n     *\n     * _Available since v4.9._\n     */\n    function eip712Domain()\n        public\n        view\n        virtual\n        override\n        returns (\n            bytes1 fields,\n            string memory name,\n            string memory version,\n            uint256 chainId,\n            address verifyingContract,\n            bytes32 salt,\n            uint256[] memory extensions\n        )\n    {\n        return (\n            hex\"0f\", // 01111\n            _name.toStringWithFallback(_nameFallback),\n            _version.toStringWithFallback(_versionFallback),\n            block.chainid,\n            address(this),\n            bytes32(0),\n            new uint256[](0)\n        );\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/math/Math.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    enum Rounding {\n        Down, // Toward negative infinity\n        Up, // Toward infinity\n        Zero // Toward zero\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 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 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 up instead\n     * of rounding down.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b - 1) / b can overflow on addition, so we distribute.\n        return a == 0 ? 0 : (a - 1) / b + 1;\n    }\n\n    /**\n     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n     * with further edits by 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^256 and mod 2^256 - 1, then use\n            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2^256 + prod0.\n            uint256 prod0; // 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                prod0 := mul(x, y)\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^256. Also prevents denominator == 0.\n            require(denominator > prod1, \"Math: mulDiv overflow\");\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. Always >= 1.\n            // See https://cs.stackexchange.com/q/138556/92363.\n\n            // Does not overflow because the denominator cannot be zero at this stage in the function.\n            uint256 twos = denominator & (~denominator + 1);\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^256 / 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^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv = 1 mod 2^4.\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 works\n            // in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2^8\n            inverse *= 2 - denominator * inverse; // inverse mod 2^16\n            inverse *= 2 - denominator * inverse; // inverse mod 2^32\n            inverse *= 2 - denominator * inverse; // inverse mod 2^64\n            inverse *= 2 - denominator * inverse; // inverse mod 2^128\n            inverse *= 2 - denominator * inverse; // inverse mod 2^256\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^256. Since the preconditions guarantee that the outcome is\n            // less than 2^256, 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     * @notice 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        uint256 result = mulDiv(x, y, denominator);\n        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n            result += 1;\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n     *\n     * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        if (a == 0) {\n            return 0;\n        }\n\n        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n        //\n        // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n        //\n        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n        //\n        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n        uint256 result = 1 << (log2(a) >> 1);\n\n        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n        // into the expected uint128 result.\n        unchecked {\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            return min(result, a / result);\n        }\n    }\n\n    /**\n     * @notice 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 + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 128;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 64;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 32;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 16;\n            }\n            if (value >> 8 > 0) {\n                value >>= 8;\n                result += 8;\n            }\n            if (value >> 4 > 0) {\n                value >>= 4;\n                result += 4;\n            }\n            if (value >> 2 > 0) {\n                value >>= 2;\n                result += 2;\n            }\n            if (value >> 1 > 0) {\n                result += 1;\n            }\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 + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10, rounded down, of a positive value.\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 + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256, rounded down, of a positive value.\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        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 16;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 8;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 4;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 2;\n            }\n            if (value >> 8 > 0) {\n                result += 1;\n            }\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 + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/math/SafeCast.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCast {\n    /**\n     * @dev Returns the downcasted uint248 from uint256, reverting on\n     * overflow (when the input is greater than largest uint248).\n     *\n     * Counterpart to Solidity's `uint248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint248(uint256 value) internal pure returns (uint248) {\n        require(value <= type(uint248).max, \"SafeCast: value doesn't fit in 248 bits\");\n        return uint248(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint240 from uint256, reverting on\n     * overflow (when the input is greater than largest uint240).\n     *\n     * Counterpart to Solidity's `uint240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint240(uint256 value) internal pure returns (uint240) {\n        require(value <= type(uint240).max, \"SafeCast: value doesn't fit in 240 bits\");\n        return uint240(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint232 from uint256, reverting on\n     * overflow (when the input is greater than largest uint232).\n     *\n     * Counterpart to Solidity's `uint232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint232(uint256 value) internal pure returns (uint232) {\n        require(value <= type(uint232).max, \"SafeCast: value doesn't fit in 232 bits\");\n        return uint232(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint224 from uint256, reverting on\n     * overflow (when the input is greater than largest uint224).\n     *\n     * Counterpart to Solidity's `uint224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     *\n     * _Available since v4.2._\n     */\n    function toUint224(uint256 value) internal pure returns (uint224) {\n        require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n        return uint224(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint216 from uint256, reverting on\n     * overflow (when the input is greater than largest uint216).\n     *\n     * Counterpart to Solidity's `uint216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint216(uint256 value) internal pure returns (uint216) {\n        require(value <= type(uint216).max, \"SafeCast: value doesn't fit in 216 bits\");\n        return uint216(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint208 from uint256, reverting on\n     * overflow (when the input is greater than largest uint208).\n     *\n     * Counterpart to Solidity's `uint208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint208(uint256 value) internal pure returns (uint208) {\n        require(value <= type(uint208).max, \"SafeCast: value doesn't fit in 208 bits\");\n        return uint208(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint200 from uint256, reverting on\n     * overflow (when the input is greater than largest uint200).\n     *\n     * Counterpart to Solidity's `uint200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint200(uint256 value) internal pure returns (uint200) {\n        require(value <= type(uint200).max, \"SafeCast: value doesn't fit in 200 bits\");\n        return uint200(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint192 from uint256, reverting on\n     * overflow (when the input is greater than largest uint192).\n     *\n     * Counterpart to Solidity's `uint192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint192(uint256 value) internal pure returns (uint192) {\n        require(value <= type(uint192).max, \"SafeCast: value doesn't fit in 192 bits\");\n        return uint192(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint184 from uint256, reverting on\n     * overflow (when the input is greater than largest uint184).\n     *\n     * Counterpart to Solidity's `uint184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint184(uint256 value) internal pure returns (uint184) {\n        require(value <= type(uint184).max, \"SafeCast: value doesn't fit in 184 bits\");\n        return uint184(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint176 from uint256, reverting on\n     * overflow (when the input is greater than largest uint176).\n     *\n     * Counterpart to Solidity's `uint176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint176(uint256 value) internal pure returns (uint176) {\n        require(value <= type(uint176).max, \"SafeCast: value doesn't fit in 176 bits\");\n        return uint176(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint168 from uint256, reverting on\n     * overflow (when the input is greater than largest uint168).\n     *\n     * Counterpart to Solidity's `uint168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint168(uint256 value) internal pure returns (uint168) {\n        require(value <= type(uint168).max, \"SafeCast: value doesn't fit in 168 bits\");\n        return uint168(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint160 from uint256, reverting on\n     * overflow (when the input is greater than largest uint160).\n     *\n     * Counterpart to Solidity's `uint160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint160(uint256 value) internal pure returns (uint160) {\n        require(value <= type(uint160).max, \"SafeCast: value doesn't fit in 160 bits\");\n        return uint160(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint152 from uint256, reverting on\n     * overflow (when the input is greater than largest uint152).\n     *\n     * Counterpart to Solidity's `uint152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint152(uint256 value) internal pure returns (uint152) {\n        require(value <= type(uint152).max, \"SafeCast: value doesn't fit in 152 bits\");\n        return uint152(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint144 from uint256, reverting on\n     * overflow (when the input is greater than largest uint144).\n     *\n     * Counterpart to Solidity's `uint144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint144(uint256 value) internal pure returns (uint144) {\n        require(value <= type(uint144).max, \"SafeCast: value doesn't fit in 144 bits\");\n        return uint144(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint136 from uint256, reverting on\n     * overflow (when the input is greater than largest uint136).\n     *\n     * Counterpart to Solidity's `uint136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint136(uint256 value) internal pure returns (uint136) {\n        require(value <= type(uint136).max, \"SafeCast: value doesn't fit in 136 bits\");\n        return uint136(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint128 from uint256, reverting on\n     * overflow (when the input is greater than largest uint128).\n     *\n     * Counterpart to Solidity's `uint128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint128(uint256 value) internal pure returns (uint128) {\n        require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n        return uint128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint120 from uint256, reverting on\n     * overflow (when the input is greater than largest uint120).\n     *\n     * Counterpart to Solidity's `uint120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint120(uint256 value) internal pure returns (uint120) {\n        require(value <= type(uint120).max, \"SafeCast: value doesn't fit in 120 bits\");\n        return uint120(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint112 from uint256, reverting on\n     * overflow (when the input is greater than largest uint112).\n     *\n     * Counterpart to Solidity's `uint112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint112(uint256 value) internal pure returns (uint112) {\n        require(value <= type(uint112).max, \"SafeCast: value doesn't fit in 112 bits\");\n        return uint112(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint104 from uint256, reverting on\n     * overflow (when the input is greater than largest uint104).\n     *\n     * Counterpart to Solidity's `uint104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint104(uint256 value) internal pure returns (uint104) {\n        require(value <= type(uint104).max, \"SafeCast: value doesn't fit in 104 bits\");\n        return uint104(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint96 from uint256, reverting on\n     * overflow (when the input is greater than largest uint96).\n     *\n     * Counterpart to Solidity's `uint96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     *\n     * _Available since v4.2._\n     */\n    function toUint96(uint256 value) internal pure returns (uint96) {\n        require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n        return uint96(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint88 from uint256, reverting on\n     * overflow (when the input is greater than largest uint88).\n     *\n     * Counterpart to Solidity's `uint88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint88(uint256 value) internal pure returns (uint88) {\n        require(value <= type(uint88).max, \"SafeCast: value doesn't fit in 88 bits\");\n        return uint88(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint80 from uint256, reverting on\n     * overflow (when the input is greater than largest uint80).\n     *\n     * Counterpart to Solidity's `uint80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint80(uint256 value) internal pure returns (uint80) {\n        require(value <= type(uint80).max, \"SafeCast: value doesn't fit in 80 bits\");\n        return uint80(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint72 from uint256, reverting on\n     * overflow (when the input is greater than largest uint72).\n     *\n     * Counterpart to Solidity's `uint72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint72(uint256 value) internal pure returns (uint72) {\n        require(value <= type(uint72).max, \"SafeCast: value doesn't fit in 72 bits\");\n        return uint72(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint64 from uint256, reverting on\n     * overflow (when the input is greater than largest uint64).\n     *\n     * Counterpart to Solidity's `uint64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint64(uint256 value) internal pure returns (uint64) {\n        require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n        return uint64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint56 from uint256, reverting on\n     * overflow (when the input is greater than largest uint56).\n     *\n     * Counterpart to Solidity's `uint56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint56(uint256 value) internal pure returns (uint56) {\n        require(value <= type(uint56).max, \"SafeCast: value doesn't fit in 56 bits\");\n        return uint56(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint48 from uint256, reverting on\n     * overflow (when the input is greater than largest uint48).\n     *\n     * Counterpart to Solidity's `uint48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint48(uint256 value) internal pure returns (uint48) {\n        require(value <= type(uint48).max, \"SafeCast: value doesn't fit in 48 bits\");\n        return uint48(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint40 from uint256, reverting on\n     * overflow (when the input is greater than largest uint40).\n     *\n     * Counterpart to Solidity's `uint40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint40(uint256 value) internal pure returns (uint40) {\n        require(value <= type(uint40).max, \"SafeCast: value doesn't fit in 40 bits\");\n        return uint40(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint32 from uint256, reverting on\n     * overflow (when the input is greater than largest uint32).\n     *\n     * Counterpart to Solidity's `uint32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint32(uint256 value) internal pure returns (uint32) {\n        require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n        return uint32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint24 from uint256, reverting on\n     * overflow (when the input is greater than largest uint24).\n     *\n     * Counterpart to Solidity's `uint24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint24(uint256 value) internal pure returns (uint24) {\n        require(value <= type(uint24).max, \"SafeCast: value doesn't fit in 24 bits\");\n        return uint24(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint16 from uint256, reverting on\n     * overflow (when the input is greater than largest uint16).\n     *\n     * Counterpart to Solidity's `uint16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint16(uint256 value) internal pure returns (uint16) {\n        require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n        return uint16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint8 from uint256, reverting on\n     * overflow (when the input is greater than largest uint8).\n     *\n     * Counterpart to Solidity's `uint8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint8(uint256 value) internal pure returns (uint8) {\n        require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n        return uint8(value);\n    }\n\n    /**\n     * @dev Converts a signed int256 into an unsigned uint256.\n     *\n     * Requirements:\n     *\n     * - input must be greater than or equal to 0.\n     *\n     * _Available since v3.0._\n     */\n    function toUint256(int256 value) internal pure returns (uint256) {\n        require(value >= 0, \"SafeCast: value must be positive\");\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int248 from int256, reverting on\n     * overflow (when the input is less than smallest int248 or\n     * greater than largest int248).\n     *\n     * Counterpart to Solidity's `int248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt248(int256 value) internal pure returns (int248 downcasted) {\n        downcasted = int248(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 248 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int240 from int256, reverting on\n     * overflow (when the input is less than smallest int240 or\n     * greater than largest int240).\n     *\n     * Counterpart to Solidity's `int240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt240(int256 value) internal pure returns (int240 downcasted) {\n        downcasted = int240(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 240 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int232 from int256, reverting on\n     * overflow (when the input is less than smallest int232 or\n     * greater than largest int232).\n     *\n     * Counterpart to Solidity's `int232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt232(int256 value) internal pure returns (int232 downcasted) {\n        downcasted = int232(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 232 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int224 from int256, reverting on\n     * overflow (when the input is less than smallest int224 or\n     * greater than largest int224).\n     *\n     * Counterpart to Solidity's `int224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt224(int256 value) internal pure returns (int224 downcasted) {\n        downcasted = int224(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 224 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int216 from int256, reverting on\n     * overflow (when the input is less than smallest int216 or\n     * greater than largest int216).\n     *\n     * Counterpart to Solidity's `int216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt216(int256 value) internal pure returns (int216 downcasted) {\n        downcasted = int216(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 216 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int208 from int256, reverting on\n     * overflow (when the input is less than smallest int208 or\n     * greater than largest int208).\n     *\n     * Counterpart to Solidity's `int208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt208(int256 value) internal pure returns (int208 downcasted) {\n        downcasted = int208(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 208 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int200 from int256, reverting on\n     * overflow (when the input is less than smallest int200 or\n     * greater than largest int200).\n     *\n     * Counterpart to Solidity's `int200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt200(int256 value) internal pure returns (int200 downcasted) {\n        downcasted = int200(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 200 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int192 from int256, reverting on\n     * overflow (when the input is less than smallest int192 or\n     * greater than largest int192).\n     *\n     * Counterpart to Solidity's `int192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt192(int256 value) internal pure returns (int192 downcasted) {\n        downcasted = int192(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 192 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int184 from int256, reverting on\n     * overflow (when the input is less than smallest int184 or\n     * greater than largest int184).\n     *\n     * Counterpart to Solidity's `int184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt184(int256 value) internal pure returns (int184 downcasted) {\n        downcasted = int184(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 184 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int176 from int256, reverting on\n     * overflow (when the input is less than smallest int176 or\n     * greater than largest int176).\n     *\n     * Counterpart to Solidity's `int176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt176(int256 value) internal pure returns (int176 downcasted) {\n        downcasted = int176(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 176 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int168 from int256, reverting on\n     * overflow (when the input is less than smallest int168 or\n     * greater than largest int168).\n     *\n     * Counterpart to Solidity's `int168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt168(int256 value) internal pure returns (int168 downcasted) {\n        downcasted = int168(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 168 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int160 from int256, reverting on\n     * overflow (when the input is less than smallest int160 or\n     * greater than largest int160).\n     *\n     * Counterpart to Solidity's `int160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt160(int256 value) internal pure returns (int160 downcasted) {\n        downcasted = int160(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 160 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int152 from int256, reverting on\n     * overflow (when the input is less than smallest int152 or\n     * greater than largest int152).\n     *\n     * Counterpart to Solidity's `int152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt152(int256 value) internal pure returns (int152 downcasted) {\n        downcasted = int152(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 152 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int144 from int256, reverting on\n     * overflow (when the input is less than smallest int144 or\n     * greater than largest int144).\n     *\n     * Counterpart to Solidity's `int144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt144(int256 value) internal pure returns (int144 downcasted) {\n        downcasted = int144(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 144 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int136 from int256, reverting on\n     * overflow (when the input is less than smallest int136 or\n     * greater than largest int136).\n     *\n     * Counterpart to Solidity's `int136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt136(int256 value) internal pure returns (int136 downcasted) {\n        downcasted = int136(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 136 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt128(int256 value) internal pure returns (int128 downcasted) {\n        downcasted = int128(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 128 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int120 from int256, reverting on\n     * overflow (when the input is less than smallest int120 or\n     * greater than largest int120).\n     *\n     * Counterpart to Solidity's `int120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt120(int256 value) internal pure returns (int120 downcasted) {\n        downcasted = int120(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 120 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int112 from int256, reverting on\n     * overflow (when the input is less than smallest int112 or\n     * greater than largest int112).\n     *\n     * Counterpart to Solidity's `int112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt112(int256 value) internal pure returns (int112 downcasted) {\n        downcasted = int112(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 112 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int104 from int256, reverting on\n     * overflow (when the input is less than smallest int104 or\n     * greater than largest int104).\n     *\n     * Counterpart to Solidity's `int104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt104(int256 value) internal pure returns (int104 downcasted) {\n        downcasted = int104(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 104 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int96 from int256, reverting on\n     * overflow (when the input is less than smallest int96 or\n     * greater than largest int96).\n     *\n     * Counterpart to Solidity's `int96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt96(int256 value) internal pure returns (int96 downcasted) {\n        downcasted = int96(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 96 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int88 from int256, reverting on\n     * overflow (when the input is less than smallest int88 or\n     * greater than largest int88).\n     *\n     * Counterpart to Solidity's `int88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt88(int256 value) internal pure returns (int88 downcasted) {\n        downcasted = int88(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 88 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int80 from int256, reverting on\n     * overflow (when the input is less than smallest int80 or\n     * greater than largest int80).\n     *\n     * Counterpart to Solidity's `int80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt80(int256 value) internal pure returns (int80 downcasted) {\n        downcasted = int80(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 80 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int72 from int256, reverting on\n     * overflow (when the input is less than smallest int72 or\n     * greater than largest int72).\n     *\n     * Counterpart to Solidity's `int72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt72(int256 value) internal pure returns (int72 downcasted) {\n        downcasted = int72(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 72 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt64(int256 value) internal pure returns (int64 downcasted) {\n        downcasted = int64(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 64 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int56 from int256, reverting on\n     * overflow (when the input is less than smallest int56 or\n     * greater than largest int56).\n     *\n     * Counterpart to Solidity's `int56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt56(int256 value) internal pure returns (int56 downcasted) {\n        downcasted = int56(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 56 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int48 from int256, reverting on\n     * overflow (when the input is less than smallest int48 or\n     * greater than largest int48).\n     *\n     * Counterpart to Solidity's `int48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt48(int256 value) internal pure returns (int48 downcasted) {\n        downcasted = int48(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 48 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int40 from int256, reverting on\n     * overflow (when the input is less than smallest int40 or\n     * greater than largest int40).\n     *\n     * Counterpart to Solidity's `int40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt40(int256 value) internal pure returns (int40 downcasted) {\n        downcasted = int40(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 40 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt32(int256 value) internal pure returns (int32 downcasted) {\n        downcasted = int32(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 32 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int24 from int256, reverting on\n     * overflow (when the input is less than smallest int24 or\n     * greater than largest int24).\n     *\n     * Counterpart to Solidity's `int24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt24(int256 value) internal pure returns (int24 downcasted) {\n        downcasted = int24(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 24 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt16(int256 value) internal pure returns (int16 downcasted) {\n        downcasted = int16(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 16 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt8(int256 value) internal pure returns (int8 downcasted) {\n        downcasted = int8(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 8 bits\");\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     *\n     * _Available since v3.0._\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n        require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n        return int256(value);\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/math/SignedMath.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n    /**\n     * @dev Returns the largest of two signed numbers.\n     */\n    function max(int256 a, int256 b) internal pure returns (int256) {\n        return 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 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            // must be unchecked in order to support `n = type(int256).min`\n            return uint256(n >= 0 ? n : -n);\n        }\n    }\n}\n"
      },
      "src/StargateBase.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.22;\n\nimport { SafeCast } from \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\n\nimport { ILayerZeroEndpointV2 } from \"@layerzerolabs/lz-evm-oapp-v2/contracts/oapp/interfaces/IOAppCore.sol\";\nimport { Origin } from \"@layerzerolabs/lz-evm-oapp-v2/contracts/oapp/OApp.sol\";\n// Solidity does not support splitting import across multiple lines\n// solhint-disable-next-line max-line-length\nimport { OFTLimit, OFTFeeDetail, OFTReceipt, SendParam, MessagingReceipt, MessagingFee, IOFT } from \"@layerzerolabs/lz-evm-oapp-v2/contracts/oft/interfaces/IOFT.sol\";\nimport { OFTComposeMsgCodec } from \"@layerzerolabs/lz-evm-oapp-v2/contracts/oft/libs/OFTComposeMsgCodec.sol\";\n\nimport { IStargate, Ticket } from \"./interfaces/IStargate.sol\";\nimport { IStargateFeeLib, FeeParams } from \"./interfaces/IStargateFeeLib.sol\";\nimport { ITokenMessaging, RideBusParams, TaxiParams } from \"./interfaces/ITokenMessaging.sol\";\nimport { ITokenMessagingHandler } from \"./interfaces/ITokenMessagingHandler.sol\";\nimport { ICreditMessagingHandler, Credit, TargetCredit } from \"./interfaces/ICreditMessagingHandler.sol\";\nimport { Path } from \"./libs/Path.sol\";\nimport { Transfer } from \"./libs/Transfer.sol\";\n\n/// @title The base contract for StargateOFT, StargatePool, StargatePoolMigratable, and StargatePoolNative.\nabstract contract StargateBase is Transfer, IStargate, ITokenMessagingHandler, ICreditMessagingHandler {\n    using SafeCast for uint256;\n\n    // Stargate status\n    uint8 internal constant NOT_ENTERED = 1;\n    uint8 internal constant ENTERED = 2;\n    uint8 internal constant PAUSED = 3;\n\n    /// @dev The token for the Pool or OFT.\n    /// @dev address(0) indicates native coin, such as ETH.\n    address public immutable override token;\n    /// @dev The shared decimals (lowest common decimals between chains).\n    uint8 public immutable override sharedDecimals;\n    /// @dev The rate between local decimals and shared decimals.\n    uint256 internal immutable convertRate;\n\n    /// @dev The local LayerZero EndpointV2.\n    ILayerZeroEndpointV2 public immutable endpoint;\n    /// @dev The local LayerZero endpoint ID\n    uint32 public immutable localEid;\n\n    address internal feeLib;\n    /// @dev The StargateBase status.  Options include 1. NOT_ENTERED 2. ENTERED and 3. PAUSED.\n    uint8 public status = NOT_ENTERED;\n    /// @dev The treasury accrued fees, stored in SD.\n    uint64 public treasuryFee;\n\n    address internal creditMessaging;\n    address internal lzToken;\n    address internal planner;\n    address internal tokenMessaging;\n    address internal treasurer;\n\n    /// @dev Mapping of paths from this chain to other chains identified by their endpoint ID.\n    mapping(uint32 eid => Path path) public paths;\n\n    /// @dev A store for tokens that could not be delivered because _outflow() failed.\n    /// @dev retryReceiveToken() can be called to retry the receive.\n    mapping(bytes32 guid => mapping(uint8 index => bytes32 hash)) public unreceivedTokens;\n\n    modifier onlyCaller(address _caller) {\n        if (msg.sender != _caller) revert Stargate_Unauthorized();\n        _;\n    }\n\n    modifier nonReentrantAndNotPaused() {\n        // On the first call to nonReentrant, _status will be _NOT_ENTERED\n        if (status != NOT_ENTERED) {\n            if (status == ENTERED) revert Stargate_ReentrantCall();\n            revert Stargate_Paused();\n        }\n        // Any calls to nonReentrant after this point will fail\n        status = ENTERED;\n        _;\n        status = NOT_ENTERED;\n    }\n\n    error Stargate_ReentrantCall();\n    error Stargate_InvalidTokenDecimals();\n    error Stargate_Unauthorized();\n    error Stargate_SlippageTooHigh();\n    error Stargate_UnreceivedTokenNotFound();\n    error Stargate_OutflowFailed();\n    error Stargate_InvalidAmount();\n    error Stargate_InsufficientFare();\n    error Stargate_InvalidPath();\n    error Stargate_LzTokenUnavailable();\n    error Stargate_Paused();\n    error Stargate_RecoverTokenUnsupported();\n\n    event AddressConfigSet(AddressConfig config);\n    event CreditsSent(uint32 dstEid, Credit[] credits);\n    event CreditsReceived(uint32 srcEid, Credit[] credits);\n    event UnreceivedTokenCached(\n        bytes32 guid,\n        uint8 index,\n        uint32 srcEid,\n        address receiver,\n        uint256 amountLD,\n        bytes composeMsg\n    );\n    event OFTPathSet(uint32 dstEid, bool oft);\n    event PauseSet(bool paused);\n    event PlannerFeeWithdrawn(uint256 amount);\n    event TreasuryFeeAdded(uint64 amountSD);\n    event TreasuryFeeWithdrawn(address to, uint64 amountSD);\n\n    struct AddressConfig {\n        address feeLib;\n        address planner;\n        address treasurer;\n        address tokenMessaging;\n        address creditMessaging;\n        address lzToken;\n    }\n\n    /// @notice Create a new Stargate contract\n    /// @dev Reverts with InvalidTokenDecimals if the token decimals are smaller than the shared decimals.\n    /// @param _token The token for the pool or oft. If the token is address(0), it is the native coin\n    /// @param _tokenDecimals The number of decimals for this tokens implementation on this chain\n    /// @param _sharedDecimals The number of decimals shared between all implementations of the OFT\n    /// @param _endpoint The LZ endpoint contract\n    /// @param _owner The owner of this contract\n    constructor(address _token, uint8 _tokenDecimals, uint8 _sharedDecimals, address _endpoint, address _owner) {\n        token = _token;\n        if (_tokenDecimals < _sharedDecimals) revert Stargate_InvalidTokenDecimals();\n        convertRate = 10 ** (_tokenDecimals - _sharedDecimals);\n        sharedDecimals = _sharedDecimals;\n\n        endpoint = ILayerZeroEndpointV2(_endpoint);\n        localEid = endpoint.eid();\n        _transferOwnership(_owner);\n    }\n\n    // ---------------------------------- Only Owner ------------------------------------------\n\n    /// @notice Configure the roles for this contract.\n    /// @param _config An AddressConfig object containing the addresses for the different roles used by Stargate.\n    function setAddressConfig(AddressConfig calldata _config) external onlyOwner {\n        feeLib = _config.feeLib;\n        planner = _config.planner;\n        treasurer = _config.treasurer;\n        tokenMessaging = _config.tokenMessaging;\n        creditMessaging = _config.creditMessaging;\n        lzToken = _config.lzToken;\n        emit AddressConfigSet(_config);\n    }\n\n    /// @notice Sets a given Path as using OFT or resets it from OFT.\n    /// @dev Set the path as OFT if the remote chain is using OFT.\n    /// @dev When migrating from OFT to pool on remote chain (e.g. migrate USDC to circles), reset the path to non-OFT.\n    /// @dev Reverts with InvalidPath if the destination chain is the same as local.\n    /// @param _dstEid The destination chain endpoint ID\n    /// @param _oft Whether to set or reset the path\n    function setOFTPath(uint32 _dstEid, bool _oft) external onlyOwner {\n        if (_dstEid == localEid) revert Stargate_InvalidPath();\n        paths[_dstEid].setOFTPath(_oft);\n        emit OFTPathSet(_dstEid, _oft);\n    }\n\n    // ---------------------------------- Only Treasurer ------------------------------------------\n\n    /// @notice Withdraw from the accrued fees in the treasury.\n    /// @param _to The destination account\n    /// @param _amountSD The amount to withdraw in SD\n    function withdrawTreasuryFee(address _to, uint64 _amountSD) external onlyCaller(treasurer) {\n        treasuryFee -= _amountSD;\n        _safeOutflow(_to, _sd2ld(_amountSD));\n        emit TreasuryFeeWithdrawn(_to, _amountSD);\n    }\n\n    /// @notice Add tokens to the treasury, from the senders account.\n    /// @dev Only used for increasing the overall budget for transaction rewards\n    /// @dev The treasuryFee is essentially the reward pool.\n    /// @dev Rewards are capped to the treasury amount, which limits exposure so\n    /// @dev Stargate does not pay beyond what it's charged.\n    /// @param _amountLD The amount to add in LD\n    function addTreasuryFee(uint256 _amountLD) external payable onlyCaller(treasurer) {\n        _assertMsgValue(_amountLD);\n        uint64 amountSD = _inflow(msg.sender, _amountLD);\n        treasuryFee += amountSD;\n        emit TreasuryFeeAdded(amountSD);\n    }\n\n    /// @dev Recover tokens sent to this contract by mistake.\n    /// @dev Only the treasurer can recover the token.\n    /// @dev Reverts with Stargate_RecoverTokenUnsupported if the treasurer attempts to withdraw StargateBase.token().\n    /// @param _token the token to recover. if 0x0 then it is native token\n    /// @param _to the address to send the token to\n    /// @param _amount the amount to send\n    function recoverToken(\n        address _token,\n        address _to,\n        uint256 _amount\n    ) public virtual nonReentrantAndNotPaused onlyCaller(treasurer) returns (uint256) {\n        /// @dev Excess native is considered planner accumulated fees.\n        if (_token == address(0)) revert Stargate_RecoverTokenUnsupported();\n        Transfer.safeTransfer(_token, _to, _amount, false);\n        return _amount;\n    }\n\n    // ---------------------------------- Only Planner ------------------------------------------\n\n    /// @notice Pause or unpause a Stargate\n    /// @dev Be careful with this call, as it unsets the re-entry guard.\n    /// @param _paused Whether to pause or unpause the stargate\n    function setPause(bool _paused) external onlyCaller(planner) {\n        if (status == ENTERED) revert Stargate_ReentrantCall();\n        status = _paused ? PAUSED : NOT_ENTERED;\n        emit PauseSet(_paused);\n    }\n\n    function _plannerFee() internal view virtual returns (uint256) {\n        return address(this).balance;\n    }\n\n    function plannerFee() external view returns (uint256 available) {\n        available = _plannerFee();\n    }\n\n    /// @notice Withdraw planner fees accumulated in StargateBase.\n    /// @dev The planner fee is accumulated in StargateBase to avoid the cost of passing msg.value to TokenMessaging.\n    function withdrawPlannerFee() external virtual onlyCaller(planner) {\n        uint256 available = _plannerFee();\n        Transfer.safeTransferNative(msg.sender, available, false);\n        emit PlannerFeeWithdrawn(available);\n    }\n\n    // ------------------------------- Public Functions ---------------------------------------\n\n    /// @notice Send tokens through the Stargate\n    /// @dev Emits OFTSent when the send is successful\n    /// @param _sendParam The SendParam object detailing the transaction\n    /// @param _fee The MessagingFee object describing the fee to pay\n    /// @param _refundAddress The address to refund any LZ fees paid in excess\n    /// @return msgReceipt The receipt proving the message was sent\n    /// @return oftReceipt The receipt proving the OFT swap\n    function send(\n        SendParam calldata _sendParam,\n        MessagingFee calldata _fee,\n        address _refundAddress\n    ) external payable override returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt) {\n        (msgReceipt, oftReceipt, ) = sendToken(_sendParam, _fee, _refundAddress);\n    }\n\n    function sendToken(\n        SendParam calldata _sendParam,\n        MessagingFee calldata _fee,\n        address _refundAddress\n    )\n        public\n        payable\n        override\n        nonReentrantAndNotPaused\n        returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt, Ticket memory ticket)\n    {\n        // step 1: assets inflows and apply the fee to the input amount\n        (bool isTaxi, uint64 amountInSD, uint64 amountOutSD) = _inflowAndCharge(_sendParam);\n\n        // step 2: generate the oft receipt\n        oftReceipt = OFTReceipt(_sd2ld(amountInSD), _sd2ld(amountOutSD));\n\n        // step 3: assert the messaging fee\n        MessagingFee memory messagingFee = _assertMessagingFee(_fee, oftReceipt.amountSentLD);\n\n        // step 4: send the token depending on the mode Taxi or Bus\n        if (isTaxi) {\n            msgReceipt = _taxi(_sendParam, messagingFee, amountOutSD, _refundAddress);\n        } else {\n            (msgReceipt, ticket) = _rideBus(_sendParam, messagingFee, amountOutSD, _refundAddress);\n        }\n\n        emit OFTSent(\n            msgReceipt.guid,\n            _sendParam.dstEid,\n            msg.sender,\n            oftReceipt.amountSentLD,\n            oftReceipt.amountReceivedLD\n        );\n    }\n\n    /// @notice Retry receiving a token that initially failed.\n    /// @dev The message has been delivered by the Messaging layer, so it is ok for anyone to retry.\n    /// @dev try to receive the token if the previous attempt failed in lzReceive\n    /// @dev Reverts with UnreceivedTokenNotFound if the message is not found in the cache\n    /// @dev Emits OFTReceived if the receive succeeds\n    /// @param _guid The global unique ID for the message that failed\n    /// @param _index The index of the message that failed\n    /// @param _srcEid The source endpoint ID for the message that failed\n    /// @param _receiver The account receiver for the message that failed\n    /// @param _amountLD The amount of tokens in LD to transfer to the account\n    /// @param _composeMsg The bytes representing the compose message in the message that failed\n    function retryReceiveToken(\n        bytes32 _guid,\n        uint8 _index,\n        uint32 _srcEid,\n        address _receiver,\n        uint256 _amountLD,\n        bytes calldata _composeMsg\n    ) external nonReentrantAndNotPaused {\n        if (unreceivedTokens[_guid][_index] != keccak256(abi.encodePacked(_srcEid, _receiver, _amountLD, _composeMsg)))\n            revert Stargate_UnreceivedTokenNotFound();\n        delete unreceivedTokens[_guid][_index];\n\n        _safeOutflow(_receiver, _amountLD);\n        _postOutflow(_ld2sd(_amountLD));\n        if (_composeMsg.length > 0) {\n            endpoint.sendCompose(_receiver, _guid, 0, _composeMsg);\n        }\n        emit OFTReceived(_guid, _srcEid, _receiver, _amountLD);\n    }\n\n    // ------------------------------- Only Messaging ---------------------------------------\n\n    /// @notice Entrypoint for receiving tokens\n    /// @dev Emits OFTReceived when the OFT token is correctly received\n    /// @dev Emits UnreceivedTokenCached when the OFT token is not received\n    /// @param _origin The Origin struct describing the origin, useful for composing\n    /// @param _guid The global unique ID for this message, useful for composing\n    function receiveTokenBus(\n        Origin calldata _origin,\n        bytes32 _guid,\n        uint8 _seatNumber,\n        address _receiver,\n        uint64 _amountSD\n    ) external nonReentrantAndNotPaused onlyCaller(tokenMessaging) {\n        uint256 amountLD = _sd2ld(_amountSD);\n\n        bool success = _outflow(_receiver, amountLD);\n        if (success) {\n            _postOutflow(_amountSD);\n            emit OFTReceived(_guid, _origin.srcEid, _receiver, amountLD);\n        } else {\n            /**\n             * @dev The busRide mode does not support composeMsg in any form. Thus we hardcode it to \"\"\n             */\n            unreceivedTokens[_guid][_seatNumber] = keccak256(abi.encodePacked(_origin.srcEid, _receiver, amountLD, \"\"));\n            emit UnreceivedTokenCached(_guid, _seatNumber, _origin.srcEid, _receiver, amountLD, \"\");\n        }\n    }\n\n    // taxi mode\n    function receiveTokenTaxi(\n        Origin calldata _origin,\n        bytes32 _guid,\n        address _receiver,\n        uint64 _amountSD,\n        bytes calldata _composeMsg\n    ) external nonReentrantAndNotPaused onlyCaller(tokenMessaging) {\n        uint256 amountLD = _sd2ld(_amountSD);\n        bool hasCompose = _composeMsg.length > 0;\n        bytes memory composeMsg;\n        if (hasCompose) {\n            composeMsg = OFTComposeMsgCodec.encode(_origin.nonce, _origin.srcEid, amountLD, _composeMsg);\n        }\n\n        bool success = _outflow(_receiver, amountLD);\n        if (success) {\n            _postOutflow(_amountSD);\n            // send the composeMsg to the endpoint\n            if (hasCompose) {\n                endpoint.sendCompose(_receiver, _guid, 0, composeMsg);\n            }\n            emit OFTReceived(_guid, _origin.srcEid, _receiver, amountLD);\n        } else {\n            /**\n             * @dev We use the '0' index to represent the seat number. This is because for a type 'taxi' msg,\n             *      there is only ever one corresponding receiveTokenTaxi function per GUID.\n             */\n            unreceivedTokens[_guid][0] = keccak256(abi.encodePacked(_origin.srcEid, _receiver, amountLD, composeMsg));\n            emit UnreceivedTokenCached(_guid, 0, _origin.srcEid, _receiver, amountLD, composeMsg);\n        }\n    }\n\n    function sendCredits(\n        uint32 _dstEid,\n        TargetCredit[] calldata _credits\n    ) external nonReentrantAndNotPaused onlyCaller(creditMessaging) returns (Credit[] memory) {\n        Credit[] memory credits = new Credit[](_credits.length);\n        uint256 index = 0;\n        for (uint256 i = 0; i < _credits.length; i++) {\n            TargetCredit calldata c = _credits[i];\n            uint64 decreased = paths[c.srcEid].tryDecreaseCredit(c.amount, c.minAmount);\n            if (decreased > 0) credits[index++] = Credit(c.srcEid, decreased);\n        }\n        // resize the array to the actual number of credits\n        assembly {\n            mstore(credits, index)\n        }\n        emit CreditsSent(_dstEid, credits);\n        return credits;\n    }\n\n    /// @notice Entrypoint for receiving credits into paths\n    /// @dev Emits CreditsReceived when credits are received\n    /// @param _srcEid The endpoint ID of the source of credits\n    /// @param _credits An array indicating to which paths and how much credits to add\n    function receiveCredits(\n        uint32 _srcEid,\n        Credit[] calldata _credits\n    ) external nonReentrantAndNotPaused onlyCaller(creditMessaging) {\n        for (uint256 i = 0; i < _credits.length; i++) {\n            Credit calldata c = _credits[i];\n            paths[c.srcEid].increaseCredit(c.amount);\n        }\n        emit CreditsReceived(_srcEid, _credits);\n    }\n\n    // ---------------------------------- View Functions ------------------------------------------\n\n    /// @notice Provides a quote for sending OFT to another chain.\n    /// @dev Implements the IOFT interface\n    /// @param _sendParam The parameters for the send operation\n    /// @return limit The information on OFT transfer limits\n    /// @return oftFeeDetails The details of OFT transaction cost or reward\n    /// @return receipt The OFT receipt information, indicating how many tokens would be sent and received\n    function quoteOFT(\n        SendParam calldata _sendParam\n    ) external view returns (OFTLimit memory limit, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory receipt) {\n        // cap the transfer to the paths limit\n        limit = OFTLimit(_sd2ld(1), _sd2ld(paths[_sendParam.dstEid].credit));\n\n        // get the expected amount in the destination chain from FeeLib\n        uint64 amountInSD = _ld2sd(_sendParam.amountLD > limit.maxAmountLD ? limit.maxAmountLD : _sendParam.amountLD);\n        FeeParams memory params = _buildFeeParams(_sendParam.dstEid, amountInSD, _isTaxiMode(_sendParam.oftCmd));\n        uint64 amountOutSD = IStargateFeeLib(feeLib).applyFeeView(params);\n\n        // fill in the FeeDetails if there is a fee or reward\n        if (amountOutSD != amountInSD) {\n            oftFeeDetails = new OFTFeeDetail[](1);\n            if (amountOutSD < amountInSD) {\n                // fee\n                oftFeeDetails[0] = OFTFeeDetail(-1 * _sd2ld(amountInSD - amountOutSD).toInt256(), \"protocol fee\");\n            } else if (amountOutSD > amountInSD) {\n                // reward\n                uint64 reward = amountOutSD - amountInSD;\n                (amountOutSD, reward) = _capReward(amountOutSD, reward);\n                if (amountOutSD == amountInSD) {\n                    // hide the Fee detail if the reward is capped to 0\n                    oftFeeDetails = new OFTFeeDetail[](0);\n                } else {\n                    oftFeeDetails[0] = OFTFeeDetail(_sd2ld(reward).toInt256(), \"reward\");\n                }\n            }\n        }\n\n        receipt = OFTReceipt(_sd2ld(amountInSD), _sd2ld(amountOutSD));\n    }\n\n    /// @notice Provides a quote for the send() operation.\n    /// @dev Implements the IOFT interface.\n    /// @dev Reverts with InvalidAmount if send mode is drive but value is specified.\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    /// @dev MessagingFee: LayerZero message fee\n    ///   - nativeFee: The native fee.\n    ///   - lzTokenFee: The LZ token fee.\n    function quoteSend(\n        SendParam calldata _sendParam,\n        bool _payInLzToken\n    ) external view returns (MessagingFee memory fee) {\n        uint64 amountSD = _ld2sd(_sendParam.amountLD);\n        if (amountSD == 0) revert Stargate_InvalidAmount();\n\n        bool isTaxi = _isTaxiMode(_sendParam.oftCmd);\n        if (isTaxi) {\n            fee = ITokenMessaging(tokenMessaging).quoteTaxi(\n                TaxiParams({\n                    sender: msg.sender,\n                    dstEid: _sendParam.dstEid,\n                    receiver: _sendParam.to,\n                    amountSD: amountSD,\n                    composeMsg: _sendParam.composeMsg,\n                    extraOptions: _sendParam.extraOptions\n                }),\n                _payInLzToken\n            );\n        } else {\n            bool nativeDrop = _sendParam.extraOptions.length > 0;\n            fee = ITokenMessaging(tokenMessaging).quoteRideBus(_sendParam.dstEid, nativeDrop);\n        }\n    }\n\n    /// @notice Returns the current roles configured.\n    /// @return An AddressConfig struct containing the current configuration\n    function getAddressConfig() external view returns (AddressConfig memory) {\n        return\n            AddressConfig({\n                feeLib: feeLib,\n                planner: planner,\n                treasurer: treasurer,\n                tokenMessaging: tokenMessaging,\n                creditMessaging: creditMessaging,\n                lzToken: lzToken\n            });\n    }\n\n    /// @notice Get the OFT version information\n    /// @dev Implements the IOFT interface.\n    /// @dev 0 version means the message encoding is not compatible with the default OFT.\n    /// @return interfaceId The ERC165 interface ID for this contract\n    /// @return version The cross-chain compatible message encoding version.\n    function oftVersion() external pure override returns (bytes4 interfaceId, uint64 version) {\n        return (type(IOFT).interfaceId, 0);\n    }\n\n    /// @notice Indicates whether the OFT contract requires approval of the 'token()' to send.\n    /// @dev Implements the IOFT interface.\n    /// @return Whether approval of the underlying token implementation is required\n    function approvalRequired() external pure override returns (bool) {\n        return true;\n    }\n\n    // ---------------------------------- Internal Functions ------------------------------------------\n\n    /// @notice Ingest value into the contract and charge the Stargate fee.\n    /// @dev This is triggered when value is transferred from an account into Stargate to execute a swap.\n    /// @param _sendParam A SendParam struct containing the swap information\n    function _inflowAndCharge(\n        SendParam calldata _sendParam\n    ) internal returns (bool isTaxi, uint64 amountInSD, uint64 amountOutSD) {\n        isTaxi = _isTaxiMode(_sendParam.oftCmd);\n        amountInSD = _inflow(msg.sender, _sendParam.amountLD);\n\n        FeeParams memory feeParams = _buildFeeParams(_sendParam.dstEid, amountInSD, isTaxi);\n\n        amountOutSD = _chargeFee(feeParams, _ld2sd(_sendParam.minAmountLD));\n\n        paths[_sendParam.dstEid].decreaseCredit(amountOutSD); // remove the credit from the path\n        _postInflow(amountOutSD); // post inflow actions with the amount deducted by the fee\n    }\n\n    /// @notice Consult the FeeLib the fee/reward for sending this token\n    /// @dev Reverts with SlippageTooHigh when the slippage amount sent would be below the desired minimum or zero.\n    /// @return amountOutSD The actual amount that would be sent after applying fees/rewards\n    function _chargeFee(FeeParams memory _feeParams, uint64 _minAmountOutSD) internal returns (uint64 amountOutSD) {\n        // get the output amount from the fee library\n        amountOutSD = IStargateFeeLib(feeLib).applyFee(_feeParams);\n\n        uint64 amountInSD = _feeParams.amountInSD;\n        if (amountOutSD < amountInSD) {\n            // fee\n            treasuryFee += amountInSD - amountOutSD;\n        } else if (amountOutSD > amountInSD) {\n            // reward\n            uint64 reward = amountOutSD - amountInSD;\n            (amountOutSD, reward) = _capReward(amountOutSD, reward);\n            if (reward > 0) treasuryFee -= reward;\n        }\n\n        if (amountOutSD < _minAmountOutSD || amountOutSD == 0) revert Stargate_SlippageTooHigh(); // 0 not allowed\n    }\n\n    function _taxi(\n        SendParam calldata _sendParam,\n        MessagingFee memory _messagingFee,\n        uint64 _amountSD,\n        address _refundAddress\n    ) internal returns (MessagingReceipt memory receipt) {\n        if (_messagingFee.lzTokenFee > 0) _payLzToken(_messagingFee.lzTokenFee); // handle lz token fee\n\n        receipt = ITokenMessaging(tokenMessaging).taxi{ value: _messagingFee.nativeFee }(\n            TaxiParams({\n                sender: msg.sender,\n                dstEid: _sendParam.dstEid,\n                receiver: _sendParam.to,\n                amountSD: _amountSD,\n                composeMsg: _sendParam.composeMsg,\n                extraOptions: _sendParam.extraOptions\n            }),\n            _messagingFee,\n            _refundAddress\n        );\n    }\n\n    function _rideBus(\n        SendParam calldata _sendParam,\n        MessagingFee memory _messagingFee,\n        uint64 _amountSD,\n        address _refundAddress\n    ) internal virtual returns (MessagingReceipt memory receipt, Ticket memory ticket) {\n        if (_messagingFee.lzTokenFee > 0) revert Stargate_LzTokenUnavailable();\n\n        (receipt, ticket) = ITokenMessaging(tokenMessaging).rideBus(\n            RideBusParams({\n                sender: msg.sender,\n                dstEid: _sendParam.dstEid,\n                receiver: _sendParam.to,\n                amountSD: _amountSD,\n                nativeDrop: _sendParam.extraOptions.length > 0\n            })\n        );\n\n        uint256 busFare = receipt.fee.nativeFee;\n        uint256 providedFare = _messagingFee.nativeFee;\n\n        // assert sufficient nativeFee was provided to cover the fare\n        if (busFare == providedFare) {\n            // return; Do nothing in this case\n        } else if (providedFare > busFare) {\n            uint256 refund;\n            unchecked {\n                refund = providedFare - busFare;\n            }\n            Transfer.transferNative(_refundAddress, refund, false); // no gas limit to refund\n        } else {\n            revert Stargate_InsufficientFare();\n        }\n    }\n\n    /// @notice Pay the LZ fee in LZ tokens.\n    /// @dev Reverts with LzTokenUnavailable if the LZ token OFT has not been set.\n    /// @param _lzTokenFee The fee to pay in LZ tokens\n    function _payLzToken(uint256 _lzTokenFee) internal {\n        address lzTkn = lzToken;\n        if (lzTkn == address(0)) revert Stargate_LzTokenUnavailable();\n        Transfer.safeTransferTokenFrom(lzTkn, msg.sender, address(endpoint), _lzTokenFee);\n    }\n\n    /// @notice Translate an amount in SD to LD\n    /// @dev Since SD <= LD by definition, convertRate >= 1, so there is no rounding errors in this function.\n    /// @param _amountSD The amount in SD\n    /// @return amountLD The same value expressed in LD\n    function _sd2ld(uint64 _amountSD) internal view returns (uint256 amountLD) {\n        unchecked {\n            amountLD = _amountSD * convertRate;\n        }\n    }\n\n    /// @notice Translate an value in LD to SD\n    /// @dev Since SD <= LD by definition, convertRate >= 1, so there might be rounding during the cast.\n    /// @param _amountLD The value in LD\n    /// @return amountSD The same value expressed in SD\n    function _ld2sd(uint256 _amountLD) internal view returns (uint64 amountSD) {\n        unchecked {\n            amountSD = SafeCast.toUint64(_amountLD / convertRate);\n        }\n    }\n\n    /// @dev if _cmd is empty, Taxi mode. Otherwise, Bus mode\n    function _isTaxiMode(bytes calldata _oftCmd) internal pure returns (bool) {\n        return _oftCmd.length == 0;\n    }\n\n    // ---------------------------------- Virtual Functions ------------------------------------------\n\n    /// @notice Limits the reward awarded when withdrawing value.\n    /// @param _amountOutSD The amount of expected on the destination chain in SD\n    /// @param _reward The initial calculated reward by FeeLib\n    /// @return newAmountOutSD The actual amount to be delivered on the destination chain\n    /// @return newReward The actual reward after applying any caps\n    function _capReward(\n        uint64 _amountOutSD,\n        uint64 _reward\n    ) internal view virtual returns (uint64 newAmountOutSD, uint64 newReward);\n\n    /// @notice Hook called when there is ingress of value into the contract.\n    /// @param _from The account from which to obtain the value\n    /// @param _amountLD The amount of tokens to get from the account in LD\n    /// @return amountSD The actual amount of tokens in SD that got into the Stargate\n    function _inflow(address _from, uint256 _amountLD) internal virtual returns (uint64 amountSD);\n\n    /// @notice Hook called when there is egress of value out of the contract.\n    /// @return success Whether the outflow was successful\n    function _outflow(address _to, uint256 _amountLD) internal virtual returns (bool success);\n\n    /// @notice Hook called when there is egress of value out of the contract.\n    /// @dev Reverts with OutflowFailed when the outflow hook fails\n    function _safeOutflow(address _to, uint256 _amountLD) internal virtual {\n        bool success = _outflow(_to, _amountLD);\n        if (!success) revert Stargate_OutflowFailed();\n    }\n\n    /// @notice Ensure that the value passed through the message equals the native fee\n    /// @dev the native fee should be the same as msg value by default\n    /// @dev Reverts with InvalidAmount if the native fee does not match the value passed.\n    /// @param _fee The MessagingFee object containing the expected fee\n    /// @return The messaging fee object\n    function _assertMessagingFee(\n        MessagingFee memory _fee,\n        uint256 /*_amountInLD*/\n    ) internal view virtual returns (MessagingFee memory) {\n        if (_fee.nativeFee != msg.value) revert Stargate_InvalidAmount();\n        return _fee;\n    }\n\n    /// @notice Ensure the msg.value is as expected.\n    /// @dev Override this contract to provide a specific validation.\n    /// @dev This implementation will revert if value is passed, because we do not expect value except for\n    /// @dev the native token when adding to the treasury.\n    /// @dev Reverts with InvalidAmount if msg.value > 0\n    function _assertMsgValue(uint256 /*_amountLD*/) internal view virtual {\n        if (msg.value > 0) revert Stargate_InvalidAmount();\n    }\n\n    /// @dev Build the FeeParams object for the FeeLib\n    /// @param _dstEid The destination endpoint ID\n    /// @param _amountInSD The amount to send in SD\n    /// @param _isTaxi Whether this send is riding the bus or taxing\n    function _buildFeeParams(\n        uint32 _dstEid,\n        uint64 _amountInSD,\n        bool _isTaxi\n    ) internal view virtual returns (FeeParams memory);\n\n    /// @notice Hook called after the inflow of value into the contract by sendToken().\n    /// Function meant to be overridden\n    // solhint-disable-next-line no-empty-blocks\n    function _postInflow(uint64 _amountSD) internal virtual {}\n\n    /// @notice Hook called after the outflow of value out of the contract by receiveToken().\n    /// Function meant to be overridden\n    // solhint-disable-next-line no-empty-blocks\n    function _postOutflow(uint64 _amountSD) internal virtual {}\n}\n"
      },
      "src/StargatePool.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.22;\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nimport { StargateType, MessagingReceipt, MessagingFee, SendParam, OFTReceipt } from \"./interfaces/IStargate.sol\";\nimport { IStargatePool } from \"./interfaces/IStargatePool.sol\";\nimport { ITokenMessaging, TaxiParams } from \"./interfaces/ITokenMessaging.sol\";\nimport { Transfer } from \"./libs/Transfer.sol\";\nimport { StargateBase, FeeParams } from \"./StargateBase.sol\";\nimport { LPToken } from \"./utils/LPToken.sol\";\n\n/// @title A Stargate contract representing a liquidity pool. Users can deposit tokens into the pool and receive\n/// @title LP tokens in exchange, which can be later be redeemed to recover their deposit and a reward which is\n/// @title a fraction of the fee accrued by the liquidity pool during the staking time.\ncontract StargatePool is StargateBase, IStargatePool {\n    LPToken internal immutable lp;\n\n    uint64 internal tvlSD;\n    uint64 internal poolBalanceSD;\n    uint64 internal deficitOffsetSD;\n\n    event Deposited(address indexed payer, address indexed receiver, uint256 amountLD);\n    event Redeemed(address indexed payer, address indexed receiver, uint256 amountLD);\n\n    error Stargate_OnlyTaxi();\n\n    /// @notice Create a Stargate pool to provide liquidity. This also creates the LP token contract.\n    /// @param _lpTokenName The name for the LP token\n    /// @param _lpTokenSymbol The symbol for the LP token\n    /// @param _token The token for the pool or oft. If the token is address(0), it is the native coin\n    /// @param _tokenDecimals The number of decimals for this tokens implementation on this chain\n    /// @param _sharedDecimals The number of decimals shared between all implementations of the OFT\n    /// @param _endpoint The LZ endpoint contract\n    /// @param _owner The owner of this contract\n    constructor(\n        string memory _lpTokenName,\n        string memory _lpTokenSymbol,\n        address _token,\n        uint8 _tokenDecimals,\n        uint8 _sharedDecimals,\n        address _endpoint,\n        address _owner\n    ) StargateBase(_token, _tokenDecimals, _sharedDecimals, _endpoint, _owner) {\n        lp = new LPToken(_lpTokenName, _lpTokenSymbol, _tokenDecimals);\n    }\n\n    // -------- LP operations --------\n\n    /// @notice Deposit token into the pool\n    /// @dev Emits Deposited when the token is deposited\n    /// @param _receiver The account to mint the LP tokens to\n    /// @param _amountLD The amount of tokens to deposit in LD\n    /// @return amountLD The actual amount of tokens deposited in LD\n    function deposit(\n        address _receiver,\n        uint256 _amountLD\n    ) external payable nonReentrantAndNotPaused returns (uint256 amountLD) {\n        // charge the sender\n        _assertMsgValue(_amountLD);\n        uint64 amountSD = _inflow(msg.sender, _amountLD);\n        _postInflow(amountSD); // increase the local credit and pool balance\n\n        // mint LP token to the receiver\n        amountLD = _sd2ld(amountSD);\n        lp.mint(_receiver, amountLD);\n        tvlSD += amountSD;\n        emit Deposited(msg.sender, _receiver, amountLD);\n    }\n\n    /// @notice Redeem the LP token of the sender and return the underlying token to receiver\n    /// @dev Emits Redeemed when the LP tokens are redeemed successfully.\n    /// @dev Reverts if the sender does not hold enough LP tokens or if the pool does not have enough credit.\n    /// @param _amountLD The amount of LP token to redeem in LD\n    /// @param _receiver The account to which to return the underlying tokens\n    /// @return amountLD The amount of LP token burned and the amount of underlying token sent to the receiver\n    function redeem(uint256 _amountLD, address _receiver) external nonReentrantAndNotPaused returns (uint256 amountLD) {\n        uint64 amountSD = _ld2sd(_amountLD);\n        paths[localEid].decreaseCredit(amountSD);\n\n        // de-dust LP token\n        amountLD = _sd2ld(amountSD);\n        // burn LP token. Will revert if the sender doesn't have enough LP token\n        lp.burnFrom(msg.sender, amountLD);\n        tvlSD -= amountSD;\n\n        // send the underlying token from the pool to the receiver\n        _safeOutflow(_receiver, amountLD);\n        _postOutflow(amountSD); // decrease the pool balance\n\n        emit Redeemed(msg.sender, _receiver, amountLD);\n    }\n\n    /// @notice Redeem LP tokens and use the withdrawn tokens to execute a send\n    /// @dev Emits Redeemed when the LP tokens are redeemed successfully.\n    /// @dev Emits OFTSent when the LP tokens are redeemed successfully.\n    /// @param _sendParam The RedeemSendParam object describing the redeem and send\n    /// @param _fee The MessagingFee describing the fee to pay for the send\n    /// @param _refundAddress The address to refund any LZ fees paid in excess\n    /// @return msgReceipt The messaging receipt proving the send\n    /// @return oftReceipt The OFT receipt proving the send\n    function redeemSend(\n        SendParam calldata _sendParam,\n        MessagingFee calldata _fee,\n        address _refundAddress\n    )\n        external\n        payable\n        nonReentrantAndNotPaused\n        returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt)\n    {\n        if (!_isTaxiMode(_sendParam.oftCmd)) revert Stargate_OnlyTaxi();\n\n        // remove the dust\n        uint64 amountInSD = _ld2sd(_sendParam.amountLD);\n        uint256 amountInLD = _sd2ld(amountInSD);\n\n        // burn LP token of 'msg.sender'. it will revert if the sender doesn't have enough LP token\n        lp.burnFrom(msg.sender, amountInLD);\n        emit Redeemed(msg.sender, address(0), amountInLD);\n\n        // charge fees and handle credit\n        FeeParams memory feeParams = _buildFeeParams(_sendParam.dstEid, amountInSD, true);\n        uint64 amountOutSD = _chargeFee(feeParams, _ld2sd(_sendParam.minAmountLD));\n\n        // need to update the TVL after charging the fee, otherwise the deficit will be wrong\n        tvlSD -= amountInSD;\n\n        // handle credit and pool balance\n        // due to the both of them are already increased when deposit, so if\n        // 1) the amountOutSD is less than amountInSD, the fee should be removed from both of them\n        // 2) the amountOutSD is more than amountInSD, the reward should be added to both of them\n        paths[_sendParam.dstEid].decreaseCredit(amountOutSD);\n        if (amountInSD > amountOutSD) {\n            // fee\n            uint64 fee = amountInSD - amountOutSD;\n            paths[localEid].decreaseCredit(fee);\n            poolBalanceSD -= fee;\n        } else if (amountInSD < amountOutSD) {\n            // reward\n            uint64 reward = amountOutSD - amountInSD;\n            paths[localEid].increaseCredit(reward);\n            poolBalanceSD += reward;\n        }\n\n        // send the token to the receiver\n        MessagingFee memory messagingFee = _assertMessagingFee(_fee, 0);\n        msgReceipt = _taxi(_sendParam, messagingFee, amountOutSD, _refundAddress);\n        oftReceipt = OFTReceipt(amountInLD, _sd2ld(amountOutSD));\n        emit OFTSent(msgReceipt.guid, _sendParam.dstEid, msg.sender, amountInLD, oftReceipt.amountReceivedLD);\n    }\n\n    /// @notice Get how many LP tokens can be redeemed by a given account.\n    /// @dev Use 0x0 to get the total maximum redeemable (since its capped to the local credit)\n    /// @param _owner The account to check for\n    /// @return amountLD The max amount of LP tokens redeemable by the account\n    function redeemable(address _owner) external view returns (uint256 amountLD) {\n        uint256 cap = _sd2ld(paths[localEid].credit);\n        if (_owner == address(0)) {\n            amountLD = cap;\n        } else {\n            uint256 userLp = lp.balanceOf(_owner);\n            amountLD = cap > userLp ? userLp : cap;\n        }\n    }\n\n    /// @notice Get a quote on the fee associated with a RedeemSend operation\n    /// @param _sendParam The RedeemSendParam object describing the RedeemSend\n    /// @param _payInLzToken Whether to pay the LZ fee in LZ token\n    /// @return fee The MessagingFee object that describes the Fee that would be associated with this RedeemSend\n    function quoteRedeemSend(\n        SendParam calldata _sendParam,\n        bool _payInLzToken\n    ) external view returns (MessagingFee memory fee) {\n        if (!_isTaxiMode(_sendParam.oftCmd)) revert Stargate_OnlyTaxi();\n        uint64 amountInSD = _ld2sd(_sendParam.amountLD);\n        fee = ITokenMessaging(tokenMessaging).quoteTaxi(\n            TaxiParams({\n                sender: msg.sender,\n                dstEid: _sendParam.dstEid,\n                receiver: _sendParam.to,\n                amountSD: amountInSD,\n                composeMsg: _sendParam.composeMsg,\n                extraOptions: _sendParam.extraOptions\n            }),\n            _payInLzToken\n        );\n    }\n\n    /// @notice Get the total value locked in this pool\n    /// @dev The TVL of the pool is the total supply of the LP token since they are minted 1:1.\n    /// @return The total value locked in LD\n    function tvl() external view override returns (uint256) {\n        return _sd2ld(tvlSD);\n    }\n\n    /// @notice Get the current pool balance\n    /// @dev The pool balance is the total amount of tokens in the pool, it reflects liquidity.\n    /// @return The pool balance in LD\n    function poolBalance() external view override returns (uint256) {\n        return _sd2ld(poolBalanceSD);\n    }\n\n    /// @notice Get the current deficit offset\n    /// @dev The deficit offset allows manipulation of the ideal pool liquidity beyond surplus 0.\n    /// @return The deficit offset in LD\n    function deficitOffset() external view returns (uint256) {\n        return _sd2ld(deficitOffsetSD);\n    }\n\n    /// @notice Returns the type of Stargate contract.\n    /// @dev Fulfills the IStargate interface.\n    /// @return The type of Stargate contract\n    function stargateType() external pure override returns (StargateType) {\n        return StargateType.Pool;\n    }\n\n    /// @notice Returns the LP token contract used to represent pool ownership.\n    /// @return The address of the LP token contract.\n    function lpToken() external view override returns (address) {\n        return address(lp);\n    }\n\n    /// @notice Limits the reward awarded when withdrawing value.\n    /// @dev Concretes the StargateBase contract.\n    /// @dev Liquidity pools cap the reward to the total fees accrued in the treasury.\n    /// @param _amountOutSD The amount of tokens expected on the destination chain in SD\n    /// @param _reward The initial calculated reward by FeeLib\n    /// @return newAmountOutSD The actual amount to be received on the destination chain\n    /// @return newReward The actual reward after applying any caps\n    function _capReward(uint64 _amountOutSD, uint64 _reward) internal view override returns (uint64, uint64) {\n        uint64 rewardCap = treasuryFee;\n        if (_reward > rewardCap) {\n            // exceeds cap, recalculate with new reward\n            unchecked {\n                return (_amountOutSD - _reward + rewardCap, rewardCap);\n            }\n        } else {\n            // lower than cap, return the original values\n            return (_amountOutSD, _reward);\n        }\n    }\n\n    /// @notice Increase the local credit and pool balance\n    function _postInflow(uint64 _amountSD) internal override {\n        paths[localEid].increaseCredit(_amountSD);\n        poolBalanceSD += _amountSD;\n    }\n\n    /// @notice Decrease the pool balance\n    function _postOutflow(uint64 _amountSD) internal override {\n        poolBalanceSD -= _amountSD;\n    }\n\n    /// @notice Charge an account an amount of pooled tokens.\n    /// @dev Reverts if the charge can not be completed.\n    /// @param _from The account to charge\n    /// @param _amountLD How many tokens to charge in LD\n    /// @return amountSD The amount of tokens charged in SD\n    function _inflow(address _from, uint256 _amountLD) internal virtual override returns (uint64 amountSD) {\n        amountSD = _ld2sd(_amountLD);\n        Transfer.safeTransferTokenFrom(token, _from, address(this), _sd2ld(amountSD)); // remove the dust and transfer\n    }\n\n    /// @notice Transfer a token from the pool to an account.\n    /// @param _to The destination account\n    /// @param _amountLD How many tokens to transfer in LD\n    /// @return success Whether the transfer succeeded or not\n    function _outflow(address _to, uint256 _amountLD) internal virtual override returns (bool success) {\n        success = Transfer.transferToken(token, _to, _amountLD);\n    }\n\n    function _buildFeeParams(\n        uint32 _dstEid,\n        uint64 _amountInSD,\n        bool _isTaxi\n    ) internal view override returns (FeeParams memory) {\n        uint64 t = tvlSD + deficitOffsetSD;\n        uint64 deficitSD = t > poolBalanceSD ? t - poolBalanceSD : 0;\n        return FeeParams(msg.sender, _dstEid, _amountInSD, deficitSD, paths[_dstEid].isOFTPath(), _isTaxi);\n    }\n\n    // ---------------------------------- Only Treasurer ------------------------------------------\n\n    function recoverToken(\n        address _token,\n        address _to,\n        uint256 _amount\n    ) public virtual override onlyCaller(treasurer) returns (uint256) {\n        // only allow to recover the excess of poolBalanceSD + treasuryFee if the token is the pool token\n        if (_token == token) {\n            uint256 cap = _thisBalance() - _sd2ld(poolBalanceSD + treasuryFee);\n            _amount = _amount > cap ? cap : _amount;\n        }\n        return super.recoverToken(_token, _to, _amount);\n    }\n\n    function _thisBalance() internal view virtual returns (uint256) {\n        return IERC20(token).balanceOf(address(this));\n    }\n\n    // ---------------------------------- Only Planner ------------------------------------------\n\n    function setDeficitOffset(uint256 _deficitOffsetLD) external onlyCaller(planner) {\n        deficitOffsetSD = _ld2sd(_deficitOffsetLD);\n    }\n}\n"
      },
      "src/interfaces/ICreditMessaging.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport { MessagingFee } from \"@layerzerolabs/lz-evm-oapp-v2/contracts/oft/interfaces/IOFT.sol\";\n\n/// @notice Stores the information related to a batch of credit transfers.\nstruct TargetCreditBatch {\n    uint16 assetId;\n    TargetCredit[] credits;\n}\n\n/// @notice Stores the information related to a single credit transfer.\nstruct TargetCredit {\n    uint32 srcEid;\n    uint64 amount; // the amount of credits to intended to send\n    uint64 minAmount; // the minimum amount of credits to keep on local chain after sending\n}\n\n/// @title Credit Messaging API\n/// @dev This interface defines the API for quoting and sending credits to other chains.\ninterface ICreditMessaging {\n    /// @notice Sends credits to the destination endpoint.\n    /// @param _dstEid The destination LayerZero endpoint ID.\n    /// @param _creditBatches The credit batch payloads to send to the destination LayerZero endpoint ID.\n    function sendCredits(uint32 _dstEid, TargetCreditBatch[] calldata _creditBatches) external payable;\n\n    /// @notice Quotes the fee for sending credits to the destination endpoint.\n    /// @param _dstEid The destination LayerZero endpoint ID.\n    /// @param _creditBatches The credit batch payloads to send to the destination LayerZero endpoint ID.\n    /// @return fee The fee for sending the credits to the destination endpoint.\n    function quoteSendCredits(\n        uint32 _dstEid,\n        TargetCreditBatch[] calldata _creditBatches\n    ) external view returns (MessagingFee memory fee);\n}\n"
      },
      "src/interfaces/ICreditMessagingHandler.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport { TargetCredit } from \"./ICreditMessaging.sol\";\n\nstruct Credit {\n    uint32 srcEid;\n    uint64 amount;\n}\n\n/// @dev This is an internal interface, defining functions to handle messages/calls from the credit messaging contract.\ninterface ICreditMessagingHandler {\n    function sendCredits(uint32 _dstEid, TargetCredit[] calldata _credits) external returns (Credit[] memory);\n\n    function receiveCredits(uint32 _srcEid, Credit[] calldata _credits) external;\n}\n"
      },
      "src/interfaces/IStargate.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\n// Solidity does not support splitting import across multiple lines\n// solhint-disable-next-line max-line-length\nimport { IOFT, SendParam, MessagingFee, MessagingReceipt, OFTReceipt } from \"@layerzerolabs/lz-evm-oapp-v2/contracts/oft/interfaces/IOFT.sol\";\n\n/// @notice Stargate implementation type.\nenum StargateType {\n    Pool,\n    OFT\n}\n\n/// @notice Ticket data for bus ride.\nstruct Ticket {\n    uint72 ticketId;\n    bytes passengerBytes;\n}\n\n/// @title Interface for Stargate.\n/// @notice Defines an API for sending tokens to destination chains.\ninterface IStargate is IOFT {\n    /// @dev This function is same as `send` in OFT interface but returns the ticket data if in the bus ride mode,\n    /// which allows the caller to ride and drive the bus in the same transaction.\n    function sendToken(\n        SendParam calldata _sendParam,\n        MessagingFee calldata _fee,\n        address _refundAddress\n    ) external payable returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt, Ticket memory ticket);\n\n    /// @notice Returns the Stargate implementation type.\n    function stargateType() external pure returns (StargateType);\n}\n"
      },
      "src/interfaces/IStargateFeeLib.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\n/// @notice Parameters used to assess fees to send tokens to a destination endpoint.\nstruct FeeParams {\n    address sender;\n    uint32 dstEid;\n    uint64 amountInSD;\n    uint64 deficitSD;\n    bool toOFT;\n    bool isTaxi;\n}\n\n/// @title Interface for assessing fees to send tokens to a destination endpoint.\ninterface IStargateFeeLib {\n    /// @notice Apply a fee for a given request, allowing for state modification.\n    /// @dev This is included for future proofing potential implementations\n    /// @dev where state is modified in the feeLib based on a FeeParams\n\n    function applyFee(FeeParams calldata _params) external returns (uint64 amountOutSD);\n    /// @notice Apply a fee for a given request, without modifying state.\n    function applyFeeView(FeeParams calldata _params) external view returns (uint64 amountOutSD);\n}\n"
      },
      "src/interfaces/IStargatePool.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport { IStargate, SendParam, MessagingReceipt, MessagingFee, OFTReceipt } from \"./IStargate.sol\";\n\n/// @title An interface for Stargate Pools\n/// @notice Stargate Pools are a type of IStargate that allows users to pool token liquidity.\ninterface IStargatePool is IStargate {\n    /// @notice Deposit token into the pool\n    /// @param _receiver The account to mint the LP tokens to\n    /// @param _amountLD The amount of tokens to deposit in LD\n    /// @return amountLD The actual amount of tokens deposited in LD\n    function deposit(address _receiver, uint256 _amountLD) external payable returns (uint256 amountLD);\n\n    /// @notice Redeem an amount of LP tokens from the senders account, claiming rewards.\n    /// @param _amountLD The amount of LP tokens to redeem\n    /// @param _receiver The account to transfer the\n    function redeem(uint256 _amountLD, address _receiver) external returns (uint256 amountLD);\n\n    /// @notice Get how many LP tokens are redeemable for a given account\n    /// @param _owner The address of the account to check\n    /// @return amountLD The amount of LP tokens redeemable, in LD\n    function redeemable(address _owner) external view returns (uint256 amountLD);\n\n    /// @notice Redeem LP tokens and send the withdrawn tokens to a destination endpoint.\n    /// @param _sendParam The SendParam payload describing the redeem and send\n    /// @param _fee The MessagingFee to perform redeemSend\n    /// @param _refundAddress The address to refund excess LayerZero messaging fees.\n    /// @return receipt The MessagingReceipt describing the result of redeemSend\n    /// @return oftReceipt The OFTReceipt describing the result of redeemSend\n    function redeemSend(\n        SendParam calldata _sendParam,\n        MessagingFee calldata _fee,\n        address _refundAddress\n    ) external payable returns (MessagingReceipt memory receipt, OFTReceipt memory oftReceipt);\n\n    /// @notice Quote the messaging fee for a redeemSend operation\n    /// @param _sendParam The SendParam payload describing the redeem and send\n    /// @param _payInLzToken Whether to pay the fee in LZ token\n    /// @return messagingFee The MessagingFee for the redeemSend operation\n    function quoteRedeemSend(\n        SendParam calldata _sendParam,\n        bool _payInLzToken\n    ) external view returns (MessagingFee memory messagingFee);\n\n    /// @notice Get the Total Value Locked in the pool.\n    /// @return The total value locked\n    function tvl() external view returns (uint256);\n\n    /// @notice Get the available balance of the pool\n    function poolBalance() external view returns (uint256);\n\n    /// @notice Get the address of the LP token\n    /// @return The address of the LP token contract.\n    function lpToken() external view returns (address);\n}\n"
      },
      "src/interfaces/ITokenMessaging.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport { MessagingReceipt, MessagingFee, Ticket } from \"./IStargate.sol\";\n\n/// @notice Payload for sending a taxi message.\n/// @dev A taxi message is sent immediately and is not stored on the bus.\nstruct TaxiParams {\n    address sender;\n    uint32 dstEid;\n    bytes32 receiver;\n    uint64 amountSD;\n    bytes composeMsg;\n    bytes extraOptions;\n}\n\n/// @notice Payload for riding the bus.\n/// @dev Riding the bus is a two-step process:\n/// @dev - The message is sent to the bus,\n/// @dev - The bus is driven to the destination.\nstruct RideBusParams {\n    address sender;\n    uint32 dstEid;\n    bytes32 receiver;\n    uint64 amountSD;\n    bool nativeDrop;\n}\n\n/// @title Token Messaging API.\n/// @notice This interface defines the API for sending a taxi message, riding the bus, and driving the bus, along with\n/// corresponding quote functions.\ninterface ITokenMessaging {\n    /// @notice Sends a taxi message\n    /// @param _params The taxi message payload\n    /// @param _messagingFee The messaging fee for sending a taxi message\n    /// @param _refundAddress The address to refund excess LayerZero MessagingFees\n    /// @return receipt The MessagingReceipt resulting from sending the taxi\n    function taxi(\n        TaxiParams calldata _params,\n        MessagingFee calldata _messagingFee,\n        address _refundAddress\n    ) external payable returns (MessagingReceipt memory receipt);\n\n    /// @notice Quotes the messaging fee for sending a taxi message\n    /// @param _params The taxi message payload\n    /// @param _payInLzToken Whether to pay the fee in LZ token\n    /// @return fee The MessagingFee for sending the taxi message\n    function quoteTaxi(TaxiParams calldata _params, bool _payInLzToken) external view returns (MessagingFee memory fee);\n\n    /// @notice Sends a message to ride the bus, queuing the passenger in preparation for the drive.\n    /// @notice The planner will later driveBus to the destination endpoint.\n    /// @param _params The rideBus message payload\n    /// @return receipt The MessagingReceipt resulting from sending the rideBus message\n    /// @return ticket The Ticket for riding the bus\n    function rideBus(\n        RideBusParams calldata _params\n    ) external returns (MessagingReceipt memory receipt, Ticket memory ticket);\n\n    /// @notice Quotes the messaging fee for riding the bus\n    /// @param _dstEid The destination LayerZero endpoint ID.\n    /// @param _nativeDrop Whether to pay for a native drop on the destination.\n    /// @return fee The MessagingFee for riding the bus\n    function quoteRideBus(uint32 _dstEid, bool _nativeDrop) external view returns (MessagingFee memory fee);\n\n    /// @notice Drives the bus to the destination.\n    /// @param _dstEid The destination LayerZero endpoint ID.\n    /// @param _passengers The passengers to drive to the destination.\n    /// @return receipt The MessagingReceipt resulting from driving the bus\n    function driveBus(\n        uint32 _dstEid,\n        bytes calldata _passengers\n    ) external payable returns (MessagingReceipt memory receipt);\n\n    /// @notice Quotes the messaging fee for driving the bus to the destination.\n    /// @param _dstEid The destination LayerZero endpoint ID.\n    /// @param _passengers The passengers to drive to the destination.\n    /// @return fee The MessagingFee for driving the bus\n    function quoteDriveBus(uint32 _dstEid, bytes calldata _passengers) external view returns (MessagingFee memory fee);\n}\n"
      },
      "src/interfaces/ITokenMessagingHandler.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport { Origin } from \"@layerzerolabs/lz-evm-oapp-v2/contracts/oapp/OApp.sol\";\n\n/// @dev This is an internal interface, defining the function to handle token message from the token messaging contract.\ninterface ITokenMessagingHandler {\n    function receiveTokenBus(\n        Origin calldata _origin,\n        bytes32 _guid,\n        uint8 _seatNumber,\n        address _receiver,\n        uint64 _amountSD\n    ) external;\n\n    function receiveTokenTaxi(\n        Origin calldata _origin,\n        bytes32 _guid,\n        address _receiver,\n        uint64 _amountSD,\n        bytes calldata _composeMsg\n    ) external;\n}\n"
      },
      "src/libs/Path.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.22;\n\n/// @dev The Path struct contains the bus base fare multiplier bps and the credit in the same slot for gas saving.\nstruct Path {\n    uint64 credit; // available credit for the path, in SD\n}\n\nusing PathLib for Path global;\n\n/**\n * @title A library to operate on Paths.\n * @dev A Path is a route through which value can be sent. It entails the local chain and a destination chain, and has\n *      a given amount of credit associated with it. Every time the value is sent from A to B, the credit on A is\n *      decreased and credit on B is increased. If credit hits 0 then the path can no longer be used.\n */\nlibrary PathLib {\n    uint64 internal constant UNLIMITED_CREDIT = type(uint64).max;\n\n    // solhint-disable-next-line event-name-camelcase\n    event Path_CreditBurned(uint64 amountSD);\n\n    error Path_InsufficientCredit();\n    error Path_AlreadyHasCredit();\n    error Path_UnlimitedCredit();\n\n    /// @notice Increase credit for a given Path.\n    /// @dev Reverts with Path_UnlimitedCredit if the increase would hit the maximum amount of credit (reserved value)\n    /// @param _path The Path for which to increase credit\n    /// @param _amountSD The amount by which to increase credit\n    function increaseCredit(Path storage _path, uint64 _amountSD) internal {\n        uint64 credit = _path.credit;\n        if (credit == UNLIMITED_CREDIT) return;\n        credit += _amountSD;\n        if (credit == UNLIMITED_CREDIT) revert Path_UnlimitedCredit();\n        _path.credit = credit;\n    }\n\n    /// @notice Decrease credit for a given Path.\n    /// @dev Reverts with InsufficientCredit if there is not enough credit\n    /// @param _path The Path for which to decrease credit\n    /// @param _amountSD The amount by which to decrease credit\n    function decreaseCredit(Path storage _path, uint64 _amountSD) internal {\n        uint64 currentCredit = _path.credit;\n        if (currentCredit == UNLIMITED_CREDIT) return;\n        if (currentCredit < _amountSD) revert Path_InsufficientCredit();\n        unchecked {\n            _path.credit = currentCredit - _amountSD;\n        }\n    }\n\n    /// @notice Decrease credit for a given path, even if only a partial amount is possible.\n    /// @param _path The Path for which to decrease credit\n    /// @param _amountSD The amount by which try to decrease credit\n    /// @param _minKept The minimum amount of credit to keep after the decrease\n    /// @return decreased The actual amount of credit decreased\n    function tryDecreaseCredit(\n        Path storage _path,\n        uint64 _amountSD,\n        uint64 _minKept\n    ) internal returns (uint64 decreased) {\n        uint64 currentCredit = _path.credit;\n        // not allowed to try to decrease unlimited credit\n        if (currentCredit == UNLIMITED_CREDIT) revert Path_UnlimitedCredit();\n        if (_minKept < currentCredit) {\n            unchecked {\n                uint64 maxDecreased = currentCredit - _minKept;\n                decreased = _amountSD > maxDecreased ? maxDecreased : _amountSD;\n                _path.credit = currentCredit - decreased;\n            }\n        }\n    }\n\n    /// @notice Set a given path as OFT or reset an OFT path to 0 credit.\n    /// @dev A Path for which the asset is using an OFT on destination gets unlimited credit because value transfers\n    /// @dev do not spend value.\n    /// @dev Such a path is expected to not have credit before.\n    /// @dev Reverts with AlreadyHasCredit if the Path already had credit assigned to it\n    /// @param _path The Path to set\n    /// @param _oft Whether to set it as OFT or reset it from OFT\n    function setOFTPath(Path storage _path, bool _oft) internal {\n        uint64 currentCredit = _path.credit;\n        if (_oft) {\n            // only allow un-limiting from 0\n            if (currentCredit != 0) revert Path_AlreadyHasCredit();\n            _path.credit = UNLIMITED_CREDIT;\n        } else {\n            // only allow resetting from unlimited\n            if (currentCredit != UNLIMITED_CREDIT) revert Path_AlreadyHasCredit();\n            _path.credit = 0;\n        }\n    }\n\n    /// @notice Check whether a given Path is set as OFT.\n    /// @param _path The path to examine\n    /// @return whether the Path is set as OFT\n    function isOFTPath(Path storage _path) internal view returns (bool) {\n        return _path.credit == UNLIMITED_CREDIT;\n    }\n\n    /// @notice Burn credit for a given Path during bridged token migration.\n    function burnCredit(Path storage _path, uint64 _amountSD) internal {\n        decreaseCredit(_path, _amountSD);\n        emit Path_CreditBurned(_amountSD);\n    }\n}\n"
      },
      "src/libs/Transfer.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.22;\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\n\n/// @dev WARNING: Transferring tokens, when the token address is wrong, will fail silently.\ncontract Transfer is Ownable {\n    error Transfer_TransferFailed();\n    error Transfer_ApproveFailed();\n\n    // @dev default this to 2300, but it is modifiable\n    // @dev this is intended to provide just enough gas to receive native tokens.\n    // @dev ie. empty fallbacks or EOA addresses\n    uint256 internal transferGasLimit = 2300;\n\n    function getTransferGasLimit() external view returns (uint256) {\n        return transferGasLimit;\n    }\n\n    function setTransferGasLimit(uint256 _gasLimit) external onlyOwner {\n        transferGasLimit = _gasLimit;\n    }\n\n    /// @notice Transfer native coin to an account\n    /// @dev If gas is unlimited, we pass 63/64 of the gasleft()\n    /// @dev This call may revert due to out of gas instead of returning false.\n    /// @param _to The account to transfer native coin to\n    /// @param _value The amount of native coin to transfer\n    /// @param _gasLimited Whether to limit gas available for the 'fall-back'\n    /// @return success Whether the transfer was successful\n    function transferNative(address _to, uint256 _value, bool _gasLimited) internal returns (bool success) {\n        uint256 gasForCall = _gasLimited ? transferGasLimit : gasleft();\n\n        // @dev We dont care about the data returned here, only success or not.\n        assembly {\n            success := call(gasForCall, _to, _value, 0, 0, 0, 0)\n        }\n    }\n\n    /// @notice Transfer an ERC20 token from the sender to an account\n    /// @param _token The address of the ERC20 token to send\n    /// @param _to The receiving account\n    /// @param _value The amount of tokens to transfer\n    /// @return success Whether the transfer was successful or not\n    function transferToken(address _token, address _to, uint256 _value) internal returns (bool success) {\n        success = _call(_token, abi.encodeWithSelector(IERC20(_token).transfer.selector, _to, _value));\n    }\n\n    /// @notice Transfer an ERC20 token from one account to another\n    /// @param _token The address of the ERC20 token to send\n    /// @param _from The source account\n    /// @param _to The destination account\n    /// @param _value The amount of tokens to transfer\n    /// @return success Whether the transfer was successful or not\n    function transferTokenFrom(\n        address _token,\n        address _from,\n        address _to,\n        uint256 _value\n    ) internal returns (bool success) {\n        success = _call(_token, abi.encodeWithSelector(IERC20(_token).transferFrom.selector, _from, _to, _value));\n    }\n\n    /// @notice Transfer either native coin or ERC20 token from the sender to an account\n    /// @param _token The ERC20 address or 0x0 if native is desired\n    /// @param _to The destination account\n    /// @param _value the amount to transfer\n    /// @param _gasLimited Whether to limit the amount of gas when doing a native transfer\n    /// @return success Whether the transfer was successful or not\n    function transfer(address _token, address _to, uint256 _value, bool _gasLimited) internal returns (bool success) {\n        if (_token == address(0)) {\n            success = transferNative(_to, _value, _gasLimited);\n        } else {\n            success = transferToken(_token, _to, _value);\n        }\n    }\n\n    /// @notice Approve a given amount of token for an account\n    /// @param _token The OFT contract to use for approval\n    /// @param _spender The account to approve\n    /// @param _value The amount of tokens to approve\n    /// @return success Whether the approval succeeded\n    function approveToken(address _token, address _spender, uint256 _value) internal returns (bool success) {\n        success = _call(_token, abi.encodeWithSelector(IERC20(_token).approve.selector, _spender, _value));\n    }\n\n    /// @notice Transfer native coin to an account or revert\n    /// @dev Reverts with TransferFailed if the transfer failed\n    /// @param _to The account to transfer native coin to\n    /// @param _value The amount of native coin to transfer\n    /// @param _gasLimited Whether to limit the amount of gas to 2300\n    function safeTransferNative(address _to, uint256 _value, bool _gasLimited) internal {\n        if (!transferNative(_to, _value, _gasLimited)) revert Transfer_TransferFailed();\n    }\n\n    /// @notice Transfer an ERC20 token from one account to another or revert\n    /// @dev Reverts with TransferFailed when the transfer fails\n    /// @param _token The address of the ERC20 token to send\n    /// @param _to The destination account\n    /// @param _value The amount of tokens to transfer\n    function safeTransferToken(address _token, address _to, uint256 _value) internal {\n        if (!transferToken(_token, _to, _value)) revert Transfer_TransferFailed();\n    }\n\n    /// @notice Transfer an ERC20 token from one account to another\n    /// @dev Reverts with TransferFailed when the transfer fails\n    /// @param _token The address of the ERC20 token to send\n    /// @param _from The source account\n    /// @param _to The destination account\n    /// @param _value The amount of tokens to transfer\n    function safeTransferTokenFrom(address _token, address _from, address _to, uint256 _value) internal {\n        if (!transferTokenFrom(_token, _from, _to, _value)) revert Transfer_TransferFailed();\n    }\n\n    /// @notice Transfer either native coin or ERC20 token from the sender to an account\n    /// @dev Reverts with TransferFailed when the transfer fails\n    /// @param _token The ERC20 address or 0x0 if native is desired\n    /// @param _to The destination account\n    /// @param _value the amount to transfer\n    /// @param _gasLimited Whether to limit the amount of gas when doing a native transfer\n    function safeTransfer(address _token, address _to, uint256 _value, bool _gasLimited) internal {\n        if (!transfer(_token, _to, _value, _gasLimited)) revert Transfer_TransferFailed();\n    }\n\n    /// @notice Approve a given amount of token for an account or revert\n    /// @dev Reverts with ApproveFailed if the approval failed\n    /// @dev Consider using forceApproveToken(...) to ensure the approval is set correctly.\n    /// @param _token The OFT contract to use for approval\n    /// @param _spender The account to approve\n    /// @param _value The amount of tokens to approve\n    function safeApproveToken(address _token, address _spender, uint256 _value) internal {\n        if (!approveToken(_token, _spender, _value)) revert Transfer_ApproveFailed();\n    }\n\n    /// @notice Force approve a given amount of token for an account by first resetting the approval\n    /// @dev Some tokens that require the approval to be set to zero before setting it to a non-zero value, e.g. USDT.\n    /// @param _token The OFT contract to use for approval\n    /// @param _spender The account to approve\n    /// @param _value The amount of tokens to approve\n    function forceApproveToken(address _token, address _spender, uint256 _value) internal {\n        if (!approveToken(_token, _spender, _value)) {\n            safeApproveToken(_token, _spender, 0);\n            safeApproveToken(_token, _spender, _value);\n        }\n    }\n\n    function _call(address _token, bytes memory _data) private returns (bool success) {\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool s, bytes memory returndata) = _token.call(_data);\n        success = s ? returndata.length == 0 || abi.decode(returndata, (bool)) : false;\n    }\n}\n"
      },
      "src/utils/LPToken.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.22;\n\nimport { ERC20Permit, ERC20 } from \"@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol\";\n\n/// @title A contract representing an ERC20Permit used for representing liquidity pool ownership.\ncontract LPToken is ERC20Permit {\n    address public immutable stargate;\n    uint8 internal immutable tokenDecimals;\n\n    error LPToken_Unauthorized();\n\n    modifier onlyStargate() {\n        if (msg.sender != stargate) revert LPToken_Unauthorized();\n        _;\n    }\n\n    /**\n     * @notice Create a LP token to represent partial pool ownership.\n     * @dev The sender of the message is set to the Stargate role. This is because it is expected that each\n     *      StargatePool will create its own LPToken.\n     * @param _name The name of the ERC20\n     * @param _symbol The symbol for the ERC20\n     * @param _decimals How many decimals does the ERC20 has\n     */\n    constructor(string memory _name, string memory _symbol, uint8 _decimals) ERC20(_name, _symbol) ERC20Permit(_name) {\n        stargate = msg.sender;\n        tokenDecimals = _decimals;\n    }\n\n    /// @notice Mint new LP tokens and transfer them to an account.\n    /// @param _to The account to send the newly minted tokens to\n    /// @param _amount How many tokens to mint\n    function mint(address _to, uint256 _amount) external onlyStargate {\n        _mint(_to, _amount);\n    }\n\n    /// @notice Burn tokens currently owned by an account.\n    /// @param _from The account to burn the tokens from\n    /// @param _amount How many tokens to burn\n    function burnFrom(address _from, uint256 _amount) external onlyStargate {\n        _burn(_from, _amount);\n    }\n\n    /// @notice How many decimals are used by this token.\n    /// @return The amount of decimals\n    function decimals() public view override returns (uint8) {\n        return tokenDecimals;\n    }\n}\n"
      }
    }
  }}